repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
mindmill/open-cmis-explorer
resources/mindmill/ui/debug/TechnicalInfo-dbg.js
13288
/*! * SAP UI development toolkit for HTML5 (SAPUI5/OpenUI5) * (c) Copyright 2009-2015 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides a popup with technical informations about the running SAPUI5 core sap.ui.define('sap/ui/debug/TechnicalInfo', ['jquery.sap.global', 'sap/ui/core/Core', 'sap/ui/core/Popup', 'jquery.sap.strings'], function(jQuery, Core, Popup/* , jQuerySap */) { "use strict"; /*global alert */ var TechnicalInfo = { open : function(callback) { function serialize(o) { if (o && window.JSON) { return window.JSON.stringify(o); } if ( o === "" ) { return '""'; } return "" + o + (o ? "???" : ""); } function list(o,prefix) { prefix = prefix || ''; if ( !prefix ) { html.push("<table border='0' cellspacing='0' cellpadding='0'>"); } jQuery.each(o, function(i,v) { if ( !v || typeof v === 'string' || typeof v === 'number' || v instanceof Date ) { html.push("<tr><td>", prefix, "<b>", jQuery.sap.escapeHTML(serialize(i)), "</b></td><td>", jQuery.sap.escapeHTML(serialize(v)), "</td></tr>"); } else { html.push("<tr><td>", prefix, "<b>", jQuery.sap.escapeHTML(serialize(i)), "</b></td><td></td></tr>"); list(v, prefix + "&nbsp;&nbsp;"); } }); if ( !prefix) { html.push("</table>"); } } if ( this._oPopup && this._oPopup.isOpen() ) { return; } var ojQSData = this._ojQSData = callback() || {}; var bCT = false,bLV = false,bEmbedded = true; if ( jQuery.sap.getObject("sap.ui.debug.DebugEnv") ) { bCT = sap.ui.debug.DebugEnv.getInstance().isControlTreeShown(); bLV = sap.ui.debug.DebugEnv.getInstance().isTraceWindowShown(); bEmbedded = sap.ui.debug.DebugEnv.getInstance().isRunningEmbedded(); } var sDCUrl = "/sapui5-internal/download/index.jsp"; var bDC = jQuery.sap.syncHead(sDCUrl); var sOUUrl = "/sapui5-sdk-dist/optimize-module-set"; var bOU = jQuery.sap.syncHead(sOUUrl); if ( !bOU ) { sOUUrl = "/demokit/optimize-module-set"; bOU = jQuery.sap.syncHead(sOUUrl); } var bUseDbgSrc = jQuery.sap.debug(); var bUseStatistics = jQuery.sap.statistics(); var sWeinreId = jQuery.sap.uid(); var sWeinreClientUrl = sap.ui.getCore().getConfiguration().getWeinreServer() + "/client/#" + sWeinreId; var html = []; html.push("<div id='sap-ui-techinfo' class='sapUiTInf sapUiDlg' style='width:640px; position: relative;'>"); html.push("<table border='0' cellpadding='3'>"); try { var oVersionInfo = sap.ui.getVersionInfo(); var sVersion = "<a href='" + sap.ui.resource("", "sap-ui-version.json") + "' target='_blank' title='Open Version Info'>" + oVersionInfo.version + "</a>"; html.push("<tr><td align='right' valign='top'><b>SAPUI5 Version</b></td><td>", sVersion, " (built at ", oVersionInfo.buildTimestamp, ", last change ", oVersionInfo.scmRevision, ")</td></tr>"); } catch (ex) { html.push("<tr><td align='right' valign='top'><b>SAPUI5 Version</b></td><td>not available</td></tr>"); } html.push("<tr><td align='right' valign='top'><b>Core Version</b></td><td>", sap.ui.version, " (built at ", sap.ui.buildinfo.buildtime, ", last change ", sap.ui.buildinfo.lastchange, ")</td></tr>"); html.push("<tr><td align='right' valign='top'><b>User Agent</b></td><td>", jQuery.sap.escapeHTML(navigator.userAgent), (document.documentMode ? ", Document Mode '" + document.documentMode + "'" : ""), "</td></tr>"); html.push("<tr><td align='right' valign='top'><b>Configuration</b></td><td><div class='sapUiTInfCfg'>"); list(ojQSData.config); html.push("</div></td></tr>"); html.push("<tr><td align='right' valign='top'><b>Loaded Modules</b></td><td><div id='sap-ui-techinfo-modules' class='sapUiTInfMList'>"); this._renderModules(html, 20); html.push("</div></td></tr>"); if ( bDC ) { html.push("<tr><td></td><td><a id=\"sap-ui-techinfo-customModule\" href=\"" + sDCUrl + "\">Create Custom Bootstrap Module</a></td></tr>"); } if ( bOU ) { html.push("<tr><td></td><td><a id=\"sap-ui-techinfo-optimizeModuleSet\" href=\"" + sOUUrl + "\">Calculate Optimized Module Set URL</a></td></tr>"); } html.push("<tr><td align='right' valign='top' rowSpan='4'><b>Debug Tools</b></td>", "<td><input id='sap-ui-techinfo-useDbgSources' type='checkbox'", bUseDbgSrc ? " checked='checked'" : "", "><span ", ">Use Debug Sources (reload)</span></input></td></tr>"); html.push("<tr><td><input id='sap-ui-techinfo-showControls' type='checkbox'", bCT ? " checked='checked'" : "", bEmbedded ? "" : " readonly='readonly'", "><span ", bEmbedded ? "" : " style='color:grey'", ">Show UIAreas, Controls and Properties</span></input></td></tr>"); html.push("<tr><td><input id='sap-ui-techinfo-showLogViewer' type='checkbox' ", bLV ? " checked='checked'" : "", bEmbedded ? "" : " readonly='readonly' style='color:grey'", "><span ", bEmbedded ? "" : " style='color:grey'", ">Show Log Viewer</span></input></td></tr>"); html.push("<tr><td><input id='sap-ui-techinfo-useStatistics' type='checkbox' ", bUseStatistics ? " checked='checked'" : "", "><span ", ">Enable SAP-statistics for oData calls</span></input></td></tr>"); html.push("<tr><td colspan='2' align='center' valign='bottom' height='40'><button id='sap-ui-techinfo-close' class='sapUiBtn sapUiBtnS sapUiBtnNorm sapUiBtnStd'>Close</button></td></tr>"); html.push("</table>"); if ( bDC ) { html.push("<form id=\"sap-ui-techinfo-submit\" target=\"_blank\" method=\"post\" action=\"" + sDCUrl + "\">"); html.push("<input type=\"hidden\" name=\"modules\"/>"); html.push("</form>"); } if ( bOU ) { html.push("<form id=\"sap-ui-techinfo-optimize-submit\" target=\"_blank\" method=\"post\" action=\"" + sOUUrl + "\">"); html.push("<input type=\"hidden\" name=\"version\"/>"); html.push("<input type=\"hidden\" name=\"libs\"/>"); html.push("<input type=\"hidden\" name=\"modules\"/>"); html.push("</form>"); } if (sap.ui.getCore().getConfiguration().getRTL()) { html.push("<div style='position: absolute; bottom: 5px; left: 5px; text-align: left'>"); } else { html.push("<div style='position: absolute; bottom: 5px; right: 5px; text-align: right'>"); } html.push("<canvas id='sap-ui-techinfo-qrcode' width='0' height='0'></canvas>"); html.push("<br><a id='sap-ui-techinfo-weinre' href=\"" + sWeinreClientUrl + "\" target=\"_blank\">Remote Web Inspector</a>"); html.push("</div></div>"); this._$Ref = jQuery(html.join("")); this._$Ref.find('#sap-ui-techinfo-useDbgSources').click(jQuery.proxy(this.onUseDbgSources, this)); this._$Ref.find('#sap-ui-techinfo-showControls').click(jQuery.proxy(this.onShowControls, this)); this._$Ref.find('#sap-ui-techinfo-showLogViewer').click(jQuery.proxy(this.onShowLogViewer, this)); this._$Ref.find('#sap-ui-techinfo-more').click(jQuery.proxy(this.onShowAllModules, this)); this._$Ref.find('#sap-ui-techinfo-close').click(jQuery.proxy(this.close, this)); this._$Ref.find('#sap-ui-techinfo-customModule').click(jQuery.proxy(this.onCreateCustomModule, this)); this._$Ref.find('#sap-ui-techinfo-optimizeModuleSet').click(jQuery.proxy(this.onOptimizeModuleSet, this)); this._$Ref.find('#sap-ui-techinfo-weinre').click(jQuery.proxy(this.onOpenWebInspector, this)); this._$Ref.find('#sap-ui-techinfo-useStatistics').click(jQuery.proxy(this.onUseStatistics, this)); this._oPopup = new Popup(this._$Ref.get(0), /*modal*/true, /*shadow*/true, /*autoClose*/false); var bValidBrowser = !!!sap.ui.Device.browser.internet_explorer || !!sap.ui.Device.browser.internet_explorer && sap.ui.Device.browser.version > 8; var bDevAvailable = bValidBrowser && jQuery.sap.sjax({type: "HEAD", url: sap.ui.resource("sap.ui.dev", "library.js")}).success; if (bDevAvailable) { this._oPopup.attachOpened(function(oEvent) { // since the log, control tree and property list are using // the z-index 999999 the popup needs a higher z-index to // be able to click on the technical info. this._$().css("z-index", "1000000"); // add the QR code when the control is available jQuery.sap.require("sap.ui.dev.qrcode.QRCode"); if (sap.ui.dev.qrcode.QRCode._renderQRCode) { var sAbsUrl = window.location.href, sWeinreTargetUrl = sAbsUrl + (sAbsUrl.indexOf("?") > 0 ? "&" : "?") + "sap-ui-weinreId=" + sWeinreId; sap.ui.dev.qrcode.QRCode._renderQRCode(jQuery.sap.domById("sap-ui-techinfo-qrcode"), sWeinreTargetUrl); } }); } this._oPopup.open(400); }, close : function() { this._oPopup.destroy(); this._oPopup = undefined; this._$Ref.remove(); this._$Ref = undefined; this._ojQSData = undefined; }, _renderModules : function(html, iLimit) { var CLASS_4_MOD_STATE = { "5" : " sapUiTInfMFail" // FAILED }; var modules = this._ojQSData.modules; var modnames = []; jQuery.each(modules, function(sName,oModule) { if ( oModule.state > 0 ) { modnames.push(sName); } }); modnames.sort(); var iMore = (iLimit && modnames.length > iLimit) ? modnames.length - iLimit : 0; if ( iMore ) { modnames.sort(function(a,b) { if ( a === b ) { return 0; } var ia = modules[a].url ? 1 : 0; var ib = modules[b].url ? 1 : 0; if ( ia != ib ) { return ib - ia; } return a < b ? -1 : 1; }); modnames = modnames.slice(0, iLimit); } jQuery.each(modnames, function(i,v) { var mod = modules[v]; html.push("<span", " title='", mod.url ? jQuery.sap.escapeHTML(mod.url) : ("embedded in " + mod.parent), "'", " class='sapUiTInfM", CLASS_4_MOD_STATE[mod.state] || "", "'>", v, ",</span> "); }); if ( iMore ) { html.push("<span id='sap-ui-techinfo-more' title='Show all modules' class='sapUiTInfMMore'>...(" + iMore + " more)</span>"); } }, onShowAllModules : function(e) { var html = []; this._renderModules(html, 0); this._$Ref.find("[id=sap-ui-techinfo-modules]").html(html.join("")); }, onCreateCustomModule : function(e) { e.preventDefault(); e.stopPropagation(); var modnames = []; jQuery.each(this._ojQSData.modules, function(i,v) { modnames.push(i); }); modnames.sort(); jQuery("input[name='modules']", this._$Ref).attr("value", modnames.join(",")); jQuery("form", this._$Ref)[0].submit(); }, onOptimizeModuleSet : function(e) { e.preventDefault(); e.stopPropagation(); var libnames = []; jQuery.each(sap.ui.getCore().getLoadedLibraries(), function(i,v) { libnames.push(i); }); var modnames = []; jQuery.each(this._ojQSData.modules, function(sName,oModule) { if ( oModule.state >= 0 ) { modnames.push(sName); } }); modnames.sort(); var $Form = jQuery("#sap-ui-techinfo-optimize-submit",this._$Ref); jQuery("input[name='version']", $Form).attr("value", "2.0"); jQuery("input[name='libs']", $Form).attr("value", libnames.join(",")); jQuery("input[name='modules']", $Form).attr("value", modnames.join(",")); $Form[0].submit(); }, ensureDebugEnv : function(bShowControls) { if ( !jQuery.sap.getObject("sap.ui.debug.DebugEnv") ) { try { jQuery.sap.require("sap-ui-debug"); // when sap-ui-debug is loaded, control tree and property list are shown by defualt // so disable them again if they are not desired if ( !bShowControls ) { sap.ui.debug.DebugEnv.getInstance().hideControlTree(); sap.ui.debug.DebugEnv.getInstance().hidePropertyList(); } } catch (e) { // failed to load debug env (not installed?) return false; } } return true; }, onShowControls : function(e) { if ( e.target.readOnly ) { e.preventDefault(); e.stopPropagation(); return; } if ( this.ensureDebugEnv(true) ) { if ( e.target.checked ) { sap.ui.debug.DebugEnv.getInstance().showControlTree(); sap.ui.debug.DebugEnv.getInstance().showPropertyList(); } else { sap.ui.debug.DebugEnv.getInstance().hideControlTree(); sap.ui.debug.DebugEnv.getInstance().hidePropertyList(); } } }, onShowLogViewer : function(e) { if ( e.target.readOnly ) { e.preventDefault(); e.stopPropagation(); return; } if ( this.ensureDebugEnv(false) ) { if ( e.target.checked ) { sap.ui.debug.DebugEnv.getInstance().showTraceWindow(); } else { sap.ui.debug.DebugEnv.getInstance().hideTraceWindow(); } } }, onUseDbgSources : function(e) { jQuery.sap.debug(!!e.target.checked); }, onUseStatistics : function(e) { jQuery.sap.statistics(!!e.target.checked); }, onOpenWebInspector: function(e) { /*eslint-disable no-alert */ if (!sap.ui.getCore().getConfiguration().getWeinreServer()) { alert("Cannot start Web Inspector - WEINRE server is not configured."); e.preventDefault(); } else if (!!!sap.ui.Device.browser.webkit) { alert("Cannot start Web Inspector - WEINRE only runs on WebKit, please use Chrome or Safari."); e.preventDefault(); } /*eslint-enable no-alert */ } }; return TechnicalInfo; }, /* bExport= */ true);
bsd-2-clause
JayBenzzz/homebrew
Library/Homebrew/os/mac.rb
10540
require 'hardware' require 'os/mac/version' require 'os/mac/xcode' require 'os/mac/xquartz' module OS module Mac extend self ::MacOS = self # compatibility # This can be compared to numerics, strings, or symbols # using the standard Ruby Comparable methods. def version @version ||= Version.new(MACOS_VERSION) end def cat version.to_sym end def locate tool # Don't call tools (cc, make, strip, etc.) directly! # Give the name of the binary you look for as a string to this method # in order to get the full path back as a Pathname. (@locate ||= {}).fetch(tool) do |key| @locate[key] = if File.executable?(path = "/usr/bin/#{tool}") Pathname.new path # Homebrew GCCs most frequently; much faster to check this before xcrun # This also needs to be queried if xcrun won't work, e.g. CLT-only elsif File.executable?(path = "#{HOMEBREW_PREFIX}/bin/#{tool}") Pathname.new path else # If the tool isn't in /usr/bin or from Homebrew, # then we first try to use xcrun to find it. # If it's not there, or xcode-select is misconfigured, we have to # look in dev_tools_path, and finally in xctoolchain_path, because the # tools were split over two locations beginning with Xcode 4.3+. xcrun_path = begin path = `/usr/bin/xcrun -find #{tool} 2>/dev/null`.chomp # If xcrun finds a superenv tool then discard the result. path unless path.include?("Library/ENV") end paths = %W[#{xcrun_path} #{dev_tools_path}/#{tool} #{xctoolchain_path}/usr/bin/#{tool}] paths.map { |p| Pathname.new(p) }.find { |p| p.executable? } end end end def dev_tools_prefix dev_tools_path.parent.parent end def dev_tools_path @dev_tools_path ||= if tools_in_prefix? CLT::MAVERICKS_PKG_PATH Pathname.new "#{CLT::MAVERICKS_PKG_PATH}/usr/bin" elsif tools_in_prefix? "/" Pathname.new "/usr/bin" elsif not (make_path = `/usr/bin/xcrun -find make 2>/dev/null`).empty? Pathname.new(make_path.chomp).dirname elsif Xcode.prefix && File.exist?("#{Xcode.prefix}/usr/bin/make") Pathname.new "#{Xcode.prefix}/usr/bin" end end def tools_in_prefix?(prefix) %w{cc make}.all? { |tool| File.executable? "#{prefix}/usr/bin/#{tool}" } end def xctoolchain_path # As of Xcode 4.3, some tools are located in the "xctoolchain" directory @xctoolchain_path ||= begin path = Pathname.new("#{Xcode.prefix}/Toolchains/XcodeDefault.xctoolchain") # If only the CLT are installed, all tools will be under dev_tools_path, # this path won't exist, and xctoolchain_path will be nil. path if path.exist? end end def sdk_path(v = version) (@sdk_path ||= {}).fetch(v.to_s) do |key| opts = [] # First query Xcode itself opts << `#{locate('xcodebuild')} -version -sdk macosx#{v} Path 2>/dev/null`.chomp # Xcode.prefix is pretty smart, so lets look inside to find the sdk opts << "#{Xcode.prefix}/Platforms/MacOSX.platform/Developer/SDKs/MacOSX#{v}.sdk" # Xcode < 4.3 style opts << "/Developer/SDKs/MacOSX#{v}.sdk" @sdk_path[key] = opts.map { |a| Pathname.new(a) }.detect(&:directory?) end end def default_cc cc = locate 'cc' cc.realpath.basename.to_s rescue nil end def default_compiler case default_cc when /^gcc-4.0/ then :gcc_4_0 when /^gcc/ then :gcc when /^llvm/ then :llvm when "clang" then :clang else # guess :( if Xcode.version >= "4.3" :clang elsif Xcode.version >= "4.2" :llvm else :gcc end end end def default_cxx_stdlib version >= :mavericks ? :libcxx : :libstdcxx end def gcc_40_build_version @gcc_40_build_version ||= if (path = locate("gcc-4.0")) %x{#{path} --version}[/build (\d{4,})/, 1].to_i end end alias_method :gcc_4_0_build_version, :gcc_40_build_version def gcc_42_build_version @gcc_42_build_version ||= begin gcc = MacOS.locate('gcc-4.2') gcc ||= Formula.factory('apple-gcc42').opt_prefix/'bin/gcc-4.2' rescue nil raise if gcc.nil? || !gcc.exist? rescue gcc = nil end if gcc && gcc.realpath.basename.to_s !~ /^llvm/ %x{#{gcc} --version}[/build (\d{4,})/, 1].to_i end end alias_method :gcc_build_version, :gcc_42_build_version def llvm_build_version # for Xcode 3 on OS X 10.5 this will not exist # NOTE may not be true anymore but we can't test @llvm_build_version ||= if (path = locate("llvm-gcc")) && path.realpath.basename.to_s !~ /^clang/ %x{#{path} --version}[/LLVM build (\d{4,})/, 1].to_i end end def clang_version @clang_version ||= if (path = locate("clang")) %x{#{path} --version}[/(?:clang|LLVM) version (\d\.\d)/, 1] end end def clang_build_version @clang_build_version ||= if (path = locate("clang")) %x{#{path} --version}[%r[clang-(\d{2,})], 1].to_i end end def non_apple_gcc_version(cc) path = Formula.factory("gcc").opt_prefix/"bin/#{cc}" path = nil unless path.exist? return unless path ||= locate(cc) ivar = "@#{cc.gsub(/(-|\.)/, '')}_version" return instance_variable_get(ivar) if instance_variable_defined?(ivar) `#{path} --version` =~ /gcc(-\d\.\d \(GCC\))? (\d\.\d\.\d)/ instance_variable_set(ivar, $2) end # See these issues for some history: # http://github.com/Homebrew/homebrew/issues/13 # http://github.com/Homebrew/homebrew/issues/41 # http://github.com/Homebrew/homebrew/issues/48 def macports_or_fink paths = [] # First look in the path because MacPorts is relocatable and Fink # may become relocatable in the future. %w{port fink}.each do |ponk| path = which(ponk) paths << path unless path.nil? end # Look in the standard locations, because even if port or fink are # not in the path they can still break builds if the build scripts # have these paths baked in. %w{/sw/bin/fink /opt/local/bin/port}.each do |ponk| path = Pathname.new(ponk) paths << path if path.exist? end # Finally, some users make their MacPorts or Fink directorie # read-only in order to try out Homebrew, but this doens't work as # some build scripts error out when trying to read from these now # unreadable paths. %w{/sw /opt/local}.map { |p| Pathname.new(p) }.each do |path| paths << path if path.exist? && !path.readable? end paths.uniq end def prefer_64_bit? Hardware::CPU.is_64_bit? and version > :leopard end def preferred_arch if prefer_64_bit? Hardware::CPU.arch_64_bit else Hardware::CPU.arch_32_bit end end STANDARD_COMPILERS = { "2.5" => { :gcc_40_build => 5370 }, "3.1.4" => { :gcc_40_build => 5493, :gcc_42_build => 5577 }, "3.2.6" => { :gcc_40_build => 5494, :gcc_42_build => 5666, :llvm_build => 2335, :clang => "1.7", :clang_build => 77 }, "4.0" => { :gcc_40_build => 5494, :gcc_42_build => 5666, :llvm_build => 2335, :clang => "2.0", :clang_build => 137 }, "4.0.1" => { :gcc_40_build => 5494, :gcc_42_build => 5666, :llvm_build => 2335, :clang => "2.0", :clang_build => 137 }, "4.0.2" => { :gcc_40_build => 5494, :gcc_42_build => 5666, :llvm_build => 2335, :clang => "2.0", :clang_build => 137 }, "4.2" => { :llvm_build => 2336, :clang => "3.0", :clang_build => 211 }, "4.3" => { :llvm_build => 2336, :clang => "3.1", :clang_build => 318 }, "4.3.1" => { :llvm_build => 2336, :clang => "3.1", :clang_build => 318 }, "4.3.2" => { :llvm_build => 2336, :clang => "3.1", :clang_build => 318 }, "4.3.3" => { :llvm_build => 2336, :clang => "3.1", :clang_build => 318 }, "4.4" => { :llvm_build => 2336, :clang => "4.0", :clang_build => 421 }, "4.4.1" => { :llvm_build => 2336, :clang => "4.0", :clang_build => 421 }, "4.5" => { :llvm_build => 2336, :clang => "4.1", :clang_build => 421 }, "4.5.1" => { :llvm_build => 2336, :clang => "4.1", :clang_build => 421 }, "4.5.2" => { :llvm_build => 2336, :clang => "4.1", :clang_build => 421 }, "4.6" => { :llvm_build => 2336, :clang => "4.2", :clang_build => 425 }, "4.6.1" => { :llvm_build => 2336, :clang => "4.2", :clang_build => 425 }, "4.6.2" => { :llvm_build => 2336, :clang => "4.2", :clang_build => 425 }, "4.6.3" => { :llvm_build => 2336, :clang => "4.2", :clang_build => 425 }, "5.0" => { :clang => "5.0", :clang_build => 500 }, "5.0.1" => { :clang => "5.0", :clang_build => 500 }, "5.0.2" => { :clang => "5.0", :clang_build => 500 }, "5.1" => { :clang => "5.1", :clang_build => 503 }, "5.1.1" => { :clang => "5.1", :clang_build => 503 }, } def compilers_standard? STANDARD_COMPILERS.fetch(Xcode.version.to_s).all? do |method, build| send(:"#{method}_version") == build end rescue IndexError onoe <<-EOS.undent Homebrew doesn't know what compiler versions ship with your version of Xcode (#{Xcode.version}). Please `brew update` and if that doesn't help, file an issue with the output of `brew --config`: https://github.com/Homebrew/homebrew/issues Note that we only track stable, released versions of Xcode. Thanks! EOS end def app_with_bundle_id(*ids) path = mdfind(*ids).first Pathname.new(path) unless path.nil? or path.empty? end def mdfind(*ids) return [] unless OS.mac? (@mdfind ||= {}).fetch(ids) do @mdfind[ids] = `/usr/bin/mdfind "#{mdfind_query(*ids)}"`.split("\n") end end def pkgutil_info(id) (@pkginfo ||= {}).fetch(id) do |key| @pkginfo[key] = `/usr/sbin/pkgutil --pkg-info "#{key}" 2>/dev/null`.strip end end def mdfind_query(*ids) ids.map! { |id| "kMDItemCFBundleIdentifier == #{id}" }.join(" || ") end end end
bsd-2-clause
rogeriopradoj/frapi-without-vhost
library/Frapi/Action.php
11288
<?php /** * Action class * * 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://getfrapi.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@getfrapi.com so we can send you a copy immediately. * * This class contains the action context methods * and everything that is going to be used to load the * actions. * * It also contains an array that says which fields need * to be logged in in order to use and which fields simply need * a username/email and secretkey (Set from the admin). * * @license New BSD * @package frapi * @uses Frapi_Action_Exception */ class Frapi_Action { // Types used in getParam for casting const TYPE_INT = 'int'; const TYPE_INTEGER = 'int'; const TYPE_LONG = 'int'; const TYPE_STRING = 'string'; const TYPE_FLOAT = 'float'; const TYPE_DOUBLE = 'double'; const TYPE_BOOL = 'bool'; const TYPE_ARRAY = 'array'; const TYPE_OBJECT = 'object'; const TYPE_SQL = 'sqlsafe'; const TYPE_OUTPUT = 'output'; const TYPE_SAFESQLARRAY = 'safesqlarray'; const TYPE_OUTPUTSAFE = 'outputsafe'; const TYPE_FILE = 'file'; /** * The value of the current action being * executed by the webservice. * * @var string $action The action. */ protected $action; /** * The parameters passed to the action * context object. * * @var mixed $params This can be a string or an array * but usually this comes from the $_REQUEST */ protected $params; /** * Those are the files uploaded to the server. * * @var mixed $params The values of the $_FILES variable */ protected $files; /** * This is something that is going to be used only * in the child classes to store the error message * * @var ErrorContext Stores an error context */ protected $errors; /** * This is stored in sessionID passed. * * @var string $uid The user uid (Internally used only) */ protected $uid; /** * If one decides to use a custom template in the XML or HTML output * then this variable will be set. * * @var string The name of the custom template to load from custom/Output/{type}/custom/ */ protected $customTemplate = false; /** * Get an instance of the desired type of Action * Context using the action passed to it * * @param string $action The action context to load * @return Action instance */ public static function getInstance($action) { $directory = CUSTOM_ACTION . DIRECTORY_SEPARATOR; $filePlain = ucfirst(strtolower($action)); $file = $directory . $filePlain . '.php'; $class = 'Action_' . $filePlain; if (!file_exists($file) || !is_readable($file)) { throw new Frapi_Action_Exception ( Frapi_Error::ERROR_INVALID_ACTION_REQUEST_MSG, 'ERROR_INVALID_ACTION_REQUEST', Frapi_Error::ERROR_INVALID_ACTION_REQUEST_NO, null, 400 ); } if (!class_exists($class, false)) { require $file; } return new $class; } /** * Set the action context parameters * * @param array $params The params to populate xml with. */ public function setActionFiles($params) { $this->files = $params; return $this; } /** * Set the action context parameters * * @param array $params The params to populate xml with. */ public function setActionParams(array $params) { $this->action = isset($params['action']) ? $params['action'] : null; $this->params = $params; return $this; } /** * Set the action context action method to be called, for reference * * @param string $action */ public function setAction($action) { $this->action = $action; return $this; } /** * Retrieve the action we are invoking. * * This method is used to retrieve the name of the action we are * currently invoking. This is mainly used by the likes of the custom * authentication. * * @return string The action being invoked. */ public function getAction() { return $this->action; } /** * Set the template file to use * * This method is used to set the custom template file to use * instead of the default Actionname.xml.tpl or Actionname.html.tpl * * @param string $customTemplateFileName The template file to load. * @return void */ public function setTemplateFileName($customTemplateFileName) { $this->customTemplate = $customTemplateFileName; return $this; } /** * Get the template to load * * This method fetches the template filename to use and * returns it's value. * * @return mixed Either false or a string with the name of the file. */ public function getTemplateFileName() { return $this->customTemplate; } /** * This method validates that all your parameters * required for your action to run are present. * * If they are not, uhoh! Return a new error. * * @param Array $requiredParameters An array of the required params * @return Mixed Either an ErrorContext with missing param or true */ protected function hasRequiredParameters($requiredParameters) { $missingParams = array(); foreach ($requiredParameters as $param) { if (!isset($this->params[$param]) && !isset($this->files[$param])) { $missingParams[] = $param; } } if (!empty($missingParams)) { $missingParamsString = implode(', ', $missingParams); throw new Frapi_Action_Exception ( Frapi_Error::ERROR_MISSING_REQUEST_ARG_MSG, 'ERROR_MISSING_REQUEST_ARG', Frapi_Error::ERROR_MISSING_REQUEST_ARG_NO, sprintf(Frapi_Error::ERROR_MISSING_REQUEST_ARG_LABEL, $missingParamsString), 400 ); } return true; } // The RESTful actions public function executeGet() { return $this->executeAction(); } public function executePut() { return $this->executeAction(); } public function executePost() { return $this->executeAction(); } public function executeDelete() { return $this->executeAction(); } public function executeHead() { return $this->executeAction(); } public function executeTrace() { return $this->executeAction(); } public function executeOptions(){ return $this->executeAction(); } // non-RESTful action but curl -X DOCS could have some interesting // implications in the future. public function executeDocs() { return $this->executeAction(); } /** * Return all the parameters * * Return all the request parameters we are currently holding * in $this->params * * @return array An array of request parameters and files maybe. */ public function getParams() { return $this->params; } /** * Return the files uploaded * * This method is exactly like $this->getParams() however * it returns a list of variables that were stored about the * uploaded files instead of parameters. * * @return array An array of uploaded file information */ public function getFiles() { return $this->files; } /** * This method will return the value of the * parameter. If it's not set then it returns null. * * The function is coded such that FALSE is known to indicate * non-existence of param in $params, NULL indicates that * param was empty and no default or error was supplied. * * Exhibits cascading behaviour so that any, and all parameters except * $key can be left null, to choose not to use those features. * For instance, ::getParam('get-key', null, 'AA886622', null) * will use the default type self::TYPE_STRING and if the param does * not exist then it will return 'AA886622' AS IS! Type conversions * are never applied to the default value. * * @param string $key The name of the param key * @param string $type The type of casting to do when returning * the requested parameter * @param Mixed $default The default value, if param is empty. * @param String $error_name The error name to raise, as last resort. * * @return Mixed String when the key is valid, ErrorContext if not valid, or null if not set. */ protected function getParam($key, $type = self::TYPE_STRING, $default = null, $error_name = null) { $param = isset($this->params[$key]) ? $this->params[$key] : $default; switch ($type) { case self::TYPE_FILE; $param = null; if (isset($this->files) && isset($this->files[$key])) { $param = $this->files[$key]; } break; case self::TYPE_STRING: $param = (string)$param; break; case self::TYPE_INTEGER: $param = (int)$param; break; case self::TYPE_FLOAT: case self::TYPE_DOUBLE: $param = (float)$param; break; case self::TYPE_ARRAY: $param = (array)$param; break; case self::TYPE_OBJECT: $param = (object)$param; break; case self::TYPE_SQL: // This isn't our problem. We shouldn't have that anymore. $param = mysql_escape_string($param); break; case self::TYPE_OUTPUT: case self::TYPE_OUTPUTSAFE: $param = htmlentities($param, ENT_QUOTES, 'UTF-8'); break; case self::TYPE_SAFESQLARRAY: // Same as TYPE_SQL: Not our problem. $tmpArray = array(); foreach ((array)$param as $val => $par) { $val = mysql_escape_string($val); $par = mysql_escape_string($par); $tmpArray[$val] = $par; } $param = $tmpArray; break; default: $param = null; } return $param; } /** * This method checks whether a param exists or not. * * @param string $key The name of the param key * @return bool Whether the parameter exists or not */ protected function hasParam($key) { return isset($this->params[$key]); } }
bsd-2-clause
useabode/redash
node_modules/mapbox-gl/js/render/draw_collision_debug.js
1169
'use strict'; module.exports = drawCollisionDebug; function drawCollisionDebug(painter, source, layer, coords) { var gl = painter.gl; gl.enable(gl.STENCIL_TEST); var program = painter.useProgram('collisionbox'); for (var i = 0; i < coords.length; i++) { var coord = coords[i]; var tile = source.getTile(coord); var bucket = tile.getBucket(layer); if (!bucket) continue; var bufferGroups = bucket.bufferGroups.collisionBox; if (!bufferGroups || !bufferGroups.length) continue; var group = bufferGroups[0]; if (group.layoutVertexBuffer.length === 0) continue; gl.uniformMatrix4fv(program.u_matrix, false, coord.posMatrix); painter.enableTileClippingMask(coord); painter.lineWidth(1); gl.uniform1f(program.u_scale, Math.pow(2, painter.transform.zoom - tile.coord.z)); gl.uniform1f(program.u_zoom, painter.transform.zoom * 10); gl.uniform1f(program.u_maxzoom, (tile.coord.z + 1) * 10); group.vaos[layer.id].bind(gl, program, group.layoutVertexBuffer); gl.drawArrays(gl.LINES, 0, group.layoutVertexBuffer.length); } }
bsd-2-clause
passerbyid/homebrew-core
Formula/s6.rb
2886
class S6 < Formula desc "Small & secure supervision software suite." homepage "https://skarnet.org/software/s6/" stable do url "https://skarnet.org/software/s6/s6-2.6.0.0.tar.gz" sha256 "146dd54086063c6ffb6f554c3e92b8b12a24165fdfab24839de811f79dcf9a40" resource "skalibs" do url "https://skarnet.org/software/skalibs/skalibs-2.5.1.1.tar.gz" sha256 "aa387f11a01751b37fd32603fdf9328a979f74f97f0172def1b0ad73b7e8d51d" end resource "execline" do url "https://skarnet.org/software/execline/execline-2.3.0.1.tar.gz" sha256 "2bf65aaaf808718952e05c2221b4e9472271e53ebd915c8d1d49a3e992583bf4" end end bottle do sha256 "055a227b16fdaf33cdf43442f3d17c9574bd0896e67607b666d27ff97b3c966b" => :sierra sha256 "22e5fb903bacda03540bcb1233a0c0d4f22067acb7a8c1e48f01fbc0f070e844" => :el_capitan sha256 "966fdf4c2149c8c74ad728606c9c0b6517aca72a7d751b07727f5dd13dafe723" => :yosemite end head do url "git://git.skarnet.org/s6" resource "skalibs" do url "git://git.skarnet.org/skalibs" end resource "execline" do url "git://git.skarnet.org/execline" end end def install resources.each { |r| r.stage(buildpath/r.name) } build_dir = buildpath/"build" cd "skalibs" do system "./configure", "--disable-shared", "--prefix=#{build_dir}", "--libdir=#{build_dir}/lib" system "make", "install" end cd "execline" do system "./configure", "--prefix=#{build_dir}", "--bindir=#{libexec}/execline", "--with-include=#{build_dir}/include", "--with-lib=#{build_dir}/lib", "--with-sysdeps=#{build_dir}/lib/skalibs/sysdeps", "--disable-shared" system "make", "install" end system "./configure", "--prefix=#{prefix}", "--libdir=#{build_dir}/lib", "--includedir=#{build_dir}/include", "--with-include=#{build_dir}/include", "--with-lib=#{build_dir}/lib", "--with-lib=#{build_dir}/lib/execline", "--with-sysdeps=#{build_dir}/lib/skalibs/sysdeps", "--disable-static", "--disable-shared" system "make", "install" # Some S6 tools expect execline binaries to be on the path bin.env_script_all_files(libexec/"bin", :PATH => "#{libexec}/execline:$PATH") sbin.env_script_all_files(libexec/"sbin", :PATH => "#{libexec}/execline:$PATH") (bin/"execlineb").write_env_script libexec/"execline/execlineb", :PATH => "#{libexec}/execline:$PATH" end test do # Test execline test_script = testpath/"test.eb" test_script.write <<-EOS.undent import PATH if { [ ! -z ${PATH} ] } true EOS system "#{bin}/execlineb", test_script # Test s6 (testpath/"log").mkpath pipe_output("#{bin}/s6-log #{testpath}/log", "Test input\n") assert_equal "Test input\n", File.read(testpath/"log/current") end end
bsd-2-clause
Mickasso90/homebrew-cask
Casks/bittorrent-sync.rb
219
class BittorrentSync < Cask url 'http://download-lb.utorrent.com/endpoint/btsync/os/osx/track/stable' homepage 'http://www.bittorrent.com/sync' version 'latest' sha256 :no_check link 'BitTorrent Sync.app' end
bsd-2-clause
privacylab/talek
pir/pircuda/context_cuda.go
2222
//+build +cuda,!travis package pircuda import ( "sync" "github.com/barnex/cuda5/cu" "github.com/privacylab/talek/common" ) const ( // CudaDeviceID is the hardcoded GPU device we'll use CudaDeviceID = 0 ) // ContextCUDA represents a single CUDA context // Currently, we only support 1 live ShardCUDA per ContextCUDA // Before creating a new ShardCUDA, the old one must be Free() type ContextCUDA struct { log *common.Logger name string KernelMutex *sync.Mutex kernelSource string kernelDataSize int device cu.Device Ctx cu.Context module cu.Module PIRFn cu.Function groupSize int } // NewContextCUDA creates a new CUDA context, shared among ShardCUDA instances func NewContextCUDA(name string, kernelSource string, kernelDataSize int) (*ContextCUDA, error) { c := &ContextCUDA{} c.log = common.NewLogger(name) c.name = name c.KernelMutex = &sync.Mutex{} c.kernelSource = kernelSource c.kernelDataSize = kernelDataSize cu.Init(0) c.device = cu.DeviceGet(CudaDeviceID) c.groupSize = c.device.Attribute(cu.MAX_THREADS_PER_BLOCK) c.Ctx = cu.CtxCreate(cu.CTX_SCHED_AUTO, c.device) c.Ctx.SetCurrent() //major, minor := c.device.ComputeCapability() //c.log.Info.Printf("CUDA Compute Compatibility: %v.%v\n", major, minor) //c.module = cu.ModuleLoadData(kernelSource) c.module = cu.ModuleLoad(kernelSource) c.PIRFn = c.module.GetFunction("pir") // Weird hack in context handling if cu.CtxGetCurrent() == 0 && c.Ctx != 0 { c.Ctx.SetCurrent() } c.log.Info.Printf("NewContextCUDA(%v) finished\n", c.name) return c, nil } /********************************************* * PUBLIC METHODS *********************************************/ // GetGroupSize returns the working group size of this context func (c *ContextCUDA) GetGroupSize() int { return c.groupSize } // GetKernelDataSize returns the size (in bytes) of a single data item in the kernel func (c *ContextCUDA) GetKernelDataSize() int { return c.kernelDataSize } // Free currently does nothing. ShardCL waits for the go garbage collector func (c *ContextCUDA) Free() error { c.Ctx.Destroy() c.log.Info.Printf("%v.Free finished\n", c.name) return nil }
bsd-2-clause
unofficial-opensource-apple/WebCore
editing/EditingStyle.cpp
68947
/* * Copyright (C) 2007, 2008, 2009, 2013 Apple Inc. * Copyright (C) 2010, 2011 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: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 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. */ #include "config.h" #include "EditingStyle.h" #include "ApplyStyleCommand.h" #include "CSSComputedStyleDeclaration.h" #include "CSSParser.h" #include "CSSRuleList.h" #include "CSSStyleRule.h" #include "CSSValueList.h" #include "CSSValuePool.h" #include "Editor.h" #include "Frame.h" #include "HTMLFontElement.h" #include "HTMLInterchange.h" #include "HTMLNames.h" #include "Node.h" #include "NodeTraversal.h" #include "QualifiedName.h" #include "RenderStyle.h" #include "StyleFontSizeFunctions.h" #include "StyleProperties.h" #include "StyleResolver.h" #include "StyleRule.h" #include "StyledElement.h" #include "VisibleUnits.h" #include "htmlediting.h" namespace WebCore { // Editing style properties must be preserved during editing operation. // e.g. when a user inserts a new paragraph, all properties listed here must be copied to the new paragraph. static const CSSPropertyID editingProperties[] = { CSSPropertyColor, CSSPropertyFontFamily, CSSPropertyFontSize, CSSPropertyFontStyle, CSSPropertyFontVariant, CSSPropertyFontWeight, CSSPropertyLetterSpacing, CSSPropertyLineHeight, CSSPropertyOrphans, CSSPropertyTextAlign, CSSPropertyTextIndent, CSSPropertyTextTransform, CSSPropertyWhiteSpace, CSSPropertyWidows, CSSPropertyWordSpacing, #if PLATFORM(IOS) CSSPropertyWebkitTapHighlightColor, CSSPropertyWebkitCompositionFillColor, #endif CSSPropertyWebkitTextDecorationsInEffect, CSSPropertyWebkitTextFillColor, #if ENABLE(IOS_TEXT_AUTOSIZING) CSSPropertyWebkitTextSizeAdjust, #endif CSSPropertyWebkitTextStrokeColor, CSSPropertyWebkitTextStrokeWidth, // Non-inheritable properties CSSPropertyBackgroundColor, CSSPropertyTextDecoration, }; const unsigned numAllEditingProperties = WTF_ARRAY_LENGTH(editingProperties); const unsigned numInheritableEditingProperties = numAllEditingProperties - 2; enum EditingPropertiesToInclude { OnlyInheritableEditingProperties, AllEditingProperties }; template <class StyleDeclarationType> static PassRefPtr<MutableStyleProperties> copyEditingProperties(StyleDeclarationType* style, EditingPropertiesToInclude type) { if (type == AllEditingProperties) return style->copyPropertiesInSet(editingProperties, numAllEditingProperties); return style->copyPropertiesInSet(editingProperties, numInheritableEditingProperties); } static inline bool isEditingProperty(int id) { for (size_t i = 0; i < WTF_ARRAY_LENGTH(editingProperties); ++i) { if (editingProperties[i] == id) return true; } return false; } static PassRefPtr<MutableStyleProperties> copyPropertiesFromComputedStyle(ComputedStyleExtractor& computedStyle, EditingStyle::PropertiesToInclude propertiesToInclude) { switch (propertiesToInclude) { case EditingStyle::AllProperties: return computedStyle.copyProperties(); case EditingStyle::OnlyEditingInheritableProperties: return copyEditingProperties(&computedStyle, OnlyInheritableEditingProperties); case EditingStyle::EditingPropertiesInEffect: return copyEditingProperties(&computedStyle, AllEditingProperties); } ASSERT_NOT_REACHED(); return 0; } static PassRefPtr<MutableStyleProperties> copyPropertiesFromComputedStyle(Node* node, EditingStyle::PropertiesToInclude propertiesToInclude) { ComputedStyleExtractor computedStyle(node); return copyPropertiesFromComputedStyle(computedStyle, propertiesToInclude); } static PassRefPtr<CSSValue> extractPropertyValue(const StyleProperties* style, CSSPropertyID propertyID) { return style ? style->getPropertyCSSValue(propertyID) : PassRefPtr<CSSValue>(); } static PassRefPtr<CSSValue> extractPropertyValue(ComputedStyleExtractor* computedStyle, CSSPropertyID propertyID) { return computedStyle->propertyValue(propertyID); } template<typename T> int identifierForStyleProperty(T* style, CSSPropertyID propertyID) { RefPtr<CSSValue> value = extractPropertyValue(style, propertyID); if (!value || !value->isPrimitiveValue()) return 0; return toCSSPrimitiveValue(value.get())->getValueID(); } template<typename T> PassRefPtr<MutableStyleProperties> getPropertiesNotIn(StyleProperties* styleWithRedundantProperties, T* baseStyle); enum LegacyFontSizeMode { AlwaysUseLegacyFontSize, UseLegacyFontSizeOnlyIfPixelValuesMatch }; static int legacyFontSizeFromCSSValue(Document*, CSSPrimitiveValue*, bool shouldUseFixedFontDefaultSize, LegacyFontSizeMode); static bool isTransparentColorValue(CSSValue*); static bool hasTransparentBackgroundColor(StyleProperties*); static PassRefPtr<CSSValue> backgroundColorInEffect(Node*); class HTMLElementEquivalent { WTF_MAKE_FAST_ALLOCATED; public: HTMLElementEquivalent(CSSPropertyID, CSSValueID primitiveValue, const QualifiedName& tagName); virtual ~HTMLElementEquivalent() { } virtual bool matches(const Element* element) const { return !m_tagName || element->hasTagName(*m_tagName); } virtual bool hasAttribute() const { return false; } virtual bool propertyExistsInStyle(const StyleProperties* style) const { return style->getPropertyCSSValue(m_propertyID); } virtual bool valueIsPresentInStyle(Element*, StyleProperties*) const; virtual void addToStyle(Element*, EditingStyle*) const; protected: HTMLElementEquivalent(CSSPropertyID); HTMLElementEquivalent(CSSPropertyID, const QualifiedName& tagName); const CSSPropertyID m_propertyID; const RefPtr<CSSPrimitiveValue> m_primitiveValue; const QualifiedName* m_tagName; // We can store a pointer because HTML tag names are const global. }; HTMLElementEquivalent::HTMLElementEquivalent(CSSPropertyID id) : m_propertyID(id) , m_tagName(0) { } HTMLElementEquivalent::HTMLElementEquivalent(CSSPropertyID id, const QualifiedName& tagName) : m_propertyID(id) , m_tagName(&tagName) { } HTMLElementEquivalent::HTMLElementEquivalent(CSSPropertyID id, CSSValueID primitiveValue, const QualifiedName& tagName) : m_propertyID(id) , m_primitiveValue(CSSPrimitiveValue::createIdentifier(primitiveValue)) , m_tagName(&tagName) { ASSERT(primitiveValue != CSSValueInvalid); } bool HTMLElementEquivalent::valueIsPresentInStyle(Element* element, StyleProperties* style) const { RefPtr<CSSValue> value = style->getPropertyCSSValue(m_propertyID); return matches(element) && value && value->isPrimitiveValue() && toCSSPrimitiveValue(value.get())->getValueID() == m_primitiveValue->getValueID(); } void HTMLElementEquivalent::addToStyle(Element*, EditingStyle* style) const { style->setProperty(m_propertyID, m_primitiveValue->cssText()); } class HTMLTextDecorationEquivalent : public HTMLElementEquivalent { public: HTMLTextDecorationEquivalent(CSSValueID primitiveValue, const QualifiedName& tagName); virtual bool propertyExistsInStyle(const StyleProperties*) const; virtual bool valueIsPresentInStyle(Element*, StyleProperties*) const; }; HTMLTextDecorationEquivalent::HTMLTextDecorationEquivalent(CSSValueID primitiveValue, const QualifiedName& tagName) : HTMLElementEquivalent(CSSPropertyTextDecoration, primitiveValue, tagName) // m_propertyID is used in HTMLElementEquivalent::addToStyle { } bool HTMLTextDecorationEquivalent::propertyExistsInStyle(const StyleProperties* style) const { return style->getPropertyCSSValue(CSSPropertyWebkitTextDecorationsInEffect) || style->getPropertyCSSValue(CSSPropertyTextDecoration); } bool HTMLTextDecorationEquivalent::valueIsPresentInStyle(Element* element, StyleProperties* style) const { RefPtr<CSSValue> styleValue = style->getPropertyCSSValue(CSSPropertyWebkitTextDecorationsInEffect); if (!styleValue) styleValue = style->getPropertyCSSValue(CSSPropertyTextDecoration); return matches(element) && styleValue && styleValue->isValueList() && toCSSValueList(styleValue.get())->hasValue(m_primitiveValue.get()); } class HTMLAttributeEquivalent : public HTMLElementEquivalent { public: HTMLAttributeEquivalent(CSSPropertyID, const QualifiedName& tagName, const QualifiedName& attrName); HTMLAttributeEquivalent(CSSPropertyID, const QualifiedName& attrName); bool matches(const Element* elem) const { return HTMLElementEquivalent::matches(elem) && elem->hasAttribute(m_attrName); } virtual bool hasAttribute() const { return true; } virtual bool valueIsPresentInStyle(Element*, StyleProperties*) const; virtual void addToStyle(Element*, EditingStyle*) const; virtual PassRefPtr<CSSValue> attributeValueAsCSSValue(Element*) const; inline const QualifiedName& attributeName() const { return m_attrName; } protected: const QualifiedName& m_attrName; // We can store a reference because HTML attribute names are const global. }; HTMLAttributeEquivalent::HTMLAttributeEquivalent(CSSPropertyID id, const QualifiedName& tagName, const QualifiedName& attrName) : HTMLElementEquivalent(id, tagName) , m_attrName(attrName) { } HTMLAttributeEquivalent::HTMLAttributeEquivalent(CSSPropertyID id, const QualifiedName& attrName) : HTMLElementEquivalent(id) , m_attrName(attrName) { } bool HTMLAttributeEquivalent::valueIsPresentInStyle(Element* element, StyleProperties* style) const { RefPtr<CSSValue> value = attributeValueAsCSSValue(element); RefPtr<CSSValue> styleValue = style->getPropertyCSSValue(m_propertyID); return compareCSSValuePtr(value, styleValue); } void HTMLAttributeEquivalent::addToStyle(Element* element, EditingStyle* style) const { if (RefPtr<CSSValue> value = attributeValueAsCSSValue(element)) style->setProperty(m_propertyID, value->cssText()); } PassRefPtr<CSSValue> HTMLAttributeEquivalent::attributeValueAsCSSValue(Element* element) const { ASSERT(element); if (!element->hasAttribute(m_attrName)) return 0; RefPtr<MutableStyleProperties> dummyStyle; dummyStyle = MutableStyleProperties::create(); dummyStyle->setProperty(m_propertyID, element->getAttribute(m_attrName)); return dummyStyle->getPropertyCSSValue(m_propertyID); } class HTMLFontSizeEquivalent : public HTMLAttributeEquivalent { public: HTMLFontSizeEquivalent(); virtual PassRefPtr<CSSValue> attributeValueAsCSSValue(Element*) const; }; HTMLFontSizeEquivalent::HTMLFontSizeEquivalent() : HTMLAttributeEquivalent(CSSPropertyFontSize, HTMLNames::fontTag, HTMLNames::sizeAttr) { } PassRefPtr<CSSValue> HTMLFontSizeEquivalent::attributeValueAsCSSValue(Element* element) const { ASSERT(element); if (!element->hasAttribute(m_attrName)) return 0; CSSValueID size; if (!HTMLFontElement::cssValueFromFontSizeNumber(element->getAttribute(m_attrName), size)) return 0; return CSSPrimitiveValue::createIdentifier(size); } float EditingStyle::NoFontDelta = 0.0f; EditingStyle::EditingStyle() : m_shouldUseFixedDefaultFontSize(false) , m_fontSizeDelta(NoFontDelta) { } EditingStyle::EditingStyle(Node* node, PropertiesToInclude propertiesToInclude) : m_shouldUseFixedDefaultFontSize(false) , m_fontSizeDelta(NoFontDelta) { init(node, propertiesToInclude); } EditingStyle::EditingStyle(const Position& position, PropertiesToInclude propertiesToInclude) : m_shouldUseFixedDefaultFontSize(false) , m_fontSizeDelta(NoFontDelta) { init(position.deprecatedNode(), propertiesToInclude); } EditingStyle::EditingStyle(const StyleProperties* style) : m_shouldUseFixedDefaultFontSize(false) , m_fontSizeDelta(NoFontDelta) { if (style) m_mutableStyle = style->mutableCopy(); extractFontSizeDelta(); } EditingStyle::EditingStyle(CSSPropertyID propertyID, const String& value) : m_mutableStyle(0) , m_shouldUseFixedDefaultFontSize(false) , m_fontSizeDelta(NoFontDelta) { setProperty(propertyID, value); } EditingStyle::~EditingStyle() { } static RGBA32 cssValueToRGBA(CSSValue* colorValue) { if (!colorValue || !colorValue->isPrimitiveValue()) return Color::transparent; CSSPrimitiveValue* primitiveColor = toCSSPrimitiveValue(colorValue); if (primitiveColor->isRGBColor()) return primitiveColor->getRGBA32Value(); RGBA32 rgba = 0; CSSParser::parseColor(rgba, colorValue->cssText()); return rgba; } template<typename T> static inline RGBA32 textColorFromStyle(T* style) { return cssValueToRGBA(extractPropertyValue(style, CSSPropertyColor).get()); } template<typename T> static inline RGBA32 backgroundColorFromStyle(T* style) { return cssValueToRGBA(extractPropertyValue(style, CSSPropertyBackgroundColor).get()); } static inline RGBA32 rgbaBackgroundColorInEffect(Node* node) { return cssValueToRGBA(backgroundColorInEffect(node).get()); } static int textAlignResolvingStartAndEnd(int textAlign, int direction) { switch (textAlign) { case CSSValueCenter: case CSSValueWebkitCenter: return CSSValueCenter; case CSSValueJustify: return CSSValueJustify; case CSSValueLeft: case CSSValueWebkitLeft: return CSSValueLeft; case CSSValueRight: case CSSValueWebkitRight: return CSSValueRight; case CSSValueStart: return direction != CSSValueRtl ? CSSValueLeft : CSSValueRight; case CSSValueEnd: return direction == CSSValueRtl ? CSSValueRight : CSSValueLeft; } return CSSValueInvalid; } template<typename T> static int textAlignResolvingStartAndEnd(T* style) { return textAlignResolvingStartAndEnd(identifierForStyleProperty(style, CSSPropertyTextAlign), identifierForStyleProperty(style, CSSPropertyDirection)); } void EditingStyle::init(Node* node, PropertiesToInclude propertiesToInclude) { if (isTabSpanTextNode(node)) node = tabSpanNode(node)->parentNode(); else if (isTabSpanNode(node)) node = node->parentNode(); ComputedStyleExtractor computedStyleAtPosition(node); // FIXME: It's strange to not set background-color and text-decoration when propertiesToInclude is EditingPropertiesInEffect. // However editing/selection/contains-boundaries.html fails without this ternary. m_mutableStyle = copyPropertiesFromComputedStyle(computedStyleAtPosition, propertiesToInclude == EditingPropertiesInEffect ? OnlyEditingInheritableProperties : propertiesToInclude); if (propertiesToInclude == EditingPropertiesInEffect) { if (RefPtr<CSSValue> value = backgroundColorInEffect(node)) m_mutableStyle->setProperty(CSSPropertyBackgroundColor, value->cssText()); if (RefPtr<CSSValue> value = computedStyleAtPosition.propertyValue(CSSPropertyWebkitTextDecorationsInEffect)) m_mutableStyle->setProperty(CSSPropertyTextDecoration, value->cssText()); } if (node && node->computedStyle()) { RenderStyle* renderStyle = node->computedStyle(); removeTextFillAndStrokeColorsIfNeeded(renderStyle); if (renderStyle->fontDescription().keywordSize()) m_mutableStyle->setProperty(CSSPropertyFontSize, computedStyleAtPosition.getFontSizeCSSValuePreferringKeyword()->cssText()); } m_shouldUseFixedDefaultFontSize = computedStyleAtPosition.useFixedFontDefaultSize(); extractFontSizeDelta(); } void EditingStyle::removeTextFillAndStrokeColorsIfNeeded(RenderStyle* renderStyle) { // If a node's text fill color is invalid, then its children use // their font-color as their text fill color (they don't // inherit it). Likewise for stroke color. if (!renderStyle->textFillColor().isValid()) m_mutableStyle->removeProperty(CSSPropertyWebkitTextFillColor); if (!renderStyle->textStrokeColor().isValid()) m_mutableStyle->removeProperty(CSSPropertyWebkitTextStrokeColor); } void EditingStyle::setProperty(CSSPropertyID propertyID, const String& value, bool important) { if (!m_mutableStyle) m_mutableStyle = MutableStyleProperties::create(); m_mutableStyle->setProperty(propertyID, value, important); } void EditingStyle::extractFontSizeDelta() { if (!m_mutableStyle) return; if (m_mutableStyle->getPropertyCSSValue(CSSPropertyFontSize)) { // Explicit font size overrides any delta. m_mutableStyle->removeProperty(CSSPropertyWebkitFontSizeDelta); return; } // Get the adjustment amount out of the style. RefPtr<CSSValue> value = m_mutableStyle->getPropertyCSSValue(CSSPropertyWebkitFontSizeDelta); if (!value || !value->isPrimitiveValue()) return; CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value.get()); // Only PX handled now. If we handle more types in the future, perhaps // a switch statement here would be more appropriate. if (!primitiveValue->isPx()) return; m_fontSizeDelta = primitiveValue->getFloatValue(); m_mutableStyle->removeProperty(CSSPropertyWebkitFontSizeDelta); } bool EditingStyle::isEmpty() const { return (!m_mutableStyle || m_mutableStyle->isEmpty()) && m_fontSizeDelta == NoFontDelta; } bool EditingStyle::textDirection(WritingDirection& writingDirection) const { if (!m_mutableStyle) return false; RefPtr<CSSValue> unicodeBidi = m_mutableStyle->getPropertyCSSValue(CSSPropertyUnicodeBidi); if (!unicodeBidi || !unicodeBidi->isPrimitiveValue()) return false; CSSValueID unicodeBidiValue = toCSSPrimitiveValue(unicodeBidi.get())->getValueID(); if (unicodeBidiValue == CSSValueEmbed) { RefPtr<CSSValue> direction = m_mutableStyle->getPropertyCSSValue(CSSPropertyDirection); if (!direction || !direction->isPrimitiveValue()) return false; writingDirection = toCSSPrimitiveValue(direction.get())->getValueID() == CSSValueLtr ? LeftToRightWritingDirection : RightToLeftWritingDirection; return true; } if (unicodeBidiValue == CSSValueNormal) { writingDirection = NaturalWritingDirection; return true; } return false; } void EditingStyle::setStyle(PassRefPtr<MutableStyleProperties> style) { m_mutableStyle = style; // FIXME: We should be able to figure out whether or not font is fixed width for mutable style. // We need to check font-family is monospace as in FontDescription but we don't want to duplicate code here. m_shouldUseFixedDefaultFontSize = false; extractFontSizeDelta(); } void EditingStyle::overrideWithStyle(const StyleProperties* style) { return mergeStyle(style, OverrideValues); } void EditingStyle::clear() { m_mutableStyle.clear(); m_shouldUseFixedDefaultFontSize = false; m_fontSizeDelta = NoFontDelta; } PassRefPtr<EditingStyle> EditingStyle::copy() const { RefPtr<EditingStyle> copy = EditingStyle::create(); if (m_mutableStyle) copy->m_mutableStyle = m_mutableStyle->mutableCopy(); copy->m_shouldUseFixedDefaultFontSize = m_shouldUseFixedDefaultFontSize; copy->m_fontSizeDelta = m_fontSizeDelta; return copy; } PassRefPtr<EditingStyle> EditingStyle::extractAndRemoveBlockProperties() { RefPtr<EditingStyle> blockProperties = EditingStyle::create(); if (!m_mutableStyle) return blockProperties; blockProperties->m_mutableStyle = m_mutableStyle->copyBlockProperties(); m_mutableStyle->removeBlockProperties(); return blockProperties; } PassRefPtr<EditingStyle> EditingStyle::extractAndRemoveTextDirection() { RefPtr<EditingStyle> textDirection = EditingStyle::create(); textDirection->m_mutableStyle = MutableStyleProperties::create(); textDirection->m_mutableStyle->setProperty(CSSPropertyUnicodeBidi, CSSValueEmbed, m_mutableStyle->propertyIsImportant(CSSPropertyUnicodeBidi)); textDirection->m_mutableStyle->setProperty(CSSPropertyDirection, m_mutableStyle->getPropertyValue(CSSPropertyDirection), m_mutableStyle->propertyIsImportant(CSSPropertyDirection)); m_mutableStyle->removeProperty(CSSPropertyUnicodeBidi); m_mutableStyle->removeProperty(CSSPropertyDirection); return textDirection; } void EditingStyle::removeBlockProperties() { if (!m_mutableStyle) return; m_mutableStyle->removeBlockProperties(); } void EditingStyle::removeStyleAddedByNode(Node* node) { if (!node || !node->parentNode()) return; RefPtr<MutableStyleProperties> parentStyle = copyPropertiesFromComputedStyle(node->parentNode(), EditingPropertiesInEffect); RefPtr<MutableStyleProperties> nodeStyle = copyPropertiesFromComputedStyle(node, EditingPropertiesInEffect); removeEquivalentProperties(*parentStyle); removeEquivalentProperties(*nodeStyle); } void EditingStyle::removeStyleConflictingWithStyleOfNode(Node* node) { if (!node || !node->parentNode() || !m_mutableStyle) return; RefPtr<MutableStyleProperties> parentStyle = copyPropertiesFromComputedStyle(node->parentNode(), EditingPropertiesInEffect); RefPtr<EditingStyle> nodeStyle = EditingStyle::create(node, EditingPropertiesInEffect); nodeStyle->removeEquivalentProperties(*parentStyle); MutableStyleProperties* style = nodeStyle->style(); unsigned propertyCount = style->propertyCount(); for (unsigned i = 0; i < propertyCount; ++i) m_mutableStyle->removeProperty(style->propertyAt(i).id()); } void EditingStyle::collapseTextDecorationProperties() { if (!m_mutableStyle) return; RefPtr<CSSValue> textDecorationsInEffect = m_mutableStyle->getPropertyCSSValue(CSSPropertyWebkitTextDecorationsInEffect); if (!textDecorationsInEffect) return; if (textDecorationsInEffect->isValueList()) m_mutableStyle->setProperty(CSSPropertyTextDecoration, textDecorationsInEffect->cssText(), m_mutableStyle->propertyIsImportant(CSSPropertyTextDecoration)); else m_mutableStyle->removeProperty(CSSPropertyTextDecoration); m_mutableStyle->removeProperty(CSSPropertyWebkitTextDecorationsInEffect); } // CSS properties that create a visual difference only when applied to text. static const CSSPropertyID textOnlyProperties[] = { CSSPropertyTextDecoration, CSSPropertyWebkitTextDecorationsInEffect, CSSPropertyFontStyle, CSSPropertyFontWeight, CSSPropertyColor, }; TriState EditingStyle::triStateOfStyle(EditingStyle* style) const { if (!style || !style->m_mutableStyle) return FalseTriState; return triStateOfStyle(style->m_mutableStyle.get(), DoNotIgnoreTextOnlyProperties); } template<typename T> TriState EditingStyle::triStateOfStyle(T* styleToCompare, ShouldIgnoreTextOnlyProperties shouldIgnoreTextOnlyProperties) const { RefPtr<MutableStyleProperties> difference = getPropertiesNotIn(m_mutableStyle.get(), styleToCompare); if (shouldIgnoreTextOnlyProperties == IgnoreTextOnlyProperties) difference->removePropertiesInSet(textOnlyProperties, WTF_ARRAY_LENGTH(textOnlyProperties)); if (difference->isEmpty()) return TrueTriState; if (difference->propertyCount() == m_mutableStyle->propertyCount()) return FalseTriState; return MixedTriState; } TriState EditingStyle::triStateOfStyle(const VisibleSelection& selection) const { if (!selection.isCaretOrRange()) return FalseTriState; if (selection.isCaret()) return triStateOfStyle(EditingStyle::styleAtSelectionStart(selection).get()); TriState state = FalseTriState; bool nodeIsStart = true; for (Node* node = selection.start().deprecatedNode(); node; node = NodeTraversal::next(node)) { if (node->renderer() && node->hasEditableStyle()) { ComputedStyleExtractor computedStyle(node); TriState nodeState = triStateOfStyle(&computedStyle, node->isTextNode() ? EditingStyle::DoNotIgnoreTextOnlyProperties : EditingStyle::IgnoreTextOnlyProperties); if (nodeIsStart) { state = nodeState; nodeIsStart = false; } else if (state != nodeState && node->isTextNode()) { state = MixedTriState; break; } } if (node == selection.end().deprecatedNode()) break; } return state; } bool EditingStyle::conflictsWithInlineStyleOfElement(StyledElement* element, EditingStyle* extractedStyle, Vector<CSSPropertyID>* conflictingProperties) const { ASSERT(element); ASSERT(!conflictingProperties || conflictingProperties->isEmpty()); const StyleProperties* inlineStyle = element->inlineStyle(); if (!m_mutableStyle || !inlineStyle) return false; unsigned propertyCount = m_mutableStyle->propertyCount(); for (unsigned i = 0; i < propertyCount; ++i) { CSSPropertyID propertyID = m_mutableStyle->propertyAt(i).id(); // We don't override whitespace property of a tab span because that would collapse the tab into a space. if (propertyID == CSSPropertyWhiteSpace && isTabSpanNode(element)) continue; if (propertyID == CSSPropertyWebkitTextDecorationsInEffect && inlineStyle->getPropertyCSSValue(CSSPropertyTextDecoration)) { if (!conflictingProperties) return true; conflictingProperties->append(CSSPropertyTextDecoration); if (extractedStyle) extractedStyle->setProperty(CSSPropertyTextDecoration, inlineStyle->getPropertyValue(CSSPropertyTextDecoration), inlineStyle->propertyIsImportant(CSSPropertyTextDecoration)); continue; } if (!inlineStyle->getPropertyCSSValue(propertyID)) continue; if (propertyID == CSSPropertyUnicodeBidi && inlineStyle->getPropertyCSSValue(CSSPropertyDirection)) { if (!conflictingProperties) return true; conflictingProperties->append(CSSPropertyDirection); if (extractedStyle) extractedStyle->setProperty(propertyID, inlineStyle->getPropertyValue(propertyID), inlineStyle->propertyIsImportant(propertyID)); } if (!conflictingProperties) return true; conflictingProperties->append(propertyID); if (extractedStyle) extractedStyle->setProperty(propertyID, inlineStyle->getPropertyValue(propertyID), inlineStyle->propertyIsImportant(propertyID)); } return conflictingProperties && !conflictingProperties->isEmpty(); } static const Vector<std::unique_ptr<HTMLElementEquivalent>>& htmlElementEquivalents() { static NeverDestroyed<Vector<std::unique_ptr<HTMLElementEquivalent>>> HTMLElementEquivalents; if (!HTMLElementEquivalents.get().size()) { HTMLElementEquivalents.get().append(std::make_unique<HTMLElementEquivalent>(CSSPropertyFontWeight, CSSValueBold, HTMLNames::bTag)); HTMLElementEquivalents.get().append(std::make_unique<HTMLElementEquivalent>(CSSPropertyFontWeight, CSSValueBold, HTMLNames::strongTag)); HTMLElementEquivalents.get().append(std::make_unique<HTMLElementEquivalent>(CSSPropertyVerticalAlign, CSSValueSub, HTMLNames::subTag)); HTMLElementEquivalents.get().append(std::make_unique<HTMLElementEquivalent>(CSSPropertyVerticalAlign, CSSValueSuper, HTMLNames::supTag)); HTMLElementEquivalents.get().append(std::make_unique<HTMLElementEquivalent>(CSSPropertyFontStyle, CSSValueItalic, HTMLNames::iTag)); HTMLElementEquivalents.get().append(std::make_unique<HTMLElementEquivalent>(CSSPropertyFontStyle, CSSValueItalic, HTMLNames::emTag)); HTMLElementEquivalents.get().append(std::make_unique<HTMLTextDecorationEquivalent>(CSSValueUnderline, HTMLNames::uTag)); HTMLElementEquivalents.get().append(std::make_unique<HTMLTextDecorationEquivalent>(CSSValueLineThrough, HTMLNames::sTag)); HTMLElementEquivalents.get().append(std::make_unique<HTMLTextDecorationEquivalent>(CSSValueLineThrough, HTMLNames::strikeTag)); } return HTMLElementEquivalents; } bool EditingStyle::conflictsWithImplicitStyleOfElement(HTMLElement* element, EditingStyle* extractedStyle, ShouldExtractMatchingStyle shouldExtractMatchingStyle) const { if (!m_mutableStyle) return false; const Vector<std::unique_ptr<HTMLElementEquivalent>>& HTMLElementEquivalents = htmlElementEquivalents(); for (size_t i = 0; i < HTMLElementEquivalents.size(); ++i) { const HTMLElementEquivalent* equivalent = HTMLElementEquivalents[i].get(); if (equivalent->matches(element) && equivalent->propertyExistsInStyle(m_mutableStyle.get()) && (shouldExtractMatchingStyle == ExtractMatchingStyle || !equivalent->valueIsPresentInStyle(element, m_mutableStyle.get()))) { if (extractedStyle) equivalent->addToStyle(element, extractedStyle); return true; } } return false; } static const Vector<std::unique_ptr<HTMLAttributeEquivalent>>& htmlAttributeEquivalents() { static NeverDestroyed<Vector<std::unique_ptr<HTMLAttributeEquivalent>>> HTMLAttributeEquivalents; if (!HTMLAttributeEquivalents.get().size()) { // elementIsStyledSpanOrHTMLEquivalent depends on the fact each HTMLAttriuteEquivalent matches exactly one attribute // of exactly one element except dirAttr. HTMLAttributeEquivalents.get().append(std::make_unique<HTMLAttributeEquivalent>(CSSPropertyColor, HTMLNames::fontTag, HTMLNames::colorAttr)); HTMLAttributeEquivalents.get().append(std::make_unique<HTMLAttributeEquivalent>(CSSPropertyFontFamily, HTMLNames::fontTag, HTMLNames::faceAttr)); HTMLAttributeEquivalents.get().append(std::make_unique<HTMLFontSizeEquivalent>()); HTMLAttributeEquivalents.get().append(std::make_unique<HTMLAttributeEquivalent>(CSSPropertyDirection, HTMLNames::dirAttr)); HTMLAttributeEquivalents.get().append(std::make_unique<HTMLAttributeEquivalent>(CSSPropertyUnicodeBidi, HTMLNames::dirAttr)); } return HTMLAttributeEquivalents; } bool EditingStyle::conflictsWithImplicitStyleOfAttributes(HTMLElement* element) const { ASSERT(element); if (!m_mutableStyle) return false; const Vector<std::unique_ptr<HTMLAttributeEquivalent>>& HTMLAttributeEquivalents = htmlAttributeEquivalents(); for (size_t i = 0; i < HTMLAttributeEquivalents.size(); ++i) { if (HTMLAttributeEquivalents[i]->matches(element) && HTMLAttributeEquivalents[i]->propertyExistsInStyle(m_mutableStyle.get()) && !HTMLAttributeEquivalents[i]->valueIsPresentInStyle(element, m_mutableStyle.get())) return true; } return false; } bool EditingStyle::extractConflictingImplicitStyleOfAttributes(HTMLElement* element, ShouldPreserveWritingDirection shouldPreserveWritingDirection, EditingStyle* extractedStyle, Vector<QualifiedName>& conflictingAttributes, ShouldExtractMatchingStyle shouldExtractMatchingStyle) const { ASSERT(element); // HTMLAttributeEquivalent::addToStyle doesn't support unicode-bidi and direction properties ASSERT(!extractedStyle || shouldPreserveWritingDirection == PreserveWritingDirection); if (!m_mutableStyle) return false; const Vector<std::unique_ptr<HTMLAttributeEquivalent>>& HTMLAttributeEquivalents = htmlAttributeEquivalents(); bool removed = false; for (size_t i = 0; i < HTMLAttributeEquivalents.size(); ++i) { const HTMLAttributeEquivalent* equivalent = HTMLAttributeEquivalents[i].get(); // unicode-bidi and direction are pushed down separately so don't push down with other styles. if (shouldPreserveWritingDirection == PreserveWritingDirection && equivalent->attributeName() == HTMLNames::dirAttr) continue; if (!equivalent->matches(element) || !equivalent->propertyExistsInStyle(m_mutableStyle.get()) || (shouldExtractMatchingStyle == DoNotExtractMatchingStyle && equivalent->valueIsPresentInStyle(element, m_mutableStyle.get()))) continue; if (extractedStyle) equivalent->addToStyle(element, extractedStyle); conflictingAttributes.append(equivalent->attributeName()); removed = true; } return removed; } bool EditingStyle::styleIsPresentInComputedStyleOfNode(Node* node) const { if (!m_mutableStyle) return true; ComputedStyleExtractor computedStyle(node); return getPropertiesNotIn(m_mutableStyle.get(), &computedStyle)->isEmpty(); } bool EditingStyle::elementIsStyledSpanOrHTMLEquivalent(const HTMLElement* element) { bool elementIsSpanOrElementEquivalent = false; if (element->hasTagName(HTMLNames::spanTag)) elementIsSpanOrElementEquivalent = true; else { const Vector<std::unique_ptr<HTMLElementEquivalent>>& HTMLElementEquivalents = htmlElementEquivalents(); size_t i; for (i = 0; i < HTMLElementEquivalents.size(); ++i) { if (HTMLElementEquivalents[i]->matches(element)) { elementIsSpanOrElementEquivalent = true; break; } } } if (!element->hasAttributes()) return elementIsSpanOrElementEquivalent; // span, b, etc... without any attributes unsigned matchedAttributes = 0; const Vector<std::unique_ptr<HTMLAttributeEquivalent>>& HTMLAttributeEquivalents = htmlAttributeEquivalents(); for (size_t i = 0; i < HTMLAttributeEquivalents.size(); ++i) { if (HTMLAttributeEquivalents[i]->matches(element) && HTMLAttributeEquivalents[i]->attributeName() != HTMLNames::dirAttr) matchedAttributes++; } if (!elementIsSpanOrElementEquivalent && !matchedAttributes) return false; // element is not a span, a html element equivalent, or font element. if (element->getAttribute(HTMLNames::classAttr) == AppleStyleSpanClass) matchedAttributes++; if (element->hasAttribute(HTMLNames::styleAttr)) { if (const StyleProperties* style = element->inlineStyle()) { unsigned propertyCount = style->propertyCount(); for (unsigned i = 0; i < propertyCount; ++i) { if (!isEditingProperty(style->propertyAt(i).id())) return false; } } matchedAttributes++; } // font with color attribute, span with style attribute, etc... ASSERT(matchedAttributes <= element->attributeCount()); return matchedAttributes >= element->attributeCount(); } void EditingStyle::prepareToApplyAt(const Position& position, ShouldPreserveWritingDirection shouldPreserveWritingDirection) { if (!m_mutableStyle) return; // ReplaceSelectionCommand::handleStyleSpans() requires that this function only removes the editing style. // If this function was modified in the future to delete all redundant properties, then add a boolean value to indicate // which one of editingStyleAtPosition or computedStyle is called. RefPtr<EditingStyle> editingStyleAtPosition = EditingStyle::create(position, EditingPropertiesInEffect); StyleProperties* styleAtPosition = editingStyleAtPosition->m_mutableStyle.get(); RefPtr<CSSValue> unicodeBidi; RefPtr<CSSValue> direction; if (shouldPreserveWritingDirection == PreserveWritingDirection) { unicodeBidi = m_mutableStyle->getPropertyCSSValue(CSSPropertyUnicodeBidi); direction = m_mutableStyle->getPropertyCSSValue(CSSPropertyDirection); } removeEquivalentProperties(*styleAtPosition); if (textAlignResolvingStartAndEnd(m_mutableStyle.get()) == textAlignResolvingStartAndEnd(styleAtPosition)) m_mutableStyle->removeProperty(CSSPropertyTextAlign); if (textColorFromStyle(m_mutableStyle.get()) == textColorFromStyle(styleAtPosition)) m_mutableStyle->removeProperty(CSSPropertyColor); if (hasTransparentBackgroundColor(m_mutableStyle.get()) || cssValueToRGBA(m_mutableStyle->getPropertyCSSValue(CSSPropertyBackgroundColor).get()) == rgbaBackgroundColorInEffect(position.containerNode())) m_mutableStyle->removeProperty(CSSPropertyBackgroundColor); if (unicodeBidi && unicodeBidi->isPrimitiveValue()) { m_mutableStyle->setProperty(CSSPropertyUnicodeBidi, static_cast<CSSValueID>(toCSSPrimitiveValue(unicodeBidi.get())->getValueID())); if (direction && direction->isPrimitiveValue()) m_mutableStyle->setProperty(CSSPropertyDirection, static_cast<CSSValueID>(toCSSPrimitiveValue(direction.get())->getValueID())); } } void EditingStyle::mergeTypingStyle(Document& document) { RefPtr<EditingStyle> typingStyle = document.frame()->selection().typingStyle(); if (!typingStyle || typingStyle == this) return; mergeStyle(typingStyle->style(), OverrideValues); } void EditingStyle::mergeInlineStyleOfElement(StyledElement* element, CSSPropertyOverrideMode mode, PropertiesToInclude propertiesToInclude) { ASSERT(element); if (!element->inlineStyle()) return; switch (propertiesToInclude) { case AllProperties: mergeStyle(element->inlineStyle(), mode); return; case OnlyEditingInheritableProperties: mergeStyle(copyEditingProperties(element->inlineStyle(), OnlyInheritableEditingProperties).get(), mode); return; case EditingPropertiesInEffect: mergeStyle(copyEditingProperties(element->inlineStyle(), AllEditingProperties).get(), mode); return; } } static inline bool elementMatchesAndPropertyIsNotInInlineStyleDecl(const HTMLElementEquivalent* equivalent, const StyledElement* element, EditingStyle::CSSPropertyOverrideMode mode, StyleProperties* style) { return equivalent->matches(element) && (!element->inlineStyle() || !equivalent->propertyExistsInStyle(element->inlineStyle())) && (mode == EditingStyle::OverrideValues || !equivalent->propertyExistsInStyle(style)); } static PassRefPtr<MutableStyleProperties> extractEditingProperties(const StyleProperties* style, EditingStyle::PropertiesToInclude propertiesToInclude) { if (!style) return 0; switch (propertiesToInclude) { case EditingStyle::AllProperties: case EditingStyle::EditingPropertiesInEffect: return copyEditingProperties(style, AllEditingProperties); case EditingStyle::OnlyEditingInheritableProperties: return copyEditingProperties(style, OnlyInheritableEditingProperties); } ASSERT_NOT_REACHED(); return 0; } void EditingStyle::mergeInlineAndImplicitStyleOfElement(StyledElement* element, CSSPropertyOverrideMode mode, PropertiesToInclude propertiesToInclude) { RefPtr<EditingStyle> styleFromRules = EditingStyle::create(); styleFromRules->mergeStyleFromRulesForSerialization(element); if (element->inlineStyle()) styleFromRules->m_mutableStyle->mergeAndOverrideOnConflict(*element->inlineStyle()); styleFromRules->m_mutableStyle = extractEditingProperties(styleFromRules->m_mutableStyle.get(), propertiesToInclude); mergeStyle(styleFromRules->m_mutableStyle.get(), mode); const Vector<std::unique_ptr<HTMLElementEquivalent>>& elementEquivalents = htmlElementEquivalents(); for (size_t i = 0; i < elementEquivalents.size(); ++i) { if (elementMatchesAndPropertyIsNotInInlineStyleDecl(elementEquivalents[i].get(), element, mode, m_mutableStyle.get())) elementEquivalents[i]->addToStyle(element, this); } const Vector<std::unique_ptr<HTMLAttributeEquivalent>>& attributeEquivalents = htmlAttributeEquivalents(); for (size_t i = 0; i < attributeEquivalents.size(); ++i) { if (attributeEquivalents[i]->attributeName() == HTMLNames::dirAttr) continue; // We don't want to include directionality if (elementMatchesAndPropertyIsNotInInlineStyleDecl(attributeEquivalents[i].get(), element, mode, m_mutableStyle.get())) attributeEquivalents[i]->addToStyle(element, this); } } PassRefPtr<EditingStyle> EditingStyle::wrappingStyleForSerialization(Node* context, bool shouldAnnotate) { RefPtr<EditingStyle> wrappingStyle; if (shouldAnnotate) { wrappingStyle = EditingStyle::create(context, EditingStyle::EditingPropertiesInEffect); // Styles that Mail blockquotes contribute should only be placed on the Mail blockquote, // to help us differentiate those styles from ones that the user has applied. // This helps us get the color of content pasted into blockquotes right. wrappingStyle->removeStyleAddedByNode(enclosingNodeOfType(firstPositionInOrBeforeNode(context), isMailBlockquote, CanCrossEditingBoundary)); // Call collapseTextDecorationProperties first or otherwise it'll copy the value over from in-effect to text-decorations. wrappingStyle->collapseTextDecorationProperties(); return wrappingStyle.release(); } wrappingStyle = EditingStyle::create(); // When not annotating for interchange, we only preserve inline style declarations. for (Node* node = context; node && !node->isDocumentNode(); node = node->parentNode()) { if (node->isStyledElement() && !isMailBlockquote(node)) { wrappingStyle->mergeInlineAndImplicitStyleOfElement(toStyledElement(node), EditingStyle::DoNotOverrideValues, EditingStyle::EditingPropertiesInEffect); } } return wrappingStyle.release(); } static void mergeTextDecorationValues(CSSValueList* mergedValue, const CSSValueList* valueToMerge) { RefPtr<CSSPrimitiveValue> underline = cssValuePool().createIdentifierValue(CSSValueUnderline); RefPtr<CSSPrimitiveValue> lineThrough = cssValuePool().createIdentifierValue(CSSValueLineThrough); if (valueToMerge->hasValue(underline.get()) && !mergedValue->hasValue(underline.get())) mergedValue->append(underline.get()); if (valueToMerge->hasValue(lineThrough.get()) && !mergedValue->hasValue(lineThrough.get())) mergedValue->append(lineThrough.get()); } void EditingStyle::mergeStyle(const StyleProperties* style, CSSPropertyOverrideMode mode) { if (!style) return; if (!m_mutableStyle) { m_mutableStyle = style->mutableCopy(); return; } unsigned propertyCount = style->propertyCount(); for (unsigned i = 0; i < propertyCount; ++i) { StyleProperties::PropertyReference property = style->propertyAt(i); RefPtr<CSSValue> value = m_mutableStyle->getPropertyCSSValue(property.id()); // text decorations never override values if ((property.id() == CSSPropertyTextDecoration || property.id() == CSSPropertyWebkitTextDecorationsInEffect) && property.value()->isValueList() && value) { if (value->isValueList()) { mergeTextDecorationValues(toCSSValueList(value.get()), toCSSValueList(property.value())); continue; } value = 0; // text-decoration: none is equivalent to not having the property } if (mode == OverrideValues || (mode == DoNotOverrideValues && !value)) m_mutableStyle->setProperty(property.id(), property.value()->cssText(), property.isImportant()); } int oldFontSizeDelta = m_fontSizeDelta; extractFontSizeDelta(); m_fontSizeDelta += oldFontSizeDelta; } static PassRefPtr<MutableStyleProperties> styleFromMatchedRulesForElement(Element* element, unsigned rulesToInclude) { RefPtr<MutableStyleProperties> style = MutableStyleProperties::create(); auto matchedRules = element->document().ensureStyleResolver().styleRulesForElement(element, rulesToInclude); for (unsigned i = 0; i < matchedRules.size(); ++i) { if (matchedRules[i]->isStyleRule()) style->mergeAndOverrideOnConflict(static_pointer_cast<StyleRule>(matchedRules[i])->properties()); } return style.release(); } void EditingStyle::mergeStyleFromRules(StyledElement* element) { RefPtr<MutableStyleProperties> styleFromMatchedRules = styleFromMatchedRulesForElement(element, StyleResolver::AuthorCSSRules | StyleResolver::CrossOriginCSSRules); // Styles from the inline style declaration, held in the variable "style", take precedence // over those from matched rules. if (m_mutableStyle) styleFromMatchedRules->mergeAndOverrideOnConflict(*m_mutableStyle); clear(); m_mutableStyle = styleFromMatchedRules; } void EditingStyle::mergeStyleFromRulesForSerialization(StyledElement* element) { mergeStyleFromRules(element); // The property value, if it's a percentage, may not reflect the actual computed value. // For example: style="height: 1%; overflow: visible;" in quirksmode // FIXME: There are others like this, see <rdar://problem/5195123> Slashdot copy/paste fidelity problem RefPtr<MutableStyleProperties> fromComputedStyle = MutableStyleProperties::create(); ComputedStyleExtractor computedStyle(element); { unsigned propertyCount = m_mutableStyle->propertyCount(); for (unsigned i = 0; i < propertyCount; ++i) { StyleProperties::PropertyReference property = m_mutableStyle->propertyAt(i); CSSValue* value = property.value(); if (!value->isPrimitiveValue()) continue; if (toCSSPrimitiveValue(value)->isPercentage()) { if (RefPtr<CSSValue> computedPropertyValue = computedStyle.propertyValue(property.id())) fromComputedStyle->addParsedProperty(CSSProperty(property.id(), computedPropertyValue.release())); } } } m_mutableStyle->mergeAndOverrideOnConflict(*fromComputedStyle); } static void removePropertiesInStyle(MutableStyleProperties* styleToRemovePropertiesFrom, StyleProperties* style) { unsigned propertyCount = style->propertyCount(); Vector<CSSPropertyID> propertiesToRemove(propertyCount); for (unsigned i = 0; i < propertyCount; ++i) propertiesToRemove[i] = style->propertyAt(i).id(); styleToRemovePropertiesFrom->removePropertiesInSet(propertiesToRemove.data(), propertiesToRemove.size()); } void EditingStyle::removeStyleFromRulesAndContext(StyledElement* element, Node* context) { ASSERT(element); if (!m_mutableStyle) return; // 1. Remove style from matched rules because style remain without repeating it in inline style declaration RefPtr<MutableStyleProperties> styleFromMatchedRules = styleFromMatchedRulesForElement(element, StyleResolver::AllButEmptyCSSRules); if (styleFromMatchedRules && !styleFromMatchedRules->isEmpty()) m_mutableStyle = getPropertiesNotIn(m_mutableStyle.get(), styleFromMatchedRules.get()); // 2. Remove style present in context and not overriden by matched rules. RefPtr<EditingStyle> computedStyle = EditingStyle::create(context, EditingPropertiesInEffect); if (computedStyle->m_mutableStyle) { if (!computedStyle->m_mutableStyle->getPropertyCSSValue(CSSPropertyBackgroundColor)) computedStyle->m_mutableStyle->setProperty(CSSPropertyBackgroundColor, CSSValueTransparent); removePropertiesInStyle(computedStyle->m_mutableStyle.get(), styleFromMatchedRules.get()); m_mutableStyle = getPropertiesNotIn(m_mutableStyle.get(), computedStyle->m_mutableStyle.get()); } // 3. If this element is a span and has display: inline or float: none, remove them unless they are overriden by rules. // These rules are added by serialization code to wrap text nodes. if (isStyleSpanOrSpanWithOnlyStyleAttribute(element)) { if (!styleFromMatchedRules->getPropertyCSSValue(CSSPropertyDisplay) && identifierForStyleProperty(m_mutableStyle.get(), CSSPropertyDisplay) == CSSValueInline) m_mutableStyle->removeProperty(CSSPropertyDisplay); if (!styleFromMatchedRules->getPropertyCSSValue(CSSPropertyFloat) && identifierForStyleProperty(m_mutableStyle.get(), CSSPropertyFloat) == CSSValueNone) m_mutableStyle->removeProperty(CSSPropertyFloat); } } void EditingStyle::removePropertiesInElementDefaultStyle(Element* element) { if (!m_mutableStyle || m_mutableStyle->isEmpty()) return; RefPtr<StyleProperties> defaultStyle = styleFromMatchedRulesForElement(element, StyleResolver::UAAndUserCSSRules); removePropertiesInStyle(m_mutableStyle.get(), defaultStyle.get()); } template<typename T> void EditingStyle::removeEquivalentProperties(const T& style) { Vector<CSSPropertyID> propertiesToRemove; for (auto& property : m_mutableStyle->m_propertyVector) { if (style.propertyMatches(property.id(), property.value())) propertiesToRemove.append(property.id()); } // FIXME: This should use mass removal. for (auto& property : propertiesToRemove) m_mutableStyle->removeProperty(property); } void EditingStyle::forceInline() { if (!m_mutableStyle) m_mutableStyle = MutableStyleProperties::create(); const bool propertyIsImportant = true; m_mutableStyle->setProperty(CSSPropertyDisplay, CSSValueInline, propertyIsImportant); } bool EditingStyle::convertPositionStyle() { if (!m_mutableStyle) return false; RefPtr<CSSPrimitiveValue> sticky = cssValuePool().createIdentifierValue(CSSValueWebkitSticky); if (m_mutableStyle->propertyMatches(CSSPropertyPosition, sticky.get())) { m_mutableStyle->setProperty(CSSPropertyPosition, cssValuePool().createIdentifierValue(CSSValueStatic), m_mutableStyle->propertyIsImportant(CSSPropertyPosition)); return false; } RefPtr<CSSPrimitiveValue> fixed = cssValuePool().createIdentifierValue(CSSValueFixed); if (m_mutableStyle->propertyMatches(CSSPropertyPosition, fixed.get())) { m_mutableStyle->setProperty(CSSPropertyPosition, cssValuePool().createIdentifierValue(CSSValueAbsolute), m_mutableStyle->propertyIsImportant(CSSPropertyPosition)); return true; } RefPtr<CSSPrimitiveValue> absolute = cssValuePool().createIdentifierValue(CSSValueAbsolute); if (m_mutableStyle->propertyMatches(CSSPropertyPosition, absolute.get())) return true; return false; } bool EditingStyle::isFloating() { RefPtr<CSSValue> v = m_mutableStyle->getPropertyCSSValue(CSSPropertyFloat); RefPtr<CSSPrimitiveValue> noneValue = cssValuePool().createIdentifierValue(CSSValueNone); return v && !v->equals(*noneValue); } int EditingStyle::legacyFontSize(Document* document) const { RefPtr<CSSValue> cssValue = m_mutableStyle->getPropertyCSSValue(CSSPropertyFontSize); if (!cssValue || !cssValue->isPrimitiveValue()) return 0; return legacyFontSizeFromCSSValue(document, toCSSPrimitiveValue(cssValue.get()), m_shouldUseFixedDefaultFontSize, AlwaysUseLegacyFontSize); } PassRefPtr<EditingStyle> EditingStyle::styleAtSelectionStart(const VisibleSelection& selection, bool shouldUseBackgroundColorInEffect) { if (selection.isNone()) return 0; Position position = adjustedSelectionStartForStyleComputation(selection); // If the pos is at the end of a text node, then this node is not fully selected. // Move it to the next deep equivalent position to avoid removing the style from this node. // e.g. if pos was at Position("hello", 5) in <b>hello<div>world</div></b>, we want Position("world", 0) instead. // We only do this for range because caret at Position("hello", 5) in <b>hello</b>world should give you font-weight: bold. Node* positionNode = position.containerNode(); if (selection.isRange() && positionNode && positionNode->isTextNode() && position.computeOffsetInContainerNode() == positionNode->maxCharacterOffset()) position = nextVisuallyDistinctCandidate(position); Element* element = position.element(); if (!element) return 0; RefPtr<EditingStyle> style = EditingStyle::create(element, EditingStyle::AllProperties); style->mergeTypingStyle(element->document()); // If background color is transparent, traverse parent nodes until we hit a different value or document root // Also, if the selection is a range, ignore the background color at the start of selection, // and find the background color of the common ancestor. if (shouldUseBackgroundColorInEffect && (selection.isRange() || hasTransparentBackgroundColor(style->m_mutableStyle.get()))) { RefPtr<Range> range(selection.toNormalizedRange()); if (PassRefPtr<CSSValue> value = backgroundColorInEffect(range->commonAncestorContainer(IGNORE_EXCEPTION))) style->setProperty(CSSPropertyBackgroundColor, value->cssText()); } return style; } WritingDirection EditingStyle::textDirectionForSelection(const VisibleSelection& selection, EditingStyle* typingStyle, bool& hasNestedOrMultipleEmbeddings) { hasNestedOrMultipleEmbeddings = true; if (selection.isNone()) return NaturalWritingDirection; Position position = selection.start().downstream(); Node* node = position.deprecatedNode(); if (!node) return NaturalWritingDirection; Position end; if (selection.isRange()) { end = selection.end().upstream(); Node* pastLast = Range::create(*end.document(), position.parentAnchoredEquivalent(), end.parentAnchoredEquivalent())->pastLastNode(); for (Node* n = node; n && n != pastLast; n = NodeTraversal::next(n)) { if (!n->isStyledElement()) continue; RefPtr<CSSValue> unicodeBidi = ComputedStyleExtractor(n).propertyValue(CSSPropertyUnicodeBidi); if (!unicodeBidi || !unicodeBidi->isPrimitiveValue()) continue; CSSValueID unicodeBidiValue = toCSSPrimitiveValue(unicodeBidi.get())->getValueID(); if (unicodeBidiValue == CSSValueEmbed || unicodeBidiValue == CSSValueBidiOverride) return NaturalWritingDirection; } } if (selection.isCaret()) { WritingDirection direction; if (typingStyle && typingStyle->textDirection(direction)) { hasNestedOrMultipleEmbeddings = false; return direction; } node = selection.visibleStart().deepEquivalent().deprecatedNode(); } // The selection is either a caret with no typing attributes or a range in which no embedding is added, so just use the start position // to decide. Node* block = enclosingBlock(node); WritingDirection foundDirection = NaturalWritingDirection; for (; node != block; node = node->parentNode()) { if (!node->isStyledElement()) continue; ComputedStyleExtractor computedStyle(node); RefPtr<CSSValue> unicodeBidi = computedStyle.propertyValue(CSSPropertyUnicodeBidi); if (!unicodeBidi || !unicodeBidi->isPrimitiveValue()) continue; CSSValueID unicodeBidiValue = toCSSPrimitiveValue(unicodeBidi.get())->getValueID(); if (unicodeBidiValue == CSSValueNormal) continue; if (unicodeBidiValue == CSSValueBidiOverride) return NaturalWritingDirection; ASSERT(unicodeBidiValue == CSSValueEmbed); RefPtr<CSSValue> direction = computedStyle.propertyValue(CSSPropertyDirection); if (!direction || !direction->isPrimitiveValue()) continue; CSSValueID directionValue = toCSSPrimitiveValue(direction.get())->getValueID(); if (directionValue != CSSValueLtr && directionValue != CSSValueRtl) continue; if (foundDirection != NaturalWritingDirection) return NaturalWritingDirection; // In the range case, make sure that the embedding element persists until the end of the range. if (selection.isRange() && !end.deprecatedNode()->isDescendantOf(node)) return NaturalWritingDirection; foundDirection = directionValue == CSSValueLtr ? LeftToRightWritingDirection : RightToLeftWritingDirection; } hasNestedOrMultipleEmbeddings = false; return foundDirection; } static void reconcileTextDecorationProperties(MutableStyleProperties* style) { RefPtr<CSSValue> textDecorationsInEffect = style->getPropertyCSSValue(CSSPropertyWebkitTextDecorationsInEffect); RefPtr<CSSValue> textDecoration = style->getPropertyCSSValue(CSSPropertyTextDecoration); // We shouldn't have both text-decoration and -webkit-text-decorations-in-effect because that wouldn't make sense. ASSERT(!textDecorationsInEffect || !textDecoration); if (textDecorationsInEffect) { style->setProperty(CSSPropertyTextDecoration, textDecorationsInEffect->cssText()); style->removeProperty(CSSPropertyWebkitTextDecorationsInEffect); textDecoration = textDecorationsInEffect; } // If text-decoration is set to "none", remove the property because we don't want to add redundant "text-decoration: none". if (textDecoration && !textDecoration->isValueList()) style->removeProperty(CSSPropertyTextDecoration); } StyleChange::StyleChange(EditingStyle* style, const Position& position) : m_applyBold(false) , m_applyItalic(false) , m_applyUnderline(false) , m_applyLineThrough(false) , m_applySubscript(false) , m_applySuperscript(false) { Document* document = position.anchorNode() ? &position.anchorNode()->document() : 0; if (!style || !style->style() || !document || !document->frame()) return; Node* node = position.containerNode(); if (!node) return; ComputedStyleExtractor computedStyle(node); // FIXME: take care of background-color in effect RefPtr<MutableStyleProperties> mutableStyle = getPropertiesNotIn(style->style(), &computedStyle); reconcileTextDecorationProperties(mutableStyle.get()); if (!document->frame()->editor().shouldStyleWithCSS()) extractTextStyles(document, mutableStyle.get(), computedStyle.useFixedFontDefaultSize()); // Changing the whitespace style in a tab span would collapse the tab into a space. if (isTabSpanTextNode(position.deprecatedNode()) || isTabSpanNode((position.deprecatedNode()))) mutableStyle->removeProperty(CSSPropertyWhiteSpace); // If unicode-bidi is present in mutableStyle and direction is not, then add direction to mutableStyle. // FIXME: Shouldn't this be done in getPropertiesNotIn? if (mutableStyle->getPropertyCSSValue(CSSPropertyUnicodeBidi) && !style->style()->getPropertyCSSValue(CSSPropertyDirection)) mutableStyle->setProperty(CSSPropertyDirection, style->style()->getPropertyValue(CSSPropertyDirection)); // Save the result for later m_cssStyle = mutableStyle->asText().stripWhiteSpace(); } static void setTextDecorationProperty(MutableStyleProperties* style, const CSSValueList* newTextDecoration, CSSPropertyID propertyID) { if (newTextDecoration->length()) style->setProperty(propertyID, newTextDecoration->cssText(), style->propertyIsImportant(propertyID)); else { // text-decoration: none is redundant since it does not remove any text decorations. style->removeProperty(propertyID); } } void StyleChange::extractTextStyles(Document* document, MutableStyleProperties* style, bool shouldUseFixedFontDefaultSize) { ASSERT(style); if (identifierForStyleProperty(style, CSSPropertyFontWeight) == CSSValueBold) { style->removeProperty(CSSPropertyFontWeight); m_applyBold = true; } int fontStyle = identifierForStyleProperty(style, CSSPropertyFontStyle); if (fontStyle == CSSValueItalic || fontStyle == CSSValueOblique) { style->removeProperty(CSSPropertyFontStyle); m_applyItalic = true; } // Assuming reconcileTextDecorationProperties has been called, there should not be -webkit-text-decorations-in-effect // Furthermore, text-decoration: none has been trimmed so that text-decoration property is always a CSSValueList. RefPtr<CSSValue> textDecoration = style->getPropertyCSSValue(CSSPropertyTextDecoration); if (textDecoration && textDecoration->isValueList()) { RefPtr<CSSPrimitiveValue> underline = cssValuePool().createIdentifierValue(CSSValueUnderline); RefPtr<CSSPrimitiveValue> lineThrough = cssValuePool().createIdentifierValue(CSSValueLineThrough); RefPtr<CSSValueList> newTextDecoration = toCSSValueList(textDecoration.get())->copy(); if (newTextDecoration->removeAll(underline.get())) m_applyUnderline = true; if (newTextDecoration->removeAll(lineThrough.get())) m_applyLineThrough = true; // If trimTextDecorations, delete underline and line-through setTextDecorationProperty(style, newTextDecoration.get(), CSSPropertyTextDecoration); } int verticalAlign = identifierForStyleProperty(style, CSSPropertyVerticalAlign); switch (verticalAlign) { case CSSValueSub: style->removeProperty(CSSPropertyVerticalAlign); m_applySubscript = true; break; case CSSValueSuper: style->removeProperty(CSSPropertyVerticalAlign); m_applySuperscript = true; break; } if (style->getPropertyCSSValue(CSSPropertyColor)) { m_applyFontColor = Color(textColorFromStyle(style)).serialized(); style->removeProperty(CSSPropertyColor); } m_applyFontFace = style->getPropertyValue(CSSPropertyFontFamily); // Remove single quotes for Outlook 2007 compatibility. See https://bugs.webkit.org/show_bug.cgi?id=79448 m_applyFontFace.replaceWithLiteral('\'', ""); style->removeProperty(CSSPropertyFontFamily); if (RefPtr<CSSValue> fontSize = style->getPropertyCSSValue(CSSPropertyFontSize)) { if (!fontSize->isPrimitiveValue()) style->removeProperty(CSSPropertyFontSize); // Can't make sense of the number. Put no font size. else if (int legacyFontSize = legacyFontSizeFromCSSValue(document, toCSSPrimitiveValue(fontSize.get()), shouldUseFixedFontDefaultSize, UseLegacyFontSizeOnlyIfPixelValuesMatch)) { m_applyFontSize = String::number(legacyFontSize); style->removeProperty(CSSPropertyFontSize); } } } static void diffTextDecorations(MutableStyleProperties* style, CSSPropertyID propertID, CSSValue* refTextDecoration) { RefPtr<CSSValue> textDecoration = style->getPropertyCSSValue(propertID); if (!textDecoration || !textDecoration->isValueList() || !refTextDecoration || !refTextDecoration->isValueList()) return; RefPtr<CSSValueList> newTextDecoration = toCSSValueList(textDecoration.get())->copy(); CSSValueList* valuesInRefTextDecoration = toCSSValueList(refTextDecoration); for (size_t i = 0; i < valuesInRefTextDecoration->length(); i++) newTextDecoration->removeAll(valuesInRefTextDecoration->item(i)); setTextDecorationProperty(style, newTextDecoration.get(), propertID); } static bool fontWeightIsBold(CSSValue* fontWeight) { if (!fontWeight) return false; if (!fontWeight->isPrimitiveValue()) return false; // Because b tag can only bold text, there are only two states in plain html: bold and not bold. // Collapse all other values to either one of these two states for editing purposes. switch (toCSSPrimitiveValue(fontWeight)->getValueID()) { case CSSValue100: case CSSValue200: case CSSValue300: case CSSValue400: case CSSValue500: case CSSValueNormal: return false; case CSSValueBold: case CSSValue600: case CSSValue700: case CSSValue800: case CSSValue900: return true; default: break; } ASSERT_NOT_REACHED(); // For CSSValueBolder and CSSValueLighter return false; } template<typename T> static bool fontWeightIsBold(T* style) { return fontWeightIsBold(extractPropertyValue(style, CSSPropertyFontWeight).get()); } template<typename T> static PassRefPtr<MutableStyleProperties> extractPropertiesNotIn(StyleProperties* styleWithRedundantProperties, T* baseStyle) { ASSERT(styleWithRedundantProperties); RefPtr<EditingStyle> result = EditingStyle::create(styleWithRedundantProperties); result->removeEquivalentProperties(*baseStyle); RefPtr<MutableStyleProperties> mutableStyle = result->style(); RefPtr<CSSValue> baseTextDecorationsInEffect = extractPropertyValue(baseStyle, CSSPropertyWebkitTextDecorationsInEffect); diffTextDecorations(mutableStyle.get(), CSSPropertyTextDecoration, baseTextDecorationsInEffect.get()); diffTextDecorations(mutableStyle.get(), CSSPropertyWebkitTextDecorationsInEffect, baseTextDecorationsInEffect.get()); if (extractPropertyValue(baseStyle, CSSPropertyFontWeight) && fontWeightIsBold(mutableStyle.get()) == fontWeightIsBold(baseStyle)) mutableStyle->removeProperty(CSSPropertyFontWeight); if (extractPropertyValue(baseStyle, CSSPropertyColor) && textColorFromStyle(mutableStyle.get()) == textColorFromStyle(baseStyle)) mutableStyle->removeProperty(CSSPropertyColor); if (extractPropertyValue(baseStyle, CSSPropertyTextAlign) && textAlignResolvingStartAndEnd(mutableStyle.get()) == textAlignResolvingStartAndEnd(baseStyle)) mutableStyle->removeProperty(CSSPropertyTextAlign); if (extractPropertyValue(baseStyle, CSSPropertyBackgroundColor) && backgroundColorFromStyle(mutableStyle.get()) == backgroundColorFromStyle(baseStyle)) mutableStyle->removeProperty(CSSPropertyBackgroundColor); return mutableStyle.release(); } template<typename T> PassRefPtr<MutableStyleProperties> getPropertiesNotIn(StyleProperties* styleWithRedundantProperties, T* baseStyle) { return extractPropertiesNotIn(styleWithRedundantProperties, baseStyle); } static bool isCSSValueLength(CSSPrimitiveValue* value) { return value->isFontIndependentLength(); } int legacyFontSizeFromCSSValue(Document* document, CSSPrimitiveValue* value, bool shouldUseFixedFontDefaultSize, LegacyFontSizeMode mode) { ASSERT(document); // FIXME: This method should take a Document& if (isCSSValueLength(value)) { int pixelFontSize = value->getIntValue(CSSPrimitiveValue::CSS_PX); int legacyFontSize = Style::legacyFontSizeForPixelSize(pixelFontSize, shouldUseFixedFontDefaultSize, *document); // Use legacy font size only if pixel value matches exactly to that of legacy font size. int cssPrimitiveEquivalent = legacyFontSize - 1 + CSSValueXSmall; if (mode == AlwaysUseLegacyFontSize || Style::fontSizeForKeyword(cssPrimitiveEquivalent, shouldUseFixedFontDefaultSize, *document) == pixelFontSize) return legacyFontSize; return 0; } if (CSSValueXSmall <= value->getValueID() && value->getValueID() <= CSSValueWebkitXxxLarge) return value->getValueID() - CSSValueXSmall + 1; return 0; } bool isTransparentColorValue(CSSValue* cssValue) { if (!cssValue) return true; if (!cssValue->isPrimitiveValue()) return false; CSSPrimitiveValue* value = toCSSPrimitiveValue(cssValue); if (value->isRGBColor()) return !alphaChannel(value->getRGBA32Value()); return value->getValueID() == CSSValueTransparent; } bool hasTransparentBackgroundColor(StyleProperties* style) { RefPtr<CSSValue> cssValue = style->getPropertyCSSValue(CSSPropertyBackgroundColor); return isTransparentColorValue(cssValue.get()); } PassRefPtr<CSSValue> backgroundColorInEffect(Node* node) { for (Node* ancestor = node; ancestor; ancestor = ancestor->parentNode()) { if (RefPtr<CSSValue> value = ComputedStyleExtractor(ancestor).propertyValue(CSSPropertyBackgroundColor)) { if (!isTransparentColorValue(value.get())) return value.release(); } } return 0; } }
bsd-2-clause
bric3/homebrew-cask
Casks/cardhop.rb
1010
cask "cardhop" do version "1.3.8,236" sha256 "edbc00e147cd2fd9262e6615ed0d18a16d63ebd22e0e6f333a4606a6dfbbaf13" url "https://cdn.flexibits.com/Cardhop_#{version.before_comma}.zip" name "Cardhop" desc "Contacts manager" homepage "https://flexibits.com/cardhop" livecheck do url "https://flexibits.com/cardhop/appcast.php" strategy :sparkle end auto_updates true app "Cardhop.app" uninstall launchctl: "com.flexibits.cardhop.mac.launcher", quit: "com.flexibits.cardhop.mac" zap trash: [ "~/Library/Preferences/com.flexibits.cardhop.mac.plist", "~/Library/Application Scripts/com.flexibits.cardhop.mac", "~/Library/Application Scripts/com.flexibits.cardhop.mac.launcher", "~/Library/Application Scripts/com.flexibits.cardhop.mac.BluetoothDialer", "~/Library/Containers/com.flexibits.cardhop.mac", "~/Library/Containers/com.flexibits.cardhop.mac.launcher", "~/Library/Containers/com.flexibits.cardhop.mac.BluetoothDialer", ] end
bsd-2-clause
jvehent/homebrew-core
Formula/curl.rb
4495
class Curl < Formula desc "Get a file from an HTTP, HTTPS or FTP server" homepage "https://curl.haxx.se/" url "https://curl.haxx.se/download/curl-7.50.3.tar.bz2" sha256 "7b7347d976661d02c84a1f4d6daf40dee377efdc45b9e2c77dedb8acf140d8ec" bottle do cellar :any sha256 "638108732f8c4dacea7953c81b070d8ab8bde837e0608f0b4ca36124b7ff1055" => :sierra sha256 "b425bee3c2602e9b470db43b00418805e97ab675bfdd292be194e61fca8d9f52" => :el_capitan sha256 "acd850690b6578bf1f7682804734cadf5b922aa17d696ef5154b15d048712319" => :yosemite sha256 "cfbb0a2c28b150d13a239b9a6acd95cdd530cf57f7e26831f966d672e88dfcc0" => :mavericks end keg_only :provided_by_osx option "with-libidn", "Build with support for Internationalized Domain Names" option "with-rtmpdump", "Build with RTMP support" option "with-libssh2", "Build with scp and sftp support" option "with-c-ares", "Build with C-Ares async DNS support" option "with-gssapi", "Build with GSSAPI/Kerberos authentication support." option "with-libmetalink", "Build with libmetalink support." option "with-libressl", "Build with LibreSSL instead of Secure Transport or OpenSSL" option "with-nghttp2", "Build with HTTP/2 support (requires OpenSSL or LibreSSL)" deprecated_option "with-idn" => "with-libidn" deprecated_option "with-rtmp" => "with-rtmpdump" deprecated_option "with-ssh" => "with-libssh2" deprecated_option "with-ares" => "with-c-ares" # HTTP/2 support requires OpenSSL 1.0.2+ or LibreSSL 2.1.3+ for ALPN Support # which is currently not supported by Secure Transport (DarwinSSL). if MacOS.version < :mountain_lion || (build.with?("nghttp2") && build.without?("libressl")) depends_on "openssl" else option "with-openssl", "Build with OpenSSL instead of Secure Transport" depends_on "openssl" => :optional end depends_on "pkg-config" => :build depends_on "libidn" => :optional depends_on "rtmpdump" => :optional depends_on "libssh2" => :optional depends_on "c-ares" => :optional depends_on "libmetalink" => :optional depends_on "libressl" => :optional depends_on "nghttp2" => :optional def install # Fail if someone tries to use both SSL choices. # Long-term, handle conflicting options case in core code. if build.with?("libressl") && build.with?("openssl") odie <<-EOS.undent --with-openssl and --with-libressl are both specified and curl can only use one at a time. EOS end args = %W[ --disable-debug --disable-dependency-tracking --disable-silent-rules --prefix=#{prefix} ] # cURL has a new firm desire to find ssl with PKG_CONFIG_PATH instead of using # "--with-ssl" any more. "when possible, set the PKG_CONFIG_PATH environment # variable instead of using this option". Multi-SSL choice breaks w/o using it. if build.with? "libressl" ENV.prepend_path "PKG_CONFIG_PATH", "#{Formula["libressl"].opt_lib}/pkgconfig" args << "--with-ssl=#{Formula["libressl"].opt_prefix}" args << "--with-ca-bundle=#{etc}/libressl/cert.pem" elsif MacOS.version < :mountain_lion || build.with?("openssl") || build.with?("nghttp2") ENV.prepend_path "PKG_CONFIG_PATH", "#{Formula["openssl"].opt_lib}/pkgconfig" args << "--with-ssl=#{Formula["openssl"].opt_prefix}" args << "--with-ca-bundle=#{etc}/openssl/cert.pem" else args << "--with-darwinssl" end args << (build.with?("libssh2") ? "--with-libssh2" : "--without-libssh2") args << (build.with?("libidn") ? "--with-libidn" : "--without-libidn") args << (build.with?("libmetalink") ? "--with-libmetalink" : "--without-libmetalink") args << (build.with?("gssapi") ? "--with-gssapi" : "--without-gssapi") args << (build.with?("rtmpdump") ? "--with-librtmp" : "--without-librtmp") if build.with? "c-ares" args << "--enable-ares=#{Formula["c-ares"].opt_prefix}" else args << "--disable-ares" end system "./configure", *args system "make", "install" libexec.install "lib/mk-ca-bundle.pl" end test do # Fetch the curl tarball and see that the checksum matches. # This requires a network connection, but so does Homebrew in general. filename = (testpath/"test.tar.gz") system "#{bin}/curl", "-L", stable.url, "-o", filename filename.verify_checksum stable.checksum system libexec/"mk-ca-bundle.pl", "test.pem" assert File.exist?("test.pem") assert File.exist?("certdata.txt") end end
bsd-2-clause
benchalmers/win-installer
src/InstallAgent/State/Installer.cs
6300
using HelperFunctions; using Microsoft.Win32; using System; namespace State { public static class Installer { private static int currentState; private static readonly string stateRegKey = InstallAgent.InstallAgent.rootRegKeyName + @"\InstallerState"; private static readonly int systemCleaned = (int)( States.RemovedFromFilters | States.BootStartDisabled | States.MSIsUninstalled | States.DrvsAndDevsUninstalled | States.CleanedUp ); private static readonly int everythingInstalled = (int)( States.XenBusInstalled | States.XenIfaceInstalled | States.XenVifInstalled | States.XenNetInstalled | States.XenVbdInstalled | States.CertificatesInstalled ); private static readonly int complete = (int) ( States.NetworkSettingsSaved | States.NetworkSettingsRestored) | systemCleaned | everythingInstalled; private struct StateInfo { private readonly string name; private readonly int defaultValue; public StateInfo(string name, int defaultValue) { this.name = name; this.defaultValue = defaultValue; } public string Name { get { return name; } } public int DefaultValue { get { return defaultValue; } } }; private static readonly StateInfo[] statesDefault = { new StateInfo("NetworkSettingsSaved", 0), new StateInfo("NetworkSettingsRestored", 0), new StateInfo("RemovedFromFilters", 0), new StateInfo("BootStartDisabled", 0), new StateInfo("MSIsUninstalled", 0), new StateInfo("DrvsAndDevsUninstalled", 0), new StateInfo("CleanedUp", 0), new StateInfo("XenBusInstalled", 0), new StateInfo("XenIfaceInstalled", 0), new StateInfo("XenVifInstalled", 0), new StateInfo("XenNetInstalled", 0), new StateInfo("XenVbdInstalled", 0), new StateInfo("CertificatesInstalled", 0), new StateInfo("ProceedWithSystemClean", 0), }; [Flags] // For most of the flags, setting them to 1 means either // the task is complete or no action required. public enum States { NetworkSettingsSaved = 1 << 0, NetworkSettingsRestored = 1 << 1, // ---- PV Drivers Removal States ---- RemovedFromFilters = 1 << 2, BootStartDisabled = 1 << 3, MSIsUninstalled = 1 << 4, DrvsAndDevsUninstalled = 1 << 5, CleanedUp = 1 << 6, // --------------- End --------------- // ------- PV Drivers Installed ------- XenBusInstalled = 1 << 7, XenIfaceInstalled = 1 << 8, XenVifInstalled = 1 << 9, XenNetInstalled = 1 << 10, XenVbdInstalled = 1 << 11, // ---------------- End --------------- CertificatesInstalled = 1 << 12, ProceedWithSystemClean = 1 << 13, } // Static constructor: queries the Registry for the // state of the installer and initializes itself. static Installer() { // In .NET 3.5: Creates a new subkey or opens an // existing subkey for write access RegistryKey installStateRK = Registry.LocalMachine.CreateSubKey(stateRegKey); currentState = 0; for (int i = 0; i < statesDefault.Length; ++i) { int flag = (int) installStateRK.GetValue( statesDefault[i].Name, statesDefault[i].DefaultValue ); currentState |= flag << i; } } public static void SetFlag(States flag) { int i = Helpers.BitIdxFromFlag((uint)flag); string flagName = statesDefault[i].Name; using (RegistryKey installStateRK = Registry.LocalMachine.OpenSubKey(stateRegKey, true)) { installStateRK.SetValue(flagName, 1, RegistryValueKind.DWord); currentState |= (int)flag; } } public static void UnsetFlag(States flag) { int i = Helpers.BitIdxFromFlag((uint)flag); string flagName = statesDefault[i].Name; using (RegistryKey installStateRK = Registry.LocalMachine.OpenSubKey(stateRegKey, true)) { installStateRK.SetValue(flagName, 0, RegistryValueKind.DWord); currentState &= ~(int)flag; } } public static void FlipFlag(States flag) { if (GetFlag(flag)) { UnsetFlag(flag); } else { SetFlag(flag); } } public static void LogicalANDFlag(States flag, bool value) { if (GetFlag(flag) & value) { SetFlag(flag); } else { UnsetFlag(flag); } } public static void LogicalORFlag(States flag, bool value) { if (GetFlag(flag) | value) { SetFlag(flag); } else { UnsetFlag(flag); } } public static bool GetFlag(States flag) { return (currentState & (int) flag) != 0; } public static bool SystemCleaned() { // (currentState & systemCleaned) clears all other bits // so we can check just the ones we need return (currentState & systemCleaned) == systemCleaned; } public static bool EverythingInstalled() { return (currentState & everythingInstalled) == everythingInstalled; } public static bool Complete() { return currentState == complete; } } }
bsd-2-clause
fsjohnhuang/lpp
src/beta 0.3/lpp/lpp.Location.js
517
(function() { lpp.Location = { getAP: function(relativePath) { return lpp("<div><a href=\"" + relativePath + "\"></a></div>").child('a').dom[0].href; }, getCurDirAP: function() { return getAP('./'); }, getQueryParam: function(key) { var r, reg; reg = RegExp("(^|&)" + key + "=([^&]*)(&|$)", "i"); r = location.search.substr(1).match(reg); if (r != null) { return unescape(r[2]); } else { return null; } } }; }).call(this);
bsd-2-clause
AeroGlass/g3m
Commons/G3MSharedSDK/src/org/glob3/mobile/generated/GInitializationTask.java
268
package org.glob3.mobile.generated; // // GInitializationTask.hpp // G3MiOSSDK // // Created by Diego Gomez Deck on 12/11/12. // // public abstract class GInitializationTask extends GTask { public abstract boolean isDone(G3MContext context); }
bsd-2-clause
zoraseb/perun
perun-core/src/main/java/cz/metacentrum/perun/core/implApi/AttributesManagerImplApi.java
114513
/** * */ package cz.metacentrum.perun.core.implApi; import cz.metacentrum.perun.core.api.ActionType; import cz.metacentrum.perun.core.api.Attribute; import cz.metacentrum.perun.core.api.AttributeDefinition; import cz.metacentrum.perun.core.api.AttributeRights; import cz.metacentrum.perun.core.api.Facility; import cz.metacentrum.perun.core.api.Group; import cz.metacentrum.perun.core.api.Host; import cz.metacentrum.perun.core.api.Member; import cz.metacentrum.perun.core.api.Pair; import cz.metacentrum.perun.core.api.PerunBean; import cz.metacentrum.perun.core.api.PerunSession; import cz.metacentrum.perun.core.api.Resource; import cz.metacentrum.perun.core.api.RichAttribute; import cz.metacentrum.perun.core.api.Service; import cz.metacentrum.perun.core.api.User; import cz.metacentrum.perun.core.api.UserExtSource; import cz.metacentrum.perun.core.api.Vo; import cz.metacentrum.perun.core.api.exceptions.ActionTypeNotExistsException; import cz.metacentrum.perun.core.api.exceptions.AnonymizationNotSupportedException; import cz.metacentrum.perun.core.api.exceptions.AttributeDefinitionExistsException; import cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException; import cz.metacentrum.perun.core.api.exceptions.InternalErrorException; import cz.metacentrum.perun.core.api.exceptions.ModuleNotExistsException; import cz.metacentrum.perun.core.api.exceptions.WrongAttributeAssignmentException; import cz.metacentrum.perun.core.api.exceptions.WrongAttributeValueException; import cz.metacentrum.perun.core.api.exceptions.WrongModuleTypeException; import cz.metacentrum.perun.core.api.exceptions.WrongReferenceAttributeValueException; import cz.metacentrum.perun.core.blImpl.AttributesManagerBlImpl; import cz.metacentrum.perun.core.implApi.modules.attributes.AttributesModuleImplApi; import cz.metacentrum.perun.core.implApi.modules.attributes.UserVirtualAttributesModuleImplApi; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.ServiceLoader; import java.util.Set; /** * @author Michal Prochazka <michalp@ics.muni.cz> * @author Slavek Licehammer <glory@ics.muni.cz> */ public interface AttributesManagerImplApi { /** * Get all <b>non-empty</b> attributes associated with the facility. * * @param sess perun session * @param facility facility to get the attributes from * @return list of attributes * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getAttributes(PerunSession sess, Facility facility); /** * Get all attributes associated with the facility which have name in list attrNames (empty too). * Virtual attribute too. * * @param sess perun session * @param facility to get the attributes from * @param attrNames list of attributes' names * @return list of attributes * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getAttributes(PerunSession sess, Facility facility, List<String> attrNames); /** * Get all virtual attributes associated with the facility. * * @param sess perun session * @param facility to get the attributes from * @return list of attributes * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getVirtualAttributes(PerunSession sess, Facility facility); /** * Get all virtual attributes associated with the member. * * @param sess perun session * @param member to get the attributes from * @return list of attributes * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getVirtualAttributes(PerunSession sess, Member member); /** * Get all virtual attributes associated with the vo. * * @param sess perun session * @param vo to get the attributes from * @return list of attributes * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getVirtualAttributes(PerunSession sess, Vo vo); /** * Get all virtual attributes associated with the group. * * @param sess perun session * @param group to get the attributes from * @return list of attributes * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getVirtualAttributes(PerunSession sess, Group group); /** * Get all virtual attributes associated with the host. * * @param sess perun session * @param host to get the attributes from * @return list of attributes * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getVirtualAttributes(PerunSession sess, Host host); /** * Get all <b>non-empty</b> attributes associated with the vo. * * @param sess perun session * @param vo vo to get the attributes from * @return list of attributes * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getAttributes(PerunSession sess, Vo vo); /** * Get all <b>non-empty</b> attributes associated with the group. * * @param sess perun session * @param group group to get the attributes from * @return list of attributes * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getAttributes(PerunSession sess, Group group); /** * Get all <b>non-empty</b> attributes associated with the resource. * * @param sess perun session * @param resource resource to get the attributes from * @return list of attributes * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getAttributes(PerunSession sess, Resource resource); /** * Get all virtual attributes associated with the resource. * * @param sess perun session * @param resource to get the attributes from * @return list of attributes * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getVirtualAttributes(PerunSession sess, Resource resource); /** * Get all <b>non-empty</b> attributes associated with the member on the resource. * * @param sess perun session * @param member to get the attributes from * @param resource to get the attributes from * @return list of attributes * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getAttributes(PerunSession sess, Member member, Resource resource); /** * Get all virtual attributes associated with the member on the resource. * * @param sess perun session * @param member to get the attributes from * @param resource to get the attributes from * @return list of attributes * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getVirtualAttributes(PerunSession sess, Member member, Resource resource); /** * Get all <b>non-empty, non-virtual</b> attributes associated with the member in the group. * * @param sess perun session * @param member to get the attributes from * @param group group to get the attributes from * @return list of attributes * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getAttributes(PerunSession sess, Member member, Group group); /** * Get all attributes (empty and virtual too) associated with the member in the group which have name in list attrNames. * * @param sess perun session * @param member to get the attributes from * @param group group to get the attributes from * @param attrNames list of attributes' names * @return list of attributes * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getAttributes(PerunSession sess, Member member, Group group, List<String> attrNames); /** * Get all attributes (empty and virtual too) associated with the member on the resource which have name in list attrNames. * * @param sess perun session * @param member to get the attributes from * @param resource resource to get the attributes from * @param attrNames list of attributes' names * @return list of attributes * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getAttributes(PerunSession sess, Member member, Resource resource, List<String> attrNames); /** * Get all attributes (empty and virtual too) associated with the group on the resource which have name in list attrNames. * * @param sess perun session * @param resource to get the attributes for * @param group to get the attributes for * @param attrNames list of attributes names * @return list of selected attributes for group and resource objects * @throws InternalErrorException */ List<Attribute> getAttributes(PerunSession sess, Resource resource, Group group, List<String> attrNames); /** * Get all attributes (empty and virtual too) associated with the user on the facility which have name in list attrNames. * * @param sess perun session * @param user to get the attributes from * @param facility facility to get the attributes from * @param attrNames list of attributes' names * @return list of attributes * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getAttributes(PerunSession sess, User user, Facility facility, List<String> attrNames); /** * Get all <b>non-empty</b> attributes associated with the member. * * @param sess perun session * @param member member to get the attributes from * @return list of attributes * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getAttributes(PerunSession sess, Member member); /** * Get all <b>non-empty</b> attributes associated with the group starts with name startPartOfName. * Get only nonvirtual attributes with NotNull value. * * PRIVILEGE: Get only those attributes the principal has access to. * * @param sess perun session * @param group to get the attributes from * @param startPartOfName attribute name start with this part * @return list of attributes which name start with startPartOfName * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getAllAttributesStartWithNameWithoutNullValue(PerunSession sess, Group group, String startPartOfName); /** * Get all <b>non-empty</b> attributes associated with the resource starts with name startPartOfName. * Get only nonvirtual attributes with notNull value. * * PRIVILEGE: Get only those attributes the principal has access to. * * @param sess perun session * @param resource to get the attributes from * @param startPartOfName attribute name start with this part * @return list of attributes which name start with startPartOfName * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getAllAttributesStartWithNameWithoutNullValue(PerunSession sess, Resource resource, String startPartOfName); /** * Get all attributes associated with the vo which have name in list attrNames (empty and virtual too). * * @param sess perun session * @param vo to get the attributes from * @param attrNames list of attributes' names * @return list of attributes * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getAttributes(PerunSession sess, Vo vo, List<String> attrNames); /** * Get all attributes associated with the member which have name in list attrNames (empty and virtual too). * * @param sess perun session * @param member to get the attributes from * @param attrNames list of attributes' names * @return list of attributes * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getAttributes(PerunSession sess, Member member, List<String> attrNames); /** * Get all attributes associated with the group which have name in list attrNames (empty too). * * @param sess perun session * @param group to get the attributes from * @param attrNames list of attributes' names * @return list of attributes * * @throws InternalErrorException if an exception raises in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getAttributes(PerunSession sess, Group group, List<String> attrNames); /** * Get all attributes associated with the resource which have name in list attrNames (empty too). * * @param sess perun session * @param resource to get the attributes from * @param attrNames list of attributes' names * @return list of attributes * * @throws InternalErrorException if an exception raises in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getAttributes(PerunSession sess, Resource resource, List<String> attrNames); /** * Get all attributes associated with the UserExtSource which have name in list attrNames (empty and virtual too). * * @param sess perun session * @param ues to get the attributes from * @param attrNames list of attributes' names * @return list of attributes * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getAttributes(PerunSession sess, UserExtSource ues, List<String> attrNames); /** * Get all <b>non-empty</b> attributes associated with the user on the facility. * * @param sess perun session * @param facility * @param user * @return list of attributes * * @throws InternalErrorException */ List<Attribute> getAttributes(PerunSession sess, Facility facility, User user); /** * Get all <b>non-empty</b> attributes associated with any user on the facility. * * @param sess perun session * @param facility * @return list of attributes * @throws InternalErrorException */ List<Attribute> getUserFacilityAttributesForAnyUser(PerunSession sess, Facility facility); /** * Get all entiteless attributes with subject equaled String key * * @param sess * @param key * @return * @throws InternalErrorException */ List<Attribute> getAttributes(PerunSession sess, String key); /** * Get all entityless attributes with attributeName * @param sess perun session * @param attrName * @return attribute * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getEntitylessAttributes(PerunSession sess, String attrName); /** * Return value of entityless attribute by attr_id and key (subject). * Value is in the format from DB. * IMPORTANT: return only values in String (special format for Map or List)! * * If value is null, return null. * If attribute with subject=key not exists, create new one with null value and return null. * * @param sess * @param attrId * @param key * @return attr_value in string * * @throws InternalErrorException if runtime error exception has been thrown * @throws AttributeNotExistsException throw exception if attribute with value not exists in DB */ String getEntitylessAttrValueForUpdate(PerunSession sess, int attrId, String key) throws AttributeNotExistsException; /** * Returns list of Keys which fits the attributeDefinition. * * @param sess * @param attributeDefinition * @return * @throws InternalErrorException */ List<String> getEntitylessKeys(PerunSession sess, AttributeDefinition attributeDefinition); /** * Returns all attributes with not-null value which fits the attributeDefinition. Can't process core or virtual attributes. * * @param sess * @param attributeDefinition * @return list of attributes * @throws InternalErrorException */ List<Attribute> getAttributesByAttributeDefinition(PerunSession sess, AttributeDefinition attributeDefinition); /** * Get all virtual attributes associated with the user on the facility. * * @param sess perun session * @param facility to get the attributes from * @param user to get the attributes from * @return list of attributes * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getVirtualAttributes(PerunSession sess, Facility facility, User user); /** * Get all virtual attributes associated with the member in the group. * * @param sess perun session * @param member to get the attributes from * @param group to get the attributes from * @return list of attributes * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getVirtualAttributes(PerunSession sess, Member member, Group group); /** * Get all <b>non-empty</b> attributes associated with the user. * * @param sess perun session * @param user * @return list of attributes * * @throws InternalErrorException */ List<Attribute> getAttributes(PerunSession sess, User user); /** * Get all attributes associated with the user which have name in list attrNames (empty and virtual too). * * @param sess perun session * @param user to get the attributes from * @param attrNames list of attributes' names * @return list of attributes * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getAttributes(PerunSession sess, User user, List<String> attrNames); /** * Get all virtual attributes associated with the user. * * @param sess perun session * @param user to get the attributes from * @return list of attributes * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getVirtualAttributes(PerunSession sess, User user); /** * Get all virtual attributes associated with the UserExtSource. * * @param sess perun session * @param ues to get the attributes from * @return list of attributes * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getVirtualAttributes(PerunSession sess, UserExtSource ues); List<Attribute> getAttributes(PerunSession sess, Host host); /** * Get all attributes associated with the host which have name in list attrNames (empty and virtual too). Empty list attrNames will return no attributes. * * @param sess perun session * @param host host to get attributes for * @param attrNames list of attributes' names * @return list of attributes */ List<Attribute> getAttributes(PerunSession sess, Host host, List<String> attrNames); List<Attribute> getAttributes(PerunSession sess, Resource resource, Group group); /** * Get all <b>non-empty</b> attributes associated with the UserExtSource. * * @param sess perun session * @param ues to get the attributes from * @return list of attributes * * @throws InternalErrorException */ List<Attribute> getAttributes(PerunSession sess, UserExtSource ues); /** * Get all <b>non-empty</b> attributes associated with the user on the all facilities. * This method doesn't use cache. * * @param sess perun session * @param user * @return list of attributes * * @throws InternalErrorException */ List<RichAttribute<User, Facility>> getAllUserFacilityRichAttributes(PerunSession sess, User user); /** * Get particular attribute for the facility. * * @param attributeName attribute name defined in the particular manager * @param facility to get attribute from * @return attribute * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws AttributeNotExistsException if the attribute doesn't exists in the underlaying data source */ Attribute getAttribute(PerunSession sess, Facility facility, String attributeName) throws AttributeNotExistsException; /** * Get particular attribute for the vo. * * @param attributeName attribute name defined in the particular manager * @param vo to get attribute from * @return attribute * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws AttributeNotExistsException if the attribute doesn't exists in the underlaying data source */ Attribute getAttribute(PerunSession sess, Vo vo, String attributeName) throws AttributeNotExistsException; /** * Get particular attribute for the group. * * @param attributeName attribute name defined in the particular manager * @param group to get attribute from * @return attribute * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws AttributeNotExistsException if the attribute doesn't exists in the underlaying data source */ Attribute getAttribute(PerunSession sess, Group group, String attributeName) throws AttributeNotExistsException; /** * Get particular attribute for the resource. * * @param attributeName attribute name defined in the particular manager * @param resource to get attribute from * @return attribute * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws AttributeNotExistsException if the attribute doesn't exists in the underlaying data source */ Attribute getAttribute(PerunSession sess, Resource resource, String attributeName) throws AttributeNotExistsException; /** * Get particular attribute for the member on this resource. * * @param member to get attribute from * @param resource to get attribute from * @param attributeName attribute name defined in the particular manager * @return attribute * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws AttributeNotExistsException if the attribute doesn't exists in the underlaying data source */ Attribute getAttribute(PerunSession sess, Member member, Resource resource, String attributeName) throws AttributeNotExistsException; /** * Get particular attribute for the member in this group. * * @param sess perun session * @param member to get attribute from * @param group to get attribute from * @param attributeName attribute name defined in the particular manager * @return attribute * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws AttributeNotExistsException if the attribute doesn't exists in the underlying data source */ Attribute getAttribute(PerunSession sess, Member member, Group group, String attributeName) throws AttributeNotExistsException; /** * Get particular attribute for the member. * * @param attributeName attribute name defined in the particular manager * @param member to get attribute from * @return attribute * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws AttributeNotExistsException if the attribute doesn't exists in the underlaying data source */ Attribute getAttribute(PerunSession sess, Member member, String attributeName) throws AttributeNotExistsException; /** * Get particular attribute for the user on this facility. * * @param attributeName attribute name defined in the particular manager * @return attribute * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws AttributeNotExistsException if the attribute doesn't exists in the underlaying data source */ Attribute getAttribute(PerunSession sess, Facility facility, User user, String attributeName) throws AttributeNotExistsException; /** * Get particular attribute for the user. * * @param sess * @param user * @param attributeName attribute name defined in the particular manager * @return attribute * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws AttributeNotExistsException if the attribute doesn't exists in the underlaying data source */ Attribute getAttribute(PerunSession sess, User user, String attributeName) throws AttributeNotExistsException; Attribute getAttribute(PerunSession sess, Host host, String attributeName) throws AttributeNotExistsException; Attribute getAttribute(PerunSession sess, Resource resource, Group group, String attributeName) throws AttributeNotExistsException; /** * Get particular entityless attribute * @param sess perun session * @param key key to get attribute for * @param attributeName * @return attribute * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws AttributeNotExistsException if the attribute doesn't exists in the underlaying data source */ Attribute getAttribute(PerunSession sess, String key, String attributeName) throws AttributeNotExistsException; /** * Gets map from keys to string values for an entityless attribute. * @param sess not used * @param attributeName full attribute name * @return unordered hashmap */ Map<String,String> getEntitylessStringAttributeMapping(PerunSession sess, String attributeName) throws AttributeNotExistsException; /** * Get particular attribute for the User External Source. * * @param sess * @param ues * @param attributeName attribute name defined in the particular manager * @return attribute * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws AttributeNotExistsException if the attribute doesn't exists in the underlaying data source */ Attribute getAttribute(PerunSession sess, UserExtSource ues, String attributeName) throws AttributeNotExistsException; /** * Get attributes definition (attribute without defined value). * * @param attributeName attribute name defined in the particular manager * @return attribute * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws AttributeNotExistsException if the attribute doesn't exists in the underlaying data source */ AttributeDefinition getAttributeDefinition(PerunSession sess, String attributeName) throws AttributeNotExistsException; /** * Get attributes definition (attribute without defined value). * * @return List of attributes * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<AttributeDefinition> getAttributesDefinition(PerunSession sess); /** * Get attributes definition (attribute without defined value) with specified namespace. * * @param namespace get only attributes with this namespace * @return List of attributes * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<AttributeDefinition> getAttributesDefinitionByNamespace(PerunSession sess, String namespace); /** * Get attibute definition (attribute without defined value). * * @param id attribute id * @return attribute * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws AttributeNotExistsException if the attribute doesn't exists in the underlaying data source */ AttributeDefinition getAttributeDefinitionById(PerunSession sess, int id) throws AttributeNotExistsException; /** * Get particular attribute for the facility. * * @param id attribute id * @param facility to get attribute from * @return attribute * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws AttributeNotExistsException if the attribute doesn't exists in the underlaying data source */ Attribute getAttributeById(PerunSession sess, Facility facility, int id) throws AttributeNotExistsException; /** * Get particular attribute for the vo. * * @param id attribute id * @param vo to get attribute from * @return attribute * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws AttributeNotExistsException if the attribute doesn't exists in the underlaying data source */ Attribute getAttributeById(PerunSession sess, Vo vo, int id) throws AttributeNotExistsException; /** * Get particular attribute for the resource. * * @param id attribute id * @param resource to get attribute from * @return attribute * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws AttributeNotExistsException if the attribute doesn't exists in the underlaying data source */ Attribute getAttributeById(PerunSession sess, Resource resource, int id) throws AttributeNotExistsException; /** * Get particular attribute for the member on this resource. * * @param member to get attribute from * @param resource to get attribute from * @param id attribute id * @return attribute * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws AttributeNotExistsException if the attribute doesn't exists in the underlaying data source */ Attribute getAttributeById(PerunSession sess, Member member, Resource resource, int id) throws AttributeNotExistsException; /** * Get particular attribute for the member in this group. * * @param sess perun session * @param member to get attribute from * @param group to get attribute from * @param id attribute id * @return attribute * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws AttributeNotExistsException if the attribute doesn't exists in the underlying data source */ Attribute getAttributeById(PerunSession sess, Member member, Group group, int id) throws AttributeNotExistsException; /** * Get particular attribute for the member. * * @param sess * @param member * @param id attribute id * @return attribute * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws AttributeNotExistsException if the attribute doesn't exists in the underlaying data source */ Attribute getAttributeById(PerunSession sess, Member member, int id) throws AttributeNotExistsException; /** * Get particular attribute for the user on this facility. * * @param sess * @param facility * @param user * @param id attribute id * @return attribute * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws AttributeNotExistsException if the attribute doesn't exists in the underlaying data source */ Attribute getAttributeById(PerunSession sess, Facility facility, User user, int id) throws AttributeNotExistsException; /** * Get particular attribute for the user. * * @param sess * @param user * @param id attribute id * @return attribute * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws AttributeNotExistsException if the attribute doesn't exists in the underlaying data source */ Attribute getAttributeById(PerunSession sess, User user, int id) throws AttributeNotExistsException; Attribute getAttributeById(PerunSession sess, Host host, int id) throws AttributeNotExistsException; Attribute getAttributeById(PerunSession sess, Resource resource, Group group, int id) throws AttributeNotExistsException; Attribute getAttributeById(PerunSession sess, Group group, int id) throws AttributeNotExistsException; /** * Get particular attribute for the user external source. * * @param sess * @param ues * @param id attribute id * @return attribute * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws AttributeNotExistsException if the attribute doesn't exists in the underlaying data source */ Attribute getAttributeById(PerunSession sess, UserExtSource ues, int id) throws AttributeNotExistsException; /** * Store the particular attribute associated with the given perun bean. If an attribute is core attribute then the attribute isn't stored (It's skkiped whithout any notification). * * @param sess perun session * @param object object of setting the attribute, must be one of perunBean or string * @param attribute attribute to set * @return true if new value differs from old value (i.e. values changed) * false otherwise (value do not change) * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws WrongAttributeAssignmentException if the namespace of the attribute does not match the perunBean */ boolean setAttribute(PerunSession sess, Object object, Attribute attribute) throws WrongAttributeAssignmentException, WrongAttributeValueException; /** * Store the particular attribute associated with the bean1 and bean2. If an attribute is core attribute then the attribute isn't stored (It's skkiped whithout any notification). * * @param sess perun session * @param bean1 first perun bean * @param bean2 second perun bean * @param attribute attribute to set * * @return true if new value differs from old value (i.e. values changed) * false otherwise (value do not change) * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ boolean setAttribute(PerunSession sess, PerunBean bean1, PerunBean bean2, Attribute attribute) throws WrongAttributeAssignmentException, WrongAttributeValueException; /** * Insert attribute value in DB. * * @param sess perun session * @param attribute that will be stored in the DB * @param tableName in the database in which the attribute will be inserted * @param columnNames of the database table in which the attribute will be written * @param columnValues of the objects, for which the attribute will be written, corresponding to the columnNames * @return true if new value differs from old value (i.e. values changed) * false otherwise (value do not change) */ boolean insertAttribute(PerunSession sess, Attribute attribute, String tableName, List<String> columnNames, List<Object> columnValues); /** * Update attribute value in DB. * * @param sess perun session * @param attribute that will be stored in the DB * @param tableName in the database for updating * @param columnNames of the database table in which the attribute will be written * @param columnValues of the objects, for which the attribute will be written, corresponding to the columnNames * @return true if new value differs from old value (i.e. values changed) * false otherwise (value do not change) */ boolean updateAttribute(PerunSession sess, Attribute attribute, String tableName, List<String> columnNames, List<Object> columnValues); /** * Set entityless attribute with null value (for key and attribute). Shouldn't be called from upper layer !!! * * @param sess * @param key key for storing entityless attribute * @param attribute attribute to set * * @return true if insert is ok * * @throws InternalErrorException if runtimeException is thrown */ boolean setAttributeWithNullValue(final PerunSession sess, final String key, final Attribute attribute); /** * Store the particular virtual attribute associated with the facility. * * @param sess perun session * @param facility * @param attribute attribute to set * @return true if attribute was really changed * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws ModuleNotExistsException * @throws WrongModuleTypeException * @throws WrongReferenceAttributeValueException */ boolean setVirtualAttribute(PerunSession sess, Facility facility, Attribute attribute) throws WrongReferenceAttributeValueException; /** * Store the particular virtual attribute associated with the resource. * * @param sess perun session * @param resource * @param attribute attribute to set * @return true if attribute was really changed * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws ModuleNotExistsException * @throws WrongModuleTypeException * @throws WrongReferenceAttributeValueException */ boolean setVirtualAttribute(PerunSession sess, Resource resource, Attribute attribute) throws WrongReferenceAttributeValueException; /** * Store the particular virtual attribute associated with the group. * * @param sess perun session * @param group * @param attribute attribute to set * @return true if attribute was really changed * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws ModuleNotExistsException * @throws WrongModuleTypeException */ boolean setVirtualAttribute(PerunSession sess, Group group, Attribute attribute); /** * Store the particular virtual attribute associated with the facility and user combination. * * @param sess perun session * @param facility * @param user * @param attribute attribute to set * @return true if attribute was really changed * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws ModuleNotExistsException * @throws WrongModuleTypeException * @throws WrongReferenceAttributeValueException */ boolean setVirtualAttribute(PerunSession sess, Facility facility, User user, Attribute attribute) throws WrongReferenceAttributeValueException; /** * Store the particular virtual attribute associated with the resource and group combination. * * @param sess perun session * @param resource * @param group * @param attribute attribute to set * @return true if attribute was really changed * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws ModuleNotExistsException * @throws WrongModuleTypeException * @throws WrongReferenceAttributeValueException */ boolean setVirtualAttribute(PerunSession sess, Resource resource, Group group, Attribute attribute) throws WrongReferenceAttributeValueException; /** * Store the particular virtual attribute associated with the member and group combination. * * @param sess perun session * @param member member to set on * @param group group to set on * @param attribute attribute to set * @return true if attribute was really changed * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws ModuleNotExistsException * @throws WrongModuleTypeException */ boolean setVirtualAttribute(PerunSession sess, Member member, Group group, Attribute attribute); /** * Store the particular virtual attribute associated with the member. * * @param sess perun session * @param member * @param attribute attribute to set * @return true if attribute was really changed * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws ModuleNotExistsException * @throws WrongModuleTypeException */ boolean setVirtualAttribute(PerunSession sess, Member member, Attribute attribute); /** * Store the particular virtual attribute associated with the user. * * @param sess perun session * @param user * @param attribute attribute to set * @return true if attribute was really changed * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws ModuleNotExistsException * @throws WrongModuleTypeException */ boolean setVirtualAttribute(PerunSession sess, User user, Attribute attribute); /** * Store the particular virtual attribute associated with the user external source. * * @param sess perun session * @param ues * @param attribute attribute to set * @return true if attribute was really changed * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws ModuleNotExistsException * @throws WrongModuleTypeException */ boolean setVirtualAttribute(PerunSession sess, UserExtSource ues, Attribute attribute); /** * Creates an attribute, the attribute is stored into the appropriate DB table according to the namespace. * * @param sess * @param attribute attribute to create * * @return attribute with set id * * @throws AttributeDefinitionExistsException if attribute already exists * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ AttributeDefinition createAttribute(PerunSession sess, AttributeDefinition attribute) throws AttributeDefinitionExistsException; /** * Deletes the attribute. Definition and all values. * * @param sess * @param attribute attribute to delete * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ void deleteAttribute(PerunSession sess, AttributeDefinition attribute); /** * Delete all authz for the attribute. * * @param sess * @param attribute the attribute * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorExceptions */ void deleteAllAttributeAuthz(PerunSession sess, AttributeDefinition attribute); /** * Get attributes definions required by all services assigned on the resource. * * @param sess perun session * @param resource * @return attributes definions required by all services assigned on the resource. * * @throws InternalErrorException */ List<AttributeDefinition> getResourceRequiredAttributesDefinition(PerunSession sess, Resource resource); /** * Get facility attributes which are required by services. Services are known from the resource. * * @param sess perun session * @param resourceToGetServicesFrom resource from which the services are taken * @param facility you get attributes for this facility * @return list of facility attributes which are required by services which are assigned to resource * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getRequiredAttributes(PerunSession sess, Resource resourceToGetServicesFrom, Facility facility); /** * Get resource attributes which are required by services. * * @param sess perun session * @param resource * @param serviceIds * @return list of resource attributes which are required by services which are selceted * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getRequiredAttributes(PerunSession sess, Resource resource, List<Integer> serviceIds); /** * Get resource attributes which are required by services. Services are known from the resourceToGetServicesFrom. * * @param sess perun session * @param resourceToGetServicesFrom resource from which the services are taken * @param resource resource for which you want to get the attributes * @return list of resource attributes which are required by services which are assigned to resource. * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getRequiredAttributes(PerunSession sess, Resource resourceToGetServicesFrom, Resource resource); /** * Get member attributes which are required by services. Services are known from the resourceToGetServicesFrom. * * @param sess perun session * @param resourceToGetServicesFrom resource from which the services are taken * @param member you get attributes for this member * @return list of member attributes which are required by services which are assigned to resource. * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getRequiredAttributes(PerunSession sess, Resource resourceToGetServicesFrom, Member member); /** * Get member-resource attributes which are required by services. Services are known from the resourceToGetServicesFrom. * * @param sess perun session * @param resourceToGetServicesFrom resource from which the services are taken * @param member you get attributes for this member and the resource * @param resource you get attributes for this resource and the member * @return list of member-resource attributes which are required by services which are assigned to another resource. * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getRequiredAttributes(PerunSession sess, Resource resourceToGetServicesFrom, Member member, Resource resource); /** * Get user-facility attributes which are required by services. Services are known from the resource. * * @param sess perun session * @param resourceToGetServicesFrom resource from which the services are taken * @param facility facility from which the services are taken * @param user you get attributes for this user * @return list of member-resource attributes which are required by services which are assigned to another resource. * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getRequiredAttributes(PerunSession sess, Resource resourceToGetServicesFrom, Facility facility, User user); List<Attribute> getRequiredAttributes(PerunSession sess, Resource resourceToGetServicesFrom, Resource resource, Group group); /** * Get user attributes which are required by services. Services are known from the resource. * * @param sess perun session * @param resourceToGetServicesFrom * @param user you get attributes for this user * @return list of user attributes which are required by services which are assigned to resource. * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getRequiredAttributes(PerunSession sess, Resource resourceToGetServicesFrom, User user); List<Attribute> getRequiredAttributes(PerunSession sess, Resource resourceToGetServicesFrom, Host host); List<Attribute> getRequiredAttributes(PerunSession sess, Resource resourceToGetServicesFrom, Group group); /** * Get all attributes which are required by service. * Required attribues are requisite for Service to run. * * @param sess sess * @param service service from which the attributes will be listed * * @return All attributes which are required by service. * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<AttributeDefinition> getRequiredAttributesDefinition(PerunSession sess, Service service); /** * Get facility attributes which are required by all services which are connected to this facility. * * @param sess perun session * @param facility you get attributes for this facility * @return list of facility attributes which are required by all services which are connected to this facility. * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getRequiredAttributes(PerunSession sess, Facility facility); /** * Get facility attributes which are required by the service. * * @param sess perun session * @param facility you get attributes for this facility * @param service attribute required by this service you'll get * @return list of facility attributes which are required by the service * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getRequiredAttributes(PerunSession sess, Service service, Facility facility); /** * Get vo attributes which are required by the service. * * @param sess perun session * @param vo you get attributes for this vo * @param service attribute required by this service you'll get * @return list of vo attributes which are required by the service * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getRequiredAttributes(PerunSession sess, Service service, Vo vo); /** * Get resource attributes which are required by the service. * * @param sess perun session * @param resource resource for which you want to get the attributes * @param service attribute required by this service you'll get * @return list of resource attributes which are required by the service * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getRequiredAttributes(PerunSession sess, Service service, Resource resource); /** * Get member-resource attributes which are required by the service. * * @param sess perun session * @param service attribute required by this service you'll get * @param member you get attributes for this member and the resource * @param resource you get attributes for this resource and the member * @return list of attributes which are required by the service. * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getRequiredAttributes(PerunSession sess, Service service, Member member, Resource resource); /** * Get member-resource attributes which are required by service for each member in list of members. * * @param sess perun session * @param service attribute required by this service * @param resource you get attributes for this resource and the members * @param members you get attributes for this list of members and the resource * @return map of member and his list of attributes * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ HashMap<Member, List<Attribute>> getRequiredAttributes(PerunSession sess, Service service, Resource resource, List<Member> members); /** * Get member attributes which are required by service for each member in list of members. * * @param sess perun session * @param service attribute required by this service * @param resource resource only to get allowed members * @param members you get attributes for this list of members * @return map of member and his list of attributes * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ HashMap<Member, List<Attribute>> getRequiredAttributes(PerunSession sess, Resource resource, Service service, List<Member> members); /** * Get user-facility attributes which are required by the service for each user in list of users. * * @param sess perun session * @param service attribute required by this service * @param facility you get attributes for this facility and user * @param users you get attributes for this user and facility * @return map of userID and his list of attributes * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ HashMap<User, List<Attribute>> getRequiredAttributes(PerunSession sess, Service service, Facility facility, List<User> users); /** * Get user attributes which are required by the service for each user in list of users. * * @param sess perun session * @param service attribute required by this service * @param users you get attributes for this user and facility * @return map of userID and his list of attributes * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ HashMap<User, List<Attribute>> getRequiredAttributes(PerunSession sess, Service service, List<User> users); /** * Get member-group attributes which are required by the service. * * @param sess perun session * @param member you get attributes for this member and the group * @param group you get attributes for this group in which member is associated * @param service attribute required by this service you'll get * @return list of attributes which are required by the service. * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getRequiredAttributes(PerunSession sess, Service service, Member member, Group group); /** * Get member-group attributes which are required by the service, for the given members and the given group. * * @param sess perun session * @param members you get attributes for this member and the group * @param group you get attributes for these groups in which member is associated * @param service attribute required by this service you'll get * @return list of attributes which are required by the service. * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ Map<Member, List<Attribute>> getRequiredAttributes(PerunSession sess, Service service, List<Member> members, Group group); /** * Get member-group attributes which are required by services. Services are known from the resourceToGetServicesFrom. * * @param sess perun session * @param resourceToGetServicesFrom resource from which the services are taken * @param group you get attributes for this group and the member * @param member you get attributes for this member and the group * @return list of member-group attributes which are required by services which are assigned to another resource. * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getRequiredAttributes(PerunSession sess, Resource resourceToGetServicesFrom, Member member, Group group); /** * Get member attributes which are required by the service. * * @param sess perun session * @param service attribute required by this service you'll get * @param member * @return list of attributes which are required by the service. * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getRequiredAttributes(PerunSession sess, Service service, Member member); /** * Get user-facility attributes which are required by the service. * * @param sess perun session * @param service attribute required by this service you'll get * @param facility * @param user * @return list of attributes which are required by the service. * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getRequiredAttributes(PerunSession sess, Service service, Facility facility, User user); /** * Get user attributes which are required by the service. * * @param sess perun session * @param service attribute required by this service you'll get * @param user * @return list of attributes which are required by the service. * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ List<Attribute> getRequiredAttributes(PerunSession sess, Service service, User user); List<Attribute> getRequiredAttributes(PerunSession sess, Service service, Resource resource, Group group); /** * Get group-resource attributes which are required by the services. * * @param sess session * @param services services * @param resource resource * @param group group * @return list of attributes which are required by the service. */ List<Attribute> getRequiredAttributes(PerunSession sess, List<Service> services, Resource resource, Group group); List<Attribute> getRequiredAttributes(PerunSession sess, Service service, Host host); List<Attribute> getRequiredAttributes(PerunSession sess, Service service, Group group); /** * Get group attributes which are required by the given service for given groups. * * @param sess session * @param service service for which are taken the required attributes * @param groups groups * @return attributes mapped by their groups */ Map<Group, List<Attribute>> getRequiredAttributesForGroups(PerunSession sess, Service service, List<Group> groups); /** * Get group attributes which are required by the given services. * * @param sess session * @param services services * @param group group * @return list of group attributes which are required by the given services */ List<Attribute> getRequiredAttributes(PerunSession sess, List<Service> services, Group group); /** * This method try to fill a value of the resource attribute. Value may be copied from some facility attribute. * * @param sess perun session * @param resource resource, attribute of which you want to fill * @param attribute attribute to fill. If attributes already have set value, this value won't be owerwriten. This means the attribute value must be empty otherwise this method won't fill it. * @return attribute which MAY have filled value * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ Attribute fillAttribute(PerunSession sess, Resource resource, Attribute attribute); /** * This method try to fill value of the member-resource attribute. This value is automatically generated, but not all atrributes can be filled this way. * * @param sess perun session * @param member attribute of this member (and resource) and you want to fill * @param resource attribute of this resource (and member) and you want to fill * @param attribute attribute to fill. If attributes already have set value, this value won't be owerwriten. This means the attribute value must be empty otherwise this method won't fill it. * @return attribute which MAY have filled value * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ Attribute fillAttribute(PerunSession sess, Member member, Resource resource, Attribute attribute); /** * This method tries to fill value of the member-group attribute. This value is automatically generated, but not all attributes can be filled this way. * * @param sess perun session * @param member attribute of this member (and group) you want to fill * @param group attribute of this group you want to fill * @param attribute attribute to fill. If attributes already have set value, this value won't be overwritten. This means the attribute value must be empty otherwise this method won't fill it. * @return attribute which MAY have filled value * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ Attribute fillAttribute(PerunSession sess, Member member, Group group, Attribute attribute); /** * This method try to fill value of the user-facility attribute. This value is automatically generated, but not all atrributes can be filled this way. * * @param sess perun session * @param facility attribute of this facility (and user) and you want to fill * @param user attribute of this user (and facility) and you want to fill * @param attribute attribute to fill. If attributes already have set value, this value won't be owerwriten. This means the attribute value must be empty otherwise this method won't fill it. * @return attribute which MAY have filled value * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ Attribute fillAttribute(PerunSession sess, Facility facility, User user, Attribute attribute); /** * This method try to fill value of the user attribute. This value is automatically generated, but not all atrributes can be filled this way. * * @param sess perun session * @param user attribute of this user (and facility) and you want to fill * @param attribute attribute to fill. If attributes already have set value, this value won't be owerwriten. This means the attribute value must be empty otherwise this method won't fill it. * @return attribute which MAY have filled value * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ Attribute fillAttribute(PerunSession sess, User user, Attribute attribute); /** * This method try to fill value of the member attribute. This value is automatically generated, but not all atrributes can be filled this way. * * @param sess perun session * @param member attribute of this member (and facility) and you want to fill * @param attribute attribute to fill. If attributes already have set value, this value won't be owerwriten. This means the attribute value must be empty otherwise this method won't fill it. * @return attribute which MAY have filled value * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ Attribute fillAttribute(PerunSession sess, Member member, Attribute attribute); Attribute fillAttribute(PerunSession sess, Host host, Attribute attribute); Attribute fillAttribute(PerunSession sess, Resource resource, Group group, Attribute attribute); Attribute fillAttribute(PerunSession sess, Group group, Attribute attribute); /** * This method try to fill value of the user external source attribute. This value is automatically generated, but not all atrributes can be filled this way. * * @param sess perun session * @param ues attribute of this user external source you want to fill * @param attribute attribute to fill. If attributes already have set value, this value won't be owerwriten. This means the attribute value must be empty otherwise this method won't fill it. * @return attribute which may have filled value * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ Attribute fillAttribute(PerunSession sess, UserExtSource ues, Attribute attribute); /** * If you need to do some further work with other modules, this method do that * * @param sess perun session * @param facility * @param attribute * @throws InternalErrorException */ void changedAttributeHook(PerunSession sess, Facility facility, Attribute attribute); /** * If you need to do some further work with other modules, this method do that * * @param sess perun session * @param key * @param attribute * @throws InternalErrorException */ void changedAttributeHook(PerunSession sess, String key, Attribute attribute); /** * If you need to do some further work with other modules, this method do that * * @param sess * @param vo * @param attribute * @throws InternalErrorException */ void changedAttributeHook(PerunSession sess, Vo vo, Attribute attribute); /** * If you need to do some further work with other modules, this method do that * * @param sess * @param host * @param attribute * @throws InternalErrorException */ void changedAttributeHook(PerunSession sess, Host host, Attribute attribute); /** * If you need to do some further work with other modules, this method do that * * @param sess * @param group * @param attribute * @throws InternalErrorException * @throws WrongReferenceAttributeValueException */ void changedAttributeHook(PerunSession sess, Group group, Attribute attribute) throws WrongReferenceAttributeValueException; /** * If you need to do some further work with other modules, this method do that * * @param sess * @param user * @param attribute * @throws InternalErrorException * @throws WrongReferenceAttributeValueException */ void changedAttributeHook(PerunSession sess, User user, Attribute attribute) throws WrongReferenceAttributeValueException; /** * If you need to do some further work with other modules, this method do that * * @param sess * @param member * @param attribute * @throws InternalErrorException * @throws WrongReferenceAttributeValueException */ void changedAttributeHook(PerunSession sess, Member member, Attribute attribute) throws WrongReferenceAttributeValueException; /** * If you need to do some further work with other modules, this method do that * * @param sess * @param resource * @param group * @param attribute * @throws InternalErrorException */ void changedAttributeHook(PerunSession sess, Resource resource, Group group, Attribute attribute); /** * If you need to do some further work with other modules, this method do that * * @param sess * @param resource * @param attribute * @throws InternalErrorException * @throws WrongReferenceAttributeValueException */ void changedAttributeHook(PerunSession sess, Resource resource, Attribute attribute) throws WrongReferenceAttributeValueException; /** * If you need to do some further work with other modules, this method do that * * @param sess * @param member * @param resource * @param attribute * @throws InternalErrorException * @throws WrongReferenceAttributeValueException */ void changedAttributeHook(PerunSession sess, Member member, Resource resource, Attribute attribute) throws WrongReferenceAttributeValueException; /** * If you need to do some further work with other modules, this method do that * * @param sess * @param member * @param group * @param attribute * @throws InternalErrorException */ void changedAttributeHook(PerunSession sess, Member member, Group group, Attribute attribute); /** * If you need to do some further work with other modules, this method do that * * @param sess * @param facility * @param user * @param attribute * @throws InternalErrorException */ void changedAttributeHook(PerunSession sess, Facility facility, User user, Attribute attribute); /** * If you need to do some further work with other modules, this method do that * * @param sess * @param ues * @param attribute * @throws InternalErrorException */ void changedAttributeHook(PerunSession sess, UserExtSource ues, Attribute attribute); /** * Check if value of this facility attribute has valid semantics. * * @param sess perun session * @param facility facility for which you want to check validity of attribute * @param attribute attribute to check * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws WrongReferenceAttributeValueException if the attribute value has wrong/illegal semantics */ void checkAttributeSemantics(PerunSession sess, Facility facility, Attribute attribute) throws WrongReferenceAttributeValueException; /** * Check if value of this vo attribute has valid semantics. * * @param sess perun session * @param vo vo for which you want to check validity of attribute * @param attribute attribute to check * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws WrongReferenceAttributeValueException if the attribute value has wrong/illegal semantics */ void checkAttributeSemantics(PerunSession sess, Vo vo, Attribute attribute) throws WrongReferenceAttributeValueException; /** * Check if value of this group attribute has valid semantics. * * @param sess perun session * @param group group for which you want to check validity of attribute * @param attribute attribute to check * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws WrongReferenceAttributeValueException if the attribute value has wrong/illegal semantics */ void checkAttributeSemantics(PerunSession sess, Group group, Attribute attribute) throws WrongReferenceAttributeValueException; /** * Check if value of this resource attribute has valid semantics. * * @param sess perun session * @param resource resource for which you want to check validity of attribute * @param attribute attribute to check * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws WrongReferenceAttributeValueException if the attribute value has wrong/illegal semantics */ void checkAttributeSemantics(PerunSession sess, Resource resource, Attribute attribute) throws WrongReferenceAttributeValueException; /** * Check if value of this member-resource attribute has valid semantics. * * * @param sess perun session * @param member member for which (and for specified resource) you want to check validity of attribute * @param resource resource for which (and for specified member) you want to check validity of attribute * @param attribute attribute to check * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws WrongReferenceAttributeValueException if the attribute value has wrong/illegal semantics */ void checkAttributeSemantics(PerunSession sess, Member member, Resource resource, Attribute attribute) throws WrongReferenceAttributeValueException; /** * Check if value of this member-group attribute has valid semantics. * * @param sess perun session * @param group group for which (and for specified member) you want to check validity of attribute * @param member member for which (and for specified group) you want to check validity of attribute * @param attribute attribute to check * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ void checkAttributeSemantics(PerunSession sess, Member member, Group group, Attribute attribute); /** * Check if value of this user-facility attribute has valid semantics. * * * @param sess perun session * @param facility facility for which (and for specified user) you want to check validity of attribute * @param user user for which (and for specified facility) you want to check validity of attribute * @param attribute attribute to check * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws WrongReferenceAttributeValueException if the attribute value has wrong/illegal semantics */ void checkAttributeSemantics(PerunSession sess, Facility facility, User user, Attribute attribute) throws WrongReferenceAttributeValueException; /** * Check if value of this user attribute has valid semantics. * * * @param sess perun session * @param user user for which (and for specified facility) you want to check validity of attribute * @param attribute attribute to check * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws WrongReferenceAttributeValueException if the attribute value has wrong/illegal semantics */ void checkAttributeSemantics(PerunSession sess, User user, Attribute attribute) throws WrongReferenceAttributeValueException; /** * Check if value of this member attribute has valid semantics. * * * @param sess perun session * @param member member for which you want to check validity of attribute * @param attribute attribute to check * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws WrongReferenceAttributeValueException if the attribute value has wrong/illegal semantics */ void checkAttributeSemantics(PerunSession sess, Member member, Attribute attribute) throws WrongReferenceAttributeValueException; /** * Check if value of this host attribute has valid semantics. * * @param sess perun session * @param host host for which you want to check validity of attribute * @param attribute attribute to check * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ void checkAttributeSemantics(PerunSession sess, Host host, Attribute attribute); /** * Check if value of this group-resource attribute has valid semantics. * * @param sess perun session * @param resource resource for which (and for specified group) you want to check validity of attribute * @param group group for which (and for specified member) you want to check validity of attribute * @param attribute attribute to check * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws WrongReferenceAttributeValueException if the attribute value has wrong/illegal semantics */ void checkAttributeSemantics(PerunSession sess, Resource resource, Group group, Attribute attribute) throws WrongReferenceAttributeValueException; /** * Check if value of this entityless attribute has valid semantics. * * * @param sess perun session * @param key key for which you want to check validity of attribute * @param attribute attribute to check * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws WrongReferenceAttributeValueException if the attribute value has wrong/illegal semantics */ void checkAttributeSemantics(PerunSession sess, String key, Attribute attribute) throws WrongReferenceAttributeValueException; /** * Check if value of this user external source attribute has valid semantics. * * * @param sess perun session * @param ues user external source for which you want to check validity of attribute * @param attribute attribute to check * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ void checkAttributeSemantics(PerunSession sess, UserExtSource ues, Attribute attribute); /** * Check if value of this facility attribute has valid syntax. * * @param sess perun session * @param facility facility for which you want to check validity of attribute * @param attribute attribute to check * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws WrongAttributeValueException if the attribute value has wrong/illegal syntax */ void checkAttributeSyntax(PerunSession sess, Facility facility, Attribute attribute) throws WrongAttributeValueException; /** * Check if value of this vo attribute has valid syntax. * * @param sess perun session * @param vo vo for which you want to check validity of attribute * @param attribute attribute to check * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws WrongAttributeValueException if the attribute value has wrong/illegal syntax */ void checkAttributeSyntax(PerunSession sess, Vo vo, Attribute attribute) throws WrongAttributeValueException; /** * Check if value of this group attribute has valid syntax. * * @param sess perun session * @param group group for which you want to check validity of attribute * @param attribute attribute to check * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws WrongAttributeValueException if the attribute value has wrong/illegal syntax */ void checkAttributeSyntax(PerunSession sess, Group group, Attribute attribute) throws WrongAttributeValueException; /** * Check if value of this resource attribute has valid syntax. * * @param sess perun session * @param resource resource for which you want to check validity of attribute * @param attribute attribute to check * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws WrongAttributeValueException if the attribute value has wrong/illegal syntax */ void checkAttributeSyntax(PerunSession sess, Resource resource, Attribute attribute) throws WrongAttributeValueException; /** * Check if value of this member-resource attribute has valid syntax. * * @param sess perun session * @param member member for which (and for specified resource) you want to check validity of attribute * @param resource resource for which (and for specified member) you want to check validity of attribute * @param attribute attribute to check * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws WrongAttributeValueException if the attribute value has wrong/illegal syntax */ void checkAttributeSyntax(PerunSession sess, Member member, Resource resource, Attribute attribute) throws WrongAttributeValueException; /** * Check if value of this member-group attribute has valid syntax. * * @param sess perun session * @param group group for which (and for specified member) you want to check validity of attribute * @param member member for which (and for specified group) you want to check validity of attribute * @param attribute attribute to check * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws WrongAttributeValueException if the attribute value has wrong/illegal syntax */ void checkAttributeSyntax(PerunSession sess, Member member, Group group, Attribute attribute) throws WrongAttributeValueException; /** * Check if value of this user-facility attribute has valid syntax. * * @param sess perun session * @param facility facility for which (and for specified user) you want to check validity of attribute * @param user user for which (and for specified facility) you want to check validity of attribute * @param attribute attribute to check * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws WrongAttributeValueException if the attribute value has wrong/illegal syntax */ void checkAttributeSyntax(PerunSession sess, Facility facility, User user, Attribute attribute) throws WrongAttributeValueException; /** * Check if value of this user attribute has valid syntax. * * @param sess perun session * @param user user for which (and for specified facility) you want to check validity of attribute * @param attribute attribute to check * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws WrongAttributeValueException if the attribute value has wrong/illegal syntax */ void checkAttributeSyntax(PerunSession sess, User user, Attribute attribute) throws WrongAttributeValueException; /** * Check if value of this member attribute has valid syntax. * * @param sess perun session * @param member member for which you want to check validity of attribute * @param attribute attribute to check * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws WrongAttributeValueException if the attribute value has wrong/illegal syntax */ void checkAttributeSyntax(PerunSession sess, Member member, Attribute attribute) throws WrongAttributeValueException; /** * Check if value of this host attribute has valid syntax. * * @param sess perun session * @param host host for which you want to check validity of attribute * @param attribute attribute to check * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws WrongAttributeValueException if the attribute value has wrong/illegal syntax */ void checkAttributeSyntax(PerunSession sess, Host host, Attribute attribute) throws WrongAttributeValueException; /** * Check if value of this group-resource attribute has valid syntax. * * @param sess perun session * @param group group for which (and for specified resource) you want to check validity of attribute * @param resource resource for which (and for specified group) you want to check validity of attribute * @param attribute attribute to check * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws WrongAttributeValueException if the attribute value has wrong/illegal syntax */ void checkAttributeSyntax(PerunSession sess, Resource resource, Group group, Attribute attribute) throws WrongAttributeValueException; /** * Check if value of this entityless attribute has valid syntax. * * @param sess perun session * @param key key for which you want to check validity of attribute * @param attribute attribute to check * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws WrongAttributeValueException if the attribute value has wrong/illegal syntax */ void checkAttributeSyntax(PerunSession sess, String key, Attribute attribute) throws WrongAttributeValueException; /** * Check if value of this user external source attribute has valid syntax. * * * @param sess perun session * @param ues user external source for which you want to check validity of attribute * @param attribute attribute to check * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws WrongAttributeValueException if the attribute value has wrong/illegal syntax */ void checkAttributeSyntax(PerunSession sess, UserExtSource ues, Attribute attribute) throws WrongAttributeValueException; /** * Gets anonymized value of the attribute. * * @param sess perun session * @param user user * @param attribute attribute to get anonymized value from * @return attribute with anonymized value * * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException * @throws AnonymizationNotSupportedException if the module doesn't exist or it doesn't implement this method */ Attribute getAnonymizedValue(PerunSession sess, User user, Attribute attribute) throws AnonymizationNotSupportedException; /** * Unset particular attribute for the facility. * * @param sess perun session * @param facility remove attribute from this facility * @param attribute attribute to remove * @return {@code true} if attribute was changed (deleted) or {@code false} if attribute was not present in a first place * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ boolean removeAttribute(PerunSession sess, Facility facility, AttributeDefinition attribute); /** * Unset particular entityless attribute with subject equals key. * * @param sess perun session * @param key subject of entityless attribute * @param attribute attribute to remove * @return {@code true} if attribute was changed (deleted) or {@code false} if attribute was not present in a first place * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ boolean removeAttribute(PerunSession sess, String key, AttributeDefinition attribute); /** * Unset all attributes for the facility. * * @param sess perun session * @param facility remove attributes from this facility * @return {@code true} if attributes was deleted or {@code false} if attributes was not deleted * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ boolean removeAllAttributes(PerunSession sess, Facility facility); /** * Remove all non-virtual group-resource attribute on selected resource * * @param sess * @param resource * @throws InternalErrorException */ void removeAllGroupResourceAttributes(PerunSession sess, Resource resource); /** * Remove all non-virtual member-resource attributes assigned to resource * * @param sess * @param resource * @throws InternalErrorException */ void removeAllMemberResourceAttributes(PerunSession sess, Resource resource); /** * Unset particular attribute for the vo. * * @param sess perun session * @param vo remove attribute from this vo * @param attribute attribute to remove * @return {@code true} if attribute was changed (deleted) or {@code false} if attribute was not present in a first place * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ boolean removeAttribute(PerunSession sess, Vo vo, AttributeDefinition attribute); /** * Unset all attributes for the vo. * * @param sess perun session * @param vo remove attributes from this vo * @return {@code true} if attributes was deleted or {@code false} if attributes was not deleted * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ boolean removeAllAttributes(PerunSession sess, Vo vo); /** * Unset particular attribute for the group. * * @param sess perun session * @param group remove attribute from this group * @param attribute attribute to remove * @return {@code true} if attribute was changed (deleted) or {@code false} if attribute was not present in a first place * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ boolean removeAttribute(PerunSession sess, Group group, AttributeDefinition attribute); /** * Unset all attributes for the group. * * @param sess perun session * @param group remove attributes from this group * @return {@code true} if attributes was deleted or {@code false} if attributes was not deleted * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ boolean removeAllAttributes(PerunSession sess, Group group); /** * Unset particular attribute for the resource. * * @param sess perun session * @param resource remove attribute from this resource * @param attribute attribute to remove * @return {@code true} if attribute was changed (deleted) or {@code false} if attribute was not present in a first place * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ boolean removeAttribute(PerunSession sess, Resource resource, AttributeDefinition attribute); /** * Unset all attributes for the resource. * * @param sess perun session * @param resource remove attributes from this resource * @return {@code true} if attributes was deleted or {@code false} if attributes was not deleted * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ boolean removeAllAttributes(PerunSession sess, Resource resource); /** * Unset particular member-resorce attribute for the member on the resource. * * @param sess perun session * @param member remove attribute from this member * @param resource remove attributes for this resource * @param attribute attribute to remove * @return {@code true} if attribute was changed (deleted) or {@code false} if attribute was not present in a first place * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ boolean removeAttribute(PerunSession sess, Member member, Resource resource, AttributeDefinition attribute); /** * Unset all (member-resource) attributes for the member on the resource. * * @param sess perun session * @param member remove attributes from this member * @param resource remove attributes from this resource * @return {@code true} if attributes was deleted or {@code false} if attributes was not deleted * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ boolean removeAllAttributes(PerunSession sess, Member member, Resource resource); /** * Unset particular attribute for the member in the group. Core attributes can't be removed this way. * * @param sess perun session * @param group remove attributes for this group * @param member remove attribute from this member * @param attribute attribute to remove * @return {@code true} if attribute was changed (deleted) or {@code false} if attribute was not present in a first place * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ boolean removeAttribute(PerunSession sess, Member member, Group group, AttributeDefinition attribute); /** * Unset all attributes for the member in the group. * * @param sess perun session * @param group remove attributes for this group * @param member remove attributes from this member * @return {@code true} if attributes was deleted or {@code false} if attributes was not deleted * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ boolean removeAllAttributes(PerunSession sess, Member member, Group group); /** * Unset particular member attribute * * @param sess perun session * @param member * @param attribute attribute to remove * @return {@code true} if attribute was changed (deleted) or {@code false} if attribute was not present in a first place * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ boolean removeAttribute(PerunSession sess, Member member, AttributeDefinition attribute); /** * Unset all member attributes for the member. * * @param sess perun session * @param member * @return {@code true} if attributes was deleted or {@code false} if attributes was not deleted * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ boolean removeAllAttributes(PerunSession sess, Member member); /** * Unset particular user-facility attribute * * @param sess perun session * @param facility * @param user * @param attribute attribute to remove * @return {@code true} if attribute was changed (deleted) or {@code false} if attribute was not present in a first place * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ boolean removeAttribute(PerunSession sess, Facility facility, User user, AttributeDefinition attribute); /** * Unset all (user-facility) <b>non-virtual</b> attributes for the user on the facility. * * @param sess perun session * @param facility * @param user * @return {@code true} if attributes was deleted or {@code false} if attributes was not deleted * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ boolean removeAllAttributes(PerunSession sess, Facility facility, User user); /** * Unset all (user-facility) <b>non-virtual</b> attributes for any user on the facility. * * @param sess perun session * @param facility * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ boolean removeAllUserFacilityAttributesForAnyUser(PerunSession sess, Facility facility); /** * Unset all (user-facility) <b>non-virtual</b> attributes for the user and <b>all facilities</b> * * @param sess perun session * @param user * @return {@code true} if attributes was deleted or {@code false} if attributes was not deleted * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ boolean removeAllUserFacilityAttributes(PerunSession sess, User user); /** * Unset particular user-facility virtual attribute value. * * @param sess perun session * @param facility * @param user * @param attribute attribute to remove * @return {@code true} if attribute was changed (deleted) or {@code false} if attribute was not present in a first place * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ boolean removeVirtualAttribute(PerunSession sess, Facility facility, User user, AttributeDefinition attribute); /** * Unset particular resource virtual attribute value. * * @param sess * @param resource * @param attribute * @return {@code true} if attribute was changed (deleted) or {@code false} if attribute was not present in a first place * @throws InternalErrorException * @throws WrongAttributeValueException * @throws WrongReferenceAttributeValueException */ boolean removeVirtualAttribute(PerunSession sess, Resource resource, AttributeDefinition attribute) throws WrongAttributeValueException, WrongReferenceAttributeValueException; /** * Unset particular group-resource virtual attribute value. * * @param sess * @param resource * @param group * @param attribute * @return {@code true} if attribute was changed (deleted) or {@code false} if attribute was not present in a first place * @throws InternalErrorException */ boolean removeVirtualAttribute(PerunSession sess, Resource resource, Group group, AttributeDefinition attribute); /** * Unset particular user attribute * * @param sess perun session * @param user * @param attribute attribute to remove * @return {@code true} if attribute was changed (deleted) or {@code false} if attribute was not present in a first place * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ boolean removeAttribute(PerunSession sess, User user, AttributeDefinition attribute); /** * Unset all user attributes for the user. * * @param sess perun session * @param user * @return {@code true} if attributes was deleted or {@code false} if attributes was not deleted * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ boolean removeAllAttributes(PerunSession sess, User user); /** * Unset particular host attribute * * @param sess perun session * @param host * @param attribute attribute to remove * @return {@code true} if attribute was changed (deleted) or {@code false} if attribute was not present in a first place * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ boolean removeAttribute(PerunSession sess, Host host, AttributeDefinition attribute); /** * Unset all user attributes for the host. * * @param sess perun session * @param host * @return {@code true} if attributes was deleted or {@code false} if attributes was not deleted * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ boolean removeAllAttributes(PerunSession sess, Host host); /** * Unset particular group_resource attribute * * @param sess perun session * @param resource resource * @param group group * @param attribute attribute to remove * @return {@code true} if attribute was changed (deleted) or {@code false} if attribute was not present in a first place * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ boolean removeAttribute(PerunSession sess, Resource resource, Group group, AttributeDefinition attribute); /** * Unset all group_resource attributes * * @param sess perun session * @param resource Resource * @param group Group * @return {@code true} if attributes was deleted or {@code false} if attributes was not deleted * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ boolean removeAllAttributes(PerunSession sess, Resource resource, Group group); /** * Unset particular user external source attribute * * @param sess perun session * @param ues * @param attribute attribute to remove * @return {@code true} if attribute was changed (deleted) or {@code false} if attribute was not present in a first place * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ boolean removeAttribute(PerunSession sess, UserExtSource ues, AttributeDefinition attribute); /** * Unset all UserExtSource attributes for the user external source. * * @param sess perun session * @param ues * @return {@code true} if attributes was deleted or {@code false} if attributes was not deleted * @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException */ boolean removeAllAttributes(PerunSession sess, UserExtSource ues); /** * Check if attribute exists in underlaying data source. * * @param sess perun session * @param attribute attribute to check * @return true if attribute exists in underlaying data source, false othewise * * @throws InternalErrorException if unexpected error occured */ boolean attributeExists(PerunSession sess, AttributeDefinition attribute); /** * Check if attribute exists in underlaying data source. * * @param sess perun session * @param attribute attribute to check * @throws InternalErrorException if unexpected error occured * @throws AttributeNotExistsException if attribute doesn';t exists */ void checkAttributeExists(PerunSession sess, AttributeDefinition attribute) throws AttributeNotExistsException; /** * Check if actionType exists in underlaying data source. * * @param sess perun session * @param actionType actionType to check * @throws InternalErrorException if unexpected error occured * @throws ActionTypeNotExistsException if attriobute doesn't exists */ void checkActionTypeExists(PerunSession sess, ActionType actionType) throws ActionTypeNotExistsException; /* * @see cz.metacentrum.perun.core.implApi.AttributesManagerImplApi#checkAttributeExists(PerunSession, AttributeDefinition) * @param expectedNamespace expected namespace * @throws WrongAttributeAssignmentException if attribute's namespace is to equal to expected namespace void checkAttributeExists(PerunSession sess, AttributeDefinition attribute, String expectedNamespace) throws InternalErrorException, AttributeNotExistsException, WrongAttributeAssignmentException; */ /** * Batch version of checkAttributeExists */ void checkAttributesExists(PerunSession sess, List<? extends AttributeDefinition> attributes) throws AttributeNotExistsException; /* * @see cz.metacentrum.perun.core.implApi.AttributesManagerImplApi#checkAttributesExists(PerunSession, List) * @param expectedNamespace expected namespace * @throws WrongAttributeAssignmentException if any attribute's namespace is to equal to expected namespace void checkAttributesExists(PerunSession sess, List<? extends AttributeDefinition> attributes, String expectedNamespace) throws InternalErrorException, AttributeNotExistsException, WrongAttributeAssignmentException; */ /** * Determine if attribute is core attribute. * * @param sess * @param attribute * @return true if attribute is core attribute */ boolean isCoreAttribute(PerunSession sess, AttributeDefinition attribute); /** * Determine if attribute is defined (def) attribute. * * @param sess * @param attribute * @return true if attribute is defined attribute * false otherwise */ boolean isDefAttribute(PerunSession sess, AttributeDefinition attribute); /** * Determine if attribute is optional (opt) attribute. * * @param sess * @param attribute * @return true if attribute is optional attribute * false otherwise */ boolean isOptAttribute(PerunSession sess, AttributeDefinition attribute); /** * Determine if attribute is core-managed attribute. * * @param sess * @param attribute * @return true if attribute is core-managed */ boolean isCoreManagedAttribute(PerunSession sess, AttributeDefinition attribute); /** * Determine if attribute is virtual attribute. * * @param sess * @param attribute * @return true if attribute is virtual */ boolean isVirtAttribute(PerunSession sess, AttributeDefinition attribute); /** * Determine if attribute is from specified namespace. * * @param attribute * @param namespace * @return true if the attribute is from specified namespace false otherwise */ boolean isFromNamespace(AttributeDefinition attribute, String namespace); /** * Determine if attribute is from specified namespace. * * @param sess * @param attribute * @param namespace * * @throws WrongAttributeAssignmentException if the attribute isn't from specified namespace */ void checkNamespace(PerunSession sess, AttributeDefinition attribute, String namespace) throws WrongAttributeAssignmentException; /** * Determine if attributes are from specified namespace. * * @param sess * @param attributes * @param namespace * * @throws WrongAttributeAssignmentException if any of the attribute isn't from specified namespace */ void checkNamespace(PerunSession sess, List<? extends AttributeDefinition> attributes, String namespace) throws WrongAttributeAssignmentException; /** * Get all values for specified resource attribute. Atibute can't be core or virt. * * @param sess * @param attributeDefinition attribute definition, namespace resource * @return * * @throws InternalErrorException */ List<Object> getAllResourceValues(PerunSession sess, AttributeDefinition attributeDefinition); /** * Get all values for specified group-resource attribute. Atibute can't be core or virt. * * @param sess * @param attributeDefinition attribute definition, namespace group-resource * @return * * @throws InternalErrorException */ List<Object> getAllGroupResourceValues(PerunSession sess, AttributeDefinition attributeDefinition); /** * Get all values for specified group attribute. Atibute can't be core or virt. * * @param sess * @param attributeDefinition attribute definition, namespace group * @return * * @throws InternalErrorException */ List<Object> getAllGroupValues(PerunSession sess, AttributeDefinition attributeDefinition); /** * Get all values for specified user attribute. Atibute can't be core or virt. * * @param sess * @param attributeDefinition attribute definition, namespace user * @return * * @throws InternalErrorException */ List<Object> getAllUserValues(PerunSession sess, AttributeDefinition attributeDefinition); /** * Check if this attribute is currently required on this facility. Attribute can be from any namespace. * * @param sess * @param facility * @param attributeDefinition * @return * * @throws InternalErrorException */ boolean isAttributeRequiredByFacility(PerunSession sess, Facility facility, AttributeDefinition attributeDefinition); /** * Check if this attribute is currently required on this vo. Attribute can be from any namespace. * * @param sess * @param vo * @param attributeDefinition * @return * * @throws InternalErrorException */ boolean isAttributeRequiredByVo(PerunSession sess, Vo vo, AttributeDefinition attributeDefinition); /** * Check if this attribute is currently required on this group. Attribute can be from any namespace. * * @param sess * @param group * @param attributeDefinition * @return * * @throws InternalErrorException */ boolean isAttributeRequiredByGroup(PerunSession sess, Group group, AttributeDefinition attributeDefinition); /** * Check if this attribute is currently required on this resource. Attribute can be from any namespace. * * @param sess * @param resource * @param attributeDefinition * @return * * @throws InternalErrorException */ boolean isAttributeRequiredByResource(PerunSession sess, Resource resource, AttributeDefinition attributeDefinition); /** * This method get all similar attr_names which start with partOfAttributeName * * @param sess * @param startingPartOfAttributeName is something like: urn:perun:user_facility:attribute-def:def:login-namespace: * @return list of similar attribute names like: urn:perun:user_facility:attribute-def:def:login-namespace:cesnet etc. * @throws InternalErrorException * @throws AttributeNotExistsException */ List<String> getAllSimilarAttributeNames(PerunSession sess, String startingPartOfAttributeName); /** * Get the attributeModule for the attribute * * @param attribute get the attribute module for this attribute * @see cz.metacentrum.perun.core.impl.AttributesManagerImpl#getAttributesModule(PerunSession,String) */ Object getAttributesModule(PerunSession sess, AttributeDefinition attribute); /** * Get uninitiated attributeModule for the attribute * * @param attribute get the attribute module for this attribute * @see cz.metacentrum.perun.core.impl.AttributesManagerImpl#getUninitializedAttributesModule(PerunSession, AttributeDefinition) */ AttributesModuleImplApi getUninitializedAttributesModule(PerunSession sess, AttributeDefinition attribute); /** * Updates AttributeDefinition. * * @param perunSession * @param attributeDefinition * @return returns updated attributeDefinition * @throws InternalErrorException */ AttributeDefinition updateAttributeDefinition(PerunSession perunSession, AttributeDefinition attributeDefinition); /** * Gets attribute rights of an attribute with id given as a parameter. * If the attribute has no rights for a role, it returns empty list. That means the returned list has always 4 items * for each of the roles VOADMIN, FACILITYADMIN, GROUPADMIN, SELF. * Info: not return rights for role VoObserver (could be same like read rights for VoAdmin) * * @param sess perun session * @param attributeId id of the attribute * @return all rights of the attribute * @throws InternalErrorException */ List<AttributeRights> getAttributeRights(PerunSession sess, int attributeId); /** * Sets attribute right given as a parameter. * The method sets the rights for attribute and role exactly as it is given in the list of action types. That means it can * remove a right, if the right is missing in the list. * Info: If there is role VoAdmin in the list, use it for setting also VoObserver rights (only for read) automatic * * @param sess perun session * @param right attribute right * @throws InternalErrorException */ void setAttributeRight(PerunSession sess, AttributeRights right); /** * Get user virtual attribute module by the attribute. * * @param sess * @param attribute attribute for which you get the module * @return instance of user attribute module * * @throws InternalErrorException * @throws WrongModuleTypeException * @throws ModuleNotExistsException */ UserVirtualAttributesModuleImplApi getUserVirtualAttributeModule(PerunSession sess, AttributeDefinition attribute); /** * Init attribute modules map in Impl layer. And register them in Auditer for message listening. * * @see AttributesManagerBlImpl#initialize() * @param modules List of attribute module class instances */ void initAndRegisterAttributeModules(PerunSession session, ServiceLoader<AttributesModuleImplApi> modules, Set<AttributeDefinition> allAttributesDef); /** * Add attribute module to attribute module map in Impl layer (if it is not there yet). * * @see AttributesManagerBlImpl#createAttribute(PerunSession, AttributeDefinition) * @param module module to add */ void initAttributeModule(AttributesModuleImplApi module); /** * Remove attribute module from attribute module map in Impl layer. * * @see AttributesManagerBlImpl#deleteAttribute(PerunSession, AttributeDefinition) * @param module module to remove */ void removeAttributeModule(AttributesModuleImplApi module); /** * Register attribute module in Auditer for message listening (if it is not there yet). * * @see AttributesManagerBlImpl#createAttribute(PerunSession, AttributeDefinition) * @param module module to register */ void registerAttributeModule(AttributesModuleImplApi module); /** * Unregister attribute module in Auditer from message listening (if it is not there yet). * * @see AttributesManagerBlImpl#deleteAttribute(PerunSession, AttributeDefinition) * @param module module to unregister */ void unregisterAttributeModule(AttributesModuleImplApi module); /** * Finds ids of PerunBeans that have the attribute's value for the attribute. * * See {@link cz.metacentrum.perun.core.bl.AttributesManagerBl#getPerunBeanIdsForUniqueAttributeValue(PerunSession, Attribute)} for details. */ Set<Pair<Integer,Integer>> getPerunBeanIdsForUniqueAttributeValue(PerunSession sess, Attribute attribute); /** * Copies all values of the attribute to table _attr_u_values which has unique constraint. */ void convertAttributeValuesToUnique(PerunSession session, AttributeDefinition attrDef); /** * Deletes all values of the attribute from table _attr_u_values which has unique constraint. And returns how many rows were deleted. */ int convertAttributeValuesToNonunique(PerunSession session, AttributeDefinition attrDef); }
bsd-2-clause
wjchen84/lfd
examples/rope_register_transfer.py
3616
#!/usr/bin/env python from __future__ import division import numpy as np from lfd.environment.simulation import DynamicSimulationRobotWorld from lfd.environment.simulation_object import XmlSimulationObject, BoxSimulationObject from lfd.environment import environment from lfd.environment import sim_util from lfd.demonstration.demonstration import Demonstration from lfd.registration.registration import TpsRpmRegistrationFactory from lfd.registration.plotting_openrave import registration_plot_cb from lfd.transfer.transfer import FingerTrajectoryTransferer from lfd.transfer.registration_transfer import TwoStepRegistrationAndTrajectoryTransferer from move_rope import create_augmented_traj, create_rope def create_rope_demo(env, rope_poss): rope_sim_obj = create_rope(rope_poss) env.sim.add_objects([rope_sim_obj]) env.sim.settle() scene_state = env.observe_scene() env.sim.remove_objects([rope_sim_obj]) pick_pos = rope_poss[0] + .1 * (rope_poss[1] - rope_poss[0]) drop_pos = rope_poss[3] + .1 * (rope_poss[2] - rope_poss[3]) + np.r_[0, .2, 0] pick_R = np.array([[0, 0, 1], [0, 1, 0], [-1, 0, 0]]) drop_R = np.array([[0, 1, 0], [0, 0, -1], [-1, 0, 0]]) move_height = .2 aug_traj = create_augmented_traj(env.sim.robot, pick_pos, drop_pos, pick_R, drop_R, move_height) demo = Demonstration("rope_demo", scene_state, aug_traj) return demo def main(): # define simulation objects table_height = 0.77 sim_objs = [] sim_objs.append(XmlSimulationObject("robots/pr2-beta-static.zae", dynamic=False)) sim_objs.append(BoxSimulationObject("table", [1, 0, table_height-.1], [.85, .85, .1], dynamic=False)) # initialize simulation world and environment sim = DynamicSimulationRobotWorld() sim.add_objects(sim_objs) sim.create_viewer() sim.robot.SetDOFValues([0.25], [sim.robot.GetJoint('torso_lift_joint').GetJointIndex()]) sim.robot.SetDOFValues([1.25], [sim.robot.GetJoint('head_tilt_joint').GetJointIndex()]) # move head down so it can see the rope sim_util.reset_arms_to_side(sim) env = environment.LfdEnvironment(sim, sim, downsample_size=0.025) demo_rope_poss = np.array([[.2, -.2, table_height+0.006], [.8, -.2, table_height+0.006], [.8, .2, table_height+0.006], [.2, .2, table_height+0.006]]) demo = create_rope_demo(env, demo_rope_poss) test_rope_poss = np.array([[.2, -.2, table_height+0.006], [.5, -.4, table_height+0.006], [.8, .0, table_height+0.006], [.8, .2, table_height+0.006], [.6, .0, table_height+0.006], [.4, .2, table_height+0.006], [.2, .2, table_height+0.006]]) test_rope_sim_obj = create_rope(test_rope_poss) sim.add_objects([test_rope_sim_obj]) sim.settle() test_scene_state = env.observe_scene() reg_factory = TpsRpmRegistrationFactory() traj_transferer = FingerTrajectoryTransferer(sim) plot_cb = lambda i, i_em, x_nd, y_md, xtarg_nd, wt_n, f, corr_nm, rad: registration_plot_cb(sim, x_nd, y_md, f) reg_and_traj_transferer = TwoStepRegistrationAndTrajectoryTransferer(reg_factory, traj_transferer) test_aug_traj = reg_and_traj_transferer.transfer(demo, test_scene_state, callback=plot_cb, plotting=True) env.execute_augmented_trajectory(test_aug_traj) if __name__ == '__main__': main()
bsd-2-clause
MircoT/homebrew-cask
Casks/deepstream.rb
605
cask 'deepstream' do version '3.1.3' sha256 'c690d1374028bb7fbb3d000bac64176e0cc93a50b15909d186e77ab0a154f055' # github.com/deepstreamIO/deepstream.io was verified as official when first introduced to the cask url "https://github.com/deepstreamIO/deepstream.io/releases/download/v#{version}/deepstream.io-mac-#{version}.pkg" appcast 'https://github.com/deepstreamIO/deepstream.io/releases.atom' name 'deepstream' homepage 'https://deepstreamhub.com/open-source/' pkg "deepstream.io-mac-#{version}.pkg" uninstall pkgutil: 'deepstream.io' caveats do files_in_usr_local end end
bsd-2-clause
gdi2290/sample-Angular2
tns_modules/angular2/test/render/dom/compiler/compiler_common_tests.js
8158
var __extends = this.__extends || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; var __decorate = this.__decorate || function (decorators, target, key, value) { var kind = typeof (arguments.length == 2 ? value = target : value); for (var i = decorators.length - 1; i >= 0; --i) { var decorator = decorators[i]; switch (kind) { case "function": value = decorator(value) || value; break; case "number": decorator(target, key, value); break; case "undefined": decorator(target, key); break; case "object": value = decorator(target, key, value) || value; break; } } return value; }; var test_lib_1 = require('angular2/test_lib'); var dom_adapter_1 = require('angular2/src/dom/dom_adapter'); var collection_1 = require('angular2/src/facade/collection'); var lang_1 = require('angular2/src/facade/lang'); var async_1 = require('angular2/src/facade/async'); var compiler_1 = require('angular2/src/render/dom/compiler/compiler'); var api_1 = require('angular2/src/render/api'); var compile_element_1 = require('angular2/src/render/dom/compiler/compile_element'); var compile_step_1 = require('angular2/src/render/dom/compiler/compile_step'); var compile_step_factory_1 = require('angular2/src/render/dom/compiler/compile_step_factory'); var compile_control_1 = require('angular2/src/render/dom/compiler/compile_control'); var template_loader_1 = require('angular2/src/render/dom/compiler/template_loader'); var url_resolver_1 = require('angular2/src/services/url_resolver'); function runCompilerCommonTests() { test_lib_1.describe('compiler', function () { var mockStepFactory; function createCompiler(processClosure, urlData) { if (urlData === void 0) { urlData = null; } if (lang_1.isBlank(urlData)) { urlData = collection_1.MapWrapper.create(); } var tplLoader = new FakeTemplateLoader(urlData); mockStepFactory = new MockStepFactory([new MockStep(processClosure)]); return new compiler_1.Compiler(mockStepFactory, tplLoader); } test_lib_1.it('should run the steps and build the ProtoView of the root element', test_lib_1.inject([test_lib_1.AsyncTestCompleter], function (async) { var compiler = createCompiler(function (parent, current, control) { current.inheritedProtoView.bindVariable('b', 'a'); }); compiler.compile(new api_1.Template({ componentId: 'someComponent', inline: '<div></div>' })).then(function (protoView) { test_lib_1.expect(protoView.variableBindings).toEqual(collection_1.MapWrapper.createFromStringMap({ 'a': 'b' })); async.done(); }); })); test_lib_1.it('should use the inline template and compile in sync', test_lib_1.inject([test_lib_1.AsyncTestCompleter], function (async) { var compiler = createCompiler(EMPTY_STEP); compiler.compile(new api_1.Template({ componentId: 'someId', inline: 'inline component' })).then(function (protoView) { test_lib_1.expect(dom_adapter_1.DOM.getInnerHTML(protoView.render.delegate.element)).toEqual('inline component'); async.done(); }); })); test_lib_1.it('should load url templates', test_lib_1.inject([test_lib_1.AsyncTestCompleter], function (async) { var urlData = collection_1.MapWrapper.createFromStringMap({ 'someUrl': 'url component' }); var compiler = createCompiler(EMPTY_STEP, urlData); compiler.compile(new api_1.Template({ componentId: 'someId', absUrl: 'someUrl' })).then(function (protoView) { test_lib_1.expect(dom_adapter_1.DOM.getInnerHTML(protoView.render.delegate.element)).toEqual('url component'); async.done(); }); })); test_lib_1.it('should report loading errors', test_lib_1.inject([test_lib_1.AsyncTestCompleter], function (async) { var compiler = createCompiler(EMPTY_STEP, collection_1.MapWrapper.create()); async_1.PromiseWrapper.catchError(compiler.compile(new api_1.Template({ componentId: 'someId', absUrl: 'someUrl' })), function (e) { test_lib_1.expect(e.message).toContain("Failed to load the template \"someId\""); async.done(); }); })); test_lib_1.it('should wait for async subtasks to be resolved', test_lib_1.inject([test_lib_1.AsyncTestCompleter], function (async) { var subTasksCompleted = false; var completer = async_1.PromiseWrapper.completer(); var compiler = createCompiler(function (parent, current, control) { collection_1.ListWrapper.push(mockStepFactory.subTaskPromises, completer.promise.then(function (_) { subTasksCompleted = true; })); }); var pvPromise = compiler.compile(new api_1.Template({ componentId: 'someId', inline: 'some component' })); test_lib_1.expect(pvPromise).toBePromise(); test_lib_1.expect(subTasksCompleted).toEqual(false); completer.resolve(null); pvPromise.then(function (protoView) { test_lib_1.expect(subTasksCompleted).toEqual(true); async.done(); }); })); }); } exports.runCompilerCommonTests = runCompilerCommonTests; var MockStepFactory = (function (_super) { __extends(MockStepFactory, _super); function MockStepFactory(steps) { _super.call(this); this.steps = steps; } MockStepFactory.prototype.createSteps = function (template, subTaskPromises) { this.subTaskPromises = subTaskPromises; collection_1.ListWrapper.forEach(this.subTaskPromises, function (p) { return collection_1.ListWrapper.push(subTaskPromises, p); }); return this.steps; }; return MockStepFactory; })(compile_step_factory_1.CompileStepFactory); var MockStep = (function (_super) { __extends(MockStep, _super); function MockStep(process) { _super.call(this); this.processClosure = process; } MockStep.prototype.process = function (parent, current, control) { this.processClosure(parent, current, control); }; return MockStep; })(compile_step_1.CompileStep); Object.defineProperty(MockStep.prototype.process, "parameters", { get: function () { return [[compile_element_1.CompileElement], [compile_element_1.CompileElement], [compile_control_1.CompileControl]]; } }); var EMPTY_STEP = function (parent, current, control) { if (lang_1.isPresent(parent)) { current.inheritedProtoView = parent.inheritedProtoView; } }; var FakeTemplateLoader = (function (_super) { __extends(FakeTemplateLoader, _super); function FakeTemplateLoader(urlData) { _super.call(this, null, new url_resolver_1.UrlResolver()); this._urlData = urlData; } FakeTemplateLoader.prototype.load = function (template) { if (lang_1.isPresent(template.inline)) { return async_1.PromiseWrapper.resolve(dom_adapter_1.DOM.createTemplate(template.inline)); } if (lang_1.isPresent(template.absUrl)) { var content = collection_1.MapWrapper.get(this._urlData, template.absUrl); if (lang_1.isPresent(content)) { return async_1.PromiseWrapper.resolve(dom_adapter_1.DOM.createTemplate(content)); } } return async_1.PromiseWrapper.reject('Load failed'); }; return FakeTemplateLoader; })(template_loader_1.TemplateLoader); Object.defineProperty(FakeTemplateLoader.prototype.load, "parameters", { get: function () { return [[api_1.Template]]; } });
bsd-2-clause
zmwangx/homebrew-core
Formula/singular.rb
1434
class Singular < Formula desc "Computer algebra system for polynomial computations" homepage "https://www.singular.uni-kl.de/" url "https://service.mathematik.uni-kl.de/ftp/pub/Math/Singular/SOURCES/4-1-2/singular-4.1.2p1.tar.gz" version "4.1.2p1" sha256 "b520809ce061059081a973d4a3b102b05863d49c20565d03f638ba5146296d4f" revision 2 bottle do sha256 "8729b1dc62c815119dcf2dd02c28bd46bff1f6d26b4f94fbe19bcd068bebabd1" => :catalina sha256 "c8667a4ade11b37490a21f5ebba2aeae703d8531bdfa7622c4ebd83bc1e809f2" => :mojave sha256 "366655725abfcebfd6aac79713aeb568282f5c23509b66dc5154367d2bd13934" => :high_sierra end head do url "https://github.com/Singular/Sources.git" depends_on "autoconf" => :build depends_on "automake" => :build depends_on "libtool" => :build end depends_on "gmp" depends_on "mpfr" depends_on "ntl" def install system "./autogen.sh" if build.head? system "./configure", "--disable-debug", "--disable-dependency-tracking", "--disable-silent-rules", "--prefix=#{prefix}", "CXXFLAGS=-std=c++11" system "make", "install" end test do testinput = <<~EOS ring r = 0,(x,y,z),dp; poly p = x; poly q = y; poly qq = z; p*q*qq; EOS assert_match "xyz", pipe_output("#{bin}/Singular", testinput, 0) end end
bsd-2-clause
BlazeLoader/BlazeLoader
src/main/com/blazeloader/api/item/ItemRegistry.java
658
package com.blazeloader.api.item; import net.minecraft.item.Item; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class ItemRegistry { private static final ItemRegistry instance = new ItemRegistry(); private static Map<Item, ArrayList<String>> variantNames = new HashMap<Item, ArrayList<String>>(); public static ItemRegistry instance() { return instance; } protected void registerVariantNames(Item item, ArrayList<String> variants) { variantNames.put(item, variants); } public void insertItemVariantNames(Map<Item, List<String>> mapping) { mapping.putAll(variantNames); } }
bsd-2-clause
bdotdub/goexif
exif/regress_expected_test.go
134049
package exif var regressExpected = map[string]map[FieldName]string{ "2006-08-03-16-29-38-sep-2006-08-03-16-29-38a.jpg": map[FieldName]string{ DateTime: `{Id: 132, Val: "2006:08:03 16:29:38"}`, XResolution: `{Id: 11A, Val: ["180/1"]}`, ExifVersion: `{Id: 9000, Val: "0220"}`, CompressedBitsPerPixel: `{Id: 9102, Val: ["5/1"]}`, Flash: `{Id: 9209, Val: [24]}`, Model: `{Id: 110, Val: "Canon PowerShot SD600"}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [5108]}`, MaxApertureValue: `{Id: 9205, Val: ["95/32"]}`, FocalLength: `{Id: 920A, Val: ["5800/1000"]}`, ColorSpace: `{Id: A001, Val: [1]}`, FocalPlaneXResolution: `{Id: A20E, Val: ["2816000/225"]}`, DateTimeOriginal: `{Id: 9003, Val: "2006:08:03 16:29:38"}`, MakerNote: `{Id: 927C, Val: ""}`, SensingMethod: `{Id: A217, Val: [2]}`, DigitalZoomRatio: `{Id: A404, Val: ["2816/2816"]}`, SceneCaptureType: `{Id: A406, Val: [0]}`, FNumber: `{Id: 829D, Val: ["28/10"]}`, FocalPlaneResolutionUnit: `{Id: A210, Val: [2]}`, Orientation: `{Id: 112, Val: [6]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [1]}`, ExifIFDPointer: `{Id: 8769, Val: [196]}`, ExposureTime: `{Id: 829A, Val: ["1/1500"]}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, MeteringMode: `{Id: 9207, Val: [5]}`, FocalPlaneYResolution: `{Id: A20F, Val: ["2112000/169"]}`, YResolution: `{Id: 11B, Val: ["180/1"]}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [4323]}`, ShutterSpeedValue: `{Id: 9201, Val: ["338/32"]}`, ApertureValue: `{Id: 9202, Val: ["95/32"]}`, ExposureBiasValue: `{Id: 9204, Val: ["0/3"]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, PixelYDimension: `{Id: A003, Val: [2112]}`, FileSource: `{Id: A300, Val: ""}`, WhiteBalance: `{Id: A403, Val: [0]}`, Make: `{Id: 10F, Val: "Canon"}`, DateTimeDigitized: `{Id: 9004, Val: "2006:08:03 16:29:38"}`, UserComment: `{Id: 9286, Val: ""}`, PixelXDimension: `{Id: A002, Val: [2816]}`, InteroperabilityIFDPointer: `{Id: A005, Val: [2824]}`, CustomRendered: `{Id: A401, Val: [0]}`, ExposureMode: `{Id: A402, Val: [0]}`, InteroperabilityIndex: `{Id: 1, Val: "R98"}`, }, "2013-02-05-23-12-09-sep-DSCI0001.jpg": map[FieldName]string{ DateTimeOriginal: `{Id: 9003, Val: "2013:02:05 23:12:09"}`, MakerNote: `{Id: 927C, Val: " BARCODE:A265KS008000; ZP:812; FP:124; AWB:235,679; PWB:476,304; PMF:12,11610; LV:493; LUM:3-8-9-8-1-11;20;26;19;10;A:1,F1:6,F2:18;ET:145, W:2, F:3 ;FV: 41FV: 36FV: 43FV: 223FV: 258FV: 9FV: 466FV: 216FP: 10FP: 8FP: 6FP: 6FP: 6FP: 0FP: 8FP: 8AFS: 110"}`, SensingMethod: `{Id: A217, Val: [2]}`, SceneType: `{Id: A301, Val: ""}`, DigitalZoomRatio: `{Id: A404, Val: ["100/100"]}`, SceneCaptureType: `{Id: A406, Val: [0]}`, ImageDescription: `{Id: 10E, Val: ""}`, Software: `{Id: 131, Val: " 1.0"}`, FNumber: `{Id: 829D, Val: ["28/10"]}`, Sharpness: `{Id: A40A, Val: [0]}`, Orientation: `{Id: 112, Val: [1]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [2]}`, ExifIFDPointer: `{Id: 8769, Val: [240]}`, ExposureTime: `{Id: 829A, Val: ["1/60"]}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, MeteringMode: `{Id: 9207, Val: [3]}`, YResolution: `{Id: 11B, Val: ["288/3"]}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [5863]}`, ShutterSpeedValue: `{Id: 9201, Val: ["5907/1000"]}`, ApertureValue: `{Id: 9202, Val: ["3072/1000"]}`, ExposureBiasValue: `{Id: 9204, Val: ["0/10"]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, PixelYDimension: `{Id: A003, Val: [1200]}`, FileSource: `{Id: A300, Val: ""}`, WhiteBalance: `{Id: A403, Val: [0]}`, Make: `{Id: 10F, Val: "Polaroid"}`, DateTimeDigitized: `{Id: 9004, Val: "2013:02:05 23:12:09"}`, PixelXDimension: `{Id: A002, Val: [1600]}`, InteroperabilityIFDPointer: `{Id: A005, Val: [4838]}`, ExposureMode: `{Id: A402, Val: [0]}`, InteroperabilityIndex: `{Id: 1, Val: "R98"}`, DateTime: `{Id: 132, Val: "2013:02:05 23:12:09"}`, ExposureProgram: `{Id: 8822, Val: [2]}`, XResolution: `{Id: 11A, Val: ["288/3"]}`, ISOSpeedRatings: `{Id: 8827, Val: [100]}`, ExifVersion: `{Id: 9000, Val: "0210"}`, CompressedBitsPerPixel: `{Id: 9102, Val: ["3766184/1920000"]}`, Flash: `{Id: 9209, Val: [1]}`, FocalLengthIn35mmFilm: `{Id: A405, Val: [35]}`, Model: `{Id: 110, Val: "Polaroid i532"}`, Copyright: `{Id: 8298, Val: "Copyright 2005"}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [4974]}`, MaxApertureValue: `{Id: 9205, Val: ["3072/1000"]}`, LightSource: `{Id: 9208, Val: [0]}`, FocalLength: `{Id: 920A, Val: ["5954/1000"]}`, ColorSpace: `{Id: A001, Val: [1]}`, }, "2012-12-21-11-15-19-sep-IMG_0001.jpg": map[FieldName]string{ Model: `{Id: 110, Val: "Canon EOS REBEL T4i"}`, Artist: `{Id: 13B, Val: ""}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [14327]}`, ShutterSpeedValue: `{Id: 9201, Val: ["327680/65536"]}`, ExposureBiasValue: `{Id: 9204, Val: ["0/1"]}`, FocalLength: `{Id: 920A, Val: ["24/1"]}`, ColorSpace: `{Id: A001, Val: [1]}`, PixelYDimension: `{Id: A003, Val: [3456]}`, FocalPlaneXResolution: `{Id: A20E, Val: ["5184000/894"]}`, Make: `{Id: 10F, Val: "Canon"}`, DateTimeOriginal: `{Id: 9003, Val: "2012:12:21 11:15:19"}`, DateTimeDigitized: `{Id: 9004, Val: "2012:12:21 11:15:19"}`, PixelXDimension: `{Id: A002, Val: [5184]}`, InteroperabilityIFDPointer: `{Id: A005, Val: [8806]}`, InteroperabilityIndex: `{Id: 1, Val: "R98"}`, FocalPlaneResolutionUnit: `{Id: A210, Val: [2]}`, Orientation: `{Id: 112, Val: [1]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [2]}`, GPSInfoIFDPointer: `{Id: 8825, Val: [9034]}`, ExifVersion: `{Id: 9000, Val: "0230"}`, MeteringMode: `{Id: 9207, Val: [5]}`, Flash: `{Id: 9209, Val: [16]}`, FocalPlaneYResolution: `{Id: A20F, Val: ["3456000/597"]}`, YResolution: `{Id: 11B, Val: ["72/1"]}`, Copyright: `{Id: 8298, Val: ""}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [10924]}`, ApertureValue: `{Id: 9202, Val: ["286720/65536"]}`, SubSecTimeDigitized: `{Id: 9292, Val: "00"}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, WhiteBalance: `{Id: A403, Val: [0]}`, MakerNote: `{Id: 927C, Val: ""}`, UserComment: `{Id: 9286, Val: ""}`, SubSecTime: `{Id: 9290, Val: "00"}`, CustomRendered: `{Id: A401, Val: [0]}`, ExposureMode: `{Id: A402, Val: [0]}`, SceneCaptureType: `{Id: A406, Val: [0]}`, DateTime: `{Id: 132, Val: "2012:12:21 11:15:19"}`, FNumber: `{Id: 829D, Val: ["45/10"]}`, ExposureProgram: `{Id: 8822, Val: [0]}`, SubSecTimeOriginal: `{Id: 9291, Val: "00"}`, GPSVersionID: `{Id: 0, Val: [2,3,0,0]}`, XResolution: `{Id: 11A, Val: ["72/1"]}`, ExifIFDPointer: `{Id: 8769, Val: [360]}`, ExposureTime: `{Id: 829A, Val: ["1/30"]}`, ISOSpeedRatings: `{Id: 8827, Val: [1600]}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, }, "2006-12-10-23-58-20-sep-2006-12-10-23-58-20a.jpg": map[FieldName]string{ FNumber: `{Id: 829D, Val: ["28/10"]}`, FocalPlaneResolutionUnit: `{Id: A210, Val: [2]}`, Orientation: `{Id: 112, Val: [1]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [1]}`, ExifIFDPointer: `{Id: 8769, Val: [196]}`, ExposureTime: `{Id: 829A, Val: ["1/80"]}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, MeteringMode: `{Id: 9207, Val: [5]}`, FocalPlaneYResolution: `{Id: A20F, Val: ["1704000/210"]}`, YResolution: `{Id: 11B, Val: ["180/1"]}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [6465]}`, ShutterSpeedValue: `{Id: 9201, Val: ["202/32"]}`, ApertureValue: `{Id: 9202, Val: ["95/32"]}`, ExposureBiasValue: `{Id: 9204, Val: ["0/3"]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, PixelYDimension: `{Id: A003, Val: [1704]}`, FileSource: `{Id: A300, Val: ""}`, WhiteBalance: `{Id: A403, Val: [0]}`, Make: `{Id: 10F, Val: "Canon"}`, DateTimeDigitized: `{Id: 9004, Val: "2006:12:10 23:58:20"}`, UserComment: `{Id: 9286, Val: ""}`, PixelXDimension: `{Id: A002, Val: [2272]}`, InteroperabilityIFDPointer: `{Id: A005, Val: [1844]}`, CustomRendered: `{Id: A401, Val: [0]}`, ExposureMode: `{Id: A402, Val: [0]}`, InteroperabilityIndex: `{Id: 1, Val: "R98"}`, DateTime: `{Id: 132, Val: "2006:12:10 23:58:20"}`, XResolution: `{Id: 11A, Val: ["180/1"]}`, ExifVersion: `{Id: 9000, Val: "0220"}`, CompressedBitsPerPixel: `{Id: 9102, Val: ["3/1"]}`, Flash: `{Id: 9209, Val: [24]}`, Model: `{Id: 110, Val: "Canon PowerShot A80"}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [2036]}`, MaxApertureValue: `{Id: 9205, Val: ["95/32"]}`, FocalLength: `{Id: 920A, Val: ["250/32"]}`, ColorSpace: `{Id: A001, Val: [1]}`, FocalPlaneXResolution: `{Id: A20E, Val: ["2272000/280"]}`, DateTimeOriginal: `{Id: 9003, Val: "2006:12:10 23:58:20"}`, MakerNote: `{Id: 927C, Val: ""}`, SensingMethod: `{Id: A217, Val: [2]}`, DigitalZoomRatio: `{Id: A404, Val: ["2272/2272"]}`, SceneCaptureType: `{Id: A406, Val: [0]}`, }, "2008-06-17-01-21-30-sep-2008-06-17-01-21-30a.jpg": map[FieldName]string{ DateTimeDigitized: `{Id: 9004, Val: "2008:06:17 01:21:30"}`, CompressedBitsPerPixel: `{Id: 9102, Val: ["2/1"]}`, MeteringMode: `{Id: 9207, Val: [2]}`, UserComment: `{Id: 9286, Val: ""}`, PixelXDimension: `{Id: A002, Val: [2592]}`, ImageDescription: `{Id: 10E, Val: "DCFC1247.JPG "}`, Model: `{Id: 110, Val: "5MP Digital Camera"}`, ExposureBiasValue: `{Id: 9204, Val: ["0/10"]}`, PixelYDimension: `{Id: A003, Val: [1944]}`, Orientation: `{Id: 112, Val: [1]}`, XResolution: `{Id: 11A, Val: ["72/1"]}`, ISOSpeedRatings: `{Id: 8827, Val: [100]}`, ExifVersion: `{Id: 9000, Val: "0220"}`, Flash: `{Id: 9209, Val: [0]}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [1041]}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [13506]}`, ExposureProgram: `{Id: 8822, Val: [2]}`, MaxApertureValue: `{Id: 9205, Val: ["30/10"]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [2]}`, ExifIFDPointer: `{Id: 8769, Val: [253]}`, ExposureTime: `{Id: 829A, Val: ["10/326"]}`, SceneType: `{Id: A301, Val: ""}`, InteroperabilityIndex: `{Id: 1, Val: "R98"}`, YResolution: `{Id: 11B, Val: ["72/1"]}`, Software: `{Id: 131, Val: "A520_CT019"}`, DateTime: `{Id: 132, Val: "2008:06:17 01:22:13"}`, LightSource: `{Id: 9208, Val: [0]}`, FocalLength: `{Id: 920A, Val: ["645/100"]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, Make: `{Id: 10F, Val: "Polaroid"}`, DateTimeOriginal: `{Id: 9003, Val: "2008:06:17 01:21:30"}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, InteroperabilityIFDPointer: `{Id: A005, Val: [1011]}`, FNumber: `{Id: 829D, Val: ["28/10"]}`, ColorSpace: `{Id: A001, Val: [1]}`, FileSource: `{Id: A300, Val: ""}`, }, "2006-11-11-19-17-56-sep-2006-11-11-19-17-56a.jpg": map[FieldName]string{ Make: `{Id: 10F, Val: "NIKON"}`, DateTimeOriginal: `{Id: 9003, Val: "2006:11:11 19:17:56"}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, InteroperabilityIFDPointer: `{Id: A005, Val: [1026]}`, ExposureMode: `{Id: A402, Val: [0]}`, FocalLengthIn35mmFilm: `{Id: A405, Val: [38]}`, SceneCaptureType: `{Id: A406, Val: [0]}`, Contrast: `{Id: A408, Val: [0]}`, FNumber: `{Id: 829D, Val: ["28/10"]}`, ColorSpace: `{Id: A001, Val: [1]}`, FileSource: `{Id: A300, Val: ""}`, WhiteBalance: `{Id: A403, Val: [0]}`, Sharpness: `{Id: A40A, Val: [0]}`, DateTimeDigitized: `{Id: 9004, Val: "2006:11:11 19:17:56"}`, CompressedBitsPerPixel: `{Id: 9102, Val: ["4/1"]}`, MeteringMode: `{Id: 9207, Val: [5]}`, MakerNote: `{Id: 927C, Val: ""}`, UserComment: `{Id: 9286, Val: " "}`, PixelXDimension: `{Id: A002, Val: [2048]}`, GainControl: `{Id: A407, Val: [0]}`, Saturation: `{Id: A409, Val: [0]}`, SubjectDistanceRange: `{Id: A40C, Val: [0]}`, ImageDescription: `{Id: 10E, Val: " "}`, Model: `{Id: 110, Val: "E3200"}`, ExposureBiasValue: `{Id: 9204, Val: ["0/10"]}`, PixelYDimension: `{Id: A003, Val: [1536]}`, Orientation: `{Id: 112, Val: [1]}`, XResolution: `{Id: 11A, Val: ["300/1"]}`, ISOSpeedRatings: `{Id: 8827, Val: [50]}`, ExifVersion: `{Id: 9000, Val: "0220"}`, Flash: `{Id: 9209, Val: [25]}`, CustomRendered: `{Id: A401, Val: [1]}`, DigitalZoomRatio: `{Id: A404, Val: ["0/100"]}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [4596]}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [4546]}`, ExposureProgram: `{Id: 8822, Val: [2]}`, MaxApertureValue: `{Id: 9205, Val: ["30/10"]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [2]}`, ExifIFDPointer: `{Id: 8769, Val: [284]}`, ExposureTime: `{Id: 829A, Val: ["10/601"]}`, SceneType: `{Id: A301, Val: ""}`, InteroperabilityIndex: `{Id: 1, Val: "R98"}`, YResolution: `{Id: 11B, Val: ["300/1"]}`, Software: `{Id: 131, Val: "E3200v1.1"}`, DateTime: `{Id: 132, Val: "2006:11:11 19:17:56"}`, LightSource: `{Id: 9208, Val: [0]}`, FocalLength: `{Id: 920A, Val: ["58/10"]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, }, "2007-08-24-02-40-42-sep-2007-08-24-02-40-42a.jpg": map[FieldName]string{ DateTimeDigitized: `{Id: 9004, Val: "2007:08:24 02:40:42"}`, CompressedBitsPerPixel: `{Id: 9102, Val: ["5/1"]}`, MeteringMode: `{Id: 9207, Val: [5]}`, MakerNote: `{Id: 927C, Val: ""}`, UserComment: `{Id: 9286, Val: ""}`, PixelXDimension: `{Id: A002, Val: [2592]}`, SensingMethod: `{Id: A217, Val: [2]}`, Model: `{Id: 110, Val: "Canon PowerShot SD450"}`, ExposureBiasValue: `{Id: 9204, Val: ["0/3"]}`, PixelYDimension: `{Id: A003, Val: [1944]}`, FocalPlaneResolutionUnit: `{Id: A210, Val: [2]}`, Orientation: `{Id: 112, Val: [1]}`, XResolution: `{Id: 11A, Val: ["180/1"]}`, ExifVersion: `{Id: 9000, Val: "0220"}`, Flash: `{Id: 9209, Val: [24]}`, FocalPlaneYResolution: `{Id: A20F, Val: ["1944000/168"]}`, CustomRendered: `{Id: A401, Val: [0]}`, DigitalZoomRatio: `{Id: A404, Val: ["2592/2592"]}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [5108]}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [2084]}`, MaxApertureValue: `{Id: 9205, Val: ["147/32"]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [1]}`, ExifIFDPointer: `{Id: 8769, Val: [196]}`, ExposureTime: `{Id: 829A, Val: ["1/400"]}`, InteroperabilityIndex: `{Id: 1, Val: "R98"}`, YResolution: `{Id: 11B, Val: ["180/1"]}`, DateTime: `{Id: 132, Val: "2007:08:24 02:40:42"}`, ShutterSpeedValue: `{Id: 9201, Val: ["277/32"]}`, ApertureValue: `{Id: 9202, Val: ["213/32"]}`, FocalLength: `{Id: 920A, Val: ["17400/1000"]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, FocalPlaneXResolution: `{Id: A20E, Val: ["2592000/225"]}`, Make: `{Id: 10F, Val: "Canon"}`, DateTimeOriginal: `{Id: 9003, Val: "2007:08:24 02:40:42"}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, InteroperabilityIFDPointer: `{Id: A005, Val: [2206]}`, ExposureMode: `{Id: A402, Val: [0]}`, SceneCaptureType: `{Id: A406, Val: [0]}`, FNumber: `{Id: 829D, Val: ["100/10"]}`, ColorSpace: `{Id: A001, Val: [1]}`, FileSource: `{Id: A300, Val: ""}`, WhiteBalance: `{Id: A403, Val: [0]}`, }, "f2-exif.jpg": map[FieldName]string{ Orientation: `{Id: 112, Val: [2]}`, XResolution: `{Id: 11A, Val: ["72/1"]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [1]}`, ExifIFDPointer: `{Id: 8769, Val: [134]}`, ExifVersion: `{Id: 9000, Val: "0210"}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, PixelXDimension: `{Id: A002, Val: [0]}`, YResolution: `{Id: 11B, Val: ["72/1"]}`, DateTime: `{Id: 132, Val: "2012:11:04 05:42:32"}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, ColorSpace: `{Id: A001, Val: [65535]}`, PixelYDimension: `{Id: A003, Val: [0]}`, }, "f7-exif.jpg": map[FieldName]string{ YResolution: `{Id: 11B, Val: ["72/1"]}`, DateTime: `{Id: 132, Val: "2012:11:04 05:42:32"}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, ColorSpace: `{Id: A001, Val: [65535]}`, PixelYDimension: `{Id: A003, Val: [0]}`, Orientation: `{Id: 112, Val: [7]}`, XResolution: `{Id: 11A, Val: ["72/1"]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [1]}`, ExifIFDPointer: `{Id: 8769, Val: [134]}`, ExifVersion: `{Id: 9000, Val: "0210"}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, PixelXDimension: `{Id: A002, Val: [0]}`, }, "2007-05-12-08-19-07-sep-2007-05-12-08-19-07a.jpg": map[FieldName]string{ ThumbJPEGInterchangeFormat: `{Id: 201, Val: [27422]}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [8332]}`, ExposureProgram: `{Id: 8822, Val: [2]}`, MaxApertureValue: `{Id: 9205, Val: ["33/10"]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [1]}`, ExifIFDPointer: `{Id: 8769, Val: [282]}`, ExposureTime: `{Id: 829A, Val: ["1/50"]}`, InteroperabilityIndex: `{Id: 1, Val: "R98"}`, YResolution: `{Id: 11B, Val: ["72/1"]}`, Software: `{Id: 131, Val: "1.00 "}`, DateTime: `{Id: 132, Val: "2007:06:17 22:56:38"}`, LightSource: `{Id: 9208, Val: [0]}`, FocalLength: `{Id: 920A, Val: ["630/100"]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, Make: `{Id: 10F, Val: "CASIO COMPUTER CO.,LTD."}`, DateTimeOriginal: `{Id: 9003, Val: "2007:05:12 08:19:07"}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, InteroperabilityIFDPointer: `{Id: A005, Val: [27298]}`, ExposureMode: `{Id: A402, Val: [0]}`, FocalLengthIn35mmFilm: `{Id: A405, Val: [38]}`, SceneCaptureType: `{Id: A406, Val: [0]}`, Contrast: `{Id: A408, Val: [0]}`, FNumber: `{Id: 829D, Val: ["31/10"]}`, ColorSpace: `{Id: A001, Val: [1]}`, FileSource: `{Id: A300, Val: ""}`, WhiteBalance: `{Id: A403, Val: [0]}`, Sharpness: `{Id: A40A, Val: [0]}`, DateTimeDigitized: `{Id: 9004, Val: "2007:06:17 22:56:38"}`, CompressedBitsPerPixel: `{Id: 9102, Val: ["252746/307200"]}`, MeteringMode: `{Id: 9207, Val: [5]}`, MakerNote: `{Id: 927C, Val: ""}`, PixelXDimension: `{Id: A002, Val: [640]}`, GainControl: `{Id: A407, Val: [2]}`, Saturation: `{Id: A409, Val: [0]}`, Model: `{Id: 110, Val: "EX-Z70 "}`, ExposureBiasValue: `{Id: 9204, Val: ["0/3"]}`, PixelYDimension: `{Id: A003, Val: [480]}`, Orientation: `{Id: 112, Val: [1]}`, XResolution: `{Id: 11A, Val: ["72/1"]}`, ExifVersion: `{Id: 9000, Val: "0221"}`, Flash: `{Id: 9209, Val: [16]}`, CustomRendered: `{Id: A401, Val: [0]}`, DigitalZoomRatio: `{Id: A404, Val: ["0/0"]}`, }, "2009-03-26-09-23-20-sep-2009-03-26-09-23-20a.jpg": map[FieldName]string{ Model: `{Id: 110, Val: "Canon PowerShot SD750"}`, ShutterSpeedValue: `{Id: 9201, Val: ["287/32"]}`, FocalPlaneResolutionUnit: `{Id: A210, Val: [2]}`, Make: `{Id: 10F, Val: "Canon"}`, Orientation: `{Id: 112, Val: [1]}`, XResolution: `{Id: 11A, Val: ["180/1"]}`, ISOSpeedRatings: `{Id: 8827, Val: [160]}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, InteroperabilityIFDPointer: `{Id: A005, Val: [3334]}`, FocalPlaneYResolution: `{Id: A20F, Val: ["2304000/169"]}`, CustomRendered: `{Id: A401, Val: [0]}`, DigitalZoomRatio: `{Id: A404, Val: ["3072/3072"]}`, SceneCaptureType: `{Id: A406, Val: [0]}`, FNumber: `{Id: 829D, Val: ["28/10"]}`, FileSource: `{Id: A300, Val: ""}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [1]}`, DateTimeDigitized: `{Id: 9004, Val: "2009:03:26 09:23:20"}`, MakerNote: `{Id: 927C, Val: ""}`, PixelXDimension: `{Id: A002, Val: [3072]}`, SensingMethod: `{Id: A217, Val: [2]}`, YResolution: `{Id: 11B, Val: ["180/1"]}`, DateTime: `{Id: 132, Val: "2009:03:26 09:23:20"}`, ApertureValue: `{Id: 9202, Val: ["95/32"]}`, ExposureBiasValue: `{Id: 9204, Val: ["0/3"]}`, FocalLength: `{Id: 920A, Val: ["5800/1000"]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, PixelYDimension: `{Id: A003, Val: [2304]}`, FocalPlaneXResolution: `{Id: A20E, Val: ["3072000/225"]}`, ExifVersion: `{Id: 9000, Val: "0220"}`, DateTimeOriginal: `{Id: 9003, Val: "2009:03:26 09:23:20"}`, Flash: `{Id: 9209, Val: [24]}`, ExposureMode: `{Id: A402, Val: [0]}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [5108]}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [5513]}`, MaxApertureValue: `{Id: 9205, Val: ["95/32"]}`, ColorSpace: `{Id: A001, Val: [1]}`, WhiteBalance: `{Id: A403, Val: [0]}`, ExifIFDPointer: `{Id: 8769, Val: [196]}`, ExposureTime: `{Id: 829A, Val: ["1/500"]}`, CompressedBitsPerPixel: `{Id: 9102, Val: ["5/1"]}`, MeteringMode: `{Id: 9207, Val: [5]}`, UserComment: `{Id: 9286, Val: ""}`, InteroperabilityIndex: `{Id: 1, Val: "R98"}`, }, "2008-06-02-10-03-57-sep-2008-06-02-10-03-57a.jpg": map[FieldName]string{ Orientation: `{Id: 112, Val: [1]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [2]}`, ExifVersion: `{Id: 9000, Val: "0220"}`, MeteringMode: `{Id: 9207, Val: [4]}`, Flash: `{Id: 9209, Val: [65]}`, YResolution: `{Id: 11B, Val: ["288/3"]}`, Copyright: `{Id: 8298, Val: "Copyright 2006"}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [3756]}`, ApertureValue: `{Id: 9202, Val: ["2970/1000"]}`, MaxApertureValue: `{Id: 9205, Val: ["2970/1000"]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, WhiteBalance: `{Id: A403, Val: [0]}`, MakerNote: `{Id: 927C, Val: ""}`, SensingMethod: `{Id: A217, Val: [2]}`, ExposureMode: `{Id: A402, Val: [0]}`, Software: `{Id: 131, Val: "00.00.1240a"}`, DateTime: `{Id: 132, Val: "2008:06:13 06:16:19"}`, FNumber: `{Id: 829D, Val: ["2800/1000"]}`, ExposureProgram: `{Id: 8822, Val: [7]}`, XResolution: `{Id: 11A, Val: ["288/3"]}`, ExifIFDPointer: `{Id: 8769, Val: [226]}`, ExposureTime: `{Id: 829A, Val: ["10/600"]}`, ISOSpeedRatings: `{Id: 8827, Val: [100]}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, CompressedBitsPerPixel: `{Id: 9102, Val: ["5896224/3145728"]}`, Model: `{Id: 110, Val: "i533"}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [5972]}`, ShutterSpeedValue: `{Id: 9201, Val: ["5907/1000"]}`, ExposureBiasValue: `{Id: 9204, Val: ["0/10"]}`, LightSource: `{Id: 9208, Val: [4]}`, FocalLength: `{Id: 920A, Val: ["6200/1000"]}`, ColorSpace: `{Id: A001, Val: [1]}`, PixelYDimension: `{Id: A003, Val: [1536]}`, FileSource: `{Id: A300, Val: ""}`, Make: `{Id: 10F, Val: "Polaroid"}`, DateTimeOriginal: `{Id: 9003, Val: "2008:06:02 10:03:57"}`, DateTimeDigitized: `{Id: 9004, Val: "2008:06:13 06:16:19"}`, PixelXDimension: `{Id: A002, Val: [2048]}`, InteroperabilityIFDPointer: `{Id: A005, Val: [3620]}`, SceneType: `{Id: A301, Val: ""}`, DigitalZoomRatio: `{Id: A404, Val: ["100/100"]}`, InteroperabilityIndex: `{Id: 1, Val: "R98"}`, Sharpness: `{Id: A40A, Val: [0]}`, }, "2009-04-11-03-01-38-sep-2009-04-11-03-01-38a.jpg": map[FieldName]string{ ImageDescription: `{Id: 10E, Val: " "}`, Model: `{Id: 110, Val: "COOLPIX L18"}`, Software: `{Id: 131, Val: "COOLPIX L18 V1.1"}`, Make: `{Id: 10F, Val: "NIKON"}`, Orientation: `{Id: 112, Val: [1]}`, XResolution: `{Id: 11A, Val: ["300/1"]}`, ISOSpeedRatings: `{Id: 8827, Val: [227]}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, InteroperabilityIFDPointer: `{Id: A005, Val: [33536]}`, CustomRendered: `{Id: A401, Val: [0]}`, DigitalZoomRatio: `{Id: A404, Val: ["0/100"]}`, FocalLengthIn35mmFilm: `{Id: A405, Val: [35]}`, SceneCaptureType: `{Id: A406, Val: [0]}`, Contrast: `{Id: A408, Val: [0]}`, FNumber: `{Id: 829D, Val: ["28/10"]}`, ExposureProgram: `{Id: 8822, Val: [2]}`, FileSource: `{Id: A300, Val: ""}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [2]}`, DateTimeDigitized: `{Id: 9004, Val: "2009:04:11 03:01:38"}`, MakerNote: `{Id: 927C, Val: ""}`, PixelXDimension: `{Id: A002, Val: [3264]}`, SceneType: `{Id: A301, Val: ""}`, YResolution: `{Id: 11B, Val: ["300/1"]}`, DateTime: `{Id: 132, Val: "2009:04:11 03:01:38"}`, ExposureBiasValue: `{Id: 9204, Val: ["0/10"]}`, LightSource: `{Id: 9208, Val: [0]}`, FocalLength: `{Id: 920A, Val: ["5700/1000"]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, PixelYDimension: `{Id: A003, Val: [2448]}`, ExifVersion: `{Id: 9000, Val: "0220"}`, DateTimeOriginal: `{Id: 9003, Val: "2009:04:11 03:01:38"}`, Flash: `{Id: 9209, Val: [24]}`, ExposureMode: `{Id: A402, Val: [0]}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [33660]}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [9697]}`, MaxApertureValue: `{Id: 9205, Val: ["30/10"]}`, ColorSpace: `{Id: A001, Val: [1]}`, WhiteBalance: `{Id: A403, Val: [0]}`, Sharpness: `{Id: A40A, Val: [1]}`, ExifIFDPointer: `{Id: 8769, Val: [230]}`, ExposureTime: `{Id: 829A, Val: ["1/250"]}`, CompressedBitsPerPixel: `{Id: 9102, Val: ["4/1"]}`, MeteringMode: `{Id: 9207, Val: [5]}`, UserComment: `{Id: 9286, Val: " "}`, GainControl: `{Id: A407, Val: [1]}`, Saturation: `{Id: A409, Val: [0]}`, SubjectDistanceRange: `{Id: A40C, Val: [0]}`, InteroperabilityIndex: `{Id: 1, Val: "R98"}`, }, "2012-06-02-10-12-28-sep-2012-06-02-10-12-28.jpg": map[FieldName]string{ Make: `{Id: 10F, Val: "Panasonic"}`, DateTimeDigitized: `{Id: 9004, Val: "2012:06:02 10:12:28"}`, PixelXDimension: `{Id: A002, Val: [4608]}`, InteroperabilityIFDPointer: `{Id: A005, Val: [10506]}`, CustomRendered: `{Id: A401, Val: [0]}`, ExposureMode: `{Id: A402, Val: [0]}`, InteroperabilityIndex: `{Id: 1, Val: "R98"}`, DateTime: `{Id: 132, Val: "2012:06:02 10:12:28"}`, ExposureProgram: `{Id: 8822, Val: [2]}`, XResolution: `{Id: 11A, Val: ["180/1"]}`, ISOSpeedRatings: `{Id: 8827, Val: [100]}`, ExifVersion: `{Id: 9000, Val: "0230"}`, CompressedBitsPerPixel: `{Id: 9102, Val: ["4/1"]}`, Flash: `{Id: 9209, Val: [16]}`, FocalLengthIn35mmFilm: `{Id: A405, Val: [28]}`, Saturation: `{Id: A409, Val: [0]}`, Model: `{Id: 110, Val: "DMC-FH25"}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [11764]}`, MaxApertureValue: `{Id: 9205, Val: ["441/128"]}`, LightSource: `{Id: 9208, Val: [0]}`, FocalLength: `{Id: 920A, Val: ["50/10"]}`, ColorSpace: `{Id: A001, Val: [1]}`, DateTimeOriginal: `{Id: 9003, Val: "2012:06:02 10:12:28"}`, MakerNote: `{Id: 927C, Val: ""}`, SensingMethod: `{Id: A217, Val: [2]}`, SceneType: `{Id: A301, Val: ""}`, DigitalZoomRatio: `{Id: A404, Val: ["0/10"]}`, SceneCaptureType: `{Id: A406, Val: [0]}`, GainControl: `{Id: A407, Val: [0]}`, Contrast: `{Id: A408, Val: [0]}`, Software: `{Id: 131, Val: "Ver.1.0 "}`, FNumber: `{Id: 829D, Val: ["33/10"]}`, Sharpness: `{Id: A40A, Val: [0]}`, Orientation: `{Id: 112, Val: [1]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [2]}`, ExifIFDPointer: `{Id: 8769, Val: [636]}`, ExposureTime: `{Id: 829A, Val: ["10/4000"]}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, MeteringMode: `{Id: 9207, Val: [5]}`, YResolution: `{Id: 11B, Val: ["180/1"]}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [7486]}`, ExposureBiasValue: `{Id: 9204, Val: ["0/100"]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, PixelYDimension: `{Id: A003, Val: [3456]}`, FileSource: `{Id: A300, Val: ""}`, WhiteBalance: `{Id: A403, Val: [0]}`, }, "2011-10-28-18-25-43-sep-2011-10-28-18-25-43.jpg": map[FieldName]string{ ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [3670]}`, ExposureBiasValue: `{Id: 9204, Val: ["0/6"]}`, ColorSpace: `{Id: A001, Val: [1]}`, PixelYDimension: `{Id: A003, Val: [537]}`, Make: `{Id: 10F, Val: "NIKON CORPORATION"}`, DateTimeOriginal: `{Id: 9003, Val: "2011:10:28 18:25:43"}`, PixelXDimension: `{Id: A002, Val: [800]}`, ImageUniqueID: `{Id: A420, Val: "7fa4f6d028df5f2fc1bad8102be81064"}`, Orientation: `{Id: 112, Val: [1]}`, YCbCrPositioning: `{Id: 213, Val: [2]}`, MeteringMode: `{Id: 9207, Val: [5]}`, FocalLengthIn35mmFilm: `{Id: A405, Val: [120]}`, MaxApertureValue: `{Id: 9205, Val: ["50/10"]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, WhiteBalance: `{Id: A403, Val: [0]}`, MakerNote: `{Id: 927C, Val: ""}`, UserComment: `{Id: 9286, Val: "ASCII "}`, SensingMethod: `{Id: A217, Val: [2]}`, CustomRendered: `{Id: A401, Val: [0]}`, FNumber: `{Id: 829D, Val: ["56/10"]}`, ExposureProgram: `{Id: 8822, Val: [0]}`, SubSecTimeOriginal: `{Id: 9291, Val: "50"}`, ExifIFDPointer: `{Id: 8769, Val: [208]}`, ExposureTime: `{Id: 829A, Val: ["10/600"]}`, Saturation: `{Id: A409, Val: [0]}`, Model: `{Id: 110, Val: "NIKON D80"}`, LightSource: `{Id: 9208, Val: [0]}`, FocalLength: `{Id: 920A, Val: ["800/10"]}`, FileSource: `{Id: A300, Val: ""}`, DateTimeDigitized: `{Id: 9004, Val: "2011:10:28 18:25:43"}`, InteroperabilityIFDPointer: `{Id: A005, Val: [3604]}`, SceneType: `{Id: A301, Val: ""}`, CFAPattern: `{Id: A302, Val: ""}`, DigitalZoomRatio: `{Id: A404, Val: ["1/1"]}`, GainControl: `{Id: A407, Val: [2]}`, InteroperabilityIndex: `{Id: 1, Val: "R98"}`, Sharpness: `{Id: A40A, Val: [0]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, ExifVersion: `{Id: 9000, Val: "0221"}`, Flash: `{Id: 9209, Val: [31]}`, SubjectDistanceRange: `{Id: A40C, Val: [0]}`, YResolution: `{Id: 11B, Val: ["300/1"]}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [3728]}`, SubSecTimeDigitized: `{Id: 9292, Val: "50"}`, SubSecTime: `{Id: 9290, Val: "50"}`, ExposureMode: `{Id: A402, Val: [0]}`, SceneCaptureType: `{Id: A406, Val: [0]}`, Contrast: `{Id: A408, Val: [0]}`, Software: `{Id: 131, Val: "Ver.1.11 "}`, DateTime: `{Id: 132, Val: "2011:10:28 18:25:43"}`, XResolution: `{Id: 11A, Val: ["300/1"]}`, ISOSpeedRatings: `{Id: 8827, Val: [1250]}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, CompressedBitsPerPixel: `{Id: 9102, Val: ["2/1"]}`, }, "2007-07-13-17-02-30-sep-2007-07-13-17-02-30a.jpg": map[FieldName]string{ DateTimeDigitized: `{Id: 9004, Val: "2007:07:13 17:02:30"}`, MeteringMode: `{Id: 9207, Val: [2]}`, MakerNote: `{Id: 927C, Val: ""}`, PixelXDimension: `{Id: A002, Val: [3648]}`, GainControl: `{Id: A407, Val: [0]}`, Saturation: `{Id: A409, Val: [0]}`, SubjectDistanceRange: `{Id: A40C, Val: [0]}`, ImageDescription: `{Id: 10E, Val: "Digital StillCamera"}`, Model: `{Id: 110, Val: "ViviCam X30 "}`, ExposureBiasValue: `{Id: 9204, Val: ["0/10"]}`, PixelYDimension: `{Id: A003, Val: [2736]}`, Orientation: `{Id: 112, Val: [1]}`, XResolution: `{Id: 11A, Val: ["72/1"]}`, ISOSpeedRatings: `{Id: 8827, Val: [64]}`, ExifVersion: `{Id: 9000, Val: "0220"}`, Flash: `{Id: 9209, Val: [0]}`, CustomRendered: `{Id: A401, Val: [0]}`, DigitalZoomRatio: `{Id: A404, Val: ["100/100"]}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [1156]}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [20544]}`, ExposureProgram: `{Id: 8822, Val: [2]}`, MaxApertureValue: `{Id: 9205, Val: ["30/10"]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [2]}`, ExifIFDPointer: `{Id: 8769, Val: [266]}`, ExposureTime: `{Id: 829A, Val: ["1/110"]}`, RelatedSoundFile: `{Id: A004, Val: " "}`, InteroperabilityIndex: `{Id: 1, Val: "R98"}`, YResolution: `{Id: 11B, Val: ["72/1"]}`, Software: `{Id: 131, Val: "Ver 1.00 "}`, DateTime: `{Id: 132, Val: "2007:07:13 17:02:30"}`, ShutterSpeedValue: `{Id: 9201, Val: ["678/100"]}`, ApertureValue: `{Id: 9202, Val: ["45/10"]}`, LightSource: `{Id: 9208, Val: [0]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, Make: `{Id: 10F, Val: "Vivitar"}`, DateTimeOriginal: `{Id: 9003, Val: "2007:07:13 17:02:30"}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, InteroperabilityIFDPointer: `{Id: A005, Val: [1010]}`, ExposureMode: `{Id: A402, Val: [0]}`, FocalLengthIn35mmFilm: `{Id: A405, Val: [35]}`, SceneCaptureType: `{Id: A406, Val: [0]}`, Contrast: `{Id: A408, Val: [0]}`, FNumber: `{Id: 829D, Val: ["48/10"]}`, ColorSpace: `{Id: A001, Val: [1]}`, FileSource: `{Id: A300, Val: ""}`, WhiteBalance: `{Id: A403, Val: [0]}`, Sharpness: `{Id: A40A, Val: [0]}`, }, "2007-05-26-04-49-45-sep-2007-05-26-04-49-45a.jpg": map[FieldName]string{ FNumber: `{Id: 829D, Val: ["32/10"]}`, ColorSpace: `{Id: A001, Val: [1]}`, FileSource: `{Id: A300, Val: ""}`, WhiteBalance: `{Id: A403, Val: [0]}`, Sharpness: `{Id: A40A, Val: [0]}`, DateTimeDigitized: `{Id: 9004, Val: "2007:05:26 04:49:45"}`, CompressedBitsPerPixel: `{Id: 9102, Val: ["4/1"]}`, MeteringMode: `{Id: 9207, Val: [5]}`, MakerNote: `{Id: 927C, Val: ""}`, UserComment: `{Id: 9286, Val: " "}`, PixelXDimension: `{Id: A002, Val: [2592]}`, GainControl: `{Id: A407, Val: [0]}`, Saturation: `{Id: A409, Val: [0]}`, SubjectDistanceRange: `{Id: A40C, Val: [0]}`, ImageDescription: `{Id: 10E, Val: " "}`, Model: `{Id: 110, Val: "COOLPIX L3"}`, ExposureBiasValue: `{Id: 9204, Val: ["0/10"]}`, PixelYDimension: `{Id: A003, Val: [1944]}`, Orientation: `{Id: 112, Val: [1]}`, XResolution: `{Id: 11A, Val: ["300/1"]}`, ISOSpeedRatings: `{Id: 8827, Val: [50]}`, ExifVersion: `{Id: 9000, Val: "0220"}`, Flash: `{Id: 9209, Val: [24]}`, CustomRendered: `{Id: A401, Val: [0]}`, DigitalZoomRatio: `{Id: A404, Val: ["0/100"]}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [4596]}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [10120]}`, ExposureProgram: `{Id: 8822, Val: [2]}`, MaxApertureValue: `{Id: 9205, Val: ["34/10"]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [2]}`, ExifIFDPointer: `{Id: 8769, Val: [284]}`, ExposureTime: `{Id: 829A, Val: ["10/3486"]}`, SceneType: `{Id: A301, Val: ""}`, InteroperabilityIndex: `{Id: 1, Val: "R98"}`, YResolution: `{Id: 11B, Val: ["300/1"]}`, Software: `{Id: 131, Val: "COOLPIX L3v1.2"}`, DateTime: `{Id: 132, Val: "2007:05:26 04:49:45"}`, LightSource: `{Id: 9208, Val: [0]}`, FocalLength: `{Id: 920A, Val: ["63/10"]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, Make: `{Id: 10F, Val: "NIKON"}`, DateTimeOriginal: `{Id: 9003, Val: "2007:05:26 04:49:45"}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, InteroperabilityIFDPointer: `{Id: A005, Val: [1026]}`, ExposureMode: `{Id: A402, Val: [0]}`, FocalLengthIn35mmFilm: `{Id: A405, Val: [38]}`, SceneCaptureType: `{Id: A406, Val: [2]}`, Contrast: `{Id: A408, Val: [0]}`, }, "2006-12-17-07-09-14-sep-2006-12-17-07-09-14a.jpg": map[FieldName]string{ ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [2]}`, ExifIFDPointer: `{Id: 8769, Val: [586]}`, ExposureTime: `{Id: 829A, Val: ["1/160"]}`, InteroperabilityIndex: `{Id: 1, Val: "R98"}`, YResolution: `{Id: 11B, Val: ["72/1"]}`, Software: `{Id: 131, Val: "Optio S6 Ver 1.00"}`, DateTime: `{Id: 132, Val: "2006:12:17 07:09:14"}`, FocalLength: `{Id: 920A, Val: ["62/10"]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, Make: `{Id: 10F, Val: "PENTAX Corporation"}`, DateTimeOriginal: `{Id: 9003, Val: "2006:12:17 07:09:14"}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, InteroperabilityIFDPointer: `{Id: A005, Val: [31048]}`, ExposureMode: `{Id: A402, Val: [0]}`, FocalLengthIn35mmFilm: `{Id: A405, Val: [38]}`, SceneCaptureType: `{Id: A406, Val: [0]}`, Contrast: `{Id: A408, Val: [0]}`, FNumber: `{Id: 829D, Val: ["270/100"]}`, ColorSpace: `{Id: A001, Val: [1]}`, WhiteBalance: `{Id: A403, Val: [0]}`, Sharpness: `{Id: A40A, Val: [0]}`, DateTimeDigitized: `{Id: 9004, Val: "2006:12:17 07:09:14"}`, CompressedBitsPerPixel: `{Id: 9102, Val: ["5725504/3145728"]}`, MeteringMode: `{Id: 9207, Val: [5]}`, MakerNote: `{Id: 927C, Val: ""}`, PixelXDimension: `{Id: A002, Val: [2048]}`, Saturation: `{Id: A409, Val: [0]}`, SubjectDistanceRange: `{Id: A40C, Val: [2]}`, Model: `{Id: 110, Val: "PENTAX Optio S6"}`, ExposureBiasValue: `{Id: 9204, Val: ["0/10"]}`, PixelYDimension: `{Id: A003, Val: [1536]}`, Orientation: `{Id: 112, Val: [1]}`, XResolution: `{Id: 11A, Val: ["72/1"]}`, ISOSpeedRatings: `{Id: 8827, Val: [64]}`, ExifVersion: `{Id: 9000, Val: "0220"}`, Flash: `{Id: 9209, Val: [24]}`, CustomRendered: `{Id: A401, Val: [0]}`, DigitalZoomRatio: `{Id: A404, Val: ["100/100"]}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [31172]}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [7063]}`, ExposureProgram: `{Id: 8822, Val: [2]}`, MaxApertureValue: `{Id: 9205, Val: ["27/10"]}`, }, "2008-06-06-13-29-29-sep-2008-06-06-13-29-29a.jpg": map[FieldName]string{ DateTimeOriginal: `{Id: 9003, Val: "2008:06:06 13:29:29"}`, MakerNote: `{Id: 927C, Val: ""}`, SensingMethod: `{Id: A217, Val: [2]}`, DigitalZoomRatio: `{Id: A404, Val: ["3072/3072"]}`, SceneCaptureType: `{Id: A406, Val: [0]}`, FNumber: `{Id: 829D, Val: ["35/10"]}`, FocalPlaneResolutionUnit: `{Id: A210, Val: [2]}`, Orientation: `{Id: 112, Val: [6]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [1]}`, ExifIFDPointer: `{Id: 8769, Val: [196]}`, ExposureTime: `{Id: 829A, Val: ["1/320"]}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, MeteringMode: `{Id: 9207, Val: [5]}`, FocalPlaneYResolution: `{Id: A20F, Val: ["1200000/169"]}`, YResolution: `{Id: 11B, Val: ["180/1"]}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [6594]}`, ShutterSpeedValue: `{Id: 9201, Val: ["266/32"]}`, ApertureValue: `{Id: 9202, Val: ["116/32"]}`, ExposureBiasValue: `{Id: 9204, Val: ["0/3"]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, PixelYDimension: `{Id: A003, Val: [1200]}`, FileSource: `{Id: A300, Val: ""}`, WhiteBalance: `{Id: A403, Val: [0]}`, Make: `{Id: 10F, Val: "Canon"}`, DateTimeDigitized: `{Id: 9004, Val: "2008:06:06 13:29:29"}`, UserComment: `{Id: 9286, Val: ""}`, PixelXDimension: `{Id: A002, Val: [1600]}`, InteroperabilityIFDPointer: `{Id: A005, Val: [3334]}`, CustomRendered: `{Id: A401, Val: [0]}`, ExposureMode: `{Id: A402, Val: [0]}`, InteroperabilityIndex: `{Id: 1, Val: "R98"}`, DateTime: `{Id: 132, Val: "2008:06:06 13:29:29"}`, XResolution: `{Id: 11A, Val: ["180/1"]}`, ISOSpeedRatings: `{Id: 8827, Val: [80]}`, ExifVersion: `{Id: 9000, Val: "0220"}`, CompressedBitsPerPixel: `{Id: 9102, Val: ["5/1"]}`, Flash: `{Id: 9209, Val: [16]}`, Model: `{Id: 110, Val: "Canon DIGITAL IXUS 75"}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [5108]}`, MaxApertureValue: `{Id: 9205, Val: ["116/32"]}`, FocalLength: `{Id: 920A, Val: ["8462/1000"]}`, ColorSpace: `{Id: A001, Val: [1]}`, FocalPlaneXResolution: `{Id: A20E, Val: ["1600000/225"]}`, }, "2009-06-11-19-23-18-sep-2009-06-11-19-23-18a.jpg": map[FieldName]string{ Model: `{Id: 110, Val: "Canon EOS DIGITAL REBEL XTi"}`, YResolution: `{Id: 11B, Val: ["3500000/10000"]}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [606]}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [7150]}`, ApertureValue: `{Id: 9202, Val: ["11257/1627"]}`, ExposureBiasValue: `{Id: 9204, Val: ["0/1"]}`, FocalLength: `{Id: 920A, Val: ["47/1"]}`, ColorSpace: `{Id: A001, Val: [65535]}`, PixelYDimension: `{Id: A003, Val: [2100]}`, Make: `{Id: 10F, Val: "Canon"}`, DateTimeOriginal: `{Id: 9003, Val: "2009:06:11 19:23:18"}`, DateTimeDigitized: `{Id: 9004, Val: "2009:06:11 19:23:18"}`, PixelXDimension: `{Id: A002, Val: [1400]}`, Software: `{Id: 131, Val: "Adobe Photoshop CS3 Macintosh"}`, DateTime: `{Id: 132, Val: "2009:06:23 18:42:05"}`, ExposureProgram: `{Id: 8822, Val: [1]}`, Orientation: `{Id: 112, Val: [1]}`, XResolution: `{Id: 11A, Val: ["3500000/10000"]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [1]}`, ExifIFDPointer: `{Id: 8769, Val: [264]}`, ExposureTime: `{Id: 829A, Val: ["1/4"]}`, ISOSpeedRatings: `{Id: 8827, Val: [200]}`, ExifVersion: `{Id: 9000, Val: "0220"}`, MeteringMode: `{Id: 9207, Val: [1]}`, Flash: `{Id: 9209, Val: [16]}`, }, "f6-exif.jpg": map[FieldName]string{ Orientation: `{Id: 112, Val: [6]}`, XResolution: `{Id: 11A, Val: ["72/1"]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [1]}`, ExifIFDPointer: `{Id: 8769, Val: [134]}`, ExifVersion: `{Id: 9000, Val: "0210"}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, PixelXDimension: `{Id: A002, Val: [0]}`, YResolution: `{Id: 11B, Val: ["72/1"]}`, DateTime: `{Id: 132, Val: "2012:11:04 05:42:32"}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, ColorSpace: `{Id: A001, Val: [65535]}`, PixelYDimension: `{Id: A003, Val: [0]}`, }, "f8-exif.jpg": map[FieldName]string{ YResolution: `{Id: 11B, Val: ["72/1"]}`, DateTime: `{Id: 132, Val: "2012:11:04 05:42:32"}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, ColorSpace: `{Id: A001, Val: [65535]}`, PixelYDimension: `{Id: A003, Val: [0]}`, Orientation: `{Id: 112, Val: [8]}`, XResolution: `{Id: 11A, Val: ["72/1"]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [1]}`, ExifIFDPointer: `{Id: 8769, Val: [134]}`, ExifVersion: `{Id: 9000, Val: "0210"}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, PixelXDimension: `{Id: A002, Val: [0]}`, }, "FailedHash-NoDate-sep-remembory.jpg": map[FieldName]string{ Make: `{Id: 10F, Val: "Brother"}`, Orientation: `{Id: 112, Val: [1]}`, XResolution: `{Id: 11A, Val: ["150/1"]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, ExifIFDPointer: `{Id: 8769, Val: [192]}`, PixelXDimension: `{Id: A002, Val: [1232]}`, Model: `{Id: 110, Val: "MFC-7840W"}`, YResolution: `{Id: 11B, Val: ["150/1"]}`, Software: `{Id: 131, Val: "Apple Image Capture"}`, PixelYDimension: `{Id: A003, Val: [1626]}`, }, "f1-exif.jpg": map[FieldName]string{ Orientation: `{Id: 112, Val: [1]}`, XResolution: `{Id: 11A, Val: ["72/1"]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [1]}`, ExifIFDPointer: `{Id: 8769, Val: [134]}`, ExifVersion: `{Id: 9000, Val: "0210"}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, PixelXDimension: `{Id: A002, Val: [0]}`, YResolution: `{Id: 11B, Val: ["72/1"]}`, DateTime: `{Id: 132, Val: "2012:11:04 05:42:02"}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, ColorSpace: `{Id: A001, Val: [65535]}`, PixelYDimension: `{Id: A003, Val: [0]}`, }, "2007-01-17-21-49-44-sep-2007-01-17-21-49-44a.jpg": map[FieldName]string{ FNumber: `{Id: 829D, Val: ["33/10"]}`, ColorSpace: `{Id: A001, Val: [1]}`, FileSource: `{Id: A300, Val: ""}`, WhiteBalance: `{Id: A403, Val: [0]}`, DateTimeDigitized: `{Id: 9004, Val: "2007:01:17 21:49:44"}`, MeteringMode: `{Id: 9207, Val: [2]}`, MakerNote: `{Id: 927C, Val: "6106789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456"}`, PixelXDimension: `{Id: A002, Val: [2816]}`, SensingMethod: `{Id: A217, Val: [2]}`, ImageDescription: `{Id: 10E, Val: "Digital image "}`, Model: `{Id: 110, Val: "6MP-9Y8 "}`, ExposureBiasValue: `{Id: 9204, Val: ["0/10"]}`, PixelYDimension: `{Id: A003, Val: [2112]}`, Orientation: `{Id: 112, Val: [1]}`, XResolution: `{Id: 11A, Val: ["180/1"]}`, ISOSpeedRatings: `{Id: 8827, Val: [50]}`, ExifVersion: `{Id: 9000, Val: "0220"}`, Flash: `{Id: 9209, Val: [24]}`, CustomRendered: `{Id: A401, Val: [0]}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [956]}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [7024]}`, ExposureProgram: `{Id: 8822, Val: [2]}`, MaxApertureValue: `{Id: 9205, Val: ["297/100"]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [2]}`, ExifIFDPointer: `{Id: 8769, Val: [266]}`, ExposureTime: `{Id: 829A, Val: ["1/30"]}`, InteroperabilityIndex: `{Id: 1, Val: "R98"}`, YResolution: `{Id: 11B, Val: ["180/1"]}`, Software: `{Id: 131, Val: "1.00.018PR "}`, DateTime: `{Id: 132, Val: "2007:01:17 21:49:44"}`, ShutterSpeedValue: `{Id: 9201, Val: ["491/100"]}`, ApertureValue: `{Id: 9202, Val: ["33/10"]}`, LightSource: `{Id: 9208, Val: [0]}`, FocalLength: `{Id: 920A, Val: ["73/10"]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, Make: `{Id: 10F, Val: "Digital Camera "}`, DateTimeOriginal: `{Id: 9003, Val: "2007:01:17 21:49:44"}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, InteroperabilityIFDPointer: `{Id: A005, Val: [832]}`, ExposureMode: `{Id: A402, Val: [0]}`, SceneCaptureType: `{Id: A406, Val: [0]}`, }, "2216-11-15-11-46-51-sep-2216-11-15-11-46-51a.jpg": map[FieldName]string{ Orientation: `{Id: 112, Val: [1]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [2]}`, ExifVersion: `{Id: 9000, Val: "0221"}`, MeteringMode: `{Id: 9207, Val: [5]}`, Flash: `{Id: 9209, Val: [24]}`, FocalLengthIn35mmFilm: `{Id: A405, Val: [36]}`, SubjectDistanceRange: `{Id: A40C, Val: [0]}`, YResolution: `{Id: 11B, Val: ["480/1"]}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [17818]}`, ApertureValue: `{Id: 9202, Val: ["452/100"]}`, MaxApertureValue: `{Id: 9205, Val: ["286/100"]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, WhiteBalance: `{Id: A403, Val: [0]}`, MakerNote: `{Id: 927C, Val: ""}`, SensingMethod: `{Id: A217, Val: [2]}`, CustomRendered: `{Id: A401, Val: [0]}`, ExposureMode: `{Id: A402, Val: [0]}`, SceneCaptureType: `{Id: A406, Val: [0]}`, Contrast: `{Id: A408, Val: [0]}`, Software: `{Id: 131, Val: "KODAK EASYSHARE C813 ZOOM DIGITAL CAMERA"}`, FNumber: `{Id: 829D, Val: ["480/100"]}`, ExposureProgram: `{Id: 8822, Val: [2]}`, ExposureIndex: `{Id: A215, Val: ["80/1"]}`, XResolution: `{Id: 11A, Val: ["480/1"]}`, ExifIFDPointer: `{Id: 8769, Val: [2316]}`, ExposureTime: `{Id: 829A, Val: ["1016/1000000"]}`, ISOSpeedRatings: `{Id: 8827, Val: [80]}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, Saturation: `{Id: A409, Val: [0]}`, Model: `{Id: 110, Val: "KODAK EASYSHARE C813 ZOOM DIGITAL CAMERA"}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [5175]}`, ShutterSpeedValue: `{Id: 9201, Val: ["994/100"]}`, ExposureBiasValue: `{Id: 9204, Val: ["0/10"]}`, LightSource: `{Id: 9208, Val: [0]}`, FocalLength: `{Id: 920A, Val: ["60/10"]}`, ColorSpace: `{Id: A001, Val: [1]}`, PixelYDimension: `{Id: A003, Val: [2472]}`, FileSource: `{Id: A300, Val: ""}`, Make: `{Id: 10F, Val: "EASTMAN KODAK COMPANY"}`, DateTimeOriginal: `{Id: 9003, Val: "2216:11:15 11:46:51"}`, DateTimeDigitized: `{Id: 9004, Val: "2216:11:15 11:46:51"}`, PixelXDimension: `{Id: A002, Val: [3296]}`, InteroperabilityIFDPointer: `{Id: A005, Val: [17674]}`, SceneType: `{Id: A301, Val: ""}`, DigitalZoomRatio: `{Id: A404, Val: ["0/10"]}`, GainControl: `{Id: A407, Val: [0]}`, Sharpness: `{Id: A40A, Val: [0]}`, }, "2007-05-30-14-28-01-sep-2007-05-30-14-28-01a.jpg": map[FieldName]string{ Orientation: `{Id: 112, Val: [1]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [2]}`, ExifVersion: `{Id: 9000, Val: "0220"}`, MeteringMode: `{Id: 9207, Val: [5]}`, Flash: `{Id: 9209, Val: [16]}`, FocalLengthIn35mmFilm: `{Id: A405, Val: [35]}`, SubjectDistanceRange: `{Id: A40C, Val: [0]}`, YResolution: `{Id: 11B, Val: ["300/1"]}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [4596]}`, MaxApertureValue: `{Id: 9205, Val: ["32/10"]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, WhiteBalance: `{Id: A403, Val: [0]}`, MakerNote: `{Id: 927C, Val: ""}`, UserComment: `{Id: 9286, Val: " "}`, CustomRendered: `{Id: A401, Val: [0]}`, ExposureMode: `{Id: A402, Val: [0]}`, SceneCaptureType: `{Id: A406, Val: [0]}`, Contrast: `{Id: A408, Val: [0]}`, Software: `{Id: 131, Val: "COOLPIX S6V1.0"}`, DateTime: `{Id: 132, Val: "2007:05:30 14:28:01"}`, FNumber: `{Id: 829D, Val: ["30/10"]}`, ExposureProgram: `{Id: 8822, Val: [2]}`, XResolution: `{Id: 11A, Val: ["300/1"]}`, ExifIFDPointer: `{Id: 8769, Val: [284]}`, ExposureTime: `{Id: 829A, Val: ["10/40"]}`, ISOSpeedRatings: `{Id: 8827, Val: [53]}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, CompressedBitsPerPixel: `{Id: 9102, Val: ["2/1"]}`, Saturation: `{Id: A409, Val: [0]}`, Model: `{Id: 110, Val: "COOLPIX S6"}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [5274]}`, ExposureBiasValue: `{Id: 9204, Val: ["0/10"]}`, LightSource: `{Id: 9208, Val: [0]}`, FocalLength: `{Id: 920A, Val: ["58/10"]}`, ColorSpace: `{Id: A001, Val: [1]}`, PixelYDimension: `{Id: A003, Val: [2112]}`, FileSource: `{Id: A300, Val: ""}`, Make: `{Id: 10F, Val: "NIKON"}`, DateTimeOriginal: `{Id: 9003, Val: "2007:05:30 14:28:01"}`, DateTimeDigitized: `{Id: 9004, Val: "2007:05:30 14:28:01"}`, PixelXDimension: `{Id: A002, Val: [2816]}`, InteroperabilityIFDPointer: `{Id: A005, Val: [1026]}`, SceneType: `{Id: A301, Val: ""}`, DigitalZoomRatio: `{Id: A404, Val: ["0/100"]}`, GainControl: `{Id: A407, Val: [1]}`, InteroperabilityIndex: `{Id: 1, Val: "R98"}`, ImageDescription: `{Id: 10E, Val: " "}`, Sharpness: `{Id: A40A, Val: [0]}`, }, "2004-01-11-22-45-15-sep-2004-01-11-22-45-15a.jpg": map[FieldName]string{ Make: `{Id: 10F, Val: "Samsung Techwin"}`, Orientation: `{Id: 112, Val: [1]}`, XResolution: `{Id: 11A, Val: ["72/1"]}`, ISOSpeedRatings: `{Id: 8827, Val: [150]}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, InteroperabilityIFDPointer: `{Id: A005, Val: [1009]}`, FNumber: `{Id: 829D, Val: ["320/100"]}`, ExposureProgram: `{Id: 8822, Val: [2]}`, FileSource: `{Id: A300, Val: ""}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [2]}`, DateTimeDigitized: `{Id: 9004, Val: "2004:01:11 22:45:15"}`, PixelXDimension: `{Id: A002, Val: [1600]}`, SceneType: `{Id: A301, Val: ""}`, YResolution: `{Id: 11B, Val: ["72/1"]}`, DateTime: `{Id: 132, Val: "2004:01:11 22:45:19"}`, ExposureBiasValue: `{Id: 9204, Val: ["95/10"]}`, LightSource: `{Id: 9208, Val: [0]}`, FocalLength: `{Id: 920A, Val: ["82/11"]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, PixelYDimension: `{Id: A003, Val: [1200]}`, ExifVersion: `{Id: 9000, Val: "0220"}`, DateTimeOriginal: `{Id: 9003, Val: "2004:01:11 22:45:15"}`, Flash: `{Id: 9209, Val: [1]}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [1039]}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [3530]}`, MaxApertureValue: `{Id: 9205, Val: ["32/10"]}`, ColorSpace: `{Id: A001, Val: [1]}`, ExifIFDPointer: `{Id: 8769, Val: [251]}`, ExposureTime: `{Id: 829A, Val: ["1000/30000"]}`, CompressedBitsPerPixel: `{Id: 9102, Val: ["2/1"]}`, MeteringMode: `{Id: 9207, Val: [2]}`, RelatedSoundFile: `{Id: A004, Val: ""}`, InteroperabilityIndex: `{Id: 1, Val: "R98"}`, ImageDescription: `{Id: 10E, Val: "SAMSUNG DIGITAL CAMERA "}`, Model: `{Id: 110, Val: "U-CA 501"}`, Software: `{Id: 131, Val: "M5011S-1031"}`, }, "2007-06-06-16-15-25-sep-2007-06-06-16-15-25a.jpg": map[FieldName]string{ XResolution: `{Id: 11A, Val: ["300/1"]}`, ExifIFDPointer: `{Id: 8769, Val: [284]}`, ExposureTime: `{Id: 829A, Val: ["10/2870"]}`, ISOSpeedRatings: `{Id: 8827, Val: [50]}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, CompressedBitsPerPixel: `{Id: 9102, Val: ["2/1"]}`, Saturation: `{Id: A409, Val: [0]}`, Model: `{Id: 110, Val: "E3700"}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [5967]}`, ExposureBiasValue: `{Id: 9204, Val: ["0/10"]}`, LightSource: `{Id: 9208, Val: [0]}`, FocalLength: `{Id: 920A, Val: ["54/10"]}`, ColorSpace: `{Id: A001, Val: [1]}`, PixelYDimension: `{Id: A003, Val: [1536]}`, FileSource: `{Id: A300, Val: ""}`, Make: `{Id: 10F, Val: "NIKON"}`, DateTimeOriginal: `{Id: 9003, Val: "2007:06:06 16:15:25"}`, DateTimeDigitized: `{Id: 9004, Val: "2007:06:06 16:15:25"}`, PixelXDimension: `{Id: A002, Val: [2048]}`, InteroperabilityIFDPointer: `{Id: A005, Val: [1026]}`, SceneType: `{Id: A301, Val: ""}`, DigitalZoomRatio: `{Id: A404, Val: ["0/100"]}`, GainControl: `{Id: A407, Val: [0]}`, InteroperabilityIndex: `{Id: 1, Val: "R98"}`, ImageDescription: `{Id: 10E, Val: " "}`, Sharpness: `{Id: A40A, Val: [0]}`, Orientation: `{Id: 112, Val: [1]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [2]}`, ExifVersion: `{Id: 9000, Val: "0220"}`, MeteringMode: `{Id: 9207, Val: [5]}`, Flash: `{Id: 9209, Val: [24]}`, FocalLengthIn35mmFilm: `{Id: A405, Val: [35]}`, SubjectDistanceRange: `{Id: A40C, Val: [0]}`, YResolution: `{Id: 11B, Val: ["300/1"]}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [4596]}`, MaxApertureValue: `{Id: 9205, Val: ["30/10"]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, WhiteBalance: `{Id: A403, Val: [0]}`, MakerNote: `{Id: 927C, Val: ""}`, UserComment: `{Id: 9286, Val: " "}`, CustomRendered: `{Id: A401, Val: [0]}`, ExposureMode: `{Id: A402, Val: [0]}`, SceneCaptureType: `{Id: A406, Val: [0]}`, Contrast: `{Id: A408, Val: [0]}`, Software: `{Id: 131, Val: "E3700v1.2"}`, DateTime: `{Id: 132, Val: "2007:06:06 16:15:25"}`, FNumber: `{Id: 829D, Val: ["48/10"]}`, ExposureProgram: `{Id: 8822, Val: [2]}`, }, "2011-05-07-13-02-49-sep-2011-05-07-13-02-49a.jpg": map[FieldName]string{ ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [1]}`, ExifIFDPointer: `{Id: 8769, Val: [218]}`, SceneType: `{Id: A301, Val: ""}`, GPSTimeStamp: `{Id: 7, Val: ["19/1","3/1","43/1"]}`, InteroperabilityIndex: `{Id: 1, Val: "R98"}`, YResolution: `{Id: 11B, Val: ["72/1"]}`, Software: `{Id: 131, Val: "M7500BSAAAAAAD3050"}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, GPSVersionID: `{Id: 0, Val: [2,2,0,0]}`, GPSMapDatum: `{Id: 12, Val: "WGS-84"}`, Make: `{Id: 10F, Val: "HTC"}`, GPSInfoIFDPointer: `{Id: 8825, Val: [502]}`, DateTimeOriginal: `{Id: 9003, Val: "2011:05:07 13:02:49"}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, InteroperabilityIFDPointer: `{Id: A005, Val: [472]}`, Contrast: `{Id: A408, Val: [0]}`, GPSLongitudeRef: `{Id: 3, Val: "E"}`, GPSProcessingMethod: `{Id: 1B, Val: "ASCIIHYBRID-FIX"}`, ColorSpace: `{Id: A001, Val: [1]}`, FileSource: `{Id: A300, Val: ""}`, WhiteBalance: `{Id: A403, Val: [0]}`, GPSAltitudeRef: `{Id: 5, Val: [0]}`, DateTimeDigitized: `{Id: 9004, Val: "2011:05:07 13:02:49"}`, PixelXDimension: `{Id: A002, Val: [2048]}`, GPSLatitude: `{Id: 2, Val: ["0/1","0/1","0/100"]}`, Model: `{Id: 110, Val: "RAPH800"}`, PixelYDimension: `{Id: A003, Val: [1536]}`, GPSLatitudeRef: `{Id: 1, Val: "N"}`, GPSLongitude: `{Id: 4, Val: ["0/1","0/1","0/100"]}`, Orientation: `{Id: 112, Val: [1]}`, XResolution: `{Id: 11A, Val: ["72/1"]}`, ExifVersion: `{Id: 9000, Val: "0220"}`, GPSAltitude: `{Id: 6, Val: ["0/1"]}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [920]}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [22806]}`, GPSDateStamp: `{Id: 1D, Val: "2011:05:07 "}`, }, "2007-11-07-11-40-44-sep-2007-11-07-11-40-44a.jpg": map[FieldName]string{ Make: `{Id: 10F, Val: "FUJIFILM"}`, DateTimeDigitized: `{Id: 9004, Val: "2007:11:07 11:40:44"}`, PixelXDimension: `{Id: A002, Val: [2592]}`, InteroperabilityIFDPointer: `{Id: A005, Val: [1158]}`, CustomRendered: `{Id: A401, Val: [1]}`, ExposureMode: `{Id: A402, Val: [0]}`, InteroperabilityIndex: `{Id: 1, Val: "R98"}`, DateTime: `{Id: 132, Val: "2007:11:07 11:40:44"}`, ExposureProgram: `{Id: 8822, Val: [2]}`, XResolution: `{Id: 11A, Val: ["72/1"]}`, ISOSpeedRatings: `{Id: 8827, Val: [64]}`, ExifVersion: `{Id: 9000, Val: "0220"}`, CompressedBitsPerPixel: `{Id: 9102, Val: ["20/10"]}`, Flash: `{Id: 9209, Val: [16]}`, Model: `{Id: 110, Val: "FinePix Z1 "}`, Copyright: `{Id: 8298, Val: " "}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [1306]}`, MaxApertureValue: `{Id: 9205, Val: ["360/100"]}`, LightSource: `{Id: 9208, Val: [0]}`, FocalLength: `{Id: 920A, Val: ["610/100"]}`, ColorSpace: `{Id: A001, Val: [1]}`, FocalPlaneXResolution: `{Id: A20E, Val: ["4442/1"]}`, DateTimeOriginal: `{Id: 9003, Val: "2007:11:07 11:40:44"}`, BrightnessValue: `{Id: 9203, Val: ["906/100"]}`, MakerNote: `{Id: 927C, Val: ""}`, SensingMethod: `{Id: A217, Val: [2]}`, SceneType: `{Id: A301, Val: ""}`, SceneCaptureType: `{Id: A406, Val: [0]}`, Software: `{Id: 131, Val: "Digital Camera FinePix Z1 Ver1.00"}`, FNumber: `{Id: 829D, Val: ["800/100"]}`, FocalPlaneResolutionUnit: `{Id: A210, Val: [3]}`, Sharpness: `{Id: A40A, Val: [0]}`, Orientation: `{Id: 112, Val: [1]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [2]}`, ExifIFDPointer: `{Id: 8769, Val: [294]}`, ExposureTime: `{Id: 829A, Val: ["10/2000"]}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, MeteringMode: `{Id: 9207, Val: [5]}`, FocalPlaneYResolution: `{Id: A20F, Val: ["4442/1"]}`, SubjectDistanceRange: `{Id: A40C, Val: [0]}`, YResolution: `{Id: 11B, Val: ["72/1"]}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [9900]}`, ShutterSpeedValue: `{Id: 9201, Val: ["764/100"]}`, ApertureValue: `{Id: 9202, Val: ["600/100"]}`, ExposureBiasValue: `{Id: 9204, Val: ["0/100"]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, PixelYDimension: `{Id: A003, Val: [1944]}`, FileSource: `{Id: A300, Val: ""}`, WhiteBalance: `{Id: A403, Val: [0]}`, }, "2008-09-02-17-43-48-sep-2008-09-02-17-43-48a.jpg": map[FieldName]string{ ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [2]}`, ExifIFDPointer: `{Id: 8769, Val: [302]}`, DateTimeDigitized: `{Id: 9004, Val: "2008:09:02 17:43:48"}`, PixelXDimension: `{Id: A002, Val: [1280]}`, InteroperabilityIndex: `{Id: 1, Val: "R98"}`, ImageDescription: `{Id: 10E, Val: " "}`, Model: `{Id: 110, Val: "Z550a"}`, YResolution: `{Id: 11B, Val: ["72/1"]}`, Software: `{Id: 131, Val: "R6GA004 prgCXC1250583_GENERIC_M 2.0"}`, DateTime: `{Id: 132, Val: "2008:09:02 17:43:48"}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, PixelYDimension: `{Id: A003, Val: [1024]}`, Make: `{Id: 10F, Val: "Sony Ericsson"}`, Orientation: `{Id: 112, Val: [1]}`, XResolution: `{Id: 11A, Val: ["72/1"]}`, ExifVersion: `{Id: 9000, Val: "0220"}`, DateTimeOriginal: `{Id: 9003, Val: "2008:09:02 17:43:48"}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, InteroperabilityIFDPointer: `{Id: A005, Val: [612]}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [748]}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [4641]}`, ColorSpace: `{Id: A001, Val: [1]}`, }, "2012-12-19-21-38-40-sep-temple_square1.jpg": map[FieldName]string{ Make: `{Id: 10F, Val: "HTC"}`, XResolution: `{Id: 11A, Val: ["72/1"]}`, ISOSpeedRatings: `{Id: 8827, Val: [801]}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, InteroperabilityIFDPointer: `{Id: A005, Val: [322]}`, GPSProcessingMethod: `{Id: 1B, Val: "ASCIIGPS"}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [1]}`, DateTimeDigitized: `{Id: 9004, Val: "2012:12:19 21:38:40"}`, PixelXDimension: `{Id: A002, Val: [3264]}`, GPSLatitude: `{Id: 2, Val: ["40/1","46/1","1322/100"]}`, YResolution: `{Id: 11B, Val: ["72/1"]}`, FocalLength: `{Id: 920A, Val: ["457/100"]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, PixelYDimension: `{Id: A003, Val: [1952]}`, GPSLongitude: `{Id: 4, Val: ["111/1","53/1","2840/100"]}`, GPSInfoIFDPointer: `{Id: 8825, Val: [352]}`, ExifVersion: `{Id: 9000, Val: "0220"}`, DateTimeOriginal: `{Id: 9003, Val: "2012:12:19 21:38:40"}`, GPSLongitudeRef: `{Id: 3, Val: "W"}`, GPSAltitude: `{Id: 6, Val: ["1334/1"]}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [696]}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [38469]}`, ColorSpace: `{Id: A001, Val: [1]}`, GPSAltitudeRef: `{Id: 5, Val: [0]}`, GPSDateStamp: `{Id: 1D, Val: "2012:12:20"}`, ExifIFDPointer: `{Id: 8769, Val: [136]}`, GPSTimeStamp: `{Id: 7, Val: ["4/1","38/1","40/1"]}`, InteroperabilityIndex: `{Id: 1, Val: "R98"}`, Model: `{Id: 110, Val: "ADR6400L"}`, GPSVersionID: `{Id: 0, Val: [2,2,0]}`, GPSLatitudeRef: `{Id: 1, Val: "N"}`, GPSMapDatum: `{Id: 12, Val: "WGS-84"}`, }, "2009-08-05-08-11-31-sep-2009-08-05-08-11-31a.jpg": map[FieldName]string{ DateTimeDigitized: `{Id: 9004, Val: "2009:08:05 08:11:31"}`, CompressedBitsPerPixel: `{Id: 9102, Val: ["20/10"]}`, BrightnessValue: `{Id: 9203, Val: ["719/100"]}`, MeteringMode: `{Id: 9207, Val: [5]}`, MakerNote: `{Id: 927C, Val: "FUJIFILM0130" !"#,012NORMAL d"}`, PixelXDimension: `{Id: A002, Val: [2848]}`, SensingMethod: `{Id: A217, Val: [2]}`, SubjectDistanceRange: `{Id: A40C, Val: [0]}`, Model: `{Id: 110, Val: "FinePix E550 "}`, Copyright: `{Id: 8298, Val: " "}`, ExposureBiasValue: `{Id: 9204, Val: ["0/100"]}`, PixelYDimension: `{Id: A003, Val: [2136]}`, FocalPlaneResolutionUnit: `{Id: A210, Val: [3]}`, Orientation: `{Id: 112, Val: [1]}`, XResolution: `{Id: 11A, Val: ["72/1"]}`, ISOSpeedRatings: `{Id: 8827, Val: [100]}`, ExifVersion: `{Id: 9000, Val: "0220"}`, Flash: `{Id: 9209, Val: [16]}`, FocalPlaneYResolution: `{Id: A20F, Val: ["5292/1"]}`, CustomRendered: `{Id: A401, Val: [0]}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [1306]}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [8596]}`, ExposureProgram: `{Id: 8822, Val: [2]}`, MaxApertureValue: `{Id: 9205, Val: ["300/100"]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [2]}`, ExifIFDPointer: `{Id: 8769, Val: [294]}`, ExposureTime: `{Id: 829A, Val: ["10/3000"]}`, SceneType: `{Id: A301, Val: ""}`, InteroperabilityIndex: `{Id: 1, Val: "R98"}`, YResolution: `{Id: 11B, Val: ["72/1"]}`, Software: `{Id: 131, Val: "Digital Camera FinePix E550 Ver1.00"}`, DateTime: `{Id: 132, Val: "2009:08:05 08:11:31"}`, ShutterSpeedValue: `{Id: 9201, Val: ["820/100"]}`, ApertureValue: `{Id: 9202, Val: ["400/100"]}`, LightSource: `{Id: 9208, Val: [0]}`, FocalLength: `{Id: 920A, Val: ["720/100"]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, FocalPlaneXResolution: `{Id: A20E, Val: ["5292/1"]}`, Make: `{Id: 10F, Val: "FUJIFILM"}`, DateTimeOriginal: `{Id: 9003, Val: "2009:08:05 08:11:31"}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, InteroperabilityIFDPointer: `{Id: A005, Val: [1158]}`, ExposureMode: `{Id: A402, Val: [0]}`, SceneCaptureType: `{Id: A406, Val: [0]}`, FNumber: `{Id: 829D, Val: ["400/100"]}`, ColorSpace: `{Id: A001, Val: [1]}`, FileSource: `{Id: A300, Val: ""}`, WhiteBalance: `{Id: A403, Val: [1]}`, Sharpness: `{Id: A40A, Val: [0]}`, }, "2007-01-01-12-00-00-sep-2007-01-01-12-00-00a.jpg": map[FieldName]string{ FNumber: `{Id: 829D, Val: ["270/100"]}`, ColorSpace: `{Id: A001, Val: [1]}`, FileSource: `{Id: A300, Val: ""}`, WhiteBalance: `{Id: A403, Val: [0]}`, Sharpness: `{Id: A40A, Val: [0]}`, DateTimeDigitized: `{Id: 9004, Val: "2007:01:01 12:00:00"}`, MeteringMode: `{Id: 9207, Val: [5]}`, MakerNote: `{Id: 927C, Val: ""}`, PixelXDimension: `{Id: A002, Val: [1280]}`, SensingMethod: `{Id: A217, Val: [2]}`, GainControl: `{Id: A407, Val: [2]}`, Saturation: `{Id: A409, Val: [0]}`, SubjectDistanceRange: `{Id: A40C, Val: [0]}`, Model: `{Id: 110, Val: "KODAK EASYSHARE C713 ZOOM DIGITAL CAMERA"}`, ExposureBiasValue: `{Id: 9204, Val: ["0/10"]}`, PixelYDimension: `{Id: A003, Val: [960]}`, Orientation: `{Id: 112, Val: [1]}`, XResolution: `{Id: 11A, Val: ["480/1"]}`, ISOSpeedRatings: `{Id: 8827, Val: [200]}`, ExifVersion: `{Id: 9000, Val: "0221"}`, Flash: `{Id: 9209, Val: [25]}`, CustomRendered: `{Id: A401, Val: [0]}`, DigitalZoomRatio: `{Id: A404, Val: ["0/10"]}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [13848]}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [3436]}`, ExposureProgram: `{Id: 8822, Val: [2]}`, MaxApertureValue: `{Id: 9205, Val: ["286/100"]}`, ExposureIndex: `{Id: A215, Val: ["200/1"]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [2]}`, ExifIFDPointer: `{Id: 8769, Val: [340]}`, ExposureTime: `{Id: 829A, Val: ["8942/1000000"]}`, SceneType: `{Id: A301, Val: ""}`, InteroperabilityIndex: `{Id: 1, Val: "R98"}`, YResolution: `{Id: 11B, Val: ["480/1"]}`, Software: `{Id: 131, Val: "KODAK EASYSHARE C713 ZOOM DIGITAL CAMERA"}`, ShutterSpeedValue: `{Id: 9201, Val: ["680/100"]}`, ApertureValue: `{Id: 9202, Val: ["286/100"]}`, LightSource: `{Id: 9208, Val: [0]}`, FocalLength: `{Id: 920A, Val: ["60/10"]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, Make: `{Id: 10F, Val: "EASTMAN KODAK COMPANY"}`, DateTimeOriginal: `{Id: 9003, Val: "2007:01:01 12:00:00"}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, InteroperabilityIFDPointer: `{Id: A005, Val: [13816]}`, ExposureMode: `{Id: A402, Val: [0]}`, FocalLengthIn35mmFilm: `{Id: A405, Val: [36]}`, SceneCaptureType: `{Id: A406, Val: [0]}`, Contrast: `{Id: A408, Val: [0]}`, }, "2007-08-15-14-42-46-sep-2007-08-15-14-42-46a.jpg": map[FieldName]string{ ExposureMode: `{Id: A402, Val: [0]}`, ExifVersion: `{Id: 9000, Val: "0221"}`, DateTimeOriginal: `{Id: 9003, Val: "2007:08:15 14:42:46"}`, Flash: `{Id: 9209, Val: [24]}`, WhiteBalance: `{Id: A403, Val: [0]}`, Sharpness: `{Id: A40A, Val: [0]}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [8472]}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [3060]}`, MaxApertureValue: `{Id: 9205, Val: ["37/10"]}`, ColorSpace: `{Id: A001, Val: [1]}`, ExposureIndex: `{Id: A215, Val: ["80/1"]}`, ExifIFDPointer: `{Id: 8769, Val: [320]}`, GainControl: `{Id: A407, Val: [0]}`, Saturation: `{Id: A409, Val: [0]}`, SubjectDistanceRange: `{Id: A40C, Val: [0]}`, ExposureTime: `{Id: 829A, Val: ["1/160"]}`, MeteringMode: `{Id: 9207, Val: [5]}`, Model: `{Id: 110, Val: "KODAK C663 ZOOM DIGITAL CAMERA"}`, ShutterSpeedValue: `{Id: 9201, Val: ["73/10"]}`, Make: `{Id: 10F, Val: "EASTMAN KODAK COMPANY"}`, Orientation: `{Id: 112, Val: [1]}`, XResolution: `{Id: 11A, Val: ["230/1"]}`, CustomRendered: `{Id: A401, Val: [0]}`, DigitalZoomRatio: `{Id: A404, Val: ["0/100"]}`, FocalLengthIn35mmFilm: `{Id: A405, Val: [66]}`, SceneCaptureType: `{Id: A406, Val: [0]}`, Contrast: `{Id: A408, Val: [0]}`, ISOSpeedRatings: `{Id: 8827, Val: [80]}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, FNumber: `{Id: 829D, Val: ["36/10"]}`, ExposureProgram: `{Id: 8822, Val: [2]}`, FileSource: `{Id: A300, Val: ""}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [1]}`, DateTimeDigitized: `{Id: 9004, Val: "2007:08:15 14:42:46"}`, MakerNote: `{Id: 927C, Val: ""}`, PixelXDimension: `{Id: A002, Val: [2832]}`, SensingMethod: `{Id: A217, Val: [2]}`, SceneType: `{Id: A301, Val: ""}`, YResolution: `{Id: 11B, Val: ["230/1"]}`, ApertureValue: `{Id: 9202, Val: ["37/10"]}`, ExposureBiasValue: `{Id: 9204, Val: ["0/3"]}`, LightSource: `{Id: 9208, Val: [0]}`, FocalLength: `{Id: 920A, Val: ["110/10"]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, PixelYDimension: `{Id: A003, Val: [2128]}`, }, "2007-02-02-18-13-29-sep-2007-02-02-18-13-29a.jpg": map[FieldName]string{ Make: `{Id: 10F, Val: "PENTAX Corporation "}`, DateTimeDigitized: `{Id: 9004, Val: "2007:02:02 18:13:29"}`, PixelXDimension: `{Id: A002, Val: [2560]}`, InteroperabilityIFDPointer: `{Id: A005, Val: [30974]}`, CustomRendered: `{Id: A401, Val: [0]}`, ExposureMode: `{Id: A402, Val: [0]}`, InteroperabilityIndex: `{Id: 1, Val: "R98"}`, DateTime: `{Id: 132, Val: "2007:02:02 18:13:29"}`, ExposureProgram: `{Id: 8822, Val: [2]}`, XResolution: `{Id: 11A, Val: ["72/1"]}`, ISOSpeedRatings: `{Id: 8827, Val: [200]}`, ExifVersion: `{Id: 9000, Val: "0220"}`, CompressedBitsPerPixel: `{Id: 9102, Val: ["27033600/4915200"]}`, Flash: `{Id: 9209, Val: [25]}`, FocalLengthIn35mmFilm: `{Id: A405, Val: [35]}`, Saturation: `{Id: A409, Val: [0]}`, Model: `{Id: 110, Val: "PENTAX Optio S5z "}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [31098]}`, MaxApertureValue: `{Id: 9205, Val: ["28/10"]}`, FocalLength: `{Id: 920A, Val: ["580/100"]}`, ColorSpace: `{Id: A001, Val: [1]}`, DateTimeOriginal: `{Id: 9003, Val: "2007:02:02 18:13:29"}`, MakerNote: `{Id: 927C, Val: ""}`, DigitalZoomRatio: `{Id: A404, Val: ["0/0"]}`, SceneCaptureType: `{Id: A406, Val: [0]}`, Contrast: `{Id: A408, Val: [0]}`, Software: `{Id: 131, Val: "Optio S5z Ver 1.00 "}`, FNumber: `{Id: 829D, Val: ["26/10"]}`, Sharpness: `{Id: A40A, Val: [0]}`, Orientation: `{Id: 112, Val: [1]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [1]}`, ExifIFDPointer: `{Id: 8769, Val: [586]}`, ExposureTime: `{Id: 829A, Val: ["1/60"]}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, MeteringMode: `{Id: 9207, Val: [5]}`, SubjectDistanceRange: `{Id: A40C, Val: [2]}`, YResolution: `{Id: 11B, Val: ["72/1"]}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [8800]}`, ExposureBiasValue: `{Id: 9204, Val: ["0/3"]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, PixelYDimension: `{Id: A003, Val: [1920]}`, WhiteBalance: `{Id: A403, Val: [0]}`, }, "2012-09-21-22-07-34-sep-2012-09-21-22-07-34.jpg": map[FieldName]string{ XResolution: `{Id: 11A, Val: ["180/1"]}`, ExifIFDPointer: `{Id: 8769, Val: [240]}`, ExposureTime: `{Id: 829A, Val: ["1/60"]}`, ISOSpeedRatings: `{Id: 8827, Val: [500]}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, CompressedBitsPerPixel: `{Id: 9102, Val: ["3/1"]}`, Model: `{Id: 110, Val: "Canon PowerShot SD940 IS"}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [4855]}`, ShutterSpeedValue: `{Id: 9201, Val: ["189/32"]}`, ExposureBiasValue: `{Id: 9204, Val: ["0/3"]}`, FocalLength: `{Id: 920A, Val: ["5000/1000"]}`, ColorSpace: `{Id: A001, Val: [1]}`, PixelYDimension: `{Id: A003, Val: [2448]}`, FocalPlaneXResolution: `{Id: A20E, Val: ["3264000/244"]}`, FileSource: `{Id: A300, Val: ""}`, Make: `{Id: 10F, Val: "Canon"}`, DateTimeOriginal: `{Id: 9003, Val: "2012:09:21 22:07:34"}`, DateTimeDigitized: `{Id: 9004, Val: "2012:09:21 22:07:34"}`, PixelXDimension: `{Id: A002, Val: [3264]}`, InteroperabilityIFDPointer: `{Id: A005, Val: [3288]}`, DigitalZoomRatio: `{Id: A404, Val: ["4000/4000"]}`, InteroperabilityIndex: `{Id: 1, Val: "R98"}`, ImageDescription: `{Id: 10E, Val: " "}`, FocalPlaneResolutionUnit: `{Id: A210, Val: [2]}`, Orientation: `{Id: 112, Val: [1]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [2]}`, ExifVersion: `{Id: 9000, Val: "0221"}`, MeteringMode: `{Id: 9207, Val: [5]}`, Flash: `{Id: 9209, Val: [25]}`, FocalPlaneYResolution: `{Id: A20F, Val: ["2448000/183"]}`, YResolution: `{Id: 11B, Val: ["180/1"]}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [5108]}`, ApertureValue: `{Id: 9202, Val: ["95/32"]}`, MaxApertureValue: `{Id: 9205, Val: ["95/32"]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, WhiteBalance: `{Id: A403, Val: [0]}`, MakerNote: `{Id: 927C, Val: ""}`, UserComment: `{Id: 9286, Val: ""}`, SensingMethod: `{Id: A217, Val: [2]}`, CustomRendered: `{Id: A401, Val: [0]}`, ExposureMode: `{Id: A402, Val: [0]}`, SceneCaptureType: `{Id: A406, Val: [2]}`, DateTime: `{Id: 132, Val: "2012:09:21 22:07:34"}`, FNumber: `{Id: 829D, Val: ["28/10"]}`, }, "2009-04-23-07-21-35-sep-2009-04-23-07-21-35a.jpg": map[FieldName]string{ FNumber: `{Id: 829D, Val: ["26/10"]}`, ColorSpace: `{Id: A001, Val: [1]}`, WhiteBalance: `{Id: A403, Val: [0]}`, Sharpness: `{Id: A40A, Val: [0]}`, DateTimeDigitized: `{Id: 9004, Val: "2009:04:23 07:21:35"}`, CompressedBitsPerPixel: `{Id: 9102, Val: ["13301888/4915200"]}`, MeteringMode: `{Id: 9207, Val: [5]}`, MakerNote: `{Id: 927C, Val: ""}`, PixelXDimension: `{Id: A002, Val: [2560]}`, Saturation: `{Id: A409, Val: [0]}`, SubjectDistanceRange: `{Id: A40C, Val: [3]}`, Model: `{Id: 110, Val: "PENTAX Optio S50"}`, ExposureBiasValue: `{Id: 9204, Val: ["0/10"]}`, PixelYDimension: `{Id: A003, Val: [1920]}`, Orientation: `{Id: 112, Val: [1]}`, XResolution: `{Id: 11A, Val: ["72/1"]}`, ISOSpeedRatings: `{Id: 8827, Val: [100]}`, ExifVersion: `{Id: 9000, Val: "0220"}`, Flash: `{Id: 9209, Val: [9]}`, CustomRendered: `{Id: A401, Val: [0]}`, DigitalZoomRatio: `{Id: A404, Val: ["0/100"]}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [31176]}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [6015]}`, MaxApertureValue: `{Id: 9205, Val: ["28/10"]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [2]}`, ExifIFDPointer: `{Id: 8769, Val: [590]}`, ExposureTime: `{Id: 829A, Val: ["1/40"]}`, InteroperabilityIndex: `{Id: 1, Val: "R98"}`, YResolution: `{Id: 11B, Val: ["72/1"]}`, Software: `{Id: 131, Val: "Optio S50 Ver 1.00"}`, DateTime: `{Id: 132, Val: "2009:04:23 07:21:35"}`, FocalLength: `{Id: 920A, Val: ["58/10"]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, Make: `{Id: 10F, Val: "PENTAX Corporation"}`, DateTimeOriginal: `{Id: 9003, Val: "2009:04:23 07:21:35"}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, InteroperabilityIFDPointer: `{Id: A005, Val: [31040]}`, ExposureMode: `{Id: A402, Val: [0]}`, FocalLengthIn35mmFilm: `{Id: A405, Val: [35]}`, SceneCaptureType: `{Id: A406, Val: [0]}`, Contrast: `{Id: A408, Val: [0]}`, }, "f3-exif.jpg": map[FieldName]string{ Orientation: `{Id: 112, Val: [3]}`, XResolution: `{Id: 11A, Val: ["72/1"]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [1]}`, ExifIFDPointer: `{Id: 8769, Val: [134]}`, ExifVersion: `{Id: 9000, Val: "0210"}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, PixelXDimension: `{Id: A002, Val: [0]}`, YResolution: `{Id: 11B, Val: ["72/1"]}`, DateTime: `{Id: 132, Val: "2012:11:04 05:42:32"}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, ColorSpace: `{Id: A001, Val: [65535]}`, PixelYDimension: `{Id: A003, Val: [0]}`, }, "2011-01-24-22-06-02-sep-2011-01-24-22-06-02a.jpg": map[FieldName]string{ Make: `{Id: 10F, Val: "Nokia"}`, Orientation: `{Id: 112, Val: [1]}`, XResolution: `{Id: 11A, Val: ["300/1"]}`, ExifVersion: `{Id: 9000, Val: "0220"}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, CustomRendered: `{Id: A401, Val: [0]}`, ExposureMode: `{Id: A402, Val: [0]}`, SceneCaptureType: `{Id: A406, Val: [0]}`, DigitalZoomRatio: `{Id: A404, Val: ["1024/1024"]}`, DateTimeOriginal: `{Id: 9003, Val: "2011:01:24 22:06:02"}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [25601]}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [3385]}`, ColorSpace: `{Id: A001, Val: [1]}`, WhiteBalance: `{Id: A403, Val: [0]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [1]}`, ExifIFDPointer: `{Id: 8769, Val: [157]}`, PixelXDimension: `{Id: A002, Val: [1200]}`, MakerNote: `{Id: 927C, Val: ""}`, DateTimeDigitized: `{Id: 9004, Val: "2011:01:24 22:06:02"}`, Model: `{Id: 110, Val: "6350"}`, YResolution: `{Id: 11B, Val: ["300/1"]}`, Software: `{Id: 131, Val: "V 12.40"}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, PixelYDimension: `{Id: A003, Val: [1600]}`, }, "f4-exif.jpg": map[FieldName]string{ Orientation: `{Id: 112, Val: [4]}`, XResolution: `{Id: 11A, Val: ["72/1"]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [1]}`, ExifIFDPointer: `{Id: 8769, Val: [134]}`, ExifVersion: `{Id: 9000, Val: "0210"}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, PixelXDimension: `{Id: A002, Val: [0]}`, YResolution: `{Id: 11B, Val: ["72/1"]}`, DateTime: `{Id: 132, Val: "2012:11:04 05:42:32"}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, ColorSpace: `{Id: A001, Val: [65535]}`, PixelYDimension: `{Id: A003, Val: [0]}`, }, "2007-05-02-17-02-21-sep-2007-05-02-17-02-21a.jpg": map[FieldName]string{ XResolution: `{Id: 11A, Val: ["180/1"]}`, ExifIFDPointer: `{Id: 8769, Val: [196]}`, ExposureTime: `{Id: 829A, Val: ["1/60"]}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, CompressedBitsPerPixel: `{Id: 9102, Val: ["3/1"]}`, Model: `{Id: 110, Val: "Canon IXY DIGITAL 55"}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [6306]}`, ShutterSpeedValue: `{Id: 9201, Val: ["189/32"]}`, ExposureBiasValue: `{Id: 9204, Val: ["0/3"]}`, FocalLength: `{Id: 920A, Val: ["7109/1000"]}`, ColorSpace: `{Id: A001, Val: [1]}`, PixelYDimension: `{Id: A003, Val: [1200]}`, FocalPlaneXResolution: `{Id: A20E, Val: ["1600000/225"]}`, FileSource: `{Id: A300, Val: ""}`, Make: `{Id: 10F, Val: "Canon"}`, DateTimeOriginal: `{Id: 9003, Val: "2007:05:02 17:02:21"}`, DateTimeDigitized: `{Id: 9004, Val: "2007:05:02 17:02:21"}`, PixelXDimension: `{Id: A002, Val: [1600]}`, InteroperabilityIFDPointer: `{Id: A005, Val: [2226]}`, DigitalZoomRatio: `{Id: A404, Val: ["2592/2592"]}`, InteroperabilityIndex: `{Id: 1, Val: "R98"}`, FocalPlaneResolutionUnit: `{Id: A210, Val: [2]}`, Orientation: `{Id: 112, Val: [1]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [1]}`, ExifVersion: `{Id: 9000, Val: "0220"}`, MeteringMode: `{Id: 9207, Val: [5]}`, Flash: `{Id: 9209, Val: [9]}`, FocalPlaneYResolution: `{Id: A20F, Val: ["1200000/168"]}`, YResolution: `{Id: 11B, Val: ["180/1"]}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [5108]}`, ApertureValue: `{Id: 9202, Val: ["107/32"]}`, MaxApertureValue: `{Id: 9205, Val: ["107/32"]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, WhiteBalance: `{Id: A403, Val: [0]}`, MakerNote: `{Id: 927C, Val: ""}`, UserComment: `{Id: 9286, Val: ""}`, SensingMethod: `{Id: A217, Val: [2]}`, CustomRendered: `{Id: A401, Val: [0]}`, ExposureMode: `{Id: A402, Val: [0]}`, SceneCaptureType: `{Id: A406, Val: [0]}`, DateTime: `{Id: 132, Val: "2007:05:02 17:02:21"}`, FNumber: `{Id: 829D, Val: ["32/10"]}`, }, "2010-06-20-20-07-39-sep-2010-06-20-20-07-39a.jpg": map[FieldName]string{ YResolution: `{Id: 11B, Val: ["4718592/65536"]}`, DateTime: `{Id: 132, Val: "2010:10:31 22:39:25"}`, ApertureValue: `{Id: 9202, Val: ["116/32"]}`, ExposureBiasValue: `{Id: 9204, Val: ["0/3"]}`, FocalLength: `{Id: 920A, Val: ["9681/1000"]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, PixelYDimension: `{Id: A003, Val: [2736]}`, FocalPlaneXResolution: `{Id: A20E, Val: ["3648000/241"]}`, ExifVersion: `{Id: 9000, Val: "0220"}`, DateTimeOriginal: `{Id: 9003, Val: "2010:06:20 20:07:39"}`, Flash: `{Id: 9209, Val: [16]}`, ExposureMode: `{Id: A402, Val: [0]}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [3408]}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [5126]}`, MaxApertureValue: `{Id: 9205, Val: ["116/32"]}`, ColorSpace: `{Id: A001, Val: [1]}`, WhiteBalance: `{Id: A403, Val: [0]}`, ExifIFDPointer: `{Id: 8769, Val: [302]}`, ExposureTime: `{Id: 829A, Val: ["1/10"]}`, CompressedBitsPerPixel: `{Id: 9102, Val: ["3/1"]}`, MeteringMode: `{Id: 9207, Val: [5]}`, UserComment: `{Id: 9286, Val: ""}`, ImageDescription: `{Id: 10E, Val: " "}`, Model: `{Id: 110, Val: "Canon PowerShot SD1200 IS"}`, Software: `{Id: 131, Val: "QuickTime 7.6.6"}`, ShutterSpeedValue: `{Id: 9201, Val: ["106/32"]}`, FocalPlaneResolutionUnit: `{Id: A210, Val: [2]}`, Make: `{Id: 10F, Val: "Canon"}`, Orientation: `{Id: 112, Val: [1]}`, XResolution: `{Id: 11A, Val: ["4718592/65536"]}`, ISOSpeedRatings: `{Id: 8827, Val: [800]}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, FocalPlaneYResolution: `{Id: A20F, Val: ["2736000/181"]}`, CustomRendered: `{Id: A401, Val: [0]}`, DigitalZoomRatio: `{Id: A404, Val: ["3648/3648"]}`, SceneCaptureType: `{Id: A406, Val: [0]}`, FNumber: `{Id: 829D, Val: ["35/10"]}`, FileSource: `{Id: A300, Val: ""}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [2]}`, DateTimeDigitized: `{Id: 9004, Val: "2010:06:20 20:07:39"}`, MakerNote: `{Id: 927C, Val: ""}`, PixelXDimension: `{Id: A002, Val: [3648]}`, SensingMethod: `{Id: A217, Val: [2]}`, }, "2099-08-12-19-59-29-sep-2099-08-12-19-59-29a.jpg": map[FieldName]string{ Orientation: `{Id: 112, Val: [1]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [2]}`, ExifVersion: `{Id: 9000, Val: "0221"}`, MeteringMode: `{Id: 9207, Val: [5]}`, Flash: `{Id: 9209, Val: [31]}`, FocalLengthIn35mmFilm: `{Id: A405, Val: [27]}`, SubjectDistanceRange: `{Id: A40C, Val: [0]}`, YResolution: `{Id: 11B, Val: ["300/1"]}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [28588]}`, MaxApertureValue: `{Id: 9205, Val: ["36/10"]}`, SubSecTimeDigitized: `{Id: 9292, Val: "00"}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, WhiteBalance: `{Id: A403, Val: [0]}`, MakerNote: `{Id: 927C, Val: ""}`, UserComment: `{Id: 9286, Val: "ASCII "}`, SubSecTime: `{Id: 9290, Val: "00"}`, SensingMethod: `{Id: A217, Val: [2]}`, CustomRendered: `{Id: A401, Val: [0]}`, ExposureMode: `{Id: A402, Val: [0]}`, SceneCaptureType: `{Id: A406, Val: [0]}`, Contrast: `{Id: A408, Val: [1]}`, Software: `{Id: 131, Val: "Ver.1.00 "}`, DateTime: `{Id: 132, Val: "2099:08:12 19:59:29"}`, FNumber: `{Id: 829D, Val: ["35/10"]}`, ExposureProgram: `{Id: 8822, Val: [0]}`, SubSecTimeOriginal: `{Id: 9291, Val: "00"}`, XResolution: `{Id: 11A, Val: ["300/1"]}`, ExifIFDPointer: `{Id: 8769, Val: [216]}`, ExposureTime: `{Id: 829A, Val: ["10/600"]}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, CompressedBitsPerPixel: `{Id: 9102, Val: ["2/1"]}`, Saturation: `{Id: A409, Val: [0]}`, Model: `{Id: 110, Val: "NIKON D70s"}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [8886]}`, ExposureBiasValue: `{Id: 9204, Val: ["0/6"]}`, LightSource: `{Id: 9208, Val: [0]}`, FocalLength: `{Id: 920A, Val: ["180/10"]}`, ColorSpace: `{Id: A001, Val: [1]}`, PixelYDimension: `{Id: A003, Val: [2000]}`, FileSource: `{Id: A300, Val: ""}`, Make: `{Id: 10F, Val: "NIKON CORPORATION"}`, DateTimeOriginal: `{Id: 9003, Val: "2099:08:12 19:59:29"}`, DateTimeDigitized: `{Id: 9004, Val: "2099:08:12 19:59:29"}`, PixelXDimension: `{Id: A002, Val: [3008]}`, InteroperabilityIFDPointer: `{Id: A005, Val: [28448]}`, SceneType: `{Id: A301, Val: ""}`, CFAPattern: `{Id: A302, Val: ""}`, DigitalZoomRatio: `{Id: A404, Val: ["1/1"]}`, GainControl: `{Id: A407, Val: [0]}`, InteroperabilityIndex: `{Id: 1, Val: "R98"}`, Sharpness: `{Id: A40A, Val: [0]}`, }, "2011-11-18-15-38-34-sep-Photo11181538.jpg": map[FieldName]string{ Make: `{Id: 10F, Val: "PANTECH"}`, Orientation: `{Id: 112, Val: [1]}`, XResolution: `{Id: 11A, Val: ["72/1"]}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, InteroperabilityIFDPointer: `{Id: A005, Val: [518]}`, CustomRendered: `{Id: A401, Val: [1]}`, DigitalZoomRatio: `{Id: A404, Val: ["0/0"]}`, Contrast: `{Id: A408, Val: [1]}`, ExposureProgram: `{Id: 8822, Val: [2]}`, FileSource: `{Id: A300, Val: ""}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [1]}`, DateTimeDigitized: `{Id: 9004, Val: "2011:11:18 15:38:34"}`, PixelXDimension: `{Id: A002, Val: [1600]}`, SceneType: `{Id: A301, Val: ""}`, YResolution: `{Id: 11B, Val: ["72/1"]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, PixelYDimension: `{Id: A003, Val: [1200]}`, ExifVersion: `{Id: 9000, Val: "0220"}`, DateTimeOriginal: `{Id: 9003, Val: "2011:11:18 15:38:34"}`, ExposureMode: `{Id: A402, Val: [0]}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [642]}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [12226]}`, ColorSpace: `{Id: A001, Val: [1]}`, WhiteBalance: `{Id: A403, Val: [0]}`, Sharpness: `{Id: A40A, Val: [0]}`, ExifIFDPointer: `{Id: 8769, Val: [204]}`, BrightnessValue: `{Id: 9203, Val: ["0/1024"]}`, MeteringMode: `{Id: 9207, Val: [2]}`, Saturation: `{Id: A409, Val: [0]}`, InteroperabilityIndex: `{Id: 1, Val: "R98"}`, Model: `{Id: 110, Val: "P2020"}`, Software: `{Id: 131, Val: "M6290A-KPVMZL-2.6.0140T"}`, }, "2009-06-20-07-59-05-sep-2009-06-20-07-59-05a.jpg": map[FieldName]string{ ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [1]}`, ExifIFDPointer: `{Id: 8769, Val: [514]}`, ExposureTime: `{Id: 829A, Val: ["1/500"]}`, SceneType: `{Id: A301, Val: ""}`, InteroperabilityIndex: `{Id: 1, Val: "R98"}`, YResolution: `{Id: 11B, Val: ["480/1"]}`, ShutterSpeedValue: `{Id: 9201, Val: ["9/1"]}`, ApertureValue: `{Id: 9202, Val: ["36/10"]}`, LightSource: `{Id: 9208, Val: [0]}`, FocalLength: `{Id: 920A, Val: ["559/10"]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, Make: `{Id: 10F, Val: "EASTMAN KODAK COMPANY"}`, DateTimeOriginal: `{Id: 9003, Val: "2009:06:20 07:59:05"}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, InteroperabilityIFDPointer: `{Id: A005, Val: [8728]}`, ExposureMode: `{Id: A402, Val: [0]}`, FocalLengthIn35mmFilm: `{Id: A405, Val: [337]}`, SceneCaptureType: `{Id: A406, Val: [0]}`, Contrast: `{Id: A408, Val: [0]}`, FNumber: `{Id: 829D, Val: ["35/10"]}`, ColorSpace: `{Id: A001, Val: [1]}`, FileSource: `{Id: A300, Val: ""}`, WhiteBalance: `{Id: A403, Val: [0]}`, Sharpness: `{Id: A40A, Val: [0]}`, DateTimeDigitized: `{Id: 9004, Val: "2009:06:20 07:59:05"}`, MeteringMode: `{Id: 9207, Val: [5]}`, MakerNote: `{Id: 927C, Val: ""}`, PixelXDimension: `{Id: A002, Val: [3072]}`, SensingMethod: `{Id: A217, Val: [2]}`, GainControl: `{Id: A407, Val: [2]}`, Saturation: `{Id: A409, Val: [0]}`, SubjectDistanceRange: `{Id: A40C, Val: [0]}`, Model: `{Id: 110, Val: "KODAK EASYSHARE Z710 ZOOM DIGITAL CAMERA"}`, ExposureBiasValue: `{Id: 9204, Val: ["0/3"]}`, PixelYDimension: `{Id: A003, Val: [2304]}`, Orientation: `{Id: 112, Val: [1]}`, XResolution: `{Id: 11A, Val: ["480/1"]}`, ISOSpeedRatings: `{Id: 8827, Val: [160]}`, ExifVersion: `{Id: 9000, Val: "0221"}`, Flash: `{Id: 9209, Val: [89]}`, CustomRendered: `{Id: A401, Val: [0]}`, DigitalZoomRatio: `{Id: A404, Val: ["0/100"]}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [9032]}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [4569]}`, ExposureProgram: `{Id: 8822, Val: [2]}`, MaxApertureValue: `{Id: 9205, Val: ["36/10"]}`, ExposureIndex: `{Id: A215, Val: ["160/1"]}`, }, "2011-10-28-17-50-18-sep-2011-10-28-17-50-18a.jpg": map[FieldName]string{ Make: `{Id: 10F, Val: "Canon"}`, DateTimeDigitized: `{Id: 9004, Val: "2011:10:28 17:50:18"}`, UserComment: `{Id: 9286, Val: ""}`, SubSecTime: `{Id: 9290, Val: "92"}`, PixelXDimension: `{Id: A002, Val: [576]}`, InteroperabilityIFDPointer: `{Id: A005, Val: [1120]}`, CustomRendered: `{Id: A401, Val: [0]}`, ExposureMode: `{Id: A402, Val: [0]}`, InteroperabilityIndex: `{Id: 1, Val: "R03"}`, DateTime: `{Id: 132, Val: "2011:11:08 07:27:55"}`, ExposureProgram: `{Id: 8822, Val: [2]}`, SubSecTimeOriginal: `{Id: 9291, Val: "92"}`, XResolution: `{Id: 11A, Val: ["720000/10000"]}`, ISOSpeedRatings: `{Id: 8827, Val: [800]}`, ExifVersion: `{Id: 9000, Val: "0221"}`, Flash: `{Id: 9209, Val: [9]}`, Model: `{Id: 110, Val: "Canon EOS 5D Mark II"}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [1266]}`, FocalLength: `{Id: 920A, Val: ["34/1"]}`, SubSecTimeDigitized: `{Id: 9292, Val: "92"}`, ColorSpace: `{Id: A001, Val: [65535]}`, FocalPlaneXResolution: `{Id: A20E, Val: ["5616000/1459"]}`, DateTimeOriginal: `{Id: 9003, Val: "2011:10:28 17:50:18"}`, SceneCaptureType: `{Id: A406, Val: [0]}`, Software: `{Id: 131, Val: "Adobe Photoshop CS4 Macintosh"}`, FNumber: `{Id: 829D, Val: ["4/1"]}`, FocalPlaneResolutionUnit: `{Id: A210, Val: [2]}`, GPSVersionID: `{Id: 0, Val: [2,2,0,0]}`, Orientation: `{Id: 112, Val: [1]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [2]}`, ExifIFDPointer: `{Id: 8769, Val: [364]}`, GPSInfoIFDPointer: `{Id: 8825, Val: [1152]}`, ExposureTime: `{Id: 829A, Val: ["1/60"]}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, MeteringMode: `{Id: 9207, Val: [5]}`, FocalPlaneYResolution: `{Id: A20F, Val: ["3744000/958"]}`, YResolution: `{Id: 11B, Val: ["720000/10000"]}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [6186]}`, ShutterSpeedValue: `{Id: 9201, Val: ["393216/65536"]}`, ApertureValue: `{Id: 9202, Val: ["262144/65536"]}`, ExposureBiasValue: `{Id: 9204, Val: ["0/1"]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, PixelYDimension: `{Id: A003, Val: [864]}`, WhiteBalance: `{Id: A403, Val: [1]}`, }, "2007-06-26-10-13-04-sep-2007-06-26-10-13-04a.jpg": map[FieldName]string{ XResolution: `{Id: 11A, Val: ["320/1"]}`, ExposureTime: `{Id: 829A, Val: ["23697424/268435456"]}`, ExifIFDPointer: `{Id: 8769, Val: [262]}`, ISOSpeedRatings: `{Id: 8827, Val: [100]}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, CompressedBitsPerPixel: `{Id: 9102, Val: ["6389872/3145728"]}`, RelatedSoundFile: `{Id: A004, Val: "RelatedSound"}`, Model: `{Id: 110, Val: "DV"}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [6292]}`, ShutterSpeedValue: `{Id: 9201, Val: ["7/1"]}`, ExposureBiasValue: `{Id: 9204, Val: ["1/4"]}`, LightSource: `{Id: 9208, Val: [0]}`, ColorSpace: `{Id: A001, Val: [1]}`, PixelYDimension: `{Id: A003, Val: [1536]}`, FileSource: `{Id: A300, Val: ""}`, Make: `{Id: 10F, Val: "CEC"}`, DateTimeOriginal: `{Id: 9003, Val: "2007:06:26 10:13:04"}`, DateTimeDigitized: `{Id: 9004, Val: "2007:06:26 10:13:04"}`, PixelXDimension: `{Id: A002, Val: [2048]}`, InteroperabilityIFDPointer: `{Id: A005, Val: [1170]}`, SceneType: `{Id: A301, Val: ""}`, InteroperabilityIndex: `{Id: 1, Val: "R98"}`, ImageDescription: `{Id: 10E, Val: "My beautiful picture"}`, Orientation: `{Id: 112, Val: [1]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [2]}`, ExifVersion: `{Id: 9000, Val: "0210"}`, MeteringMode: `{Id: 9207, Val: [2]}`, Flash: `{Id: 9209, Val: [0]}`, YResolution: `{Id: 11B, Val: ["384/1"]}`, Copyright: `{Id: 8298, Val: "Copyright2004"}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [1306]}`, ApertureValue: `{Id: 9202, Val: ["3/1"]}`, MaxApertureValue: `{Id: 9205, Val: ["3/1"]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, MakerNote: `{Id: 927C, Val: ""}`, SensingMethod: `{Id: A217, Val: [2]}`, Software: `{Id: 131, Val: "DVWare 1.0"}`, DateTime: `{Id: 132, Val: "2007:06:26 10:13:04"}`, FNumber: `{Id: 829D, Val: ["3/1"]}`, ExposureProgram: `{Id: 8822, Val: [3]}`, ExposureIndex: `{Id: A215, Val: ["146/1"]}`, }, "f5-exif.jpg": map[FieldName]string{ YResolution: `{Id: 11B, Val: ["72/1"]}`, DateTime: `{Id: 132, Val: "2012:11:04 05:42:32"}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, ColorSpace: `{Id: A001, Val: [65535]}`, PixelYDimension: `{Id: A003, Val: [0]}`, Orientation: `{Id: 112, Val: [5]}`, XResolution: `{Id: 11A, Val: ["72/1"]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [1]}`, ExifIFDPointer: `{Id: 8769, Val: [134]}`, ExifVersion: `{Id: 9000, Val: "0210"}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, PixelXDimension: `{Id: A002, Val: [0]}`, }, "2006-12-21-15-55-26-sep-2006-12-21-15-55-26a.jpg": map[FieldName]string{ Make: `{Id: 10F, Val: "SONY"}`, Orientation: `{Id: 112, Val: [1]}`, XResolution: `{Id: 11A, Val: ["72/1"]}`, ISOSpeedRatings: `{Id: 8827, Val: [100]}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, InteroperabilityIFDPointer: `{Id: A005, Val: [2278]}`, CustomRendered: `{Id: A401, Val: [0]}`, SceneCaptureType: `{Id: A406, Val: [0]}`, Contrast: `{Id: A408, Val: [0]}`, FNumber: `{Id: 829D, Val: ["28/10"]}`, ExposureProgram: `{Id: 8822, Val: [2]}`, FileSource: `{Id: A300, Val: ""}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [2]}`, DateTimeDigitized: `{Id: 9004, Val: "2006:12:21 15:55:26"}`, MakerNote: `{Id: 927C, Val: ""}`, PixelXDimension: `{Id: A002, Val: [2592]}`, SceneType: `{Id: A301, Val: ""}`, YResolution: `{Id: 11B, Val: ["72/1"]}`, DateTime: `{Id: 132, Val: "2006:12:21 15:55:26"}`, ExposureBiasValue: `{Id: 9204, Val: ["-20/10"]}`, LightSource: `{Id: 9208, Val: [0]}`, FocalLength: `{Id: 920A, Val: ["79/10"]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, PixelYDimension: `{Id: A003, Val: [1944]}`, ExifVersion: `{Id: 9000, Val: "0220"}`, DateTimeOriginal: `{Id: 9003, Val: "2006:12:21 15:55:26"}`, Flash: `{Id: 9209, Val: [79]}`, ExposureMode: `{Id: A402, Val: [1]}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [2484]}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [13571]}`, MaxApertureValue: `{Id: 9205, Val: ["48/16"]}`, ColorSpace: `{Id: A001, Val: [1]}`, WhiteBalance: `{Id: A403, Val: [0]}`, Sharpness: `{Id: A40A, Val: [0]}`, ExifIFDPointer: `{Id: 8769, Val: [256]}`, ExposureTime: `{Id: 829A, Val: ["10/400"]}`, CompressedBitsPerPixel: `{Id: 9102, Val: ["8/1"]}`, MeteringMode: `{Id: 9207, Val: [3]}`, Saturation: `{Id: A409, Val: [0]}`, InteroperabilityIndex: `{Id: 1, Val: "R98"}`, ImageDescription: `{Id: 10E, Val: " "}`, Model: `{Id: 110, Val: "DSC-W15"}`, }, "2010-09-02-08-43-02-sep-2010-09-02-08-43-02a.jpg": map[FieldName]string{ Orientation: `{Id: 112, Val: [1]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [2]}`, ExifVersion: `{Id: 9000, Val: "0221"}`, MeteringMode: `{Id: 9207, Val: [5]}`, Flash: `{Id: 9209, Val: [65]}`, YResolution: `{Id: 11B, Val: ["72/1"]}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [9204]}`, MaxApertureValue: `{Id: 9205, Val: ["362/100"]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, WhiteBalance: `{Id: A403, Val: [0]}`, MakerNote: `{Id: 927C, Val: ""}`, UserComment: `{Id: 9286, Val: " "}`, CustomRendered: `{Id: A401, Val: [0]}`, ExposureMode: `{Id: A402, Val: [0]}`, SceneCaptureType: `{Id: A406, Val: [3]}`, Contrast: `{Id: A408, Val: [0]}`, Software: `{Id: 131, Val: "Version 1.0 "}`, DateTime: `{Id: 132, Val: "2010:09:02 08:43:02"}`, FNumber: `{Id: 829D, Val: ["53/10"]}`, ExposureProgram: `{Id: 8822, Val: [5]}`, XResolution: `{Id: 11A, Val: ["72/1"]}`, ExifIFDPointer: `{Id: 8769, Val: [996]}`, ExposureTime: `{Id: 829A, Val: ["10/500"]}`, ISOSpeedRatings: `{Id: 8827, Val: [800]}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, CompressedBitsPerPixel: `{Id: 9102, Val: ["1/1"]}`, Saturation: `{Id: A409, Val: [0]}`, Model: `{Id: 110, Val: "FE370,X880,C575 "}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [3562]}`, ExposureBiasValue: `{Id: 9204, Val: ["0/10"]}`, LightSource: `{Id: 9208, Val: [0]}`, FocalLength: `{Id: 920A, Val: ["210/10"]}`, ColorSpace: `{Id: A001, Val: [1]}`, PixelYDimension: `{Id: A003, Val: [2448]}`, FileSource: `{Id: A300, Val: ""}`, Make: `{Id: 10F, Val: "OLYMPUS IMAGING CORP. "}`, DateTimeOriginal: `{Id: 9003, Val: "2010:09:02 08:43:02"}`, DateTimeDigitized: `{Id: 9004, Val: "2010:09:02 08:43:02"}`, PixelXDimension: `{Id: A002, Val: [3264]}`, InteroperabilityIFDPointer: `{Id: A005, Val: [1714]}`, SceneType: `{Id: A301, Val: ""}`, DigitalZoomRatio: `{Id: A404, Val: ["0/100"]}`, GainControl: `{Id: A407, Val: [2]}`, InteroperabilityIndex: `{Id: 1, Val: "R98"}`, ImageDescription: `{Id: 10E, Val: "OLYMPUS DIGITAL CAMERA "}`, Sharpness: `{Id: A40A, Val: [0]}`, }, "2011-08-07-19-22-57-sep-2011-08-07-19-22-57a.jpg": map[FieldName]string{ Make: `{Id: 10F, Val: "NIKON CORPORATION"}`, DateTimeDigitized: `{Id: 9004, Val: "2011:08:07 19:22:57"}`, CustomRendered: `{Id: A401, Val: [0]}`, ExposureMode: `{Id: A402, Val: [0]}`, DateTime: `{Id: 132, Val: "2011:08:11 09:46:32"}`, ExposureProgram: `{Id: 8822, Val: [3]}`, SubSecTimeOriginal: `{Id: 9291, Val: "65"}`, XResolution: `{Id: 11A, Val: ["300/1"]}`, ISOSpeedRatings: `{Id: 8827, Val: [400]}`, ExifVersion: `{Id: 9000, Val: "0221"}`, Flash: `{Id: 9209, Val: [7]}`, FocalLengthIn35mmFilm: `{Id: A405, Val: [93]}`, Saturation: `{Id: A409, Val: [0]}`, Model: `{Id: 110, Val: "NIKON D200"}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [802]}`, MaxApertureValue: `{Id: 9205, Val: ["43/10"]}`, LightSource: `{Id: 9208, Val: [0]}`, FocalLength: `{Id: 920A, Val: ["620/10"]}`, SubSecTimeDigitized: `{Id: 9292, Val: "65"}`, DateTimeOriginal: `{Id: 9003, Val: "2011:08:07 19:22:57"}`, SensingMethod: `{Id: A217, Val: [2]}`, SceneType: `{Id: A301, Val: ""}`, CFAPattern: `{Id: A302, Val: ""}`, DigitalZoomRatio: `{Id: A404, Val: ["1/1"]}`, SceneCaptureType: `{Id: A406, Val: [0]}`, GainControl: `{Id: A407, Val: [1]}`, Contrast: `{Id: A408, Val: [0]}`, Software: `{Id: 131, Val: "Ver.1.00"}`, FNumber: `{Id: 829D, Val: ["45/10"]}`, SubjectDistance: `{Id: 9206, Val: ["63/100"]}`, Sharpness: `{Id: A40A, Val: [0]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, ExifIFDPointer: `{Id: 8769, Val: [186]}`, ExposureTime: `{Id: 829A, Val: ["1/30"]}`, MeteringMode: `{Id: 9207, Val: [2]}`, SubjectDistanceRange: `{Id: A40C, Val: [0]}`, YResolution: `{Id: 11B, Val: ["300/1"]}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [9117]}`, ShutterSpeedValue: `{Id: 9201, Val: ["4906891/1000000"]}`, ApertureValue: `{Id: 9202, Val: ["433985/100000"]}`, ExposureBiasValue: `{Id: 9204, Val: ["2/6"]}`, FileSource: `{Id: A300, Val: ""}`, WhiteBalance: `{Id: A403, Val: [0]}`, }, "2011-03-07-09-28-03-sep-2011-03-07-09-28-03a.jpg": map[FieldName]string{ YResolution: `{Id: 11B, Val: ["72/1"]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, PixelYDimension: `{Id: A003, Val: [960]}`, ExifVersion: `{Id: 9000, Val: "0220"}`, DateTimeOriginal: `{Id: 9003, Val: "2011:03:07 09:28:03"}`, ExposureMode: `{Id: A402, Val: [0]}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [662]}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [9850]}`, ColorSpace: `{Id: A001, Val: [1]}`, WhiteBalance: `{Id: A403, Val: [0]}`, Sharpness: `{Id: A40A, Val: [0]}`, ExifIFDPointer: `{Id: 8769, Val: [224]}`, BrightnessValue: `{Id: 9203, Val: ["0/1024"]}`, MeteringMode: `{Id: 9207, Val: [2]}`, Saturation: `{Id: A409, Val: [0]}`, InteroperabilityIndex: `{Id: 1, Val: "R98"}`, Model: `{Id: 110, Val: "GU295"}`, Software: `{Id: 131, Val: "GU295-MSM1530032L-V10i-APR-22-2010-ATT-US"}`, Make: `{Id: 10F, Val: "LG Elec."}`, Orientation: `{Id: 112, Val: [1]}`, XResolution: `{Id: 11A, Val: ["72/1"]}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, InteroperabilityIFDPointer: `{Id: A005, Val: [538]}`, CustomRendered: `{Id: A401, Val: [1]}`, DigitalZoomRatio: `{Id: A404, Val: ["0/0"]}`, Contrast: `{Id: A408, Val: [0]}`, ExposureProgram: `{Id: 8822, Val: [2]}`, FileSource: `{Id: A300, Val: ""}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [1]}`, DateTimeDigitized: `{Id: 9004, Val: "2011:03:07 09:28:03"}`, PixelXDimension: `{Id: A002, Val: [1280]}`, SceneType: `{Id: A301, Val: ""}`, }, "2010-06-08-04-44-24-sep-2010-06-08-04-44-24a.jpg": map[FieldName]string{ Orientation: `{Id: 112, Val: [1]}`, ResolutionUnit: `{Id: 128, Val: [2]}`, YCbCrPositioning: `{Id: 213, Val: [2]}`, ExifVersion: `{Id: 9000, Val: "0221"}`, MeteringMode: `{Id: 9207, Val: [5]}`, Flash: `{Id: 9209, Val: [31]}`, YResolution: `{Id: 11B, Val: ["72/1"]}`, ThumbJPEGInterchangeFormat: `{Id: 201, Val: [6892]}`, MaxApertureValue: `{Id: 9205, Val: ["48/16"]}`, FlashpixVersion: `{Id: A000, Val: "0100"}`, WhiteBalance: `{Id: A403, Val: [0]}`, MakerNote: `{Id: 927C, Val: ""}`, CustomRendered: `{Id: A401, Val: [0]}`, ExposureMode: `{Id: A402, Val: [0]}`, SceneCaptureType: `{Id: A406, Val: [0]}`, Contrast: `{Id: A408, Val: [0]}`, DateTime: `{Id: 132, Val: "2010:06:08 04:44:24"}`, FNumber: `{Id: 829D, Val: ["28/10"]}`, ExposureProgram: `{Id: 8822, Val: [2]}`, XResolution: `{Id: 11A, Val: ["72/1"]}`, ExifIFDPointer: `{Id: 8769, Val: [2314]}`, ExposureTime: `{Id: 829A, Val: ["10/400"]}`, ISOSpeedRatings: `{Id: 8827, Val: [80]}`, ComponentsConfiguration: `{Id: 9101, Val: ""}`, CompressedBitsPerPixel: `{Id: 9102, Val: ["8/1"]}`, Saturation: `{Id: A409, Val: [0]}`, Model: `{Id: 110, Val: "DSC-S600"}`, ThumbJPEGInterchangeFormatLength: `{Id: 202, Val: [4029]}`, ExposureBiasValue: `{Id: 9204, Val: ["0/10"]}`, LightSource: `{Id: 9208, Val: [0]}`, FocalLength: `{Id: 920A, Val: ["51/10"]}`, ColorSpace: `{Id: A001, Val: [1]}`, PixelYDimension: `{Id: A003, Val: [2112]}`, FileSource: `{Id: A300, Val: ""}`, Make: `{Id: 10F, Val: "SONY"}`, DateTimeOriginal: `{Id: 9003, Val: "2010:06:08 04:44:24"}`, DateTimeDigitized: `{Id: 9004, Val: "2010:06:08 04:44:24"}`, PixelXDimension: `{Id: A002, Val: [2816]}`, InteroperabilityIFDPointer: `{Id: A005, Val: [6640]}`, SceneType: `{Id: A301, Val: ""}`, ImageDescription: `{Id: 10E, Val: " "}`, Sharpness: `{Id: A40A, Val: [0]}`, }, }
bsd-2-clause
kencoken/imsearch-tools
imsearchtools/utils/result_page_gen.py
5520
#!/usr/bin/env python """Retrieve ranking lists from Google Image search Uses either the Google AJAX API: http://code.google.com/apis/imagesearch/v1/ or direct page scraping to retrieve a ranked list of images returned from Google Image search for a given text query. Date created: 15 Oct 2012 """ import os.path RESULT_PAGE_HTML = ''' <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Search Result Visualization</title> <style> #result_container { } #result_container:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; } .result { float: left; padding: 5px; } .result img { height: 130px; } </style> </head> <body> <dl> <dt>Generator:</dt> <dd><!-- GENERATOR --></dd> <dt>Images returned:</dt> <dd><!-- IMAGE_COUNT --></dd> </dl> <div id="result_container"> <!-- RESULTS --> </div> </body> </html> ''' RESULT_HTML = ''' <div class="result"> <img src="<!-- RESULT_URL -->" alt="<!-- RESULT_TITLE -->" /> </div> ''' COMBINED_RESULT_PAGE_HTML = ''' <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Search Result Visualization</title> <style> #result_frames_container { } #result_frames_container>div { display: block; float: left; width: 200px; padding: 5px; border: 1px solid black; } #result_frames_container:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; } .result_img_container { height: 250px; } .result_img { max-width: 190px; max-height: 200px; } </style> <script src="http://code.jquery.com/jquery-latest.js"></script> </head> <body> <div id="result_frames_container"> <!-- RESULT_FRAMES --> </div> </body> </html> ''' RESULT_FRAME_HTML = ''' <div> <!-- RESULT_FRAME_HEADER --> <!-- RESULTS --> </div> ''' RESULT_FRAME_HEADER_HTML = ''' <dl> <dt>Generator:</dt> <dd><!-- GENERATOR --></dd> <dt>Images returned:</dt> <dd><!-- IMAGE_COUNT --></dd> </dl> ''' RESULT_IN_FRAME_HTML = ''' <div class="result_img_container"> <!-- RESULT_IDX --> <img class="result_img" src="<!-- RESULT_URL -->" alt="<!-- RESULT_TITLE -->" /> </div> ''' def gen_results_page(results, generator_name, output_filename, show_in_browser=True): result_page = RESULT_PAGE_HTML result_page = result_page.replace('<!-- GENERATOR -->', generator_name) result_page = result_page.replace('<!-- IMAGE_COUNT -->', str(len(results))) result_grid_code = '' for result in results: single_res_code = RESULT_HTML single_res_code = single_res_code.replace('<!-- RESULT_URL -->', result['url']) if result.has_key('title'): single_res_code = single_res_code.replace('<!-- RESULT_TITLE -->', result['title']) else: single_res_code = single_res_code.replace('<!-- RESULT_TITLE -->', result['image_id']) result_grid_code += single_res_code result_page = result_page.replace('<!-- RESULTS -->', result_grid_code) output = open(output_filename, 'w') output.write(result_page.encode('UTF-8')) output.close() if show_in_browser: import webbrowser webbrowser.open('file:///' + os.path.abspath(output_filename)) def combine_results_pages(results_arr, generator_name_arr, output_filename, show_in_browser=True): combined_page = COMBINED_RESULT_PAGE_HTML frames_code = '' for res_idx in range(len(results_arr)): frame_code = RESULT_FRAME_HTML results = results_arr[res_idx] generator_name = generator_name_arr[res_idx] result_grid_code = '' for res_idx, result in enumerate(results): single_res_code = RESULT_IN_FRAME_HTML single_res_code = single_res_code.replace('<!-- RESULT_IDX -->', str(res_idx+1)) single_res_code = single_res_code.replace('<!-- RESULT_URL -->', result['url']) if result.has_key('title'): single_res_code = single_res_code.replace('<!-- RESULT_TITLE -->', result['title']) else: single_res_code = single_res_code.replace('<!-- RESULT_TITLE -->', result['image_id']) result_grid_code += single_res_code result_frame_header_code = RESULT_FRAME_HEADER_HTML result_frame_header_code = result_frame_header_code.replace('<!-- GENERATOR -->', generator_name) result_frame_header_code = result_frame_header_code.replace('<!-- IMAGE_COUNT -->', str(len(results))) frame_code = frame_code.replace('<!-- RESULT_FRAME_HEADER -->', result_frame_header_code) frame_code = frame_code.replace('<!-- RESULTS -->', result_grid_code) frames_code += frame_code combined_page = combined_page.replace('<!-- RESULT_FRAMES -->', frames_code) output = open(output_filename, 'w') output.write(combined_page.encode('UTF-8')) output.close() if show_in_browser: import webbrowser webbrowser.open('file:///' + os.path.abspath(output_filename))
bsd-2-clause
babelsberg/babelsberg-r
topaz/utils/ll_dir.py
1991
from rpython.rlib import rposix from rpython.rtyper.lltypesystem import rffi, lltype from rpython.rtyper.tool import rffi_platform as platform from rpython.translator.tool.cbuild import ExternalCompilationInfo from topaz.system import IS_WINDOWS if IS_WINDOWS: def opendir(_): raise NotImplementedError("directory operations on windows") readdir = closedir = opendir else: eci = ExternalCompilationInfo( includes=["sys/types.h", "dirent.h"] ) class CConfig: _compilation_info_ = eci DIRENT = platform.Struct("struct dirent", [ ("d_name", lltype.FixedSizeArray(rffi.CHAR, 1)) ]) config = platform.configure(CConfig) DIRP = rffi.COpaquePtr("DIR") DIRENT = config["DIRENT"] DIRENTP = lltype.Ptr(DIRENT) # XXX macro=True is hack to make sure we get the correct kind of # dirent struct (which depends on defines) os_opendir = rffi.llexternal("opendir", [rffi.CCHARP], DIRP, compilation_info=eci, save_err=rffi.RFFI_SAVE_ERRNO, macro=True ) os_readdir = rffi.llexternal("readdir", [DIRP], DIRENTP, compilation_info=eci, save_err=rffi.RFFI_SAVE_ERRNO, macro=True ) os_closedir = rffi.llexternal("closedir", [DIRP], rffi.INT, compilation_info=eci, releasegil=False, macro=True ) def opendir(path): dirp = os_opendir(path) if not dirp: raise OSError(rposix.get_saved_errno(), "error in opendir") return dirp def closedir(dirp): os_closedir(dirp) def readdir(dirp): rposix.set_saved_errno(0) direntp = os_readdir(dirp) if not direntp: if rposix.get_saved_errno() == 0: return None else: raise OSError(rposix.get_saved_errno(), "error in readdir") namep = rffi.cast(rffi.CCHARP, direntp.c_d_name) return rffi.charp2str(namep)
bsd-3-clause
duythien/phanbook
core/assets/js/tags-suggest.js
2848
var list_tag = [] //Suggestion tags when create or edit post Array.prototype.remove = function() { var what, a = arguments, L = a.length, ax; while (L && this.length) { what = a[--L]; while ((ax = this.indexOf(what)) !== -1) { this.splice(ax, 1); } } return this; }; function updateTags(){ $("#tags").val(window.list_tag.join(",")); $(".post-tag").remove(); for(var i = 0;i < window.list_tag.length; i++){ $('<span class="post-tag">'+window.list_tag[i]+'<span class="icon-remove delete-tag" title="remove this tag"></span></span>').insertBefore("#tag-input"); } $(".delete-tag").click(function(){ $(this).parent().remove(); tag = $(this).parent().html() tag = tag.split("<span")[0]; tag = tag.replace(/\s+/g, ''); window.list_tag.remove(tag); updateTags(); }); } $(document).ready(function() { $("#tag-input").bind( "keyup", function( event ) { $.ajax({ type: 'GET', url: baseUri + 'tags/tagSuggest', dataType: 'html', data: { 'q': $(this).val() }, success: function (data) { d(data); $('.tag-suggestion-wrapper').html(data) }, error: function( xhr, status ) { }, complete: function( xhr, status ) { } }); }); $(document).on("click",".item-multiplier",function(){ var content = $(this).html(); tag = content.split("<span")[0]; tag = tag.replace(/\s+/g, ''); if(window.list_tag.indexOf(tag) == -1){ window.list_tag.push(tag); } updateTags(); $("#tag-input").val(""); }); //Separate each tag $("#tag-input").keyup(function(event){ if(event.which == 32){ tag = $(this).val(); tag = tag.replace(/\s+/g, ''); if(tag.length > 0){ if(window.list_tag.indexOf(tag) == -1){ window.list_tag.push(tag); } updateTags(); } $(this).val(""); } if(event.which == 8){ if($(this).val() == ""){ window.list_tag.pop(); updateTags(); } } }); //Remove lats item comma when edit a posts if ($('#tags').val()) { var tagValues = $('#tags').val().replace(/,\s*$/, ""); $('#tags').val(tagValues); var tagArray = tagValues.split(','), name = []; tagArray.forEach(function (element, index){ var val= '<span class="post-tag">' + element + '<span title="remove this tag" class="icon-remove delete-tag"></span></span>'; $('.tag-editor').before(val); }); }; });
bsd-3-clause
pgaultier/sweelix-yii1-admin-structure
views/node/step2.php
1817
<?php /** * File step2.php * * PHP version 5.4+ * * @author Philippe Gaultier <pgaultier@sweelix.net> * @copyright 2010-2014 Sweelix * @license http://www.sweelix.net/license license * @version 3.1.0 * @link http://www.sweelix.net * @category views * @package sweelix.yii1.admin.structure.views.node */ use sweelix\yii1\web\helpers\Html; Yii::app()->getClientScript()->registerSweelixScript('callback'); Yii::app()->getModule('sweeft')->registerWysiwygEditor(); ?> <?php $this->widget('sweelix\yii1\admin\core\widgets\Breadcrumb', array( 'elements' => array( array( 'content' => Yii::t('structure', 'Step {n}', array('{n}' => 1 )), 'url' => array('step1', 'nodeId' => $sourceNode->nodeId), ), array( 'content' => Yii::t('structure', 'Step {n}', array('{n}' => 2 )), ), ) )); ?> <nav> <br><br><br> <ul class="shortcuts"> <li> <?php echo Html::link( Yii::t('structure', 'Create new content'), array('content/new', 'nodeId'=>$sourceNode->nodeId), array('title'=>Yii::t('structure', 'Create new content')) );?> </li> <li class="active"> <?php echo Html::link( Yii::t('structure', 'Create new node'), array('node/new', 'nodeId'=>$sourceNode->nodeId), array('title'=>Yii::t('structure', 'Create new node')) );?> </li> </ul> <?php $this->widget('sweelix\yii1\admin\structure\widgets\TreeNodes', array('node' => $sourceNode)); ?> </nav> <section> <div id="content"> <?php $this->widget('sweelix\yii1\admin\core\widgets\ContextMenu', $mainMenu); ?> <?php echo Html::beginAjaxForm('','post',array('enctype'=>'multipart/form-data')); ?> <?php $this->renderPartial('_detail', array( 'node' => $node, 'notice' => (isset($notice)?$notice:false), )); ?> <?php echo Html::endForm(); ?> </div> </section>
bsd-3-clause
qiuyesuifeng/golex
Godeps/_workspace/src/github.com/cznic/lexer/all_test.go
9179
// Copyright (c) 2014 The lexer Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package lexer import ( "bufio" "bytes" "flag" "go/token" "io/ioutil" "os" "path/filepath" "runtime" "testing" ) var ( devFlag = flag.Bool("dev", false, "enable dev tests/utils/helpers") reFlag = flag.String("re", "re", "regexp for some of the dev tests") ) func init() { flag.Parse() } func TestScan(t *testing.T) { lexer, err := CompileLexer( nil, map[string]int{ `/[ \n]+/`: -1, `A`: 11, }, "", "test", ) if err != nil { t.Fatal(10, err) } t.Log("lexer\n", lexer) s := lexer.Scanner("testsrc", bytes.NewBufferString( ` A B `, )) x, ok := s.Scan() if !ok { t.Fatal(20, x, s.TokenStart(), "-", s.Position(), s.Token()) } if x != 11 { t.Fatal(30, x, 11, s.TokenStart(), "-", s.Position(), s.Token()) } x, ok = s.Scan() if ok { t.Fatal(40, x, s.TokenStart(), "-", s.Position(), s.Token()) } if x != 'B' { t.Fatal(50, x, 'B') } x, ok = s.Scan() if ok { t.Fatal(60) } if x != 0 { t.Fatal(70, x, 0) } } var lex = MustCompileLexer( nil, map[string]int{ `/[ \t\n\r]+/`: -1, // token separator(s) `//\*([^*]|\*+[^*/])*\*+/|//.*/`: -2, // /*...*/, //... "identifier": int(token.IDENT + 1000), // main "int_lit": int(token.INT), // 12345 "float_lit": int(token.FLOAT), // 123.45 "imaginary_lit": int(token.IMAG), // 123.45i "char_lit": int(token.CHAR), // 'a' "string_lit": int(token.STRING), // "abc" `+`: int(token.ADD), `-`: int(token.SUB), `*`: int(token.MUL), `/`: int(token.QUO), `%`: int(token.REM), `&`: int(token.AND), `|`: int(token.OR), `^`: int(token.XOR), `<<`: int(token.SHL), `>>`: int(token.SHR), `&^`: int(token.AND_NOT), `+=`: int(token.ADD_ASSIGN), `-=`: int(token.SUB_ASSIGN), `*=`: int(token.MUL_ASSIGN), `/=`: int(token.QUO_ASSIGN), `%=`: int(token.REM_ASSIGN), `&=`: int(token.AND_ASSIGN), `|=`: int(token.OR_ASSIGN), `^=`: int(token.XOR_ASSIGN), `<<=`: int(token.SHL_ASSIGN), `>>=`: int(token.SHR_ASSIGN), `&^=`: int(token.AND_NOT_ASSIGN), `&&`: int(token.LAND), `||`: int(token.LOR), `<-`: int(token.ARROW), `++`: int(token.INC), `--`: int(token.DEC), `==`: int(token.EQL), `<`: int(token.LSS), `>`: int(token.GTR), `=`: int(token.ASSIGN), `!`: int(token.NOT), `!=`: int(token.NEQ), `<=`: int(token.LEQ), `>=`: int(token.GEQ), `:=`: int(token.DEFINE), `...`: int(token.ELLIPSIS), `(`: int(token.LPAREN), `[`: int(token.LBRACK), `{`: int(token.LBRACE), `,`: int(token.COMMA), `.`: int(token.PERIOD), `)`: int(token.RPAREN), `]`: int(token.RBRACK), `}`: int(token.RBRACE), `;`: int(token.SEMICOLON), `:`: int(token.COLON), `/break/`: int(token.BREAK), `/case/`: int(token.CASE), `/chan/`: int(token.CHAN), `/const/`: int(token.CONST), `/continue/`: int(token.CONTINUE), `/default/`: int(token.DEFAULT), `/defer/`: int(token.DEFER), `/else/`: int(token.ELSE), `/fallthrough/`: int(token.FALLTHROUGH), `/for/`: int(token.FOR), `/func/`: int(token.FUNC), `/go/`: int(token.GO), `/goto/`: int(token.GOTO), `/if/`: int(token.IF), `/import/`: int(token.IMPORT), `/interface/`: int(token.INTERFACE), `/map/`: int(token.MAP), `/package/`: int(token.PACKAGE), `/range/`: int(token.RANGE), `/return/`: int(token.RETURN), `/select/`: int(token.SELECT), `/struct/`: int(token.STRUCT), `/switch/`: int(token.SWITCH), `/type/`: int(token.TYPE), `/var/`: int(token.VAR), }, ` identifier = letter { letter | unicode_digit } . letter = unicode_letter | "_" . //decimal_digit = "0" … "9" . octal_digit = "0" … "7" . //hex_digit = "0" … "9" | "A" … "F" | "a" … "f" . hex_digit = "/[0-9a-fA-F]/" . unicode_char = "/.|\n/" /* an arbitrary Unicode code point */ . unicode_digit = "/\\p{Nd}/" /* a Unicode code point classified as "Digit" */ . unicode_letter = "/\\p{L}/" /* a Unicode code point classified as "Letter" */ . int_lit = decimal_lit | octal_lit | hex_lit . //decimal_lit = ( "1" … "9" ) { decimal_digit } . decimal_lit = "/[1-9][0-9]*/" . //octal_lit = "0" { octal_digit } . octal_lit = "/0[0-7]*/" . //hex_lit = "0" ( "x" | "X" ) hex_digit { hex_digit } . hex_lit = "/0[xX][0-9a-fA-F]+/" . float_lit = decimals "." [ decimals ] [ exponent ] | decimals exponent | "." decimals [ exponent ] . //decimals = decimal_digit { decimal_digit } . decimals = "/[0-9]+/" . //exponent = ( "e" | "E" ) [ "+" | "-" ] decimals . exponent = "/[eE][-+]?[0-9]+/" . imaginary_lit = ( decimals | float_lit ) "i" . char_lit = "'" ( char_unicode_value | byte_value ) "'" . char_unicode_value = unicode_char | char_interpreter_value . char_interpreter_value = little_u_value | big_u_value | char_escaped_char . byte_value = octal_byte_value | hex_byte_value . octal_byte_value = "\\" octal_digit octal_digit octal_digit . hex_byte_value = "\\" "x" hex_digit hex_digit . little_u_value = "\\" "u" hex_digit hex_digit hex_digit hex_digit . big_u_value = "\\" "U" hex_digit hex_digit hex_digit hex_digit hex_digit hex_digit hex_digit hex_digit . char_escaped_char = "\\" ( "'" | other_escaped_char ) . //other_escaped_char = "a" | "b" | "f" | "n" | "r" | "t" | "v" | "\\" . other_escaped_char = "/[abfnrtv\\\\]/" . string_lit = raw_string_lit | interpreted_string_lit . raw_string_lit = "/\x60[^\x60]*\x60/" . interpreted_string_lit = "\"" { string_unicode_value | byte_value } "\"" . string_unicode_value = string_unicode_char | string_interpreter_value . string_unicode_char = "/[^\"\n\r\\\\]/" /* an arbitrary Unicode code point within an interpreted string */ . string_interpreter_value = little_u_value | big_u_value | string_escaped_char . string_escaped_char = "\\" ( "\"" | other_escaped_char ) . `, "Go", ) func BenchmarkNFA(b *testing.B) { var v visitor for i := 0; i < b.N; i++ { v = visitor{s: lex.Scanner("test-go-scanner", nil)} filepath.Walk(runtime.GOROOT()+"/src", func(pth string, info os.FileInfo, err error) error { if err != nil { panic(err) } if !info.IsDir() { v.visitFile(pth, info) } return nil }) } b.SetBytes(int64(b.N) * v.size) } func TestNFA(t *testing.T) { t.Logf("NFA states: %d", len(lex.nfa)) fn := filepath.Join(runtime.GOROOT(), "src", stdlib, "fmt", "scan.go") f, err := ioutil.ReadFile(fn) if err != nil { t.Fatal(err) } s, tok := lex.Scanner(fn, bytes.NewBuffer(f)), 0 for { x, ok := s.Scan() if x == 0 { break } if !ok { t.Fatalf("Scan fail: %d=%q %s-%s = %q", x, string(x), s.TokenStart(), s.Position(), string(s.Token())) } tok++ } if tok == 0 { t.Fatal(10, "no tokens found") } t.Log(tok, "tokens in", fn) } type visitor struct { s *Scanner count int tokCount int size int64 } func (v *visitor) visitFile(path string, f os.FileInfo) { ok, err := filepath.Match("*.go", filepath.Base(path)) if err != nil { panic(err) } if !ok { return } file, err := os.Open(path) if err != nil { panic(err) } defer file.Close() v.s.Include(path, bufio.NewReader(file)) for { x, ok := v.s.Scan() if x == 0 { break } if !ok { return } v.tokCount++ } v.count++ v.size += f.Size() } func TestDevParse(t *testing.T) { if !*devFlag { return } var nfa Nfa _, _, err := nfa.ParseRE("test", *reFlag) if err != nil { t.Fatal(10, err) } t.Log(nfa) } // https://github.com/cznic/golex/issues/1 func TestBug1(t *testing.T) { data := []string{ `[ \-\*]`, "[-]", "[-z]", // "[a-]", // invalid "[a-z]", "[\\-]", "[\\-z]", "[a\\-]", "[a\\-z]", } for i, s := range data { var nfa Nfa in, out, err := nfa.ParseRE("test", s) if err != nil { t.Fatal(i, s, err) } t.Logf("i: %d, s: %q, in: [%d], out: [%d]\nnfa: %s", i, s, in.Index, out.Index, nfa) } } func TestBug2(t *testing.T) { data := []string{ `[+-]`, `[+\-]`, `[\+-]`, `[\+\-]`, `[+-z]`, `[+\-z]`, `[\+-z]`, `[\+\-z]`, } for i, s := range data { var nfa Nfa in, out, err := nfa.ParseRE("test", s) if err != nil { t.Fatal(i, s, err) } t.Logf("i: %d, s: %q, in: [%d], out: [%d]\nnfa: %s", i, s, in.Index, out.Index, nfa) } }
bsd-3-clause
dbikel/refr
html/search/all_78.js
550
var searchData= [ ['xstr',['XSTR',['../compile-features_8_c.html#afc0fe0597af089c04afb9bc5a6475705',1,'XSTR():&#160;compile-features.C'],['../extract-features_8_c.html#afc0fe0597af089c04afb9bc5a6475705',1,'XSTR():&#160;extract-features.C'],['../piped-model-evaluator_8_c.html#afc0fe0597af089c04afb9bc5a6475705',1,'XSTR():&#160;piped-model-evaluator.C'],['../run-model_8_c.html#afc0fe0597af089c04afb9bc5a6475705',1,'XSTR():&#160;run-model.C'],['../symbolize-model_8_c.html#afc0fe0597af089c04afb9bc5a6475705',1,'XSTR():&#160;symbolize-model.C']]] ];
bsd-3-clause
mgrauer/qibench
library/Zend/Pdf/Resource/Image/Png.php
18526
<?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_Pdf * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: Png.php 23395 2010-11-19 15:30:47Z alexander $ */ /** Internally used classes */ // require_once 'Zend/Pdf/Element/Array.php'; // require_once 'Zend/Pdf/Element/Dictionary.php'; // require_once 'Zend/Pdf/Element/Name.php'; // require_once 'Zend/Pdf/Element/Numeric.php'; // require_once 'Zend/Pdf/Element/String/Binary.php'; /** Zend_Pdf_Resource_Image */ // require_once 'Zend/Pdf/Resource/Image.php'; /** * PNG image * * @package Zend_Pdf * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Pdf_Resource_Image_Png extends Zend_Pdf_Resource_Image { const PNG_COMPRESSION_DEFAULT_STRATEGY = 0; const PNG_COMPRESSION_FILTERED = 1; const PNG_COMPRESSION_HUFFMAN_ONLY = 2; const PNG_COMPRESSION_RLE = 3; const PNG_FILTER_NONE = 0; const PNG_FILTER_SUB = 1; const PNG_FILTER_UP = 2; const PNG_FILTER_AVERAGE = 3; const PNG_FILTER_PAETH = 4; const PNG_INTERLACING_DISABLED = 0; const PNG_INTERLACING_ENABLED = 1; const PNG_CHANNEL_GRAY = 0; const PNG_CHANNEL_RGB = 2; const PNG_CHANNEL_INDEXED = 3; const PNG_CHANNEL_GRAY_ALPHA = 4; const PNG_CHANNEL_RGB_ALPHA = 6; protected $_width; protected $_height; protected $_imageProperties; /** * Object constructor * * @param string $imageFileName * @throws Zend_Pdf_Exception * @todo Add compression conversions to support compression strategys other than PNG_COMPRESSION_DEFAULT_STRATEGY. * @todo Add pre-compression filtering. * @todo Add interlaced image handling. * @todo Add support for 16-bit images. Requires PDF version bump to 1.5 at least. * @todo Add processing for all PNG chunks defined in the spec. gAMA etc. * @todo Fix tRNS chunk support for Indexed Images to a SMask. */ public function __construct($imageFileName) { if (($imageFile = @fopen($imageFileName, 'rb')) === false ) { // require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception( "Can not open '$imageFileName' file for reading." ); } parent::__construct(); //Check if the file is a PNG fseek($imageFile, 1, SEEK_CUR); //First signature byte (%) if ('PNG' != fread($imageFile, 3)) { // require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception('Image is not a PNG'); } fseek($imageFile, 12, SEEK_CUR); //Signature bytes (Includes the IHDR chunk) IHDR processed linerarly because it doesnt contain a variable chunk length $wtmp = unpack('Ni',fread($imageFile, 4)); //Unpack a 4-Byte Long $width = $wtmp['i']; $htmp = unpack('Ni',fread($imageFile, 4)); $height = $htmp['i']; $bits = ord(fread($imageFile, 1)); //Higher than 8 bit depths are only supported in later versions of PDF. $color = ord(fread($imageFile, 1)); $compression = ord(fread($imageFile, 1)); $prefilter = ord(fread($imageFile,1)); if (($interlacing = ord(fread($imageFile,1))) != Zend_Pdf_Resource_Image_Png::PNG_INTERLACING_DISABLED) { // require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception( "Only non-interlaced images are currently supported." ); } $this->_width = $width; $this->_height = $height; $this->_imageProperties = array(); $this->_imageProperties['bitDepth'] = $bits; $this->_imageProperties['pngColorType'] = $color; $this->_imageProperties['pngFilterType'] = $prefilter; $this->_imageProperties['pngCompressionType'] = $compression; $this->_imageProperties['pngInterlacingType'] = $interlacing; fseek($imageFile, 4, SEEK_CUR); //4 Byte Ending Sequence $imageData = ''; /* * The following loop processes PNG chunks. 4 Byte Longs are packed first give the chunk length * followed by the chunk signature, a four byte code. IDAT and IEND are manditory in any PNG. */ while (!feof($imageFile)) { $chunkLengthBytes = fread($imageFile, 4); if ($chunkLengthBytes === false) { // require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception('Error ocuured while image file reading.'); } $chunkLengthtmp = unpack('Ni', $chunkLengthBytes); $chunkLength = $chunkLengthtmp['i']; $chunkType = fread($imageFile, 4); switch($chunkType) { case 'IDAT': //Image Data /* * Reads the actual image data from the PNG file. Since we know at this point that the compression * strategy is the default strategy, we also know that this data is Zip compressed. We will either copy * the data directly to the PDF and provide the correct FlateDecode predictor, or decompress the data * decode the filters and output the data as a raw pixel map. */ $imageData .= fread($imageFile, $chunkLength); fseek($imageFile, 4, SEEK_CUR); break; case 'PLTE': //Palette $paletteData = fread($imageFile, $chunkLength); fseek($imageFile, 4, SEEK_CUR); break; case 'tRNS': //Basic (non-alpha channel) transparency. $trnsData = fread($imageFile, $chunkLength); switch ($color) { case Zend_Pdf_Resource_Image_Png::PNG_CHANNEL_GRAY: $baseColor = ord(substr($trnsData, 1, 1)); $transparencyData = array(new Zend_Pdf_Element_Numeric($baseColor), new Zend_Pdf_Element_Numeric($baseColor)); break; case Zend_Pdf_Resource_Image_Png::PNG_CHANNEL_RGB: $red = ord(substr($trnsData,1,1)); $green = ord(substr($trnsData,3,1)); $blue = ord(substr($trnsData,5,1)); $transparencyData = array(new Zend_Pdf_Element_Numeric($red), new Zend_Pdf_Element_Numeric($red), new Zend_Pdf_Element_Numeric($green), new Zend_Pdf_Element_Numeric($green), new Zend_Pdf_Element_Numeric($blue), new Zend_Pdf_Element_Numeric($blue)); break; case Zend_Pdf_Resource_Image_Png::PNG_CHANNEL_INDEXED: //Find the first transparent color in the index, we will mask that. (This is a bit of a hack. This should be a SMask and mask all entries values). if(($trnsIdx = strpos($trnsData, "\0")) !== false) { $transparencyData = array(new Zend_Pdf_Element_Numeric($trnsIdx), new Zend_Pdf_Element_Numeric($trnsIdx)); } break; case Zend_Pdf_Resource_Image_Png::PNG_CHANNEL_GRAY_ALPHA: // Fall through to the next case case Zend_Pdf_Resource_Image_Png::PNG_CHANNEL_RGB_ALPHA: // require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception( "tRNS chunk illegal for Alpha Channel Images" ); break; } fseek($imageFile, 4, SEEK_CUR); //4 Byte Ending Sequence break; case 'IEND'; break 2; //End the loop too default: fseek($imageFile, $chunkLength + 4, SEEK_CUR); //Skip the section break; } } fclose($imageFile); $compressed = true; $imageDataTmp = ''; $smaskData = ''; switch ($color) { case Zend_Pdf_Resource_Image_Png::PNG_CHANNEL_RGB: $colorSpace = new Zend_Pdf_Element_Name('DeviceRGB'); break; case Zend_Pdf_Resource_Image_Png::PNG_CHANNEL_GRAY: $colorSpace = new Zend_Pdf_Element_Name('DeviceGray'); break; case Zend_Pdf_Resource_Image_Png::PNG_CHANNEL_INDEXED: if(empty($paletteData)) { // require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception( "PNG Corruption: No palette data read for indexed type PNG." ); } $colorSpace = new Zend_Pdf_Element_Array(); $colorSpace->items[] = new Zend_Pdf_Element_Name('Indexed'); $colorSpace->items[] = new Zend_Pdf_Element_Name('DeviceRGB'); $colorSpace->items[] = new Zend_Pdf_Element_Numeric((strlen($paletteData)/3-1)); $paletteObject = $this->_objectFactory->newObject(new Zend_Pdf_Element_String_Binary($paletteData)); $colorSpace->items[] = $paletteObject; break; case Zend_Pdf_Resource_Image_Png::PNG_CHANNEL_GRAY_ALPHA: /* * To decode PNG's with alpha data we must create two images from one. One image will contain the Gray data * the other will contain the Gray transparency overlay data. The former will become the object data and the latter * will become the Shadow Mask (SMask). */ if($bits > 8) { // require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception("Alpha PNGs with bit depth > 8 are not yet supported"); } $colorSpace = new Zend_Pdf_Element_Name('DeviceGray'); // require_once 'Zend/Pdf/ElementFactory.php'; $decodingObjFactory = Zend_Pdf_ElementFactory::createFactory(1); $decodingStream = $decodingObjFactory->newStreamObject($imageData); $decodingStream->dictionary->Filter = new Zend_Pdf_Element_Name('FlateDecode'); $decodingStream->dictionary->DecodeParms = new Zend_Pdf_Element_Dictionary(); $decodingStream->dictionary->DecodeParms->Predictor = new Zend_Pdf_Element_Numeric(15); $decodingStream->dictionary->DecodeParms->Columns = new Zend_Pdf_Element_Numeric($width); $decodingStream->dictionary->DecodeParms->Colors = new Zend_Pdf_Element_Numeric(2); //GreyAlpha $decodingStream->dictionary->DecodeParms->BitsPerComponent = new Zend_Pdf_Element_Numeric($bits); $decodingStream->skipFilters(); $pngDataRawDecoded = $decodingStream->value; //Iterate every pixel and copy out gray data and alpha channel (this will be slow) for($pixel = 0, $pixelcount = ($width * $height); $pixel < $pixelcount; $pixel++) { $imageDataTmp .= $pngDataRawDecoded[($pixel*2)]; $smaskData .= $pngDataRawDecoded[($pixel*2)+1]; } $compressed = false; $imageData = $imageDataTmp; //Overwrite image data with the gray channel without alpha break; case Zend_Pdf_Resource_Image_Png::PNG_CHANNEL_RGB_ALPHA: /* * To decode PNG's with alpha data we must create two images from one. One image will contain the RGB data * the other will contain the Gray transparency overlay data. The former will become the object data and the latter * will become the Shadow Mask (SMask). */ if($bits > 8) { // require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception("Alpha PNGs with bit depth > 8 are not yet supported"); } $colorSpace = new Zend_Pdf_Element_Name('DeviceRGB'); // require_once 'Zend/Pdf/ElementFactory.php'; $decodingObjFactory = Zend_Pdf_ElementFactory::createFactory(1); $decodingStream = $decodingObjFactory->newStreamObject($imageData); $decodingStream->dictionary->Filter = new Zend_Pdf_Element_Name('FlateDecode'); $decodingStream->dictionary->DecodeParms = new Zend_Pdf_Element_Dictionary(); $decodingStream->dictionary->DecodeParms->Predictor = new Zend_Pdf_Element_Numeric(15); $decodingStream->dictionary->DecodeParms->Columns = new Zend_Pdf_Element_Numeric($width); $decodingStream->dictionary->DecodeParms->Colors = new Zend_Pdf_Element_Numeric(4); //RGBA $decodingStream->dictionary->DecodeParms->BitsPerComponent = new Zend_Pdf_Element_Numeric($bits); $decodingStream->skipFilters(); $pngDataRawDecoded = $decodingStream->value; //Iterate every pixel and copy out rgb data and alpha channel (this will be slow) for($pixel = 0, $pixelcount = ($width * $height); $pixel < $pixelcount; $pixel++) { $imageDataTmp .= $pngDataRawDecoded[($pixel*4)+0] . $pngDataRawDecoded[($pixel*4)+1] . $pngDataRawDecoded[($pixel*4)+2]; $smaskData .= $pngDataRawDecoded[($pixel*4)+3]; } $compressed = false; $imageData = $imageDataTmp; //Overwrite image data with the RGB channel without alpha break; default: // require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception( "PNG Corruption: Invalid color space." ); } if(empty($imageData)) { // require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception( "Corrupt PNG Image. Mandatory IDAT chunk not found." ); } $imageDictionary = $this->_resource->dictionary; if(!empty($smaskData)) { /* * Includes the Alpha transparency data as a Gray Image, then assigns the image as the Shadow Mask for the main image data. */ $smaskStream = $this->_objectFactory->newStreamObject($smaskData); $smaskStream->dictionary->Type = new Zend_Pdf_Element_Name('XObject'); $smaskStream->dictionary->Subtype = new Zend_Pdf_Element_Name('Image'); $smaskStream->dictionary->Width = new Zend_Pdf_Element_Numeric($width); $smaskStream->dictionary->Height = new Zend_Pdf_Element_Numeric($height); $smaskStream->dictionary->ColorSpace = new Zend_Pdf_Element_Name('DeviceGray'); $smaskStream->dictionary->BitsPerComponent = new Zend_Pdf_Element_Numeric($bits); $imageDictionary->SMask = $smaskStream; // Encode stream with FlateDecode filter $smaskStreamDecodeParms = array(); $smaskStreamDecodeParms['Predictor'] = new Zend_Pdf_Element_Numeric(15); $smaskStreamDecodeParms['Columns'] = new Zend_Pdf_Element_Numeric($width); $smaskStreamDecodeParms['Colors'] = new Zend_Pdf_Element_Numeric(1); $smaskStreamDecodeParms['BitsPerComponent'] = new Zend_Pdf_Element_Numeric(8); $smaskStream->dictionary->DecodeParms = new Zend_Pdf_Element_Dictionary($smaskStreamDecodeParms); $smaskStream->dictionary->Filter = new Zend_Pdf_Element_Name('FlateDecode'); } if(!empty($transparencyData)) { //This is experimental and not properly tested. $imageDictionary->Mask = new Zend_Pdf_Element_Array($transparencyData); } $imageDictionary->Width = new Zend_Pdf_Element_Numeric($width); $imageDictionary->Height = new Zend_Pdf_Element_Numeric($height); $imageDictionary->ColorSpace = $colorSpace; $imageDictionary->BitsPerComponent = new Zend_Pdf_Element_Numeric($bits); $imageDictionary->Filter = new Zend_Pdf_Element_Name('FlateDecode'); $decodeParms = array(); $decodeParms['Predictor'] = new Zend_Pdf_Element_Numeric(15); // Optimal prediction $decodeParms['Columns'] = new Zend_Pdf_Element_Numeric($width); $decodeParms['Colors'] = new Zend_Pdf_Element_Numeric((($color==Zend_Pdf_Resource_Image_Png::PNG_CHANNEL_RGB || $color==Zend_Pdf_Resource_Image_Png::PNG_CHANNEL_RGB_ALPHA)?(3):(1))); $decodeParms['BitsPerComponent'] = new Zend_Pdf_Element_Numeric($bits); $imageDictionary->DecodeParms = new Zend_Pdf_Element_Dictionary($decodeParms); //Include only the image IDAT section data. $this->_resource->value = $imageData; //Skip double compression if ($compressed) { $this->_resource->skipFilters(); } } /** * Image width */ public function getPixelWidth() { return $this->_width; } /** * Image height */ public function getPixelHeight() { return $this->_height; } /** * Image properties */ public function getProperties() { return $this->_imageProperties; } }
bsd-3-clause
google/skia
src/gpu/ops/SoftwarePathRenderer.cpp
18482
/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "src/gpu/ops/SoftwarePathRenderer.h" #include "include/gpu/GrDirectContext.h" #include "include/private/SkSemaphore.h" #include "src/core/SkTaskGroup.h" #include "src/core/SkTraceEvent.h" #include "src/gpu/GrAuditTrail.h" #include "src/gpu/GrCaps.h" #include "src/gpu/GrClip.h" #include "src/gpu/GrDeferredProxyUploader.h" #include "src/gpu/GrDirectContextPriv.h" #include "src/gpu/GrGpuResourcePriv.h" #include "src/gpu/GrOpFlushState.h" #include "src/gpu/GrProxyProvider.h" #include "src/gpu/GrRecordingContextPriv.h" #include "src/gpu/GrSWMaskHelper.h" #include "src/gpu/GrUtil.h" #include "src/gpu/SkGr.h" #include "src/gpu/effects/GrTextureEffect.h" #include "src/gpu/geometry/GrStyledShape.h" #include "src/gpu/ops/GrDrawOp.h" #include "src/gpu/v1/SurfaceDrawContext_v1.h" namespace { /** * Payload class for use with GrTDeferredProxyUploader. The software path renderer only draws * a single path into the mask texture. This stores all of the information needed by the worker * thread's call to drawShape (see below, in onDrawPath). */ class SoftwarePathData { public: SoftwarePathData(const SkIRect& maskBounds, const SkMatrix& viewMatrix, const GrStyledShape& shape, GrAA aa) : fMaskBounds(maskBounds) , fViewMatrix(viewMatrix) , fShape(shape) , fAA(aa) {} const SkIRect& getMaskBounds() const { return fMaskBounds; } const SkMatrix* getViewMatrix() const { return &fViewMatrix; } const GrStyledShape& getShape() const { return fShape; } GrAA getAA() const { return fAA; } private: SkIRect fMaskBounds; SkMatrix fViewMatrix; GrStyledShape fShape; GrAA fAA; }; bool get_unclipped_shape_dev_bounds(const GrStyledShape& shape, const SkMatrix& matrix, SkIRect* devBounds) { SkRect shapeBounds = shape.styledBounds(); if (shapeBounds.isEmpty()) { return false; } SkRect shapeDevBounds; matrix.mapRect(&shapeDevBounds, shapeBounds); // Even though these are "unclipped" bounds we still clip to the int32_t range. // This is the largest int32_t that is representable exactly as a float. The next 63 larger ints // would round down to this value when cast to a float, but who really cares. // INT32_MIN is exactly representable. static constexpr int32_t kMaxInt = 2147483520; if (!shapeDevBounds.intersect(SkRect::MakeLTRB(INT32_MIN, INT32_MIN, kMaxInt, kMaxInt))) { return false; } // Make sure that the resulting SkIRect can have representable width and height if (SkScalarRoundToInt(shapeDevBounds.width()) > kMaxInt || SkScalarRoundToInt(shapeDevBounds.height()) > kMaxInt) { return false; } shapeDevBounds.roundOut(devBounds); return true; } GrSurfaceProxyView make_deferred_mask_texture_view(GrRecordingContext* rContext, SkBackingFit fit, SkISize dimensions) { GrProxyProvider* proxyProvider = rContext->priv().proxyProvider(); const GrCaps* caps = rContext->priv().caps(); const GrBackendFormat format = caps->getDefaultBackendFormat(GrColorType::kAlpha_8, GrRenderable::kNo); GrSwizzle swizzle = caps->getReadSwizzle(format, GrColorType::kAlpha_8); auto proxy = proxyProvider->createProxy(format, dimensions, GrRenderable::kNo, 1, GrMipmapped::kNo, fit, SkBudgeted::kYes, GrProtected::kNo); return {std::move(proxy), kTopLeft_GrSurfaceOrigin, swizzle}; } } // anonymous namespace namespace skgpu::v1 { //////////////////////////////////////////////////////////////////////////////// PathRenderer::CanDrawPath SoftwarePathRenderer::onCanDrawPath(const CanDrawPathArgs& args) const { // Pass on any style that applies. The caller will apply the style if a suitable renderer is // not found and try again with the new GrStyledShape. if (!args.fShape->style().applies() && SkToBool(fProxyProvider) && (args.fAAType == GrAAType::kCoverage || args.fAAType == GrAAType::kNone)) { // This is the fallback renderer for when a path is too complicated for the GPU ones. return CanDrawPath::kAsBackup; } return CanDrawPath::kNo; } //////////////////////////////////////////////////////////////////////////////// // Gets the shape bounds, the clip bounds, and the intersection (if any). Returns false if there // is no intersection. bool SoftwarePathRenderer::GetShapeAndClipBounds(SurfaceDrawContext* sdc, const GrClip* clip, const GrStyledShape& shape, const SkMatrix& matrix, SkIRect* unclippedDevShapeBounds, SkIRect* clippedDevShapeBounds, SkIRect* devClipBounds) { // compute bounds as intersection of rt size, clip, and path *devClipBounds = clip ? clip->getConservativeBounds() : SkIRect::MakeWH(sdc->width(), sdc->height()); if (!get_unclipped_shape_dev_bounds(shape, matrix, unclippedDevShapeBounds)) { *unclippedDevShapeBounds = SkIRect::MakeEmpty(); *clippedDevShapeBounds = SkIRect::MakeEmpty(); return false; } if (!clippedDevShapeBounds->intersect(*devClipBounds, *unclippedDevShapeBounds)) { *clippedDevShapeBounds = SkIRect::MakeEmpty(); return false; } return true; } //////////////////////////////////////////////////////////////////////////////// void SoftwarePathRenderer::DrawNonAARect(SurfaceDrawContext* sdc, GrPaint&& paint, const GrUserStencilSettings& userStencilSettings, const GrClip* clip, const SkMatrix& viewMatrix, const SkRect& rect, const SkMatrix& localMatrix) { sdc->stencilRect(clip, &userStencilSettings, std::move(paint), GrAA::kNo, viewMatrix, rect, &localMatrix); } void SoftwarePathRenderer::DrawAroundInvPath(SurfaceDrawContext* sdc, GrPaint&& paint, const GrUserStencilSettings& userStencilSettings, const GrClip* clip, const SkMatrix& viewMatrix, const SkIRect& devClipBounds, const SkIRect& devPathBounds) { SkMatrix invert; if (!viewMatrix.invert(&invert)) { return; } SkRect rect; if (devClipBounds.fTop < devPathBounds.fTop) { rect.setLTRB(SkIntToScalar(devClipBounds.fLeft), SkIntToScalar(devClipBounds.fTop), SkIntToScalar(devClipBounds.fRight), SkIntToScalar(devPathBounds.fTop)); DrawNonAARect(sdc, GrPaint::Clone(paint), userStencilSettings, clip, SkMatrix::I(), rect, invert); } if (devClipBounds.fLeft < devPathBounds.fLeft) { rect.setLTRB(SkIntToScalar(devClipBounds.fLeft), SkIntToScalar(devPathBounds.fTop), SkIntToScalar(devPathBounds.fLeft), SkIntToScalar(devPathBounds.fBottom)); DrawNonAARect(sdc, GrPaint::Clone(paint), userStencilSettings, clip, SkMatrix::I(), rect, invert); } if (devClipBounds.fRight > devPathBounds.fRight) { rect.setLTRB(SkIntToScalar(devPathBounds.fRight), SkIntToScalar(devPathBounds.fTop), SkIntToScalar(devClipBounds.fRight), SkIntToScalar(devPathBounds.fBottom)); DrawNonAARect(sdc, GrPaint::Clone(paint), userStencilSettings, clip, SkMatrix::I(), rect, invert); } if (devClipBounds.fBottom > devPathBounds.fBottom) { rect.setLTRB(SkIntToScalar(devClipBounds.fLeft), SkIntToScalar(devPathBounds.fBottom), SkIntToScalar(devClipBounds.fRight), SkIntToScalar(devClipBounds.fBottom)); DrawNonAARect(sdc, std::move(paint), userStencilSettings, clip, SkMatrix::I(), rect, invert); } } void SoftwarePathRenderer::DrawToTargetWithShapeMask( GrSurfaceProxyView view, SurfaceDrawContext* sdc, GrPaint&& paint, const GrUserStencilSettings& userStencilSettings, const GrClip* clip, const SkMatrix& viewMatrix, const SkIPoint& textureOriginInDeviceSpace, const SkIRect& deviceSpaceRectToDraw) { SkMatrix invert; if (!viewMatrix.invert(&invert)) { return; } view.concatSwizzle(GrSwizzle("aaaa")); SkRect dstRect = SkRect::Make(deviceSpaceRectToDraw); // We use device coords to compute the texture coordinates. We take the device coords and apply // a translation so that the top-left of the device bounds maps to 0,0, and then a scaling // matrix to normalized coords. SkMatrix maskMatrix = SkMatrix::Translate(SkIntToScalar(-textureOriginInDeviceSpace.fX), SkIntToScalar(-textureOriginInDeviceSpace.fY)); maskMatrix.preConcat(viewMatrix); paint.setCoverageFragmentProcessor(GrTextureEffect::Make( std::move(view), kPremul_SkAlphaType, maskMatrix, GrSamplerState::Filter::kNearest)); DrawNonAARect(sdc, std::move(paint), userStencilSettings, clip, SkMatrix::I(), dstRect, invert); } //////////////////////////////////////////////////////////////////////////////// // return true on success; false on failure bool SoftwarePathRenderer::onDrawPath(const DrawPathArgs& args) { GR_AUDIT_TRAIL_AUTO_FRAME(args.fContext->priv().auditTrail(), "SoftwarePathRenderer::onDrawPath"); if (!fProxyProvider) { return false; } SkASSERT(!args.fShape->style().applies()); // We really need to know if the shape will be inverse filled or not // If the path is hairline, ignore inverse fill. bool inverseFilled = args.fShape->inverseFilled() && !GrIsStrokeHairlineOrEquivalent(args.fShape->style(), *args.fViewMatrix, nullptr); SkIRect unclippedDevShapeBounds, clippedDevShapeBounds, devClipBounds; // To prevent overloading the cache with entries during animations we limit the cache of masks // to cases where the matrix preserves axis alignment. bool useCache = fAllowCaching && !inverseFilled && args.fViewMatrix->preservesAxisAlignment() && args.fShape->hasUnstyledKey() && (GrAAType::kCoverage == args.fAAType); if (!GetShapeAndClipBounds(args.fSurfaceDrawContext, args.fClip, *args.fShape, *args.fViewMatrix, &unclippedDevShapeBounds, &clippedDevShapeBounds, &devClipBounds)) { if (inverseFilled) { DrawAroundInvPath(args.fSurfaceDrawContext, std::move(args.fPaint), *args.fUserStencilSettings, args.fClip, *args.fViewMatrix, devClipBounds, unclippedDevShapeBounds); } return true; } const SkIRect* boundsForMask = &clippedDevShapeBounds; if (useCache) { // Use the cache only if >50% of the path is visible. int unclippedWidth = unclippedDevShapeBounds.width(); int unclippedHeight = unclippedDevShapeBounds.height(); int64_t unclippedArea = sk_64_mul(unclippedWidth, unclippedHeight); int64_t clippedArea = sk_64_mul(clippedDevShapeBounds.width(), clippedDevShapeBounds.height()); int maxTextureSize = args.fSurfaceDrawContext->caps()->maxTextureSize(); if (unclippedArea > 2 * clippedArea || unclippedWidth > maxTextureSize || unclippedHeight > maxTextureSize) { useCache = false; } else { boundsForMask = &unclippedDevShapeBounds; } } skgpu::UniqueKey maskKey; if (useCache) { // We require the upper left 2x2 of the matrix to match exactly for a cache hit. SkScalar sx = args.fViewMatrix->get(SkMatrix::kMScaleX); SkScalar sy = args.fViewMatrix->get(SkMatrix::kMScaleY); SkScalar kx = args.fViewMatrix->get(SkMatrix::kMSkewX); SkScalar ky = args.fViewMatrix->get(SkMatrix::kMSkewY); static const skgpu::UniqueKey::Domain kDomain = skgpu::UniqueKey::GenerateDomain(); skgpu::UniqueKey::Builder builder(&maskKey, kDomain, 7 + args.fShape->unstyledKeySize(), "SW Path Mask"); builder[0] = boundsForMask->width(); builder[1] = boundsForMask->height(); #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK // Fractional translate does not affect caching on Android. This is done for better cache // hit ratio and speed, but it is matching HWUI behavior, which doesn't consider the matrix // at all when caching paths. SkFixed fracX = 0; SkFixed fracY = 0; #else SkScalar tx = args.fViewMatrix->get(SkMatrix::kMTransX); SkScalar ty = args.fViewMatrix->get(SkMatrix::kMTransY); // Allow 8 bits each in x and y of subpixel positioning. SkFixed fracX = SkScalarToFixed(SkScalarFraction(tx)) & 0x0000FF00; SkFixed fracY = SkScalarToFixed(SkScalarFraction(ty)) & 0x0000FF00; #endif builder[2] = SkFloat2Bits(sx); builder[3] = SkFloat2Bits(sy); builder[4] = SkFloat2Bits(kx); builder[5] = SkFloat2Bits(ky); // Distinguish between hairline and filled paths. For hairlines, we also need to include // the cap. (SW grows hairlines by 0.5 pixel with round and square caps). Note that // stroke-and-fill of hairlines is turned into pure fill by SkStrokeRec, so this covers // all cases we might see. uint32_t styleBits = args.fShape->style().isSimpleHairline() ? ((args.fShape->style().strokeRec().getCap() << 1) | 1) : 0; builder[6] = fracX | (fracY >> 8) | (styleBits << 16); args.fShape->writeUnstyledKey(&builder[7]); } GrSurfaceProxyView view; if (useCache) { sk_sp<GrTextureProxy> proxy = fProxyProvider->findOrCreateProxyByUniqueKey(maskKey); if (proxy) { GrSwizzle swizzle = args.fSurfaceDrawContext->caps()->getReadSwizzle( proxy->backendFormat(), GrColorType::kAlpha_8); view = {std::move(proxy), kTopLeft_GrSurfaceOrigin, swizzle}; args.fContext->priv().stats()->incNumPathMasksCacheHits(); } } if (!view) { SkBackingFit fit = useCache ? SkBackingFit::kExact : SkBackingFit::kApprox; GrAA aa = GrAA(GrAAType::kCoverage == args.fAAType); SkTaskGroup* taskGroup = nullptr; if (auto direct = args.fContext->asDirectContext()) { taskGroup = direct->priv().getTaskGroup(); } if (taskGroup) { view = make_deferred_mask_texture_view(args.fContext, fit, boundsForMask->size()); if (!view) { return false; } auto uploader = std::make_unique<GrTDeferredProxyUploader<SoftwarePathData>>( *boundsForMask, *args.fViewMatrix, *args.fShape, aa); GrTDeferredProxyUploader<SoftwarePathData>* uploaderRaw = uploader.get(); auto drawAndUploadMask = [uploaderRaw] { TRACE_EVENT0("skia.gpu", "Threaded SW Mask Render"); GrSWMaskHelper helper(uploaderRaw->getPixels()); if (helper.init(uploaderRaw->data().getMaskBounds())) { helper.drawShape(uploaderRaw->data().getShape(), *uploaderRaw->data().getViewMatrix(), SkRegion::kReplace_Op, uploaderRaw->data().getAA(), 0xFF); } else { SkDEBUGFAIL("Unable to allocate SW mask."); } uploaderRaw->signalAndFreeData(); }; taskGroup->add(std::move(drawAndUploadMask)); view.asTextureProxy()->texPriv().setDeferredUploader(std::move(uploader)); } else { GrSWMaskHelper helper; if (!helper.init(*boundsForMask)) { return false; } helper.drawShape(*args.fShape, *args.fViewMatrix, SkRegion::kReplace_Op, aa, 0xFF); view = helper.toTextureView(args.fContext, fit); } if (!view) { return false; } if (useCache) { SkASSERT(view.origin() == kTopLeft_GrSurfaceOrigin); // We will add an invalidator to the path so that if the path goes away we will // delete or recycle the mask texture. auto listener = GrMakeUniqueKeyInvalidationListener(&maskKey, args.fContext->priv().contextID()); fProxyProvider->assignUniqueKeyToProxy(maskKey, view.asTextureProxy()); args.fShape->addGenIDChangeListener(std::move(listener)); } args.fContext->priv().stats()->incNumPathMasksGenerated(); } SkASSERT(view); if (inverseFilled) { DrawAroundInvPath(args.fSurfaceDrawContext, GrPaint::Clone(args.fPaint), *args.fUserStencilSettings, args.fClip, *args.fViewMatrix, devClipBounds, unclippedDevShapeBounds); } DrawToTargetWithShapeMask(std::move(view), args.fSurfaceDrawContext, std::move(args.fPaint), *args.fUserStencilSettings, args.fClip, *args.fViewMatrix, SkIPoint{boundsForMask->fLeft, boundsForMask->fTop}, *boundsForMask); return true; } } // namespace skgpu::v1
bsd-3-clause
goldblade/ieducar2
public/componentes/jquery-ui-1.10.4.custom/development-bundle/ui/minified/i18n/jquery.ui.datepicker-zh-HK.min.js
916
/*! jQuery UI - v1.10.4 - 2015-11-22 * http://jqueryui.com * Copyright jQuery Foundation and other contributors; Licensed MIT */ jQuery(function(e){e.datepicker.regional["zh-HK"]={closeText:"關閉",prevText:"&#x3C;上月",nextText:"下月&#x3E;",currentText:"今天",monthNames:["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],monthNamesShort:["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],dayNames:["星期日","星期一","星期二","星期三","星期四","星期五","星期六"],dayNamesShort:["周日","周一","周二","周三","周四","周五","周六"],dayNamesMin:["日","一","二","三","四","五","六"],weekHeader:"周",dateFormat:"dd-mm-yy",firstDay:0,isRTL:!1,showMonthAfterYear:!0,yearSuffix:"年"},e.datepicker.setDefaults(e.datepicker.regional["zh-HK"])});
bsd-3-clause
adalke/rdkit
Code/GraphMol/Wrap/props.hpp
4129
// Copyright (c) 2015, Novartis Institutes for BioMedical Research 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 Novartis Institutes for BioMedical Research 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. // #ifndef _RD_WRAPPED_PROPS_H_ #define _RD_WRAPPED_PROPS_H_ #include <RDBoost/python.h> #include <RDBoost/pyint_api.h> #include <RDBoost/Wrap.h> #include <RDGeneral/Dict.h> namespace RDKit { template<class T> inline const char * GetTypeName() { //PRECONDITION(0, "Unregistered c++ type"); return "unregistered C++ type"; } template<> inline const char * GetTypeName<double>() { return "a double value"; } template<> inline const char * GetTypeName<int>() { return "an integer value";} template<> inline const char * GetTypeName<unsigned int>() { return "an unsigned integer value";} template<> inline const char * GetTypeName<bool>() { return "a True or False value";} template<class T, class U> bool AddToDict(const U& ob, boost::python::dict &dict, const std::string &key) { T res; try { if (ob.getPropIfPresent(key, res)) { dict[key] = res; } } catch (boost::bad_any_cast &) { return false; } return true; } template<class T> boost::python::dict GetPropsAsDict(const T &obj, bool includePrivate, bool includeComputed) { boost::python::dict dict; // precedence double, int, unsigned, std::vector<double>, // std::vector<int>, std::vector<unsigned>, string STR_VECT keys = obj.getPropList(includePrivate, includeComputed); for(size_t i=0;i<keys.size();++i) { if (AddToDict<double>(obj, dict, keys[i])) continue; if (AddToDict<int>(obj, dict, keys[i])) continue; if (AddToDict<unsigned int>(obj, dict, keys[i])) continue; if (AddToDict<bool>(obj, dict, keys[i])) continue; if (AddToDict<std::vector<double> >(obj, dict, keys[i])) continue; if (AddToDict<std::vector<int> >(obj, dict, keys[i])) continue; if (AddToDict<std::vector<unsigned int> >(obj, dict, keys[i])) continue; if (AddToDict<std::vector<std::string> >(obj, dict, keys[i])) continue; if (AddToDict<std::string>(obj, dict, keys[i])) continue; } return dict; } template <class RDOb, class T> T GetProp(RDOb *ob, const char *key) { T res; try { if (!ob->getPropIfPresent(key, res)) { PyErr_SetString(PyExc_KeyError, key); throw python::error_already_set(); } return res; } catch ( const boost::bad_any_cast &e ) { throw ValueErrorException(std::string("key `") + key + "` exists but does not result in " + GetTypeName<T>()); } return res; } } #endif
bsd-3-clause
8v060htwyc/whois
whois-api/src/main/java/net/ripe/db/whois/api/rest/StreamingMarshal.java
497
package net.ripe.db.whois.api.rest; public interface StreamingMarshal { void open(); void start(String name); void end(String name); <T> void write(String name, T t); <T> void writeArray(T t); <T> void startArray(String name); <T> void endArray(); void close(); // TODO: [AH] handle streaming on a higher level; e.g. have strategies for different object types (WhoisObjectStreamer) and input (streaming query, from memory) <T> void singleton(T t); }
bsd-3-clause
fcitx/mozc
src/rewriter/language_aware_rewriter_test.cc
14707
// Copyright 2010-2021, 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. #include "rewriter/language_aware_rewriter.h" #include <memory> #include <string> #include "base/logging.h" #include "base/util.h" #include "composer/composer.h" #include "composer/table.h" #include "config/config_handler.h" #include "converter/segments.h" #include "data_manager/testing/mock_data_manager.h" #include "dictionary/dictionary_mock.h" #include "dictionary/pos_matcher.h" #include "protocol/commands.pb.h" #include "protocol/config.pb.h" #include "request/conversion_request.h" #include "testing/base/public/gunit.h" #include "testing/base/public/mozctest.h" #include "usage_stats/usage_stats.h" #include "usage_stats/usage_stats_testing_util.h" #include "absl/memory/memory.h" namespace mozc { namespace { using dictionary::DictionaryMock; using dictionary::Token; void InsertASCIISequence(const std::string &text, composer::Composer *composer) { for (size_t i = 0; i < text.size(); ++i) { commands::KeyEvent key; key.set_key_code(text[i]); composer->InsertCharacterKeyEvent(key); } } } // namespace class LanguageAwareRewriterTest : public ::testing::Test { protected: // Workaround for C2512 error (no default appropriate constructor) on MSVS. LanguageAwareRewriterTest() {} ~LanguageAwareRewriterTest() override {} void SetUp() override { usage_stats::UsageStats::ClearAllStatsForTest(); dictionary_mock_ = absl::make_unique<DictionaryMock>(); } void TearDown() override { dictionary_mock_.reset(); usage_stats::UsageStats::ClearAllStatsForTest(); } LanguageAwareRewriter *CreateLanguageAwareRewriter() const { return new LanguageAwareRewriter( dictionary::PosMatcher(data_manager_.GetPosMatcherData()), dictionary_mock_.get()); } bool RewriteWithLanguageAwareInput(const LanguageAwareRewriter *rewriter, const std::string &key, std::string *composition, Segments *segments) { commands::Request client_request; client_request.set_language_aware_input( commands::Request::LANGUAGE_AWARE_SUGGESTION); composer::Table table; config::Config default_config; table.InitializeWithRequestAndConfig(client_request, default_config, data_manager_); composer::Composer composer(&table, &client_request, &default_config); InsertASCIISequence(key, &composer); composer.GetStringForPreedit(composition); // Perform the rewrite command. segments->set_request_type(Segments::SUGGESTION); if (segments->conversion_segments_size() == 0) { segments->add_segment(); } Segment *segment = segments->mutable_conversion_segment(0); segment->set_key(*composition); ConversionRequest request(&composer, &client_request, &default_config); return rewriter->Rewrite(request, segments); } std::unique_ptr<DictionaryMock> dictionary_mock_; usage_stats::scoped_usage_stats_enabler usage_stats_enabler_; const testing::MockDataManager data_manager_; private: const testing::ScopedTmpUserProfileDirectory tmp_profile_dir_; }; namespace { void PushFrontCandidate(const std::string &data, Segment *segment) { Segment::Candidate *candidate = segment->push_front_candidate(); candidate->Init(); candidate->value = data; candidate->key = data; candidate->content_value = data; candidate->content_key = data; } } // namespace TEST_F(LanguageAwareRewriterTest, LanguageAwareInput) { dictionary_mock_->AddLookupExact("house", "house", "house", Token::NONE); dictionary_mock_->AddLookupExact("query", "query", "query", Token::NONE); dictionary_mock_->AddLookupExact("google", "google", "google", Token::NONE); dictionary_mock_->AddLookupExact("naru", "naru", "naru", Token::NONE); dictionary_mock_->AddLookupExact("なる", "なる", "naru", Token::NONE); std::unique_ptr<LanguageAwareRewriter> rewriter( CreateLanguageAwareRewriter()); const std::string &kPrefix = "→ "; const std::string &kDidYouMean = "もしかして"; { // "python" is composed to "pyてょn", but "python" should be suggested, // because alphabet characters are in the middle of the word. std::string composition; Segments segments; EXPECT_TRUE(RewriteWithLanguageAwareInput(rewriter.get(), "python", &composition, &segments)); EXPECT_EQ("pyてょn", composition); const Segment::Candidate &candidate = segments.conversion_segment(0).candidate(0); EXPECT_EQ("python", candidate.key); EXPECT_EQ("python", candidate.value); EXPECT_EQ(kPrefix, candidate.prefix); EXPECT_EQ(kDidYouMean, candidate.description); } { // "mozuk" is composed to "もずk", then "mozuk" is not suggested. // The tailing alphabet characters are not counted. std::string composition; Segments segments; EXPECT_FALSE(RewriteWithLanguageAwareInput(rewriter.get(), "mozuk", &composition, &segments)); EXPECT_EQ("もずk", composition); EXPECT_EQ(0, segments.conversion_segment(0).candidates_size()); } { // "house" is composed to "ほうせ". Since "house" is in the dictionary // dislike the above "mozuk" case, "house" should be suggested. std::string composition; Segments segments; if (segments.conversion_segments_size() == 0) { segments.add_segment(); } Segment *segment = segments.mutable_conversion_segment(0); // Add three candidates. // => ["cand0", "cand1", "cand2"] PushFrontCandidate("cand2", segment); PushFrontCandidate("cand1", segment); PushFrontCandidate("cand0", segment); EXPECT_EQ(3, segment->candidates_size()); // "house" should be inserted as the 3rd candidate (b/w cand1 and cand2). // => ["cand0", "cand1", "house", "cand2"] EXPECT_TRUE(RewriteWithLanguageAwareInput(rewriter.get(), "house", &composition, &segments)); EXPECT_EQ(4, segment->candidates_size()); EXPECT_EQ("ほうせ", composition); const Segment::Candidate &candidate = segments.conversion_segment(0).candidate(2); EXPECT_EQ("house", candidate.key); EXPECT_EQ("house", candidate.value); EXPECT_EQ(kPrefix, candidate.prefix); EXPECT_EQ(kDidYouMean, candidate.description); } { // "query" is composed to "くえry". Since "query" is in the dictionary // dislike the above "mozuk" case, "query" should be suggested. std::string composition; Segments segments; EXPECT_TRUE(RewriteWithLanguageAwareInput(rewriter.get(), "query", &composition, &segments)); EXPECT_EQ("くえry", composition); const Segment::Candidate &candidate = segments.conversion_segment(0).candidate(0); EXPECT_EQ("query", candidate.key); EXPECT_EQ("query", candidate.value); EXPECT_EQ(kPrefix, candidate.prefix); EXPECT_EQ(kDidYouMean, candidate.description); } { // "google" is composed to "google" by mode_switching_handler. // If the suggestion is equal to the composition, that suggestion // is not added. std::string composition; Segments segments; EXPECT_FALSE(RewriteWithLanguageAwareInput(rewriter.get(), "google", &composition, &segments)); EXPECT_EQ("google", composition); } { // The key "なる" has two value "naru" and "なる". // In this case, language aware rewriter should not be triggered. std::string composition; Segments segments; EXPECT_FALSE(RewriteWithLanguageAwareInput(rewriter.get(), "naru", &composition, &segments)); EXPECT_EQ("なる", composition); EXPECT_EQ(0, segments.conversion_segment(0).candidates_size()); } } TEST_F(LanguageAwareRewriterTest, LanguageAwareInputUsageStats) { std::unique_ptr<LanguageAwareRewriter> rewriter( CreateLanguageAwareRewriter()); EXPECT_STATS_NOT_EXIST("LanguageAwareSuggestionTriggered"); EXPECT_STATS_NOT_EXIST("LanguageAwareSuggestionCommitted"); const std::string kPyTeyoN = "pyてょn"; { // "python" is composed to "pyてょn", but "python" should be suggested, // because alphabet characters are in the middle of the word. std::string composition; Segments segments; EXPECT_TRUE(RewriteWithLanguageAwareInput(rewriter.get(), "python", &composition, &segments)); EXPECT_EQ(kPyTeyoN, composition); const Segment::Candidate &candidate = segments.conversion_segment(0).candidate(0); EXPECT_EQ("python", candidate.key); EXPECT_EQ("python", candidate.value); EXPECT_COUNT_STATS("LanguageAwareSuggestionTriggered", 1); EXPECT_STATS_NOT_EXIST("LanguageAwareSuggestionCommitted"); } { // Call Rewrite with "python" again, then call Finish. Both ...Triggered // and ...Committed should be incremented. // Note, RewriteWithLanguageAwareInput is not used here, because // Finish also requires ConversionRequest. std::string composition; Segments segments; commands::Request client_request; client_request.set_language_aware_input( commands::Request::LANGUAGE_AWARE_SUGGESTION); composer::Table table; config::Config default_config; table.InitializeWithRequestAndConfig(client_request, default_config, data_manager_); composer::Composer composer(&table, &client_request, &default_config); InsertASCIISequence("python", &composer); composer.GetStringForPreedit(&composition); EXPECT_EQ(kPyTeyoN, composition); // Perform the rewrite command. segments.set_request_type(Segments::SUGGESTION); Segment *segment = segments.add_segment(); segment->set_key(composition); ConversionRequest request(&composer, &client_request, &default_config); EXPECT_TRUE(rewriter->Rewrite(request, &segments)); EXPECT_COUNT_STATS("LanguageAwareSuggestionTriggered", 2); segment->set_segment_type(Segment::FIXED_VALUE); EXPECT_LT(0, segment->candidates_size()); rewriter->Finish(request, &segments); EXPECT_COUNT_STATS("LanguageAwareSuggestionCommitted", 1); } } TEST_F(LanguageAwareRewriterTest, NotRewriteFullWidthAsciiToHalfWidthAscii) { std::unique_ptr<LanguageAwareRewriter> rewriter( CreateLanguageAwareRewriter()); { // "1d*=" is composed to "1d*=", which are the full width ascii // characters of "1d*=". We do not want to rewrite full width ascii to // half width ascii by LanguageAwareRewriter. std::string composition; Segments segments; EXPECT_FALSE(RewriteWithLanguageAwareInput( rewriter.get(), "1d*=", &composition, &segments)); EXPECT_EQ("1d*=", composition); } { // "xyzw" is composed to "xyzw". Do not rewrite. std::string composition; Segments segments; EXPECT_FALSE(RewriteWithLanguageAwareInput(rewriter.get(), "xyzw", &composition, &segments)); EXPECT_EQ("xyzw", composition); } } TEST_F(LanguageAwareRewriterTest, IsDisabledInTwelveKeyLayout) { dictionary_mock_->AddLookupExact("query", "query", "query", Token::NONE); struct { commands::Request::SpecialRomanjiTable table; config::Config::PreeditMethod preedit_method; int type; } const kParams[] = { // Enabled combinations. {commands::Request::DEFAULT_TABLE, config::Config::ROMAN, RewriterInterface::SUGGESTION | RewriterInterface::PREDICTION}, {commands::Request::QWERTY_MOBILE_TO_HIRAGANA, config::Config::ROMAN, RewriterInterface::SUGGESTION | RewriterInterface::PREDICTION}, // Disabled combinations. {commands::Request::DEFAULT_TABLE, config::Config::KANA, RewriterInterface::NOT_AVAILABLE}, {commands::Request::TWELVE_KEYS_TO_HIRAGANA, config::Config::ROMAN, RewriterInterface::NOT_AVAILABLE}, {commands::Request::TOGGLE_FLICK_TO_HIRAGANA, config::Config::ROMAN, RewriterInterface::NOT_AVAILABLE}, {commands::Request::GODAN_TO_HIRAGANA, config::Config::ROMAN, RewriterInterface::NOT_AVAILABLE}, }; std::unique_ptr<LanguageAwareRewriter> rewriter( CreateLanguageAwareRewriter()); for (const auto &param : kParams) { commands::Request request; request.set_language_aware_input( commands::Request::LANGUAGE_AWARE_SUGGESTION); request.set_special_romanji_table(param.table); config::Config config; config.set_preedit_method(param.preedit_method); composer::Table table; table.InitializeWithRequestAndConfig(request, config, data_manager_); composer::Composer composer(&table, &request, &config); InsertASCIISequence("query", &composer); ConversionRequest conv_request(&composer, &request, &config); EXPECT_EQ(param.type, rewriter->capability(conv_request)); } } } // namespace mozc
bsd-3-clause
kwinkunks/pylasdev
setup.py
661
from setuptools import * setup( name = "pyLASDev", version = "0.8.1", #scripts = ['geo.py'], include_package_data = True, #package_dir = {'': 'package'}, packages = ['pylasdev'], package_data = {'pylasdev': ['*.py']}, # metadata for upload to PyPI author = "Artur Muharlyamov", author_email = "muharlyamovar@ufanipi.ru", description = "Python Log ASCII Standart & Deviation files reader/writer", license = "BSD", keywords = ["geo, wells, las, dev, well, logs, log"] #url = "---", # project home page, if any # could also include long_description, download_url, classifiers, etc. )
bsd-3-clause
rongeb/anit_cms_for_zf3
vendor/zendframework/zend-tag/src/Exception/OutOfBoundsException.php
412
<?php /** * @see https://github.com/zendframework/zend-tag for the canonical source repository * @copyright Copyright (c) 2005-2018 Zend Technologies USA Inc. (https://www.zend.com) * @license https://github.com/zendframework/zend-tag/blob/master/LICENSE.md New BSD License */ namespace Zend\Tag\Exception; class OutOfBoundsException extends \OutOfBoundsException implements ExceptionInterface { }
bsd-3-clause
bqbn/addons-server
src/olympia/landfill/tests/test_users.py
1040
# -*- coding: utf-8 -*- from olympia import amo from olympia.addons.models import Addon, AddonCategory, AddonUser from olympia.amo.tests import TestCase from olympia.constants.categories import CATEGORIES from olympia.landfill.user import generate_addon_user_and_category, generate_user from olympia.users.models import UserProfile class RatingsTests(TestCase): def setUp(self): super(RatingsTests, self).setUp() self.email = 'nobody@mozilla.org' self.addon = Addon.objects.create(type=amo.ADDON_EXTENSION) def test_generate_addon_user_and_category(self): user = UserProfile.objects.create(email=self.email) category = CATEGORIES[amo.FIREFOX.id][amo.ADDON_STATICTHEME]['abstract'] generate_addon_user_and_category(self.addon, user, category) assert AddonCategory.objects.all().count() == 1 assert AddonUser.objects.all().count() == 1 def test_generate_user(self): generate_user(self.email) assert UserProfile.objects.last().email == self.email
bsd-3-clause
actor-framework/actor-framework
libcaf_core/src/serializer.cpp
1047
// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in // the main distribution directory for license terms and copyright or visit // https://github.com/actor-framework/actor-framework/blob/master/LICENSE. #include "caf/serializer.hpp" #include "caf/actor_system.hpp" namespace caf { serializer::serializer(actor_system& sys) noexcept : context_(sys.dummy_execution_unit()) { // nop } serializer::serializer(execution_unit* ctx) noexcept : context_(ctx) { // nop } serializer::~serializer() { // nop } bool serializer::begin_key_value_pair() { return begin_tuple(2); } bool serializer::end_key_value_pair() { return end_tuple(); } bool serializer::begin_associative_array(size_t size) { return begin_sequence(size); } bool serializer::end_associative_array() { return end_sequence(); } bool serializer::list(const std::vector<bool>& xs) { if (!begin_sequence(xs.size())) return false; for (bool x : xs) if (!value(x)) return false; return end_sequence(); } } // namespace caf
bsd-3-clause
boberfly/gaffer
src/GafferUI/DotNodeGadget.cpp
7786
////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2014, Image Engine Design 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 John Haddon nor the names of // any other contributors to this software 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. // ////////////////////////////////////////////////////////////////////////// #include "GafferUI/DotNodeGadget.h" #include "GafferUI/ConnectionGadget.h" #include "GafferUI/GraphGadget.h" #include "GafferUI/Nodule.h" #include "GafferUI/SpacerGadget.h" #include "GafferUI/Style.h" #include "Gaffer/Dot.h" #include "Gaffer/MetadataAlgo.h" #include "Gaffer/ScriptNode.h" #include "Gaffer/StringPlug.h" #include "Gaffer/UndoScope.h" #include "IECoreGL/GL.h" #include "IECoreGL/Selector.h" #include "boost/bind.hpp" using namespace Imath; using namespace IECore; using namespace Gaffer; using namespace GafferUI; GAFFER_GRAPHCOMPONENT_DEFINE_TYPE( DotNodeGadget ); DotNodeGadget::NodeGadgetTypeDescription<DotNodeGadget> DotNodeGadget::g_nodeGadgetTypeDescription( Gaffer::Dot::staticTypeId() ); DotNodeGadget::DotNodeGadget( Gaffer::NodePtr node ) : StandardNodeGadget( node ) { if( !runTimeCast<Dot>( node ) ) { throw Exception( "DotNodeGadget requires a Dot" ); } // Set the contents to have a small size, so the size of the Dot is controlled // largely by the nodeGadget:padding Metadata. setContents( new SpacerGadget( Box3f( V3f( -0.25 ), V3f( 0.25 ) ) ) ); node->plugDirtiedSignal().connect( boost::bind( &DotNodeGadget::plugDirtied, this, ::_1 ) ); node->nameChangedSignal().connect( boost::bind( &DotNodeGadget::nameChanged, this, ::_1 ) ); dragEnterSignal().connect( boost::bind( &DotNodeGadget::dragEnter, this, ::_2 ) ); dropSignal().connect( boost::bind( &DotNodeGadget::drop, this, ::_2 ) ); updateUpstreamNameChangedConnection(); updateLabel(); } DotNodeGadget::~DotNodeGadget() { } void DotNodeGadget::doRenderLayer( Layer layer, const Style *style ) const { if( layer != GraphLayer::Nodes ) { return NodeGadget::doRenderLayer( layer, style ); } Style::State state = getHighlighted() ? Style::HighlightedState : Style::NormalState; const Box3f b = bound(); const V3f s = b.size(); style->renderNodeFrame( Box2f( V2f( 0 ), V2f( 0 ) ), std::min( s.x, s.y ) / 2.0f, state, userColor() ); if( !m_label.empty() && !IECoreGL::Selector::currentSelector() ) { glPushMatrix(); IECoreGL::glTranslate( m_labelPosition ); style->renderText( Style::LabelText, m_label ); glPopMatrix(); } NodeGadget::doRenderLayer( layer, style ); } Gaffer::Dot *DotNodeGadget::dotNode() { return static_cast<Dot *>( node() ); } const Gaffer::Dot *DotNodeGadget::dotNode() const { return static_cast<const Dot *>( node() ); } Gaffer::Node *DotNodeGadget::upstreamNode() { Plug *plug = dotNode()->inPlug(); while( plug && runTimeCast<Dot>( plug->node() ) ) { plug = plug->getInput(); } return plug ? plug->node() : nullptr; } void DotNodeGadget::plugDirtied( const Gaffer::Plug *plug ) { const Dot *dot = dotNode(); if( plug == dot->labelTypePlug() || plug == dot->labelPlug() ) { updateLabel(); } else if( plug == dot->inPlug() ) { updateUpstreamNameChangedConnection(); updateLabel(); } } void DotNodeGadget::nameChanged( const Gaffer::GraphComponent *graphComponent ) { updateLabel(); } void DotNodeGadget::updateUpstreamNameChangedConnection() { m_upstreamNameChangedConnection.disconnect(); if( Node *n = upstreamNode() ) { m_upstreamNameChangedConnection = n->nameChangedSignal().connect( boost::bind( &DotNodeGadget::nameChanged, this, ::_1 ) ); } } void DotNodeGadget::updateLabel() { const Dot *dot = dotNode(); const Dot::LabelType labelType = (Dot::LabelType)dot->labelTypePlug()->getValue(); if( labelType == Dot::None ) { m_label.clear(); } else if( labelType == Dot::NodeName ) { m_label = dot->getName(); } else if( labelType == Dot::UpstreamNodeName ) { const Node *n = upstreamNode(); m_label = n ? n->getName() : ""; } else { m_label = dot->labelPlug()->getValue(); } Edge labelEdge = RightEdge; if( const Plug *p = dot->inPlug() ) { if( connectionTangent( nodule( p ) ).x != 0 ) { labelEdge = TopEdge; } } const Imath::Box3f thisBound = bound(); if( labelEdge == TopEdge ) { const Imath::Box3f labelBound = style()->textBound( Style::LabelText, m_label ); m_labelPosition = V2f( -labelBound.size().x / 2.0, thisBound.max.y + 1.0 ); } else { const Imath::Box3f characterBound = style()->characterBound( Style::LabelText ); m_labelPosition = V2f( thisBound.max.x, thisBound.center().y - characterBound.size().y / 2.0 ); } dirty( DirtyType::Render ); } bool DotNodeGadget::dragEnter( const DragDropEvent &event ) { if( MetadataAlgo::readOnly( dotNode() ) ) { return false; } if( dotNode()->inPlug() ) { // We've already got our plugs set up - StandardNodeGadget // behaviour will take care of everything. return false; } const Plug *plug = runTimeCast<Plug>( event.data.get() ); if( !plug ) { return false; } const GraphGadget *graphGadget = ancestor<GraphGadget>(); if( !graphGadget ) { return false; } const NodeGadget *nodeGadget = graphGadget->nodeGadget( plug->node() ); if( !nodeGadget ) { return false; } const Nodule *nodule = nodeGadget->nodule( plug ); if( !nodule ) { return false; } if( auto connectionCreator = runTimeCast<ConnectionCreator>( event.sourceGadget.get() ) ) { V3f tangent = -nodeGadget->connectionTangent( nodule ); V3f position = ( tangent * bound().size().x / 2.0f ) * fullTransform(); position = position * connectionCreator->fullTransform().inverse(); connectionCreator->updateDragEndPoint( position, tangent ); } return true; } bool DotNodeGadget::drop( const DragDropEvent &event ) { if( dotNode()->inPlug() ) { // We've already got our plugs set up - StandardNodeGadget // behaviour will take care of everything. return false; } Plug *plug = runTimeCast<Plug>( event.data.get() ); if( !plug ) { return false; } Gaffer::UndoScope undoEnabler( node()->ancestor<ScriptNode>() ); dotNode()->setup( plug ); if( plug->direction() == Plug::In ) { plug->setInput( dotNode()->outPlug() ); } else { dotNode()->inPlug()->setInput( plug ); } return true; }
bsd-3-clause
metal/metal-components
build/amd-jquery/metal-incremental-dom/src/incremental-dom.js
38217
define([], function () { 'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; /* jshint ignore:start */ /** * @license * Copyright 2015 The Incremental DOM 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. */ (function (global, factory) { factory(global.IncrementalDOM = global.IncrementalDOM || {}); })(window, function (exports) { 'use strict'; /** * Copyright 2015 The Incremental DOM 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. */ /** * A cached reference to the hasOwnProperty function. */ var hasOwnProperty = Object.prototype.hasOwnProperty; /** * A constructor function that will create blank objects. * @constructor */ function Blank() {} Blank.prototype = Object.create(null); /** * Used to prevent property collisions between our "map" and its prototype. * @param {!Object<string, *>} map The map to check. * @param {string} property The property to check. * @return {boolean} Whether map has property. */ var has = function has(map, property) { return hasOwnProperty.call(map, property); }; /** * Creates an map object without a prototype. * @return {!Object} */ var createMap = function createMap() { return new Blank(); }; /** * The property name where we store Incremental DOM data. */ var DATA_PROP = '__incrementalDOMData'; /** * Keeps track of information needed to perform diffs for a given DOM node. * @param {!string} nodeName * @param {?string=} key * @constructor */ function NodeData(nodeName, key) { /** * The attributes and their values. * @const {!Object<string, *>} */ this.attrs = createMap(); /** * An array of attribute name/value pairs, used for quickly diffing the * incomming attributes to see if the DOM node's attributes need to be * updated. * @const {Array<*>} */ this.attrsArr = []; /** * The incoming attributes for this Node, before they are updated. * @const {!Object<string, *>} */ this.newAttrs = createMap(); /** * Whether or not the statics have been applied for the node yet. * {boolean} */ this.staticsApplied = false; /** * The key used to identify this node, used to preserve DOM nodes when they * move within their parent. * @const */ this.key = key; /** * Keeps track of children within this node by their key. * {!Object<string, !Element>} */ this.keyMap = createMap(); /** * Whether or not the keyMap is currently valid. * @type {boolean} */ this.keyMapValid = true; /** * Whether or the associated node is, or contains, a focused Element. * @type {boolean} */ this.focused = false; /** * The node name for this node. * @const {string} */ this.nodeName = nodeName; /** * @type {?string} */ this.text = null; } /** * Initializes a NodeData object for a Node. * * @param {Node} node The node to initialize data for. * @param {string} nodeName The node name of node. * @param {?string=} key The key that identifies the node. * @return {!NodeData} The newly initialized data object */ var initData = function initData(node, nodeName, key) { var data = new NodeData(nodeName, key); node[DATA_PROP] = data; return data; }; /** * Retrieves the NodeData object for a Node, creating it if necessary. * * @param {?Node} node The Node to retrieve the data for. * @return {!NodeData} The NodeData for this Node. */ var getData = function getData(node) { importNode(node); return node[DATA_PROP]; }; /** * Imports node and its subtree, initializing caches. * * @param {?Node} node The Node to import. */ var importNode = function importNode(node) { if (node[DATA_PROP]) { return; } var isElement = node instanceof Element; var nodeName = isElement ? node.localName : node.nodeName; var key = isElement ? node.getAttribute('key') : null; var data = initData(node, nodeName, key); if (key) { getData(node.parentNode).keyMap[key] = node; } if (isElement) { var attributes = node.attributes; var attrs = data.attrs; var newAttrs = data.newAttrs; var attrsArr = data.attrsArr; for (var i = 0; i < attributes.length; i += 1) { var attr = attributes[i]; var name = attr.name; var value = attr.value; attrs[name] = value; newAttrs[name] = undefined; attrsArr.push(name); attrsArr.push(value); } } for (var child = node.firstChild; child; child = child.nextSibling) { importNode(child); } }; /** * Gets the namespace to create an element (of a given tag) in. * @param {string} tag The tag to get the namespace for. * @param {?Node} parent * @return {?string} The namespace to create the tag in. */ var getNamespaceForTag = function getNamespaceForTag(tag, parent) { if (tag === 'svg') { return 'http://www.w3.org/2000/svg'; } if (getData(parent).nodeName === 'foreignObject') { return null; } return parent.namespaceURI; }; /** * Creates an Element. * @param {Document} doc The document with which to create the Element. * @param {?Node} parent * @param {string} tag The tag for the Element. * @param {?string=} key A key to identify the Element. * @return {!Element} */ var createElement = function createElement(doc, parent, tag, key) { var namespace = getNamespaceForTag(tag, parent); var el = undefined; if (namespace) { el = doc.createElementNS(namespace, tag); } else { el = doc.createElement(tag); } initData(el, tag, key); return el; }; /** * Creates a Text Node. * @param {Document} doc The document with which to create the Element. * @return {!Text} */ var createText = function createText(doc) { var node = doc.createTextNode(''); initData(node, '#text', null); return node; }; /** * Copyright 2015 The Incremental DOM 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. */ /** @const */ var notifications = { /** * Called after patch has compleated with any Nodes that have been created * and added to the DOM. * @type {?function(Array<!Node>)} */ nodesCreated: null, /** * Called after patch has compleated with any Nodes that have been removed * from the DOM. * Note it's an applications responsibility to handle any childNodes. * @type {?function(Array<!Node>)} */ nodesDeleted: null }; /** * Keeps track of the state of a patch. * @constructor */ function Context() { /** * @type {(Array<!Node>|undefined)} */ this.created = notifications.nodesCreated && []; /** * @type {(Array<!Node>|undefined)} */ this.deleted = notifications.nodesDeleted && []; } /** * @param {!Node} node */ Context.prototype.markCreated = function (node) { if (this.created) { this.created.push(node); } }; /** * @param {!Node} node */ Context.prototype.markDeleted = function (node) { if (this.deleted) { this.deleted.push(node); } }; /** * Notifies about nodes that were created during the patch opearation. */ Context.prototype.notifyChanges = function () { if (this.created && this.created.length > 0) { notifications.nodesCreated(this.created); } if (this.deleted && this.deleted.length > 0) { notifications.nodesDeleted(this.deleted); } }; /** * Copyright 2016 The Incremental DOM 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. */ /** * @param {!Node} node * @return {boolean} True if the node the root of a document, false otherwise. */ var isDocumentRoot = function isDocumentRoot(node) { // For ShadowRoots, check if they are a DocumentFragment instead of if they // are a ShadowRoot so that this can work in 'use strict' if ShadowRoots are // not supported. return node instanceof Document || node instanceof DocumentFragment; }; /** * @param {!Node} node The node to start at, inclusive. * @param {?Node} root The root ancestor to get until, exclusive. * @return {!Array<!Node>} The ancestry of DOM nodes. */ var getAncestry = function getAncestry(node, root) { var ancestry = []; var cur = node; while (cur !== root) { ancestry.push(cur); cur = cur.parentNode; } return ancestry; }; /** * @param {!Node} node * @return {!Node} The root node of the DOM tree that contains node. */ var getRoot = function getRoot(node) { var cur = node; var prev = cur; while (cur) { prev = cur; cur = cur.parentNode; } return prev; }; /** * @param {!Node} node The node to get the activeElement for. * @return {?Element} The activeElement in the Document or ShadowRoot * corresponding to node, if present. */ var getActiveElement = function getActiveElement(node) { var root = getRoot(node); return isDocumentRoot(root) ? root.activeElement : null; }; /** * Gets the path of nodes that contain the focused node in the same document as * a reference node, up until the root. * @param {!Node} node The reference node to get the activeElement for. * @param {?Node} root The root to get the focused path until. * @return {!Array<Node>} */ var getFocusedPath = function getFocusedPath(node, root) { var activeElement = getActiveElement(node); if (!activeElement || !node.contains(activeElement)) { return []; } return getAncestry(activeElement, root); }; /** * Like insertBefore, but instead instead of moving the desired node, instead * moves all the other nodes after. * @param {?Node} parentNode * @param {!Node} node * @param {?Node} referenceNode */ var moveBefore = function moveBefore(parentNode, node, referenceNode) { var insertReferenceNode = node.nextSibling; var cur = referenceNode; while (cur !== node) { var next = cur.nextSibling; parentNode.insertBefore(cur, insertReferenceNode); cur = next; } }; /** @type {?Context} */ var context = null; /** @type {?Node} */ var currentNode = null; /** @type {?Node} */ var currentParent = null; /** @type {?Document} */ var doc = null; /** * @param {!Array<Node>} focusPath The nodes to mark. * @param {boolean} focused Whether or not they are focused. */ var markFocused = function markFocused(focusPath, focused) { for (var i = 0; i < focusPath.length; i += 1) { getData(focusPath[i]).focused = focused; } }; /** * Returns a patcher function that sets up and restores a patch context, * running the run function with the provided data. * @param {function((!Element|!DocumentFragment),!function(T),T=): ?Node} run * @return {function((!Element|!DocumentFragment),!function(T),T=): ?Node} * @template T */ var patchFactory = function patchFactory(run) { /** * TODO(moz): These annotations won't be necessary once we switch to Closure * Compiler's new type inference. Remove these once the switch is done. * * @param {(!Element|!DocumentFragment)} node * @param {!function(T)} fn * @param {T=} data * @return {?Node} node * @template T */ var f = function f(node, fn, data) { var prevContext = context; var prevDoc = doc; var prevCurrentNode = currentNode; var prevCurrentParent = currentParent; var previousInAttributes = false; var previousInSkip = false; context = new Context(); doc = node.ownerDocument; currentParent = node.parentNode; if ('production' !== 'production') {} var focusPath = getFocusedPath(node, currentParent); markFocused(focusPath, true); var retVal = run(node, fn, data); markFocused(focusPath, false); if ('production' !== 'production') {} context.notifyChanges(); context = prevContext; doc = prevDoc; currentNode = prevCurrentNode; currentParent = prevCurrentParent; return retVal; }; return f; }; /** * Patches the document starting at node with the provided function. This * function may be called during an existing patch operation. * @param {!Element|!DocumentFragment} node The Element or Document * to patch. * @param {!function(T)} fn A function containing elementOpen/elementClose/etc. * calls that describe the DOM. * @param {T=} data An argument passed to fn to represent DOM state. * @return {!Node} The patched node. * @template T */ var patchInner = patchFactory(function (node, fn, data) { currentNode = node; enterNode(); fn(data); exitNode(); if ('production' !== 'production') {} return node; }); /** * Patches an Element with the the provided function. Exactly one top level * element call should be made corresponding to `node`. * @param {!Element} node The Element where the patch should start. * @param {!function(T)} fn A function containing elementOpen/elementClose/etc. * calls that describe the DOM. This should have at most one top level * element call. * @param {T=} data An argument passed to fn to represent DOM state. * @return {?Node} The node if it was updated, its replacedment or null if it * was removed. * @template T */ var patchOuter = patchFactory(function (node, fn, data) { var startNode = /** @type {!Element} */{ nextSibling: node }; var expectedNextNode = null; var expectedPrevNode = null; if ('production' !== 'production') {} currentNode = startNode; fn(data); if ('production' !== 'production') {} if (node !== currentNode && node.parentNode) { removeChild(currentParent, node, getData(currentParent).keyMap); } return startNode === currentNode ? null : currentNode; }); /** * Checks whether or not the current node matches the specified nodeName and * key. * * @param {!Node} matchNode A node to match the data to. * @param {?string} nodeName The nodeName for this node. * @param {?string=} key An optional key that identifies a node. * @return {boolean} True if the node matches, false otherwise. */ var matches = function matches(matchNode, nodeName, key) { var data = getData(matchNode); // Key check is done using double equals as we want to treat a null key the // same as undefined. This should be okay as the only values allowed are // strings, null and undefined so the == semantics are not too weird. return nodeName === data.nodeName && key == data.key; }; /** * Aligns the virtual Element definition with the actual DOM, moving the * corresponding DOM node to the correct location or creating it if necessary. * @param {string} nodeName For an Element, this should be a valid tag string. * For a Text, this should be #text. * @param {?string=} key The key used to identify this element. */ var alignWithDOM = function alignWithDOM(nodeName, key) { if (currentNode && matches(currentNode, nodeName, key)) { return; } var parentData = getData(currentParent); var currentNodeData = currentNode && getData(currentNode); var keyMap = parentData.keyMap; var node = undefined; // Check to see if the node has moved within the parent. if (key) { var keyNode = keyMap[key]; if (keyNode) { if (matches(keyNode, nodeName, key)) { node = keyNode; } else if (keyNode === currentNode) { context.markDeleted(keyNode); } else { removeChild(currentParent, keyNode, keyMap); } } } // Create the node if it doesn't exist. if (!node) { if (nodeName === '#text') { node = createText(doc); } else { node = createElement(doc, currentParent, nodeName, key); } if (key) { keyMap[key] = node; } context.markCreated(node); } // Re-order the node into the right position, preserving focus if either // node or currentNode are focused by making sure that they are not detached // from the DOM. if (getData(node).focused) { // Move everything else before the node. moveBefore(currentParent, node, currentNode); } else if (currentNodeData && currentNodeData.key && !currentNodeData.focused) { // Remove the currentNode, which can always be added back since we hold a // reference through the keyMap. This prevents a large number of moves when // a keyed item is removed or moved backwards in the DOM. currentParent.replaceChild(node, currentNode); parentData.keyMapValid = false; } else { currentParent.insertBefore(node, currentNode); } currentNode = node; }; /** * @param {?Node} node * @param {?Node} child * @param {?Object<string, !Element>} keyMap */ var removeChild = function removeChild(node, child, keyMap) { node.removeChild(child); context.markDeleted( /** @type {!Node}*/child); var key = getData(child).key; if (key) { delete keyMap[key]; } }; /** * Clears out any unvisited Nodes, as the corresponding virtual element * functions were never called for them. */ var clearUnvisitedDOM = function clearUnvisitedDOM() { var node = currentParent; var data = getData(node); var keyMap = data.keyMap; var keyMapValid = data.keyMapValid; var child = node.lastChild; var key = undefined; if (child === currentNode && keyMapValid) { return; } while (child !== currentNode) { removeChild(node, child, keyMap); child = node.lastChild; } // Clean the keyMap, removing any unusued keys. if (!keyMapValid) { for (key in keyMap) { child = keyMap[key]; if (child.parentNode !== node) { context.markDeleted(child); delete keyMap[key]; } } data.keyMapValid = true; } }; /** * Changes to the first child of the current node. */ var enterNode = function enterNode() { currentParent = currentNode; currentNode = null; }; /** * @return {?Node} The next Node to be patched. */ var getNextNode = function getNextNode() { if (currentNode) { return currentNode.nextSibling; } else { return currentParent.firstChild; } }; /** * Changes to the next sibling of the current node. */ var nextNode = function nextNode() { currentNode = getNextNode(); }; /** * Changes to the parent of the current node, removing any unvisited children. */ var exitNode = function exitNode() { clearUnvisitedDOM(); currentNode = currentParent; currentParent = currentParent.parentNode; }; /** * Makes sure that the current node is an Element with a matching tagName and * key. * * @param {string} tag The element's tag. * @param {?string=} key The key used to identify this element. This can be an * empty string, but performance may be better if a unique value is used * when iterating over an array of items. * @return {!Element} The corresponding Element. */ var coreElementOpen = function coreElementOpen(tag, key) { nextNode(); alignWithDOM(tag, key); enterNode(); return (/** @type {!Element} */currentParent ); }; /** * Closes the currently open Element, removing any unvisited children if * necessary. * * @return {!Element} The corresponding Element. */ var coreElementClose = function coreElementClose() { if ('production' !== 'production') {} exitNode(); return (/** @type {!Element} */currentNode ); }; /** * Makes sure the current node is a Text node and creates a Text node if it is * not. * * @return {!Text} The corresponding Text Node. */ var coreText = function coreText() { nextNode(); alignWithDOM('#text', null); return (/** @type {!Text} */currentNode ); }; /** * Gets the current Element being patched. * @return {!Element} */ var currentElement = function currentElement() { if ('production' !== 'production') {} return (/** @type {!Element} */currentParent ); }; /** * @return {Node} The Node that will be evaluated for the next instruction. */ var currentPointer = function currentPointer() { if ('production' !== 'production') {} return getNextNode(); }; /** * Skips the children in a subtree, allowing an Element to be closed without * clearing out the children. */ var skip = function skip() { if ('production' !== 'production') {} currentNode = currentParent.lastChild; }; /** * Skips the next Node to be patched, moving the pointer forward to the next * sibling of the current pointer. */ var skipNode = nextNode; /** * Copyright 2015 The Incremental DOM 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. */ /** @const */ var symbols = { default: '__default' }; /** * @param {string} name * @return {string|undefined} The namespace to use for the attribute. */ var getNamespace = function getNamespace(name) { if (name.lastIndexOf('xml:', 0) === 0) { return 'http://www.w3.org/XML/1998/namespace'; } if (name.lastIndexOf('xlink:', 0) === 0) { return 'http://www.w3.org/1999/xlink'; } }; /** * Applies an attribute or property to a given Element. If the value is null * or undefined, it is removed from the Element. Otherwise, the value is set * as an attribute. * @param {!Element} el * @param {string} name The attribute's name. * @param {?(boolean|number|string)=} value The attribute's value. */ var applyAttr = function applyAttr(el, name, value) { if (value == null) { el.removeAttribute(name); } else { var attrNS = getNamespace(name); if (attrNS) { el.setAttributeNS(attrNS, name, value); } else { el.setAttribute(name, value); } } }; /** * Applies a property to a given Element. * @param {!Element} el * @param {string} name The property's name. * @param {*} value The property's value. */ var applyProp = function applyProp(el, name, value) { el[name] = value; }; /** * Applies a value to a style declaration. Supports CSS custom properties by * setting properties containing a dash using CSSStyleDeclaration.setProperty. * @param {CSSStyleDeclaration} style * @param {!string} prop * @param {*} value */ var setStyleValue = function setStyleValue(style, prop, value) { if (prop.indexOf('-') >= 0) { style.setProperty(prop, /** @type {string} */value); } else { style[prop] = value; } }; /** * Applies a style to an Element. No vendor prefix expansion is done for * property names/values. * @param {!Element} el * @param {string} name The attribute's name. * @param {*} style The style to set. Either a string of css or an object * containing property-value pairs. */ var applyStyle = function applyStyle(el, name, style) { if (typeof style === 'string') { el.style.cssText = style; } else { el.style.cssText = ''; var elStyle = el.style; var obj = /** @type {!Object<string,string>} */style; for (var prop in obj) { if (has(obj, prop)) { setStyleValue(elStyle, prop, obj[prop]); } } } }; /** * Updates a single attribute on an Element. * @param {!Element} el * @param {string} name The attribute's name. * @param {*} value The attribute's value. If the value is an object or * function it is set on the Element, otherwise, it is set as an HTML * attribute. */ var applyAttributeTyped = function applyAttributeTyped(el, name, value) { var type = typeof value === 'undefined' ? 'undefined' : _typeof(value); if (type === 'object' || type === 'function') { applyProp(el, name, value); } else { applyAttr(el, name, /** @type {?(boolean|number|string)} */value); } }; /** * Calls the appropriate attribute mutator for this attribute. * @param {!Element} el * @param {string} name The attribute's name. * @param {*} value The attribute's value. */ var updateAttribute = function updateAttribute(el, name, value) { var data = getData(el); var attrs = data.attrs; if (attrs[name] === value) { return; } var mutator = attributes[name] || attributes[symbols.default]; mutator(el, name, value); attrs[name] = value; }; /** * A publicly mutable object to provide custom mutators for attributes. * @const {!Object<string, function(!Element, string, *)>} */ var attributes = createMap(); // Special generic mutator that's called for any attribute that does not // have a specific mutator. attributes[symbols.default] = applyAttributeTyped; attributes['style'] = applyStyle; /** * The offset in the virtual element declaration where the attributes are * specified. * @const */ var ATTRIBUTES_OFFSET = 3; /** * Builds an array of arguments for use with elementOpenStart, attr and * elementOpenEnd. * @const {Array<*>} */ var argsBuilder = []; /** * @param {string} tag The element's tag. * @param {?string=} key The key used to identify this element. This can be an * empty string, but performance may be better if a unique value is used * when iterating over an array of items. * @param {?Array<*>=} statics An array of attribute name/value pairs of the * static attributes for the Element. These will only be set once when the * Element is created. * @param {...*} var_args, Attribute name/value pairs of the dynamic attributes * for the Element. * @return {!Element} The corresponding Element. */ var elementOpen = function elementOpen(tag, key, statics, var_args) { if ('production' !== 'production') {} var node = coreElementOpen(tag, key); var data = getData(node); if (!data.staticsApplied) { if (statics) { for (var _i = 0; _i < statics.length; _i += 2) { var name = /** @type {string} */statics[_i]; var value = statics[_i + 1]; updateAttribute(node, name, value); } } // Down the road, we may want to keep track of the statics array to use it // as an additional signal about whether a node matches or not. For now, // just use a marker so that we do not reapply statics. data.staticsApplied = true; } /* * Checks to see if one or more attributes have changed for a given Element. * When no attributes have changed, this is much faster than checking each * individual argument. When attributes have changed, the overhead of this is * minimal. */ var attrsArr = data.attrsArr; var newAttrs = data.newAttrs; var isNew = !attrsArr.length; var i = ATTRIBUTES_OFFSET; var j = 0; for (; i < arguments.length; i += 2, j += 2) { var _attr = arguments[i]; if (isNew) { attrsArr[j] = _attr; newAttrs[_attr] = undefined; } else if (attrsArr[j] !== _attr) { break; } var value = arguments[i + 1]; if (isNew || attrsArr[j + 1] !== value) { attrsArr[j + 1] = value; updateAttribute(node, _attr, value); } } if (i < arguments.length || j < attrsArr.length) { for (; i < arguments.length; i += 1, j += 1) { attrsArr[j] = arguments[i]; } if (j < attrsArr.length) { attrsArr.length = j; } /* * Actually perform the attribute update. */ for (i = 0; i < attrsArr.length; i += 2) { var name = /** @type {string} */attrsArr[i]; var value = attrsArr[i + 1]; newAttrs[name] = value; } for (var _attr2 in newAttrs) { updateAttribute(node, _attr2, newAttrs[_attr2]); newAttrs[_attr2] = undefined; } } return node; }; /** * Declares a virtual Element at the current location in the document. This * corresponds to an opening tag and a elementClose tag is required. This is * like elementOpen, but the attributes are defined using the attr function * rather than being passed as arguments. Must be folllowed by 0 or more calls * to attr, then a call to elementOpenEnd. * @param {string} tag The element's tag. * @param {?string=} key The key used to identify this element. This can be an * empty string, but performance may be better if a unique value is used * when iterating over an array of items. * @param {?Array<*>=} statics An array of attribute name/value pairs of the * static attributes for the Element. These will only be set once when the * Element is created. */ var elementOpenStart = function elementOpenStart(tag, key, statics) { if ('production' !== 'production') {} argsBuilder[0] = tag; argsBuilder[1] = key; argsBuilder[2] = statics; }; /*** * Defines a virtual attribute at this point of the DOM. This is only valid * when called between elementOpenStart and elementOpenEnd. * * @param {string} name * @param {*} value */ var attr = function attr(name, value) { if ('production' !== 'production') {} argsBuilder.push(name); argsBuilder.push(value); }; /** * Closes an open tag started with elementOpenStart. * @return {!Element} The corresponding Element. */ var elementOpenEnd = function elementOpenEnd() { if ('production' !== 'production') {} var node = elementOpen.apply(null, argsBuilder); argsBuilder.length = 0; return node; }; /** * Closes an open virtual Element. * * @param {string} tag The element's tag. * @return {!Element} The corresponding Element. */ var elementClose = function elementClose(tag) { if ('production' !== 'production') {} var node = coreElementClose(); if ('production' !== 'production') {} return node; }; /** * Declares a virtual Element at the current location in the document that has * no children. * @param {string} tag The element's tag. * @param {?string=} key The key used to identify this element. This can be an * empty string, but performance may be better if a unique value is used * when iterating over an array of items. * @param {?Array<*>=} statics An array of attribute name/value pairs of the * static attributes for the Element. These will only be set once when the * Element is created. * @param {...*} var_args Attribute name/value pairs of the dynamic attributes * for the Element. * @return {!Element} The corresponding Element. */ var elementVoid = function elementVoid(tag, key, statics, var_args) { elementOpen.apply(null, arguments); return elementClose(tag); }; /** * Declares a virtual Text at this point in the document. * * @param {string|number|boolean} value The value of the Text. * @param {...(function((string|number|boolean)):string)} var_args * Functions to format the value which are called only when the value has * changed. * @return {!Text} The corresponding text node. */ var text = function text(value, var_args) { if ('production' !== 'production') {} var node = coreText(); var data = getData(node); if (data.text !== value) { data.text = /** @type {string} */value; var formatted = value; for (var i = 1; i < arguments.length; i += 1) { /* * Call the formatter function directly to prevent leaking arguments. * https://github.com/google/incremental-dom/pull/204#issuecomment-178223574 */ var fn = arguments[i]; formatted = fn(formatted); } node.data = formatted; } return node; }; exports.patch = patchInner; exports.patchInner = patchInner; exports.patchOuter = patchOuter; exports.currentElement = currentElement; exports.currentPointer = currentPointer; exports.skip = skip; exports.skipNode = skipNode; exports.elementVoid = elementVoid; exports.elementOpenStart = elementOpenStart; exports.elementOpenEnd = elementOpenEnd; exports.elementOpen = elementOpen; exports.elementClose = elementClose; exports.text = text; exports.attr = attr; exports.symbols = symbols; exports.attributes = attributes; exports.applyAttr = applyAttr; exports.applyProp = applyProp; exports.notifications = notifications; exports.importNode = importNode; }); /* jshint ignore:end */ }); //# sourceMappingURL=incremental-dom.js.map
bsd-3-clause
celiafish/VisTrails
vistrails/gui/modules/list_configuration.py
5171
from PyQt4 import QtCore, QtGui from vistrails.core.system import get_vistrails_basic_pkg_id from vistrails.gui.modules.module_configure import StandardModuleConfigurationWidget class ListConfigurationWidget(StandardModuleConfigurationWidget): """ Configuration widget allowing to choose the number of ports. This is used to build a List from several modules while ensuring a given order. If no particular ordering is needed, connecting multiple ports to the 'head' input ports should be sufficient. """ def __init__(self, module, controller, parent=None): """ ListConfigurationWidget(module: Module, controller: VistrailController, parent: QWidget) -> TupleConfigurationWidget Let StandardModuleConfigurationWidget constructor store the controller/module object from the builder and set up the configuration widget. After StandardModuleConfigurationWidget constructor, all of these will be available: self.module : the Module object int the pipeline self.controller: the current vistrail controller """ StandardModuleConfigurationWidget.__init__(self, module, controller, parent) # Give it a nice window title self.setWindowTitle("List Configuration") # Add an empty vertical layout centralLayout = QtGui.QVBoxLayout() centralLayout.setMargin(0) centralLayout.setSpacing(0) self.setLayout(centralLayout) # Add the configuration widget config_layout = QtGui.QFormLayout() self.number = QtGui.QSpinBox() self.number.setValue(self.countAdditionalPorts()) self.connect(self.number, QtCore.SIGNAL('valueChanged(int)'), lambda r: self.updateState()) config_layout.addRow("Number of additional connections:", self.number) centralLayout.addLayout(config_layout) self.createButtons() def activate(self): self.number.focusWidget(QtCore.Qt.ActiveWindowFocusReason) def createButtons(self): """ createButtons() -> None Create and connect signals to Ok & Cancel button """ self.buttonLayout = QtGui.QHBoxLayout() self.buttonLayout.setMargin(5) self.saveButton = QtGui.QPushButton("&Save", self) self.saveButton.setFixedWidth(100) self.saveButton.setEnabled(False) self.buttonLayout.addWidget(self.saveButton) self.resetButton = QtGui.QPushButton("&Reset", self) self.resetButton.setFixedWidth(100) self.resetButton.setEnabled(False) self.buttonLayout.addWidget(self.resetButton) self.layout().addLayout(self.buttonLayout) self.connect(self.saveButton, QtCore.SIGNAL('clicked(bool)'), self.saveTriggered) self.connect(self.resetButton, QtCore.SIGNAL('clicked(bool)'), self.resetTriggered) def saveTriggered(self, checked = False): """ saveTriggered(checked: bool) -> None Update vistrail controller and module when the user click Ok """ if self.updateVistrail(): self.saveButton.setEnabled(False) self.resetButton.setEnabled(False) self.state_changed = False self.emit(QtCore.SIGNAL('stateChanged')) self.emit(QtCore.SIGNAL('doneConfigure'), self.module.id) def closeEvent(self, event): self.askToSaveChanges() event.accept() def updateVistrail(self): """ updateVistrail() -> None Update Vistrail to contain changes in the port table """ requested = self.number.value() current = self.countAdditionalPorts() if requested == current: # Nothing changed return if requested > current: sigstring = '(%s:Module)' % get_vistrails_basic_pkg_id() add_ports = [('input', 'item%d' % i, sigstring, -1) for i in xrange(current, requested)] self.controller.update_ports(self.module.id, [], add_ports) elif requested < current: delete_ports = [('input', p.name) for p in self.module.input_port_specs[requested-current:]] self.controller.update_ports(self.module.id, delete_ports, []) return True def countAdditionalPorts(self): return len(self.module.input_port_specs) def resetTriggered(self, checked = False): self.number.setValue(self.countAdditionalPorts()) self.saveButton.setEnabled(False) self.resetButton.setEnabled(False) self.state_changed = False self.emit(QtCore.SIGNAL('stateChanged')) def updateState(self): if not self.hasFocus(): self.setFocus(QtCore.Qt.TabFocusReason) self.saveButton.setEnabled(True) self.resetButton.setEnabled(True) if not self.state_changed: self.state_changed = True self.emit(QtCore.SIGNAL('stateChanged'))
bsd-3-clause
svagionitis/MIST
test/margin_array_test.cpp
2731
// // Copyright (c) 2003-2010, MIST Project, Nagoya University // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of the Nagoya University 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. // #include <iostream> #include <mist/mist.h> int main( int argc, char *argv[] ) { using namespace std; argc = 0; cout << "Running " << argv[argc] << endl; typedef mist::array2< double >::size_type size_type; mist::array2< double > a( 5, 5 ); a( 0, 0 ) = 0.1; a( 0, 1 ) = 0.2; a( 0, 2 ) = 0.1; a( 0, 3 ) = 0.6; a( 0, 4 ) = 0.4; a( 1, 0 ) = 0.3; a( 1, 1 ) = 4.1; a( 1, 2 ) = 5.2; a( 1, 3 ) = 4.7; a( 1, 4 ) = 0.3; a( 2, 0 ) = 0.2; a( 2, 1 ) = 3.5; a( 2, 2 ) = 2.8; a( 2, 3 ) = 3.9; a( 2, 4 ) = 0.8; a( 3, 0 ) = 0.4; a( 3, 1 ) = 4.2; a( 3, 2 ) = 5.9; a( 3, 3 ) = 4.2; a( 3, 4 ) = 0.9; a( 4, 0 ) = 0.2; a( 4, 1 ) = 0.3; a( 4, 2 ) = 0.1; a( 4, 3 ) = 0.1; a( 4, 4 ) = 0.4; mist::marray< mist::array2< int > > m( a, 2, 1, 1 ); for( size_type j = 0 ; j < m.height( ) ; j++ ) { for( size_type i = 0 ; i < m.width( ) ; i++ ) { m( i, j ) = static_cast< int >( i + j * m.width( ) ); } } std::cout << a << std::endl << std::endl; std::cout << m << std::endl << std::endl; m = a; std::cout << m << std::endl << std::endl; m.fill_margin( 9 ); std::cout << m << std::endl << std::endl; return( 0 ); }
bsd-3-clause
ChromeDevTools/devtools-frontend
node_modules/stylelint/lib/lintSource.js
3366
'use strict'; const isPathNotFoundError = require('./utils/isPathNotFoundError'); const lintPostcssResult = require('./lintPostcssResult'); const path = require('path'); /** @typedef {import('stylelint').InternalApi} StylelintInternalApi */ /** @typedef {import('stylelint').GetLintSourceOptions} Options */ /** @typedef {import('postcss').Result} Result */ /** @typedef {import('stylelint').PostcssResult} PostcssResult */ /** @typedef {import('stylelint').StylelintPostcssResult} StylelintPostcssResult */ /** * Run stylelint on a PostCSS Result, either one that is provided * or one that we create * @param {StylelintInternalApi} stylelint * @param {Options} options * @returns {Promise<PostcssResult>} */ module.exports = async function lintSource(stylelint, options = {}) { if (!options.filePath && options.code === undefined && !options.existingPostcssResult) { return Promise.reject(new Error('You must provide filePath, code, or existingPostcssResult')); } const isCodeNotFile = options.code !== undefined; const inputFilePath = isCodeNotFile ? options.codeFilename : options.filePath; if (inputFilePath !== undefined && !path.isAbsolute(inputFilePath)) { if (isCodeNotFile) { return Promise.reject(new Error('codeFilename must be an absolute path')); } return Promise.reject(new Error('filePath must be an absolute path')); } const isIgnored = await stylelint.isPathIgnored(inputFilePath).catch((err) => { if (isCodeNotFile && isPathNotFoundError(err)) return false; throw err; }); if (isIgnored) { return options.existingPostcssResult ? Object.assign(options.existingPostcssResult, { stylelint: createEmptyStylelintPostcssResult(), }) : createEmptyPostcssResult(inputFilePath); } const configSearchPath = stylelint._options.configFile || inputFilePath; const cwd = stylelint._options.cwd; const configForFile = await stylelint .getConfigForFile(configSearchPath, inputFilePath) .catch((err) => { if (isCodeNotFile && isPathNotFoundError(err)) return stylelint.getConfigForFile(cwd); throw err; }); if (!configForFile) { return Promise.reject(new Error('Config file not found')); } const config = configForFile.config; const existingPostcssResult = options.existingPostcssResult; const stylelintResult = { ruleSeverities: {}, customMessages: {}, disabledRanges: {}, }; const postcssResult = existingPostcssResult || (await stylelint._getPostcssResult({ code: options.code, codeFilename: options.codeFilename, filePath: inputFilePath, codeProcessors: config.codeProcessors, customSyntax: config.customSyntax, })); const stylelintPostcssResult = Object.assign(postcssResult, { stylelint: stylelintResult, }); await lintPostcssResult(stylelint._options, stylelintPostcssResult, config); return stylelintPostcssResult; }; /** * @returns {StylelintPostcssResult} */ function createEmptyStylelintPostcssResult() { return { ruleSeverities: {}, customMessages: {}, disabledRanges: {}, ignored: true, stylelintError: false, }; } /** * @param {string} [filePath] * @returns {PostcssResult} */ function createEmptyPostcssResult(filePath) { return { root: { source: { input: { file: filePath }, }, }, messages: [], opts: undefined, stylelint: createEmptyStylelintPostcssResult(), warn: () => {}, }; }
bsd-3-clause
tenstartups/wal-e
tests/gs_integration_help.py
3966
from gcloud import exceptions from gcloud import storage import base64 import hmac import json import os import pytest MANGLE_SUFFIX = None def bucket_name_mangle(bn, delimiter='-'): global MANGLE_SUFFIX if MANGLE_SUFFIX is None: MANGLE_SUFFIX = compute_mangle_suffix() return bn + delimiter + MANGLE_SUFFIX def compute_mangle_suffix(): with open(os.getenv('GOOGLE_APPLICATION_CREDENTIALS')) as f: cj = json.load(f) dm = hmac.new(b'wal-e-tests') dm.update(cj['client_id'].encode('utf-8')) dg = dm.digest() return base64.b32encode(dg[:10]).decode('utf-8').lower() def no_real_gs_credentials(): """Helps skip integration tests without live credentials. Phrased in the negative to make it read better with 'skipif'. """ if os.getenv('WALE_GS_INTEGRATION_TESTS') != 'TRUE': return True if os.getenv('GOOGLE_APPLICATION_CREDENTIALS') is None: return True return False def prepare_gs_default_test_bucket(): # Check credentials are present: this procedure should not be # called otherwise. if no_real_gs_credentials(): assert False bucket_name = bucket_name_mangle('waletdefwuy', delimiter='') conn = storage.Client() def _clean(): bucket = conn.get_bucket(bucket_name) for blob in bucket.list_blobs(): try: bucket.delete_blob(blob.path) except exceptions.NotFound: pass try: conn.create_bucket(bucket_name) except exceptions.Conflict: # Conflict: bucket already present. Re-use it, but # clean it out first. pass _clean() return bucket_name @pytest.fixture(scope='session') def default_test_gs_bucket(): if not no_real_gs_credentials(): return prepare_gs_default_test_bucket() def apathetic_bucket_delete(bucket_name, blobs, *args, **kwargs): conn = storage.Client() bucket = storage.Bucket(conn, name=bucket_name) if bucket: # Delete key names passed by the test code. bucket.delete_blobs(blobs) try: bucket.delete() except exceptions.NotFound: pass return conn def insistent_bucket_delete(conn, bucket_name, blobs): bucket = conn.get_bucket(bucket_name) if bucket: # Delete key names passed by the test code. bucket.delete_blobs(blobs) while True: try: bucket.delete() except exceptions.NotFound: continue break def insistent_bucket_create(conn, bucket_name, *args, **kwargs): while True: try: bucket = conn.create_bucket(bucket_name, *args, **kwargs) except exceptions.Conflict: # Bucket already created -- probably means the prior # delete did not process just yet. continue return bucket class FreshBucket(object): def __init__(self, bucket_name, blobs=[], *args, **kwargs): self.bucket_name = bucket_name self.blobs = blobs self.conn_args = args self.conn_kwargs = kwargs self.created_bucket = False def __enter__(self): # Clean up a dangling bucket from a previous test run, if # necessary. self.conn = apathetic_bucket_delete(self.bucket_name, self.blobs, *self.conn_args, **self.conn_kwargs) return self def create(self, *args, **kwargs): bucket = insistent_bucket_create(self.conn, self.bucket_name, *args, **kwargs) self.created_bucket = True return bucket def __exit__(self, typ, value, traceback): if not self.created_bucket: return False insistent_bucket_delete(self.conn, self.bucket_name, self.blobs) return False
bsd-3-clause
vicky2135/lucious
oscar/lib/python2.7/site-packages/pytest_django/django_compat.py
417
# Note that all functions here assume django is available. So ensure # this is the case before you call them. def is_django_unittest(request_or_item): """Returns True if the request_or_item is a Django test case, otherwise False""" from django.test import SimpleTestCase cls = getattr(request_or_item, 'cls', None) if cls is None: return False return issubclass(cls, SimpleTestCase)
bsd-3-clause
PolymerLabs/arcs-live
concrete-storage/node_modules/@firebase/messaging/dist/src/interfaces/vapid-details.d.ts
707
/** * @license * Copyright 2018 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. */ export interface VapidDetails { swScope: string; vapidKey: Uint8Array; }
bsd-3-clause
7kbird/chrome
content/browser/fileapi/timed_task_helper_unittest.cc
2152
// 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/basictypes.h" #include "base/bind.h" #include "base/location.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop_proxy.h" #include "base/run_loop.h" #include "base/time/time.h" #include "testing/gtest/include/gtest/gtest.h" #include "webkit/browser/fileapi/timed_task_helper.h" using storage::TimedTaskHelper; namespace content { namespace { class Embedder { public: Embedder() : timer_(base::MessageLoopProxy::current().get()), timer_fired_(false) {} void OnTimerFired() { timer_fired_ = true; } TimedTaskHelper* timer() { return &timer_; } bool timer_fired() const { return timer_fired_; } private: TimedTaskHelper timer_; bool timer_fired_; }; } // namespace TEST(TimedTaskHelper, FireTimerWhenAlive) { base::MessageLoop message_loop; Embedder embedder; ASSERT_FALSE(embedder.timer_fired()); ASSERT_FALSE(embedder.timer()->IsRunning()); embedder.timer()->Start( FROM_HERE, base::TimeDelta::FromSeconds(0), base::Bind(&Embedder::OnTimerFired, base::Unretained(&embedder))); ASSERT_TRUE(embedder.timer()->IsRunning()); embedder.timer()->Reset(); ASSERT_TRUE(embedder.timer()->IsRunning()); base::RunLoop().RunUntilIdle(); ASSERT_TRUE(embedder.timer_fired()); } TEST(TimedTaskHelper, FireTimerWhenAlreadyDeleted) { base::MessageLoop message_loop; // Run message loop after embedder is already deleted to make sure callback // doesn't cause a crash for use after free. { Embedder embedder; ASSERT_FALSE(embedder.timer_fired()); ASSERT_FALSE(embedder.timer()->IsRunning()); embedder.timer()->Start( FROM_HERE, base::TimeDelta::FromSeconds(0), base::Bind(&Embedder::OnTimerFired, base::Unretained(&embedder))); ASSERT_TRUE(embedder.timer()->IsRunning()); } // At this point the callback is still in the message queue but // embedder is gone. base::RunLoop().RunUntilIdle(); } } // namespace content
bsd-3-clause
ulope/django-watchman
watchman/settings.py
1022
from django.conf import settings # TODO: these should not be module level (https://github.com/mwarkentin/django-watchman/issues/13) WATCHMAN_ENABLE_PAID_CHECKS = getattr(settings, 'WATCHMAN_ENABLE_PAID_CHECKS', False) WATCHMAN_AUTH_DECORATOR = getattr(settings, 'WATCHMAN_AUTH_DECORATOR', 'watchman.decorators.token_required') WATCHMAN_TOKEN = getattr(settings, 'WATCHMAN_TOKEN', None) WATCHMAN_TOKEN_NAME = getattr(settings, 'WATCHMAN_TOKEN_NAME', 'watchman-token') WATCHMAN_ERROR_CODE = getattr(settings, 'WATCHMAN_ERROR_CODE', 500) WATCHMAN_EMAIL_RECIPIENTS = getattr(settings, 'WATCHMAN_EMAIL_RECIPIENTS', ['to@example.com']) WATCHMAN_EMAIL_HEADERS = getattr(settings, 'WATCHMAN_EMAIL_HEADERS', {}) DEFAULT_CHECKS = ( 'watchman.checks.caches', 'watchman.checks.databases', 'watchman.checks.storage', ) PAID_CHECKS = ( 'watchman.checks.email', ) if WATCHMAN_ENABLE_PAID_CHECKS: DEFAULT_CHECKS = DEFAULT_CHECKS + PAID_CHECKS WATCHMAN_CHECKS = getattr(settings, 'WATCHMAN_CHECKS', DEFAULT_CHECKS)
bsd-3-clause
skaag/chaiscript
debian/chaiscript/usr/include/chaiscript/dispatchkit/dispatchkit.hpp
35154
// This file is distributed under the BSD License. // See "license.txt" for details. // Copyright 2009-2012, Jonathan Turner (jonathan@emptycrate.com) // and Jason Turner (jason@emptycrate.com) // http://www.chaiscript.com #ifndef CHAISCRIPT_DISPATCHKIT_HPP_ #define CHAISCRIPT_DISPATCHKIT_HPP_ #include <typeinfo> #include <string> #include <map> #include <set> #include <boost/shared_ptr.hpp> #include <stdexcept> #include <vector> #include <iostream> #include <deque> #include <list> #include "boxed_value.hpp" #include "type_info.hpp" #include "proxy_functions.hpp" #include "proxy_constructors.hpp" #include "dynamic_object.hpp" #include "../chaiscript_threading.hpp" /// \namespace chaiscript::dispatch /// \brief Classes and functions specific to the runtime dispatch side of ChaiScript. Some items may be of use to the end user. namespace chaiscript { namespace exception { /** * Exception thrown in the case that an object name is invalid because it is a reserved word */ class reserved_word_error : public std::runtime_error { public: reserved_word_error(const std::string &t_word) throw() : std::runtime_error("Reserved word not allowed in object name: " + t_word), m_word(t_word) { } virtual ~reserved_word_error() throw() {} std::string word() const { return m_word; } private: std::string m_word; }; /** * Exception thrown in the case that an object name is invalid because it already exists in current context */ class name_conflict_error : public std::runtime_error { public: name_conflict_error(const std::string &t_name) throw() : std::runtime_error("Name already exists in current context " + t_name), m_name(t_name) { } virtual ~name_conflict_error() throw() {} std::string name() const { return m_name; } private: std::string m_name; }; /** * Exception thrown in the case that a non-const object was added as a shared object */ class global_non_const : public std::runtime_error { public: global_non_const() throw() : std::runtime_error("a global object must be const") { } virtual ~global_non_const() throw() {} }; } /// \brief Holds a collection of ChaiScript settings which can be applied to the ChaiScript runtime. /// Used to implement loadable module support. class Module { public: Module &add(const Type_Info &ti, const std::string &name) { m_typeinfos.push_back(std::make_pair(ti, name)); return *this; } Module &add(const Dynamic_Cast_Conversion &d) { m_conversions.push_back(d); return *this; } Module &add(const Proxy_Function &f, const std::string &name) { m_funcs.push_back(std::make_pair(f, name)); return *this; } Module &add_global_const(const Boxed_Value &t_bv, const std::string &t_name) { if (!t_bv.is_const()) { throw exception::global_non_const(); } m_globals.push_back(std::make_pair(t_bv, t_name)); return *this; } //Add a bit of chaiscript to eval during module implementation Module &eval(const std::string &str) { m_evals.push_back(str); return *this; } Module &add(const boost::shared_ptr<Module> &m) { m->apply(*this, *this); return *m; } template<typename Eval, typename Engine> void apply(Eval &t_eval, Engine &t_engine) const { apply(m_typeinfos.begin(), m_typeinfos.end(), t_engine); apply(m_funcs.begin(), m_funcs.end(), t_engine); apply_eval(m_evals.begin(), m_evals.end(), t_eval); apply_single(m_conversions.begin(), m_conversions.end(), t_engine); apply_globals(m_globals.begin(), m_globals.end(), t_engine); } private: std::vector<std::pair<Type_Info, std::string> > m_typeinfos; std::vector<std::pair<Proxy_Function, std::string> > m_funcs; std::vector<std::pair<Boxed_Value, std::string> > m_globals; std::vector<std::string> m_evals; std::vector<Dynamic_Cast_Conversion> m_conversions; template<typename T, typename InItr> void apply(InItr begin, InItr end, T &t) const { while (begin != end) { try { t.add(begin->first, begin->second); } catch (const exception::name_conflict_error &) { /// \todo Should we throw an error if there's a name conflict /// while applying a module? } ++begin; } } template<typename T, typename InItr> void apply_globals(InItr begin, InItr end, T &t) const { while (begin != end) { t.add_global_const(begin->first, begin->second); ++begin; } } template<typename T, typename InItr> void apply_single(InItr begin, InItr end, T &t) const { while (begin != end) { t.add(*begin); ++begin; } } template<typename T, typename InItr> void apply_eval(InItr begin, InItr end, T &t) const { while (begin != end) { t.eval(*begin); ++begin; } } }; /// Convenience typedef for Module objects to be added to the ChaiScript runtime typedef boost::shared_ptr<Module> ModulePtr; namespace detail { /** * A Proxy_Function implementation that is able to take * a vector of Proxy_Functions and perform a dispatch on them. It is * used specifically in the case of dealing with Function object variables */ class Dispatch_Function : public dispatch::Proxy_Function_Base { public: Dispatch_Function(const std::vector<Proxy_Function> &t_funcs) : Proxy_Function_Base(build_type_infos(t_funcs)), m_funcs(t_funcs) { } virtual bool operator==(const dispatch::Proxy_Function_Base &rhs) const { try { const Dispatch_Function &dispatchfun = dynamic_cast<const Dispatch_Function &>(rhs); return m_funcs == dispatchfun.m_funcs; } catch (const std::bad_cast &) { return false; } } virtual ~Dispatch_Function() {} virtual std::vector<Const_Proxy_Function> get_contained_functions() const { return std::vector<Const_Proxy_Function>(m_funcs.begin(), m_funcs.end()); } virtual int get_arity() const { typedef std::vector<Proxy_Function> function_vec; function_vec::const_iterator begin = m_funcs.begin(); const function_vec::const_iterator end = m_funcs.end(); if (begin != end) { int arity = (*begin)->get_arity(); ++begin; while (begin != end) { if (arity != (*begin)->get_arity()) { // The arities in the list do not match, so it's unspecified return -1; } ++begin; } return arity; } return -1; // unknown arity } virtual bool call_match(const std::vector<Boxed_Value> &vals) const { typedef std::vector<Proxy_Function> function_vec; function_vec::const_iterator begin = m_funcs.begin(); function_vec::const_iterator end = m_funcs.end(); while (begin != end) { if ((*begin)->call_match(vals)) { return true; } else { ++begin; } } return false; } virtual std::string annotation() const { return "Multiple method dispatch function wrapper."; } protected: virtual Boxed_Value do_call(const std::vector<Boxed_Value> &params) const { return dispatch::dispatch(m_funcs.begin(), m_funcs.end(), params); } private: std::vector<Proxy_Function> m_funcs; static std::vector<Type_Info> build_type_infos(const std::vector<Proxy_Function> &t_funcs) { typedef std::vector<Proxy_Function> function_vec; function_vec::const_iterator begin = t_funcs.begin(); const function_vec::const_iterator end = t_funcs.end(); if (begin != end) { std::vector<Type_Info> type_infos = (*begin)->get_param_types(); ++begin; bool sizemismatch = false; while (begin != end) { std::vector<Type_Info> param_types = (*begin)->get_param_types(); if (param_types.size() != type_infos.size()) { sizemismatch = true; } for (size_t i = 0; i < type_infos.size() && i < param_types.size(); ++i) { if (!(type_infos[i] == param_types[i])) { type_infos[i] = detail::Get_Type_Info<Boxed_Value>::get(); } } ++begin; } assert(type_infos.size() > 0 && " type_info vector size is < 0, this is only possible if something else is broken"); if (sizemismatch) { type_infos.resize(1); } return type_infos; } return std::vector<Type_Info>(); } }; } namespace detail { /** * Main class for the dispatchkit. Handles management * of the object stack, functions and registered types. */ class Dispatch_Engine { public: typedef std::map<std::string, chaiscript::Type_Info> Type_Name_Map; typedef std::map<std::string, Boxed_Value> Scope; typedef std::deque<Scope> StackData; typedef boost::shared_ptr<StackData> Stack; struct State { std::map<std::string, std::vector<Proxy_Function> > m_functions; std::map<std::string, Proxy_Function> m_function_objects; std::map<std::string, Boxed_Value> m_global_objects; Type_Name_Map m_types; std::set<std::string> m_reserved_words; }; Dispatch_Engine() : m_place_holder(boost::shared_ptr<dispatch::Placeholder_Object>(new dispatch::Placeholder_Object())) { } ~Dispatch_Engine() { detail::Dynamic_Conversions::get().cleanup(m_conversions.begin(), m_conversions.end()); } /** * Add a new conversion for upcasting to a base class */ void add(const Dynamic_Cast_Conversion &d) { m_conversions.push_back(d); return detail::Dynamic_Conversions::get().add_conversion(d); } /** * Add a new named Proxy_Function to the system */ void add(const Proxy_Function &f, const std::string &name) { validate_object_name(name); add_function(f, name); } /** * Set the value of an object, by name. If the object * is not available in the current scope it is created */ void add(const Boxed_Value &obj, const std::string &name) { validate_object_name(name); StackData &stack = get_stack_data(); for (int i = static_cast<int>(stack.size())-1; i >= 0; --i) { std::map<std::string, Boxed_Value>::const_iterator itr = stack[i].find(name); if (itr != stack[i].end()) { stack[i][name] = obj; return; } } add_object(name, obj); } /** * Adds a named object to the current scope */ void add_object(const std::string &name, const Boxed_Value &obj) { StackData &stack = get_stack_data(); validate_object_name(name); Scope &scope = stack.back(); Scope::iterator itr = scope.find(name); if (itr != stack.back().end()) { throw exception::name_conflict_error(name); } else { stack.back().insert(std::make_pair(name, obj)); } } /** * Adds a new global shared object, between all the threads */ void add_global_const(const Boxed_Value &obj, const std::string &name) { validate_object_name(name); if (!obj.is_const()) { throw exception::global_non_const(); } chaiscript::detail::threading::unique_lock<chaiscript::detail::threading::shared_mutex> l(m_global_object_mutex); if (m_state.m_global_objects.find(name) != m_state.m_global_objects.end()) { throw exception::name_conflict_error(name); } else { m_state.m_global_objects.insert(std::make_pair(name, obj)); } } /** * Adds a new scope to the stack */ void new_scope() { StackData &stack = get_stack_data(); stack.push_back(Scope()); } /** * Pops the current scope from the stack */ void pop_scope() { StackData &stack = get_stack_data(); if (stack.size() > 1) { stack.pop_back(); } else { throw std::range_error("Unable to pop global stack"); } } /// Pushes a new stack on to the list of stacks void new_stack() { Stack s(new Stack::element_type()); s->push_back(Scope()); m_stack_holder->stacks.push_back(s); } void pop_stack() { m_stack_holder->stacks.pop_back(); } /// \returns the current stack Stack get_stack() const { return m_stack_holder->stacks.back(); } /** * Searches the current stack for an object of the given name * includes a special overload for the _ place holder object to * ensure that it is always in scope. */ Boxed_Value get_object(const std::string &name) const { // Is it a placeholder object? if (name == "_") { return m_place_holder; } StackData &stack = get_stack_data(); // Is it in the stack? for (int i = static_cast<int>(stack.size())-1; i >= 0; --i) { std::map<std::string, Boxed_Value>::const_iterator stackitr = stack[i].find(name); if (stackitr != stack[i].end()) { return stackitr->second; } } // Is the value we are looking for a global? { chaiscript::detail::threading::shared_lock<chaiscript::detail::threading::shared_mutex> l(m_global_object_mutex); std::map<std::string, Boxed_Value>::const_iterator itr = m_state.m_global_objects.find(name); if (itr != m_state.m_global_objects.end()) { return itr->second; } } // If all that failed, then check to see if it's a function return get_function_object(name); } /** * Registers a new named type */ void add(const Type_Info &ti, const std::string &name) { add_global_const(const_var(ti), name + "_type"); chaiscript::detail::threading::unique_lock<chaiscript::detail::threading::shared_mutex> l(m_mutex); m_state.m_types.insert(std::make_pair(name, ti)); } /** * Returns the type info for a named type */ Type_Info get_type(const std::string &name) const { chaiscript::detail::threading::shared_lock<chaiscript::detail::threading::shared_mutex> l(m_mutex); Type_Name_Map::const_iterator itr = m_state.m_types.find(name); if (itr != m_state.m_types.end()) { return itr->second; } throw std::range_error("Type Not Known"); } /** * Returns the registered name of a known type_info object * compares the "bare_type_info" for the broadest possible * match */ std::string get_type_name(const Type_Info &ti) const { chaiscript::detail::threading::shared_lock<chaiscript::detail::threading::shared_mutex> l(m_mutex); for (Type_Name_Map::const_iterator itr = m_state.m_types.begin(); itr != m_state.m_types.end(); ++itr) { if (itr->second.bare_equal(ti)) { return itr->first; } } return ti.bare_name(); } /** * Return all registered types */ std::vector<std::pair<std::string, Type_Info> > get_types() const { chaiscript::detail::threading::shared_lock<chaiscript::detail::threading::shared_mutex> l(m_mutex); return std::vector<std::pair<std::string, Type_Info> >(m_state.m_types.begin(), m_state.m_types.end()); } /** * Return a function by name */ std::vector< Proxy_Function > get_function(const std::string &t_name) const { chaiscript::detail::threading::shared_lock<chaiscript::detail::threading::shared_mutex> l(m_mutex); const std::map<std::string, std::vector<Proxy_Function> > &funs = get_functions_int(); std::map<std::string, std::vector<Proxy_Function> >::const_iterator itr = funs.find(t_name); if (itr != funs.end()) { return itr->second; } else { return std::vector<Proxy_Function>(); } } /// \returns a function object (Boxed_Value wrapper) if it exists /// \throws std::range_error if it does not Boxed_Value get_function_object(const std::string &t_name) const { chaiscript::detail::threading::shared_lock<chaiscript::detail::threading::shared_mutex> l(m_mutex); const std::map<std::string, Proxy_Function> &funs = get_function_objects_int(); std::map<std::string, Proxy_Function>::const_iterator itr = funs.find(t_name); if (itr != funs.end()) { return const_var(itr->second); } else { throw std::range_error("Object not found: " + t_name); } } /** * Return true if a function exists */ bool function_exists(const std::string &name) const { chaiscript::detail::threading::shared_lock<chaiscript::detail::threading::shared_mutex> l(m_mutex); const std::map<std::string, std::vector<Proxy_Function> > &functions = get_functions_int(); return functions.find(name) != functions.end(); } /// \returns All values in the local thread state, added through the add() function std::map<std::string, Boxed_Value> get_locals() const { StackData &stack = get_stack_data(); Scope &scope = stack.front(); return scope; } /// \brief Sets all of the locals for the current thread state. /// /// \param[in] t_locals The map<name, value> set of variables to replace the current state with /// /// Any existing locals are removed and the given set of variables is added void set_locals(const std::map<std::string, Boxed_Value> &t_locals) { StackData &stack = get_stack_data(); Scope &scope = stack.front(); scope = t_locals; } /// /// Get a map of all objects that can be seen from the current scope in a scripting context /// std::map<std::string, Boxed_Value> get_scripting_objects() const { // We don't want the current context, but one up if it exists StackData &stack = (m_stack_holder->stacks.size()==1)?(*(m_stack_holder->stacks.back())):(*m_stack_holder->stacks[m_stack_holder->stacks.size()-2]); std::map<std::string, Boxed_Value> retval; // note: map insert doesn't overwrite existing values, which is why this works for (StackData::reverse_iterator itr = stack.rbegin(); itr != stack.rend(); ++itr) { retval.insert(itr->begin(), itr->end()); } // add the global values { chaiscript::detail::threading::shared_lock<chaiscript::detail::threading::shared_mutex> l(m_global_object_mutex); retval.insert(m_state.m_global_objects.begin(), m_state.m_global_objects.end()); } return retval; } /// /// Get a map of all functions that can be seen from a scripting context /// std::map<std::string, Boxed_Value> get_function_objects() const { chaiscript::detail::threading::shared_lock<chaiscript::detail::threading::shared_mutex> l(m_mutex); const std::map<std::string, Proxy_Function> &funs = get_function_objects_int(); std::map<std::string, Boxed_Value> objs; for (std::map<std::string, Proxy_Function>::const_iterator itr = funs.begin(); itr != funs.end(); ++itr) { objs.insert(std::make_pair(itr->first, const_var(itr->second))); } return objs; } /** * Get a vector of all registered functions */ std::vector<std::pair<std::string, Proxy_Function > > get_functions() const { chaiscript::detail::threading::shared_lock<chaiscript::detail::threading::shared_mutex> l(m_mutex); std::vector<std::pair<std::string, Proxy_Function> > rets; const std::map<std::string, std::vector<Proxy_Function> > &functions = get_functions_int(); for (std::map<std::string, std::vector<Proxy_Function> >::const_iterator itr = functions.begin(); itr != functions.end(); ++itr) { for (std::vector<Proxy_Function>::const_iterator itr2 = itr->second.begin(); itr2 != itr->second.end(); ++itr2) { rets.push_back(std::make_pair(itr->first, *itr2)); } } return rets; } void add_reserved_word(const std::string &name) { chaiscript::detail::threading::unique_lock<chaiscript::detail::threading::shared_mutex> l(m_mutex); m_state.m_reserved_words.insert(name); } Boxed_Value call_function(const std::string &t_name, const std::vector<Boxed_Value> &params) const { std::vector<Proxy_Function> functions = get_function(t_name); return dispatch::dispatch(functions.begin(), functions.end(), params); } Boxed_Value call_function(const std::string &t_name) const { return call_function(t_name, std::vector<Boxed_Value>()); } Boxed_Value call_function(const std::string &t_name, const Boxed_Value &p1) const { std::vector<Boxed_Value> params; params.push_back(p1); return call_function(t_name, params); } Boxed_Value call_function(const std::string &t_name, const Boxed_Value &p1, const Boxed_Value &p2) const { std::vector<Boxed_Value> params; params.push_back(p1); params.push_back(p2); return call_function(t_name, params); } /** * Dump object info to stdout */ void dump_object(const Boxed_Value &o) const { std::cout << (o.is_const()?"const ":"") << type_name(o) << std::endl; } /** * Dump type info to stdout */ void dump_type(const Type_Info &type) const { std::cout << (type.is_const()?"const ":"") << get_type_name(type); } /** * Dump function to stdout */ void dump_function(const std::pair<const std::string, Proxy_Function > &f) const { std::vector<Type_Info> params = f.second->get_param_types(); std::string annotation = f.second->annotation(); if (annotation.size() > 0) { std::cout << annotation; } dump_type(params.front()); std::cout << " " << f.first << "("; for (std::vector<Type_Info>::const_iterator itr = params.begin() + 1; itr != params.end(); ) { dump_type(*itr); ++itr; if (itr != params.end()) { std::cout << ", "; } } std::cout << ") " << std::endl; } /** * Dump all system info to stdout */ void dump_system() const { std::cout << "Registered Types: " << std::endl; std::vector<std::pair<std::string, Type_Info> > types = get_types(); for (std::vector<std::pair<std::string, Type_Info> >::const_iterator itr = types.begin(); itr != types.end(); ++itr) { std::cout << itr->first << ": "; std::cout << itr->second.bare_name(); std::cout << std::endl; } std::cout << std::endl; std::vector<std::pair<std::string, Proxy_Function > > funcs = get_functions(); std::cout << "Functions: " << std::endl; for (std::vector<std::pair<std::string, Proxy_Function > >::const_iterator itr = funcs.begin(); itr != funcs.end(); ++itr) { dump_function(*itr); } std::cout << std::endl; } /** * return true if the Boxed_Value matches the registered type by name */ bool is_type(const Boxed_Value &r, const std::string &user_typename) const { try { if (get_type(user_typename).bare_equal(r.get_type_info())) { return true; } } catch (const std::range_error &) { } try { const dispatch::Dynamic_Object &d = boxed_cast<const dispatch::Dynamic_Object &>(r); return d.get_type_name() == user_typename; } catch (const std::bad_cast &) { } return false; } std::string type_name(const Boxed_Value &obj) const { return get_type_name(obj.get_type_info()); } State get_state() { chaiscript::detail::threading::shared_lock<chaiscript::detail::threading::shared_mutex> l(m_mutex); chaiscript::detail::threading::shared_lock<chaiscript::detail::threading::shared_mutex> l2(m_global_object_mutex); return m_state; } void set_state(const State &t_state) { chaiscript::detail::threading::unique_lock<chaiscript::detail::threading::shared_mutex> l(m_mutex); chaiscript::detail::threading::unique_lock<chaiscript::detail::threading::shared_mutex> l2(m_global_object_mutex); m_state = t_state; } void save_function_params(const std::vector<Boxed_Value> &t_params) { m_stack_holder->call_params.insert(m_stack_holder->call_params.begin(), t_params.begin(), t_params.end()); } void new_function_call() { ++m_stack_holder->call_depth; } void pop_function_call() { --m_stack_holder->call_depth; assert(m_stack_holder->call_depth >= 0); if (m_stack_holder->call_depth == 0) { /// \todo Critical: this needs to be smarter, memory can expand quickly /// in tight loops involving function calls m_stack_holder->call_params.clear(); } } private: /** * Returns the current stack * make const/non const versions */ StackData &get_stack_data() const { return *(m_stack_holder->stacks.back()); } const std::map<std::string, Proxy_Function> &get_function_objects_int() const { return m_state.m_function_objects; } std::map<std::string, Proxy_Function> &get_function_objects_int() { return m_state.m_function_objects; } const std::map<std::string, std::vector<Proxy_Function> > &get_functions_int() const { return m_state.m_functions; } std::map<std::string, std::vector<Proxy_Function> > &get_functions_int() { return m_state.m_functions; } static bool function_less_than(const Proxy_Function &lhs, const Proxy_Function &rhs) { const std::vector<Type_Info> lhsparamtypes = lhs->get_param_types(); const std::vector<Type_Info> rhsparamtypes = rhs->get_param_types(); const size_t lhssize = lhsparamtypes.size(); const size_t rhssize = rhsparamtypes.size(); const Type_Info boxed_type = user_type<Boxed_Value>(); const Type_Info boxed_pod_type = user_type<Boxed_Number>(); boost::shared_ptr<const dispatch::Dynamic_Proxy_Function> dynamic_lhs(boost::dynamic_pointer_cast<const dispatch::Dynamic_Proxy_Function>(lhs)); boost::shared_ptr<const dispatch::Dynamic_Proxy_Function> dynamic_rhs(boost::dynamic_pointer_cast<const dispatch::Dynamic_Proxy_Function>(rhs)); if (dynamic_lhs && dynamic_rhs) { if (dynamic_lhs->get_guard()) { if (dynamic_rhs->get_guard()) { return false; } else { return true; } } else { return false; } } if (dynamic_lhs && !dynamic_rhs) { return false; } if (!dynamic_lhs && dynamic_rhs) { return true; } for (size_t i = 1; i < lhssize && i < rhssize; ++i) { const Type_Info lt = lhsparamtypes[i]; const Type_Info rt = rhsparamtypes[i]; if (lt.bare_equal(rt) && lt.is_const() == rt.is_const()) { continue; // The first two types are essentially the same, next iteration } // const is after non-const for the same type if (lt.bare_equal(rt) && lt.is_const() && !rt.is_const()) { return false; } if (lt.bare_equal(rt) && !lt.is_const()) { return true; } // boxed_values are sorted last if (lt.bare_equal(boxed_type)) { return false; } if (rt.bare_equal(boxed_type)) { if (lt.bare_equal(boxed_pod_type)) { return true; } return true; } if (lt.bare_equal(boxed_pod_type)) { return false; } if (rt.bare_equal(boxed_pod_type)) { return true; } // otherwise, we want to sort by typeid return lt < rt; } return false; } /** * Throw a reserved_word exception if the name is not allowed */ void validate_object_name(const std::string &name) const { chaiscript::detail::threading::shared_lock<chaiscript::detail::threading::shared_mutex> l(m_mutex); if (m_state.m_reserved_words.find(name) != m_state.m_reserved_words.end()) { throw exception::reserved_word_error(name); } } /** * Implementation detail for adding a function. * \throws exception::name_conflict_error if there's a function matching the given one being added */ void add_function(const Proxy_Function &t_f, const std::string &t_name) { chaiscript::detail::threading::unique_lock<chaiscript::detail::threading::shared_mutex> l(m_mutex); std::map<std::string, std::vector<Proxy_Function> > &funcs = get_functions_int(); std::map<std::string, std::vector<Proxy_Function> >::iterator itr = funcs.find(t_name); std::map<std::string, Proxy_Function> &func_objs = get_function_objects_int(); if (itr != funcs.end()) { std::vector<Proxy_Function> &vec = itr->second; for (std::vector<Proxy_Function>::const_iterator itr2 = vec.begin(); itr2 != vec.end(); ++itr2) { if ((*t_f) == *(*itr2)) { throw exception::name_conflict_error(t_name); } } vec.push_back(t_f); std::stable_sort(vec.begin(), vec.end(), &function_less_than); func_objs[t_name] = Proxy_Function(new Dispatch_Function(vec)); } else if (t_f->has_arithmetic_param()) { // if the function is the only function but it also contains // arithmetic operators, we must wrap it in a dispatch function // to allow for automatic arithmetic type conversions std::vector<Proxy_Function> vec; vec.push_back(t_f); funcs.insert(std::make_pair(t_name, vec)); func_objs[t_name] = Proxy_Function(new Dispatch_Function(vec)); } else { std::vector<Proxy_Function> vec; vec.push_back(t_f); funcs.insert(std::make_pair(t_name, vec)); func_objs[t_name] = t_f; } } mutable chaiscript::detail::threading::shared_mutex m_mutex; mutable chaiscript::detail::threading::shared_mutex m_global_object_mutex; struct Stack_Holder { Stack_Holder() : call_depth(0) { Stack s(new StackData()); s->push_back(Scope()); stacks.push_back(s); } std::deque<Stack> stacks; std::list<Boxed_Value> call_params; int call_depth; }; std::vector<Dynamic_Cast_Conversion> m_conversions; chaiscript::detail::threading::Thread_Storage<Stack_Holder> m_stack_holder; State m_state; Boxed_Value m_place_holder; }; } } #endif
bsd-3-clause
mylifeafterthat/sgf-project
backend/modules/ecommerce/models/ProductSearch.php
2156
<?php namespace backend\modules\ecommerce\models; use Yii; use yii\base\Model; use yii\data\ActiveDataProvider; use backend\modules\ecommerce\models\Product; /** * ProductSearch represents the model behind the search form about `backend\modules\ecommerce\models\Product`. */ class ProductSearch extends Product { /** * @inheritdoc */ public function rules() { return [ [['id', 'category_id', 'price', 'qty', 'product_type', 'status', 'created_at', 'created_by', 'updated_at', 'updated_by'], 'integer'], [['name', 'description'], 'safe'], ]; } /** * @inheritdoc */ public function scenarios() { // bypass scenarios() implementation in the parent class return Model::scenarios(); } /** * Creates data provider instance with search query applied * * @param array $params * * @return ActiveDataProvider */ public function search($params) { $query = Product::find(); $dataProvider = new ActiveDataProvider([ 'query' => $query, 'sort'=>['defaultOrder'=>['id'=>SORT_DESC]], 'pagination'=>[ 'pageSize'=>5, ], ]); $this->load($params); if (!$this->validate()) { // uncomment the following line if you do not want to return any records when validation fails // $query->where('0=1'); return $dataProvider; } $query->andFilterWhere([ 'id' => $this->id, 'category_id' => $this->category_id, 'price' => $this->price, 'qty' => $this->qty, 'product_type' => $this->product_type, 'status' => $this->status, 'created_at' => $this->created_at, 'created_by' => $this->created_by, 'updated_at' => $this->updated_at, 'updated_by' => $this->updated_by, ]); $query->andFilterWhere(['like', 'name', $this->name]) ->andFilterWhere(['like', 'description', $this->description]); return $dataProvider; } }
bsd-3-clause
bejayoharen/java-bells
lib-src/libjitsi/src/org/jitsi/impl/neomedia/codec/audio/alaw/JavaEncoder.java
9868
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package org.jitsi.impl.neomedia.codec.audio.alaw; import javax.media.*; import javax.media.format.*; /** * The ALAW Encoder. Used the FMJ ALawEncoderUtil. * * @author Damian Minkov */ public class JavaEncoder extends com.ibm.media.codec.audio.AudioCodec { /** * The last used format. */ private Format lastFormat = null; /** * The input sample size in bits. */ private int inputSampleSize; /** * The byte order. */ private boolean bigEndian = false; /** * Constructs the encoder and init the supported formats. */ public JavaEncoder() { supportedInputFormats = new AudioFormat[] { new AudioFormat( AudioFormat.LINEAR, Format.NOT_SPECIFIED, 16, 1, Format.NOT_SPECIFIED, Format.NOT_SPECIFIED ), new AudioFormat( AudioFormat.LINEAR, Format.NOT_SPECIFIED, 8, 1, Format.NOT_SPECIFIED, Format.NOT_SPECIFIED )}; // support 1 channel and 8/16 bit samples defaultOutputFormats = new AudioFormat[] { new AudioFormat( AudioFormat.ALAW, 8000, 8, 1, Format.NOT_SPECIFIED, Format.NOT_SPECIFIED )}; PLUGIN_NAME = "pcm to alaw converter"; } /** * Returns the output formats according to the input. * @param in the input format. * @return the possible output formats. */ protected Format[] getMatchingOutputFormats(Format in) { AudioFormat inFormat = (AudioFormat) in; int sampleRate = (int) (inFormat.getSampleRate()); supportedOutputFormats = new AudioFormat[] { new AudioFormat( AudioFormat.ALAW, sampleRate, 8, 1, Format.NOT_SPECIFIED, Format.NOT_SPECIFIED )}; return supportedOutputFormats; } /** * No resources to be opened. * @throws ResourceUnavailableException if open failed (which cannot * happend for this codec since no resources are to be opened) */ public void open() throws ResourceUnavailableException {} /** * No resources used to be cleared. */ public void close() {} /** * Calculate the output data size. * @param inputLength input length. * @return the output data size. */ private int calculateOutputSize(int inputLength) { if (inputSampleSize == 16) { inputLength /= 2; } return inputLength; } /** * Init the converter to the new format * @param inFormat AudioFormat */ private void initConverter(AudioFormat inFormat) { lastFormat = inFormat; inputSampleSize = inFormat.getSampleSizeInBits(); bigEndian = inFormat.getEndian()==AudioFormat.BIG_ENDIAN; } /** * Encodes the input buffer passing it to the output one * @param inputBuffer Buffer * @param outputBuffer Buffer * @return int */ public int process(Buffer inputBuffer, Buffer outputBuffer) { if (!checkInputBuffer(inputBuffer)) { return BUFFER_PROCESSED_FAILED; } if (isEOM(inputBuffer)) { propagateEOM(outputBuffer); return BUFFER_PROCESSED_OK; } Format newFormat = inputBuffer.getFormat(); if (lastFormat != newFormat) { initConverter( (AudioFormat) newFormat); } if (inputBuffer.getLength() == 0) { return OUTPUT_BUFFER_NOT_FILLED; } int outLength = calculateOutputSize(inputBuffer.getLength()); byte[] inpData = (byte[]) inputBuffer.getData(); byte[] outData = validateByteArraySize(outputBuffer, outLength); aLawEncode(bigEndian, inpData, inputBuffer.getOffset(), inputBuffer.getLength(), outData); updateOutput(outputBuffer, outputFormat, outLength, 0); return BUFFER_PROCESSED_OK; } /** * maximum that can be held in 15 bits */ public static final int MAX = 0x7fff; /** * An array where the index is the 16-bit PCM input, and the value is * the a-law result. */ private static byte[] pcmToALawMap; static { pcmToALawMap = new byte[65536]; for (int i = Short.MIN_VALUE; i <= Short.MAX_VALUE; i++) pcmToALawMap[uShortToInt((short) i)] = encode(i); } /** * 65535 */ public static final int MAX_USHORT = (Short.MAX_VALUE) * 2 + 1; /** * Unsigned short to integer. * @param value unsigned short. * @return integer. */ public static int uShortToInt(short value) { if (value >= 0) return value; else return MAX_USHORT + 1 + value; } /** * Encode an array of pcm values into a pre-allocated target array * * @param bigEndian the data byte order. * @param data An array of bytes in Little-Endian format * @param target A pre-allocated array to receive the A-law bytes. * This array must be at least half the size of the source. * @param offset of the input. * @param length of the input. */ public static void aLawEncode(boolean bigEndian, byte[] data, int offset, int length, byte[] target) { if (bigEndian) aLawEncodeBigEndian(data, offset, length, target); else aLawEncodeLittleEndian(data, offset, length, target); } /** * Encode little endian data. * @param data the input data. * @param offset the input offset. * @param length the input length. * @param target the target array to fill. */ public static void aLawEncodeLittleEndian(byte[] data, int offset, int length, byte[] target) { int size = length / 2; for (int i = 0; i < size; i++) target[i] = aLawEncode( ((data[offset + 2 * i + 1] & 0xff) << 8) | (data[offset + 2 * i]) & 0xff); } /** * Encode big endian data. * @param data the input data. * @param offset the input offset. * @param length the input length. * @param target the target array to fill. */ public static void aLawEncodeBigEndian(byte[] data, int offset, int length, byte[] target) { int size = length / 2; for (int i = 0; i < size; i++) target[i] = aLawEncode(((data[offset + 2 * i + 1]) & 0xff) | ((data[offset + 2 * i] & 0xff) << 8)); } /** * Encode a pcm value into a a-law byte * * @param pcm A 16-bit pcm value * @return A a-law encoded byte */ public static byte aLawEncode(int pcm) { return pcmToALawMap[uShortToInt((short) (pcm & 0xffff))]; } /** * Encode one a-law byte from a 16-bit signed integer. Internal use only. * * @param pcm A 16-bit signed pcm value * @return A a-law encoded byte */ private static byte encode(int pcm) { //Get the sign bit. Shift it for later use without further modification int sign = (pcm & 0x8000) >> 8; //If the number is negative, make it positive (now it's a magnitude) if (sign != 0) pcm = -pcm; //The magnitude must fit in 15 bits to avoid overflow if (pcm > MAX) pcm = MAX; /* Finding the "exponent" * Bits: * 1 2 3 4 5 6 7 8 9 A B C D E F G * S 7 6 5 4 3 2 1 0 0 0 0 0 0 0 0 * We want to find where the first 1 after the sign bit is. * We take the corresponding value from * the second row as the exponent value. * (i.e. if first 1 at position 7 -> exponent = 2) * The exponent is 0 if the 1 is not found in bits 2 through 8. * This means the exponent is 0 even if the "first 1" doesn't exist. */ int exponent = 7; //Move to the right and decrement exponent until //we hit the 1 or the exponent hits 0 for (int expMask = 0x4000; (pcm & expMask) == 0 && exponent>0; exponent--, expMask >>= 1) { } /* The last part - the "mantissa" * We need to take the four bits after the 1 we just found. * To get it, we shift 0x0f : * 1 2 3 4 5 6 7 8 9 A B C D E F G * S 0 0 0 0 0 1 . . . . . . . . . (say that exponent is 2) * . . . . . . . . . . . . 1 1 1 1 * We shift it 5 times for an exponent of two, meaning * we will shift our four bits (exponent + 3) bits. * For convenience, we will actually just shift the number, * then AND with 0x0f. * * NOTE: If the exponent is 0: * 1 2 3 4 5 6 7 8 9 A B C D E F G * S 0 0 0 0 0 0 0 Z Y X W V U T S (we know nothing about bit 9) * . . . . . . . . . . . . 1 1 1 1 * We want to get ZYXW, which means a shift of 4 instead of 3 */ int mantissa = (pcm >> ((exponent == 0) ? 4 : (exponent + 3))) & 0x0f; //The a-law byte bit arrangement is SEEEMMMM //(Sign, Exponent, and Mantissa.) byte alaw = (byte)(sign | exponent << 4 | mantissa); //Last is to flip every other bit, and the sign bit (0xD5 = 1101 0101) return (byte)(alaw^0xD5); } }
bsd-3-clause
Zaszczyk/cphalcon
tests/_data/events/ComponentX.php
1128
<?php use Phalcon\Events\Manager; /** * ComponentX * * @copyright (c) 2011-2017 Phalcon Team * @link https://www.phalconphp.com * @author Andres Gutierrez <andres@phalconphp.com> * @author Serghei Iakovlev <serghei@phalconphp.com> * * The contents of this file are subject to the New BSD License that is * bundled with this package in the file LICENSE.txt * * 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@phalconphp.com * so that we can send you a copy immediately. */ class ComponentX { /** * @var Manager */ protected $eventsManager; public function setEventsManager(Manager $eventsManager) { $this->eventsManager = $eventsManager; } /** * @return Manager */ public function getEventsManager() { return $this->eventsManager; } public function leAction() { $this->eventsManager->fire('dummy:beforeAction', $this, 'extra data'); $this->eventsManager->fire('dummy:afterAction', $this, ['extra', 'data']); } }
bsd-3-clause
adem-team/advanced
lukisongroup/efenbi/rasasayang/views/item/_form.php
2796
<?php use yii\helpers\Html; use yii\widgets\ActiveForm; use kartik\widgets\FileInput; use kartik\label\LabelInPlace; use kartik\widgets\Select2; use yii\helpers\Url; use kartik\widgets\DepDrop; use yii\helpers\ArrayHelper; use yii\web\Response; use kartik\widgets\DatePicker; use kartik\widgets\TouchSpin; $aryStt= [ ['STATUS' => 0, 'STT_NM' => 'Disable'], ['STATUS' => 1, 'STT_NM' => 'Enable'], ]; $valStt = ArrayHelper::map($aryStt, 'STATUS', 'STT_NM'); ?> <?php $form = ActiveForm::begin([ 'id'=>$model->formName(), 'options'=>['enctype'=>'multipart/form-data'], //'enableClientValidation'=> true, 'enableAjaxValidation'=>true, //true = harus beda url action controller dengan post saved url controller. 'validationUrl'=>Url::toRoute('/efenbi-rasasayang/item/valid-item'), ]); ?> <div style="height:100%;font-family: verdana, arial, sans-serif ;font-size: 8pt"> <div class="row" > <div class="col-xs-7 col-sm-7 col-md-7 col-lg-7"> <?= $form->field($model, 'ITEM_NM')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'STATUS')->widget(Select2::classname(), [ 'data' =>$valStt,//Yii::$app->gv->gvStatusArray(), 'options' => ['placeholder' => 'Pilih Status...'], ]); ?> </div> <div class="col-xs-5 col-sm-5 col-md-5 col-lg-5"> <?=$form->field($model, 'image')->widget(FileInput::classname(), [ 'name'=>'item-input-file', 'options'=>[ 'width'=>'100px', 'accept'=>'image/*', 'multiple'=>false ], 'pluginOptions'=>[ 'allowedFileExtensions'=>['jpg','gif','png'], 'showCaption' => false, 'showRemove' => true, 'showUpload' => false, 'showClose' =>false, 'showDrag' =>false, 'browseLabel' => 'Select Photo', 'removeLabel' => '', 'removeIcon'=> '<i class="glyphicon glyphicon-remove"></i>', 'removeTitle'=> 'Clear Selected File', 'defaultPreviewContent' => '<img src="https://www.mautic.org/media/images/default_avatar.png" alt="Your Avatar" style="width:160px">', 'maxFileSize'=>10 //10KB ], 'pluginEvents' => [ 'fileclear' => 'function() { log("fileclear"); }', 'filereset' => 'function() { log("filereset"); }', ] ]); ?> </div> <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12"> <?= Html::submitButton($model->isNewRecord ? 'Save' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> </div> </div> </div> <?php ActiveForm::end(); ?> <?php $this->registerJs(" $('#file-input').fileinput({ // resizeImage: true, // maxImageWidth: 160, // maxImageHeight: 160, // resizePreference: 'width' // 'previewSettings':{ // image: {width: '160px', 'height':'160px'} // }, }); ",$this::POS_READY); ?>
bsd-3-clause
dushmis/Oracle-Cloud
PaaS-SaaS_HealthCareApp/DoctorPatientCRMExtension/HealthCare/HealthCareWSProxyClient/src/com/oracle/ptsdemo/healthcare/wsclient/osc/salesparty/generated/XSDType.java
1932
package com.oracle.ptsdemo.healthcare.wsclient.osc.salesparty.generated; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAnyElement; import javax.xml.bind.annotation.XmlType; import org.w3c.dom.Element; /** * Expected type is xsd:schema. * * <p>Java class for XSDType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="XSDType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;any processContents='lax' namespace='http://www.w3.org/2001/XMLSchema' maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "XSDType", namespace = "commonj.sdo", propOrder = { "any" }) public class XSDType { @XmlAnyElement(lax = true) protected List<Object> any; /** * Gets the value of the any property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the any property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAny().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Object } * {@link Element } * * */ public List<Object> getAny() { if (any == null) { any = new ArrayList<Object>(); } return this.any; } }
bsd-3-clause
carthagecollege/django-djsani
djsani/bin/sports.py
2569
# -*- coding: utf-8 -*- import csv import os import sys # env os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djsani.settings.shell') # required if using django models import django django.setup() from django.conf import settings from djimix.core.utils import get_connection from djimix.core.utils import xsql from djsani.core.models import SPORTS import argparse import logging logger = logging.getLogger('debug_logfile') # set up command-line options desc = """ Accepts as input a college ID """ # RawTextHelpFormatter method allows for new lines in help text parser = argparse.ArgumentParser( description=desc, formatter_class=argparse.RawTextHelpFormatter ) parser.add_argument( '-i', '--cid', help="College ID", dest='cid', required=False, ) parser.add_argument( '-f', '--file', help="File name", dest='phile', required=False, ) parser.add_argument( '--test', action='store_true', help="Dry run?", dest='test' ) PHILE = os.path.join(settings.BASE_DIR, 'sql/sports_student.sql') def _xsql(cid): """Private function for executing the SQL incantation.""" with open(PHILE) as incantation: sql = '{0}{1}'.format(incantation.read(), cid) if test: print('sql incantation:') print(sql) else: logger.debug("sql = {}".format(sql)) with get_connection() as connection: row = xsql(sql, connection, key=settings.INFORMIX_DEBUG).fetchall() return row def main(): """Obtain the sports in which a student participates.""" if cid: print(_xsql(cid)) else: sendero = os.path.join(settings.BASE_DIR, 'sql', phile) if os.path.isfile(sendero): with open(sendero, 'r') as csv_file: reader = csv.DictReader(csv_file, delimiter='|') for row in reader: sports = [] clubsorgs = _xsql(row['ID']) for sport in row['Sports'].split(','): for s in SPORTS: if s[0] == sport: sports.append(s[1]) print(row['ID'], row['Athlete Status'], clubsorgs, sports) else: print("{0} is not a valid file".format(phile)) if __name__ == '__main__': args = parser.parse_args() cid = args.cid phile = args.phile test = args.test if not cid and not phile: print("You must provide a college ID or a file name") sys.exit() if test: print(args) sys.exit(main())
bsd-3-clause
ros-gbp/pcl-fuerte-release_defunct
sample_consensus/include/pcl/sample_consensus/impl/sac_model_registration.hpp
11674
/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2011, Willow Garage, 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 Willow Garage, 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. * * $Id: sac_model_registration.hpp 3503 2011-12-12 06:07:28Z rusu $ * */ #ifndef PCL_SAMPLE_CONSENSUS_IMPL_SAC_MODEL_REGISTRATION_H_ #define PCL_SAMPLE_CONSENSUS_IMPL_SAC_MODEL_REGISTRATION_H_ #include "pcl/sample_consensus/sac_model_registration.h" ////////////////////////////////////////////////////////////////////////// template <typename PointT> bool pcl::SampleConsensusModelRegistration<PointT>::isSampleGood (const std::vector<int> &samples) const { return ((input_->points[samples[1]].getArray4fMap () - input_->points[samples[0]].getArray4fMap ()).matrix ().squaredNorm () > sample_dist_thresh_ && (input_->points[samples[2]].getArray4fMap () - input_->points[samples[0]].getArray4fMap ()).matrix ().squaredNorm () > sample_dist_thresh_ && (input_->points[samples[2]].getArray4fMap () - input_->points[samples[1]].getArray4fMap ()).matrix ().squaredNorm () > sample_dist_thresh_); } ////////////////////////////////////////////////////////////////////////// template <typename PointT> bool pcl::SampleConsensusModelRegistration<PointT>::computeModelCoefficients (const std::vector<int> &samples, Eigen::VectorXf &model_coefficients) { if (!target_) { PCL_ERROR ("[pcl::SampleConsensusModelRegistration::computeModelCoefficients] No target dataset given!\n"); return (false); } // Need 3 samples if (samples.size () != 3) return (false); std::vector<int> indices_tgt (3); for (int i = 0; i < 3; ++i) indices_tgt[i] = correspondences_[samples[i]]; estimateRigidTransformationSVD (*input_, samples, *target_, indices_tgt, model_coefficients); return (true); } ////////////////////////////////////////////////////////////////////////// template <typename PointT> void pcl::SampleConsensusModelRegistration<PointT>::getDistancesToModel (const Eigen::VectorXf &model_coefficients, std::vector<double> &distances) { if (indices_->size () != indices_tgt_->size ()) { PCL_ERROR ("[pcl::SampleConsensusModelRegistration::getDistancesToModel] Number of source indices (%lu) differs than number of target indices (%lu)!\n", (unsigned long)indices_->size (), (unsigned long)indices_tgt_->size ()); distances.clear (); return; } if (!target_) { PCL_ERROR ("[pcl::SampleConsensusModelRegistration::getDistanceToModel] No target dataset given!\n"); return; } // Check if the model is valid given the user constraints if (!isModelValid (model_coefficients)) { distances.clear (); return; } distances.resize (indices_->size ()); // Get the 4x4 transformation Eigen::Matrix4f transform; transform.row (0) = model_coefficients.segment<4>(0); transform.row (1) = model_coefficients.segment<4>(4); transform.row (2) = model_coefficients.segment<4>(8); transform.row (3) = model_coefficients.segment<4>(12); for (size_t i = 0; i < indices_->size (); ++i) { Eigen::Vector4f pt_src = input_->points[(*indices_)[i]].getVector4fMap (); pt_src[3] = 1; Eigen::Vector4f pt_tgt = target_->points[(*indices_tgt_)[i]].getVector4fMap (); pt_tgt[3] = 1; Eigen::Vector4f p_tr = transform * pt_src; // Calculate the distance from the transformed point to its correspondence // need to compute the real norm here to keep MSAC and friends general distances[i] = (p_tr - pt_tgt).norm (); } } ////////////////////////////////////////////////////////////////////////// template <typename PointT> void pcl::SampleConsensusModelRegistration<PointT>::selectWithinDistance (const Eigen::VectorXf &model_coefficients, const double threshold, std::vector<int> &inliers) { if (indices_->size () != indices_tgt_->size ()) { PCL_ERROR ("[pcl::SampleConsensusModelRegistration::selectWithinDistance] Number of source indices (%lu) differs than number of target indices (%lu)!\n", (unsigned long)indices_->size (), (unsigned long)indices_tgt_->size ()); inliers.clear (); return; } if (!target_) { PCL_ERROR ("[pcl::SampleConsensusModelRegistration::selectWithinDistance] No target dataset given!\n"); return; } double thresh = threshold * threshold; // Check if the model is valid given the user constraints if (!isModelValid (model_coefficients)) { inliers.clear (); return; } inliers.resize (indices_->size ()); Eigen::Matrix4f transform; transform.row (0) = model_coefficients.segment<4>(0); transform.row (1) = model_coefficients.segment<4>(4); transform.row (2) = model_coefficients.segment<4>(8); transform.row (3) = model_coefficients.segment<4>(12); int nr_p = 0; for (size_t i = 0; i < indices_->size (); ++i) { Eigen::Vector4f pt_src = input_->points[(*indices_)[i]].getVector4fMap (); pt_src[3] = 1; Eigen::Vector4f pt_tgt = target_->points[(*indices_tgt_)[i]].getVector4fMap (); pt_tgt[3] = 1; Eigen::Vector4f p_tr = transform * pt_src; // Calculate the distance from the transformed point to its correspondence if ((p_tr - pt_tgt).squaredNorm () < thresh) inliers[nr_p++] = (*indices_)[i]; } inliers.resize (nr_p); } ////////////////////////////////////////////////////////////////////////// template <typename PointT> int pcl::SampleConsensusModelRegistration<PointT>::countWithinDistance ( const Eigen::VectorXf &model_coefficients, const double threshold) { if (indices_->size () != indices_tgt_->size ()) { PCL_ERROR ("[pcl::SampleConsensusModelRegistration::countWithinDistance] Number of source indices (%lu) differs than number of target indices (%lu)!\n", (unsigned long)indices_->size (), (unsigned long)indices_tgt_->size ()); return (0); } if (!target_) { PCL_ERROR ("[pcl::SampleConsensusModelRegistration::countWithinDistance] No target dataset given!\n"); return (0); } double thresh = threshold * threshold; // Check if the model is valid given the user constraints if (!isModelValid (model_coefficients)) return (0); Eigen::Matrix4f transform; transform.row (0) = model_coefficients.segment<4>(0); transform.row (1) = model_coefficients.segment<4>(4); transform.row (2) = model_coefficients.segment<4>(8); transform.row (3) = model_coefficients.segment<4>(12); int nr_p = 0; for (size_t i = 0; i < indices_->size (); ++i) { Eigen::Vector4f pt_src = input_->points[(*indices_)[i]].getVector4fMap (); pt_src[3] = 1; Eigen::Vector4f pt_tgt = target_->points[(*indices_tgt_)[i]].getVector4fMap (); pt_tgt[3] = 1; Eigen::Vector4f p_tr = transform * pt_src; // Calculate the distance from the transformed point to its correspondence if ((p_tr - pt_tgt).squaredNorm () < thresh) nr_p++; } return (nr_p); } ////////////////////////////////////////////////////////////////////////// template <typename PointT> void pcl::SampleConsensusModelRegistration<PointT>::optimizeModelCoefficients (const std::vector<int> &inliers, const Eigen::VectorXf &model_coefficients, Eigen::VectorXf &optimized_coefficients) { if (indices_->size () != indices_tgt_->size ()) { PCL_ERROR ("[pcl::SampleConsensusModelRegistration::optimizeModelCoefficients] Number of source indices (%lu) differs than number of target indices (%lu)!\n", (unsigned long)indices_->size (), (unsigned long)indices_tgt_->size ()); optimized_coefficients = model_coefficients; return; } // Check if the model is valid given the user constraints if (!isModelValid (model_coefficients) || !target_) { optimized_coefficients = model_coefficients; return; } std::vector<int> indices_src (inliers.size ()); std::vector<int> indices_tgt (inliers.size ()); for (size_t i = 0; i < inliers.size (); ++i) { // NOTE: not tested! indices_src[i] = (*indices_)[inliers[i]]; indices_tgt[i] = (*indices_tgt_)[inliers[i]]; } estimateRigidTransformationSVD (*input_, indices_src, *target_, indices_tgt, optimized_coefficients); } ////////////////////////////////////////////////////////////////////////// template <typename PointT> void pcl::SampleConsensusModelRegistration<PointT>::estimateRigidTransformationSVD ( const pcl::PointCloud<PointT> &cloud_src, const std::vector<int> &indices_src, const pcl::PointCloud<PointT> &cloud_tgt, const std::vector<int> &indices_tgt, Eigen::VectorXf &transform) { transform.resize (16); Eigen::Vector4f centroid_src, centroid_tgt; // Estimate the centroids of source, target compute3DCentroid (cloud_src, indices_src, centroid_src); compute3DCentroid (cloud_tgt, indices_tgt, centroid_tgt); // Subtract the centroids from source, target Eigen::MatrixXf cloud_src_demean; demeanPointCloud (cloud_src, indices_src, centroid_src, cloud_src_demean); Eigen::MatrixXf cloud_tgt_demean; demeanPointCloud (cloud_tgt, indices_tgt, centroid_tgt, cloud_tgt_demean); // Assemble the correlation matrix H = source * target' Eigen::Matrix3f H = (cloud_src_demean * cloud_tgt_demean.transpose ()).topLeftCorner<3, 3>(); // Compute the Singular Value Decomposition Eigen::JacobiSVD<Eigen::Matrix3f> svd (H, Eigen::ComputeFullU | Eigen::ComputeFullV); Eigen::Matrix3f u = svd.matrixU (); Eigen::Matrix3f v = svd.matrixV (); // Compute R = V * U' if (u.determinant () * v.determinant () < 0) { for (int x = 0; x < 3; ++x) v (x, 2) *= -1; } Eigen::Matrix3f R = v * u.transpose (); // Return the correct transformation transform.segment<3> (0) = R.row (0); transform[12] = 0; transform.segment<3> (4) = R.row (1); transform[13] = 0; transform.segment<3> (8) = R.row (2); transform[14] = 0; Eigen::Vector3f t = centroid_tgt.head<3> () - R * centroid_src.head<3> (); transform[3] = t[0]; transform[7] = t[1]; transform[11] = t[2]; transform[15] = 1.0; } #define PCL_INSTANTIATE_SampleConsensusModelRegistration(T) template class PCL_EXPORTS pcl::SampleConsensusModelRegistration<T>; #endif // PCL_SAMPLE_CONSENSUS_IMPL_SAC_MODEL_REGISTRATION_H_
bsd-3-clause
endlessm/chromium-browser
tools/gn/src/gn/function_forward_variables_from.cc
9648
// 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 "gn/err.h" #include "gn/functions.h" #include "gn/parse_tree.h" #include "gn/scope.h" namespace functions { namespace { void ForwardAllValues(const FunctionCallNode* function, Scope* source, Scope* dest, const std::set<std::string>& exclusion_set, Err* err) { Scope::MergeOptions options; // This function needs to clobber existing for it to be useful. It will be // called in a template to forward all values, but there will be some // default stuff like configs set up in both scopes, so it would always // fail if it didn't clobber. options.clobber_existing = true; options.skip_private_vars = true; options.mark_dest_used = false; options.excluded_values = exclusion_set; source->NonRecursiveMergeTo(dest, options, function, "source scope", err); source->MarkAllUsed(); } void ForwardValuesFromList(Scope* source, Scope* dest, const std::vector<Value>& list, const std::set<std::string>& exclusion_set, Err* err) { for (const Value& cur : list) { if (!cur.VerifyTypeIs(Value::STRING, err)) return; if (exclusion_set.find(cur.string_value()) != exclusion_set.end()) continue; const Value* value = source->GetValue(cur.string_value(), true); if (value) { // Use the storage key for the original value rather than the string in // "cur" because "cur" is a temporary that will be deleted, and Scopes // expect a persistent std::string_view (it won't copy). Not doing this // will lead the scope's key to point to invalid memory after this // returns. std::string_view storage_key = source->GetStorageKey(cur.string_value()); if (storage_key.empty()) { // Programmatic value, don't allow copying. *err = Err(cur, "This value can't be forwarded.", "The variable \"" + cur.string_value() + "\" is a built-in."); return; } // Don't allow clobbering existing values. const Value* existing_value = dest->GetValue(storage_key); if (existing_value) { *err = Err( cur, "Clobbering existing value.", "The current scope already defines a value \"" + cur.string_value() + "\".\nforward_variables_from() won't clobber " "existing values. If you want to\nmerge lists, you'll need to " "do this explicitly."); err->AppendSubErr(Err(*existing_value, "value being clobbered.")); return; } // Keep the origin information from the original value. The normal // usage is for this to be used in a template, and if there's an error, // the user expects to see the line where they set the variable // blamed, rather than a template call to forward_variables_from(). dest->SetValue(storage_key, *value, value->origin()); } } } } // namespace const char kForwardVariablesFrom[] = "forward_variables_from"; const char kForwardVariablesFrom_HelpShort[] = "forward_variables_from: Copies variables from a different scope."; const char kForwardVariablesFrom_Help[] = R"(forward_variables_from: Copies variables from a different scope. forward_variables_from(from_scope, variable_list_or_star, variable_to_not_forward_list = []) Copies the given variables from the given scope to the local scope if they exist. This is normally used in the context of templates to use the values of variables defined in the template invocation to a template-defined target. The variables in the given variable_list will be copied if they exist in the given scope or any enclosing scope. If they do not exist, nothing will happen and they be left undefined in the current scope. As a special case, if the variable_list is a string with the value of "*", all variables from the given scope will be copied. "*" only copies variables set directly on the from_scope, not enclosing ones. Otherwise it would duplicate all global variables. When an explicit list of variables is supplied, if the variable exists in the current (destination) scope already, an error will be thrown. If "*" is specified, variables in the current scope will be clobbered (the latter is important because most targets have an implicit configs list, which means it wouldn't work at all if it didn't clobber). The sources assignment filter (see "gn help set_sources_assignment_filter") is never applied by this function. It's assumed than any desired filtering was already done when sources was set on the from_scope. If variables_to_not_forward_list is non-empty, then it must contains a list of variable names that will not be forwarded. This is mostly useful when variable_list_or_star has a value of "*". Examples # forward_variables_from(invoker, ["foo"]) # is equivalent to: assert(!defined(foo)) if (defined(invoker.foo)) { foo = invoker.foo } # This is a common action template. It would invoke a script with some given # parameters, and wants to use the various types of deps and the visibility # from the invoker if it's defined. It also injects an additional dependency # to all targets. template("my_test") { action(target_name) { forward_variables_from(invoker, [ "data_deps", "deps", "public_deps", "visibility"]) # Add our test code to the dependencies. # "deps" may or may not be defined at this point. if (defined(deps)) { deps += [ "//tools/doom_melon" ] } else { deps = [ "//tools/doom_melon" ] } } } # This is a template around a target whose type depends on a global variable. # It forwards all values from the invoker. template("my_wrapper") { target(my_wrapper_target_type, target_name) { forward_variables_from(invoker, "*") } } # A template that wraps another. It adds behavior based on one # variable, and forwards all others to the nested target. template("my_ios_test_app") { ios_test_app(target_name) { forward_variables_from(invoker, "*", ["test_bundle_name"]) if (!defined(extra_substitutions)) { extra_substitutions = [] } extra_substitutions += [ "BUNDLE_ID_TEST_NAME=$test_bundle_name" ] } } )"; // This function takes a ListNode rather than a resolved vector of values // both avoid copying the potentially-large source scope, and so the variables // in the source scope can be marked as used. Value RunForwardVariablesFrom(Scope* scope, const FunctionCallNode* function, const ListNode* args_list, Err* err) { const auto& args_vector = args_list->contents(); if (args_vector.size() != 2 && args_vector.size() != 3) { *err = Err(function, "Wrong number of arguments.", "Expecting two or three arguments."); return Value(); } Value* value = nullptr; // Value to use, may point to result_value. Value result_value; // Storage for the "evaluate" case. const IdentifierNode* identifier = args_vector[0]->AsIdentifier(); if (identifier) { // Optimize the common case where the input scope is an identifier. This // prevents a copy of a potentially large Scope object. value = scope->GetMutableValue(identifier->value().value(), Scope::SEARCH_NESTED, true); if (!value) { *err = Err(identifier, "Undefined identifier."); return Value(); } } else { // Non-optimized case, just evaluate the argument. result_value = args_vector[0]->Execute(scope, err); if (err->has_error()) return Value(); value = &result_value; } // Extract the source scope. if (!value->VerifyTypeIs(Value::SCOPE, err)) return Value(); Scope* source = value->scope_value(); // Extract the exclusion list if defined. std::set<std::string> exclusion_set; if (args_vector.size() == 3) { Value exclusion_value = args_vector[2]->Execute(scope, err); if (err->has_error()) return Value(); if (exclusion_value.type() != Value::LIST) { *err = Err(exclusion_value, "Not a valid list of variables to exclude.", "Expecting a list of strings."); return Value(); } for (const Value& cur : exclusion_value.list_value()) { if (!cur.VerifyTypeIs(Value::STRING, err)) return Value(); exclusion_set.insert(cur.string_value()); } } // Extract the list. If all_values is not set, the what_value will be a list. Value what_value = args_vector[1]->Execute(scope, err); if (err->has_error()) return Value(); if (what_value.type() == Value::STRING) { if (what_value.string_value() == "*") { ForwardAllValues(function, source, scope, exclusion_set, err); return Value(); } } else { if (what_value.type() == Value::LIST) { ForwardValuesFromList(source, scope, what_value.list_value(), exclusion_set, err); return Value(); } } // Not the right type of argument. *err = Err(what_value, "Not a valid list of variables to copy.", "Expecting either the string \"*\" or a list of strings."); return Value(); } } // namespace functions
bsd-3-clause
mudunuriRaju/tlr-live
tollbackend/web/js/angular-1.5.5/i18n/angular-locale_bem.js
4089
'use strict'; angular.module("ngLocale", [], ["$provide", function ($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "uluchelo", "akasuba" ], "DAY": [ "Pa Mulungu", "Palichimo", "Palichibuli", "Palichitatu", "Palichine", "Palichisano", "Pachibelushi" ], "ERANAMES": [ "Before Yesu", "After Yesu" ], "ERAS": [ "BC", "AD" ], "FIRSTDAYOFWEEK": 0, "MONTH": [ "Januari", "Februari", "Machi", "Epreo", "Mei", "Juni", "Julai", "Ogasti", "Septemba", "Oktoba", "Novemba", "Disemba" ], "SHORTDAY": [ "Pa Mulungu", "Palichimo", "Palichibuli", "Palichitatu", "Palichine", "Palichisano", "Pachibelushi" ], "SHORTMONTH": [ "Jan", "Feb", "Mac", "Epr", "Mei", "Jun", "Jul", "Oga", "Sep", "Okt", "Nov", "Dis" ], "STANDALONEMONTH": [ "Januari", "Februari", "Machi", "Epreo", "Mei", "Juni", "Julai", "Ogasti", "Septemba", "Oktoba", "Novemba", "Disemba" ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "EEEE, d MMMM y", "longDate": "d MMMM y", "medium": "d MMM y h:mm:ss a", "mediumDate": "d MMM y", "mediumTime": "h:mm:ss a", "short": "dd/MM/y h:mm a", "shortDate": "dd/MM/y", "shortTime": "h:mm a" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "ZMW", "DECIMAL_SEP": ".", "GROUP_SEP": ",", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-\u00a4", "negSuf": "", "posPre": "\u00a4", "posSuf": "" } ] }, "id": "bem", "localeID": "bem", "pluralCat": function (n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER; } }); }]);
bsd-3-clause
ajrulez/ig-json-parser
processor/src/test/java/com/instagram/common/json/annotation/processor/InterModuleTest.java
3225
// Copyright 2004-present Facebook. All Rights Reserved. package com.instagram.common.json.annotation.processor; import java.io.IOException; import com.instagram.common.json.annotation.processor.dependent.SubclassUUT; import com.instagram.common.json.annotation.processor.dependent.SubclassUUT__JsonHelper; import com.instagram.common.json.annotation.processor.dependent.SubclassWithAbstractParentUUT; import com.instagram.common.json.annotation.processor.dependent.SubclassWithAbstractParentUUT__JsonHelper; import com.instagram.common.json.annotation.processor.dependent.WrapperClassUUT; import com.instagram.common.json.annotation.processor.dependent.WrapperClassUUT__JsonHelper; import com.instagram.common.json.annotation.processor.parent.ParentUUT; import org.json.JSONException; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * Try to do stuff across modules. */ public class InterModuleTest { /** * Subclasses a java object in a different class. */ @Test public void subclassingTest() throws IOException, JSONException { final int intValue = 25; final String stringValue = "hello world\r\n\'\""; final int subIntValue = 30; SubclassUUT uut = new SubclassUUT(); uut.parentInt = intValue; uut.subclassInt = subIntValue; uut.parentString = stringValue; // serialize it String serialized = SubclassUUT__JsonHelper.serializeToJson(uut); SubclassUUT parsed = SubclassUUT__JsonHelper.parseFromJson(serialized); assertEquals(uut.parentInt, parsed.parentInt); assertEquals(uut.parentString, parsed.parentString); assertEquals(uut.subclassInt, parsed.subclassInt); } /** * Subclasses an abstract java object in a different class. */ @Test public void abstractSubclassingTest() throws IOException, JSONException { final int intValue = 25; final String stringValue = "hello world\r\n\'\""; final int subIntValue = 30; SubclassWithAbstractParentUUT uut = new SubclassWithAbstractParentUUT(); uut.parentInt = intValue; uut.subclassInt = subIntValue; uut.parentString = stringValue; // serialize it String serialized = SubclassWithAbstractParentUUT__JsonHelper.serializeToJson(uut); SubclassWithAbstractParentUUT parsed = SubclassWithAbstractParentUUT__JsonHelper.parseFromJson(serialized); assertEquals(uut.parentInt, parsed.parentInt); assertEquals(uut.parentString, parsed.parentString); assertEquals(uut.subclassInt, parsed.subclassInt); } /** * Includes a java object in a different class. */ @Test public void wrapperTest() throws IOException, JSONException { final int intValue = 25; final String stringValue = "hello world\r\n\'\""; WrapperClassUUT uut = new WrapperClassUUT(); uut.parent = new ParentUUT(); uut.parent.parentInt = intValue; uut.parent.parentString = stringValue; // serialize it String serialized = WrapperClassUUT__JsonHelper.serializeToJson(uut); WrapperClassUUT parsed = WrapperClassUUT__JsonHelper.parseFromJson(serialized); assertEquals(uut.parent.parentInt, parsed.parent.parentInt); assertEquals(uut.parent.parentString, parsed.parent.parentString); } }
bsd-3-clause
cathalmccabe/PYNQ
pynq/lib/pynqmicroblaze/magic.py
3738
# Copyright (c) 2018, Xilinx, 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: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder 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 HOLDER 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. __author__ = "Peter Ogden" __copyright__ = "Copyright 2018, Xilinx" __email__ = "pynq_support@xilinx.com" from IPython.core.magic import cell_magic, Magics, magics_class from IPython import get_ipython from IPython.display import display, HTML from IPython.display import display_javascript from .rpc import MicroblazeRPC class _DataHolder: pass class _FunctionWrapper: def __init__(self, function, program): self.library = program self.stdio = program._mb.stream self._mb = program._mb self._function = function def __call__(self, *args): return self._function(*args) async def call_async(self, *args): return await self._function.call_async(*args) def reset(self): self._mb.reset() def release(self): self.reset() @magics_class class MicroblazeMagics(Magics): def name2obj(self, name): _proxy = _DataHolder() exec("_proxy.obj = {}".format(name), locals(), self.shell.user_ns) return _proxy.obj @cell_magic def microblaze(self, line, cell): mb_info = self.name2obj(line) try: program = MicroblazeRPC(mb_info, '#line 1 "cell_magic"\n\n' + cell) except RuntimeError as r: return HTML("<pre>Compile FAILED\n" + r.args[0] + "</pre>") for name, adapter in program.visitor.functions.items(): if adapter.filename == "cell_magic": self.shell.user_ns.update( {name: _FunctionWrapper(getattr(program, name), program)}) js = """ try { require(['notebook/js/codecell'], function(codecell) { codecell.CodeCell.options_default.highlight_modes[ 'magic_text/x-csrc'] = {'reg':[/^%%microblaze/]}; Jupyter.notebook.events.one('kernel_ready.Kernel', function(){ Jupyter.notebook.get_cells().map(function(cell){ if (cell.cell_type == 'code'){ cell.auto_highlight(); } }) ; }); }); } catch (e) {}; """ instance = get_ipython() if instance: get_ipython().register_magics(MicroblazeMagics) display_javascript(js, raw=True) import nest_asyncio nest_asyncio.apply()
bsd-3-clause
justinccdev/opensim
OpenSim/Services/Interfaces/IUserProfilesService.cs
3307
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project 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 DEVELOPERS ``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 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. */ using System; using OpenSim.Framework; using OpenMetaverse; using OpenMetaverse.StructuredData; namespace OpenSim.Services.Interfaces { public interface IUserProfilesService { #region Classifieds OSD AvatarClassifiedsRequest(UUID creatorId); bool ClassifiedUpdate(UserClassifiedAdd ad, ref string result); bool ClassifiedInfoRequest(ref UserClassifiedAdd ad, ref string result); bool ClassifiedDelete(UUID recordId); #endregion Classifieds #region Picks OSD AvatarPicksRequest(UUID creatorId); bool PickInfoRequest(ref UserProfilePick pick, ref string result); bool PicksUpdate(ref UserProfilePick pick, ref string result); bool PicksDelete(UUID pickId); #endregion Picks #region Notes bool AvatarNotesRequest(ref UserProfileNotes note); bool NotesUpdate(ref UserProfileNotes note, ref string result); #endregion Notes #region Profile Properties bool AvatarPropertiesRequest(ref UserProfileProperties prop, ref string result); bool AvatarPropertiesUpdate(ref UserProfileProperties prop, ref string result); #endregion Profile Properties #region Interests bool AvatarInterestsUpdate(UserProfileProperties prop, ref string result); #endregion Interests #region Utility OSD AvatarImageAssetsRequest(UUID avatarId); #endregion Utility #region UserData bool RequestUserAppData(ref UserAppData prop, ref string result); bool SetUserAppData(UserAppData prop, ref string result); #endregion UserData } }
bsd-3-clause
patrickm/chromium.src
chrome/browser/extensions/api/identity/identity_apitest.cc
51333
// Copyright (c) 2012 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/command_line.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/values.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/extensions/api/identity/identity_api.h" #include "chrome/browser/extensions/component_loader.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/extensions/extension_function_test_utils.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/signin/signin_manager.h" #include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/api/identity/oauth2_manifest_handler.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/test_switches.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_source.h" #include "content/public/test/test_utils.h" #include "extensions/common/id_util.h" #include "google_apis/gaia/google_service_auth_error.h" #include "google_apis/gaia/oauth2_mint_token_flow.h" #include "grit/browser_resources.h" #include "net/test/spawned_test_server/spawned_test_server.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" using testing::_; using testing::Return; using testing::ReturnRef; namespace extensions { namespace { namespace errors = identity_constants; namespace utils = extension_function_test_utils; static const char kAccessToken[] = "auth_token"; static const char kExtensionId[] = "ext_id"; // This helps us be able to wait until an AsyncExtensionFunction calls // SendResponse. class SendResponseDelegate : public UIThreadExtensionFunction::DelegateForTests { public: SendResponseDelegate() : should_post_quit_(false) {} virtual ~SendResponseDelegate() {} void set_should_post_quit(bool should_quit) { should_post_quit_ = should_quit; } bool HasResponse() { return response_.get() != NULL; } bool GetResponse() { EXPECT_TRUE(HasResponse()); return *response_.get(); } virtual void OnSendResponse(UIThreadExtensionFunction* function, bool success, bool bad_message) OVERRIDE { ASSERT_FALSE(bad_message); ASSERT_FALSE(HasResponse()); response_.reset(new bool); *response_ = success; if (should_post_quit_) { base::MessageLoopForUI::current()->Quit(); } } private: scoped_ptr<bool> response_; bool should_post_quit_; }; class AsyncExtensionBrowserTest : public ExtensionBrowserTest { protected: // Asynchronous function runner allows tests to manipulate the browser window // after the call happens. void RunFunctionAsync( UIThreadExtensionFunction* function, const std::string& args) { response_delegate_.reset(new SendResponseDelegate); function->set_test_delegate(response_delegate_.get()); scoped_ptr<base::ListValue> parsed_args(utils::ParseList(args)); EXPECT_TRUE(parsed_args.get()) << "Could not parse extension function arguments: " << args; function->SetArgs(parsed_args.get()); if (!function->GetExtension()) { scoped_refptr<Extension> empty_extension( utils::CreateEmptyExtension()); function->set_extension(empty_extension.get()); } function->set_browser_context(browser()->profile()); function->set_has_callback(true); function->Run(); } std::string WaitForError(UIThreadExtensionFunction* function) { RunMessageLoopUntilResponse(); EXPECT_FALSE(function->GetResultList()) << "Did not expect a result"; return function->GetError(); } base::Value* WaitForSingleResult(UIThreadExtensionFunction* function) { RunMessageLoopUntilResponse(); EXPECT_TRUE(function->GetError().empty()) << "Unexpected error: " << function->GetError(); const base::Value* single_result = NULL; if (function->GetResultList() != NULL && function->GetResultList()->Get(0, &single_result)) { return single_result->DeepCopy(); } return NULL; } private: void RunMessageLoopUntilResponse() { // If the RunImpl of |function| didn't already call SendResponse, run the // message loop until they do. if (!response_delegate_->HasResponse()) { response_delegate_->set_should_post_quit(true); content::RunMessageLoop(); } EXPECT_TRUE(response_delegate_->HasResponse()); } scoped_ptr<SendResponseDelegate> response_delegate_; }; class TestOAuth2MintTokenFlow : public OAuth2MintTokenFlow { public: enum ResultType { ISSUE_ADVICE_SUCCESS, MINT_TOKEN_SUCCESS, MINT_TOKEN_FAILURE, MINT_TOKEN_BAD_CREDENTIALS, MINT_TOKEN_SERVICE_ERROR }; TestOAuth2MintTokenFlow(ResultType result, OAuth2MintTokenFlow::Delegate* delegate) : OAuth2MintTokenFlow(NULL, delegate, OAuth2MintTokenFlow::Parameters()), result_(result), delegate_(delegate) { } virtual void Start() OVERRIDE { switch (result_) { case ISSUE_ADVICE_SUCCESS: { IssueAdviceInfo info; delegate_->OnIssueAdviceSuccess(info); break; } case MINT_TOKEN_SUCCESS: { delegate_->OnMintTokenSuccess(kAccessToken, 3600); break; } case MINT_TOKEN_FAILURE: { GoogleServiceAuthError error(GoogleServiceAuthError::CONNECTION_FAILED); delegate_->OnMintTokenFailure(error); break; } case MINT_TOKEN_BAD_CREDENTIALS: { GoogleServiceAuthError error( GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS); delegate_->OnMintTokenFailure(error); break; } case MINT_TOKEN_SERVICE_ERROR: { GoogleServiceAuthError error = GoogleServiceAuthError::FromServiceError("invalid_scope"); delegate_->OnMintTokenFailure(error); break; } } } private: ResultType result_; OAuth2MintTokenFlow::Delegate* delegate_; }; // Waits for a specific GURL to generate a NOTIFICATION_LOAD_STOP event and // saves a pointer to the window embedding the WebContents, which can be later // closed. class WaitForGURLAndCloseWindow : public content::WindowedNotificationObserver { public: explicit WaitForGURLAndCloseWindow(GURL url) : WindowedNotificationObserver( content::NOTIFICATION_LOAD_STOP, content::NotificationService::AllSources()), url_(url) {} // NotificationObserver: virtual void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) OVERRIDE { content::NavigationController* web_auth_flow_controller = content::Source<content::NavigationController>(source).ptr(); content::WebContents* web_contents = web_auth_flow_controller->GetWebContents(); if (web_contents->GetURL() == url_) { // It is safe to keep the pointer here, because we know in a test, that // the WebContents won't go away before CloseEmbedderWebContents is // called. Don't copy this code to production. embedder_web_contents_ = web_contents->GetEmbedderWebContents(); // Condtionally invoke parent class so that Wait will not exit // until the target URL arrives. content::WindowedNotificationObserver::Observe(type, source, details); } } // Closes the window embedding the WebContents. The action is separated from // the Observe method to make sure the list of observers is not deleted, // while some event is already being processed. (That causes ASAN failures.) void CloseEmbedderWebContents() { if (embedder_web_contents_) embedder_web_contents_->Close(); } private: GURL url_; content::WebContents* embedder_web_contents_; }; } // namespace class MockGetAuthTokenFunction : public IdentityGetAuthTokenFunction { public: MockGetAuthTokenFunction() : login_access_token_result_(true), login_ui_result_(true), scope_ui_result_(true), login_ui_shown_(false), scope_ui_shown_(false) { } void set_login_access_token_result(bool result) { login_access_token_result_ = result; } void set_login_ui_result(bool result) { login_ui_result_ = result; } void set_scope_ui_failure(GaiaWebAuthFlow::Failure failure) { scope_ui_result_ = false; scope_ui_failure_ = failure; } void set_scope_ui_oauth_error(const std::string& oauth_error) { scope_ui_result_ = false; scope_ui_failure_ = GaiaWebAuthFlow::OAUTH_ERROR; scope_ui_oauth_error_ = oauth_error; } bool login_ui_shown() const { return login_ui_shown_; } bool scope_ui_shown() const { return scope_ui_shown_; } virtual void StartLoginAccessTokenRequest() OVERRIDE { if (login_access_token_result_) { OnGetTokenSuccess(login_token_request_.get(), "access_token", base::Time::Now() + base::TimeDelta::FromHours(1LL)); } else { GoogleServiceAuthError error( GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS); OnGetTokenFailure(login_token_request_.get(), error); } } virtual void ShowLoginPopup() OVERRIDE { EXPECT_FALSE(login_ui_shown_); login_ui_shown_ = true; if (login_ui_result_) SigninSuccess(); else SigninFailed(); } virtual void ShowOAuthApprovalDialog( const IssueAdviceInfo& issue_advice) OVERRIDE { scope_ui_shown_ = true; if (scope_ui_result_) { OnGaiaFlowCompleted(kAccessToken, "3600"); } else if (scope_ui_failure_ == GaiaWebAuthFlow::SERVICE_AUTH_ERROR) { GoogleServiceAuthError error(GoogleServiceAuthError::CONNECTION_FAILED); OnGaiaFlowFailure(scope_ui_failure_, error, ""); } else { GoogleServiceAuthError error(GoogleServiceAuthError::NONE); OnGaiaFlowFailure(scope_ui_failure_, error, scope_ui_oauth_error_); } } MOCK_CONST_METHOD0(HasLoginToken, bool()); MOCK_METHOD1(CreateMintTokenFlow, OAuth2MintTokenFlow* (const std::string& login_access_token)); private: ~MockGetAuthTokenFunction() {} bool login_access_token_result_; bool login_ui_result_; bool scope_ui_result_; GaiaWebAuthFlow::Failure scope_ui_failure_; std::string scope_ui_oauth_error_; bool login_ui_shown_; bool scope_ui_shown_; }; class MockQueuedMintRequest : public IdentityMintRequestQueue::Request { public: MOCK_METHOD1(StartMintToken, void(IdentityMintRequestQueue::MintType)); }; class GetAuthTokenFunctionTest : public AsyncExtensionBrowserTest { protected: enum OAuth2Fields { NONE = 0, CLIENT_ID = 1, SCOPES = 2, AS_COMPONENT = 4 }; virtual ~GetAuthTokenFunctionTest() {} // Helper to create an extension with specific OAuth2Info fields set. // |fields_to_set| should be computed by using fields of Oauth2Fields enum. const Extension* CreateExtension(int fields_to_set) { const Extension* ext; base::FilePath manifest_path = test_data_dir_.AppendASCII("platform_apps/oauth2"); base::FilePath component_manifest_path = test_data_dir_.AppendASCII("packaged_app/component_oauth2"); if ((fields_to_set & AS_COMPONENT) == 0) ext = LoadExtension(manifest_path); else ext = LoadExtensionAsComponent(component_manifest_path); OAuth2Info& oauth2_info = const_cast<OAuth2Info&>(OAuth2Info::GetOAuth2Info(ext)); if ((fields_to_set & CLIENT_ID) != 0) oauth2_info.client_id = "client1"; if ((fields_to_set & SCOPES) != 0) { oauth2_info.scopes.push_back("scope1"); oauth2_info.scopes.push_back("scope2"); } extension_id_ = ext->id(); oauth_scopes_ = std::set<std::string>(oauth2_info.scopes.begin(), oauth2_info.scopes.end()); return ext; } IdentityAPI* id_api() { return IdentityAPI::GetFactoryInstance()->Get(browser()->profile()); } const std::string GetPrimaryAccountId() { SigninManagerBase* signin_manager = SigninManagerFactory::GetForProfile(browser()->profile()); return signin_manager->GetAuthenticatedAccountId(); } void SetCachedToken(const IdentityTokenCacheValue& token_data) { ExtensionTokenKey key(extension_id_, GetPrimaryAccountId(), oauth_scopes_); id_api()->SetCachedToken(key, token_data); } const IdentityTokenCacheValue& GetCachedToken() { ExtensionTokenKey key(extension_id_, GetPrimaryAccountId(), oauth_scopes_); return id_api()->GetCachedToken(key); } void QueueRequestStart(IdentityMintRequestQueue::MintType type, IdentityMintRequestQueue::Request* request) { ExtensionTokenKey key(extension_id_, GetPrimaryAccountId(), oauth_scopes_); id_api()->mint_queue()->RequestStart(type, key, request); } void QueueRequestComplete(IdentityMintRequestQueue::MintType type, IdentityMintRequestQueue::Request* request) { ExtensionTokenKey key(extension_id_, GetPrimaryAccountId(), oauth_scopes_); id_api()->mint_queue()->RequestComplete(type, key, request); } private: std::string extension_id_; std::set<std::string> oauth_scopes_; }; IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, NoClientId) { scoped_refptr<MockGetAuthTokenFunction> func(new MockGetAuthTokenFunction()); func->set_extension(CreateExtension(SCOPES)); std::string error = utils::RunFunctionAndReturnError( func.get(), "[{}]", browser()); EXPECT_EQ(std::string(errors::kInvalidClientId), error); EXPECT_FALSE(func->login_ui_shown()); EXPECT_FALSE(func->scope_ui_shown()); } IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, NoScopes) { scoped_refptr<MockGetAuthTokenFunction> func(new MockGetAuthTokenFunction()); func->set_extension(CreateExtension(CLIENT_ID)); std::string error = utils::RunFunctionAndReturnError( func.get(), "[{}]", browser()); EXPECT_EQ(std::string(errors::kInvalidScopes), error); EXPECT_FALSE(func->login_ui_shown()); EXPECT_FALSE(func->scope_ui_shown()); } IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, NonInteractiveNotSignedIn) { scoped_refptr<MockGetAuthTokenFunction> func(new MockGetAuthTokenFunction()); func->set_extension(CreateExtension(CLIENT_ID | SCOPES)); EXPECT_CALL(*func.get(), HasLoginToken()).WillOnce(Return(false)); std::string error = utils::RunFunctionAndReturnError( func.get(), "[{}]", browser()); EXPECT_EQ(std::string(errors::kUserNotSignedIn), error); EXPECT_FALSE(func->login_ui_shown()); EXPECT_FALSE(func->scope_ui_shown()); } IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, NonInteractiveMintFailure) { scoped_refptr<MockGetAuthTokenFunction> func(new MockGetAuthTokenFunction()); func->set_extension(CreateExtension(CLIENT_ID | SCOPES)); EXPECT_CALL(*func.get(), HasLoginToken()) .WillOnce(Return(true)); TestOAuth2MintTokenFlow* flow = new TestOAuth2MintTokenFlow( TestOAuth2MintTokenFlow::MINT_TOKEN_FAILURE, func.get()); EXPECT_CALL(*func.get(), CreateMintTokenFlow(_)).WillOnce(Return(flow)); std::string error = utils::RunFunctionAndReturnError( func.get(), "[{}]", browser()); EXPECT_TRUE(StartsWithASCII(error, errors::kAuthFailure, false)); EXPECT_FALSE(func->login_ui_shown()); EXPECT_FALSE(func->scope_ui_shown()); } IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, NonInteractiveLoginAccessTokenFailure) { scoped_refptr<MockGetAuthTokenFunction> func(new MockGetAuthTokenFunction()); func->set_extension(CreateExtension(CLIENT_ID | SCOPES)); EXPECT_CALL(*func.get(), HasLoginToken()) .WillOnce(Return(true)); func->set_login_access_token_result(false); std::string error = utils::RunFunctionAndReturnError( func.get(), "[{}]", browser()); EXPECT_TRUE(StartsWithASCII(error, errors::kAuthFailure, false)); } IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, NonInteractiveMintAdviceSuccess) { scoped_refptr<const Extension> extension(CreateExtension(CLIENT_ID | SCOPES)); scoped_refptr<MockGetAuthTokenFunction> func(new MockGetAuthTokenFunction()); func->set_extension(extension.get()); EXPECT_CALL(*func.get(), HasLoginToken()).WillOnce(Return(true)); TestOAuth2MintTokenFlow* flow = new TestOAuth2MintTokenFlow( TestOAuth2MintTokenFlow::ISSUE_ADVICE_SUCCESS, func.get()); EXPECT_CALL(*func.get(), CreateMintTokenFlow(_)).WillOnce(Return(flow)); std::string error = utils::RunFunctionAndReturnError( func.get(), "[{}]", browser()); EXPECT_EQ(std::string(errors::kNoGrant), error); EXPECT_FALSE(func->login_ui_shown()); EXPECT_FALSE(func->scope_ui_shown()); EXPECT_EQ(IdentityTokenCacheValue::CACHE_STATUS_ADVICE, GetCachedToken().status()); } IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, NonInteractiveMintBadCredentials) { scoped_refptr<MockGetAuthTokenFunction> func(new MockGetAuthTokenFunction()); func->set_extension(CreateExtension(CLIENT_ID | SCOPES)); EXPECT_CALL(*func.get(), HasLoginToken()) .WillOnce(Return(true)); TestOAuth2MintTokenFlow* flow = new TestOAuth2MintTokenFlow( TestOAuth2MintTokenFlow::MINT_TOKEN_BAD_CREDENTIALS, func.get()); EXPECT_CALL(*func.get(), CreateMintTokenFlow(_)).WillOnce(Return(flow)); std::string error = utils::RunFunctionAndReturnError( func.get(), "[{}]", browser()); EXPECT_TRUE(StartsWithASCII(error, errors::kAuthFailure, false)); EXPECT_FALSE(func->login_ui_shown()); EXPECT_FALSE(func->scope_ui_shown()); EXPECT_EQ(GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS, id_api()->GetAuthStatusForTest().state()); } IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, NonInteractiveMintServiceError) { scoped_refptr<MockGetAuthTokenFunction> func(new MockGetAuthTokenFunction()); func->set_extension(CreateExtension(CLIENT_ID | SCOPES)); EXPECT_CALL(*func.get(), HasLoginToken()).WillOnce(Return(true)); TestOAuth2MintTokenFlow* flow = new TestOAuth2MintTokenFlow( TestOAuth2MintTokenFlow::MINT_TOKEN_SERVICE_ERROR, func.get()); EXPECT_CALL(*func.get(), CreateMintTokenFlow(_)).WillOnce(Return(flow)); std::string error = utils::RunFunctionAndReturnError(func.get(), "[{}]", browser()); EXPECT_TRUE(StartsWithASCII(error, errors::kAuthFailure, false)); EXPECT_FALSE(func->login_ui_shown()); EXPECT_FALSE(func->scope_ui_shown()); EXPECT_EQ(GoogleServiceAuthError::AuthErrorNone(), id_api()->GetAuthStatusForTest()); } IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, NonInteractiveSuccess) { #if defined(OS_WIN) && defined(USE_ASH) // Disable this test in Metro+Ash for now (http://crbug.com/262796). if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests)) return; #endif scoped_refptr<MockGetAuthTokenFunction> func(new MockGetAuthTokenFunction()); scoped_refptr<const Extension> extension(CreateExtension(CLIENT_ID | SCOPES)); func->set_extension(extension.get()); EXPECT_CALL(*func.get(), HasLoginToken()).WillOnce(Return(true)); TestOAuth2MintTokenFlow* flow = new TestOAuth2MintTokenFlow( TestOAuth2MintTokenFlow::MINT_TOKEN_SUCCESS, func.get()); EXPECT_CALL(*func.get(), CreateMintTokenFlow(_)).WillOnce(Return(flow)); scoped_ptr<base::Value> value(utils::RunFunctionAndReturnSingleResult( func.get(), "[{}]", browser())); std::string access_token; EXPECT_TRUE(value->GetAsString(&access_token)); EXPECT_EQ(std::string(kAccessToken), access_token); EXPECT_FALSE(func->login_ui_shown()); EXPECT_FALSE(func->scope_ui_shown()); EXPECT_EQ(IdentityTokenCacheValue::CACHE_STATUS_TOKEN, GetCachedToken().status()); } IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, InteractiveLoginCanceled) { scoped_refptr<MockGetAuthTokenFunction> func(new MockGetAuthTokenFunction()); func->set_extension(CreateExtension(CLIENT_ID | SCOPES)); EXPECT_CALL(*func.get(), HasLoginToken()).WillOnce(Return(false)); func->set_login_ui_result(false); std::string error = utils::RunFunctionAndReturnError( func.get(), "[{\"interactive\": true}]", browser()); EXPECT_EQ(std::string(errors::kUserNotSignedIn), error); EXPECT_TRUE(func->login_ui_shown()); EXPECT_FALSE(func->scope_ui_shown()); } IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, InteractiveMintBadCredentialsLoginCanceled) { scoped_refptr<MockGetAuthTokenFunction> func(new MockGetAuthTokenFunction()); func->set_extension(CreateExtension(CLIENT_ID | SCOPES)); EXPECT_CALL(*func.get(), HasLoginToken()) .WillOnce(Return(true)); TestOAuth2MintTokenFlow* flow = new TestOAuth2MintTokenFlow( TestOAuth2MintTokenFlow::MINT_TOKEN_BAD_CREDENTIALS, func.get()); EXPECT_CALL(*func.get(), CreateMintTokenFlow(_)).WillOnce(Return(flow)); func->set_login_ui_result(false); std::string error = utils::RunFunctionAndReturnError( func.get(), "[{\"interactive\": true}]", browser()); EXPECT_EQ(std::string(errors::kUserNotSignedIn), error); EXPECT_TRUE(func->login_ui_shown()); EXPECT_FALSE(func->scope_ui_shown()); } IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, InteractiveLoginSuccessNoToken) { scoped_refptr<MockGetAuthTokenFunction> func(new MockGetAuthTokenFunction()); func->set_extension(CreateExtension(CLIENT_ID | SCOPES)); EXPECT_CALL(*func.get(), HasLoginToken()).WillOnce(Return(false)); func->set_login_ui_result(false); std::string error = utils::RunFunctionAndReturnError( func.get(), "[{\"interactive\": true}]", browser()); EXPECT_EQ(std::string(errors::kUserNotSignedIn), error); EXPECT_TRUE(func->login_ui_shown()); EXPECT_FALSE(func->scope_ui_shown()); } IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, InteractiveLoginSuccessMintFailure) { scoped_refptr<MockGetAuthTokenFunction> func(new MockGetAuthTokenFunction()); func->set_extension(CreateExtension(CLIENT_ID | SCOPES)); EXPECT_CALL(*func.get(), HasLoginToken()) .WillOnce(Return(false)); func->set_login_ui_result(true); TestOAuth2MintTokenFlow* flow = new TestOAuth2MintTokenFlow( TestOAuth2MintTokenFlow::MINT_TOKEN_FAILURE, func.get()); EXPECT_CALL(*func.get(), CreateMintTokenFlow(_)).WillOnce(Return(flow)); std::string error = utils::RunFunctionAndReturnError( func.get(), "[{\"interactive\": true}]", browser()); EXPECT_TRUE(StartsWithASCII(error, errors::kAuthFailure, false)); EXPECT_TRUE(func->login_ui_shown()); EXPECT_FALSE(func->scope_ui_shown()); } IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, InteractiveLoginSuccessLoginAccessTokenFailure) { scoped_refptr<MockGetAuthTokenFunction> func(new MockGetAuthTokenFunction()); func->set_extension(CreateExtension(CLIENT_ID | SCOPES)); EXPECT_CALL(*func.get(), HasLoginToken()).WillOnce(Return(false)); func->set_login_ui_result(true); func->set_login_access_token_result(false); std::string error = utils::RunFunctionAndReturnError( func.get(), "[{\"interactive\": true}]", browser()); EXPECT_TRUE(StartsWithASCII(error, errors::kAuthFailure, false)); EXPECT_TRUE(func->login_ui_shown()); EXPECT_FALSE(func->scope_ui_shown()); } IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, InteractiveLoginSuccessMintSuccess) { scoped_refptr<MockGetAuthTokenFunction> func(new MockGetAuthTokenFunction()); func->set_extension(CreateExtension(CLIENT_ID | SCOPES)); EXPECT_CALL(*func.get(), HasLoginToken()) .WillOnce(Return(false)); func->set_login_ui_result(true); TestOAuth2MintTokenFlow* flow = new TestOAuth2MintTokenFlow( TestOAuth2MintTokenFlow::MINT_TOKEN_SUCCESS, func.get()); EXPECT_CALL(*func.get(), CreateMintTokenFlow(_)).WillOnce(Return(flow)); scoped_ptr<base::Value> value(utils::RunFunctionAndReturnSingleResult( func.get(), "[{\"interactive\": true}]", browser())); std::string access_token; EXPECT_TRUE(value->GetAsString(&access_token)); EXPECT_EQ(std::string(kAccessToken), access_token); EXPECT_TRUE(func->login_ui_shown()); EXPECT_FALSE(func->scope_ui_shown()); } IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, InteractiveLoginSuccessApprovalAborted) { scoped_refptr<MockGetAuthTokenFunction> func(new MockGetAuthTokenFunction()); func->set_extension(CreateExtension(CLIENT_ID | SCOPES)); EXPECT_CALL(*func.get(), HasLoginToken()) .WillOnce(Return(false)); func->set_login_ui_result(true); TestOAuth2MintTokenFlow* flow = new TestOAuth2MintTokenFlow( TestOAuth2MintTokenFlow::ISSUE_ADVICE_SUCCESS, func.get()); EXPECT_CALL(*func.get(), CreateMintTokenFlow(_)).WillOnce(Return(flow)); func->set_scope_ui_failure(GaiaWebAuthFlow::WINDOW_CLOSED); std::string error = utils::RunFunctionAndReturnError( func.get(), "[{\"interactive\": true}]", browser()); EXPECT_EQ(std::string(errors::kUserRejected), error); EXPECT_TRUE(func->login_ui_shown()); EXPECT_TRUE(func->scope_ui_shown()); } IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, InteractiveLoginSuccessApprovalSuccess) { scoped_refptr<const Extension> extension(CreateExtension(CLIENT_ID | SCOPES)); scoped_refptr<MockGetAuthTokenFunction> func(new MockGetAuthTokenFunction()); func->set_extension(extension.get()); EXPECT_CALL(*func.get(), HasLoginToken()).WillOnce(Return(false)); func->set_login_ui_result(true); TestOAuth2MintTokenFlow* flow = new TestOAuth2MintTokenFlow( TestOAuth2MintTokenFlow::ISSUE_ADVICE_SUCCESS, func.get()); EXPECT_CALL(*func.get(), CreateMintTokenFlow(_)) .WillOnce(Return(flow)); scoped_ptr<base::Value> value(utils::RunFunctionAndReturnSingleResult( func.get(), "[{\"interactive\": true}]", browser())); std::string access_token; EXPECT_TRUE(value->GetAsString(&access_token)); EXPECT_EQ(std::string(kAccessToken), access_token); EXPECT_TRUE(func->login_ui_shown()); EXPECT_TRUE(func->scope_ui_shown()); } IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, InteractiveApprovalAborted) { scoped_refptr<MockGetAuthTokenFunction> func(new MockGetAuthTokenFunction()); func->set_extension(CreateExtension(CLIENT_ID | SCOPES)); EXPECT_CALL(*func.get(), HasLoginToken()) .WillOnce(Return(true)); TestOAuth2MintTokenFlow* flow = new TestOAuth2MintTokenFlow( TestOAuth2MintTokenFlow::ISSUE_ADVICE_SUCCESS, func.get()); EXPECT_CALL(*func.get(), CreateMintTokenFlow(_)).WillOnce(Return(flow)); func->set_scope_ui_failure(GaiaWebAuthFlow::WINDOW_CLOSED); std::string error = utils::RunFunctionAndReturnError( func.get(), "[{\"interactive\": true}]", browser()); EXPECT_EQ(std::string(errors::kUserRejected), error); EXPECT_FALSE(func->login_ui_shown()); EXPECT_TRUE(func->scope_ui_shown()); } IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, InteractiveApprovalLoadFailed) { scoped_refptr<MockGetAuthTokenFunction> func(new MockGetAuthTokenFunction()); func->set_extension(CreateExtension(CLIENT_ID | SCOPES)); EXPECT_CALL(*func.get(), HasLoginToken()) .WillOnce(Return(true)); TestOAuth2MintTokenFlow* flow = new TestOAuth2MintTokenFlow( TestOAuth2MintTokenFlow::ISSUE_ADVICE_SUCCESS, func.get()); EXPECT_CALL(*func.get(), CreateMintTokenFlow(_)).WillOnce(Return(flow)); func->set_scope_ui_failure(GaiaWebAuthFlow::LOAD_FAILED); std::string error = utils::RunFunctionAndReturnError( func.get(), "[{\"interactive\": true}]", browser()); EXPECT_EQ(std::string(errors::kPageLoadFailure), error); EXPECT_FALSE(func->login_ui_shown()); EXPECT_TRUE(func->scope_ui_shown()); } IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, InteractiveApprovalInvalidRedirect) { scoped_refptr<MockGetAuthTokenFunction> func(new MockGetAuthTokenFunction()); func->set_extension(CreateExtension(CLIENT_ID | SCOPES)); EXPECT_CALL(*func.get(), HasLoginToken()) .WillOnce(Return(true)); TestOAuth2MintTokenFlow* flow = new TestOAuth2MintTokenFlow( TestOAuth2MintTokenFlow::ISSUE_ADVICE_SUCCESS, func.get()); EXPECT_CALL(*func.get(), CreateMintTokenFlow(_)).WillOnce(Return(flow)); func->set_scope_ui_failure(GaiaWebAuthFlow::INVALID_REDIRECT); std::string error = utils::RunFunctionAndReturnError( func.get(), "[{\"interactive\": true}]", browser()); EXPECT_EQ(std::string(errors::kInvalidRedirect), error); EXPECT_FALSE(func->login_ui_shown()); EXPECT_TRUE(func->scope_ui_shown()); } IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, InteractiveApprovalConnectionFailure) { scoped_refptr<MockGetAuthTokenFunction> func(new MockGetAuthTokenFunction()); func->set_extension(CreateExtension(CLIENT_ID | SCOPES)); EXPECT_CALL(*func.get(), HasLoginToken()) .WillOnce(Return(true)); TestOAuth2MintTokenFlow* flow = new TestOAuth2MintTokenFlow( TestOAuth2MintTokenFlow::ISSUE_ADVICE_SUCCESS, func.get()); EXPECT_CALL(*func.get(), CreateMintTokenFlow(_)).WillOnce(Return(flow)); func->set_scope_ui_failure(GaiaWebAuthFlow::SERVICE_AUTH_ERROR); std::string error = utils::RunFunctionAndReturnError( func.get(), "[{\"interactive\": true}]", browser()); EXPECT_TRUE(StartsWithASCII(error, errors::kAuthFailure, false)); EXPECT_FALSE(func->login_ui_shown()); EXPECT_TRUE(func->scope_ui_shown()); } IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, InteractiveApprovalOAuthErrors) { scoped_refptr<const Extension> extension(CreateExtension(CLIENT_ID | SCOPES)); std::map<std::string, std::string> error_map; error_map.insert(std::make_pair("access_denied", errors::kUserRejected)); error_map.insert(std::make_pair("invalid_scope", errors::kInvalidScopes)); error_map.insert(std::make_pair( "unmapped_error", std::string(errors::kAuthFailure) + "unmapped_error")); for (std::map<std::string, std::string>::const_iterator it = error_map.begin(); it != error_map.end(); ++it) { scoped_refptr<MockGetAuthTokenFunction> func( new MockGetAuthTokenFunction()); func->set_extension(extension.get()); EXPECT_CALL(*func.get(), HasLoginToken()).WillOnce(Return(true)); // Make sure we don't get a cached issue_advice result, which would cause // flow to be leaked. id_api()->EraseAllCachedTokens(); TestOAuth2MintTokenFlow* flow = new TestOAuth2MintTokenFlow( TestOAuth2MintTokenFlow::ISSUE_ADVICE_SUCCESS, func.get()); EXPECT_CALL(*func.get(), CreateMintTokenFlow(_)).WillOnce(Return(flow)); func->set_scope_ui_oauth_error(it->first); std::string error = utils::RunFunctionAndReturnError( func.get(), "[{\"interactive\": true}]", browser()); EXPECT_EQ(it->second, error); EXPECT_FALSE(func->login_ui_shown()); EXPECT_TRUE(func->scope_ui_shown()); } } IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, InteractiveApprovalSuccess) { scoped_refptr<const Extension> extension(CreateExtension(CLIENT_ID | SCOPES)); scoped_refptr<MockGetAuthTokenFunction> func(new MockGetAuthTokenFunction()); func->set_extension(extension.get()); EXPECT_CALL(*func.get(), HasLoginToken()).WillOnce(Return(true)); TestOAuth2MintTokenFlow* flow = new TestOAuth2MintTokenFlow( TestOAuth2MintTokenFlow::ISSUE_ADVICE_SUCCESS, func.get()); EXPECT_CALL(*func.get(), CreateMintTokenFlow(_)) .WillOnce(Return(flow)); scoped_ptr<base::Value> value(utils::RunFunctionAndReturnSingleResult( func.get(), "[{\"interactive\": true}]", browser())); std::string access_token; EXPECT_TRUE(value->GetAsString(&access_token)); EXPECT_EQ(std::string(kAccessToken), access_token); EXPECT_FALSE(func->login_ui_shown()); EXPECT_TRUE(func->scope_ui_shown()); EXPECT_EQ(IdentityTokenCacheValue::CACHE_STATUS_TOKEN, GetCachedToken().status()); } IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, NoninteractiveQueue) { scoped_refptr<const Extension> extension(CreateExtension(CLIENT_ID | SCOPES)); scoped_refptr<MockGetAuthTokenFunction> func(new MockGetAuthTokenFunction()); func->set_extension(extension.get()); // Create a fake request to block the queue. MockQueuedMintRequest queued_request; IdentityMintRequestQueue::MintType type = IdentityMintRequestQueue::MINT_TYPE_NONINTERACTIVE; EXPECT_CALL(queued_request, StartMintToken(type)).Times(1); QueueRequestStart(type, &queued_request); // The real request will start processing, but wait in the queue behind // the blocker. EXPECT_CALL(*func.get(), HasLoginToken()).WillOnce(Return(true)); RunFunctionAsync(func.get(), "[{}]"); // Verify that we have fetched the login token at this point. testing::Mock::VerifyAndClearExpectations(func.get()); // The flow will be created after the first queued request clears. TestOAuth2MintTokenFlow* flow = new TestOAuth2MintTokenFlow( TestOAuth2MintTokenFlow::MINT_TOKEN_SUCCESS, func.get()); EXPECT_CALL(*func.get(), CreateMintTokenFlow(_)).WillOnce(Return(flow)); QueueRequestComplete(type, &queued_request); scoped_ptr<base::Value> value(WaitForSingleResult(func.get())); std::string access_token; EXPECT_TRUE(value->GetAsString(&access_token)); EXPECT_EQ(std::string(kAccessToken), access_token); EXPECT_FALSE(func->login_ui_shown()); EXPECT_FALSE(func->scope_ui_shown()); } IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, InteractiveQueue) { scoped_refptr<const Extension> extension(CreateExtension(CLIENT_ID | SCOPES)); scoped_refptr<MockGetAuthTokenFunction> func(new MockGetAuthTokenFunction()); func->set_extension(extension.get()); // Create a fake request to block the queue. MockQueuedMintRequest queued_request; IdentityMintRequestQueue::MintType type = IdentityMintRequestQueue::MINT_TYPE_INTERACTIVE; EXPECT_CALL(queued_request, StartMintToken(type)).Times(1); QueueRequestStart(type, &queued_request); // The real request will start processing, but wait in the queue behind // the blocker. EXPECT_CALL(*func.get(), HasLoginToken()).WillOnce(Return(true)); TestOAuth2MintTokenFlow* flow1 = new TestOAuth2MintTokenFlow( TestOAuth2MintTokenFlow::ISSUE_ADVICE_SUCCESS, func.get()); EXPECT_CALL(*func.get(), CreateMintTokenFlow(_)).WillOnce(Return(flow1)); RunFunctionAsync(func.get(), "[{\"interactive\": true}]"); // Verify that we have fetched the login token and run the first flow. testing::Mock::VerifyAndClearExpectations(func.get()); EXPECT_FALSE(func->scope_ui_shown()); // The UI will be displayed and a token retrieved after the first // queued request clears. QueueRequestComplete(type, &queued_request); scoped_ptr<base::Value> value(WaitForSingleResult(func.get())); std::string access_token; EXPECT_TRUE(value->GetAsString(&access_token)); EXPECT_EQ(std::string(kAccessToken), access_token); EXPECT_FALSE(func->login_ui_shown()); EXPECT_TRUE(func->scope_ui_shown()); } IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, InteractiveQueuedNoninteractiveFails) { scoped_refptr<const Extension> extension(CreateExtension(CLIENT_ID | SCOPES)); scoped_refptr<MockGetAuthTokenFunction> func(new MockGetAuthTokenFunction()); func->set_extension(extension.get()); // Create a fake request to block the interactive queue. MockQueuedMintRequest queued_request; IdentityMintRequestQueue::MintType type = IdentityMintRequestQueue::MINT_TYPE_INTERACTIVE; EXPECT_CALL(queued_request, StartMintToken(type)).Times(1); QueueRequestStart(type, &queued_request); // Non-interactive requests fail without hitting GAIA, because a // consent UI is known to be up. EXPECT_CALL(*func.get(), HasLoginToken()).WillOnce(Return(true)); std::string error = utils::RunFunctionAndReturnError( func.get(), "[{}]", browser()); EXPECT_EQ(std::string(errors::kNoGrant), error); EXPECT_FALSE(func->login_ui_shown()); EXPECT_FALSE(func->scope_ui_shown()); QueueRequestComplete(type, &queued_request); } IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, NonInteractiveCacheHit) { scoped_refptr<const Extension> extension(CreateExtension(CLIENT_ID | SCOPES)); scoped_refptr<MockGetAuthTokenFunction> func(new MockGetAuthTokenFunction()); func->set_extension(extension.get()); // pre-populate the cache with a token IdentityTokenCacheValue token(kAccessToken, base::TimeDelta::FromSeconds(3600)); SetCachedToken(token); // Get a token. Should not require a GAIA request. EXPECT_CALL(*func.get(), HasLoginToken()) .WillOnce(Return(true)); scoped_ptr<base::Value> value(utils::RunFunctionAndReturnSingleResult( func.get(), "[{}]", browser())); std::string access_token; EXPECT_TRUE(value->GetAsString(&access_token)); EXPECT_EQ(std::string(kAccessToken), access_token); EXPECT_FALSE(func->login_ui_shown()); EXPECT_FALSE(func->scope_ui_shown()); } IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, NonInteractiveIssueAdviceCacheHit) { scoped_refptr<const Extension> extension(CreateExtension(CLIENT_ID | SCOPES)); scoped_refptr<MockGetAuthTokenFunction> func(new MockGetAuthTokenFunction()); func->set_extension(extension.get()); // pre-populate the cache with advice IssueAdviceInfo info; IdentityTokenCacheValue token(info); SetCachedToken(token); // Should return an error without a GAIA request. EXPECT_CALL(*func.get(), HasLoginToken()) .WillOnce(Return(true)); std::string error = utils::RunFunctionAndReturnError( func.get(), "[{}]", browser()); EXPECT_EQ(std::string(errors::kNoGrant), error); EXPECT_FALSE(func->login_ui_shown()); EXPECT_FALSE(func->scope_ui_shown()); } IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, InteractiveCacheHit) { scoped_refptr<const Extension> extension(CreateExtension(CLIENT_ID | SCOPES)); scoped_refptr<MockGetAuthTokenFunction> func(new MockGetAuthTokenFunction()); func->set_extension(extension.get()); // Create a fake request to block the queue. MockQueuedMintRequest queued_request; IdentityMintRequestQueue::MintType type = IdentityMintRequestQueue::MINT_TYPE_INTERACTIVE; EXPECT_CALL(queued_request, StartMintToken(type)).Times(1); QueueRequestStart(type, &queued_request); // The real request will start processing, but wait in the queue behind // the blocker. EXPECT_CALL(*func.get(), HasLoginToken()).WillOnce(Return(true)); TestOAuth2MintTokenFlow* flow = new TestOAuth2MintTokenFlow( TestOAuth2MintTokenFlow::ISSUE_ADVICE_SUCCESS, func.get()); EXPECT_CALL(*func.get(), CreateMintTokenFlow(_)).WillOnce(Return(flow)); RunFunctionAsync(func.get(), "[{\"interactive\": true}]"); // Populate the cache with a token while the request is blocked. IdentityTokenCacheValue token(kAccessToken, base::TimeDelta::FromSeconds(3600)); SetCachedToken(token); // When we wake up the request, it returns the cached token without // displaying a UI, or hitting GAIA. QueueRequestComplete(type, &queued_request); scoped_ptr<base::Value> value(WaitForSingleResult(func.get())); std::string access_token; EXPECT_TRUE(value->GetAsString(&access_token)); EXPECT_EQ(std::string(kAccessToken), access_token); EXPECT_FALSE(func->login_ui_shown()); EXPECT_FALSE(func->scope_ui_shown()); } IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, LoginInvalidatesTokenCache) { scoped_refptr<MockGetAuthTokenFunction> func(new MockGetAuthTokenFunction()); scoped_refptr<const Extension> extension(CreateExtension(CLIENT_ID | SCOPES)); func->set_extension(extension.get()); // pre-populate the cache with a token IdentityTokenCacheValue token(kAccessToken, base::TimeDelta::FromSeconds(3600)); SetCachedToken(token); // Because the user is not signed in, the token will be removed, // and we'll hit GAIA for new tokens. EXPECT_CALL(*func.get(), HasLoginToken()) .WillOnce(Return(false)); func->set_login_ui_result(true); TestOAuth2MintTokenFlow* flow = new TestOAuth2MintTokenFlow( TestOAuth2MintTokenFlow::ISSUE_ADVICE_SUCCESS, func.get()); EXPECT_CALL(*func.get(), CreateMintTokenFlow(_)) .WillOnce(Return(flow)); scoped_ptr<base::Value> value(utils::RunFunctionAndReturnSingleResult( func.get(), "[{\"interactive\": true}]", browser())); std::string access_token; EXPECT_TRUE(value->GetAsString(&access_token)); EXPECT_EQ(std::string(kAccessToken), access_token); EXPECT_TRUE(func->login_ui_shown()); EXPECT_TRUE(func->scope_ui_shown()); EXPECT_EQ(IdentityTokenCacheValue::CACHE_STATUS_TOKEN, GetCachedToken().status()); } IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, ComponentWithChromeClientId) { scoped_refptr<MockGetAuthTokenFunction> func(new MockGetAuthTokenFunction()); scoped_refptr<const Extension> extension( CreateExtension(SCOPES | AS_COMPONENT)); func->set_extension(extension.get()); const OAuth2Info& oauth2_info = OAuth2Info::GetOAuth2Info(extension.get()); EXPECT_TRUE(oauth2_info.client_id.empty()); EXPECT_FALSE(func->GetOAuth2ClientId().empty()); EXPECT_NE("client1", func->GetOAuth2ClientId()); } IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, ComponentWithNormalClientId) { scoped_refptr<MockGetAuthTokenFunction> func(new MockGetAuthTokenFunction()); scoped_refptr<const Extension> extension( CreateExtension(CLIENT_ID | SCOPES | AS_COMPONENT)); func->set_extension(extension.get()); EXPECT_EQ("client1", func->GetOAuth2ClientId()); } class RemoveCachedAuthTokenFunctionTest : public ExtensionBrowserTest { protected: bool InvalidateDefaultToken() { scoped_refptr<IdentityRemoveCachedAuthTokenFunction> func( new IdentityRemoveCachedAuthTokenFunction); func->set_extension(utils::CreateEmptyExtension(kExtensionId).get()); return utils::RunFunction( func.get(), std::string("[{\"token\": \"") + kAccessToken + "\"}]", browser(), extension_function_test_utils::NONE); } IdentityAPI* id_api() { return IdentityAPI::GetFactoryInstance()->Get(browser()->profile()); } void SetCachedToken(IdentityTokenCacheValue& token_data) { ExtensionTokenKey key(extensions::id_util::GenerateId(kExtensionId), "test@example.com", std::set<std::string>()); id_api()->SetCachedToken(key, token_data); } const IdentityTokenCacheValue& GetCachedToken() { return id_api()->GetCachedToken( ExtensionTokenKey(extensions::id_util::GenerateId(kExtensionId), "test@example.com", std::set<std::string>())); } }; IN_PROC_BROWSER_TEST_F(RemoveCachedAuthTokenFunctionTest, NotFound) { EXPECT_TRUE(InvalidateDefaultToken()); EXPECT_EQ(IdentityTokenCacheValue::CACHE_STATUS_NOTFOUND, GetCachedToken().status()); } IN_PROC_BROWSER_TEST_F(RemoveCachedAuthTokenFunctionTest, Advice) { IssueAdviceInfo info; IdentityTokenCacheValue advice(info); SetCachedToken(advice); EXPECT_TRUE(InvalidateDefaultToken()); EXPECT_EQ(IdentityTokenCacheValue::CACHE_STATUS_ADVICE, GetCachedToken().status()); } IN_PROC_BROWSER_TEST_F(RemoveCachedAuthTokenFunctionTest, NonMatchingToken) { IdentityTokenCacheValue token("non_matching_token", base::TimeDelta::FromSeconds(3600)); SetCachedToken(token); EXPECT_TRUE(InvalidateDefaultToken()); EXPECT_EQ(IdentityTokenCacheValue::CACHE_STATUS_TOKEN, GetCachedToken().status()); EXPECT_EQ("non_matching_token", GetCachedToken().token()); } IN_PROC_BROWSER_TEST_F(RemoveCachedAuthTokenFunctionTest, MatchingToken) { IdentityTokenCacheValue token(kAccessToken, base::TimeDelta::FromSeconds(3600)); SetCachedToken(token); EXPECT_EQ(IdentityTokenCacheValue::CACHE_STATUS_TOKEN, GetCachedToken().status()); EXPECT_TRUE(InvalidateDefaultToken()); EXPECT_EQ(IdentityTokenCacheValue::CACHE_STATUS_NOTFOUND, GetCachedToken().status()); } class LaunchWebAuthFlowFunctionTest : public AsyncExtensionBrowserTest { public: virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE { // Reduce performance test variance by disabling background networking. command_line->AppendSwitch(switches::kDisableBackgroundNetworking); } }; IN_PROC_BROWSER_TEST_F(LaunchWebAuthFlowFunctionTest, UserCloseWindow) { net::SpawnedTestServer https_server( net::SpawnedTestServer::TYPE_HTTPS, net::SpawnedTestServer::kLocalhost, base::FilePath(FILE_PATH_LITERAL( "chrome/test/data/extensions/api_test/identity"))); ASSERT_TRUE(https_server.Start()); GURL auth_url(https_server.GetURL("files/interaction_required.html")); scoped_refptr<IdentityLaunchWebAuthFlowFunction> function( new IdentityLaunchWebAuthFlowFunction()); scoped_refptr<Extension> empty_extension( utils::CreateEmptyExtension()); function->set_extension(empty_extension.get()); WaitForGURLAndCloseWindow popup_observer(auth_url); std::string args = "[{\"interactive\": true, \"url\": \"" + auth_url.spec() + "\"}]"; RunFunctionAsync(function.get(), args); popup_observer.Wait(); popup_observer.CloseEmbedderWebContents(); EXPECT_EQ(std::string(errors::kUserRejected), WaitForError(function.get())); } IN_PROC_BROWSER_TEST_F(LaunchWebAuthFlowFunctionTest, InteractionRequired) { net::SpawnedTestServer https_server( net::SpawnedTestServer::TYPE_HTTPS, net::SpawnedTestServer::kLocalhost, base::FilePath(FILE_PATH_LITERAL( "chrome/test/data/extensions/api_test/identity"))); ASSERT_TRUE(https_server.Start()); GURL auth_url(https_server.GetURL("files/interaction_required.html")); scoped_refptr<IdentityLaunchWebAuthFlowFunction> function( new IdentityLaunchWebAuthFlowFunction()); scoped_refptr<Extension> empty_extension( utils::CreateEmptyExtension()); function->set_extension(empty_extension.get()); std::string args = "[{\"interactive\": false, \"url\": \"" + auth_url.spec() + "\"}]"; std::string error = utils::RunFunctionAndReturnError(function.get(), args, browser()); EXPECT_EQ(std::string(errors::kInteractionRequired), error); } IN_PROC_BROWSER_TEST_F(LaunchWebAuthFlowFunctionTest, LoadFailed) { net::SpawnedTestServer https_server( net::SpawnedTestServer::TYPE_HTTPS, net::SpawnedTestServer::kLocalhost, base::FilePath(FILE_PATH_LITERAL( "chrome/test/data/extensions/api_test/identity"))); ASSERT_TRUE(https_server.Start()); GURL auth_url(https_server.GetURL("files/five_hundred.html")); scoped_refptr<IdentityLaunchWebAuthFlowFunction> function( new IdentityLaunchWebAuthFlowFunction()); scoped_refptr<Extension> empty_extension( utils::CreateEmptyExtension()); function->set_extension(empty_extension.get()); std::string args = "[{\"interactive\": true, \"url\": \"" + auth_url.spec() + "\"}]"; std::string error = utils::RunFunctionAndReturnError(function.get(), args, browser()); EXPECT_EQ(std::string(errors::kPageLoadFailure), error); } IN_PROC_BROWSER_TEST_F(LaunchWebAuthFlowFunctionTest, NonInteractiveSuccess) { #if defined(OS_WIN) && defined(USE_ASH) // Disable this test in Metro+Ash for now (http://crbug.com/262796). if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests)) return; #endif scoped_refptr<IdentityLaunchWebAuthFlowFunction> function( new IdentityLaunchWebAuthFlowFunction()); scoped_refptr<Extension> empty_extension( utils::CreateEmptyExtension()); function->set_extension(empty_extension.get()); function->InitFinalRedirectURLPrefixForTest("abcdefghij"); scoped_ptr<base::Value> value(utils::RunFunctionAndReturnSingleResult( function.get(), "[{\"interactive\": false," "\"url\": \"https://abcdefghij.chromiumapp.org/callback#test\"}]", browser())); std::string url; EXPECT_TRUE(value->GetAsString(&url)); EXPECT_EQ(std::string("https://abcdefghij.chromiumapp.org/callback#test"), url); } IN_PROC_BROWSER_TEST_F( LaunchWebAuthFlowFunctionTest, InteractiveFirstNavigationSuccess) { #if defined(OS_WIN) && defined(USE_ASH) // Disable this test in Metro+Ash for now (http://crbug.com/262796). if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests)) return; #endif scoped_refptr<IdentityLaunchWebAuthFlowFunction> function( new IdentityLaunchWebAuthFlowFunction()); scoped_refptr<Extension> empty_extension( utils::CreateEmptyExtension()); function->set_extension(empty_extension.get()); function->InitFinalRedirectURLPrefixForTest("abcdefghij"); scoped_ptr<base::Value> value(utils::RunFunctionAndReturnSingleResult( function.get(), "[{\"interactive\": true," "\"url\": \"https://abcdefghij.chromiumapp.org/callback#test\"}]", browser())); std::string url; EXPECT_TRUE(value->GetAsString(&url)); EXPECT_EQ(std::string("https://abcdefghij.chromiumapp.org/callback#test"), url); } IN_PROC_BROWSER_TEST_F( LaunchWebAuthFlowFunctionTest, InteractiveSecondNavigationSuccess) { net::SpawnedTestServer https_server( net::SpawnedTestServer::TYPE_HTTPS, net::SpawnedTestServer::kLocalhost, base::FilePath(FILE_PATH_LITERAL( "chrome/test/data/extensions/api_test/identity"))); ASSERT_TRUE(https_server.Start()); GURL auth_url(https_server.GetURL("files/redirect_to_chromiumapp.html")); scoped_refptr<IdentityLaunchWebAuthFlowFunction> function( new IdentityLaunchWebAuthFlowFunction()); scoped_refptr<Extension> empty_extension( utils::CreateEmptyExtension()); function->set_extension(empty_extension.get()); function->InitFinalRedirectURLPrefixForTest("abcdefghij"); std::string args = "[{\"interactive\": true, \"url\": \"" + auth_url.spec() + "\"}]"; scoped_ptr<base::Value> value( utils::RunFunctionAndReturnSingleResult(function.get(), args, browser())); std::string url; EXPECT_TRUE(value->GetAsString(&url)); EXPECT_EQ(std::string("https://abcdefghij.chromiumapp.org/callback#test"), url); } } // namespace extensions // Tests the chrome.identity API implemented by custom JS bindings . IN_PROC_BROWSER_TEST_F(ExtensionApiTest, ChromeIdentityJsBindings) { ASSERT_TRUE(RunExtensionTest("identity/js_bindings")) << message_; }
bsd-3-clause
kurtrwall/wagtail
wagtail/wagtailimages/tests/test_models.py
17102
from __future__ import absolute_import, unicode_literals import unittest from django.contrib.auth import get_user_model from django.contrib.auth.models import Group, Permission from django.core.files.uploadedfile import SimpleUploadedFile from django.core.urlresolvers import reverse from django.db.utils import IntegrityError from django.test import TestCase from django.test.utils import override_settings from willow.image import Image as WillowImage from wagtail.tests.testapp.models import EventPage, EventPageCarouselItem from wagtail.tests.utils import WagtailTestUtils from wagtail.wagtailcore.models import Collection, GroupCollectionPermission, Page from wagtail.wagtailimages.models import Rendition, SourceImageIOError from wagtail.wagtailimages.rect import Rect from .utils import Image, get_test_image_file class TestImage(TestCase): def setUp(self): # Create an image for running tests on self.image = Image.objects.create( title="Test image", file=get_test_image_file(), ) def test_is_portrait(self): self.assertFalse(self.image.is_portrait()) def test_is_landscape(self): self.assertTrue(self.image.is_landscape()) def test_get_rect(self): self.assertTrue(self.image.get_rect(), Rect(0, 0, 640, 480)) def test_get_focal_point(self): self.assertEqual(self.image.get_focal_point(), None) # Add a focal point to the image self.image.focal_point_x = 100 self.image.focal_point_y = 200 self.image.focal_point_width = 50 self.image.focal_point_height = 20 # Get it self.assertEqual(self.image.get_focal_point(), Rect(75, 190, 125, 210)) def test_has_focal_point(self): self.assertFalse(self.image.has_focal_point()) # Add a focal point to the image self.image.focal_point_x = 100 self.image.focal_point_y = 200 self.image.focal_point_width = 50 self.image.focal_point_height = 20 self.assertTrue(self.image.has_focal_point()) def test_set_focal_point(self): self.assertEqual(self.image.focal_point_x, None) self.assertEqual(self.image.focal_point_y, None) self.assertEqual(self.image.focal_point_width, None) self.assertEqual(self.image.focal_point_height, None) self.image.set_focal_point(Rect(100, 150, 200, 350)) self.assertEqual(self.image.focal_point_x, 150) self.assertEqual(self.image.focal_point_y, 250) self.assertEqual(self.image.focal_point_width, 100) self.assertEqual(self.image.focal_point_height, 200) self.image.set_focal_point(None) self.assertEqual(self.image.focal_point_x, None) self.assertEqual(self.image.focal_point_y, None) self.assertEqual(self.image.focal_point_width, None) self.assertEqual(self.image.focal_point_height, None) def test_is_stored_locally(self): self.assertTrue(self.image.is_stored_locally()) @override_settings(DEFAULT_FILE_STORAGE='wagtail.tests.dummy_external_storage.DummyExternalStorage') def test_is_stored_locally_with_external_storage(self): self.assertFalse(self.image.is_stored_locally()) class TestImageQuerySet(TestCase): def test_search_method(self): # Create an image for running tests on image = Image.objects.create( title="Test image", file=get_test_image_file(), ) # Search for it results = Image.objects.search("Test") self.assertEqual(list(results), [image]) def test_operators(self): aaa_image = Image.objects.create( title="AAA Test image", file=get_test_image_file(), ) zzz_image = Image.objects.create( title="ZZZ Test image", file=get_test_image_file(), ) results = Image.objects.search("aaa test", operator='and') self.assertEqual(list(results), [aaa_image]) results = Image.objects.search("aaa test", operator='or') sorted_results = sorted(results, key=lambda img: img.title) self.assertEqual(sorted_results, [aaa_image, zzz_image]) def test_custom_ordering(self): aaa_image = Image.objects.create( title="AAA Test image", file=get_test_image_file(), ) zzz_image = Image.objects.create( title="ZZZ Test image", file=get_test_image_file(), ) results = Image.objects.order_by('title').search("Test") self.assertEqual(list(results), [aaa_image, zzz_image]) results = Image.objects.order_by('-title').search("Test") self.assertEqual(list(results), [zzz_image, aaa_image]) def test_search_indexing_prefetches_tags(self): for i in range(0, 10): image = Image.objects.create( title="Test image %d" % i, file=get_test_image_file(), ) image.tags.add('aardvark', 'artichoke', 'armadillo') with self.assertNumQueries(2): results = { image.title: [tag.name for tag in image.tags.all()] for image in Image.get_indexed_objects() } self.assertTrue('aardvark' in results['Test image 0']) class TestImagePermissions(TestCase): def setUp(self): # Create some user accounts for testing permissions User = get_user_model() self.user = User.objects.create_user(username='user', email='user@email.com', password='password') self.owner = User.objects.create_user(username='owner', email='owner@email.com', password='password') self.editor = User.objects.create_user(username='editor', email='editor@email.com', password='password') self.editor.groups.add(Group.objects.get(name='Editors')) self.administrator = User.objects.create_superuser( username='administrator', email='administrator@email.com', password='password' ) # Owner user must have the add_image permission image_adders_group = Group.objects.create(name="Image adders") GroupCollectionPermission.objects.create( group=image_adders_group, collection=Collection.get_first_root_node(), permission=Permission.objects.get(codename='add_image'), ) self.owner.groups.add(image_adders_group) # Create an image for running tests on self.image = Image.objects.create( title="Test image", uploaded_by_user=self.owner, file=get_test_image_file(), ) def test_administrator_can_edit(self): self.assertTrue(self.image.is_editable_by_user(self.administrator)) def test_editor_can_edit(self): self.assertTrue(self.image.is_editable_by_user(self.editor)) def test_owner_can_edit(self): self.assertTrue(self.image.is_editable_by_user(self.owner)) def test_user_cant_edit(self): self.assertFalse(self.image.is_editable_by_user(self.user)) class TestRenditions(TestCase): def setUp(self): # Create an image for running tests on self.image = Image.objects.create( title="Test image", file=get_test_image_file(), ) def test_get_rendition_model(self): self.assertIs(Image.get_rendition_model(), Rendition) def test_minification(self): rendition = self.image.get_rendition('width-400') # Check size self.assertEqual(rendition.width, 400) self.assertEqual(rendition.height, 300) def test_resize_to_max(self): rendition = self.image.get_rendition('max-100x100') # Check size self.assertEqual(rendition.width, 100) self.assertEqual(rendition.height, 75) def test_resize_to_min(self): rendition = self.image.get_rendition('min-120x120') # Check size self.assertEqual(rendition.width, 160) self.assertEqual(rendition.height, 120) def test_resize_to_original(self): rendition = self.image.get_rendition('original') # Check size self.assertEqual(rendition.width, 640) self.assertEqual(rendition.height, 480) def test_cache(self): # Get two renditions with the same filter first_rendition = self.image.get_rendition('width-400') second_rendition = self.image.get_rendition('width-400') # Check that they are the same object self.assertEqual(first_rendition, second_rendition) def test_alt_attribute(self): rendition = self.image.get_rendition('width-400') self.assertEqual(rendition.alt, "Test image") class TestUsageCount(TestCase): fixtures = ['test.json'] def setUp(self): self.image = Image.objects.create( title="Test image", file=get_test_image_file(), ) @override_settings(WAGTAIL_USAGE_COUNT_ENABLED=True) def test_unused_image_usage_count(self): self.assertEqual(self.image.get_usage().count(), 0) @override_settings(WAGTAIL_USAGE_COUNT_ENABLED=True) def test_used_image_document_usage_count(self): page = EventPage.objects.get(id=4) event_page_carousel_item = EventPageCarouselItem() event_page_carousel_item.page = page event_page_carousel_item.image = self.image event_page_carousel_item.save() self.assertEqual(self.image.get_usage().count(), 1) class TestGetUsage(TestCase): fixtures = ['test.json'] def setUp(self): self.image = Image.objects.create( title="Test image", file=get_test_image_file(), ) def test_image_get_usage_not_enabled(self): self.assertEqual(list(self.image.get_usage()), []) @override_settings(WAGTAIL_USAGE_COUNT_ENABLED=True) def test_unused_image_get_usage(self): self.assertEqual(list(self.image.get_usage()), []) @override_settings(WAGTAIL_USAGE_COUNT_ENABLED=True) def test_used_image_document_get_usage(self): page = EventPage.objects.get(id=4) event_page_carousel_item = EventPageCarouselItem() event_page_carousel_item.page = page event_page_carousel_item.image = self.image event_page_carousel_item.save() self.assertTrue(issubclass(Page, type(self.image.get_usage()[0]))) class TestGetWillowImage(TestCase): fixtures = ['test.json'] def setUp(self): self.image = Image.objects.create( title="Test image", file=get_test_image_file(), ) def test_willow_image_object_returned(self): with self.image.get_willow_image() as willow_image: self.assertIsInstance(willow_image, WillowImage) def test_with_missing_image(self): # Image id=1 in test fixtures has a missing image file bad_image = Image.objects.get(id=1) # Attempting to get the Willow image for images without files # should raise a SourceImageIOError with self.assertRaises(SourceImageIOError): with bad_image.get_willow_image(): self.fail() # Shouldn't get here def test_closes_image(self): # This tests that willow closes images after use with self.image.get_willow_image(): self.assertFalse(self.image.file.closed) self.assertTrue(self.image.file.closed) def test_closes_image_on_exception(self): # This tests that willow closes images when the with is exited with an exception try: with self.image.get_willow_image(): self.assertFalse(self.image.file.closed) raise ValueError("Something went wrong!") except ValueError: pass self.assertTrue(self.image.file.closed) def test_doesnt_close_open_image(self): # This tests that when the image file is already open, get_willow_image doesn't close it (#1256) self.image.file.open('rb') with self.image.get_willow_image(): pass self.assertFalse(self.image.file.closed) self.image.file.close() class TestIssue573(TestCase): """ This tests for a bug which causes filename limit on Renditions to be reached when the Image has a long original filename and a big focal point key """ def test_issue_573(self): # Create an image with a big filename and focal point image = Image.objects.create( title="Test image", file=get_test_image_file( 'thisisaverylongfilename-abcdefghijklmnopqrstuvwxyz-supercalifragilisticexpialidocious.png' ), focal_point_x=1000, focal_point_y=1000, focal_point_width=1000, focal_point_height=1000, ) # Try creating a rendition from that image # This would crash if the bug is present image.get_rendition('fill-800x600') @override_settings(_WAGTAILSEARCH_FORCE_AUTO_UPDATE=['elasticsearch']) class TestIssue613(TestCase, WagtailTestUtils): def get_elasticsearch_backend(self): from django.conf import settings from wagtail.wagtailsearch.backends import get_search_backend backend_path = 'wagtail.wagtailsearch.backends.elasticsearch' # Search WAGTAILSEARCH_BACKENDS for an entry that uses the given backend path for backend_name, backend_conf in settings.WAGTAILSEARCH_BACKENDS.items(): if backend_conf['BACKEND'] == backend_path: return get_search_backend(backend_name) else: # no conf entry found - skip tests for this backend raise unittest.SkipTest("No WAGTAILSEARCH_BACKENDS entry for the backend %s" % backend_path) def setUp(self): self.search_backend = self.get_elasticsearch_backend() self.login() def add_image(self, **params): post_data = { 'title': "Test image", 'file': SimpleUploadedFile('test.png', get_test_image_file().file.getvalue()), } post_data.update(params) response = self.client.post(reverse('wagtailimages:add'), post_data) # Should redirect back to index self.assertRedirects(response, reverse('wagtailimages:index')) # Check that the image was created images = Image.objects.filter(title="Test image") self.assertEqual(images.count(), 1) # Test that size was populated correctly image = images.first() self.assertEqual(image.width, 640) self.assertEqual(image.height, 480) return image def edit_image(self, **params): # Create an image to edit self.image = Image.objects.create( title="Test image", file=get_test_image_file(), ) # Edit it post_data = { 'title': "Edited", } post_data.update(params) response = self.client.post(reverse('wagtailimages:edit', args=(self.image.id,)), post_data) # Should redirect back to index self.assertRedirects(response, reverse('wagtailimages:index')) # Check that the image was edited image = Image.objects.get(id=self.image.id) self.assertEqual(image.title, "Edited") return image def test_issue_613_on_add(self): # Reset the search index self.search_backend.reset_index() self.search_backend.add_type(Image) # Add an image with some tags image = self.add_image(tags="hello") self.search_backend.refresh_index() # Search for it by tag results = self.search_backend.search("hello", Image) # Check self.assertEqual(len(results), 1) self.assertEqual(results[0].id, image.id) def test_issue_613_on_edit(self): # Reset the search index self.search_backend.reset_index() self.search_backend.add_type(Image) # Add an image with some tags image = self.edit_image(tags="hello") self.search_backend.refresh_index() # Search for it by tag results = self.search_backend.search("hello", Image) # Check self.assertEqual(len(results), 1) self.assertEqual(results[0].id, image.id) class TestIssue312(TestCase): def test_duplicate_renditions(self): # Create an image image = Image.objects.create( title="Test image", file=get_test_image_file(), ) # Get two renditions and check that they're the same rend1 = image.get_rendition('fill-100x100') rend2 = image.get_rendition('fill-100x100') self.assertEqual(rend1, rend2) # Now manually duplicate the renditon and check that the database blocks it self.assertRaises( IntegrityError, Rendition.objects.create, image=rend1.image, filter=rend1.filter, width=rend1.width, height=rend1.height, focal_point_key=rend1.focal_point_key, )
bsd-3-clause
scheib/chromium
chrome/browser/share/android/javatests/src/org/chromium/chrome/browser/share/long_screenshots/LongScreenshotsMediatorTest.java
3293
// Copyright 2021 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. package org.chromium.chrome.browser.share.long_screenshots; import android.app.Activity; import android.graphics.Bitmap; import android.os.Looper; import android.view.View; import androidx.test.filters.MediumTest; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.chromium.base.FeatureList; import org.chromium.base.test.util.CommandLineFlags; import org.chromium.chrome.R; import org.chromium.chrome.browser.flags.ChromeFeatureList; import org.chromium.chrome.browser.flags.ChromeSwitches; import org.chromium.chrome.browser.share.long_screenshots.bitmap_generation.EntryManager; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; import org.chromium.chrome.test.util.browser.Features; import org.chromium.ui.test.util.DummyUiActivity; import org.chromium.ui.test.util.ThemedDummyUiActivityTestRule; /** Tests for the LongScreenshotsMediator. */ @RunWith(ChromeJUnit4ClassRunner.class) @Features.EnableFeatures(ChromeFeatureList.CHROME_SHARE_LONG_SCREENSHOT) @CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE}) public class LongScreenshotsMediatorTest { private Activity mActivity; private Bitmap mBitmap; private FeatureList.TestValues mTestValues; private LongScreenshotsMediator mMediator; @Rule public ThemedDummyUiActivityTestRule<DummyUiActivity> mActivityTestRule = new ThemedDummyUiActivityTestRule<>( DummyUiActivity.class, R.style.ColorOverlay_ChromiumAndroid); @Mock private View mView; @Mock private EntryManager mManager; @Before public void setUp() { Looper.prepare(); mActivityTestRule.launchActivity(null); mActivity = mActivityTestRule.getActivity(); MockitoAnnotations.initMocks(this); mBitmap = Bitmap.createBitmap(800, 600, Bitmap.Config.ARGB_8888); mTestValues = new FeatureList.TestValues(); mTestValues.addFieldTrialParamOverride( ChromeFeatureList.CHROME_SHARE_LONG_SCREENSHOT, "autoscroll", "0"); FeatureList.setTestValues(mTestValues); // Instantiate the object under test. mMediator = new LongScreenshotsMediator(mActivity, mManager); } @Test @MediumTest public void testShowAreaSelectionDone() { mMediator.showAreaSelectionDialog(mBitmap); Assert.assertTrue(mMediator.getDialog().isShowing()); } @Test @MediumTest public void testAreaSelectionDone() { mMediator.showAreaSelectionDialog(mBitmap); Assert.assertTrue(mMediator.getDialog().isShowing()); mMediator.areaSelectionDone(mView); Assert.assertFalse(mMediator.getDialog().isShowing()); } @Test @MediumTest public void testAreaSelectionClose() { mMediator.showAreaSelectionDialog(mBitmap); Assert.assertTrue(mMediator.getDialog().isShowing()); mMediator.areaSelectionClose(mView); Assert.assertFalse(mMediator.getDialog().isShowing()); } }
bsd-3-clause
patrickm/chromium.src
content/renderer/media/crypto/pepper_cdm_wrapper_impl.cc
2718
// 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. #if defined(ENABLE_PEPPER_CDMS) #include "content/renderer/media/crypto/pepper_cdm_wrapper_impl.h" #include "content/renderer/pepper/pepper_plugin_instance_impl.h" #include "content/renderer/pepper/pepper_webplugin_impl.h" #include "third_party/WebKit/public/platform/WebString.h" #include "third_party/WebKit/public/web/WebDocument.h" #include "third_party/WebKit/public/web/WebFrame.h" #include "third_party/WebKit/public/web/WebHelperPlugin.h" #include "third_party/WebKit/public/web/WebPlugin.h" #include "third_party/WebKit/public/web/WebView.h" namespace content { void WebHelperPluginDeleter::operator()(blink::WebHelperPlugin* plugin) const { plugin->destroy(); } scoped_ptr<PepperCdmWrapper> PepperCdmWrapperImpl::Create( blink::WebFrame* frame, const std::string& pluginType) { // TODO(jrummell): Convert to DCHECK(frame) once Blink starts passing the // WebFrame to WebContentDecryptionModuleImpl. if (!frame) return scoped_ptr<PepperCdmWrapper>(); ScopedHelperPlugin helper_plugin(blink::WebHelperPlugin::create( blink::WebString::fromUTF8(pluginType), frame)); if (!helper_plugin) return scoped_ptr<PepperCdmWrapper>(); blink::WebPlugin* plugin = helper_plugin->getPlugin(); DCHECK(!plugin->isPlaceholder()); // Prevented by Blink. // Only Pepper plugins are supported, so it must ultimately be a ppapi object. PepperWebPluginImpl* ppapi_plugin = static_cast<PepperWebPluginImpl*>(plugin); scoped_refptr<PepperPluginInstanceImpl> plugin_instance = ppapi_plugin->instance(); if (!plugin_instance) return scoped_ptr<PepperCdmWrapper>(); if (!plugin_instance->GetContentDecryptorDelegate()) return scoped_ptr<PepperCdmWrapper>(); return scoped_ptr<PepperCdmWrapper>( new PepperCdmWrapperImpl(helper_plugin.Pass(), plugin_instance)); } PepperCdmWrapperImpl::PepperCdmWrapperImpl( ScopedHelperPlugin helper_plugin, const scoped_refptr<PepperPluginInstanceImpl>& plugin_instance) : helper_plugin_(helper_plugin.Pass()), plugin_instance_(plugin_instance) { DCHECK(helper_plugin_); DCHECK(plugin_instance_); // Plugin must be a CDM. DCHECK(plugin_instance_->GetContentDecryptorDelegate()); } PepperCdmWrapperImpl::~PepperCdmWrapperImpl() { // Destroy the nested objects in reverse order. plugin_instance_ = NULL; helper_plugin_.reset(); } ContentDecryptorDelegate* PepperCdmWrapperImpl::GetCdmDelegate() { return plugin_instance_->GetContentDecryptorDelegate(); } } // namespace content #endif // defined(ENABLE_PEPPER_CDMS)
bsd-3-clause
Grrompf/Nakade
module/User/src/User/Entity/UserModel.php
9494
<?php namespace User\Entity; use Doctrine\ORM\Mapping as ORM; use Permission\Entity\RoleInterface; //todo: anpassung datenbank unique /** * @ORM\MappedSuperclass */ class UserModel implements RoleInterface { /** * Primary Identifier * * @ORM\Id * @ORM\Column(name="uid", type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * @ORM\Column(name="titel", length=10, type="string") */ protected $title; /** * @ORM\Column(name="vorname", length=20, type="string", nullable=false) */ protected $firstName; /** * @ORM\Column(name="nachname", length=30, type="string", nullable=false) */ protected $lastName; /** * @ORM\Column(name="nick", length=20, unique=true, type="string") */ protected $nickname; /** * @ORM\Column(name="sex", type="string") */ protected $sex; /** * @ORM\Column(name="geburtsdatum", type="date") */ protected $birthday; /** * @ORM\Column(name="anonym", type="boolean") */ protected $anonymous=0; /** * @ORM\Column(name="username", length=50, unique=true, type="string", nullable=false) */ protected $username; /** * @ORM\Column(name="password", length=80, type="string", nullable=false) */ protected $password; /** * @ORM\Column(name="kgs", length=50, unique=true, type="string") */ protected $kgs; /** * @ORM\Column(name="email", length=120, unique=true, type="string", nullable=false) */ protected $email; /** * @ORM\Column(name="verifyString", length=32, type="string") */ protected $verifyString; /** * @ORM\Column(name="verified", type="boolean") */ protected $verified=0; /** * @ORM\Column(name="active", type="boolean") */ protected $active=1; /** * @ORM\Column(name="pwdChange", type="datetime") */ protected $pwdChange; /** * @ORM\Column(name="edit", type="datetime") */ protected $edit; /** * @ORM\Column(name="lastLogin", type="datetime") */ protected $lastLogin; /** * @ORM\Column(name="firstLogin", type="datetime") */ protected $firstLogin; /** * @ORM\Column(name="created", type="datetime") */ protected $created; /** * @ORM\Column(name="due", type="datetime") */ protected $due; /** * @ORM\Column(name="role", length=15, type="string") */ protected $role=RoleInterface::ROLE_GUEST; /** * @ORM\Column(name="language", type="string") */ protected $language; /** * @param int $uid * * @return User */ public function setId($uid) { $this->id = $uid; return $this; } /** * @return int */ public function getId() { return $this->id; } /** * @param string $title * * @return User */ public function setTitle($title) { $this->title = $title; return $this; } /** * @return string */ public function getTitle() { return $this->title; } /** * @param string $firstName * * @return User */ public function setFirstName($firstName) { $this->firstName = $firstName; return $this; } /** * @return string */ public function getFirstName() { return $this->firstName; } /** * @param string $lastName * * @return User */ public function setLastName($lastName) { $this->lastName = $lastName; return $this; } /** * @return string */ public function getLastName() { return $this->lastName; } /** * @param string $nickname * * @return User */ public function setNickname($nickname) { $this->nickname = $nickname; return $this; } /** * @return string */ public function getNickname() { return $this->nickname; } /** * @param string $name * * @return User */ public function setUsername($name) { $this->username = $name; return $this; } /** * @return string */ public function getUsername() { return $this->username; } /** * @param string $password * * @return user */ public function setPassword($password) { $this->password = $password; return $this; } /** * @return string */ public function getPassword() { return $this->password; } /** * @param string $name * * @return User */ public function setKgs($name) { $this->kgs = $name; return $this; } /** * @return string */ public function getKgs() { return $this->kgs; } /** * @param string $email * * @return user */ public function setEmail($email) { $this->email = $email; return $this; } /** * @return string */ public function getEmail() { return $this->email; } /** * @param string $sex * * @return User */ public function setSex($sex) { $this->sex = $sex; return $this; } /** * @return string */ public function getSex() { return $this->sex; } /** * @param \DateTime $datetime * * @return User */ public function setBirthday($datetime) { $this->birthday = $datetime; return $this; } /** * @return \DateTime */ public function getBirthday() { return $this->birthday; } /** * @param bool $isAnonymous * * @return User */ public function setAnonymous($isAnonymous) { $this->anonymous = $isAnonymous; return $this; } /** * @return bool */ public function isAnonymous() { return $this->anonymous; } /** * @param string $verify * * @return user */ public function setVerifyString($verify) { $this->verifyString = $verify; return $this; } /** * @return string */ public function getVerifyString() { return $this->verifyString; } /** * @param \DateTime $datetime * * @return user */ public function setCreated($datetime) { $this->created = $datetime; return $this; } /** * @return \DateTime */ public function getCreated() { return $this->created; } /** * @param \DateTime $datetime * * @return user */ public function setEdit($datetime) { $this->edit = $datetime; return $this; } /** * @return \DateTime */ public function getEdit() { return $this->edit; } /** * @param \DateTime $datetime * * @return user */ public function setPwdChange($datetime) { $this->pwdChange = $datetime; return $this; } /** * @return \DateTime */ public function getPwdChange() { return $this->pwdChange; } /** * @param string $role * * @return user */ public function setRole($role) { $this->role = $role; return $this; } /** * @return string */ public function getRole() { return $this->role; } /** * @param \DateTime $datetime * * @return user */ public function setDue($datetime) { $this->due = $datetime; return $this; } /** * @return \DateTime */ public function getDue() { return $this->due; } /** * @param \DateTime $datetime * * @return user */ public function setLastLogin($datetime) { $this->lastLogin = $datetime; return $this; } /** * @return \DateTime */ public function getLastLogin() { return $this->lastLogin; } /** * @param \DateTime $datetime * * @return user */ public function setFirstLogin($datetime) { $this->firstLogin = $datetime; return $this; } /** * @return \DateTime */ public function getFirstLogin() { return $this->firstLogin; } /** * @param bool $active * * @return user */ public function setActive($active) { $this->active = $active; return $this; } /** * @return bool */ public function isActive() { return $this->active; } /** * @param bool $verified * * @return user */ public function setVerified($verified) { $this->verified = $verified; return $this; } /** * @return bool */ public function isVerified() { return $this->verified; } /** * @param string $language */ public function setLanguage($language) { $this->language = $language; } /** * @return string */ public function getLanguage() { return $this->language; } }
bsd-3-clause
neurokernel/sensory_int
examples/data/gen_vis_input.py
1225
#!/usr/bin/env python """ Generate sample vision model stimulus. """ import numpy as np import h5py n_col = 32 n_row = 24 dt = 1e-4 a = np.zeros(14000, np.float64) a[2000:8000] = 0.016 a[8500:13500] = 0.016 S = np.zeros((n_row, n_col, 14000), np.float64) x = np.arange(n_col)*1.5 y = np.arange(n_row)*np.sqrt(3) div = 0 signv = 1 dih = 0 signh = 1 for i in xrange(14000): div = div -0.1 if div < 0: div = x[-1] signv = 1 - signv dih = dih - 0.1 if dih < 0: dih = y[-1] signh = 1 - signh if a[i] != 0: if i<= 8000: if signv: c = 1 - np.asarray(x > div, np.double) else: c = np.asarray(x > div, np.double) I = np.tile(c, [n_row, 1]) else: if signh: c = np.reshape(1 - np.asarray(y > dih, np.double), [n_row, 1]) else: c = np.reshape(np.asarray(y > dih, np.double), [n_row, 1]) I = np.tile(c, [1, n_col]) b = I*a[i] S[:, :, i] = b A = S.reshape((n_row*n_col, 14000)) A = np.tile(A, [6, 1]).T with h5py.File('vision_input.h5', 'w') as f: f.create_dataset('array', A.shape, dtype=A.dtype, data=A)
bsd-3-clause
nwjs/chromium.src
content/browser/devtools/site_per_process_devtools_browsertest.cc
11063
// Copyright (c) 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/run_loop.h" #include "build/build_config.h" #include "content/browser/devtools/render_frame_devtools_agent_host.h" #include "content/browser/renderer_host/frame_tree.h" #include "content/browser/site_per_process_browsertest.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/devtools_agent_host.h" #include "content/public/browser/download_manager.h" #include "content/public/test/browser_test.h" #include "content/public/test/content_browser_test_utils.h" #include "content/public/test/test_utils.h" #include "content/shell/browser/shell.h" #include "content/shell/browser/shell_download_manager_delegate.h" #include "content/test/content_browser_test_utils_internal.h" #include "content/test/render_document_feature.h" #include "net/dns/mock_host_resolver.h" namespace content { class SitePerProcessDevToolsBrowserTest : public SitePerProcessBrowserTest { public: SitePerProcessDevToolsBrowserTest() {} void SetUpOnMainThread() override { host_resolver()->AddRule("*", "127.0.0.1"); SitePerProcessBrowserTest::SetUpOnMainThread(); } }; class TestClient: public DevToolsAgentHostClient { public: TestClient() : closed_(false), waiting_for_reply_(false) {} ~TestClient() override {} bool closed() { return closed_; } void DispatchProtocolMessage(DevToolsAgentHost* agent_host, base::span<const uint8_t> message) override { if (waiting_for_reply_) { waiting_for_reply_ = false; base::RunLoop::QuitCurrentDeprecated(); } } void AgentHostClosed(DevToolsAgentHost* agent_host) override { closed_ = true; } void WaitForReply() { waiting_for_reply_ = true; base::RunLoop().Run(); } private: bool closed_; bool waiting_for_reply_; }; // Fails on Android, http://crbug.com/464993. #if defined(OS_ANDROID) #define MAYBE_CrossSiteIframeAgentHost DISABLED_CrossSiteIframeAgentHost #else #define MAYBE_CrossSiteIframeAgentHost CrossSiteIframeAgentHost #endif IN_PROC_BROWSER_TEST_P(SitePerProcessDevToolsBrowserTest, MAYBE_CrossSiteIframeAgentHost) { DevToolsAgentHost::List list; GURL main_url(embedded_test_server()->GetURL("/site_per_process_main.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) ->GetPrimaryFrameTree() .root(); list = DevToolsAgentHost::GetOrCreateAll(); EXPECT_EQ(1U, list.size()); EXPECT_EQ(DevToolsAgentHost::kTypePage, list[0]->GetType()); EXPECT_EQ(main_url.spec(), list[0]->GetURL().spec()); // Load same-site page into iframe. FrameTreeNode* child = root->child_at(0); GURL http_url(embedded_test_server()->GetURL("/title1.html")); EXPECT_TRUE(NavigateToURLFromRenderer(child, http_url)); list = DevToolsAgentHost::GetOrCreateAll(); EXPECT_EQ(1U, list.size()); EXPECT_EQ(DevToolsAgentHost::kTypePage, list[0]->GetType()); EXPECT_EQ(main_url.spec(), list[0]->GetURL().spec()); // Load cross-site page into iframe. GURL::Replacements replace_host; GURL cross_site_url(embedded_test_server()->GetURL("/title2.html")); replace_host.SetHostStr("foo.com"); cross_site_url = cross_site_url.ReplaceComponents(replace_host); EXPECT_TRUE(NavigateToURLFromRenderer(root->child_at(0), cross_site_url)); list = DevToolsAgentHost::GetOrCreateAll(); EXPECT_EQ(2U, list.size()); EXPECT_EQ(DevToolsAgentHost::kTypePage, list[0]->GetType()); EXPECT_EQ(main_url.spec(), list[0]->GetURL().spec()); EXPECT_EQ(DevToolsAgentHost::kTypeFrame, list[1]->GetType()); EXPECT_EQ(cross_site_url.spec(), list[1]->GetURL().spec()); EXPECT_EQ(std::string(), list[0]->GetParentId()); EXPECT_EQ(list[0]->GetId(), list[1]->GetParentId()); EXPECT_NE(list[1]->GetId(), list[0]->GetId()); // Attaching to both agent hosts. scoped_refptr<DevToolsAgentHost> child_host = list[1]; TestClient child_client; child_host->AttachClient(&child_client); scoped_refptr<DevToolsAgentHost> parent_host = list[0]; TestClient parent_client; parent_host->AttachClient(&parent_client); // Send message to parent and child frames and get result back. constexpr char kMsg[] = R"({"id":0,"method":"incorrect.method"})"; auto message = base::as_bytes(base::make_span(kMsg, strlen(kMsg))); child_host->DispatchProtocolMessage(&child_client, message); child_client.WaitForReply(); parent_host->DispatchProtocolMessage(&parent_client, message); parent_client.WaitForReply(); // Load back same-site page into iframe. EXPECT_TRUE(NavigateToURLFromRenderer(root->child_at(0), http_url)); list = DevToolsAgentHost::GetOrCreateAll(); EXPECT_EQ(1U, list.size()); EXPECT_EQ(DevToolsAgentHost::kTypePage, list[0]->GetType()); EXPECT_EQ(main_url.spec(), list[0]->GetURL().spec()); EXPECT_TRUE(child_client.closed()); child_host->DetachClient(&child_client); child_host = nullptr; EXPECT_FALSE(parent_client.closed()); parent_host->DetachClient(&parent_client); parent_host = nullptr; } IN_PROC_BROWSER_TEST_P(SitePerProcessDevToolsBrowserTest, AgentHostForFrames) { GURL main_url(embedded_test_server()->GetURL("/site_per_process_main.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); scoped_refptr<DevToolsAgentHost> page_agent = DevToolsAgentHost::GetOrCreateFor(shell()->web_contents()); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) ->GetPrimaryFrameTree() .root(); scoped_refptr<DevToolsAgentHost> main_frame_agent = RenderFrameDevToolsAgentHost::GetOrCreateFor(root); EXPECT_EQ(page_agent.get(), main_frame_agent.get()); // Load same-site page into iframe. FrameTreeNode* child = root->child_at(0); GURL http_url(embedded_test_server()->GetURL("/title1.html")); EXPECT_TRUE(NavigateToURLFromRenderer(child, http_url)); scoped_refptr<DevToolsAgentHost> child_frame_agent = RenderFrameDevToolsAgentHost::GetOrCreateFor(child); EXPECT_EQ(page_agent.get(), child_frame_agent.get()); // Load cross-site page into iframe. GURL::Replacements replace_host; GURL cross_site_url(embedded_test_server()->GetURL("/title2.html")); replace_host.SetHostStr("foo.com"); cross_site_url = cross_site_url.ReplaceComponents(replace_host); EXPECT_TRUE(NavigateToURLFromRenderer(root->child_at(0), cross_site_url)); child_frame_agent = RenderFrameDevToolsAgentHost::GetOrCreateFor(child); EXPECT_NE(page_agent.get(), child_frame_agent.get()); EXPECT_EQ(child_frame_agent->GetParentId(), page_agent->GetId()); EXPECT_NE(child_frame_agent->GetId(), page_agent->GetId()); } IN_PROC_BROWSER_TEST_P(SitePerProcessDevToolsBrowserTest, AgentHostForPageEqualsOneForMainFrame) { GURL main_url(embedded_test_server()->GetURL("/site_per_process_main.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) ->GetPrimaryFrameTree() .root(); FrameTreeNode* child = root->child_at(0); // Load cross-site page into iframe. GURL::Replacements replace_host; GURL cross_site_url(embedded_test_server()->GetURL("/title2.html")); replace_host.SetHostStr("foo.com"); cross_site_url = cross_site_url.ReplaceComponents(replace_host); EXPECT_TRUE(NavigateToURLFromRenderer(child, cross_site_url)); // First ask for child frame, then for main frame. scoped_refptr<DevToolsAgentHost> child_frame_agent = RenderFrameDevToolsAgentHost::GetOrCreateFor(child); scoped_refptr<DevToolsAgentHost> main_frame_agent = RenderFrameDevToolsAgentHost::GetOrCreateFor(root); EXPECT_NE(main_frame_agent.get(), child_frame_agent.get()); EXPECT_EQ(child_frame_agent->GetParentId(), main_frame_agent->GetId()); EXPECT_NE(child_frame_agent->GetId(), main_frame_agent->GetId()); // Agent for web contents should be the the main frame's one. scoped_refptr<DevToolsAgentHost> page_agent = DevToolsAgentHost::GetOrCreateFor(shell()->web_contents()); EXPECT_EQ(page_agent.get(), main_frame_agent.get()); } class SitePerProcessDownloadDevToolsBrowserTest : public SitePerProcessBrowserTest { public: SitePerProcessDownloadDevToolsBrowserTest() {} void SetUpOnMainThread() override { SitePerProcessBrowserTest::SetUpOnMainThread(); ASSERT_TRUE(downloads_directory_.CreateUniqueTempDir()); DownloadManager* download_manager = shell()->web_contents()->GetBrowserContext()->GetDownloadManager(); ShellDownloadManagerDelegate* download_delegate = static_cast<ShellDownloadManagerDelegate*>( download_manager->GetDelegate()); download_delegate->SetDownloadBehaviorForTesting( downloads_directory_.GetPath()); } base::ScopedTempDir downloads_directory_; }; IN_PROC_BROWSER_TEST_P(SitePerProcessDownloadDevToolsBrowserTest, NotCommittedNavigationDoesNotBlockAgent) { ASSERT_TRUE( NavigateToURL(shell(), embedded_test_server()->GetURL("/title1.html"))); scoped_refptr<DevToolsAgentHost> agent = DevToolsAgentHost::GetOrCreateFor(shell()->web_contents()); TestClient client; agent->AttachClient(&client); constexpr char kMsg[] = R"({"id":0,"method":"incorrect.method"})"; auto message = base::as_bytes(base::make_span(kMsg, strlen(kMsg))); // Check that client is responsive. agent->DispatchProtocolMessage(&client, message); client.WaitForReply(); // Do cross process navigation that ends up being download, which will be // not committed navigation in that web contents/render frame. GURL::Replacements replace_host; GURL cross_site_url(embedded_test_server()->GetURL("/download/empty.bin")); replace_host.SetHostStr("foo.com"); cross_site_url = cross_site_url.ReplaceComponents(replace_host); ASSERT_TRUE(NavigateToURLAndExpectNoCommit(shell(), cross_site_url)); // Check that client is still responding after not committed navigation // is finished. agent->DispatchProtocolMessage(&client, message); client.WaitForReply(); ASSERT_TRUE(agent->DetachClient(&client)); } INSTANTIATE_TEST_SUITE_P(All, SitePerProcessDevToolsBrowserTest, testing::ValuesIn(RenderDocumentFeatureLevelValues())); INSTANTIATE_TEST_SUITE_P(All, SitePerProcessDownloadDevToolsBrowserTest, testing::ValuesIn(RenderDocumentFeatureLevelValues())); } // namespace content
bsd-3-clause
Safihre/cherrypy
cherrypy/test/helper.py
16369
"""A library of helper functions for the CherryPy test suite.""" import datetime import io import logging import os import re import subprocess import sys import time import unittest import warnings import contextlib import portend import pytest from cheroot.test import webtest import cherrypy from cherrypy._cpcompat import text_or_bytes, HTTPSConnection, ntob from cherrypy.lib import httputil from cherrypy.lib import gctools log = logging.getLogger(__name__) thisdir = os.path.abspath(os.path.dirname(__file__)) serverpem = os.path.join(os.getcwd(), thisdir, 'test.pem') class Supervisor(object): """Base class for modeling and controlling servers during testing.""" def __init__(self, **kwargs): for k, v in kwargs.items(): if k == 'port': setattr(self, k, int(v)) setattr(self, k, v) def log_to_stderr(msg, level): return sys.stderr.write(msg + os.linesep) class LocalSupervisor(Supervisor): """Base class for modeling/controlling servers which run in the same process. When the server side runs in a different process, start/stop can dump all state between each test module easily. When the server side runs in the same process as the client, however, we have to do a bit more work to ensure config and mounted apps are reset between tests. """ using_apache = False using_wsgi = False def __init__(self, **kwargs): for k, v in kwargs.items(): setattr(self, k, v) cherrypy.server.httpserver = self.httpserver_class # This is perhaps the wrong place for this call but this is the only # place that i've found so far that I KNOW is early enough to set this. cherrypy.config.update({'log.screen': False}) engine = cherrypy.engine if hasattr(engine, 'signal_handler'): engine.signal_handler.subscribe() if hasattr(engine, 'console_control_handler'): engine.console_control_handler.subscribe() def start(self, modulename=None): """Load and start the HTTP server.""" if modulename: # Unhook httpserver so cherrypy.server.start() creates a new # one (with config from setup_server, if declared). cherrypy.server.httpserver = None cherrypy.engine.start() self.sync_apps() def sync_apps(self): """Tell the server about any apps which the setup functions mounted.""" pass def stop(self): td = getattr(self, 'teardown', None) if td: td() cherrypy.engine.exit() for name, server in getattr(cherrypy, 'servers', {}).copy().items(): server.unsubscribe() del cherrypy.servers[name] class NativeServerSupervisor(LocalSupervisor): """Server supervisor for the builtin HTTP server.""" httpserver_class = 'cherrypy._cpnative_server.CPHTTPServer' using_apache = False using_wsgi = False def __str__(self): return 'Builtin HTTP Server on %s:%s' % (self.host, self.port) class LocalWSGISupervisor(LocalSupervisor): """Server supervisor for the builtin WSGI server.""" httpserver_class = 'cherrypy._cpwsgi_server.CPWSGIServer' using_apache = False using_wsgi = True def __str__(self): return 'Builtin WSGI Server on %s:%s' % (self.host, self.port) def sync_apps(self): """Hook a new WSGI app into the origin server.""" cherrypy.server.httpserver.wsgi_app = self.get_app() def get_app(self, app=None): """Obtain a new (decorated) WSGI app to hook into the origin server.""" if app is None: app = cherrypy.tree if self.validate: try: from wsgiref import validate except ImportError: warnings.warn( 'Error importing wsgiref. The validator will not run.') else: # wraps the app in the validator app = validate.validator(app) return app def get_cpmodpy_supervisor(**options): from cherrypy.test import modpy sup = modpy.ModPythonSupervisor(**options) sup.template = modpy.conf_cpmodpy return sup def get_modpygw_supervisor(**options): from cherrypy.test import modpy sup = modpy.ModPythonSupervisor(**options) sup.template = modpy.conf_modpython_gateway sup.using_wsgi = True return sup def get_modwsgi_supervisor(**options): from cherrypy.test import modwsgi return modwsgi.ModWSGISupervisor(**options) def get_modfcgid_supervisor(**options): from cherrypy.test import modfcgid return modfcgid.ModFCGISupervisor(**options) def get_modfastcgi_supervisor(**options): from cherrypy.test import modfastcgi return modfastcgi.ModFCGISupervisor(**options) def get_wsgi_u_supervisor(**options): cherrypy.server.wsgi_version = ('u', 0) return LocalWSGISupervisor(**options) class CPWebCase(webtest.WebCase): script_name = '' scheme = 'http' available_servers = {'wsgi': LocalWSGISupervisor, 'wsgi_u': get_wsgi_u_supervisor, 'native': NativeServerSupervisor, 'cpmodpy': get_cpmodpy_supervisor, 'modpygw': get_modpygw_supervisor, 'modwsgi': get_modwsgi_supervisor, 'modfcgid': get_modfcgid_supervisor, 'modfastcgi': get_modfastcgi_supervisor, } default_server = 'wsgi' @classmethod def _setup_server(cls, supervisor, conf): v = sys.version.split()[0] log.info('Python version used to run this test script: %s' % v) log.info('CherryPy version: %s' % cherrypy.__version__) if supervisor.scheme == 'https': ssl = ' (ssl)' else: ssl = '' log.info('HTTP server version: %s%s' % (supervisor.protocol, ssl)) log.info('PID: %s' % os.getpid()) cherrypy.server.using_apache = supervisor.using_apache cherrypy.server.using_wsgi = supervisor.using_wsgi if sys.platform[:4] == 'java': cherrypy.config.update({'server.nodelay': False}) if isinstance(conf, text_or_bytes): parser = cherrypy.lib.reprconf.Parser() conf = parser.dict_from_file(conf).get('global', {}) else: conf = conf or {} baseconf = conf.copy() baseconf.update({'server.socket_host': supervisor.host, 'server.socket_port': supervisor.port, 'server.protocol_version': supervisor.protocol, 'environment': 'test_suite', }) if supervisor.scheme == 'https': # baseconf['server.ssl_module'] = 'builtin' baseconf['server.ssl_certificate'] = serverpem baseconf['server.ssl_private_key'] = serverpem # helper must be imported lazily so the coverage tool # can run against module-level statements within cherrypy. # Also, we have to do "from cherrypy.test import helper", # exactly like each test module does, because a relative import # would stick a second instance of webtest in sys.modules, # and we wouldn't be able to globally override the port anymore. if supervisor.scheme == 'https': webtest.WebCase.HTTP_CONN = HTTPSConnection return baseconf @classmethod def setup_class(cls): '' # Creates a server conf = { 'scheme': 'http', 'protocol': 'HTTP/1.1', 'port': 54583, 'host': '127.0.0.1', 'validate': False, 'server': 'wsgi', } supervisor_factory = cls.available_servers.get( conf.get('server', 'wsgi')) if supervisor_factory is None: raise RuntimeError('Unknown server in config: %s' % conf['server']) supervisor = supervisor_factory(**conf) # Copied from "run_test_suite" cherrypy.config.reset() baseconf = cls._setup_server(supervisor, conf) cherrypy.config.update(baseconf) setup_client() if hasattr(cls, 'setup_server'): # Clear the cherrypy tree and clear the wsgi server so that # it can be updated with the new root cherrypy.tree = cherrypy._cptree.Tree() cherrypy.server.httpserver = None cls.setup_server() # Add a resource for verifying there are no refleaks # to *every* test class. cherrypy.tree.mount(gctools.GCRoot(), '/gc') cls.do_gc_test = True supervisor.start(cls.__module__) cls.supervisor = supervisor @classmethod def teardown_class(cls): '' if hasattr(cls, 'setup_server'): cls.supervisor.stop() do_gc_test = False def test_gc(self): if not self.do_gc_test: return self.getPage('/gc/stats') try: self.assertBody('Statistics:') except Exception: 'Failures occur intermittently. See #1420' def prefix(self): return self.script_name.rstrip('/') def base(self): if ((self.scheme == 'http' and self.PORT == 80) or (self.scheme == 'https' and self.PORT == 443)): port = '' else: port = ':%s' % self.PORT return '%s://%s%s%s' % (self.scheme, self.HOST, port, self.script_name.rstrip('/')) def exit(self): sys.exit() def getPage(self, url, *args, **kwargs): """Open the url. """ if self.script_name: url = httputil.urljoin(self.script_name, url) return webtest.WebCase.getPage(self, url, *args, **kwargs) def skip(self, msg='skipped '): pytest.skip(msg) def assertErrorPage(self, status, message=None, pattern=''): """Compare the response body with a built in error page. The function will optionally look for the regexp pattern, within the exception embedded in the error page.""" # This will never contain a traceback page = cherrypy._cperror.get_error_page(status, message=message) # First, test the response body without checking the traceback. # Stick a match-all group (.*) in to grab the traceback. def esc(text): return re.escape(ntob(text)) epage = re.escape(page) epage = epage.replace( esc('<pre id="traceback"></pre>'), esc('<pre id="traceback">') + b'(.*)' + esc('</pre>')) m = re.match(epage, self.body, re.DOTALL) if not m: self._handlewebError( 'Error page does not match; expected:\n' + page) return # Now test the pattern against the traceback if pattern is None: # Special-case None to mean that there should be *no* traceback. if m and m.group(1): self._handlewebError('Error page contains traceback') else: if (m is None) or ( not re.search(ntob(re.escape(pattern), self.encoding), m.group(1))): msg = 'Error page does not contain %s in traceback' self._handlewebError(msg % repr(pattern)) date_tolerance = 2 def assertEqualDates(self, dt1, dt2, seconds=None): """Assert abs(dt1 - dt2) is within Y seconds.""" if seconds is None: seconds = self.date_tolerance if dt1 > dt2: diff = dt1 - dt2 else: diff = dt2 - dt1 if not diff < datetime.timedelta(seconds=seconds): raise AssertionError('%r and %r are not within %r seconds.' % (dt1, dt2, seconds)) def _test_method_sorter(_, x, y): """Monkeypatch the test sorter to always run test_gc last in each suite.""" if x == 'test_gc': return 1 if y == 'test_gc': return -1 if x > y: return 1 if x < y: return -1 return 0 unittest.TestLoader.sortTestMethodsUsing = _test_method_sorter def setup_client(): """Set up the WebCase classes to match the server's socket settings.""" webtest.WebCase.PORT = cherrypy.server.socket_port webtest.WebCase.HOST = cherrypy.server.socket_host if cherrypy.server.ssl_certificate: CPWebCase.scheme = 'https' # --------------------------- Spawning helpers --------------------------- # class CPProcess(object): pid_file = os.path.join(thisdir, 'test.pid') config_file = os.path.join(thisdir, 'test.conf') config_template = """[global] server.socket_host: '%(host)s' server.socket_port: %(port)s checker.on: False log.screen: False log.error_file: r'%(error_log)s' log.access_file: r'%(access_log)s' %(ssl)s %(extra)s """ error_log = os.path.join(thisdir, 'test.error.log') access_log = os.path.join(thisdir, 'test.access.log') def __init__(self, wait=False, daemonize=False, ssl=False, socket_host=None, socket_port=None): self.wait = wait self.daemonize = daemonize self.ssl = ssl self.host = socket_host or cherrypy.server.socket_host self.port = socket_port or cherrypy.server.socket_port def write_conf(self, extra=''): if self.ssl: serverpem = os.path.join(thisdir, 'test.pem') ssl = """ server.ssl_certificate: r'%s' server.ssl_private_key: r'%s' """ % (serverpem, serverpem) else: ssl = '' conf = self.config_template % { 'host': self.host, 'port': self.port, 'error_log': self.error_log, 'access_log': self.access_log, 'ssl': ssl, 'extra': extra, } with io.open(self.config_file, 'w', encoding='utf-8') as f: f.write(str(conf)) def start(self, imports=None): """Start cherryd in a subprocess.""" portend.free(self.host, self.port, timeout=1) args = [ '-m', 'cherrypy', '-c', self.config_file, '-p', self.pid_file, ] r""" Command for running cherryd server with autoreload enabled Using ``` ['-c', "__requires__ = 'CherryPy'; \ import pkg_resources, re, sys; \ sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]); \ sys.exit(\ pkg_resources.load_entry_point(\ 'CherryPy', 'console_scripts', 'cherryd')())"] ``` doesn't work as it's impossible to reconstruct the `-c`'s contents. Ref: https://github.com/cherrypy/cherrypy/issues/1545 """ if not isinstance(imports, (list, tuple)): imports = [imports] for i in imports: if i: args.append('-i') args.append(i) if self.daemonize: args.append('-d') env = os.environ.copy() # Make sure we import the cherrypy package in which this module is # defined. grandparentdir = os.path.abspath(os.path.join(thisdir, '..', '..')) if env.get('PYTHONPATH', ''): env['PYTHONPATH'] = os.pathsep.join( (grandparentdir, env['PYTHONPATH'])) else: env['PYTHONPATH'] = grandparentdir self._proc = subprocess.Popen([sys.executable] + args, env=env) if self.wait: self.exit_code = self._proc.wait() else: portend.occupied(self.host, self.port, timeout=5) # Give the engine a wee bit more time to finish STARTING if self.daemonize: time.sleep(2) else: time.sleep(1) def get_pid(self): if self.daemonize: return int(open(self.pid_file, 'rb').read()) return self._proc.pid def join(self): """Wait for the process to exit.""" if self.daemonize: return self._join_daemon() self._proc.wait() def _join_daemon(self): with contextlib.suppress(IOError): os.waitpid(self.get_pid(), 0)
bsd-3-clause
zserg84/tender
modules/themes/messages/ru/themes-admin.php
1775
<?php /** * Message translations. * * This file is automatically generated by 'yii message' command. * It contains the localizable messages extracted from source code. * You may modify this file by translating the extracted messages. * * Each array element represents the translation (value) of a message (key). * If the value is empty, the message is considered as not translated. * Messages that no longer need translation will have their translations * enclosed between a pair of '@@' marks. * * Message string can be used with plural forms format. Check i18n section * of the guide for details. * * NOTE: this file must be saved in UTF-8 encoding. */ return [ 'Access control' => 'Управление доступом', 'Blogs' => 'Блоги', 'Comments' => 'Комментарии', 'Dashboard' => 'Панель управления', 'Hello, {name}' => 'Здравствуйте, {name}', 'Home' => 'Главная', 'Member since' => 'Зарегестрирован с', 'Models management' => 'Управления моделями', 'Online' => 'Онлайн', 'Permissions' => 'Права', 'Profile' => 'Профиль', 'Roles' => 'Роли', 'Rules' => 'Правила', 'Sign out' => 'Выход', 'Toggle navigation' => 'Показать/Скрыть меню', 'Users' => 'Пользователи', 'Feedback' => 'Feedback', 'Faq' => 'FAQ', 'Static Pages' => 'Статичные страницы', 'Lang' => 'Языки', 'Translations' => 'Переводы', 'GO_TO_SITE' => 'Перейти на сайт', 'Geo' => 'География', 'GeoCountry' => 'Страны', 'GeoRegion' => 'Регионы', 'GeoCity' => 'Города', ];
bsd-3-clause
evert/sabre-dav
tests/Sabre/HTTP/ResponseMock.php
436
<?php namespace Sabre\HTTP; /** * HTTP Response Mock object * * This class exists to make the transition to sabre/http easier. * * @copyright Copyright (C) 2007-2014 fruux GmbH. All rights reserved. * @author Evert Pot (http://evertpot.com/) * @license http://sabre.io/license/ Modified BSD License */ class ResponseMock extends Response { /** * Making these public. */ public $body; public $status; }
bsd-3-clause
wakatime/wakatime
wakatime/packages/py27/pygments/styles/stata_light.py
1274
# -*- coding: utf-8 -*- """ pygments.styles.stata_light ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Light Style inspired by Stata's do-file editor. Note this is not meant to be a complete style, just for Stata's file formats. :copyright: Copyright 2006-2019 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from pygments.style import Style from pygments.token import Keyword, Name, Comment, String, Error, \ Number, Operator, Whitespace, Text class StataLightStyle(Style): """ Light mode style inspired by Stata's do-file editor. This is not meant to be a complete style, just for use with Stata. """ default_style = '' styles = { Text: '#111111', Whitespace: '#bbbbbb', Error: 'bg:#e3d2d2 #a61717', String: '#7a2424', Number: '#2c2cff', Operator: '', Name.Function: '#2c2cff', Name.Other: '#be646c', Keyword: 'bold #353580', Keyword.Constant: '', Comment: 'italic #008800', Name.Variable: 'bold #35baba', Name.Variable.Global: 'bold #b5565e', }
bsd-3-clause
endlessm/chromium-browser
chrome/service/cloud_print/print_system.cc
1085
// Copyright (c) 2010 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 "chrome/service/cloud_print/print_system.h" #include "base/guid.h" #include "build/build_config.h" namespace cloud_print { PrintJobDetails::PrintJobDetails() : status(PRINT_JOB_STATUS_INVALID), platform_status_flags(0), total_pages(0), pages_printed(0) { } void PrintJobDetails::Clear() { status = PRINT_JOB_STATUS_INVALID; platform_status_flags = 0; status_message.clear(); total_pages = 0; pages_printed = 0; } PrintSystem::PrintServerWatcher::~PrintServerWatcher() {} PrintSystem::PrinterWatcher::~PrinterWatcher() {} PrintSystem::JobSpooler::~JobSpooler() {} PrintSystem::~PrintSystem() {} std::string PrintSystem::GenerateProxyId() { return base::GenerateGUID(); } #if defined(OS_LINUX) && !defined(USE_CUPS) scoped_refptr<PrintSystem> PrintSystem::CreateInstance( const base::DictionaryValue*) { return nullptr; } #endif } // namespace cloud_print
bsd-3-clause
forcedotcom/rmux
log/log_prod.go
1625
// +build !dev /* * Copyright (c) 2015, Salesforce.com, 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 Salesforce.com 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 HOLDER 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 log func init() { SetLogLevel(LOG_INFO) }
bsd-3-clause
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE36_Absolute_Path_Traversal/s01/CWE36_Absolute_Path_Traversal__char_console_w32CreateFile_68a.cpp
3611
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE36_Absolute_Path_Traversal__char_console_w32CreateFile_68a.cpp Label Definition File: CWE36_Absolute_Path_Traversal.label.xml Template File: sources-sink-68a.tmpl.cpp */ /* * @description * CWE: 36 Absolute Path Traversal * BadSource: console Read input from the console * GoodSource: Full path and file name * Sink: w32CreateFile * BadSink : Open the file named in data using CreateFile() * Flow Variant: 68 Data flow: data passed as a global variable from one function to another in different source files * * */ #include "std_testcase.h" #ifndef _WIN32 #include <wchar.h> #endif #include <windows.h> char * CWE36_Absolute_Path_Traversal__char_console_w32CreateFile_68_badData; char * CWE36_Absolute_Path_Traversal__char_console_w32CreateFile_68_goodG2BData; namespace CWE36_Absolute_Path_Traversal__char_console_w32CreateFile_68 { #ifndef OMITBAD /* bad function declaration */ void badSink(); void bad() { char * data; char dataBuffer[FILENAME_MAX] = ""; data = dataBuffer; { /* Read input from the console */ size_t dataLen = strlen(data); /* if there is room in data, read into it from the console */ if (FILENAME_MAX-dataLen > 1) { /* POTENTIAL FLAW: Read data from the console */ if (fgets(data+dataLen, (int)(FILENAME_MAX-dataLen), stdin) != NULL) { /* The next few lines remove the carriage return from the string that is * inserted by fgets() */ dataLen = strlen(data); if (dataLen > 0 && data[dataLen-1] == '\n') { data[dataLen-1] = '\0'; } } else { printLine("fgets() failed"); /* Restore NUL terminator if fgets fails */ data[dataLen] = '\0'; } } } CWE36_Absolute_Path_Traversal__char_console_w32CreateFile_68_badData = data; badSink(); } #endif /* OMITBAD */ #ifndef OMITGOOD /* good function declarations */ void goodG2BSink(); /* goodG2B uses the GoodSource with the BadSink */ static void goodG2B() { char * data; char dataBuffer[FILENAME_MAX] = ""; data = dataBuffer; #ifdef _WIN32 /* FIX: Use a fixed, full path and file name */ strcat(data, "c:\\temp\\file.txt"); #else /* FIX: Use a fixed, full path and file name */ strcat(data, "/tmp/file.txt"); #endif CWE36_Absolute_Path_Traversal__char_console_w32CreateFile_68_goodG2BData = data; goodG2BSink(); } void good() { goodG2B(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE36_Absolute_Path_Traversal__char_console_w32CreateFile_68; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
bsd-3-clause
rlutes/volttron-applications
kisensum/Simulation/SimulationDriverAgent/simulation_driver/driver_locks.py
4007
# -*- coding: utf-8 -*- {{{ # vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et: # Copyright (c) 2017, SLAC National Laboratory / Kisensum 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: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # 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. # # The views and conclusions contained in the software and documentation # are those of the authors and should not be interpreted as representing # official policies, either expressed or implied, of the FreeBSD # Project. # # This material was prepared as an account of work sponsored by an # agency of the United States Government. Neither the United States # Government nor the United States Department of Energy, nor SLAC / Kisensum, # nor any of their employees, nor any jurisdiction or organization that # has cooperated in the development of these materials, makes any # warranty, express or implied, or assumes any legal liability or # responsibility for the accuracy, completeness, or usefulness or any # information, apparatus, product, software, or process disclosed, or # represents that its use would not infringe privately owned rights. # # Reference herein to any specific commercial product, process, or # service by trade name, trademark, manufacturer, or otherwise does not # necessarily constitute or imply its endorsement, recommendation, or # favoring by the United States Government or any agency thereof, or # SLAC / Kisensum. The views and opinions of authors # expressed herein do not necessarily state or reflect those of the # United States Government or any agency thereof. # # }}} from gevent.lock import BoundedSemaphore, DummySemaphore from contextlib import contextmanager _socket_lock = None def configure_socket_lock(max_connections=0): global _socket_lock if _socket_lock is not None: raise RuntimeError("socket_lock already configured!") if max_connections < 1: _socket_lock = DummySemaphore() else: _socket_lock = BoundedSemaphore(max_connections) @contextmanager def socket_lock(): global _socket_lock if _socket_lock is None: raise RuntimeError("socket_lock not configured!") _socket_lock.acquire() try: yield finally: _socket_lock.release() _publish_lock = None def configure_publish_lock(max_connections=0): global _publish_lock if _publish_lock is not None: raise RuntimeError("publish_lock already configured!") if max_connections < 1: _publish_lock = DummySemaphore() else: _publish_lock = BoundedSemaphore(max_connections) @contextmanager def publish_lock(): global _publish_lock if _publish_lock is None: raise RuntimeError("publish_lock not configured!") _publish_lock.acquire() try: yield finally: _publish_lock.release()
bsd-3-clause
ngs-doo/dsl-client-java
core/src/test/java-generated/com/dslplatform/client/json/DecimalWithScaleOf9/NullableListOfNullableDecimalsWithScaleOf9DefaultValueTurtle.java
5080
package com.dslplatform.client.json.DecimalWithScaleOf9; import com.dslplatform.client.JsonSerialization; import com.dslplatform.patterns.Bytes; import java.io.IOException; public class NullableListOfNullableDecimalsWithScaleOf9DefaultValueTurtle { private static JsonSerialization jsonSerialization; @org.junit.BeforeClass public static void initializeJsonSerialization() throws IOException { jsonSerialization = com.dslplatform.client.StaticJson.getSerialization(); } @org.junit.Test public void testDefaultValueEquality() throws IOException { final java.util.List<java.math.BigDecimal> defaultValue = null; final Bytes defaultValueJsonSerialized = jsonSerialization.serialize(defaultValue); final java.util.List<java.math.BigDecimal> defaultValueJsonDeserialized = jsonSerialization.deserializeList(java.math.BigDecimal.class, defaultValueJsonSerialized.content, defaultValueJsonSerialized.length); com.dslplatform.ocd.javaasserts.DecimalWithScaleOf9Asserts.assertNullableListOfNullableEquals(defaultValue, defaultValueJsonDeserialized); } @org.junit.Test public void testBorderValue1Equality() throws IOException { final java.util.List<java.math.BigDecimal> borderValue1 = new java.util.ArrayList<java.math.BigDecimal>(java.util.Arrays.asList((java.math.BigDecimal) null)); final Bytes borderValue1JsonSerialized = jsonSerialization.serialize(borderValue1); final java.util.List<java.math.BigDecimal> borderValue1JsonDeserialized = jsonSerialization.deserializeList(java.math.BigDecimal.class, borderValue1JsonSerialized.content, borderValue1JsonSerialized.length); com.dslplatform.ocd.javaasserts.DecimalWithScaleOf9Asserts.assertNullableListOfNullableEquals(borderValue1, borderValue1JsonDeserialized); } @org.junit.Test public void testBorderValue2Equality() throws IOException { final java.util.List<java.math.BigDecimal> borderValue2 = new java.util.ArrayList<java.math.BigDecimal>(java.util.Arrays.asList(java.math.BigDecimal.ZERO.setScale(9))); final Bytes borderValue2JsonSerialized = jsonSerialization.serialize(borderValue2); final java.util.List<java.math.BigDecimal> borderValue2JsonDeserialized = jsonSerialization.deserializeList(java.math.BigDecimal.class, borderValue2JsonSerialized.content, borderValue2JsonSerialized.length); com.dslplatform.ocd.javaasserts.DecimalWithScaleOf9Asserts.assertNullableListOfNullableEquals(borderValue2, borderValue2JsonDeserialized); } @org.junit.Test public void testBorderValue3Equality() throws IOException { final java.util.List<java.math.BigDecimal> borderValue3 = new java.util.ArrayList<java.math.BigDecimal>(java.util.Arrays.asList(new java.math.BigDecimal("1E19"))); final Bytes borderValue3JsonSerialized = jsonSerialization.serialize(borderValue3); final java.util.List<java.math.BigDecimal> borderValue3JsonDeserialized = jsonSerialization.deserializeList(java.math.BigDecimal.class, borderValue3JsonSerialized.content, borderValue3JsonSerialized.length); com.dslplatform.ocd.javaasserts.DecimalWithScaleOf9Asserts.assertNullableListOfNullableEquals(borderValue3, borderValue3JsonDeserialized); } @org.junit.Test public void testBorderValue4Equality() throws IOException { final java.util.List<java.math.BigDecimal> borderValue4 = new java.util.ArrayList<java.math.BigDecimal>(java.util.Arrays.asList(java.math.BigDecimal.ZERO.setScale(9), java.math.BigDecimal.ONE, new java.math.BigDecimal("3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679").setScale(9, java.math.BigDecimal.ROUND_HALF_UP), new java.math.BigDecimal("-1E-9"), new java.math.BigDecimal("1E19"))); final Bytes borderValue4JsonSerialized = jsonSerialization.serialize(borderValue4); final java.util.List<java.math.BigDecimal> borderValue4JsonDeserialized = jsonSerialization.deserializeList(java.math.BigDecimal.class, borderValue4JsonSerialized.content, borderValue4JsonSerialized.length); com.dslplatform.ocd.javaasserts.DecimalWithScaleOf9Asserts.assertNullableListOfNullableEquals(borderValue4, borderValue4JsonDeserialized); } @org.junit.Test public void testBorderValue5Equality() throws IOException { final java.util.List<java.math.BigDecimal> borderValue5 = new java.util.ArrayList<java.math.BigDecimal>(java.util.Arrays.asList((java.math.BigDecimal) null, java.math.BigDecimal.ZERO.setScale(9), java.math.BigDecimal.ONE, new java.math.BigDecimal("3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679").setScale(9, java.math.BigDecimal.ROUND_HALF_UP), new java.math.BigDecimal("-1E-9"), new java.math.BigDecimal("1E19"))); final Bytes borderValue5JsonSerialized = jsonSerialization.serialize(borderValue5); final java.util.List<java.math.BigDecimal> borderValue5JsonDeserialized = jsonSerialization.deserializeList(java.math.BigDecimal.class, borderValue5JsonSerialized.content, borderValue5JsonSerialized.length); com.dslplatform.ocd.javaasserts.DecimalWithScaleOf9Asserts.assertNullableListOfNullableEquals(borderValue5, borderValue5JsonDeserialized); } }
bsd-3-clause
wdv4758h/ZipPy
edu.uci.python.benchmark/src/benchmarks/regexdna.py
1100
# The Computer Language Benchmarks Game # http://shootout.alioth.debian.org/ # contributed by Dominique Wahli # modified by Justin Peel from sys import stdin from re import sub, finditer def main(): seq = stdin.read() ilen = len(seq) seq = sub('>.*\n|\n', '', seq) clen = len(seq) variants = ( 'agggtaaa|tttaccct', '[cgt]gggtaaa|tttaccc[acg]', 'a[act]ggtaaa|tttacc[agt]t', 'ag[act]gtaaa|tttac[agt]ct', 'agg[act]taaa|ttta[agt]cct', 'aggg[acg]aaa|ttt[cgt]ccct', 'agggt[cgt]aa|tt[acg]accct', 'agggta[cgt]a|t[acg]taccct', 'agggtaa[cgt]|[acg]ttaccct') for f in variants: print f, sum(1 for i in finditer(f, seq)) subst = { 'B' : '(c|g|t)', 'D' : '(a|g|t)', 'H' : '(a|c|t)', 'K' : '(g|t)', 'M' : '(a|c)', 'N' : '(a|c|g|t)', 'R' : '(a|g)', 'S' : '(c|g)', 'V' : '(a|c|g)', 'W' : '(a|t)', 'Y' : '(c|t)'} for f, r in subst.items(): seq = sub(f, r, seq) print print ilen print clen print len(seq) main()
bsd-3-clause
meego-tablet-ux/meego-app-browser
chrome/test/test_browser_window.cc
1914
// 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 "chrome/test/test_browser_window.h" #include "ui/gfx/rect.h" TestBrowserWindow::TestBrowserWindow(Browser* browser) {} TestBrowserWindow::~TestBrowserWindow() {} bool TestBrowserWindow::IsActive() const { return false; } gfx::NativeWindow TestBrowserWindow::GetNativeHandle() { return NULL; } BrowserWindowTesting* TestBrowserWindow::GetBrowserWindowTesting() { return NULL; } StatusBubble* TestBrowserWindow::GetStatusBubble() { return NULL; } gfx::Rect TestBrowserWindow::GetRestoredBounds() const { return gfx::Rect(); } gfx::Rect TestBrowserWindow::GetBounds() const { return gfx::Rect(); } bool TestBrowserWindow::IsMaximized() const { return false; } bool TestBrowserWindow::IsFullscreen() const { return false; } bool TestBrowserWindow::IsFullscreenBubbleVisible() const { return false; } LocationBar* TestBrowserWindow::GetLocationBar() const { return const_cast<TestLocationBar*>(&location_bar_); } bool TestBrowserWindow::PreHandleKeyboardEvent( const NativeWebKeyboardEvent& event, bool* is_keyboard_shortcut) { return false; } bool TestBrowserWindow::IsBookmarkBarVisible() const { return false; } bool TestBrowserWindow::IsBookmarkBarAnimating() const { return false; } bool TestBrowserWindow::IsTabStripEditable() const { return false; } bool TestBrowserWindow::IsToolbarVisible() const { return false; } void TestBrowserWindow::ShowAboutChromeDialog() { return; } bool TestBrowserWindow::IsDownloadShelfVisible() const { return false; } DownloadShelf* TestBrowserWindow::GetDownloadShelf() { return NULL; } int TestBrowserWindow::GetExtraRenderViewHeight() const { return 0; } gfx::Rect TestBrowserWindow::GetInstantBounds() { return gfx::Rect(); }
bsd-3-clause
yungyuc/solvcon
libmarch/include/march/core/string.hpp
1983
#pragma once /* * Copyright (c) 2018, Yung-Yu Chen <yyc@solvcon.net> * BSD 3-Clause License, see COPYING */ /** * \file * String helpers. */ #include <cstdio> #include <sstream> #include <iostream> #include <iomanip> #include <string> #include <cxxabi.h> namespace march { namespace string { // FIXME: va_list format string checking template<typename ... Args> std::string format(const std::string & format, Args ... args) { size_t size = std::snprintf(nullptr, 0, format.c_str(), args ...) + 1; std::unique_ptr<char[]> buf(new char[size]); std::snprintf(buf.get(), size, format.c_str(), args ...); return std::string(buf.get(), buf.get() + size - 1); } inline std::string create_indented_newline(size_t indent) { std::string indented_newline("\n"); while (indent) { indented_newline += " "; indent--; } return indented_newline; } inline std::string replace_all_substrings( std::string subject, std::string const & source, std::string const & target ) { std::string::size_type n = 0; while ((n = subject.find(source, n)) != std::string::npos) { subject.replace(n, source.size(), target); n += target.size(); } return subject; } inline std::string from_double(double value, size_t precision=0) { std::ostringstream os; os.setf(std::ios::left); if (precision) { os.setf(std::ios::scientific); os.precision(precision); } os << value; return os.str(); } template <class T> std::string get_type_name(const T &) { char * buf = abi::__cxa_demangle(typeid(T).name(), nullptr, nullptr, nullptr); const std::string ret(buf); free(buf); return ret; } } /* end namespace string */ inline std::string error_location( const char * filename, int lineno, const char * funcname ) { return string::format("in file %s, line %d, function %s", filename, lineno, funcname); } } /* end namespace march */ // vim: set ff=unix fenc=utf8 nobomb et sw=4 ts=4:
bsd-3-clause
mstaessen/DDay.iCal
DDay.iCal/Evaluation/TimeZoneEvaluator.cs
6286
using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; namespace DDay.iCal { public class TimeZoneEvaluator : Evaluator { #region Private Fields private SortedList<Occurrence , Occurrence> m_Occurrences; #endregion #region Protected Properties protected ITimeZone TimeZone { get; set; } #endregion #region Constructors public TimeZoneEvaluator(ITimeZone tz) { TimeZone = tz; m_Occurrences = new SortedList<Occurrence, Occurrence>(); } #endregion #region Private Methods void ProcessOccurrences(IDateTime referenceDate) { //// Sort the occurrences by start time //m_Occurrences.Sort( // delegate(Occurrence o1, Occurrence o2) // { // if (o1.Period == null || o1.Period.StartTime == null) // return -1; // else if (o2.Period == null || o2.Period.StartTime == null) // return 1; // else return o1.Period.StartTime.CompareTo(o2.Period.StartTime); // } //); for (int i = 0; i < m_Occurrences.Count; i++) { Occurrence curr = m_Occurrences.Values[i]; Occurrence? next = i < m_Occurrences.Count - 1 ? (Occurrence?)m_Occurrences.Values[i + 1] : null; // Determine end times for our periods, overwriting previously calculated end times. // This is important because we don't want to overcalculate our time zone information, // but simply calculate enough to be accurate. When date/time ranges that are out of // normal working bounds are encountered, then occurrences are processed again, and // new end times are determined. if (next != null && next.HasValue) { curr.Period.EndTime = next.Value.Period.StartTime.AddTicks(-1); } else { curr.Period.EndTime = ConvertToIDateTime(EvaluationEndBounds, referenceDate); } } } #endregion #region Overrides public override void Clear() { base.Clear(); m_Occurrences.Clear(); } public override IList<IPeriod> Evaluate(IDateTime referenceDate, DateTime periodStart, DateTime periodEnd, bool includeReferenceDateInResults) { // Ensure the reference date is associated with the time zone if (referenceDate.AssociatedObject == null) referenceDate.AssociatedObject = TimeZone; List<ITimeZoneInfo> infos = new List<ITimeZoneInfo>(TimeZone.TimeZoneInfos); // Evaluate extra time periods, without re-evaluating ones that were already evaluated if ((EvaluationStartBounds == DateTime.MaxValue && EvaluationEndBounds == DateTime.MinValue) || (periodEnd.Equals(EvaluationStartBounds)) || (periodStart.Equals(EvaluationEndBounds))) { foreach (ITimeZoneInfo curr in infos) { IEvaluator evaluator = curr.GetService(typeof(IEvaluator)) as IEvaluator; Debug.Assert(curr.Start != null, "TimeZoneInfo.Start must not be null."); Debug.Assert(curr.Start.TZID == null, "TimeZoneInfo.Start must not have a time zone reference."); Debug.Assert(evaluator != null, "TimeZoneInfo.GetService(typeof(IEvaluator)) must not be null."); // Time zones must include an effective start date/time // and must provide an evaluator. if (evaluator != null) { // Set the start bounds if (EvaluationStartBounds > periodStart) EvaluationStartBounds = periodStart; // FIXME: 5 years is an arbitrary number, to eliminate the need // to recalculate time zone information as much as possible. DateTime offsetEnd = periodEnd.AddYears(5); // Adjust our reference date to never fall out of bounds with // the time zone information var tziReferenceDate = referenceDate; if (tziReferenceDate.LessThan(curr.Start)) tziReferenceDate = curr.Start; // Determine the UTC occurrences of the Time Zone observances IList<IPeriod> periods = evaluator.Evaluate( tziReferenceDate, periodStart, offsetEnd, includeReferenceDateInResults); foreach (IPeriod period in periods) { if (!Periods.Contains(period)) { Periods.Add(period); Occurrence o = new Occurrence(curr, period); if (!m_Occurrences.ContainsKey(o)) m_Occurrences.Add(o, o); } } if (EvaluationEndBounds == DateTime.MinValue || EvaluationEndBounds < offsetEnd) EvaluationEndBounds = offsetEnd; } } ProcessOccurrences(referenceDate); } else { if (EvaluationEndBounds != DateTime.MinValue && periodEnd > EvaluationEndBounds) Evaluate(referenceDate, EvaluationEndBounds, periodEnd, includeReferenceDateInResults); } return Periods; } #endregion } }
bsd-3-clause
elorian/cabinet.inreserve.kz
views/merchant/view.php
1281
<?php use yii\helpers\Html; use yii\widgets\DetailView; /* @var $this yii\web\View */ /* @var $model app\models\Merchant */ $this->title = $model->title; $this->params['breadcrumbs'][] = ['label' => 'Merchants', 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; ?> <div class="merchant-view"> <h1><?= Html::encode($this->title) ?></h1> <p> <?= Html::a('Update', ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?> <?= Html::a('Delete', ['delete', 'id' => $model->id], [ 'class' => 'btn btn-danger', 'data' => [ 'confirm' => 'Are you sure you want to delete this item?', 'method' => 'post', ], ]) ?> </p> <?= DetailView::widget([ 'model' => $model, 'attributes' => [ 'id', 'title', 'country_id', 'city_id', 'street', 'number_house', 'count_places', 'description:ntext', 'start_time', 'end_time', 'deposit', 'created_date', 'updated_date', 'status', 'owner_id', 'latitude', 'longitude', ], ]) ?> </div>
bsd-3-clause
museami/ffi
test/test_apply.lua
1336
require 'torch' require 'torchffi' local mytest = {} local tester = torch.Tester() local function eq(tensor1, tensor2, message) tester:assertTensorEq(tensor1, tensor2, 1e-300, message) end function mytest.test_apply() local input = torch.Tensor({1, 2, 3, 4}) input:apply(function(x) return 2 * x end) eq(input, torch.Tensor({2, 4, 6, 8}), "expecting doubles") end function mytest.test_applyWithNilReturn() local input = torch.Tensor({1, 2, 3, 4}) local count = 0 input:apply(function(x) count = count + 1 return end) eq(input, torch.Tensor({1, 2, 3, 4}), "expecting no change") tester:asserteq(count, 4, "count") end function mytest.test_applyWithStorageOffset() local origInput = torch.Tensor({1, 2, 3, 4, 5, 6}) local input = origInput[{{3, 5}}] input:apply(function(x) return 2 * x end) eq(origInput, torch.Tensor({1, 2, 6, 8, 10, 6}), "expecting a subset of doubles") end function mytest.test_applyWithNonContiguous() local origInput = torch.Tensor({{1, 2, 3}, {4, 5, 6}}) local input = origInput:t() assert(not input:isContiguous(), "expecting non-contiguous") input:apply(function(x) return 2 * x end) eq(input, torch.Tensor({{2, 4, 6}, {8, 10, 12}}):t(), "expecting transposed doubles") end tester:add(mytest) tester:run()
bsd-3-clause
lsimkins/laravel-zend-bundle
library/Zend/Pdf/Destination/Zoom.php
5689
<?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_Pdf * @subpackage Destination * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: Zoom.php 23775 2011-03-01 17:25:24Z ralph $ */ /** Internally used classes */ // require_once 'Zend/Pdf/Element/Array.php'; // require_once 'Zend/Pdf/Element/Name.php'; // require_once 'Zend/Pdf/Element/Null.php'; // require_once 'Zend/Pdf/Element/Numeric.php'; /** Zend_Pdf_Destination_Explicit */ // require_once 'Zend/Pdf/Destination/Explicit.php'; /** * Zend_Pdf_Destination_Zoom explicit detination * * Destination array: [page /XYZ left top zoom] * * Display the page designated by page, with the coordinates (left, top) positioned * at the upper-left corner of the window and the contents of the page * magnified by the factor zoom. A null value for any of the parameters left, top, * or zoom specifies that the current value of that parameter is to be retained unchanged. * A zoom value of 0 has the same meaning as a null value. * * @package Zend_Pdf * @subpackage Destination * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Pdf_Destination_Zoom extends Zend_Pdf_Destination_Explicit { /** * Create destination object * * @param Zend_Pdf_Page|integer $page Page object or page number * @param float $left Left edge of displayed page * @param float $top Top edge of displayed page * @param float $zoom Zoom factor * @return Zend_Pdf_Destination_Zoom * @throws Zend_Pdf_Exception */ public static function create($page, $left = null, $top = null, $zoom = null) { $destinationArray = new Zend_Pdf_Element_Array(); if ($page instanceof Zend_Pdf_Page) { $destinationArray->items[] = $page->getPageDictionary(); } else if (is_integer($page)) { $destinationArray->items[] = new Zend_Pdf_Element_Numeric($page); } else { // require_once 'Zend/Pdf/Exception.php'; throw new Zend_Pdf_Exception('Page entry must be a Zend_Pdf_Page object or a page number.'); } $destinationArray->items[] = new Zend_Pdf_Element_Name('XYZ'); if ($left === null) { $destinationArray->items[] = new Zend_Pdf_Element_Null(); } else { $destinationArray->items[] = new Zend_Pdf_Element_Numeric($left); } if ($top === null) { $destinationArray->items[] = new Zend_Pdf_Element_Null(); } else { $destinationArray->items[] = new Zend_Pdf_Element_Numeric($top); } if ($zoom === null) { $destinationArray->items[] = new Zend_Pdf_Element_Null(); } else { $destinationArray->items[] = new Zend_Pdf_Element_Numeric($zoom); } return new Zend_Pdf_Destination_Zoom($destinationArray); } /** * Get left edge of the displayed page (null means viewer application 'current value') * * @return float */ public function getLeftEdge() { return $this->_destinationArray->items[2]->value; } /** * Set left edge of the displayed page (null means viewer application 'current value') * * @param float $left * @return Zend_Pdf_Action_Zoom */ public function setLeftEdge($left) { if ($left === null) { $this->_destinationArray->items[2] = new Zend_Pdf_Element_Null(); } else { $this->_destinationArray->items[2] = new Zend_Pdf_Element_Numeric($left); } return $this; } /** * Get top edge of the displayed page (null means viewer application 'current value') * * @return float */ public function getTopEdge() { return $this->_destinationArray->items[3]->value; } /** * Set top edge of the displayed page (null means viewer application 'current viewer') * * @param float $top * @return Zend_Pdf_Action_Zoom */ public function setTopEdge($top) { if ($top === null) { $this->_destinationArray->items[3] = new Zend_Pdf_Element_Null(); } else { $this->_destinationArray->items[3] = new Zend_Pdf_Element_Numeric($top); } return $this; } /** * Get ZoomFactor of the displayed page (null or 0 means viewer application 'current value') * * @return float */ public function getZoomFactor() { return $this->_destinationArray->items[4]->value; } /** * Set ZoomFactor of the displayed page (null or 0 means viewer application 'current viewer') * * @param float $zoom * @return Zend_Pdf_Action_Zoom */ public function setZoomFactor($zoom) { if ($zoom === null) { $this->_destinationArray->items[4] = new Zend_Pdf_Element_Null(); } else { $this->_destinationArray->items[4] = new Zend_Pdf_Element_Numeric($zoom); } return $this; } }
bsd-3-clause
mvaled/sentry
tests/sentry/mediators/service_hooks/test_creator.py
1989
from __future__ import absolute_import from sentry.mediators.service_hooks import Creator from sentry.mediators.service_hooks.creator import expand_events, consolidate_events from sentry.models import ServiceHook, ServiceHookProject from sentry.testutils import TestCase class TestCreator(TestCase): def setUp(self): self.user = self.create_user() self.org = self.create_organization(owner=self.user) self.project = self.create_project(name="foo", organization=self.org) self.sentry_app = self.create_sentry_app(owner=self.org) self.creator = Creator( application=self.sentry_app.application, actor=self.sentry_app.proxy_user, organization=self.org, projects=[self.project], events=("event.created",), url=self.sentry_app.webhook_url, ) def test_creates_service_hook(self): self.creator.call() service_hook = ServiceHook.objects.get( application=self.sentry_app.application, actor_id=self.sentry_app.proxy_user.id, project_id=self.project.id, url=self.sentry_app.webhook_url, ) assert service_hook assert service_hook.events == ["event.created"] hook_project = ServiceHookProject.objects.get(project_id=self.project.id) assert hook_project.service_hook_id == service_hook.id def test_expands_resource_events_to_specific_events(self): self.creator.events = ["issue"] service_hook = self.creator.call() assert set(service_hook.events) == set( ["issue.created", "issue.resolved", "issue.ignored", "issue.assigned"] ) def test_expand_events(self): assert expand_events(["issue"]) == set( ["issue.created", "issue.resolved", "issue.ignored", "issue.assigned"] ) def test_consolidate_events(self): assert consolidate_events(["issue.created"]) == set(["issue"])
bsd-3-clause
tracingplane/tracingplane-java
bdl/compiler/src/main/scala/brown/tracingplane/bdl/compiler/JavaCompiler.scala
29421
package brown.tracingplane.bdl.compiler import scala.collection.mutable.Set import scala.collection.mutable.LinkedHashSet import scala.collection.mutable.LinkedHashMap import brown.tracingplane.bdl.compiler.Ast._ import brown.tracingplane.bdl.compiler.Ast.BuiltInType._ /** Compiles BaggageBuffers declarations to Java */ class JavaCompiler extends Compiler { override def compile(outputDir: String, objectDecl: ObjectDeclaration): Unit = { compiler(objectDecl).compile(outputDir) } def compiler(objectDecl: ObjectDeclaration): CompilerInstance = { objectDecl match { case bagDecl: BagDeclaration => return new BagCompilerInstance(bagDecl) case structDecl: StructDeclaration => return new StructCompilerInstance(structDecl) } } abstract class CompilerInstance(objectDecl: ObjectDeclaration) { def compile(): String def compile(outputDir: String): Unit var importedAndReserved = List[String](objectDecl.name, "Handler") var toImport = List[String]() def importIfPossible(fqn: String): String = { val className = fqn.drop(fqn.lastIndexOf(".") + 1) if (toImport contains fqn) { return className } else if (importedAndReserved contains className) { return fqn } else { toImport = toImport :+ fqn importedAndReserved = importedAndReserved :+ className return className } } // Built-in types that are used def Set = importIfPossible("java.util.Set") def Map = importIfPossible("java.util.Map") def ByteBuffer = importIfPossible("java.nio.ByteBuffer") def Objects = importIfPossible("java.util.Objects") // Logging def Logger = importIfPossible("org.slf4j.Logger") def LoggerFactory = importIfPossible("org.slf4j.LoggerFactory") // Transit layer api def Baggage = importIfPossible("brown.tracingplane.BaggageContext") def ActiveBaggage = importIfPossible("brown.tracingplane.ActiveBaggage") // Baggage layer api def BagKey = importIfPossible("brown.tracingplane.baggageprotocol.BagKey") def BaggageReader = importIfPossible("brown.tracingplane.baggageprotocol.BaggageReader") def BaggageWriter = importIfPossible("brown.tracingplane.baggageprotocol.BaggageWriter") // Baggage buffers api def BDLContextProvider = importIfPossible("brown.tracingplane.impl.BDLContextProvider") def BaggageHandlerRegistry = importIfPossible("brown.tracingplane.impl.BaggageHandlerRegistry") def Bag = importIfPossible("brown.tracingplane.bdl.Bag") def Struct = importIfPossible("brown.tracingplane.bdl.Struct") def Parser = importIfPossible("brown.tracingplane.bdl.Parser") def Serializer = importIfPossible("brown.tracingplane.bdl.Serializer") def Brancher = importIfPossible("brown.tracingplane.bdl.Brancher") def Joiner = importIfPossible("brown.tracingplane.bdl.Joiner") def BaggageHandler = importIfPossible("brown.tracingplane.bdl.BaggageHandler") def BBUtils = importIfPossible("brown.tracingplane.bdl.BDLUtils") def Counter = importIfPossible("brown.tracingplane.bdl.SpecialTypes.Counter") def CounterImpl = importIfPossible("brown.tracingplane.bdl.CounterImpl") def StructReader = s"${importIfPossible("brown.tracingplane.bdl.Struct")}.StructReader" def StructSizer = s"${importIfPossible("brown.tracingplane.bdl.Struct")}.StructSizer" def StructWriter = s"${importIfPossible("brown.tracingplane.bdl.Struct")}.StructWriter" def StructHandler = s"${importIfPossible("brown.tracingplane.bdl.Struct")}.StructHandler" // Baggage buffers helpers def ReaderHelpers = importIfPossible("brown.tracingplane.bdl.ReaderHelpers") def WriterHelpers = importIfPossible("brown.tracingplane.bdl.WriterHelpers") def Parsers = importIfPossible("brown.tracingplane.bdl.Parsers") def Serializers = importIfPossible("brown.tracingplane.bdl.Serializers") def Branchers = importIfPossible("brown.tracingplane.bdl.Branchers") def Joiners = importIfPossible("brown.tracingplane.bdl.Joiners") def StructHelpers = importIfPossible("brown.tracingplane.bdl.StructHelpers") def javaName(name: String): String = JavaCompilerUtils.formatCamelCase(name) def javaType(fieldType: FieldType): String = { fieldType match { case BuiltInType.taint => return "Boolean" case BuiltInType.bool => return "Boolean" case BuiltInType.int32 => return "Integer" case BuiltInType.sint32 => return "Integer" case BuiltInType.fixed32 => return "Integer" case BuiltInType.sfixed32 => return "Integer" case BuiltInType.int64 => return "Long" case BuiltInType.sint64 => return "Long" case BuiltInType.fixed64 => return "Long" case BuiltInType.sfixed64 => return "Long" case BuiltInType.float => return "Float" case BuiltInType.double => return "Double" case BuiltInType.string => return "String" case BuiltInType.bytes => return "java.nio.ByteBuffer" case BuiltInType.Set(of) => return s"$Set<${javaType(of)}>" case BuiltInType.Map(k, v) => return s"$Map<${javaType(k)}, ${javaType(v)}>" case BuiltInType.Counter => return s"$Counter" case UserDefinedType(packageName, name, _) => return importIfPossible(s"$packageName.${javaName(name)}") } } def handler(udt: UserDefinedType): String = s"${javaType(udt)}.Handler.instance" def counterHandler: String = s"$CounterImpl.Handler.instance" def parser(fieldType: FieldType): String = { fieldType match { case prim: PrimitiveType => return s"$Parsers.${prim}Parser()" case udt: UserDefinedType => return handler(udt) case BuiltInType.Counter => return s"($Parser)$counterHandler" case BuiltInType.Set(of) => return s"$Parsers.<${javaType(of)}>setParser(${parser(of)})" case BuiltInType.Map(k, v) => return s"$Parsers.<${javaType(k)},${javaType(v)}>mapParser(${keyParser(k)}, ${parser(v)})" } } def serializer(fieldType: FieldType): String = { fieldType match { case prim: PrimitiveType => return s"$Serializers.${prim}Serializer()" case udt: UserDefinedType => return handler(udt) case BuiltInType.Counter => return s"($Serializer)$counterHandler" case BuiltInType.Set(of) => return s"$Serializers.<${javaType(of)}>setSerializer(${serializer(of)})" case BuiltInType.Map(k, v) => return s"$Serializers.<${javaType(k)},${javaType(v)}>mapSerializer(${keySerializer(k)}, ${serializer(v)})" } } def joiner(fieldType: FieldType): String = { fieldType match { case BuiltInType.taint => return s"$Joiners.or()" case prim: PrimitiveType => return s"$Joiners.<${javaType(fieldType)}>first()" case udt: UserDefinedType => { udt.structType match { case true => return s"$Joiners.<${javaType(fieldType)}>first()" case false => return handler(udt) } } case BuiltInType.Counter => return s"($Joiner)$counterHandler" case BuiltInType.Set(of) => return s"$Joiners.<${javaType(of)}>setUnion()" case BuiltInType.Map(k, v) => return s"$Joiners.<${javaType(k)}, ${javaType(v)}>mapMerge(${joiner(v)})" } } def brancher(fieldType: FieldType): String = { fieldType match { case prim: PrimitiveType => return s"$Branchers.<${javaType(fieldType)}>noop()" case udt: UserDefinedType => { udt.structType match { case true => return s"$Branchers.<${javaType(fieldType)}>noop()" case false => return handler(udt) } } case BuiltInType.Counter => return s"($Brancher)$counterHandler" case BuiltInType.Set(of) => return s"$Branchers.<${javaType(of)}>set()" case BuiltInType.Map(k, v) => return s"$Branchers.<${javaType(k)}, ${javaType(v)}>map(${brancher(v)})" } } def toStringStatement(fieldtype: FieldType, instance: String): String = toStringStatement(fieldtype, instance, 0) def toStringStatement(fieldtype: FieldType, instance: String, recurseCount: Integer): String = { val lambdaVarname = s"_v$recurseCount" fieldtype match { case set: BuiltInType.Set => s"$BBUtils.toString($instance)" case BuiltInType.Map(k, v) => s"$BBUtils.toString($instance, $lambdaVarname -> ${toStringStatement(v, lambdaVarname, recurseCount + 1)})" case _ => s"String.valueOf($instance)" } } def keyParser(primitiveType: PrimitiveType): String = { return s"$ReaderHelpers.to_$primitiveType" } def keySerializer(primitiveType: PrimitiveType): String = { return s"$WriterHelpers.from_$primitiveType" } } class StructCompilerInstance(structDecl: StructDeclaration) extends CompilerInstance(structDecl) { override def compile(): String = { return JavaCompilerUtils.formatIndentation(new StructToCompile(structDecl).declaration, " "); } override def compile(outputDir: String): Unit = { val toCompile = new StructToCompile(structDecl) val text = JavaCompilerUtils.formatIndentation(toCompile.declaration, " "); JavaCompilerUtils.writeOutputFile(outputDir, toCompile.PackageName, toCompile.Name, text) } abstract class StructFieldToCompile(decl: StructFieldDeclaration) { val Name: String = javaName(decl.name) val Type: String = javaType(decl.fieldtype) def DefaultValue: String = { decl.fieldtype match { case BuiltInType.bool => return "false" case BuiltInType.int32 | BuiltInType.sint32 | BuiltInType.fixed32 => return "0" case BuiltInType.int64 | BuiltInType.sint64 | BuiltInType.fixed64 => return "0L" case BuiltInType.float => return "0.0f" case BuiltInType.double => return "0.0d" case BuiltInType.string => return "\"\"" case BuiltInType.bytes => return s"$StructHelpers.EMPTY_BYTE_BUFFER" case _ => return s"new $Type()" } } val fieldDeclaration = s"public $Type $Name = $DefaultValue;" val defaultValueName = s"_${Name}_defaultValue" val defaultValueDeclaration = s"private static final $Type $defaultValueName = $DefaultValue;" def NullCheck(instance: String): String = s"$instance.$Name == null ? $defaultValueName : $instance.$Name" val ReaderName: String val SizerName: String val WriterName: String val privateFieldsDeclaration: String def equalsStatement(a: String, b: String) = s"if (!$BBUtils.equals($a.$Name, $b.$Name, $defaultValueName)) return false;" def readStatement(buf: String, instance: String) = s"$instance.$Name = $ReaderName.readFrom($buf);" def serializedSizeStatement(size: String, instance: String) = s"$size += $SizerName.serializedSize(${NullCheck(instance)});" def writeStatement(buf: String, instance: String) = s"$WriterName.writeTo($buf, ${NullCheck(instance)});" def toString(instance: String) = s"""$BBUtils.indent(String.format("$Name = %s\\n", ${toStringStatement(decl.fieldtype, NullCheck(instance))}))""" } class BuiltInStructFieldToCompile(decl: StructFieldDeclaration) extends StructFieldToCompile(decl) { val ReaderName = s"_${Name}Reader" val SizerName = s"_${Name}Sizer" val WriterName = s"_${Name}Writer" val privateFieldsDeclaration: String = s""" private static final $StructReader<$Type> $ReaderName = $StructHelpers.${decl.fieldtype}Reader; private static final $StructSizer<$Type> $SizerName = $StructHelpers.${decl.fieldtype}Sizer; private static final $StructWriter<$Type> $WriterName = $StructHelpers.${decl.fieldtype}Writer;""" } class UserDefinedStructFieldToCompile(decl: StructFieldDeclaration, userfield: UserDefinedType) extends StructFieldToCompile(decl) { val HandlerName = s"_${Name}Handler" val ReaderName = HandlerName val SizerName = HandlerName val WriterName = HandlerName val privateFieldsDeclaration: String = s""" private static final $StructHandler<$Type> $HandlerName = ${handler(userfield)};""" } class StructToCompile(decl: StructDeclaration) { val Name: String = javaName(decl.name) val PackageName: String = decl.packageName val varName: String = Name.head.toLower + Name.tail val fields = decl.fields.map { x => x match { case StructFieldDeclaration(fieldtype: UserDefinedType, _) => new UserDefinedStructFieldToCompile(x, fieldtype) case _ => new BuiltInStructFieldToCompile(x) } } val body = s""" public class $Name implements $Struct { private static final $Logger _log = $LoggerFactory.getLogger($Name.class); ${fields.map(_.fieldDeclaration).mkString("\n")} private static final $Name _defaultValue = new $Name(); ${fields.map(_.defaultValueDeclaration).mkString("\n")} @Override public $StructHandler<?> handler() { return Handler.instance; } @Override public String toString() { StringBuilder b = new StringBuilder(); b.append("$Name{\\n"); ${fields.map(x => s"b.append(${x.toString("this")});").mkString("\n")} b.append("}"); return b.toString(); } @Override public boolean equals(Object other) { if (other == null) { return $Name.equals(this, _defaultValue); } else if (!(other instanceof $Name)) { return false; } else { return $Name.equals(this, ($Name) other); } } @Override public int hashCode() { int result = 1; ${fields.map(x => s"result = result * 37 + (${x.NullCheck("this")}).hashCode();").mkString("\n")} return result; } private static boolean equals($Name a, $Name b) { ${fields.map(_.equalsStatement("a", "b")).mkString("\n")} return true; } public static class Handler implements $StructHandler<$Name> { public static final Handler instance = new Handler(); private Handler(){} ${fields.map(_.privateFieldsDeclaration).mkString("\n")} @Override public $Name readFrom($ByteBuffer buf) throws Exception { $Name instance = new $Name(); try { ${fields.map(_.readStatement("buf", "instance")).mkString("\n")} } catch (Exception e) { _log.warn("Exception parsing $Name ", e); } return instance; } @Override public void writeTo($ByteBuffer buf, $Name instance) { try { ${fields.map(_.writeStatement("buf", "instance")).mkString("\n")} } catch (Exception e) { _log.warn("Exception serializing $Name ", e); } } @Override public int serializedSize($Name instance) { int size = 0; ${fields.map(_.serializedSizeStatement("size", "instance")).mkString("\n")} return size; } } }""" val declaration = s"""/** Generated by BaggageBuffersCompiler */ package ${decl.packageName}; ${toImport.map(x => s"import $x;").mkString("\n")} ${body}""" } } class BagCompilerInstance(bagDecl: BagDeclaration) extends CompilerInstance(bagDecl) { override def compile(): String = { return JavaCompilerUtils.formatIndentation(new BagToCompile(bagDecl).declaration, " "); } override def compile(outputDir: String): Unit = { val toCompile = new BagToCompile(bagDecl) val text = JavaCompilerUtils.formatIndentation(toCompile.declaration, " "); JavaCompilerUtils.writeOutputFile(outputDir, toCompile.PackageName, toCompile.Name, text) } abstract class FieldToCompile(decl: FieldDeclaration) { val Name: String = javaName(decl.name) val Type: String = javaType(decl.fieldtype) def DefaultValue: String = { decl.fieldtype match { case BuiltInType.taint => return "false" case _ => return "null" } } val fieldDeclaration = s"public $Type $Name = $DefaultValue;" val BagKeyName = s"_${Name}Key" val bagKeyFieldDeclaration = s"private static final $BagKey $BagKeyName = $BagKey.indexed(${decl.index});" val ParserName: String val SerializerName: String val BrancherName: String val JoinerName: String val privateFieldsDeclaration: String def parseStatement(reader: String, instance: String) = s""" if ($reader.enter($BagKeyName)) { $instance.$Name = $ParserName.parse($reader); $reader.exit(); }""" def serializeStatement(writer: String, instance: String) = s""" if ($instance.$Name != null) { $writer.enter($BagKeyName); $SerializerName.serialize($writer, $instance.$Name); $writer.exit(); }""" def branchStatement(instance: String, newInstance: String) = s"$newInstance.$Name = $BrancherName.branch($instance.$Name);" def joinStatement(left: String, right: String, newInstance: String) = s"$newInstance.$Name = $JoinerName.join($left.$Name, $right.$Name);" def toString(instance: String) = s"""$instance.$Name == null ? "" : $BBUtils.indent(String.format("$Name = %s\\n", ${toStringStatement(decl.fieldtype, s"$instance.$Name")}))""" } class BuiltInFieldToCompile(decl: FieldDeclaration) extends FieldToCompile(decl) { val ParserName = s"_${Name}Parser" val SerializerName = s"_${Name}Serializer" val BrancherName = s"_${Name}Brancher" val JoinerName = s"_${Name}Joiner" val privateFieldsDeclaration: String = s""" private static final $Parser<$Type> $ParserName = ${parser(decl.fieldtype)}; private static final $Serializer<$Type> $SerializerName = ${serializer(decl.fieldtype)}; private static final $Brancher<$Type> $BrancherName = ${brancher(decl.fieldtype)}; private static final $Joiner<$Type> $JoinerName = ${joiner(decl.fieldtype)};""" } class CounterToCompile(decl: FieldDeclaration) extends FieldToCompile(decl) { val HandlerName = s"_${Name}Handler" val ParserName = HandlerName val SerializerName = HandlerName val BrancherName = HandlerName val JoinerName = HandlerName val privateFieldsDeclaration: String = s""" private static final $BaggageHandler<? extends $Type> $HandlerName = $counterHandler;""" } class UserDefinedBagFieldToCompile(decl: FieldDeclaration, userfield: UserDefinedType) extends FieldToCompile(decl) { val HandlerName = s"_${Name}Handler" val ParserName = HandlerName val SerializerName = HandlerName val BrancherName = HandlerName val JoinerName = HandlerName val privateFieldsDeclaration: String = s""" private static final $BaggageHandler<$Type> $HandlerName = ${handler(userfield)};""" } class UserDefinedStructFieldToCompile(decl: FieldDeclaration, userfield: UserDefinedType) extends FieldToCompile(decl) { val HandlerName = s"_${Name}Handler" val ParserName = HandlerName val SerializerName = HandlerName val BrancherName = s"_${Name}Brancher" val JoinerName = s"_${Name}Joiner" val privateFieldsDeclaration: String = s""" private static final $StructHandler<$Type> $HandlerName = ${handler(userfield)}; private static final $Brancher<$Type> $BrancherName = ${brancher(decl.fieldtype)}; private static final $Joiner<$Type> $JoinerName = ${joiner(decl.fieldtype)};""" } class BagToCompile(decl: BagDeclaration) { val Name: String = javaName(decl.name) val PackageName: String = decl.packageName val varName: String = Name.head.toLower + Name.tail val fields = decl.fields.sortWith(_.index < _.index).map { x => x match { case FieldDeclaration(BuiltInType.Counter, _, _) => new CounterToCompile(x) case FieldDeclaration(fieldtype: UserDefinedType, _, _) => { fieldtype.structType match { case true => new UserDefinedStructFieldToCompile(x, fieldtype) case false => new UserDefinedBagFieldToCompile(x, fieldtype) } } case _ => new BuiltInFieldToCompile(x) } } val body = s""" public class $Name implements $Bag { private static final $Logger _log = $LoggerFactory.getLogger($Name.class); ${fields.map(_.fieldDeclaration).mkString("\n")} public boolean _overflow = false; /** * <p> * Get the {@link $Name} set in the active {@link $Baggage} carried by the current thread. If no baggage is being * carried by the current thread, or if there is no $Name in it, then this method returns {@code null}. * </p> * * <p> * To get $Name from a specific Baggage instance, use {@link #getFrom($Baggage)}. * </p> * * @return the $Name being carried in the {@link $Baggage} of the current thread, or {@code null} * if none is being carried. The returned instance maybe be modified and modifications will be reflected in * the baggage. */ public static $Name get() { $Bag bag = $BDLContextProvider.get($ActiveBaggage.peek(), Handler.registration()); if (bag instanceof $Name) { return ($Name) bag; } else { return null; } } /** * <p> * Get the {@link $Name} set in {@code baggage}. If {@code baggage} has no $Name set then * this method returns null. * </p> * * <p> * This method does <b>not</b> affect the Baggage being carried by the current thread. To get $Name * from the current thread's Baggage, use {@link #get()}. * </p> * * @param baggage A baggage instance to get the {@link $Name} from * @return the {@link $Name} instance being carried in {@code baggage}, or {@code null} if none is being carried. * The returned instance can be modified, and modifications will be reflected in the baggage. */ public static $Name getFrom($Baggage baggage) { $Bag bag = $BDLContextProvider.get(baggage, Handler.registration()); if (bag instanceof $Name) { return ($Name) bag; } else if (bag != null) { Handler.checkRegistration(); } return null; } /** * <p> * Update the {@link $Name} set in the current thread's baggage. This method will overwrite any existing * $Name set in the current thread's baggage. * </p> * * <p> * To set the {@link $Name} in a specific {@link $Baggage} instance, use * {@link #setIn($Baggage, $Name)} * </p> * * @param $varName the new {@link $Name} to set in the current thread's {@link $Baggage}. If {@code null} * then any existing mappings will be removed. */ public static void set($Name $varName) { $ActiveBaggage.update($BDLContextProvider.set($ActiveBaggage.peek(), Handler.registration(), $varName)); } /** * <p> * Update the {@link $Name} set in {@code baggage}. This method will overwrite any existing * $Name set in {@code baggage}. * </p> * * <p> * This method does <b>not</b> affect the {@link $Baggage} being carried by the current thread. To set the * {@link $Name} for the current thread, use {@link #set($Name)} * </p> * * @param baggage A baggage instance to set the {@link $Name} in * @param $varName the new $Name to set in {@code baggage}. If {@code null}, it will remove any * mapping present. * @return a possibly new {@link $Baggage} instance that contains all previous mappings plus the new mapping. */ public static $Baggage setIn($Baggage baggage, $Name $varName) { return $BDLContextProvider.set(baggage, Handler.registration(), $varName); } @Override public $BaggageHandler<?> handler() { return Handler.instance; } @Override public String toString() { StringBuilder b = new StringBuilder(); b.append("$Name{\\n"); ${fields.map(x => s"b.append(${x.toString("this")});").mkString("\n")} b.append("}"); return b.toString(); } public static class Handler implements $BaggageHandler<$Name> { public static final Handler instance = new Handler(); private static $BagKey registration = null; static synchronized $BagKey checkRegistration() { registration = $BaggageHandlerRegistry.get(instance); if (registration == null) { _log.error("$Name MUST be registered to a key before it can be propagated. " + "There is currently no registration for $Name and it will not be propagated. " + "To register a bag set the bag.{index} property in your application.conf (eg, for " + "index 10, bag.10 = \\\"${decl.packageName}.$Name\\\") or with -Dbag.{index} flag " + "(eg, for index 10, -Dbag.10=${decl.packageName}.$Name)"); } return registration; } static BagKey registration() { return registration == null ? checkRegistration() : registration; } private Handler(){} ${fields.map(_.bagKeyFieldDeclaration).mkString("\n")} ${fields.map(_.privateFieldsDeclaration).mkString("\n")} @Override public boolean isInstance($Bag bag) { return bag == null || bag instanceof $Name; } @Override public $Name parse($BaggageReader reader) { $Name instance = new $Name(); ${fields.map(_.parseStatement("reader", "instance")).mkString("\n")} instance._overflow = reader.didOverflow(); return instance; } @Override public void serialize($BaggageWriter writer, $Name instance) { if (instance == null) { return; } writer.didOverflowHere(instance._overflow); ${fields.map(_.serializeStatement("writer", "instance")).mkString("\n")} } @Override public $Name branch($Name instance) { if (instance == null) { return null; } $Name newInstance = new $Name(); ${fields.map(_.branchStatement("instance", "newInstance")).mkString("\n")} return newInstance; } @Override public $Name join($Name left, $Name right) { if (left == null) { return right; } else if (right == null) { return left; } else { ${fields.map(_.joinStatement("left", "right", "left")).mkString("\n")} return left; } } } }""" val declaration = s"""/** Generated by BaggageBuffersCompiler */ package ${decl.packageName}; ${toImport.sortWith(_ < _).map(x => s"import $x;").mkString("\n")} ${body}""" } } }
bsd-3-clause
HalCanary/skia-hc
tests/PDFTaggedTest.cpp
4814
/* * Copyright 2018 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "tests/Test.h" #include "include/core/SkCanvas.h" #include "include/core/SkFont.h" #include "include/core/SkStream.h" #include "include/docs/SkPDFDocument.h" using PDFTag = SkPDF::StructureElementNode; // Test building a tagged PDF. // Add this to args.gn to output the PDF to a file: // extra_cflags = [ "-DSK_PDF_TEST_TAGS_OUTPUT_PATH=\"/tmp/foo.pdf\"" ] DEF_TEST(SkPDF_tagged, r) { REQUIRE_PDF_DOCUMENT(SkPDF_tagged, r); #ifdef SK_PDF_TEST_TAGS_OUTPUT_PATH SkFILEWStream outputStream(SK_PDF_TEST_TAGS_OUTPUT_PATH); #else SkDynamicMemoryWStream outputStream; #endif SkSize pageSize = SkSize::Make(612, 792); // U.S. Letter SkPDF::Metadata metadata; metadata.fTitle = "Example Tagged PDF"; metadata.fCreator = "Skia"; SkTime::DateTime now; SkTime::GetDateTime(&now); metadata.fCreation = now; metadata.fModified = now; // The document tag. PDFTag root; root.fNodeId = 1; root.fType = SkPDF::DocumentStructureType::kDocument; root.fChildCount = 5; PDFTag rootChildren[5]; root.fChildren = rootChildren; // Heading. PDFTag& h1 = rootChildren[0]; h1.fNodeId = 2; h1.fType = SkPDF::DocumentStructureType::kH1; h1.fChildCount = 0; // Initial paragraph. PDFTag& p = rootChildren[1]; p.fNodeId = 3; p.fType = SkPDF::DocumentStructureType::kP; p.fChildCount = 0; // Hidden div. This is never referenced by marked content // so it should not appear in the resulting PDF. PDFTag& div = rootChildren[2]; div.fNodeId = 4; div.fType = SkPDF::DocumentStructureType::kDiv; div.fChildCount = 0; // A bulleted list of two items. PDFTag& l = rootChildren[3]; l.fNodeId = 5; l.fType = SkPDF::DocumentStructureType::kL; l.fChildCount = 4; PDFTag listChildren[4]; l.fChildren = listChildren; PDFTag& lm1 = listChildren[0]; lm1.fNodeId = 6; lm1.fType = SkPDF::DocumentStructureType::kLbl; lm1.fChildCount = 0; PDFTag& li1 = listChildren[1]; li1.fNodeId = 7; li1.fType = SkPDF::DocumentStructureType::kLI; li1.fChildCount = 0; PDFTag& lm2 = listChildren[2]; lm2.fNodeId = 8; lm2.fType = SkPDF::DocumentStructureType::kLbl; lm2.fChildCount = 0; PDFTag& li2 = listChildren[3]; li2.fNodeId = 9; li2.fType = SkPDF::DocumentStructureType::kLI; li2.fChildCount = 0; // Paragraph spanning two pages. PDFTag& p2 = rootChildren[4]; p2.fNodeId = 10; p2.fType = SkPDF::DocumentStructureType::kP; p2.fChildCount = 0; metadata.fStructureElementTreeRoot = &root; sk_sp<SkDocument> document = SkPDF::MakeDocument( &outputStream, metadata); SkPaint paint; paint.setColor(SK_ColorBLACK); // First page. SkCanvas* canvas = document->beginPage(pageSize.width(), pageSize.height()); SkPDF::SetNodeId(canvas, 2); SkFont font(nullptr, 36); const char* message = "This is the title"; canvas->translate(72, 72); canvas->drawString(message, 0, 0, font, paint); SkPDF::SetNodeId(canvas, 3); font.setSize(14); message = "This is a simple paragraph."; canvas->translate(0, 72); canvas->drawString(message, 0, 0, font, paint); SkPDF::SetNodeId(canvas, 6); font.setSize(14); message = "*"; canvas->translate(0, 72); canvas->drawString(message, 0, 0, font, paint); SkPDF::SetNodeId(canvas, 7); message = "List item 1"; canvas->translate(36, 0); canvas->drawString(message, 0, 0, font, paint); SkPDF::SetNodeId(canvas, 8); message = "*"; canvas->translate(-36, 36); canvas->drawString(message, 0, 0, font, paint); SkPDF::SetNodeId(canvas, 9); message = "List item 2"; canvas->translate(36, 0); canvas->drawString(message, 0, 0, font, paint); SkPDF::SetNodeId(canvas, 10); message = "This is a paragraph that starts on one page"; canvas->translate(-36, 6 * 72); canvas->drawString(message, 0, 0, font, paint); document->endPage(); // Second page. canvas = document->beginPage(pageSize.width(), pageSize.height()); SkPDF::SetNodeId(canvas, 10); message = "and finishes on the second page."; canvas->translate(72, 72); canvas->drawString(message, 0, 0, font, paint); // This has a node ID but never shows up in the tag tree so it // won't be tagged. SkPDF::SetNodeId(canvas, 999); message = "Page 2"; canvas->translate(468, -36); canvas->drawString(message, 0, 0, font, paint); document->endPage(); document->close(); outputStream.flush(); }
bsd-3-clause
jakubroztocil/httpie
tests/test_tokens.py
3538
""" The ideas behind these test and the named templates is to ensure consistent output across all supported different scenarios: TODO: cover more scenarios * terminal vs. redirect stdout * different combinations of `--print=HBhb` (request/response headers/body) * multipart requests * streamed uploads """ from .utils.matching import assert_output_matches, Expect, ExpectSequence from .utils import http, HTTP_OK, MockEnvironment def test_headers(): r = http('--print=H', '--offline', 'pie.dev') assert_output_matches(r, [Expect.REQUEST_HEADERS]) def test_redirected_headers(): r = http('--print=H', '--offline', 'pie.dev', env=MockEnvironment(stdout_isatty=False)) assert_output_matches(r, [Expect.REQUEST_HEADERS]) def test_terminal_headers_and_body(): r = http('--print=HB', '--offline', 'pie.dev', 'AAA=BBB') assert_output_matches(r, ExpectSequence.TERMINAL_REQUEST) def test_terminal_request_headers_response_body(httpbin): r = http('--print=Hb', httpbin + '/get') assert_output_matches(r, ExpectSequence.TERMINAL_REQUEST) def test_raw_request_headers_response_body(httpbin): r = http('--print=Hb', httpbin + '/get', env=MockEnvironment(stdout_isatty=False)) assert_output_matches(r, ExpectSequence.RAW_REQUEST) def test_terminal_request_headers_response_headers(httpbin): r = http('--print=Hh', httpbin + '/get') assert_output_matches(r, [Expect.REQUEST_HEADERS, Expect.RESPONSE_HEADERS]) def test_raw_request_headers_response_headers(httpbin): r = http('--print=Hh', httpbin + '/get', env=MockEnvironment(stdout_isatty=False)) assert_output_matches(r, [Expect.REQUEST_HEADERS, Expect.RESPONSE_HEADERS]) def test_terminal_request_body_response_body(httpbin): r = http('--print=Hh', httpbin + '/get') assert_output_matches(r, [Expect.REQUEST_HEADERS, Expect.RESPONSE_HEADERS]) def test_raw_headers_and_body(): r = http( '--print=HB', '--offline', 'pie.dev', 'AAA=BBB', env=MockEnvironment(stdout_isatty=False), ) assert_output_matches(r, ExpectSequence.RAW_REQUEST) def test_raw_body(): r = http('--print=B', '--offline', 'pie.dev', 'AAA=BBB', env=MockEnvironment(stdout_isatty=False)) assert_output_matches(r, ExpectSequence.RAW_BODY) def test_raw_exchange(httpbin): r = http('--verbose', httpbin + '/post', 'a=b', env=MockEnvironment(stdout_isatty=False)) assert HTTP_OK in r assert_output_matches(r, ExpectSequence.RAW_EXCHANGE) def test_terminal_exchange(httpbin): r = http('--verbose', httpbin + '/post', 'a=b') assert HTTP_OK in r assert_output_matches(r, ExpectSequence.TERMINAL_EXCHANGE) def test_headers_multipart_body_separator(): r = http('--print=HB', '--multipart', '--offline', 'pie.dev', 'AAA=BBB') assert_output_matches(r, ExpectSequence.TERMINAL_REQUEST) def test_redirected_headers_multipart_no_separator(): r = http( '--print=HB', '--multipart', '--offline', 'pie.dev', 'AAA=BBB', env=MockEnvironment(stdout_isatty=False), ) assert_output_matches(r, ExpectSequence.RAW_REQUEST) def test_verbose_chunked(httpbin_with_chunked_support): r = http('--verbose', '--chunked', httpbin_with_chunked_support + '/post', 'hello=world') assert HTTP_OK in r assert 'Transfer-Encoding: chunked' in r assert_output_matches(r, ExpectSequence.TERMINAL_EXCHANGE) def test_request_headers_response_body(httpbin): r = http('--print=Hb', httpbin + '/get') assert_output_matches(r, ExpectSequence.TERMINAL_REQUEST)
bsd-3-clause
birm/Elemental
src/lapack_like/condense/Bidiag/L.hpp
5265
/* Copyright (c) 2009-2015, Jack Poulson All rights reserved. This file is part of Elemental and is under the BSD 2-Clause License, which can be found in the LICENSE file in the root directory, or at http://opensource.org/licenses/BSD-2-Clause */ #pragma once #ifndef EL_BIDIAG_L_HPP #define EL_BIDIAG_L_HPP #include "./LUnb.hpp" #include "./LPan.hpp" namespace El { namespace bidiag { // NOTE: Very little is changed versus the upper case. Perhaps they should be // combined. template<typename F> inline void L( Matrix<F>& A, Matrix<F>& tP, Matrix<F>& tQ ) { DEBUG_ONLY(CSE cse("bidiag::L")) const Int m = A.Height(); const Int n = A.Width(); DEBUG_ONLY( if( m > n ) LogicError("A must be at least as wide as it is tall"); // Are these requirements necessary?!? if( tP.Viewing() || tQ.Viewing() ) LogicError("tP and tQ must not be views"); ) const Int tPHeight = m; const Int tQHeight = Max(m-1,0); tP.Resize( tPHeight, 1 ); tQ.Resize( tQHeight, 1 ); Matrix<F> X, Y; const Int bsize = Blocksize(); for( Int k=0; k<m; k+=bsize ) { const Int nb = Min(bsize,m-k); const Range<Int> ind1( k, k+nb ), ind2( k+nb, END ), indB( k, END ), indR( k, END ); auto A22 = A( ind2, ind2 ); auto ABR = A( indB, indR ); auto tP1 = tP( ind1, ALL ); if( A22.Height() > 0 ) { auto A12 = A( ind1, ind2 ); auto A21 = A( ind2, ind1 ); auto tQ1 = tQ( ind1, ALL ); X.Resize( m-k, nb ); Y.Resize( nb, n-k ); bidiag::LPan( ABR, tP1, tQ1, X, Y ); auto X21 = X( IR(nb,END), ALL ); auto Y12 = Y( ALL, IR(nb,END) ); // Set top-right entry of A21 to 1 const F epsilon = A21.Get(0,nb-1); A21.Set(0,nb-1,F(1)); Gemm( NORMAL, NORMAL, F(-1), A21, Y12, F(1), A22 ); Conjugate( A12 ); Gemm( NORMAL, NORMAL, F(-1), X21, A12, F(1), A22 ); Conjugate( A12 ); // Put back top-right entry of A21 A21.Set(0,nb-1,epsilon); } else { auto tQ1 = tQ( IR(k,k+nb-1), ALL ); bidiag::LUnb( ABR, tP1, tQ1 ); } } } // NOTE: Very little is different from the upper case. Perhaps they should // be combined. template<typename F> inline void L ( AbstractDistMatrix<F>& APre, AbstractDistMatrix<F>& tPPre, AbstractDistMatrix<F>& tQPre ) { DEBUG_ONLY( CSE cse("bidiag::U"); AssertSameGrids( APre, tPPre, tQPre ); ) auto APtr = ReadWriteProxy<F,MC,MR>( &APre ); auto& A = *APtr; auto tPPtr = WriteProxy<F,STAR,STAR>( &tPPre ); auto& tP = *tPPtr; auto tQPtr = WriteProxy<F,STAR,STAR>( &tQPre ); auto& tQ = *tQPtr; const Int m = A.Height(); const Int n = A.Width(); DEBUG_ONLY( if( m > n ) LogicError("A must be at least as wide as it is tall"); // Are these requirements necessary?!? if( tP.Viewing() || tQ.Viewing() ) LogicError("tP and tQ must not be views"); ) const Grid& g = A.Grid(); const Int tPHeight = m; const Int tQHeight = Max(m-1,0); tP.Resize( tPHeight, 1 ); tQ.Resize( tQHeight, 1 ); DistMatrix<F> X(g), Y(g); DistMatrix<F,MC,STAR> X21_MC_STAR(g); DistMatrix<F,MR,STAR> Y12Adj_MR_STAR(g); DistMatrix<F,MC, STAR> AB1_MC_STAR(g); DistMatrix<F,STAR,MR > A1R_STAR_MR(g); const Int bsize = Blocksize(); for( Int k=0; k<m; k+=bsize ) { const Int nb = Min(bsize,m-k); const Range<Int> ind1( k, k+nb ), ind2( k+nb, END ), indB( k, END ), indR( k, END ); auto A22 = A( ind2, ind2 ); auto ABR = A( indB, indR ); auto tP1 = tP( ind1, ALL ); if( A22.Height() > 0 ) { X.AlignWith( ABR ); Y.AlignWith( ABR ); X.Resize( m-k, nb ); Y.Resize( nb, n-k ); AB1_MC_STAR.AlignWith( ABR ); A1R_STAR_MR.AlignWith( ABR ); AB1_MC_STAR.Resize( m-k, nb ); A1R_STAR_MR.Resize( nb, n-k ); auto tQ1 = tQ( ind1, ALL ); bidiag::LPan( ABR, tP1, tQ1, X, Y, AB1_MC_STAR, A1R_STAR_MR ); auto X21 = X( IR(nb,END), ALL ); auto Y12 = Y( ALL, IR(nb,END) ); X21_MC_STAR.AlignWith( A22 ); Y12Adj_MR_STAR.AlignWith( A22 ); X21_MC_STAR = X21; Adjoint( Y12, Y12Adj_MR_STAR ); auto A21_MC_STAR = AB1_MC_STAR( IR(nb,m-k), IR(0,nb) ); auto A12_STAR_MR = A1R_STAR_MR( IR(0,nb), IR(nb,n-k) ); LocalGemm ( NORMAL, ADJOINT, F(-1), A21_MC_STAR, Y12Adj_MR_STAR, F(1), A22 ); Conjugate( A12_STAR_MR ); LocalGemm ( NORMAL, NORMAL, F(-1), X21_MC_STAR, A12_STAR_MR, F(1), A22 ); } else { auto tQ1 = tQ( IR(k,k+nb-1), ALL ); bidiag::LUnb( ABR, tP1, tQ1 ); } } } } // namespace bidiag } // namespace El #endif // ifndef EL_LAPACK_CONDENSE_BIDIAG_L_HPP
bsd-3-clause
redmed/echarts-www
docv/data/options/tooltip-type1.js
2490
var option = { title: { text: '阶梯瀑布图', subtext: 'From ExcelHome', sublink: 'http://e.weibo.com/1341556070/Aj1J2x5a5' }, tooltip : { trigger: 'axis', axisPointer : { // 坐标轴指示器,坐标轴触发有效 type : 'shadow' , // 默认为直线,可选为:'line' | 'shadow' shadowStyle : { color: "rgba(0,0,255,0.7)" } }, formatter: function (params) { var tar; if (params[1].value != '-') { tar = params[1]; } else { tar = params[0]; } return tar.name + '<br/>' + tar.seriesName + ' : ' + tar.value; } }, legend: { data:['支出','收入'] }, toolbox: { show : true, feature : { mark : {show: true}, dataView : {show: true, readOnly: false}, restore : {show: true}, saveAsImage : {show: true} } }, xAxis : [ { type : 'category', splitLine: {show:false}, data : function (){ var list = []; for (var i = 1; i <= 11; i++) { list.push('11月' + i + '日'); } return list; }() } ], yAxis : [ { type : 'value' } ], series : [ { name:'辅助', type:'bar', stack: '总量', itemStyle:{ normal:{ barBorderColor:'rgba(0,0,0,0)', color:'rgba(0,0,0,0)' }, emphasis:{ barBorderColor:'rgba(0,0,0,0)', color:'rgba(0,0,0,0)' } }, data:[0, 900, 1245, 1530, 1376, 1376, 1511, 1689, 1856, 1495, 1292] }, { name:'收入', type:'bar', stack: '总量', itemStyle : { normal: {label : {show: true, position: 'top'}}}, data:[900, 345, 393, '-', '-', 135, 178, 286, '-', '-', '-'] }, { name:'支出', type:'bar', stack: '总量', itemStyle : { normal: {label : {show: true, position: 'bottom'}}}, data:['-', '-', '-', 108, 154, '-', '-', '-', 119, 361, 203] } ] };
bsd-3-clause
brotherjack/Rood-Kamer
roodkamer/static/libs/ajax/ckeditor/plugins/eqneditor/dialogs/eqneditor.js
3257
/* Equation Editor Plugin for CKEditor v4 Version 1.4 This plugin allows equations to be created and edited from within CKEditor. For more information goto: http://www.codecogs.com/latex/integration/ckeditor_v4/install.php Copyright CodeCogs 2006-2013 Written by Will Bateman. Special Thanks to: - Kyle Jones for a fix to allow multiple editor to load on one page */ window.CCounter=0; CKEDITOR.dialog.add( 'eqneditorDialog', function(editor) { var http = ('https:' == document.location.protocol ? 'https://' : 'http://'); window.CCounter++; return { title : editor.lang.eqneditor.title, minWidth : 550, minHeight : 380, resizable: CKEDITOR.DIALOG_RESIZE_NONE, contents : [ { id : 'CCEquationEditor', label : 'EqnEditor', elements : [ { type: 'html', html: '<div id="CCtoolbar'+window.CCounter+'"></div>', style: 'margin-top:-9px' }, { type: 'html', html: '<label for="CClatex'+window.CCounter+'">Equation (LaTeX):</label>', }, { type: 'html', html: '<textarea id="CClatex'+window.CCounter+'" rows="5"></textarea>', style:'border:1px solid #8fb6bd; width:540px; font-size:16px; padding:5px; background-color:#ffc', }, { type: 'html', html: '<label for="CCequation'+window.CCounter+'">Preview:</label>' }, { type :'html', html: '<div style="position:absolute; left:5px; bottom:0; z-index:999"><a href="http://www.codecogs.com" target="_blank"><img src="'+http+'codecogs.izyba.com/images/poweredbycodecogs.png" width="105" height="35" border="0" alt="Powered by CodeCogs" style="vertical-align:-4px"/></a> &nbsp; <a href="http://www.codecogs.com/latex/about.php" target="_blank">About</a> | <a href="http://www.codecogs.com/latex/popup.php" target="_blank">Install</a> | <a href="http://www.codecogs.com/pages/forums/forum_view.php?f=28" target="_blank">Forum</a> | <a href="http://www.codecogs.com" target="_blank">CodeCogs</a> &copy; 2007-2013</div><img id="CCequation'+window.CCounter+'" src="'+http+'www.codecogs.com/images/spacer.gif" />' } ] } ], onLoad : function() { EqEditor.embed('CCtoolbar'+window.CCounter,'','efull'); EqEditor.add(new EqTextArea('CCequation'+window.CCounter, 'CClatex'+window.CCounter), false); }, onShow : function() { var dialog = this, sel = editor.getSelection(), image = sel.getStartElement().getAscendant('img',true); // has the users selected an equation. Make sure we have the image element, include itself if(image) { var sName = image.getAttribute('src').match( /(gif|svg)\.latex\?(.*)/ ); if(sName!=null) EqEditor.getTextArea().setText(sName[2]); dialog.insertMode = true; } // set-up the field values based on selected or newly created image dialog.setupContent( dialog.image ); }, onOk : function() { var eqn = editor.document.createElement( 'img' ); eqn.setAttribute( 'alt', EqEditor.getTextArea().getLaTeX()); eqn.setAttribute( 'src', EqEditor.getTextArea().exportEquation('urlencoded')); editor.insertElement(eqn); } }; });
bsd-3-clause
TomoakiNagahara/ethna
test/ActionForm_Validator_Custom_Test.php
9042
<?php // vim: foldmethod=marker /** * ActionForm_Validator_Custom_Test.php * * @author Yoshinari Takaoka <takaoka@beatcraft.com> * @version $Id$ */ // {{{ Ethna_ActionForm_Validator_Custom_Test /** * Test Case For Ethna_ActionForm(Custom Validator) * * @access public */ class Ethna_ActionForm_Validator_Custom_Test extends Ethna_UnitTestBase { function setUp() { $this->af->use_validator_plugin = false; $this->af->clearFormVars(); $this->af->setDef(null, array()); $this->ae->clear(); } // {{{ checkMailAddress function test_checkMailAddress() { // 'required' => true とすると // Ethna_Plugin_Validator_Required の時点で // エラーになる入力があるためここではfalseに // 設定 $form_string = array( 'type' => VAR_TYPE_STRING, 'required' => false, 'custom' => 'checkMailaddress', ); $this->af->setDef('input', $form_string); $this->af->set('input', 'hoge@fuga.net'); $this->af->validate(); $this->assertFalse($this->ae->isError('input')); $this->ae->clear(); $this->af->set('input', '-hoge@fuga.net'); $this->af->validate(); $this->assertFalse($this->ae->isError('input')); $this->ae->clear(); $this->af->set('input', '.hoge@fuga.net'); $this->af->validate(); $this->assertFalse($this->ae->isError('input')); $this->ae->clear(); $this->af->set('input', '+hoge@fuga.net'); $this->af->validate(); $this->assertFalse($this->ae->isError('input')); $this->ae->clear(); // @がない $this->af->set('input', 'hogefuga.et'); $this->af->validate(); $this->assertTrue($this->ae->isError('input')); $this->ae->clear(); // @の前に文字がない $this->af->set('input', '@hogefuga.et'); $this->af->validate(); $this->assertTrue($this->ae->isError('input')); $this->ae->clear(); // @の後に文字がない $this->af->set('input', 'hogefuga.net@'); $this->af->validate(); $this->assertTrue($this->ae->isError('input')); $this->ae->clear(); // 先頭文字が許されていない $this->af->set('input', '%hoge@fuga.net'); $this->af->validate(); $this->assertTrue($this->ae->isError('input')); $this->ae->clear(); // 末尾文字が許されていない $this->af->set('input', 'hoge@fuga.net.'); $this->af->validate(); $this->assertTrue($this->ae->isError('input')); } // }}} // {{{ checkBoolean function test_checkBoolean() { // 'required' => true とすると // Ethna_Plugin_Validator_Required の時点で // エラーになる入力があるためここではfalseに // 設定 $form_boolean = array( 'type' => VAR_TYPE_BOOLEAN, 'required' => false, 'custom' => 'checkBoolean', ); $this->af->setDef('input', $form_boolean); // HTML フォームから入ってくる値は // 文字列型である。 // @see http://www.php.net/manual/en/types.comparisons.php $this->af->set('input', '0'); $this->af->validate(); $this->assertFalse($this->ae->isError('input')); $this->ae->clear(); $this->af->set('input', '1'); $this->af->validate(); $this->assertFalse($this->ae->isError('input')); $this->ae->clear(); // 空文字列は false と見做すのが仕様 $this->af->set('input', ''); $this->af->validate(); $this->assertFalse($this->ae->isError('input')); $this->ae->clear(); // 0,1, 空文字列以外の値は全てエラー $this->af->set('input', 3); $this->af->validate(); $this->assertTrue($this->ae->isError('input')); $this->ae->clear(); $this->af->set('input', "true"); $this->af->validate(); $this->assertTrue($this->ae->isError('input')); $this->ae->clear(); $this->af->set('input', "false"); $this->af->validate(); $this->assertTrue($this->ae->isError('input')); } // }}} // {{{ checkURL function test_checkURL() { // 'required' => true とすると // Ethna_Plugin_Validator_Required の時点で // エラーになる入力があるためここではfalseに // 設定 $form_url = array( 'type' => VAR_TYPE_STRING, 'required' => false, 'custom' => 'checkURL', ); $this->af->setDef('input', $form_url); $this->af->set('input', 'http://uga.net'); $this->af->validate(); $this->assertFalse($this->ae->isError('input')); $this->ae->clear(); $this->af->set('input', 'https://uga.net'); $this->af->validate(); $this->assertFalse($this->ae->isError('input')); $this->ae->clear(); $this->af->set('input', 'ftp://uga.net'); $this->af->validate(); $this->assertFalse($this->ae->isError('input')); $this->ae->clear(); $this->af->set('input', 'http://'); $this->af->validate(); $this->assertFalse($this->ae->isError('input')); $this->ae->clear(); // 空文字列はエラーにしないのが仕様 $this->af->set('input', ''); $this->af->validate(); $this->assertFalse($this->ae->isError('input')); $this->ae->clear(); // '/'が足りない $this->af->set('input', 'http:/'); $this->af->validate(); $this->assertTrue($this->ae->isError('input')); $this->ae->clear(); // 接頭辞がない $this->af->set('input', 'hoge@fuga.net'); $this->af->validate(); $this->assertTrue($this->ae->isError('input')); } // }}} // {{{ checkVendorChar function test_checkVendorChar() { // 'required' => true とすると // Ethna_Plugin_Validator_Required の時点で // エラーになる入力があるためここではfalseに // 設定 $form_string = array( 'type' => VAR_TYPE_STRING, 'required' => false, 'custom' => 'checkVendorChar', ); $this->af->setDef('input', $form_string); $this->af->set('input', 'http://uga.net'); $this->af->validate(); $this->assertFalse($this->ae->isError('input')); $this->ae->clear(); $this->af->set('input', chr(0x00)); $this->af->validate(); $this->assertFalse($this->ae->isError('input')); $this->ae->clear(); $this->af->set('input', chr(0x79)); $this->af->validate(); $this->assertFalse($this->ae->isError('input')); $this->ae->clear(); $this->af->set('input', chr(0x80)); $this->af->validate(); $this->assertFalse($this->ae->isError('input')); $this->ae->clear(); $this->af->set('input', chr(0x8e)); $this->af->validate(); $this->assertFalse($this->ae->isError('input')); $this->ae->clear(); $this->af->set('input', chr(0x8f)); $this->af->validate(); $this->assertFalse($this->ae->isError('input')); $this->ae->clear(); $this->af->set('input', chr(0xae)); $this->af->validate(); $this->assertFalse($this->ae->isError('input')); $this->ae->clear(); $this->af->set('input', chr(0xf8)); $this->af->validate(); $this->assertFalse($this->ae->isError('input')); $this->ae->clear(); $this->af->set('input', chr(0xfd)); $this->af->validate(); $this->assertFalse($this->ae->isError('input')); $this->ae->clear(); /* IBM拡張文字 / NEC選定IBM拡張文字 */ //$c == 0xad || ($c >= 0xf9 && $c <= 0xfc) $this->af->set('input', chr(0xad)); $this->af->validate(); $this->assertTrue($this->ae->isError('input')); $this->ae->clear(); $this->af->set('input', chr(0xf9)); $this->af->validate(); $this->assertTrue($this->ae->isError('input')); $this->ae->clear(); $this->af->set('input', chr(0xfa)); $this->af->validate(); $this->assertTrue($this->ae->isError('input')); $this->ae->clear(); $this->af->set('input', chr(0xfc)); $this->af->validate(); $this->assertTrue($this->ae->isError('input')); } // }}} } // }}}
bsd-3-clause
LeonidLyalin/vova
common/humhub/protected/humhub/modules/installer/messages/pt/forms_DatabaseForm.php
161
<?php return array ( 'Hostname' => 'Nome do hospedeiro', 'Name of Database' => '', 'Password' => 'Palavra-passe', 'Username' => 'Nome de utilizador', );
bsd-3-clause
UgurAldanmaz/NLog
tests/NLog.UnitTests/Contexts/MappedDiagnosticsLogicalContextTests.cs
15901
// // Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // 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 Jaroslaw Kowalski 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. // using System.Linq; using System.Threading; namespace NLog.UnitTests.Contexts { using System; using System.Collections.Generic; using System.Threading.Tasks; using Xunit; public class MappedDiagnosticsLogicalContextTests { public MappedDiagnosticsLogicalContextTests() { MappedDiagnosticsLogicalContext.Clear(); } [Fact] public void given_item_exists_when_getting_item_should_return_item_for_objecttype_2() { string key = "testKey1"; object value = 5; MappedDiagnosticsLogicalContext.Set(key, value); string expected = "5"; string actual = MappedDiagnosticsLogicalContext.Get(key); Assert.Equal(expected, actual); } [Fact] public void given_item_exists_when_getting_item_should_return_item_for_objecttype() { string key = "testKey2"; object value = DateTime.Now; MappedDiagnosticsLogicalContext.Set(key, value); object actual = MappedDiagnosticsLogicalContext.GetObject(key); Assert.Equal(value, actual); } [Fact] public void given_no_item_exists_when_getting_item_should_return_null() { Assert.Null(MappedDiagnosticsLogicalContext.GetObject("itemThatShouldNotExist")); } [Fact] public void given_no_item_exists_when_getting_item_should_return_empty_string() { Assert.Empty(MappedDiagnosticsLogicalContext.Get("itemThatShouldNotExist")); } [Fact] public void given_item_exists_when_getting_item_should_return_item() { const string key = "Key"; const string item = "Item"; MappedDiagnosticsLogicalContext.Set(key, item); Assert.Equal(item, MappedDiagnosticsLogicalContext.Get(key)); } [Fact] public void given_item_does_not_exist_when_setting_item_should_contain_item() { const string key = "Key"; const string item = "Item"; MappedDiagnosticsLogicalContext.Set(key, item); Assert.True(MappedDiagnosticsLogicalContext.Contains(key)); } [Fact] public void given_item_exists_when_setting_item_should_not_throw() { const string key = "Key"; const string item = "Item"; MappedDiagnosticsLogicalContext.Set(key, item); var exRecorded = Record.Exception(() => MappedDiagnosticsLogicalContext.Set(key, item)); Assert.Null(exRecorded); } [Fact] public void given_item_exists_when_setting_item_should_update_item() { const string key = "Key"; const string item = "Item"; const string newItem = "NewItem"; MappedDiagnosticsLogicalContext.Set(key, item); MappedDiagnosticsLogicalContext.Set(key, newItem); Assert.Equal(newItem, MappedDiagnosticsLogicalContext.Get(key)); } [Fact] public void given_no_item_exists_when_getting_items_should_return_empty_collection() { Assert.Equal(0,MappedDiagnosticsLogicalContext.GetNames().Count); } [Fact] public void given_item_exists_when_getting_items_should_return_that_item() { const string key = "Key"; MappedDiagnosticsLogicalContext.Set(key, "Item"); Assert.Equal(1, MappedDiagnosticsLogicalContext.GetNames().Count); Assert.True(MappedDiagnosticsLogicalContext.GetNames().Contains("Key")); } [Fact] public void given_item_exists_after_removing_item_when_getting_items_should_not_contain_item() { const string keyThatRemains1 = "Key1"; const string keyThatRemains2 = "Key2"; const string keyThatIsRemoved = "KeyR"; MappedDiagnosticsLogicalContext.Set(keyThatRemains1, "7"); MappedDiagnosticsLogicalContext.Set(keyThatIsRemoved, 7); MappedDiagnosticsLogicalContext.Set(keyThatRemains2, 8); MappedDiagnosticsLogicalContext.Remove(keyThatIsRemoved); Assert.Equal(2, MappedDiagnosticsLogicalContext.GetNames().Count); Assert.False(MappedDiagnosticsLogicalContext.GetNames().Contains(keyThatIsRemoved)); } [Fact] public void given_item_does_not_exist_when_checking_if_context_contains_should_return_false() { Assert.False(MappedDiagnosticsLogicalContext.Contains("keyForItemThatDoesNotExist")); } [Fact] public void given_item_exists_when_checking_if_context_contains_should_return_true() { const string key = "Key"; MappedDiagnosticsLogicalContext.Set(key, "Item"); Assert.True(MappedDiagnosticsLogicalContext.Contains(key)); } [Fact] public void given_item_exists_when_removing_item_should_not_contain_item() { const string keyForItemThatShouldExist = "Key"; const string itemThatShouldExist = "Item"; MappedDiagnosticsLogicalContext.Set(keyForItemThatShouldExist, itemThatShouldExist); MappedDiagnosticsLogicalContext.Remove(keyForItemThatShouldExist); Assert.False(MappedDiagnosticsLogicalContext.Contains(keyForItemThatShouldExist)); } [Fact] public void given_item_does_not_exist_when_removing_item_should_not_throw() { const string keyForItemThatShouldExist = "Key"; var exRecorded = Record.Exception(() => MappedDiagnosticsLogicalContext.Remove(keyForItemThatShouldExist)); Assert.Null(exRecorded); } [Fact] public void given_item_does_not_exist_when_clearing_should_not_throw() { var exRecorded = Record.Exception(() => MappedDiagnosticsLogicalContext.Clear()); Assert.Null(exRecorded); } [Fact] public void given_item_exists_when_clearing_should_not_contain_item() { const string key = "Key"; MappedDiagnosticsLogicalContext.Set(key, "Item"); MappedDiagnosticsLogicalContext.Clear(); Assert.False(MappedDiagnosticsLogicalContext.Contains(key)); } [Fact] public void given_multiple_threads_running_asynchronously_when_setting_and_getting_values_should_return_thread_specific_values() { const string key = "Key"; const string valueForLogicalThread1 = "ValueForTask1"; const string valueForLogicalThread2 = "ValueForTask2"; const string valueForLogicalThread3 = "ValueForTask3"; MappedDiagnosticsLogicalContext.Clear(true); var task1 = Task.Factory.StartNew(() => { MappedDiagnosticsLogicalContext.Set(key, valueForLogicalThread1); return MappedDiagnosticsLogicalContext.Get(key); }); var task2 = Task.Factory.StartNew(() => { MappedDiagnosticsLogicalContext.Set(key, valueForLogicalThread2); return MappedDiagnosticsLogicalContext.Get(key); }); var task3 = Task.Factory.StartNew(() => { MappedDiagnosticsLogicalContext.Set(key, valueForLogicalThread3); return MappedDiagnosticsLogicalContext.Get(key); }); Task.WaitAll(); Assert.Equal(task1.Result, valueForLogicalThread1); Assert.Equal(task2.Result, valueForLogicalThread2); Assert.Equal(task3.Result, valueForLogicalThread3); } [Fact] public void parent_thread_assigns_different_values_to_childs() { const string parentKey = "ParentKey"; const string parentValueForLogicalThread1 = "Parent1"; const string parentValueForLogicalThread2 = "Parent2"; const string childKey = "ChildKey"; const string valueForChildThread1 = "Child1"; const string valueForChildThread2 = "Child2"; MappedDiagnosticsLogicalContext.Clear(true); var exitAllTasks = new ManualResetEvent(false); MappedDiagnosticsLogicalContext.Set(parentKey, parentValueForLogicalThread1); var task1 = Task.Factory.StartNew(() => { MappedDiagnosticsLogicalContext.Set(childKey, valueForChildThread1); exitAllTasks.WaitOne(); return MappedDiagnosticsLogicalContext.Get(parentKey) + "," + MappedDiagnosticsLogicalContext.Get(childKey); }); MappedDiagnosticsLogicalContext.Set(parentKey, parentValueForLogicalThread2); var task2 = Task.Factory.StartNew(() => { MappedDiagnosticsLogicalContext.Set(childKey, valueForChildThread2); exitAllTasks.WaitOne(); return MappedDiagnosticsLogicalContext.Get(parentKey) + "," + MappedDiagnosticsLogicalContext.Get(childKey); }); exitAllTasks.Set(); Task.WaitAll(); Assert.Equal(task1.Result, parentValueForLogicalThread1 + "," + valueForChildThread1); Assert.Equal(task2.Result, parentValueForLogicalThread2 + "," + valueForChildThread2); } [Fact] public void timer_cannot_inherit_mappedcontext() { object getObject = null; string getValue = null; var mre = new ManualResetEvent(false); Timer thread = new Timer((s) => { try { getObject = MappedDiagnosticsLogicalContext.GetObject("DoNotExist"); getValue = MappedDiagnosticsLogicalContext.Get("DoNotExistEither"); } finally { mre.Set(); } }); thread.Change(0, Timeout.Infinite); mre.WaitOne(); Assert.Null(getObject); Assert.Empty(getValue); } [Fact] public void disposable_removes_item() { const string itemNotRemovedKey = "itemNotRemovedKey"; const string itemRemovedKey = "itemRemovedKey"; MappedDiagnosticsLogicalContext.Clear(); MappedDiagnosticsLogicalContext.Set(itemNotRemovedKey, "itemNotRemoved"); using (MappedDiagnosticsLogicalContext.SetScoped(itemRemovedKey, "itemRemoved")) { Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { itemNotRemovedKey, itemRemovedKey }); } Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { itemNotRemovedKey }); } [Fact] public void dispose_is_idempotent() { const string itemKey = "itemKey"; MappedDiagnosticsLogicalContext.Clear(); IDisposable disposable = MappedDiagnosticsLogicalContext.SetScoped(itemKey, "item1"); disposable.Dispose(); Assert.False(MappedDiagnosticsLogicalContext.Contains(itemKey)); //This item shouldn't be removed since it is not the disposable one MappedDiagnosticsLogicalContext.Set(itemKey, "item2"); disposable.Dispose(); Assert.True(MappedDiagnosticsLogicalContext.Contains(itemKey)); } #if NET4_5 [Fact] public void disposable_multiple_items() { const string itemNotRemovedKey = "itemNotRemovedKey"; const string item1Key = "item1Key"; const string item2Key = "item2Key"; const string item3Key = "item3Key"; const string item4Key = "item4Key"; MappedDiagnosticsLogicalContext.Clear(); MappedDiagnosticsLogicalContext.Set(itemNotRemovedKey, "itemNotRemoved"); using (MappedDiagnosticsLogicalContext.SetScoped(new[] { new KeyValuePair<string, object>(item1Key, "1"), new KeyValuePair<string, object>(item2Key, "2") })) { Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { itemNotRemovedKey, item1Key, item2Key }); } Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { itemNotRemovedKey }); using (MappedDiagnosticsLogicalContext.SetScoped(new[] { new KeyValuePair<string, object>(item1Key, "1"), new KeyValuePair<string, object>(item2Key, "2"), new KeyValuePair<string, object>(item3Key, "3"), new KeyValuePair<string, object>(item4Key, "4") })) { Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { itemNotRemovedKey, item1Key, item2Key, item3Key, item4Key }); } Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { itemNotRemovedKey }); } [Fact] public void disposable_fast_clear_multiple_items() { const string item1Key = "item1Key"; const string item2Key = "item2Key"; const string item3Key = "item3Key"; const string item4Key = "item4Key"; MappedDiagnosticsLogicalContext.Clear(); using (MappedDiagnosticsLogicalContext.SetScoped(new[] { new KeyValuePair<string, object>(item1Key, "1"), new KeyValuePair<string, object>(item2Key, "2") })) { Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { item1Key, item2Key }); } Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new string[] { }); using (MappedDiagnosticsLogicalContext.SetScoped(new[] { new KeyValuePair<string, object>(item1Key, "1"), new KeyValuePair<string, object>(item2Key, "2"), new KeyValuePair<string, object>(item3Key, "3"), new KeyValuePair<string, object>(item4Key, "4") })) { Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { item1Key, item2Key, item3Key, item4Key }); } Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new string[] { }); } #endif } }
bsd-3-clause
pbrunet/pythran
third_party/nt2/trigonometric/functions/scalar/impl/trigo/fallback.hpp
1245
//============================================================================== // Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef NT2_TRIGONOMETRIC_FUNCTIONS_SCALAR_IMPL_TRIGO_FALLBACK_HPP_INCLUDED #define NT2_TRIGONOMETRIC_FUNCTIONS_SCALAR_IMPL_TRIGO_FALLBACK_HPP_INCLUDED #include <cmath> namespace nt2 { namespace details { class standard_tag{}; template <class tag > struct fallback { template < class T > static inline T cos(T x){return std::cos(x); } template < class T > static inline T sin(T x){return std::sin(x); } template < class T > static inline T tan(T x){return std::tan(x); } // functor<standard::cospi_> _cospi; // functor<standard::sinpi_> _sinpi; // functor<standard::tanpi_> _tanpi; }; #ifndef FALLBACK_TAG #define FALLBACK_TAG standard_tag #endif } } #endif
bsd-3-clause
statsmodels/statsmodels
statsmodels/datasets/anes96/data.py
3687
"""American National Election Survey 1996""" from numpy import log from statsmodels.datasets import utils as du __docformat__ = 'restructuredtext' COPYRIGHT = """This is public domain.""" TITLE = __doc__ SOURCE = """ http://www.electionstudies.org/ The American National Election Studies. """ DESCRSHORT = """This data is a subset of the American National Election Studies of 1996.""" DESCRLONG = DESCRSHORT NOTE = """:: Number of observations - 944 Number of variables - 10 Variables name definitions:: popul - Census place population in 1000s TVnews - Number of times per week that respondent watches TV news. PID - Party identification of respondent. 0 - Strong Democrat 1 - Weak Democrat 2 - Independent-Democrat 3 - Independent-Indpendent 4 - Independent-Republican 5 - Weak Republican 6 - Strong Republican age : Age of respondent. educ - Education level of respondent 1 - 1-8 grades 2 - Some high school 3 - High school graduate 4 - Some college 5 - College degree 6 - Master's degree 7 - PhD income - Income of household 1 - None or less than $2,999 2 - $3,000-$4,999 3 - $5,000-$6,999 4 - $7,000-$8,999 5 - $9,000-$9,999 6 - $10,000-$10,999 7 - $11,000-$11,999 8 - $12,000-$12,999 9 - $13,000-$13,999 10 - $14,000-$14.999 11 - $15,000-$16,999 12 - $17,000-$19,999 13 - $20,000-$21,999 14 - $22,000-$24,999 15 - $25,000-$29,999 16 - $30,000-$34,999 17 - $35,000-$39,999 18 - $40,000-$44,999 19 - $45,000-$49,999 20 - $50,000-$59,999 21 - $60,000-$74,999 22 - $75,000-89,999 23 - $90,000-$104,999 24 - $105,000 and over vote - Expected vote 0 - Clinton 1 - Dole The following 3 variables all take the values: 1 - Extremely liberal 2 - Liberal 3 - Slightly liberal 4 - Moderate 5 - Slightly conservative 6 - Conservative 7 - Extremely Conservative selfLR - Respondent's self-reported political leanings from "Left" to "Right". ClinLR - Respondents impression of Bill Clinton's political leanings from "Left" to "Right". DoleLR - Respondents impression of Bob Dole's political leanings from "Left" to "Right". logpopul - log(popul + .1) """ def load_pandas(): """Load the anes96 data and returns a Dataset class. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information. """ data = _get_data() return du.process_pandas(data, endog_idx=5, exog_idx=[10, 2, 6, 7, 8]) def load(): """Load the anes96 data and returns a Dataset class. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information. """ return load_pandas() def _get_data(): data = du.load_csv(__file__, 'anes96.csv', sep=r'\s') data = du.strip_column_names(data) data['logpopul'] = log(data['popul'] + .1) return data.astype(float)
bsd-3-clause
leiferikb/bitpop-private
chrome/browser/chromeos/options/wifi_config_view.cc
45928
// Copyright (c) 2012 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 "chrome/browser/chromeos/options/wifi_config_view.h" #include "base/string_util.h" #include "base/stringprintf.h" #include "base/utf_string_conversions.h" #include "chrome/browser/chromeos/cros/cros_library.h" #include "chrome/browser/chromeos/cros/network_library.h" #include "chrome/browser/chromeos/enrollment_dialog_view.h" #include "chrome/browser/chromeos/login/user_manager.h" #include "chrome/browser/profiles/profile_manager.h" #include "chromeos/network/onc/onc_constants.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "grit/locale_settings.h" #include "grit/theme_resources.h" #include "ui/base/events/event.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "ui/views/controls/button/checkbox.h" #include "ui/views/controls/button/image_button.h" #include "ui/views/controls/combobox/combobox.h" #include "ui/views/controls/label.h" #include "ui/views/controls/textfield/textfield.h" #include "ui/views/layout/grid_layout.h" #include "ui/views/layout/layout_constants.h" #include "ui/views/widget/widget.h" #include "ui/views/window/dialog_client_view.h" namespace chromeos { namespace { // Returns true if network is known to require 802.1x. bool Is8021x(const WifiNetwork* wifi) { return wifi && wifi->encrypted() && wifi->encryption() == SECURITY_8021X; } // Combobox that supports a preferred width. Used by Server CA combobox // because the strings inside it are too wide. class ComboboxWithWidth : public views::Combobox { public: ComboboxWithWidth(ui::ComboboxModel* model, int width) : Combobox(model), width_(width) { } virtual ~ComboboxWithWidth() {} virtual gfx::Size GetPreferredSize() OVERRIDE { gfx::Size size = Combobox::GetPreferredSize(); size.set_width(width_); return size; } private: int width_; DISALLOW_COPY_AND_ASSIGN(ComboboxWithWidth); }; enum SecurityComboboxIndex { SECURITY_INDEX_NONE = 0, SECURITY_INDEX_WEP = 1, SECURITY_INDEX_PSK = 2, SECURITY_INDEX_COUNT = 3 }; // Methods in alphabetical order. enum EAPMethodComboboxIndex { EAP_METHOD_INDEX_NONE = 0, EAP_METHOD_INDEX_LEAP = 1, EAP_METHOD_INDEX_PEAP = 2, EAP_METHOD_INDEX_TLS = 3, EAP_METHOD_INDEX_TTLS = 4, EAP_METHOD_INDEX_COUNT = 5 }; enum Phase2AuthComboboxIndex { PHASE_2_AUTH_INDEX_AUTO = 0, // LEAP, EAP-TLS have only this auth. PHASE_2_AUTH_INDEX_MD5 = 1, PHASE_2_AUTH_INDEX_MSCHAPV2 = 2, // PEAP has up to this auth. PHASE_2_AUTH_INDEX_MSCHAP = 3, PHASE_2_AUTH_INDEX_PAP = 4, PHASE_2_AUTH_INDEX_CHAP = 5, // EAP-TTLS has up to this auth. PHASE_2_AUTH_INDEX_COUNT = 6 }; } // namespace namespace internal { class SecurityComboboxModel : public ui::ComboboxModel { public: SecurityComboboxModel(); virtual ~SecurityComboboxModel(); // Overridden from ui::ComboboxModel: virtual int GetItemCount() const OVERRIDE; virtual string16 GetItemAt(int index) OVERRIDE; private: DISALLOW_COPY_AND_ASSIGN(SecurityComboboxModel); }; class EAPMethodComboboxModel : public ui::ComboboxModel { public: EAPMethodComboboxModel(); virtual ~EAPMethodComboboxModel(); // Overridden from ui::ComboboxModel: virtual int GetItemCount() const OVERRIDE; virtual string16 GetItemAt(int index) OVERRIDE; private: DISALLOW_COPY_AND_ASSIGN(EAPMethodComboboxModel); }; class Phase2AuthComboboxModel : public ui::ComboboxModel { public: explicit Phase2AuthComboboxModel(views::Combobox* eap_method_combobox); virtual ~Phase2AuthComboboxModel(); // Overridden from ui::ComboboxModel: virtual int GetItemCount() const OVERRIDE; virtual string16 GetItemAt(int index) OVERRIDE; private: views::Combobox* eap_method_combobox_; DISALLOW_COPY_AND_ASSIGN(Phase2AuthComboboxModel); }; class ServerCACertComboboxModel : public ui::ComboboxModel { public: explicit ServerCACertComboboxModel(CertLibrary* cert_library); virtual ~ServerCACertComboboxModel(); // Overridden from ui::ComboboxModel: virtual int GetItemCount() const OVERRIDE; virtual string16 GetItemAt(int index) OVERRIDE; private: CertLibrary* cert_library_; DISALLOW_COPY_AND_ASSIGN(ServerCACertComboboxModel); }; class UserCertComboboxModel : public ui::ComboboxModel { public: explicit UserCertComboboxModel(CertLibrary* cert_library); virtual ~UserCertComboboxModel(); // Overridden from ui::ComboboxModel: virtual int GetItemCount() const OVERRIDE; virtual string16 GetItemAt(int index) OVERRIDE; private: CertLibrary* cert_library_; DISALLOW_COPY_AND_ASSIGN(UserCertComboboxModel); }; // SecurityComboboxModel ------------------------------------------------------- SecurityComboboxModel::SecurityComboboxModel() { } SecurityComboboxModel::~SecurityComboboxModel() { } int SecurityComboboxModel::GetItemCount() const { return SECURITY_INDEX_COUNT; } string16 SecurityComboboxModel::GetItemAt(int index) { if (index == SECURITY_INDEX_NONE) return l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_SECURITY_NONE); else if (index == SECURITY_INDEX_WEP) return l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_SECURITY_WEP); else if (index == SECURITY_INDEX_PSK) return l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_SECURITY_PSK); NOTREACHED(); return string16(); } // EAPMethodComboboxModel ------------------------------------------------------ EAPMethodComboboxModel::EAPMethodComboboxModel() { } EAPMethodComboboxModel::~EAPMethodComboboxModel() { } int EAPMethodComboboxModel::GetItemCount() const { return EAP_METHOD_INDEX_COUNT; } string16 EAPMethodComboboxModel::GetItemAt(int index) { if (index == EAP_METHOD_INDEX_NONE) return l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_EAP_METHOD_NONE); else if (index == EAP_METHOD_INDEX_LEAP) return l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_EAP_METHOD_LEAP); else if (index == EAP_METHOD_INDEX_PEAP) return l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_EAP_METHOD_PEAP); else if (index == EAP_METHOD_INDEX_TLS) return l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_EAP_METHOD_TLS); else if (index == EAP_METHOD_INDEX_TTLS) return l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_EAP_METHOD_TTLS); NOTREACHED(); return string16(); } // Phase2AuthComboboxModel ----------------------------------------------------- Phase2AuthComboboxModel::Phase2AuthComboboxModel( views::Combobox* eap_method_combobox) : eap_method_combobox_(eap_method_combobox) { } Phase2AuthComboboxModel::~Phase2AuthComboboxModel() { } int Phase2AuthComboboxModel::GetItemCount() const { switch (eap_method_combobox_->selected_index()) { case EAP_METHOD_INDEX_NONE: case EAP_METHOD_INDEX_TLS: case EAP_METHOD_INDEX_LEAP: return PHASE_2_AUTH_INDEX_AUTO + 1; case EAP_METHOD_INDEX_PEAP: return PHASE_2_AUTH_INDEX_MSCHAPV2 + 1; case EAP_METHOD_INDEX_TTLS: return PHASE_2_AUTH_INDEX_CHAP + 1; } NOTREACHED(); return 0; } string16 Phase2AuthComboboxModel::GetItemAt(int index) { if (index == PHASE_2_AUTH_INDEX_AUTO) return l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_PHASE_2_AUTH_AUTO); else if (index == PHASE_2_AUTH_INDEX_MD5) return l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_PHASE_2_AUTH_MD5); else if (index == PHASE_2_AUTH_INDEX_MSCHAPV2) return l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_PHASE_2_AUTH_MSCHAPV2); else if (index == PHASE_2_AUTH_INDEX_MSCHAP) return l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_PHASE_2_AUTH_MSCHAP); else if (index == PHASE_2_AUTH_INDEX_PAP) return l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_PHASE_2_AUTH_PAP); else if (index == PHASE_2_AUTH_INDEX_CHAP) return l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_PHASE_2_AUTH_CHAP); NOTREACHED(); return string16(); } // ServerCACertComboboxModel --------------------------------------------------- ServerCACertComboboxModel::ServerCACertComboboxModel(CertLibrary* cert_library) : cert_library_(cert_library) { DCHECK(cert_library); } ServerCACertComboboxModel::~ServerCACertComboboxModel() { } int ServerCACertComboboxModel::GetItemCount() const { if (cert_library_->CertificatesLoading()) return 1; // "Loading" // First "Default", then the certs, then "Do not check". return cert_library_->GetCACertificates().Size() + 2; } string16 ServerCACertComboboxModel::GetItemAt(int index) { if (cert_library_->CertificatesLoading()) return l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_CERT_LOADING); if (index == 0) return l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_CERT_SERVER_CA_DEFAULT); if (index == GetItemCount() - 1) return l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_CERT_SERVER_CA_DO_NOT_CHECK); int cert_index = index - 1; return cert_library_->GetCACertificates().GetDisplayStringAt(cert_index); } // UserCertComboboxModel ------------------------------------------------------- UserCertComboboxModel::UserCertComboboxModel(CertLibrary* cert_library) : cert_library_(cert_library) { DCHECK(cert_library); } UserCertComboboxModel::~UserCertComboboxModel() { } int UserCertComboboxModel::GetItemCount() const { if (cert_library_->CertificatesLoading()) return 1; // "Loading" int num_certs = cert_library_->GetUserCertificates().Size(); if (num_certs == 0) return 1; // "None installed" return num_certs; } string16 UserCertComboboxModel::GetItemAt(int index) { if (cert_library_->CertificatesLoading()) return l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_CERT_LOADING); if (cert_library_->GetUserCertificates().Size() == 0) return l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_USER_CERT_NONE_INSTALLED); return cert_library_->GetUserCertificates().GetDisplayStringAt(index); } } // namespace internal WifiConfigView::WifiConfigView(NetworkConfigView* parent, WifiNetwork* wifi) : ChildNetworkConfigView(parent, wifi), cert_library_(NULL), ssid_textfield_(NULL), eap_method_combobox_(NULL), phase_2_auth_label_(NULL), phase_2_auth_combobox_(NULL), user_cert_label_(NULL), user_cert_combobox_(NULL), server_ca_cert_label_(NULL), server_ca_cert_combobox_(NULL), identity_label_(NULL), identity_textfield_(NULL), identity_anonymous_label_(NULL), identity_anonymous_textfield_(NULL), save_credentials_checkbox_(NULL), share_network_checkbox_(NULL), shared_network_label_(NULL), security_combobox_(NULL), passphrase_label_(NULL), passphrase_textfield_(NULL), passphrase_visible_button_(NULL), error_label_(NULL) { Init(wifi, Is8021x(wifi)); } WifiConfigView::WifiConfigView(NetworkConfigView* parent, bool show_8021x) : ChildNetworkConfigView(parent), cert_library_(NULL), ssid_textfield_(NULL), eap_method_combobox_(NULL), phase_2_auth_label_(NULL), phase_2_auth_combobox_(NULL), user_cert_label_(NULL), user_cert_combobox_(NULL), server_ca_cert_label_(NULL), server_ca_cert_combobox_(NULL), identity_label_(NULL), identity_textfield_(NULL), identity_anonymous_label_(NULL), identity_anonymous_textfield_(NULL), save_credentials_checkbox_(NULL), share_network_checkbox_(NULL), shared_network_label_(NULL), security_combobox_(NULL), passphrase_label_(NULL), passphrase_textfield_(NULL), passphrase_visible_button_(NULL), error_label_(NULL) { Init(NULL, show_8021x); } WifiConfigView::~WifiConfigView() { if (cert_library_) cert_library_->RemoveObserver(this); } views::View* WifiConfigView::GetInitiallyFocusedView() { // Return a reasonable widget for initial focus, // depending on what we're showing. if (ssid_textfield_) return ssid_textfield_; else if (eap_method_combobox_) return eap_method_combobox_; else if (passphrase_textfield_ && passphrase_textfield_->enabled()) return passphrase_textfield_; else return NULL; } bool WifiConfigView::CanLogin() { static const size_t kMinWirelessPasswordLen = 5; // We either have an existing wifi network or the user entered an SSID. if (service_path_.empty() && GetSsid().empty()) return false; // If the network requires a passphrase, make sure it is the right length. if (passphrase_textfield_ != NULL && passphrase_textfield_->enabled() && passphrase_textfield_->text().length() < kMinWirelessPasswordLen) return false; // If we're using EAP, we must have a method. if (eap_method_combobox_ && eap_method_combobox_->selected_index() == EAP_METHOD_INDEX_NONE) return false; // Block login if certs are required but user has none. if (UserCertRequired() && (!HaveUserCerts() || !IsUserCertValid())) return false; return true; } bool WifiConfigView::UserCertRequired() const { if (!cert_library_) return false; // return false until cert_library_ is initialized. return UserCertActive(); } bool WifiConfigView::HaveUserCerts() const { return cert_library_->GetUserCertificates().Size() > 0; } bool WifiConfigView::IsUserCertValid() const { if (!UserCertActive()) return false; int index = user_cert_combobox_->selected_index(); if (index < 0) return false; // Currently only hardware-backed user certificates are valid. if (cert_library_->IsHardwareBacked() && !cert_library_->GetUserCertificates().IsHardwareBackedAt(index)) return false; return true; } bool WifiConfigView::Phase2AuthActive() const { if (phase_2_auth_combobox_) return phase_2_auth_combobox_->model()->GetItemCount() > 1; return false; } bool WifiConfigView::PassphraseActive() const { if (eap_method_combobox_) { // No password for EAP-TLS. int index = eap_method_combobox_->selected_index(); return index != EAP_METHOD_INDEX_NONE && index != EAP_METHOD_INDEX_TLS; } else if (security_combobox_) { return security_combobox_->selected_index() != SECURITY_INDEX_NONE; } return false; } bool WifiConfigView::UserCertActive() const { // User certs only for EAP-TLS. if (eap_method_combobox_) return eap_method_combobox_->selected_index() == EAP_METHOD_INDEX_TLS; return false; } bool WifiConfigView::CaCertActive() const { // No server CA certs for LEAP. if (eap_method_combobox_) { int index = eap_method_combobox_->selected_index(); return index != EAP_METHOD_INDEX_NONE && index != EAP_METHOD_INDEX_LEAP; } return false; } void WifiConfigView::UpdateDialogButtons() { parent_->GetDialogClientView()->UpdateDialogButtons(); } void WifiConfigView::RefreshEapFields() { DCHECK(cert_library_); // If EAP method changes, the phase 2 auth choices may have changed also. phase_2_auth_combobox_->ModelChanged(); phase_2_auth_combobox_->SetSelectedIndex(0); bool phase_2_auth_enabled = Phase2AuthActive(); phase_2_auth_combobox_->SetEnabled(phase_2_auth_enabled && phase_2_auth_ui_data_.editable()); phase_2_auth_label_->SetEnabled(phase_2_auth_enabled); // Passphrase. bool passphrase_enabled = PassphraseActive(); passphrase_textfield_->SetEnabled(passphrase_enabled && passphrase_ui_data_.editable()); passphrase_label_->SetEnabled(passphrase_enabled); if (!passphrase_enabled) passphrase_textfield_->SetText(string16()); // User cert. bool certs_loading = cert_library_->CertificatesLoading(); bool user_cert_enabled = UserCertActive(); user_cert_label_->SetEnabled(user_cert_enabled); bool have_user_certs = !certs_loading && HaveUserCerts(); user_cert_combobox_->SetEnabled(user_cert_enabled && have_user_certs && user_cert_ui_data_.editable()); user_cert_combobox_->ModelChanged(); user_cert_combobox_->SetSelectedIndex(0); // Server CA. bool ca_cert_enabled = CaCertActive(); server_ca_cert_label_->SetEnabled(ca_cert_enabled); server_ca_cert_combobox_->SetEnabled(ca_cert_enabled && !certs_loading && server_ca_cert_ui_data_.editable()); server_ca_cert_combobox_->ModelChanged(); server_ca_cert_combobox_->SetSelectedIndex(0); // No anonymous identity if no phase 2 auth. bool identity_anonymous_enabled = phase_2_auth_enabled; identity_anonymous_textfield_->SetEnabled( identity_anonymous_enabled && identity_anonymous_ui_data_.editable()); identity_anonymous_label_->SetEnabled(identity_anonymous_enabled); if (!identity_anonymous_enabled) identity_anonymous_textfield_->SetText(string16()); RefreshShareCheckbox(); } void WifiConfigView::RefreshShareCheckbox() { if (!share_network_checkbox_) return; if (security_combobox_ && security_combobox_->selected_index() == SECURITY_INDEX_NONE) { share_network_checkbox_->SetEnabled(false); share_network_checkbox_->SetChecked(true); } else if (eap_method_combobox_ && (eap_method_combobox_->selected_index() == EAP_METHOD_INDEX_TLS || user_cert_combobox_->selected_index() != 0)) { // Can not share TLS network (requires certificate), or any network where // user certificates are enabled. share_network_checkbox_->SetEnabled(false); share_network_checkbox_->SetChecked(false); } else if (!UserManager::Get()->IsUserLoggedIn()) { // If not logged in, networks must be shared. share_network_checkbox_->SetEnabled(false); share_network_checkbox_->SetChecked(true); } else { share_network_checkbox_->SetEnabled(true); share_network_checkbox_->SetChecked(false); // Default to unshared. } } void WifiConfigView::UpdateErrorLabel() { std::string error_msg; if (UserCertRequired() && cert_library_->CertificatesLoaded()) { if (!HaveUserCerts()) { if (!UserManager::Get()->IsUserLoggedIn()) { error_msg = l10n_util::GetStringUTF8( IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_LOGIN_FOR_USER_CERT); } else { error_msg = l10n_util::GetStringUTF8( IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_PLEASE_INSTALL_USER_CERT); } } else if (!IsUserCertValid()) { error_msg = l10n_util::GetStringUTF8( IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_REQUIRE_HARDWARE_BACKED); } } if (error_msg.empty() && !service_path_.empty()) { NetworkLibrary* cros = CrosLibrary::Get()->GetNetworkLibrary(); const WifiNetwork* wifi = cros->FindWifiNetworkByPath(service_path_); if (wifi && wifi->failed()) { bool passphrase_empty = wifi->GetPassphrase().empty(); switch (wifi->error()) { case ERROR_BAD_PASSPHRASE: if (!passphrase_empty) { error_msg = l10n_util::GetStringUTF8( IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_BAD_PASSPHRASE); } break; case ERROR_BAD_WEPKEY: if (!passphrase_empty) { error_msg = l10n_util::GetStringUTF8( IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_BAD_WEPKEY); } break; default: error_msg = wifi->GetErrorString(); break; } } } if (!error_msg.empty()) { error_label_->SetText(UTF8ToUTF16(error_msg)); error_label_->SetVisible(true); } else { error_label_->SetVisible(false); } } void WifiConfigView::ContentsChanged(views::Textfield* sender, const string16& new_contents) { UpdateDialogButtons(); } bool WifiConfigView::HandleKeyEvent(views::Textfield* sender, const ui::KeyEvent& key_event) { if (sender == passphrase_textfield_ && key_event.key_code() == ui::VKEY_RETURN) { parent_->GetDialogClientView()->AcceptWindow(); } return false; } void WifiConfigView::ButtonPressed(views::Button* sender, const ui::Event& event) { if (sender == passphrase_visible_button_) { if (passphrase_textfield_) { passphrase_textfield_->SetObscured(!passphrase_textfield_->IsObscured()); passphrase_visible_button_->SetToggled( !passphrase_textfield_->IsObscured()); } } else { NOTREACHED(); } } void WifiConfigView::OnSelectedIndexChanged(views::Combobox* combobox) { if (combobox == security_combobox_) { bool passphrase_enabled = PassphraseActive(); passphrase_label_->SetEnabled(passphrase_enabled); passphrase_textfield_->SetEnabled(passphrase_enabled && passphrase_ui_data_.editable()); if (!passphrase_enabled) passphrase_textfield_->SetText(string16()); RefreshShareCheckbox(); } else if (combobox == user_cert_combobox_) { RefreshShareCheckbox(); } else if (combobox == eap_method_combobox_) { RefreshEapFields(); } UpdateDialogButtons(); UpdateErrorLabel(); } void WifiConfigView::OnCertificatesLoaded(bool initial_load) { RefreshEapFields(); UpdateDialogButtons(); UpdateErrorLabel(); } bool WifiConfigView::Login() { NetworkLibrary* cros = CrosLibrary::Get()->GetNetworkLibrary(); if (service_path_.empty()) { const bool share_default = true; // share networks by default if (!eap_method_combobox_) { // Hidden ordinary Wi-Fi connection. ConnectionSecurity security = SECURITY_UNKNOWN; switch (security_combobox_->selected_index()) { case SECURITY_INDEX_NONE: security = SECURITY_NONE; break; case SECURITY_INDEX_WEP: security = SECURITY_WEP; break; case SECURITY_INDEX_PSK: security = SECURITY_PSK; break; } cros->ConnectToUnconfiguredWifiNetwork( GetSsid(), security, GetPassphrase(), NULL, GetSaveCredentials(), GetShareNetwork(share_default)); } else { // Hidden 802.1X EAP Wi-Fi connection. chromeos::NetworkLibrary::EAPConfigData config_data; config_data.method = GetEapMethod(); config_data.auth = GetEapPhase2Auth(); config_data.server_ca_cert_nss_nickname = GetEapServerCaCertNssNickname(); config_data.use_system_cas = GetEapUseSystemCas(); config_data.client_cert_pkcs11_id = GetEapClientCertPkcs11Id(); config_data.identity = GetEapIdentity(); config_data.anonymous_identity = GetEapAnonymousIdentity(); cros->ConnectToUnconfiguredWifiNetwork( GetSsid(), SECURITY_8021X, GetPassphrase(), &config_data, GetSaveCredentials(), GetShareNetwork(share_default)); } } else { WifiNetwork* wifi = cros->FindWifiNetworkByPath(service_path_); if (!wifi) { // Shill no longer knows about this wifi network (edge case). // TODO(stevenjb): Add a notification (chromium-os13225). LOG(WARNING) << "Wifi network: " << service_path_ << " no longer exists."; return true; } if (eap_method_combobox_) { // Visible 802.1X EAP Wi-Fi connection. EAPMethod method = GetEapMethod(); DCHECK(method != EAP_METHOD_UNKNOWN); wifi->SetEAPMethod(method); wifi->SetEAPPhase2Auth(GetEapPhase2Auth()); wifi->SetEAPServerCaCertNssNickname(GetEapServerCaCertNssNickname()); wifi->SetEAPUseSystemCAs(GetEapUseSystemCas()); wifi->SetEAPClientCertPkcs11Id(GetEapClientCertPkcs11Id()); wifi->SetEAPIdentity(GetEapIdentity()); wifi->SetEAPAnonymousIdentity(GetEapAnonymousIdentity()); wifi->SetEAPPassphrase(GetPassphrase()); wifi->SetSaveCredentials(GetSaveCredentials()); } else { // Visible ordinary Wi-Fi connection. const std::string passphrase = GetPassphrase(); if (passphrase != wifi->passphrase()) wifi->SetPassphrase(passphrase); } bool share_default = (wifi->profile_type() != PROFILE_USER); wifi->SetEnrollmentDelegate( CreateEnrollmentDelegate(GetWidget()->GetNativeWindow(), wifi->name(), ProfileManager::GetLastUsedProfile())); cros->ConnectToWifiNetwork(wifi, GetShareNetwork(share_default)); // Connection failures are responsible for updating the UI, including // reopening dialogs. } return true; // dialog will be closed } std::string WifiConfigView::GetSsid() const { std::string result; if (ssid_textfield_ != NULL) { std::string untrimmed = UTF16ToUTF8(ssid_textfield_->text()); TrimWhitespaceASCII(untrimmed, TRIM_ALL, &result); } return result; } std::string WifiConfigView::GetPassphrase() const { std::string result; if (passphrase_textfield_ != NULL) result = UTF16ToUTF8(passphrase_textfield_->text()); return result; } bool WifiConfigView::GetSaveCredentials() const { if (!save_credentials_checkbox_) return true; // share networks by default (e.g. non 8021x). return save_credentials_checkbox_->checked(); } bool WifiConfigView::GetShareNetwork(bool share_default) const { if (!share_network_checkbox_) return share_default; return share_network_checkbox_->checked(); } EAPMethod WifiConfigView::GetEapMethod() const { DCHECK(eap_method_combobox_); switch (eap_method_combobox_->selected_index()) { case EAP_METHOD_INDEX_NONE: return EAP_METHOD_UNKNOWN; case EAP_METHOD_INDEX_PEAP: return EAP_METHOD_PEAP; case EAP_METHOD_INDEX_TLS: return EAP_METHOD_TLS; case EAP_METHOD_INDEX_TTLS: return EAP_METHOD_TTLS; case EAP_METHOD_INDEX_LEAP: return EAP_METHOD_LEAP; default: return EAP_METHOD_UNKNOWN; } } EAPPhase2Auth WifiConfigView::GetEapPhase2Auth() const { DCHECK(phase_2_auth_combobox_); switch (phase_2_auth_combobox_->selected_index()) { case PHASE_2_AUTH_INDEX_AUTO: return EAP_PHASE_2_AUTH_AUTO; case PHASE_2_AUTH_INDEX_MD5: return EAP_PHASE_2_AUTH_MD5; case PHASE_2_AUTH_INDEX_MSCHAPV2: return EAP_PHASE_2_AUTH_MSCHAPV2; case PHASE_2_AUTH_INDEX_MSCHAP: return EAP_PHASE_2_AUTH_MSCHAP; case PHASE_2_AUTH_INDEX_PAP: return EAP_PHASE_2_AUTH_PAP; case PHASE_2_AUTH_INDEX_CHAP: return EAP_PHASE_2_AUTH_CHAP; default: return EAP_PHASE_2_AUTH_AUTO; } } std::string WifiConfigView::GetEapServerCaCertNssNickname() const { DCHECK(server_ca_cert_combobox_); DCHECK(cert_library_); int index = server_ca_cert_combobox_->selected_index(); if (index == 0) { // First item is "Default". return std::string(); } else if (index == server_ca_cert_combobox_->model()->GetItemCount() - 1) { // Last item is "Do not check". return std::string(); } else { DCHECK(cert_library_); int cert_index = index - 1; return cert_library_->GetCACertificates().GetNicknameAt(cert_index); } } bool WifiConfigView::GetEapUseSystemCas() const { DCHECK(server_ca_cert_combobox_); // Only use system CAs if the first item ("Default") is selected. return server_ca_cert_combobox_->selected_index() == 0; } std::string WifiConfigView::GetEapClientCertPkcs11Id() const { DCHECK(user_cert_combobox_); DCHECK(cert_library_); if (!HaveUserCerts()) { return std::string(); // "None installed" } else { // Certificates are listed in the order they appear in the model. int index = user_cert_combobox_->selected_index(); return cert_library_->GetUserCertificates().GetPkcs11IdAt(index); } } std::string WifiConfigView::GetEapIdentity() const { DCHECK(identity_textfield_); return UTF16ToUTF8(identity_textfield_->text()); } std::string WifiConfigView::GetEapAnonymousIdentity() const { DCHECK(identity_anonymous_textfield_); return UTF16ToUTF8(identity_anonymous_textfield_->text()); } void WifiConfigView::Cancel() { } // This will initialize the view depending on if we have a wifi network or not. // And if we are doing simple password encryption or the more complicated // 802.1x encryption. // If we are creating the "Join other network..." dialog, we will allow user // to enter the data. And if they select the 802.1x encryption, we will show // the 802.1x fields. void WifiConfigView::Init(WifiNetwork* wifi, bool show_8021x) { if (wifi) { ParseWiFiEAPUIProperty(&eap_method_ui_data_, wifi, onc::eap::kOuter); ParseWiFiEAPUIProperty(&phase_2_auth_ui_data_, wifi, onc::eap::kInner); ParseWiFiEAPUIProperty(&user_cert_ui_data_, wifi, onc::eap::kClientCertRef); ParseWiFiEAPUIProperty(&server_ca_cert_ui_data_, wifi, onc::eap::kServerCARef); if (server_ca_cert_ui_data_.managed()) { ParseWiFiEAPUIProperty(&server_ca_cert_ui_data_, wifi, onc::eap::kUseSystemCAs); } ParseWiFiEAPUIProperty(&identity_ui_data_, wifi, onc::eap::kIdentity); ParseWiFiEAPUIProperty(&identity_anonymous_ui_data_, wifi, onc::eap::kAnonymousIdentity); ParseWiFiEAPUIProperty(&save_credentials_ui_data_, wifi, onc::eap::kSaveCredentials); if (show_8021x) ParseWiFiEAPUIProperty(&passphrase_ui_data_, wifi, onc::eap::kPassword); else ParseWiFiUIProperty(&passphrase_ui_data_, wifi, onc::wifi::kPassphrase); } views::GridLayout* layout = views::GridLayout::CreatePanel(this); SetLayoutManager(layout); const int column_view_set_id = 0; views::ColumnSet* column_set = layout->AddColumnSet(column_view_set_id); const int kPasswordVisibleWidth = 20; // Label column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::FILL, 1, views::GridLayout::USE_PREF, 0, 0); column_set->AddPaddingColumn(0, views::kRelatedControlSmallHorizontalSpacing); // Textfield, combobox. column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1, views::GridLayout::USE_PREF, 0, ChildNetworkConfigView::kInputFieldMinWidth); column_set->AddPaddingColumn(0, views::kRelatedControlSmallHorizontalSpacing); // Password visible button / policy indicator. column_set->AddColumn(views::GridLayout::CENTER, views::GridLayout::FILL, 1, views::GridLayout::USE_PREF, 0, kPasswordVisibleWidth); // Title layout->StartRow(0, column_view_set_id); views::Label* title = new views::Label(l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_JOIN_WIFI_NETWORKS)); ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); title->SetFont(rb.GetFont(ui::ResourceBundle::MediumFont)); layout->AddView(title, 5, 1); layout->AddPaddingRow(0, views::kUnrelatedControlVerticalSpacing); // SSID input layout->StartRow(0, column_view_set_id); layout->AddView(new views::Label(l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_NETWORK_ID))); if (!wifi) { ssid_textfield_ = new views::Textfield(views::Textfield::STYLE_DEFAULT); ssid_textfield_->SetController(this); ssid_textfield_->SetAccessibleName(l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_NETWORK_ID)); layout->AddView(ssid_textfield_); } else { views::Label* label = new views::Label(UTF8ToUTF16(wifi->name())); label->SetHorizontalAlignment(gfx::ALIGN_LEFT); layout->AddView(label); } layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing); // Security select if (!wifi && !show_8021x) { layout->StartRow(0, column_view_set_id); layout->AddView(new views::Label(l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_SECURITY))); security_combobox_model_.reset(new internal::SecurityComboboxModel); security_combobox_ = new views::Combobox(security_combobox_model_.get()); security_combobox_->set_listener(this); layout->AddView(security_combobox_); layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing); } // Only enumerate certificates in the data model for 802.1X networks. if (show_8021x) { // Initialize cert_library_ for 802.1X netoworks. cert_library_ = chromeos::CrosLibrary::Get()->GetCertLibrary(); // Setup a callback if certificates are yet to be loaded, if (!cert_library_->CertificatesLoaded()) cert_library_->AddObserver(this); // EAP method layout->StartRow(0, column_view_set_id); layout->AddView(new views::Label(l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_EAP_METHOD))); eap_method_combobox_model_.reset(new internal::EAPMethodComboboxModel); eap_method_combobox_ = new views::Combobox( eap_method_combobox_model_.get()); eap_method_combobox_->set_listener(this); eap_method_combobox_->SetEnabled(eap_method_ui_data_.editable()); layout->AddView(eap_method_combobox_); layout->AddView(new ControlledSettingIndicatorView(eap_method_ui_data_)); layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing); // Phase 2 authentication layout->StartRow(0, column_view_set_id); phase_2_auth_label_ = new views::Label(l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_PHASE_2_AUTH)); layout->AddView(phase_2_auth_label_); phase_2_auth_combobox_model_.reset( new internal::Phase2AuthComboboxModel(eap_method_combobox_)); phase_2_auth_combobox_ = new views::Combobox( phase_2_auth_combobox_model_.get()); phase_2_auth_label_->SetEnabled(false); phase_2_auth_combobox_->SetEnabled(false); phase_2_auth_combobox_->set_listener(this); layout->AddView(phase_2_auth_combobox_); layout->AddView(new ControlledSettingIndicatorView(phase_2_auth_ui_data_)); layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing); // Server CA certificate layout->StartRow(0, column_view_set_id); server_ca_cert_label_ = new views::Label(l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_CERT_SERVER_CA)); layout->AddView(server_ca_cert_label_); server_ca_cert_combobox_model_.reset( new internal::ServerCACertComboboxModel(cert_library_)); server_ca_cert_combobox_ = new ComboboxWithWidth( server_ca_cert_combobox_model_.get(), ChildNetworkConfigView::kInputFieldMinWidth); server_ca_cert_label_->SetEnabled(false); server_ca_cert_combobox_->SetEnabled(false); server_ca_cert_combobox_->set_listener(this); layout->AddView(server_ca_cert_combobox_); layout->AddView( new ControlledSettingIndicatorView(server_ca_cert_ui_data_)); layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing); // User certificate layout->StartRow(0, column_view_set_id); user_cert_label_ = new views::Label(l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_CERT)); layout->AddView(user_cert_label_); user_cert_combobox_model_.reset( new internal::UserCertComboboxModel(cert_library_)); user_cert_combobox_ = new views::Combobox(user_cert_combobox_model_.get()); user_cert_label_->SetEnabled(false); user_cert_combobox_->SetEnabled(false); user_cert_combobox_->set_listener(this); layout->AddView(user_cert_combobox_); layout->AddView(new ControlledSettingIndicatorView(user_cert_ui_data_)); layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing); // Identity layout->StartRow(0, column_view_set_id); identity_label_ = new views::Label(l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_CERT_IDENTITY)); layout->AddView(identity_label_); identity_textfield_ = new views::Textfield( views::Textfield::STYLE_DEFAULT); identity_textfield_->SetController(this); if (wifi && !wifi->identity().empty()) identity_textfield_->SetText(UTF8ToUTF16(wifi->identity())); identity_textfield_->SetEnabled(identity_ui_data_.editable()); layout->AddView(identity_textfield_); layout->AddView(new ControlledSettingIndicatorView(identity_ui_data_)); layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing); } // Passphrase input layout->StartRow(0, column_view_set_id); int label_text_id = IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_PASSPHRASE; passphrase_label_ = new views::Label( l10n_util::GetStringUTF16(label_text_id)); layout->AddView(passphrase_label_); passphrase_textfield_ = new views::Textfield( views::Textfield::STYLE_OBSCURED); passphrase_textfield_->SetController(this); if (wifi && !wifi->GetPassphrase().empty()) passphrase_textfield_->SetText(UTF8ToUTF16(wifi->GetPassphrase())); // Disable passphrase input initially for other network. passphrase_label_->SetEnabled(wifi != NULL); passphrase_textfield_->SetEnabled(wifi && passphrase_ui_data_.editable()); passphrase_textfield_->SetAccessibleName(l10n_util::GetStringUTF16( label_text_id)); layout->AddView(passphrase_textfield_); if (passphrase_ui_data_.managed()) { layout->AddView(new ControlledSettingIndicatorView(passphrase_ui_data_)); } else { // Password visible button. passphrase_visible_button_ = new views::ToggleImageButton(this); passphrase_visible_button_->SetTooltipText( l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_PASSPHRASE_SHOW)); passphrase_visible_button_->SetToggledTooltipText( l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_PASSPHRASE_HIDE)); passphrase_visible_button_->SetImage( views::ImageButton::STATE_NORMAL, ResourceBundle::GetSharedInstance(). GetImageSkiaNamed(IDR_NETWORK_SHOW_PASSWORD)); passphrase_visible_button_->SetImage( views::ImageButton::STATE_HOVERED, ResourceBundle::GetSharedInstance(). GetImageSkiaNamed(IDR_NETWORK_SHOW_PASSWORD_HOVER)); passphrase_visible_button_->SetToggledImage( views::ImageButton::STATE_NORMAL, ResourceBundle::GetSharedInstance(). GetImageSkiaNamed(IDR_NETWORK_HIDE_PASSWORD)); passphrase_visible_button_->SetToggledImage( views::ImageButton::STATE_HOVERED, ResourceBundle::GetSharedInstance(). GetImageSkiaNamed(IDR_NETWORK_HIDE_PASSWORD_HOVER)); passphrase_visible_button_->SetImageAlignment( views::ImageButton::ALIGN_CENTER, views::ImageButton::ALIGN_MIDDLE); layout->AddView(passphrase_visible_button_); } layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing); if (show_8021x) { // Anonymous identity layout->StartRow(0, column_view_set_id); identity_anonymous_label_ = new views::Label(l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_CERT_IDENTITY_ANONYMOUS)); layout->AddView(identity_anonymous_label_); identity_anonymous_textfield_ = new views::Textfield( views::Textfield::STYLE_DEFAULT); identity_anonymous_label_->SetEnabled(false); identity_anonymous_textfield_->SetEnabled(false); identity_anonymous_textfield_->SetController(this); layout->AddView(identity_anonymous_textfield_); layout->AddView( new ControlledSettingIndicatorView(identity_anonymous_ui_data_)); layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing); } // Checkboxes. // Save credentials if (show_8021x) { layout->StartRow(0, column_view_set_id); save_credentials_checkbox_ = new views::Checkbox( l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_SAVE_CREDENTIALS)); save_credentials_checkbox_->SetEnabled( save_credentials_ui_data_.editable()); layout->SkipColumns(1); layout->AddView(save_credentials_checkbox_); layout->AddView( new ControlledSettingIndicatorView(save_credentials_ui_data_)); } // Share network if (!wifi || (wifi->profile_type() == PROFILE_NONE && wifi->IsPassphraseRequired() && !wifi->RequiresUserProfile())) { layout->StartRow(0, column_view_set_id); share_network_checkbox_ = new views::Checkbox( l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_SHARE_NETWORK)); layout->SkipColumns(1); layout->AddView(share_network_checkbox_); } layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing); // Create an error label. layout->StartRow(0, column_view_set_id); layout->SkipColumns(1); error_label_ = new views::Label(); error_label_->SetHorizontalAlignment(gfx::ALIGN_LEFT); error_label_->SetEnabledColor(SK_ColorRED); layout->AddView(error_label_); // Initialize the field and checkbox values. // After creating the fields, we set the values. Fields need to be created // first because RefreshEapFields() will enable/disable them as appropriate. if (show_8021x) { EAPMethod eap_method = (wifi ? wifi->eap_method() : EAP_METHOD_UNKNOWN); switch (eap_method) { case EAP_METHOD_PEAP: eap_method_combobox_->SetSelectedIndex(EAP_METHOD_INDEX_PEAP); break; case EAP_METHOD_TTLS: eap_method_combobox_->SetSelectedIndex(EAP_METHOD_INDEX_TTLS); break; case EAP_METHOD_TLS: eap_method_combobox_->SetSelectedIndex(EAP_METHOD_INDEX_TLS); break; case EAP_METHOD_LEAP: eap_method_combobox_->SetSelectedIndex(EAP_METHOD_INDEX_LEAP); break; default: break; } RefreshEapFields(); // Phase 2 authentication and anonymous identity. if (Phase2AuthActive()) { EAPPhase2Auth eap_phase_2_auth = (wifi ? wifi->eap_phase_2_auth() : EAP_PHASE_2_AUTH_AUTO); switch (eap_phase_2_auth) { case EAP_PHASE_2_AUTH_MD5: phase_2_auth_combobox_->SetSelectedIndex(PHASE_2_AUTH_INDEX_MD5); break; case EAP_PHASE_2_AUTH_MSCHAPV2: phase_2_auth_combobox_->SetSelectedIndex(PHASE_2_AUTH_INDEX_MSCHAPV2); break; case EAP_PHASE_2_AUTH_MSCHAP: phase_2_auth_combobox_->SetSelectedIndex(PHASE_2_AUTH_INDEX_MSCHAP); break; case EAP_PHASE_2_AUTH_PAP: phase_2_auth_combobox_->SetSelectedIndex(PHASE_2_AUTH_INDEX_PAP); break; case EAP_PHASE_2_AUTH_CHAP: phase_2_auth_combobox_->SetSelectedIndex(PHASE_2_AUTH_INDEX_CHAP); break; default: break; } const std::string& eap_anonymous_identity = (wifi ? wifi->eap_anonymous_identity() : std::string()); identity_anonymous_textfield_->SetText( UTF8ToUTF16(eap_anonymous_identity)); } // Server CA certificate. if (CaCertActive()) { const std::string& nss_nickname = (wifi ? wifi->eap_server_ca_cert_nss_nickname() : std::string()); if (nss_nickname.empty()) { if (wifi->eap_use_system_cas()) { // "Default". server_ca_cert_combobox_->SetSelectedIndex(0); } else { // "Do not check". server_ca_cert_combobox_->SetSelectedIndex( server_ca_cert_combobox_->model()->GetItemCount() - 1); } } else { // Select the certificate if available. int cert_index = cert_library_->GetCACertificates().FindCertByNickname(nss_nickname); if (cert_index >= 0) { // Skip item for "Default". server_ca_cert_combobox_->SetSelectedIndex(1 + cert_index); } } } // User certificate. if (UserCertActive()) { const std::string& pkcs11_id = (wifi ? wifi->eap_client_cert_pkcs11_id() : std::string()); if (!pkcs11_id.empty()) { int cert_index = cert_library_->GetUserCertificates().FindCertByPkcs11Id(pkcs11_id); if (cert_index >= 0) { user_cert_combobox_->SetSelectedIndex(cert_index); } } } // Identity is always active. const std::string& eap_identity = (wifi ? wifi->eap_identity() : std::string()); identity_textfield_->SetText(UTF8ToUTF16(eap_identity)); // Passphrase if (PassphraseActive()) { const std::string& eap_passphrase = (wifi ? wifi->eap_passphrase() : std::string()); passphrase_textfield_->SetText(UTF8ToUTF16(eap_passphrase)); } // Save credentials bool save_credentials = (wifi ? wifi->save_credentials() : false); save_credentials_checkbox_->SetChecked(save_credentials); } RefreshShareCheckbox(); UpdateErrorLabel(); } void WifiConfigView::InitFocus() { views::View* view_to_focus = GetInitiallyFocusedView(); if (view_to_focus) view_to_focus->RequestFocus(); } // static void WifiConfigView::ParseWiFiUIProperty( NetworkPropertyUIData* property_ui_data, Network* network, const std::string& key) { NetworkLibrary* network_library = CrosLibrary::Get()->GetNetworkLibrary(); property_ui_data->ParseOncProperty( network->ui_data(), network_library->FindOncForNetwork(network->unique_id()), base::StringPrintf("%s.%s", onc::kWiFi, key.c_str())); } // static void WifiConfigView::ParseWiFiEAPUIProperty( NetworkPropertyUIData* property_ui_data, Network* network, const std::string& key) { ParseWiFiUIProperty( property_ui_data, network, base::StringPrintf("%s.%s", onc::wifi::kEAP, key.c_str())); } } // namespace chromeos
bsd-3-clause
5442Coach/Fred
src/org/usfirst/frc5442/Fred/subsystems/Pneumatics.java
1123
// RobotBuilder Version: 1.5 // // This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. package org.usfirst.frc5442.Fred.subsystems; import org.usfirst.frc5442.Fred.*; import edu.wpi.first.wpilibj.*; import edu.wpi.first.wpilibj.command.Subsystem; /** * */ //@SuppressWarnings("unused") public class Pneumatics extends Subsystem { private Compressor compressor = RobotMap.pneumaticsCompressor; // Put methods for controlling this subsystem // here. Call these from Commands. public Pneumatics() { compressor.start(); } public void initDefaultCommand() { // Set the default command for a subsystem here. //setDefaultCommand(new MySpecialCommand()); } }
bsd-3-clause
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE590_Free_Memory_Not_on_Heap/s01/CWE590_Free_Memory_Not_on_Heap__delete_array_int_alloca_52a.cpp
2747
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE590_Free_Memory_Not_on_Heap__delete_array_int_alloca_52a.cpp Label Definition File: CWE590_Free_Memory_Not_on_Heap__delete_array.label.xml Template File: sources-sink-52a.tmpl.cpp */ /* * @description * CWE: 590 Free Memory Not on Heap * BadSource: alloca Data buffer is allocated on the stack with alloca() * GoodSource: Allocate memory on the heap * Sink: * BadSink : Print then free data * Flow Variant: 52 Data flow: data passed as an argument from one function to another to another in three different source files * * */ #include "std_testcase.h" #include <wchar.h> namespace CWE590_Free_Memory_Not_on_Heap__delete_array_int_alloca_52 { #ifndef OMITBAD /* bad function declaration */ void badSink_b(int * data); void bad() { int * data; data = NULL; /* Initialize data */ { /* FLAW: data is allocated on the stack and deallocated in the BadSink */ int * dataBuffer = (int *)ALLOCA(100*sizeof(int)); { size_t i; for (i = 0; i < 100; i++) { dataBuffer[i] = 5; } } data = dataBuffer; } badSink_b(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* good function declarations */ void goodG2BSink_b(int * data); /* goodG2B uses the GoodSource with the BadSink */ static void goodG2B() { int * data; data = NULL; /* Initialize data */ { /* FIX: data is allocated on the heap and deallocated in the BadSink */ int * dataBuffer = new int[100]; { size_t i; for (i = 0; i < 100; i++) { dataBuffer[i] = 5; } } data = dataBuffer; } goodG2BSink_b(data); } void good() { goodG2B(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE590_Free_Memory_Not_on_Heap__delete_array_int_alloca_52; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
bsd-3-clause
mikaelwasp/toir-server
backend/views/operation-tool/update.php
1046
<?php use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $model common\models\OperationTool */ $this->title = Yii::t('app', 'Update {modelClass}: ', [ 'modelClass' => 'Инструменты для операций', ]) . $model->_id; $this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Инструменты для операций'), 'url' => ['index']]; $this->params['breadcrumbs'][] = ['label' => $model->_id, 'url' => ['view', 'id' => $model->_id]]; $this->params['breadcrumbs'][] = Yii::t('app', 'Update'); ?> <div class="operation-tool-update box-padding"> <div class="box box-default"> <div class="box-header with-border"> <h2><?= Html::encode($this->title) ?></h2> <div class="box-tools pull-right"> <span class="label label-default"></span> </div> </div> <div class="box-body" style="padding: 30px;"> <?= $this->render('_form', [ 'model' => $model, ]) ?> </div> </div> </div>
bsd-3-clause
lak/puppetshow
vendor/plugins/active_scaffold/lib/extensions/action_controller_rendering.rb
2043
# wrap the action rendering for ActiveScaffold controllers module ActionController #:nodoc: class Base def render_with_active_scaffold(*args, &block) if self.class.uses_active_scaffold? and params[:adapter] and @rendering_adapter.nil? @rendering_adapter = true # recursion control # if we need an adapter, then we render the actual stuff to a string and insert it into the adapter template render :file => rewrite_template_path_for_active_scaffold(params[:adapter]), :locals => {:payload => render_to_string(args.first, &block)}, :use_full_path => true @rendering_adapter = nil # recursion control else render_without_active_scaffold(*args, &block) end end alias_method :render_without_active_scaffold, :render alias_method :render, :render_with_active_scaffold # Rails 1.2.x if method_defined? :render_action def render_action_with_active_scaffold(action_name, status = nil, with_layout = true) #:nodoc: if self.class.uses_active_scaffold? path = rewrite_template_path_for_active_scaffold(action_name) return render(:template => path, :layout => with_layout, :status => status) if path != action_name end return render_action_without_active_scaffold(action_name, status, with_layout) end alias_method :render_action_without_active_scaffold, :render_action alias_method :render_action, :render_action_with_active_scaffold end # Rails 2.x implementation is post-initialization on :active_scaffold method private def rewrite_template_path_for_active_scaffold(path) # test for the actual file return path if template_exists? default_template_name(path) # check the ActiveScaffold-specific directories active_scaffold_config.template_search_path.each do |template_path| full_path = File.join(template_path, path) return full_path if template_exists? full_path end return path end end end
bsd-3-clause
brahmajiayatas/getweiss
admin/protected/models/Configuration.php
3231
<?php /** * This is the model class for table "tbl_configuration". * * The followings are the available columns in table 'tbl_configuration': * @property integer $Objid * @property string $Facebook * @property string $Twitter * @property string $GooglePlus * @property string $LinkedIn * @property string $Pinterest * @property string $Youtube */ class Configuration extends CActiveRecord { /** * @return string the associated database table name */ public function tableName() { return 'tbl_configuration'; } /** * @return array validation rules for model attributes. */ public function rules() { // NOTE: you should only define rules for those attributes that // will receive user inputs. return array( //array('Facebook, Twitter, GooglePlus, LinkedIn, Pinterest, Youtube', 'required'), array('Facebook, Twitter, GooglePlus, LinkedIn, Pinterest', 'length', 'max'=>400), array('Youtube', 'length', 'max'=>500), // The following rule is used by search(). // @todo Please remove those attributes that should not be searched. array('Objid, Facebook, Twitter, GooglePlus, LinkedIn, Pinterest, Youtube', 'safe', 'on'=>'search'), ); } /** * @return array relational rules. */ public function relations() { // NOTE: you may need to adjust the relation name and the related // class name for the relations automatically generated below. return array( ); } /** * @return array customized attribute labels (name=>label) */ public function attributeLabels() { return array( 'Objid' => 'Objid', 'Facebook' => 'Facebook', 'Twitter' => 'Twitter', 'GooglePlus' => 'Google Plus', 'LinkedIn' => 'Linked In', 'Pinterest' => 'Pinterest', 'Youtube' => 'Youtube', ); } /** * Retrieves a list of models based on the current search/filter conditions. * * Typical usecase: * - Initialize the model fields with values from filter form. * - Execute this method to get CActiveDataProvider instance which will filter * models according to data in model fields. * - Pass data provider to CGridView, CListView or any similar widget. * * @return CActiveDataProvider the data provider that can return the models * based on the search/filter conditions. */ public function search() { // @todo Please modify the following code to remove attributes that should not be searched. $criteria=new CDbCriteria; $criteria->compare('Objid',$this->Objid); $criteria->compare('Facebook',$this->Facebook,true); $criteria->compare('Twitter',$this->Twitter,true); $criteria->compare('GooglePlus',$this->GooglePlus,true); $criteria->compare('LinkedIn',$this->LinkedIn,true); $criteria->compare('Pinterest',$this->Pinterest,true); $criteria->compare('Youtube',$this->Youtube,true); return new CActiveDataProvider($this, array( 'criteria'=>$criteria, )); } /** * Returns the static model of the specified AR class. * Please note that you should have this exact method in all your CActiveRecord descendants! * @param string $className active record class name. * @return Configuration the static model class */ public static function model($className=__CLASS__) { return parent::model($className); } }
bsd-3-clause