code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
class RepeatError(ValueError): pass class NoneError(ValueError): pass
HarborYuan/cashier
Errors.py
Python
mit
79
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>huffman: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.5.0~camlp4 / huffman - 8.9.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> huffman <small> 8.9.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-03-05 14:29:34 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-03-05 14:29:34 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-ocamlbuild base OCamlbuild binary and libraries distributed with the OCaml compiler base-threads base base-unix base camlp4 4.02+7 Camlp4 is a system for writing extensible parsers for programming languages conf-findutils 1 Virtual package relying on findutils conf-which 1 Virtual package relying on which coq 8.5.0~camlp4 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.02.3 The OCaml compiler (virtual package) ocaml-base-compiler 4.02.3 Official 4.02.3 release ocaml-config 1 OCaml Switch Configuration ocamlbuild 0 Build system distributed with the OCaml compiler since OCaml 3.10.0 # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;palmskog@gmail.com&quot; homepage: &quot;https://github.com/coq-community/huffman&quot; dev-repo: &quot;git+https://github.com/coq-community/huffman.git&quot; bug-reports: &quot;https://github.com/coq-community/huffman/issues&quot; license: &quot;LGPL-2.1-or-later&quot; synopsis: &quot;A Coq proof of the correctness of the Huffman coding algorithm&quot; description: &quot;&quot;&quot; This projects contains a Coq proof of the correctness of the Huffman coding algorithm, as described in David A. Huffman&#39;s paper A Method for the Construction of Minimum-Redundancy Codes, Proc. IRE, pp. 1098-1101, September 1952. &quot;&quot;&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.7&quot; &amp; &lt; &quot;8.10~&quot;} ] tags: [ &quot;category:Computer Science/Decision Procedures and Certified Algorithms/Correctness proofs of algorithms&quot; &quot;category:Miscellaneous/Extracted Programs/Combinatorics&quot; &quot;keyword:data compression&quot; &quot;keyword:code&quot; &quot;keyword:huffman tree&quot; &quot;logpath:Huffman&quot; &quot;date:2019-05-15&quot; ] authors: [ &quot;Laurent Théry&quot; ] url { src: &quot;https://github.com/coq-community/huffman/archive/v8.9.0.tar.gz&quot; checksum: &quot;sha256=20b63eae0d17a23646446fcca22de945d6a19a03246bec8b5b4c8da6d6f3184b&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-huffman.8.9.0 coq.8.5.0~camlp4</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.5.0~camlp4). The following dependencies couldn&#39;t be met: - coq-huffman -&gt; coq &gt;= 8.7 -&gt; ocaml &gt;= 4.05.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-huffman.8.9.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.02.3-2.0.6/released/8.5.0~camlp4/huffman/8.9.0.html
HTML
mit
7,513
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>traversable-fincontainer: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.15.0 / traversable-fincontainer - 8.10.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> traversable-fincontainer <small> 8.10.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-02-24 00:18:42 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-02-24 00:18:42 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 4 Virtual package relying on a GMP lib system installation coq 8.15.0 Formal proof management system dune 3.0.2 Fast, portable, and opinionated build system ocaml 4.11.2 The OCaml compiler (virtual package) ocaml-base-compiler 4.11.2 Official release 4.11.2 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.3 A library manager for OCaml zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/oconnorr/traversable-fincontainer&quot; license: &quot;ASL&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/TraversableFincontainer&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.10&quot; &amp; &lt; &quot;8.11~&quot;} ] tags: [ &quot;keyword: finitary container&quot; &quot;keyword: traversable functors&quot; &quot;category: Computer Science/Data Types and Data Structures&quot; ] authors: [ &quot;Russell O&#39;Connor &lt;oconnorr@google.com&gt;&quot; ] bug-reports: &quot;https://github.com/coq-contribs/traversable-fincontainer/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/traversable-fincontainer.git&quot; synopsis: &quot;Traversable Functors are Finitary Containers&quot; description: &quot;&quot;&quot; A Coq proof that all Traversable functors are isomorphic to finitary containers.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/traversable-fincontainer/archive/v8.10.0.tar.gz&quot; checksum: &quot;md5=2d2b3b18f46d2d11651ba6022fefb71b&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-traversable-fincontainer.8.10.0 coq.8.15.0</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.15.0). The following dependencies couldn&#39;t be met: - coq-traversable-fincontainer -&gt; coq &lt; 8.11~ -&gt; ocaml &lt; 4.10 base of this switch (use `--unlock-base&#39; to force) No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-traversable-fincontainer.8.10.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.11.2-2.0.7/released/8.15.0/traversable-fincontainer/8.10.0.html
HTML
mit
7,085
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>karatsuba: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.7.2 / karatsuba - 8.6.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> karatsuba <small> 8.6.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-01-22 06:02:19 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-01-22 06:02:19 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-ocamlbuild base OCamlbuild binary and libraries distributed with the OCaml compiler base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 1 Virtual package relying on perl coq 8.7.2 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.02.3 The OCaml compiler (virtual package) ocaml-base-compiler 4.02.3 Official 4.02.3 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/karatsuba&quot; license: &quot;Unknown&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Karatsuba&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.6&quot; &amp; &lt; &quot;8.7~&quot;} ] tags: [ &quot;keyword: Karatsuba multiplication&quot; &quot;keyword: binary ring&quot; &quot;category: Mathematics/Arithmetic and Number Theory/Number theory&quot; &quot;date: 2005-09-15&quot; ] authors: [ &quot;Russell O&#39;Connor &lt;r.oconnor@cs.ru.nl&gt; [http://r6.ca/]&quot; ] bug-reports: &quot;https://github.com/coq-contribs/karatsuba/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/karatsuba.git&quot; synopsis: &quot;Karatsuba&#39;s Multiplication&quot; description: &quot;&quot;&quot; http://r6.ca/Karatsuba/ An implementation of Karatsuba&#39;s Multiplication algorithm&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/karatsuba/archive/v8.6.0.tar.gz&quot; checksum: &quot;md5=2d6f0f166881f47310c6b3f772f747ed&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-karatsuba.8.6.0 coq.8.7.2</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.7.2). The following dependencies couldn&#39;t be met: - coq-karatsuba -&gt; coq &lt; 8.7~ -&gt; ocaml &lt; 4.02.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-karatsuba.8.6.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.02.3-2.0.6/released/8.7.2/karatsuba/8.6.0.html
HTML
mit
7,194
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>tarski-geometry: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.14.1 / tarski-geometry - 8.6.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> tarski-geometry <small> 8.6.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-01-27 05:16:32 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-01-27 05:16:32 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 4 Virtual package relying on a GMP lib system installation coq 8.14.1 Formal proof management system dune 2.9.1 Fast, portable, and opinionated build system ocaml 4.11.2 The OCaml compiler (virtual package) ocaml-base-compiler 4.11.2 Official release 4.11.2 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.2 A library manager for OCaml zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/tarski-geometry&quot; license: &quot;GPL&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/TarskiGeometry&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.6&quot; &amp; &lt; &quot;8.7~&quot;} ] tags: [ &quot;keyword: geometry&quot; &quot;keyword: Tarski&#39;s geometry&quot; &quot;keyword: congruence&quot; &quot;keyword: between property&quot; &quot;keyword: orthogonality&quot; &quot;category: Mathematics/Geometry/General&quot; &quot;date: 2006-03&quot; ] authors: [ &quot;Julien Narboux &lt;Julien.Narboux@dpt-info.u-strasbg.fr&gt; [http://dpt-info.u-strasbg.fr/~narboux/]&quot; ] bug-reports: &quot;https://github.com/coq-contribs/tarski-geometry/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/tarski-geometry.git&quot; synopsis: &quot;Tarski&#39;s geometry&quot; description: &quot;&quot;&quot; http://dpt-info.u-strasbg.fr/~narboux/tarski.html This is a formalization of geometry using a simplified version of Tarski&#39;s axiom system. The development contains a formalization of the chapters 1-8 of the book &quot;Metamathematische Methoden in der Geometrie&quot; by W. Schwabhäuser, W. Szmielew and A. Tarski. This includes between properties, congruence properties, midpoint, perpendicular lines, point reflection, orthogonality ... This development aims to be a low level complement for Frédérique Guilhot&#39;s development about high-school geometry. For more information see: Mechanical Theorem Proving in Tarski&#39;s geometry in the post-proceeding of ADG 2006, F. Botana and T. Recio (Eds.), LNAI 4869, pages 139-156, 2007.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/tarski-geometry/archive/v8.6.0.tar.gz&quot; checksum: &quot;md5=087d2c5e47c0a7363e476ab65818fe64&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-tarski-geometry.8.6.0 coq.8.14.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.14.1). The following dependencies couldn&#39;t be met: - coq-tarski-geometry -&gt; coq &lt; 8.7~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-tarski-geometry.8.6.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.11.2-2.0.7/released/8.14.1/tarski-geometry/8.6.0.html
HTML
mit
7,776
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>mutual-exclusion: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.9.0 / mutual-exclusion - 8.5.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> mutual-exclusion <small> 8.5.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-03-06 09:57:06 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-03-06 09:57:06 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 2 Virtual package relying on perl coq 8.9.0 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.09.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.09.1 Official release 4.09.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.3 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;matej.kosik@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/mutual-exclusion&quot; license: &quot;LGPL 2&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/MutualExclusion&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.5&quot; &amp; &lt; &quot;8.6~&quot;} ] tags: [ &quot;keyword:mutual exclusion&quot; &quot;keyword:concurrency&quot; &quot;keyword:Peterson&#39;s algorithm&quot; &quot;keyword:co-inductive types&quot; &quot;keyword:co-induction&quot; &quot;category:Computer Science/Concurrent Systems and Protocols/Correctness of specific protocols&quot; &quot;category:Miscellaneous/Extracted Programs/Automata and protocols&quot; ] authors: [ &quot;Eduardo Giménez &lt;&gt;&quot; ] bug-reports: &quot;https://github.com/coq-contribs/mutual-exclusion/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/mutual-exclusion.git&quot; synopsis: &quot;A certification of Peterson&#39;s algorithm for managing mutual exclusion&quot; description: &quot;&quot;&quot; This is a proof of certification of Peterson&#39;s algorithm for managing mutual exclusion. The case of two processes is treated in the directory called ``binary&#39;&#39; (see the README file in this directory). The case of n processes will be available soon.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/mutual-exclusion/archive/v8.5.0.tar.gz&quot; checksum: &quot;md5=a0e3d892c7d7ff166612e7b41312c166&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-mutual-exclusion.8.5.0 coq.8.9.0</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.9.0). The following dependencies couldn&#39;t be met: - coq-mutual-exclusion -&gt; coq &lt; 8.6~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-mutual-exclusion.8.5.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.09.1-2.0.6/released/8.9.0/mutual-exclusion/8.5.0.html
HTML
mit
7,372
#!/usr/bin/env perl use v5.020; use strict; use warnings; use utf8; binmode STDOUT, ":utf8"; binmode STDERR, ":utf8"; binmode STDIN, ":encoding(UTF-8)"; use Data::Printer; use FindBin; use Getopt::Long; use Template; use Text::CSV_XS 'csv'; use lib "$FindBin::Bin/../lib"; use DartSense::Match; use DartSense::Player; use experimental 'signatures'; no warnings "experimental::signatures"; my $players = {}; my @matches; my @players; my $options = { file => '', }; GetOptions( "file=s" => \$options->{file}, ); my $aoa = csv( in => $options->{file} ); my $headers = shift @{$aoa}; my $passes = 5; for ( @{$aoa} ) { my %args; for ( my $i = 0; $i < @{$_}; $i++ ) { $args{ $headers->[$i] } = $_->[$i]; } my $player1 = getPlayer( $args{speler1} ); my $player2 = getPlayer( $args{speler2} ); push @matches, DartSense::Match->new( { %args, player1 => $player1, player2 => $player2, } ); } @matches = sort { $a->get_seq cmp $b->get_seq } @matches; for ( 1 .. $passes ) { for my $player (@players) { $player->resetPass; } for my $match (@matches) { $match->calcratings; } } @players = sort { $b->{rating} <=> $a->{rating} } @players; # p @players; my $template = Template->new( { INCLUDE_PATH => "$FindBin::Bin/../var/templates" } ); $template->process( "ranking.tt", { players => \@players }, "$FindBin::Bin/../var/www/index.html" ) || die $template->error(); for (@players) { $template->process( "player.tt", { player => $_ }, "$FindBin::Bin/../var/www/player_" . $_->get_name . ".html" ) || die $template->error(); } # p @matches; # # p $aoa; sub getPlayer { my $name = shift; my $player = $players->{$name}; if ( !$player ) { $player = DartSense::Player->new( { name => $name } ); $players->{$name} = $player; push @players, $player; } return $player; }
basbloemsaat/dartsense
bin/old/genSite.pl
Perl
mit
1,953
<html dir="LTR"> <head> <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" /> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" /> <title>LogManager Methods</title> <xml> </xml> <link rel="stylesheet" type="text/css" href="MSDN.css" /> </head> <body id="bodyID" class="dtBODY"> <div id="nsbanner"> <div id="bannerrow1"> <table class="bannerparthead" cellspacing="0"> <tr id="hdr"> <td class="runninghead">log4net SDK Documentation - Microsoft .NET Framework 4.0</td> <td class="product"> </td> </tr> </table> </div> <div id="TitleRow"> <h1 class="dtH1">LogManager Methods</h1> </div> </div> <div id="nstext"> <p>The methods of the <b>LogManager</b> class are listed below. For a complete list of <b>LogManager</b> class members, see the <a href="log4net.LogManagerMembers.html">LogManager Members</a> topic.</p> <h4 class="dtH4">Public Static (Shared) Methods</h4> <div class="tablediv"> <table class="dtTABLE" cellspacing="0"> <tr VALIGN="top"><td width="50%"><img src="pubmethod.gif"></img><img src="static.gif" /><a href="log4net.LogManager.CreateDomain_overloads.html">CreateDomain</a></td><td width="50%">Overloaded. Create a domain</td></tr> <tr VALIGN="top"><td width="50%"><img src="pubmethod.gif"></img><img src="static.gif" /><a href="log4net.LogManager.CreateRepository_overloads.html">CreateRepository</a></td><td width="50%">Overloaded. Create a logger repository.</td></tr> <tr VALIGN="top"><td width="50%"><img src="pubmethod.gif"></img><img src="static.gif" /><a href="log4net.LogManager.Exists_overloads.html">Exists</a></td><td width="50%">Overloaded. Returns the named logger if it exists.</td></tr> <tr VALIGN="top"><td width="50%"><img src="pubmethod.gif"></img><img src="static.gif" /><a href="log4net.LogManager.GetAllRepositories.html">GetAllRepositories</a></td><td width="50%"> Gets the list of currently defined repositories. </td></tr> <tr VALIGN="top"><td width="50%"><img src="pubmethod.gif"></img><img src="static.gif" /><a href="log4net.LogManager.GetCurrentLoggers_overloads.html">GetCurrentLoggers</a></td><td width="50%">Overloaded. Get the currently defined loggers.</td></tr> <tr VALIGN="top"><td width="50%"><img src="pubmethod.gif"></img><img src="static.gif" /><a href="log4net.LogManager.GetLogger_overloads.html">GetLogger</a></td><td width="50%">Overloaded. Get or create a logger.</td></tr> <tr VALIGN="top"><td width="50%"><img src="pubmethod.gif"></img><img src="static.gif" /><a href="log4net.LogManager.GetLoggerRepository_overloads.html">GetLoggerRepository</a></td><td width="50%">Overloaded. Get the logger repository.</td></tr> <tr VALIGN="top"><td width="50%"><img src="pubmethod.gif"></img><img src="static.gif" /><a href="log4net.LogManager.GetRepository_overloads.html">GetRepository</a></td><td width="50%">Overloaded. Get a logger repository.</td></tr> <tr VALIGN="top"><td width="50%"><img src="pubmethod.gif"></img><img src="static.gif" /><a href="log4net.LogManager.ResetConfiguration_overloads.html">ResetConfiguration</a></td><td width="50%">Overloaded. Reset the configuration of a repository</td></tr> <tr VALIGN="top"><td width="50%"><img src="pubmethod.gif"></img><img src="static.gif" /><a href="log4net.LogManager.Shutdown.html">Shutdown</a></td><td width="50%"> Shuts down the log4net system. </td></tr> <tr VALIGN="top"><td width="50%"><img src="pubmethod.gif"></img><img src="static.gif" /><a href="log4net.LogManager.ShutdownRepository_overloads.html">ShutdownRepository</a></td><td width="50%">Overloaded. Shutdown a logger repository.</td></tr></table> </div> <h4 class="dtH4">Public Instance Methods</h4> <div class="tablediv"> <table class="dtTABLE" cellspacing="0"> <tr VALIGN="top"><td width="50%"><img src="pubmethod.gif"></img><a href="ms-help://MS.NETFrameworkSDKv1.1/cpref/html/frlrfSystemObjectClassEqualsTopic.htm">Equals</a> (inherited from <b>Object</b>)</td><td width="50%"> Determines whether the specified <a href="ms-help://MS.NETFrameworkSDKv1.1/cpref/html/frlrfSystemObjectClassTopic.htm">Object</a> is equal to the current <a href="ms-help://MS.NETFrameworkSDKv1.1/cpref/html/frlrfSystemObjectClassTopic.htm">Object</a>. </td></tr> <tr VALIGN="top"><td width="50%"><img src="pubmethod.gif"></img><a href="ms-help://MS.NETFrameworkSDKv1.1/cpref/html/frlrfSystemObjectClassGetHashCodeTopic.htm">GetHashCode</a> (inherited from <b>Object</b>)</td><td width="50%"> Serves as a hash function for a particular type. </td></tr> <tr VALIGN="top"><td width="50%"><img src="pubmethod.gif"></img><a href="ms-help://MS.NETFrameworkSDKv1.1/cpref/html/frlrfSystemObjectClassGetTypeTopic.htm">GetType</a> (inherited from <b>Object</b>)</td><td width="50%"> Gets the <a href="ms-help://MS.NETFrameworkSDKv1.1/cpref/html/frlrfSystemTypeClassTopic.htm">Type</a> of the current instance. </td></tr> <tr VALIGN="top"><td width="50%"><img src="pubmethod.gif"></img><a href="ms-help://MS.NETFrameworkSDKv1.1/cpref/html/frlrfSystemObjectClassToStringTopic.htm">ToString</a> (inherited from <b>Object</b>)</td><td width="50%"> Returns a <a href="ms-help://MS.NETFrameworkSDKv1.1/cpref/html/frlrfSystemStringClassTopic.htm">String</a> that represents the current <a href="ms-help://MS.NETFrameworkSDKv1.1/cpref/html/frlrfSystemObjectClassTopic.htm">Object</a>. </td></tr></table> </div> <h4 class="dtH4">See Also</h4> <p> <a href="log4net.LogManager.html">LogManager Class</a> | <a href="log4net.html">log4net Namespace</a> | <a href="log4net.ILog.html">ILog</a></p> <object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" viewastext="true" style="display: none;"> <param name="Keyword" value="LogManager class, methods"> </param> </object> <hr /> <div id="footer"> <p> <a href="http://logging.apache.org/log4net">Copyright 2004-2011 The Apache Software Foundation.</a> </p> <p> </p> </div> </div> </body> </html>
npruehs/slash-framework
Ext/log4net-1.2.11/doc/release/sdk/log4net.LogManagerMethods.html
HTML
mit
6,194
<?php /** * This file is the main application controller for pasteshare * @license MIT */ namespace pasteshare; /** * Main application controller for pasteshare * * @author Anthony Vitacco <anthony@littlegno.me> */ class PasteShare { /** @var object An instance of pasteshare\Application */ private $app; /** * This function stores the application instance globally * * @param object $app An instance of pasteshare\Application */ public function __construct(Application $app) { $this->app = $app; } /** * Main index page for pasteshare * * @return object An instance of Symfony's response class */ public function newPastePage() { $options = $this->app["options"]; $options["languages"] = $this->getLanguagesFromCodeMirror(); return $this->app->render("pages/main.twig", $options); } /** * Save function for pastes * * @param object $request An instance of Symfony's request class * @return object An instance of Symfony's response class */ public function savePaste(\Symfony\Component\HttpFoundation\Request $request) { try { $dm = $this->app["deps"]["mongoDm"]; $timezone = new \DateTimeZone($this->app["deps"]["siteConfig"]->application->timezone); $paste = new \pasteshare\Paste(); if ($request->get("encrypted")) { $paste->encrypted = true; $paste->iv = $request->get("iv"); } $paste->language = $request->get("language"); $paste->contents = $request->get("contents"); $paste->created = new \DateTime("now", $timezone); if ($request->get("expires") != "Never") { $paste->expires = true; $paste->expiration = new \DateTime($request->get("expires"), $timezone); } $dm->persist($paste); $dm->flush(); $pasteUrl = $this->app->path("view", ["uniqid" => $paste->uniqid]); return $this->app->json(["status" => 200, "redirect" => $pasteUrl]); } catch (\RuntimeException $e) { return $this->app->json(["status" => 403, "error" => "Database unavailable"]); } } /** * View function for pastes * * @param object $request An instance of Symfony's request class * @return object An instance of Symfony's response class */ public function viewPaste(\Symfony\Component\HttpFoundation\Request $request) { try { $dm = $this->app["deps"]["mongoDm"]; $paste = $dm->getRepository("\pasteshare\Paste")->findOneBy(["uniqid" => $request->get("uniqid")]); } catch (\RuntimeException $e) { } $options = $this->app["options"]; $options["paste"] = $paste->toArray(); $options["language"] = $this->getLanguagesFromCodeMirror()[$paste->language]; return $this->app->render("pages/main.twig", $options); } /** * This helper function parses the mode info from CodeMirror's mode/meta.js * * @return array The language information from mode/meta.js */ private function getLanguagesFromCodeMirror() { $meta = file_get_contents( $this->app["deps"]["siteConfig"]->paths->app_root . "/bower_components/codemirror/mode/meta.js" ); preg_match("/CodeMirror.modeInfo = (\[.*?\]);/s", $meta, $json); $json = $json[1]; preg_match_all("/{.*}/", $json, $languages); $return = []; foreach ($languages[0] as $language) { preg_match("/name:\s\"(.+?)\"/", $language, $name); preg_match("/mode:\s\"(.+?)\"/", $language, $mode); $return[$mode[1]] = [ "name" => $name[1], "mode" => $mode[1] ]; } return $return; } }
breaker1/pasteshare
controllers/pasteshare/PasteShare.php
PHP
mit
4,057
<!doctype html> <html lang="en"> <head> <title>Code coverage report for All files</title> <meta charset="utf-8" /> <link rel="stylesheet" href="prettify.css" /> <link rel="stylesheet" href="base.css" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <style type='text/css'> .coverage-summary .sorter { background-image: url(sort-arrow-sprite.png); } </style> </head> <body> <div class='wrapper'> <div class='pad1'> <h1> All files </h1> <div class='clearfix'> <div class='fl pad1y space-right2'> <span class="strong">100% </span> <span class="quiet">Statements</span> <span class='fraction'>23/23</span> </div> <div class='fl pad1y space-right2'> <span class="strong">100% </span> <span class="quiet">Branches</span> <span class='fraction'>22/22</span> </div> <div class='fl pad1y space-right2'> <span class="strong">100% </span> <span class="quiet">Functions</span> <span class='fraction'>4/4</span> </div> <div class='fl pad1y space-right2'> <span class="strong">100% </span> <span class="quiet">Lines</span> <span class='fraction'>23/23</span> </div> </div> </div> <div class='status-line high'></div> <div class="pad1"> <table class="coverage-summary"> <thead> <tr> <th data-col="file" data-fmt="html" data-html="true" class="file">File</th> <th data-col="pic" data-type="number" data-fmt="html" data-html="true" class="pic"></th> <th data-col="statements" data-type="number" data-fmt="pct" class="pct">Statements</th> <th data-col="statements_raw" data-type="number" data-fmt="html" class="abs"></th> <th data-col="branches" data-type="number" data-fmt="pct" class="pct">Branches</th> <th data-col="branches_raw" data-type="number" data-fmt="html" class="abs"></th> <th data-col="functions" data-type="number" data-fmt="pct" class="pct">Functions</th> <th data-col="functions_raw" data-type="number" data-fmt="html" class="abs"></th> <th data-col="lines" data-type="number" data-fmt="pct" class="pct">Lines</th> <th data-col="lines_raw" data-type="number" data-fmt="html" class="abs"></th> </tr> </thead> <tbody><tr> <td class="file high" data-value="components"><a href="components/index.html">components</a></td> <td data-value="100" class="pic high"><div class="chart"><div class="cover-fill cover-full" style="width: 100%;"></div><div class="cover-empty" style="width:0%;"></div></div></td> <td data-value="100" class="pct high">100%</td> <td data-value="4" class="abs high">4/4</td> <td data-value="100" class="pct high">100%</td> <td data-value="2" class="abs high">2/2</td> <td data-value="100" class="pct high">100%</td> <td data-value="0" class="abs high">0/0</td> <td data-value="100" class="pct high">100%</td> <td data-value="4" class="abs high">4/4</td> </tr> <tr> <td class="file high" data-value="config"><a href="config/index.html">config</a></td> <td data-value="100" class="pic high"><div class="chart"><div class="cover-fill cover-full" style="width: 100%;"></div><div class="cover-empty" style="width:0%;"></div></div></td> <td data-value="100" class="pct high">100%</td> <td data-value="2" class="abs high">2/2</td> <td data-value="100" class="pct high">100%</td> <td data-value="0" class="abs high">0/0</td> <td data-value="100" class="pct high">100%</td> <td data-value="0" class="abs high">0/0</td> <td data-value="100" class="pct high">100%</td> <td data-value="2" class="abs high">2/2</td> </tr> <tr> <td class="file high" data-value="redux/reducers"><a href="redux/reducers/index.html">redux/reducers</a></td> <td data-value="100" class="pic high"><div class="chart"><div class="cover-fill cover-full" style="width: 100%;"></div><div class="cover-empty" style="width:0%;"></div></div></td> <td data-value="100" class="pct high">100%</td> <td data-value="17" class="abs high">17/17</td> <td data-value="100" class="pct high">100%</td> <td data-value="20" class="abs high">20/20</td> <td data-value="100" class="pct high">100%</td> <td data-value="4" class="abs high">4/4</td> <td data-value="100" class="pct high">100%</td> <td data-value="17" class="abs high">17/17</td> </tr> </tbody> </table> </div><div class='push'></div><!-- for sticky footer --> </div><!-- /wrapper --> <div class='footer quiet pad2 space-top1 center small'> Code coverage generated by <a href="http://istanbul-js.org/" target="_blank">istanbul</a> at Mon Feb 20 2017 22:58:31 GMT+0700 (ICT) </div> </div> <script src="prettify.js"></script> <script> window.onload = function () { if (typeof prettyPrint === 'function') { prettyPrint(); } }; </script> <script src="sorter.js"></script> </body> </html>
phuochau/react-native-boilerplate-production
coverage/index.html
HTML
mit
4,854
package jokrey.utilities.network.mcnp.nbio; import jokrey.utilities.encoder.tag_based.implementation.length_indicator.type.transformer.LITypeToBytesTransformer; import jokrey.utilities.encoder.type_transformer.TypeToFromRawTransformer; import jokrey.utilities.network.mcnp.io.ConnectionHandler.ConnectionState; import jokrey.utilities.network.mcnp.MCNP_Connection; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * A simple comfort wrapper for the client side of a MCNP c. * * Provides Wrapping functionality for all MCNP_HELPER methods. * @author jokrey */ public class MCNP_ConnectionAIO implements MCNP_Connection { /** can obviously also be used directly, for many operations it even has too */ public final AsynchronousSocketChannel c; public MCNP_ConnectionAIO(AsynchronousSocketChannel connection) { this.c = connection; } @Override public void close() throws IOException { c.close(); } public boolean isClosed() { return !c.isOpen(); } private int timeout = Integer.MAX_VALUE; public void setTimeout(int timeout) { this.timeout=timeout; } public void flush() { } @Override public void send_fixed(byte[] arr) throws IOException { try { write_fixed(arr).get(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { throw new IOException("[Channel threw exception: {"+e.getClass().getName()+" - "+e.getMessage()+"}]"); } } @Override public int receive_fixed(byte[] b, int off, int len) throws IOException { try { return c.read(ByteBuffer.wrap(b, off, len)).get(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { throw new IOException("[Channel threw exception: {"+e.getClass().getName()+" - "+e.getMessage()+"}]"); } } public Future<Integer> write_fixed(byte[] arr) { return c.write(ByteBuffer.wrap(arr)); } public Future<Integer> read_fixed(byte[] b, int off, int len) { return c.read(ByteBuffer.wrap(b, off, len)); } public<V> void write_fixed(byte[] arr, V attach, CompletionHandler<Integer, V> handler) { c.write(ByteBuffer.wrap(arr), attach, handler); } public<V> void write_variable(byte[] arr, V attach, CompletionHandler<Integer, V> handler) { write_fixed(getTransformer().transform((long) arr.length), attach, new CompletionHandler<Integer, V>() { @Override public void completed(Integer result, V attachment) { write_fixed(arr, attachment, handler); } @Override public void failed(Throwable exc, V attachment) { handler.failed(exc, attachment); } }); } public void expect_fixed(int len, ReceivedHandler handler) { ByteBuffer buffer = ByteBuffer.allocate(len); expect_fixed(buffer, len, handler); } public void expect_fixed(ByteBuffer buffer, int len, ReceivedHandler handler) { c.read(buffer, handler, new CompletionHandler<Integer, ReceivedHandler>() { @Override public void completed(Integer read, ReceivedHandler attachment) { if(handler==null)return; try { buffer.flip(); if(read == len) { handler.received(MCNP_ConnectionAIO.this, buffer.array()); } else if(read!= -1){ throw new RuntimeException("read wrong number of bytes"); } } catch (IOException e) { throw new RuntimeException("read wrong number of bytes"); } } @Override public void failed(Throwable throwable, ReceivedHandler handler) { throwable.printStackTrace(); } }); } public void expect_variable(ReceivedHandler handler) { expect_fixed(8, (conn, received) -> { long length = getTransformer().detransform_long(received); expect_fixed((int) length, handler); }); } public<V> void expect_variable(ByteBuffer buf, V attachment, CompletionHandler<Integer, V> handler) { expect_fixed(8, (conn, received) -> { long length = getTransformer().detransform_long(received); c.read(buf, attachment, handler); }); } public interface ReceivedHandler { void received(MCNP_ConnectionAIO conn, byte[] received) throws IOException; } private ByteBuffer cause_buffer = ByteBuffer.allocate(4); public<CT extends ConnectionState> void expect_cause(CT state, CauseReceivedHandler<CT> handler) { cause_buffer.clear(); expect_fixed(cause_buffer, 4, (conn, received) -> handler.received_cause(MCNP_ConnectionAIO.this, getTransformer().detransform_int(received), state)); } public interface CauseReceivedHandler<CT extends ConnectionState> { void received_cause(MCNP_ConnectionAIO conn, int cause, CT state) throws IOException; } @Override public TypeToFromRawTransformer<byte[]> getTransformer() { return new LITypeToBytesTransformer(); } //reimplementing default implementation to indicate that this is very much the desired. and should not be changed @Override public final boolean equals(Object obj) { return this==obj; } @Override public final int hashCode() { return super.hashCode(); } }
jokrey/utility-algorithms-java
src/jokrey/utilities/network/mcnp/nbio/MCNP_ConnectionAIO.java
Java
mit
5,844
const WRAPPER = Symbol('wrapper'); /** * @function * @description Decorator function that convert a class method to a getter */ export default function getter( prototype, property, { initializer, value, get }, ) { return { configurable: true, enumerable: true, get() { if (!this[WRAPPER]) { this[WRAPPER] = {}; } if (!this[WRAPPER][property]) { const targetSymbol = Symbol(`${property}-target`); this[targetSymbol] = initializer ? this::initializer() : value || get; this[WRAPPER][property] = typeof this[targetSymbol] === 'function' ? () => this[targetSymbol]() : () => this[targetSymbol]; } return this[WRAPPER][property](); }, }; }
ringcentral/ringcentral-js-widget
packages/ringcentral-integration/lib/getter.js
JavaScript
mit
763
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2015 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ sap.ui.define(['jquery.sap.global', './SplitContainerRenderer', 'sap/ui/core/Renderer'], function(jQuery, SplitContainerRenderer, Renderer) { "use strict"; /** * SplitApp renderer. * @namespace */ var SplitAppRenderer = { }; var SplitAppRenderer = Renderer.extend(SplitContainerRenderer); SplitAppRenderer.renderAttributes = function(oRm, oControl){ sap.m.BackgroundHelper.addBackgroundColorStyles(oRm, oControl.getBackgroundColor(), oControl.getBackgroundImage()); }; SplitAppRenderer.renderBeforeContent = function(oRm, oControl){ sap.m.BackgroundHelper.renderBackgroundImageTag(oRm, oControl, "sapMSplitContainerBG", oControl.getBackgroundImage(), oControl.getBackgroundRepeat(), oControl.getBackgroundOpacity()); }; return SplitAppRenderer; }, /* bExport= */ true);
pensoffsky/OpenUI5-AppCache
resources/sap/m/SplitAppRenderer-dbg.js
JavaScript
mit
989
from storytext.javaswttoolkit import describer as swtdescriber from org.eclipse.core.internal.runtime import InternalPlatform from org.eclipse.ui.forms.widgets import ExpandableComposite import os from pprint import pprint class Describer(swtdescriber.Describer): swtdescriber.Describer.stateWidgets = [ ExpandableComposite ] + swtdescriber.Describer.stateWidgets swtdescriber.Describer.ignoreChildren = (ExpandableComposite,) + swtdescriber.Describer.ignoreChildren def buildImages(self): swtdescriber.Describer.buildImages(self) self.buildImagesFromBundles() def buildImagesFromBundles(self): allImageTypes = [ "gif", "png", "jpg" ] allImageTypes += [ i.upper() for i in allImageTypes ] cacheFile = os.path.join(os.getenv("STORYTEXT_HOME"), "osgi_bundle_image_types") cacheExists = os.path.isfile(cacheFile) bundleImageTypes = eval(open(cacheFile).read()) if cacheExists else {} for bundle in InternalPlatform.getDefault().getBundleContext().getBundles(): usedTypes = [] name = bundle.getSymbolicName() imageTypes = bundleImageTypes.get(name, allImageTypes) for imageType in imageTypes: self.logger.debug("Searching bundle " + name + " for images of type " + imageType) images = bundle.findEntries("/", "*." + imageType, True) if images and images.hasMoreElements(): self.storeAllImages(images) usedTypes.append(imageType) if not cacheExists: bundleImageTypes[name] = usedTypes if not cacheExists: f = open(cacheFile, "w") pprint(bundleImageTypes, f) f.close() def storeAllImages(self, entries): while entries.hasMoreElements(): url = entries.nextElement() self.storeImageData(url) def getExpandableCompositeState(self, widget): return widget.isExpanded() def getExpandableCompositeDescription(self, widget): state = self.getExpandableCompositeState(widget) self.widgetsWithState[widget] = state desc = "Expandable '" + widget.getText() + "' " desc += "(expanded)" if state else "(collapsed)" if state: clientDesc = self.getDescription(widget.getClient()) desc += "\n " + clientDesc.replace("\n", "\n ") return desc
emilybache/texttest-runner
src/main/python/storytext/lib/storytext/javarcptoolkit/describer.py
Python
mit
2,499
import os from setuptools import find_packages from setuptools import setup version = '1.0' project = 'kotti_mb' install_requires=[ 'Kotti', ], here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.rst')).read() CHANGES = open(os.path.join(here, 'CHANGES.txt')).read() setup(name=project, version=version, description="AddOn for Kotti", long_description=README + '\n\n' + CHANGES, classifiers=[ "Programming Language :: Python", "Framework :: Pyramid", "License :: Repoze Public License", ], keywords='kotti addon', author='Christoph Boehner', author_email='cb@vorwaerts-werbung.de', url='http://pypi.python.org/pypi/', license='bsd', packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=install_requires, tests_require=[], entry_points={ 'fanstatic.libraries': [ 'kotti_mb = kotti_mb.fanstatic:library', ], }, extras_require={}, message_extractors={'kotti_mb': [ ('**.py', 'lingua_python', None), ('**.zcml', 'lingua_xml', None), ('**.pt', 'lingua_xml', None), ]}, )
potzenheimer/kotti_mb
setup.py
Python
mit
1,275
require 'rails' require 'rails/generators' require_relative '../../yaml_loader' module MongoidModelMaker class FullGenerator < Rails::Generators::Base argument :schema, type: :string, required: true, desc: "Yaml schema file, describes models, relations and factories" def main MongoidModelMaker::Models.new(schema).run_all end end end
Dawil/MongoidModelMaker
lib/generators/mongoid_model_maker/full_generator.rb
Ruby
mit
359
import DS from 'ember-data'; import BackboneElement from 'ember-fhir/models/backbone-element'; const { belongsTo, hasMany } = DS; export default BackboneElement.extend({ resource: belongsTo('reference', { async: false }), param: hasMany('test-script-param', { async: true }) });
davekago/ember-fhir
addon/models/test-script-rule.js
JavaScript
mit
284
<html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Play</title> <link rel="icon" type="image/png" href="Images/favicon_new_1.png"> <link href="dist/css/bootstrap.css" rel="stylesheet"> <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"> <link href="animate.css" rel="stylesheet"> <link href='https://fonts.googleapis.com/css?family=Lato' rel='stylesheet' type='text/css'> </head> <body> <div class="container"> <nav class="navbar navbar-default navbar-fixed-top nav-bg" role="navigation"> <div class="container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <div class="namescoot"><a class="navbar-brand" href="index.html"><h3>Meg Becker</h3></a></div> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right textuppernav"> <li><a href="design.html">Work</a></li> <li><a href="play.html">Play</a></li> <li><a href="about.html">About</a></li> </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav> </div> <div class="padtop"> </div> <div class="nopadding"> <div class="row no-gutters row-no-gutter"> <div clss="pad"> <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"> <div class="menuimage"> <div class="animated fadeindown"> <div class="box img-responsive" style="background:url(Images/adv-9-horiz.jpg) no-repeat 50% 50%;"> <a href="/adventures.html"> <div class="overlay4"> <span class="caption2 text-uppercase"> <h3>Adventures</h3> <h3>Through</h3> <h3>Type and Space</h3> </span> </div> </a> </div> </div> </div> </div> <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"> <div class="menuimage"> <div class="animated fadeindown"> <div class="box img-responsive" style="background:url(Images/Instinct_horiz.jpg) no-repeat 50% 50%;"> <a href="/instinct.html"> <div class="overlay4"> <span class="caption text-uppercase"> <h3>Trust Your</h3> <h3>Instinct</h3> </span> </div> </a> </div> </div> </div> </div> <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"> <div class="menuimage"> <div class="animated fadeindown"> <div class="box img-responsive" style="background:url(Images/processbook-horiz.jpg) no-repeat 50% 50%;"> <a href="/processbook.html"> <div class="overlay4"> <span class="caption text-uppercase"> <h3>Process</h3> <h3>Book</h3> </span> </div> </a> </div> </div> </div> </div> <div clss="pad"> <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"> <div class="menuimage"> <div class="animated fadeindown"> <div class="box img-responsive" style="background:url(Images/introspect-horiz.jpg) no-repeat 50% 50%;"> <a href="/introspect.html"> <div class="overlay4"> <span class="caption3 text-uppercase"> <h3>Introspect</h3> </span> </div> </a> </div> </div> </div> </div> <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"> <div class="menuimage"> <div class="animated fadeindown"> <div class="box img-responsive" style="background:url(Images/Memory-horiz.jpg) no-repeat 50% 50%;"> <a href="/memoryabstraction.html"> <div class="overlay4"> <span class="caption text-uppercase"> <h3>Memory</h3> <h3>Abstraction</h3> </span> </div> </a> </div> </div> </div> </div> <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"> <div class="menuimage"> <div class="animated fadeindown"> <div class="box img-responsive" style="background:url(Images/Fear-horiz.jpg) no-repeat 50% 50%;"> <a href="/fear.html"> <div class="overlay4"> <span class="caption text-uppercase"> <h3>an exploration</h3> <h3>of fear</h3> </span> </div> </a> </div> </div> </div> </div> </div> </div> </div> </div> <div class="clearfix footer1 navbar-fixed-bottom"> <div class="container"> <div class="animated fadeinup"> <div class="fonticons footertext faicon"> <a href="mailto:megbeckerdesign@gmail.com" target="_blank" ><i class="fa fa-envelope-o fa-1x"></i></a> <a href="http://linkedin.com/in/megbecker/" target="_blank"><i class="fa fa-linkedin-square fa-1x"></i></a> <a href="http://instagram.com/megbeckah/" target="_blank"><i class="fa fa-instagram fa-1x"></i></a> </div> </div> </div> </div> <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="dist/js/bootstrap.min.js"></script> </body> </html>
MegBecker/MegBecker.github.io
play.html
HTML
mit
6,314
-- Testbot, with turn penalty -- Used for testing turn penalties require 'testbot' properties.left_hand_driving = false local turn_penalty = 50 local turn_bias = properties.left_hand_driving and 1/1.2 or 1.2 function turn_function (angle) ---- compute turn penalty as angle^2, with a left/right bias -- multiplying by 10 converts to deci-seconds see issue #1318 k = 10*turn_penalty/(90.0*90.0) if angle>=0 then return angle*angle*k/turn_bias else return angle*angle*k*turn_bias end end
antlad/route_solver_service
profiles/rhs.lua
Lua
mit
533
// The MIT License (MIT) // // Copyright (c) Andrew Armstrong/FacticiusVir 2020 // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // This file was automatically generated and should not be edited directly. using System; namespace SharpVk.Interop.Khronos { /// <summary> /// /// </summary> public unsafe delegate SharpVk.Result VkDeviceGetPipelineExecutableInternalRepresentationsDelegate(SharpVk.Interop.Device device, SharpVk.Interop.Khronos.PipelineExecutableInfo* executableInfo, uint* internalRepresentationCount, SharpVk.Interop.Khronos.PipelineExecutableInternalRepresentation* internalRepresentations); }
FacticiusVir/SharpVk
src/SharpVk/Interop/Khronos/VkDeviceGetPipelineExecutableInternalRepresentationsDelegate.gen.cs
C#
mit
1,661
using System; using LanceTrack.Cqrs.Contract; using LinqToDB.Mapping; namespace LanceTrack.Server.Cqrs.ProjectTime.Events { [Table("InvoiceEvents")] public class InvoiceEvent : IEvent<ProjectTimeAggregateRoot, int> { [Identity, PrimaryKey] public int Id { get; set; } [Column] public int ProjectId { get; set; } [Column] public int UserId { get; set; } [Column] public DateTimeOffset At { get; set; } [Column] public InvoiceEventType EventType { get; set; } [Column] public string InvoiceNum { get; set; } [Column] public decimal InvoiceSum { get; set; } [Column] public decimal Hours { get; set; } [Column] public int RegisteredByUserId { get; set; } [Column] public DateTimeOffset RegisteredAt { get; set; } [NotColumn] public int AggregateRootId { get { return ProjectId; } } } }
rd-dev-ukraine/demo-time-track
LanceTrack.Server.Cqrs/ProjectTime/Events/InvoiceEvent.cs
C#
mit
988
# Natural Language Toolkit: POS Tag Simplification # # Copyright (C) 2001-2013 NLTK Project # Author: Steven Bird <stevenbird1@gmail.com> # URL: <http://www.nltk.org/> # For license information, see LICENSE.TXT # Brown Corpus # http://khnt.hit.uib.no/icame/manuals/brown/INDEX.HTM brown_mapping1 = { 'j': 'ADJ', 'p': 'PRO', 'm': 'MOD', 'q': 'DET', 'w': 'WH', 'r': 'ADV', 'i': 'P', 'u': 'UH', 'e': 'EX', 'o': 'NUM', 'b': 'V', 'h': 'V', 'f': 'FW', 'a': 'DET', 't': 'TO', 'cc': 'CNJ', 'cs': 'CNJ', 'cd': 'NUM', 'do': 'V', 'dt': 'DET', 'nn': 'N', 'nr': 'N', 'np': 'NP', 'nc': 'N', '--': '--' } brown_mapping2 = { 'vb': 'V', 'vbd': 'VD', 'vbg': 'VG', 'vbn': 'VN' } def simplify_brown_tag(tag): tag = tag.lower() if tag[0] in brown_mapping1: return brown_mapping1[tag[0]] elif tag[:2] in brown_mapping1: # still doesn't handle DOD tag correctly return brown_mapping1[tag[:2]] try: if '-' in tag: tag = tag.split('-')[0] return brown_mapping2[tag] except KeyError: return tag.upper() # Wall Street Journal tags (Penn Treebank) wsj_mapping = { '-lrb-': '(', '-rrb-': ')', '-lsb-': '(', '-rsb-': ')', '-lcb-': '(', '-rcb-': ')', '-none-': '', 'cc': 'CNJ', 'cd': 'NUM', 'dt': 'DET', 'ex': 'EX', 'fw': 'FW', # existential "there", foreign word 'in': 'P', 'jj': 'ADJ', 'jjr': 'ADJ', 'jjs': 'ADJ', 'ls': 'L', 'md': 'MOD', # list item marker 'nn': 'N', 'nnp': 'NP', 'nnps': 'NP', 'nns': 'N', 'pdt': 'DET', 'pos': '', 'prp': 'PRO', 'prp$': 'PRO', 'rb': 'ADV', 'rbr': 'ADV', 'rbs': 'ADV', 'rp': 'PRO', 'sym': 'S', 'to': 'TO', 'uh': 'UH', 'vb': 'V', 'vbd': 'VD', 'vbg': 'VG', 'vbn': 'VN', 'vbp': 'V', 'vbz': 'V', 'wdt': 'WH', 'wp': 'WH', 'wp$': 'WH', 'wrb': 'WH', 'bes': 'V', 'hvs': 'V', 'prp^vbp': 'PRO' # additions for NPS Chat corpus } def simplify_wsj_tag(tag): if tag and tag[0] == '^': tag = tag[1:] try: tag = wsj_mapping[tag.lower()] except KeyError: pass return tag.upper() indian_mapping = { 'nn': 'N', 'vm': 'MOD', 'jj': 'ADJ', 'nnp': 'NP', 'prp': 'PRO', 'prep': 'PRE', 'vaux': 'V', 'vfm': 'V', 'cc': 'CNJ', 'nnpc': 'NP', 'nnc': 'N', 'qc': 'QC', 'dem': 'DET', 'vrb': 'V', 'qfnum': 'NUM', 'rb': 'ADV', 'qf': 'DET', 'punc': '.', 'rp': 'PRT', 'psp': 'PSP', 'nst': 'N', 'nvb': 'N', 'vjj': 'V', 'neg': 'NEG', 'vnn': 'V', 'xc': 'XC', 'intf': 'INTF', 'nloc': 'N', 'jvb': 'ADJ', 'wq': 'WH', 'qw': 'WH', 'jj:?': 'ADJ', '"cc': 'CNJ', 'nnp,': 'NP', 'sym\xc0\xa7\xb7': 'SYM', 'symc': 'SYM'} def simplify_indian_tag(tag): if ':' in tag: tag = tag.split(':')[0] try: tag = indian_mapping[tag.lower()] except KeyError: pass return tag.upper() # Alpino tags alpino_mapping = { 'noun':'N', 'name': 'NP', 'vg': 'VG', 'punct':'.', 'verb':'V', 'pron': 'PRO', 'prep':'P' } def simplify_alpino_tag(tag): try: tag = alpino_mapping[tag] except KeyError: pass return tag.upper() # Default tag simplification def simplify_tag(tag): return tag[0].upper() if __name__ == "__main__": import doctest doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)
syllog1sm/TextBlob
text/nltk/tag/simplify.py
Python
mit
3,411
import codecs f = codecs.open("/Users/hjp/Downloads/task/data/dev.txt", 'r', 'utf-8') for line in f.readlines(): print(line) sents = line.split('\t') print(sents[1] + "\t" + sents[3]) for i in range(len(sents)): print(sents[i]) f.close()
hjpwhu/Python
src/hjp.edu.nlp.data.task/semeval.py
Python
mit
269
<md-card> <md-card-title> <md-card-title-text> <span class="md-headline">This Lab training networks</span> <span> Note: Scroll down to add networks from the list of trainings reported by your team members.</span> </md-card-title-text> </md-card-title> <md-card-content layout="column"> <div layout="row" layout-align="none center"> <span class="spacer-top-smaller">Filter:</span> <md-input-container class="input-row-longer"> <label>From year</label> <input ng-model="fromYearWork" ng-change="renderTrainings('new')"> </md-input-container> <md-input-container class="input-row-longer"> <label>To year</label> <input ng-model="toYearWork" ng-change="renderTrainings('new')"> </md-input-container> <md-button class="s48" ng-click="exportTrainingsSpreadsheet()" aria-label="Export selection" class="md-icon-button interaction-button"> <md-tooltip>Export filtered results to spreadsheet</md-tooltip> <md-icon md-svg-src="images/icons/spreadsheet.svg" class="s48"></md-icon> </md-button> </div> <form flex novalidate name="teamTrainingsForm" ng-submit="teamTrainingsForm.$valid && submitTrainingRemoval(forms['teamWorkRemove'])"> <div layout="row" class="paginator"> <md-input-container class="input-no-margin wider"> <label>Results/page</label> <md-select ng-model="pageSize" md-on-close="renderTrainings('new')" aria-label="pageSize" name="pageSize"> <md-option ng-value="10">10</md-option> <md-option ng-value="20">20</md-option> <md-option ng-value="50">50</md-option> </md-select> </md-input-container> <md-input-container class="input-no-margin"> <label>Page</label> <md-select ng-model="currentPage" md-on-close="renderTrainings('page')" aria-label="currentPage" name="currentPage"> <md-option ng-repeat="page in pages" ng-value="page">{{page}}</md-option> </md-select> </md-input-container> </div> This list contains <strong>{{selectedTrainings.length}} training networks</strong>. <ul> <li class="spacer-top" ng-repeat="(pubNum,work) in currTrainings track by $index"> <div layout="column" layout-gt-sm="row"> <div flex-gt-sm="80"> {{work.start | date : 'yyyy'}}-{{work.end | date : 'yyyy'}} : <b>{{work.network_name}}</b> - {{work.title}}, {{work.acronym}}. Ref: {{work.reference}}. </div> <div flex-gt-sm="20" layout="row"> <md-button ng-click="showDetailsTraining(work)" aria-label="Details" class="md-icon-button interaction-button"> <md-icon md-svg-src="images/icons/description_24px.svg"></md-icon> </md-button> <md-button ng-click="removeTraining(work)" aria-label="Remove" class="md-icon-button interaction-button"> <md-icon md-svg-src="images/icons/remove_24px.svg"></md-icon> </md-button> </div> </div> <md-divider class="spacer-top"></md-divider> </li> </ul> <div layout="row" class="paginator"> <md-input-container class="input-no-margin wider"> <label>Results/page</label> <md-select ng-model="pageSize" md-on-close="renderTrainings('new')" aria-label="pageSize" name="pageSize"> <md-option ng-value="10">10</md-option> <md-option ng-value="20">20</md-option> <md-option ng-value="50">50</md-option> </md-select> </md-input-container> <md-input-container class="input-no-margin"> <label>Page</label> <md-select ng-model="currentPage" md-on-close="renderTrainings('page')" aria-label="currentPage" name="currentPage"> <md-option ng-repeat="page in pages" ng-value="page">{{page}}</md-option> </md-select> </md-input-container> </div> <div layout="column" layout-gt-sm="row" layout-align="none center"> <md-button type="submit" class="button-small md-raised md-primary">Confirm removal</md-button> <div class="status-message" ng-hide="hideMessage[forms['teamWorkRemove']]"> <span class="message" ng-class="messageType[forms['teamWorkRemove']]"> {{updateStatus[forms['teamWorkRemove']]}} </span> </div> </div> </form> </md-card-content> </md-card>
jose-braga/data-management
app_client/team/productivity/funding/team.labTrainings.html
HTML
mit
5,837
#include "allhead.h" #include <string.h> #include <stdlib.h> #include <stdio.h> #include <time.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <dirent.h> #include <unistd.h> #include <sys/stat.h> #include "NLPIR.h" #define EML__SYSTEMS__ #include <assert.h> char* workspace=NULL; char* dicpath=NULL; typedef char (*SpiPtr)[255]; extern int RelasePage(void); static SpiPtr ImportDic(); extern "C" { int SpliterMain(int argc, char* argv[]) { int index=0; char *q=NULL; clock_t A=clock(); int NumPatt=0; if(argc>=4) dicpath=argv[3]; SpiPtr dicptr=ImportDic(); if(dicptr) { char filepath[1024]; DIR* d; struct dirent *file; if(!(d=opendir(argv[1]))) { printf("error in open dir : %s\n",argv[1]); return 0; } while((file=readdir(d))!=NULL) { if(strncmp(file->d_name,".",1)==0) continue; { /*判断是文件夹处理下一个*/ struct stat info; stat(file->d_name,&info); if(S_ISDIR(info.st_mode)) continue; } workspace=argv[1]; assert(workspace!=NULL); memset(filepath,0,sizeof(filepath)); strcat(filepath,argv[1]); filepath[strlen(filepath)]='/'; strcat(filepath,file->d_name); #ifdef __DEBUG__8899 printf("before testImportUserDict\n"); #endif q=testImportUserDict(1,&NumPatt,filepath); #ifdef __DEBUG__8899 printf("after testImportUserDict\n"); #endif #ifdef __DEBUG printf("\n------using brute match methods---------\n"); #endif index=HashMach(q,dicptr,NumPatt); //printf("RelasePage before\n"); RelasePage(); //printf("RelasePage after\n"); if(index) { //printf("free before\n"); free(dicptr); //printf("free after\n"); closedir(d); return index; } } //printf("exit free before\n"); free(dicptr); //printf("exit free after\n"); closedir(d); return index; } //printf("return 0\n"); return 0; } } extern "C" { int SpliterInit(void) { if(!NLPIR_Init(0,1)) { printf("NLPIR INIT FAILED!\n"); //初始化失败,退出。 return 0; } else { printf("------------Init ok!--------------\n\n"); } return 1; } int SpliterExit(void) { NLPIR_Exit(); return 1; } } static SpiPtr ImportDic() { int i=0; FILE *filPtr=NULL; SpiPtr p=(SpiPtr)malloc(300*255); if(!p) { printf("fatal error!, can't malloc memory for dictionary, will return NULL\n"); return NULL; } if(!dicpath) filPtr=fopen("userdict.txt","rb"); else filPtr=fopen(dicpath,"rb"); if(!filPtr) { free(p); return NULL; } while (!feof(filPtr)) { memset(p[i],0,255); int nu=fscanf(filPtr, "%s",p[i]); if(nu<0) continue; i++; // printf("the add dict is %s\n",p[i-1]); } fclose(filPtr); if(i==0) { printf("dic is empty, will go back directly\n"); free(p); return NULL; } return p; }
NEWPLAN/emlproj
spliter/main.cpp
C++
mit
3,374
package com.github.stocky37.util.cache.config; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeName; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import io.dropwizard.setup.Environment; import io.dropwizard.util.Duration; @JsonTypeName("guava") public class GuavaCacheFactory<K, V> implements CacheFactory<K, V> { private final CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder(); @JsonProperty public GuavaCacheFactory recordStats(boolean recordStats) { if(recordStats) cacheBuilder.recordStats(); return this; } @JsonProperty public GuavaCacheFactory initialCapacity(int initialCapacity) { cacheBuilder.initialCapacity(initialCapacity); return this; } @JsonProperty public GuavaCacheFactory concurrencyLevel(int concurrencyLevel) { cacheBuilder.concurrencyLevel(concurrencyLevel); return this; } @JsonProperty public GuavaCacheFactory maximumSize(long size) { cacheBuilder.maximumSize(size); return this; } @JsonProperty public GuavaCacheFactory maximumWeight(long weight) { cacheBuilder.maximumWeight(weight); return this; } @JsonProperty public GuavaCacheFactory weakKeys(boolean weakKeys) { if(weakKeys) cacheBuilder.weakKeys(); return this; } @JsonProperty public GuavaCacheFactory weakValues(boolean weakValues) { if(weakValues) cacheBuilder.weakValues(); return this; } @JsonProperty public GuavaCacheFactory softValues(boolean softValues) { if(softValues) cacheBuilder.softValues(); return this; } @JsonProperty public GuavaCacheFactory expireAfterWrite(Duration duration) { cacheBuilder.expireAfterWrite(duration.getQuantity(), duration.getUnit()); return this; } @JsonProperty public GuavaCacheFactory expireAfterAccess(Duration duration) { cacheBuilder.expireAfterAccess(duration.getQuantity(), duration.getUnit()); return this; } @JsonIgnore public CacheBuilder<Object, Object> getCacheBuilder() { return cacheBuilder; } @Override public <K1 extends K, V1 extends V> Cache<K1, V1> build() { return cacheBuilder.build(); } }
stocky37/dropwizard-util
cache/src/main/java/com/github/stocky37/util/cache/config/GuavaCacheFactory.java
Java
mit
2,194
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>The Time Machine</title> <link rel="stylesheet" href="css/main.css" type="text/css" /> </head> <body> <div id="container"> <canvas width="800px" height="500px"></canvas> <a class="controls-link" href="#controls">Controls</a> <div class="controls"> <fieldset class="controls"> <input type="text" value="Untitled"/> <textarea id="input">The Time Machine. By H.G. Wells. The Time Traveller (for so it will be convenient to speak of him) was expounding a recondite matter to us. His grey eyes shone and twinkled, and his usually pale face was flushed and animated. The fire burned brightly, and the soft radiance of the incandescent lights in the lilies of silver caught the bubbles that flashed and passed in our glasses. Our chairs, being his patents, embraced and caressed us rather than submitted to be sat upon, and there was that luxurious after-dinner atmosphere when thought roams gracefully free of the trammels of precision. And he put it to us in this way—marking the points with a lean forefinger—as we sat and lazily admired his earnestness over this new paradox (as we thought it) and his fecundity.</textarea> <button value="Share Drawing">Share Drawing</button> <input type="text" value="some-url"/> </fieldset> </div> </div> <div id="social"> <p>Draw and share a story.</p> <p class="social"> <iframe src="http://www.facebook.com/plugins/like.php?href=http://www.andrew-hoyer.com/experiments/walking/&amp;layout=button_count&amp;show_faces=false&amp;width=90&amp;action=like&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:90px; height:21px;" allowTransparency="true"></iframe> <a href="http://twitter.com/share" class="twitter-share-button" data-url="http://andrew-hoyer.com/experiments/walking/" data-text="Walking with CSS3 by @ndrwhr:" data-count="horizontal">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script> </p> <p><a href="http://andrew-hoyer.com/experiments">(more experiments)</a></p> </div> <script src="js/prototypes.js" type="text/javascript" charset="utf-8"></script> <script src="js/vector.js" type="text/javascript" charset="utf-8"></script> <script src="js/cursor.js" type="text/javascript" charset="utf-8"></script> <script src="js/lettersizer.js" type="text/javascript" charset="utf-8"></script> <script src="js/contentiterator.js" type="text/javascript" charset="utf-8"></script> <script src="js/canvas.js" type="text/javascript" charset="utf-8"></script> <script src="js/main.js" type="text/javascript" charset="utf-8"></script> </body> </html>
ndrwhr/timemachine
index.html
HTML
mit
2,822
namespace CarStore.Controllers { using System.Web.Mvc; using CarStore.Data; using System.Linq; using Models.Cars; public class HomeController : Controller { public ActionResult Index() { var db = new CarDbContext(); var cars = db.Cars .OrderByDescending(c => c.Id) .Take(3) .Select(c => new CarListingModel { Id = c.Id, Year = c.Year, ImageUrl = c.ImageUrl, Make = c.Make, Model = c.Model }) .ToList(); return View(cars); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } } }
Ivelin153/Car-Store
CarStore/Controllers/HomeController.cs
C#
mit
869
module.exports = function ( grunt ) { // Project configuration. grunt.initConfig({ pkg : grunt.file.readJSON( 'package.json' ), jshint : { options: { jshintrc: true }, files : ['src/javascripts/**/*.js'] }, browserify : { js: { src: 'src/javascripts/main.js', dest: 'dist/preamble.js' } }, usebanner: { dist: { options: { position: 'top', banner: '/* <%= pkg.title %> v<%= pkg.version %>' + ' - released on <%= grunt.template.today("yyyy-mm-dd") %>' + ' at <%= grunt.template.today("longTime") %>\n' + ' * <%= pkg.preamble.copyright %>\n' + ' * <%= pkg.preamble.distrights%>\n' + '*/', linebreak: true }, files: { src: [ 'dist/preamble.js', 'dist/preamble.js' ] } } }, watch : { js : { files : ['src/javascripts/**/*.js'], tasks : ['jshint'], options : { interrupt : true } }, browserify : { files : ['src/javascripts/**/*.js'], tasks : ['browserify'], options : { interrupt : true } }, banner : { files : ['dist/preamble.js'], tasks : ['usebanner'], options : { interrupt : true } } } }); // Load the plugins grunt.loadNpmTasks( 'grunt-contrib-watch' ); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-browserify'); grunt.loadNpmTasks('grunt-banner'); // Default task(s). grunt.registerTask( 'default', ['watch'] ); grunt.registerTask( 'dist', ['jshint', 'browserify', 'usebanner'] ); };
jeffschwartz/preamble
Gruntfile.js
JavaScript
mit
2,149
<?php namespace Myspace\BookmarkBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Doctrine\Common\Collections\ArrayCollection; use JMS\Serializer\Annotation\Groups; /** * Bookmark * * @ORM\Table() * @ORM\Entity(repositoryClass="Myspace\BookmarkBundle\Repository\BookmarkRepository") */ class Bookmark { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") * @Groups({"list"}) */ private $id; /** * @var string * * @ORM\Column(name="url", type="text") * @Groups({"list"}) */ private $url; /** * @var string * * @ORM\Column(name="title", type="text", nullable=true) * @Groups({"list"}) */ private $title; /** * @var string * * @ORM\Column(name="slug", type="text",nullable=true) * @Groups({"list"}) */ private $slug; /** * @var string * * @ORM\Column(name="description", type="text", nullable=true) * @Groups({"list"}) */ private $description; /** * @var string * @Groups({"list"}) * @ORM\Column(name="icon", type="text", nullable=true) */ private $icon; /** * @var \DateTime * * @ORM\Column(name="created", type="datetime",nullable=true) * @Groups({"list"}) */ private $created; /** * @ORM\ManyToMany(targetEntity="Tag", inversedBy="bookmarks") * @ORM\JoinTable( * name="bookmark_tag", * joinColumns={@ORM\JoinColumn(name="bookmark_id",referencedColumnName="id")}, * inverseJoinColumns={@ORM\JoinColumn(name="tag_id", referencedColumnName="id")} * ) */ private $tags; /** * @ORM\OneToMany(targetEntity="BookmarkTag" , mappedBy="bookmark" , cascade={"all"} , orphanRemoval=true) * */ protected $bookmarktags; public function getBookmarktags() { return $this->bookmarktags; } /** * @ORM\ManyToOne(targetEntity="Category", inversedBy="bookmarks") * @ORM\JoinColumn(name="catid", referencedColumnName="id") * @Groups({"list"}) */ protected $category; /** * @ORM\OneToMany(targetEntity="Comment", mappedBy="bookmark") */ private $comments; public function __construct() { $this->comments = new ArrayCollection(); $this->tags = new ArrayCollection(); } public function getTags() { return $this->tags; } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set url * * @param string $url * @return Bookmark */ public function setUrl($url) { $this->url = $url; return $this; } /** * Get url * * @return string */ public function getUrl() { return $this->url; } /** * Set category * * @param string $category * @return Bookmark */ public function setCategory($category) { $this->category = $category; return $this; } /** * Get category * * @return Category */ public function getCategory() { return $this->category; } /** * Set title * * @param string $title * @return Bookmark */ public function setTitle($title) { $this->title = $title; return $this; } /** * Get title * * @return string */ public function getTitle() { return $this->title; } /** * Set icon * * @param string $icon * @return Bookmark */ public function setIcon($icon) { $this->icon = $icon; return $this; } /** * Get icon * * @return string */ public function getIcon() { return $this->icon; } /** * Set slug * * @param string $slug * @return Bookmark */ public function setSlug($slug) { $this->slug = $slug; return $this; } /** * Get slug * * @return string */ public function getSlug() { return $this->slug; } /** * Set description * * @param string $description * @return Bookmark */ public function setDescription($description) { $this->description = $description; return $this; } /** * Get description * * @return string */ public function getDescription() { return $this->description; } /** * Set created * * @param \DateTime $created * @return Bookmark */ public function setCreated($created) { $this->created = $created; return $this; } /** * Get created * * @return \DateTime */ public function getCreated() { return $this->created; } }
nguyenhuuhuy/bookmarkmanager
src/Myspace/BookmarkBundle/Entity/Bookmark.php
PHP
mit
4,901
'use strict'; const User = require('../../models/admin/user'), Role = require('../../models/admin/role'), page = require('../../util/page'), _ = require('lodash'); module.exports = class UserController { /** * Display a list of users. */ static index(req, res) { page(User, req).then(data => { res.render('admin/user/index', data); }); } /** * Render the form for editing a user. */ static edit(req, res) { let id = req.params.id, view = 'admin/user/form', roles = {'admin': 'Admin'}; Role.where({}).then(cursor => { cursor.project({'name': 1}).forEach(role => { roles[role._id] = role.name; }, err => { if (id) { User.find(id).then(user => { res.render(view, {doc: user.data, roles}); }); } else { res.render(view, {doc: {}, roles}); } }); }); } /** * Save a user. */ static save(req, res) { let data = _.pick(req.body, _.concat(User.keys, 'password')); User.save(data, req.params.id).then( result => { req.flash('success', 'Saved successfully!'); res.redirect('/admin/users'); }, err =>{ _.pull(data, 'password'); req.flash('error', 'An error happened'); req.flash('old', data); res.redirect('back'); }); } /** * Delete a user. */ static delete(req, res) { User.delete(req.params.id).then( count => { req.flash('success', 'Deleted successfully!'); res.redirect('/admin/users'); }, err => { req.flash('error', 'An error happened'); res.redirect('back'); }); } }
dsx190/ecommet
lib/controllers/admin/user.js
JavaScript
mit
1,534
<!DOCTYPE html> <html> <head> <title>{% if page.title %}{{ page.title }} – {% endif %}{{ site.name }} – {{ site.description }}</title> {% include meta.html %} <!--[if lt IE 9]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link rel="icon" href="/images/favicon.ico" type="image/x-icon"> <link rel="stylesheet" type="text/css" href="{{ site.baseurl }}/style.css" /> {% if page.style %} <style type="text/css"> {{ page.style }} </style> {% endif %} {% if page.math %} {% include mathjax.html %} {% endif %} <link rel="alternate" type="application/rss+xml" title="{{ site.name }} - {{ site.description }}" href="{{ site.baseurl }}/feed.xml" /> <!-- Created with Jekyll Now - http://github.com/barryclark/jekyll-now --> </head> <body> <div class="wrapper-masthead"> <div class="container"> <header class="masthead clearfix"> <a href="{{ site.baseurl }}/" class="site-avatar"><img src="{{ site.avatar }}" /></a> <div class="site-info"> <h1 class="site-name"><a href="{{ site.baseurl }}/">{{ site.name }}</a></h1> <p class="site-description">{{ site.description }}</p> </div> <nav> <a href="{{ site.baseurl }}/">Blog</a> <a href="http://www.innodatalabs.com">Home</a> </nav> </header> </div> </div> <div id="main" role="main" class="container"> {{ content }} </div> <div class="wrapper-footer"> <div class="container"> <footer class="footer"> {% include svg-icons.html %} </footer> </div> </div> {% include analytics.html %} </body> </html>
innodatalabs/innodatalabs.github.io
_layouts/default.html
HTML
mit
1,788
/** * File * * @author Tijme Gommers <t.gommers@jetcat.nl> * @package server.helpers */ module.exports = { /** * @var Object */ fs: require('fs'), /** * File exists * * @param string Path to the file * @return boolean exists */ exists: function(file) { try { var stats = module.exports.fs.statSync(file); return true; } catch(e) { return false; } }, /** * Create a file * * @param string Path to the file * @param string Content of the file * @return boolean created */ create: function(file, content) { try { module.exports.fs.writeFileSync(file, content); } catch(e) { console.log(e); return false; } } }
Tijme/reactive
server/helpers/file.js
JavaScript
mit
840
<div id="page-wrapper"> <div class="container-fluid"> <!-- Page Heading --> <div class="row"> <div class="col-lg-12"> <h1 class="page-header"> Gerenciar Produtos </h1> <ol class="breadcrumb"> <li> <i class="glyphicon glyphicon-home"></i> <a href="#">Home</a> </li> <li class="active"> <i class="glyphicon glyphicon-th-list"></i> Gerenciar Produtos </li> </ol> </div> <div class="col-lg-6"> <div class="list-group"> <a href="#PesquisarProdutos" class="list-group-item"> <h4 class="list-group-item-heading">Pesquisar Produtos</h4> <p class="list-group-item-text">Aqui é feito a pesquisa de produtoss</p> </a> <a href="#CadastrarProdutos" class="list-group-item "> <h4 class="list-group-item-heading">Cadastrar novos produto</h4> <p class="list-group-item-text">Aqui é cadastrado os produtos no estoque</p> </a> <a href="#ListarProdutos" class="list-group-item"> <h4 class="list-group-item-heading">Listar Todos os Produtos</h4> <p class="list-group-item-text">Aqui é listado dos os produtos disponiveis no estoque</p> </a> <a href="#ListarSemEstoqueProdutos" class="list-group-item"> <h4 class="list-group-item-heading">Listar Todos os Produtos que não possuem no estoque</h4> <p class="list-group-item-text">Mostra a Lista de todos os Produtos cadastrados que não possuem em estoque</p> </a> <a href="#ListarProdutosMenorQuantidade" class="list-group-item"> <h4 class="list-group-item-heading">Listar produtos em menor quantidade</h4> <p class="list-group-item-text">Produtos que possuem menos que cinco unidades no estoque</p> </a> </div> </div> </div> <!-- /.row --> </div> <!-- /.container-fluid --> </div> <!-- /#page-wrapper -->
luisjnk/FarmaPlus
front/Estoque/GerenciarProdutos.html
HTML
mit
2,880
/*! WebUploader 0.1.6 */ /** * @fileOverview 让内部各个部件的代码可以用[amd](https://github.com/amdjs/amdjs-api/wiki/AMD)模块定义方式组织起来。 * * AMD API 内部的简单不完全实现,请忽略。只有当WebUploader被合并成一个文件的时候才会引入。 */ (function (root, factory) { var modules = {}, // 内部require, 简单不完全实现。 // https://github.com/amdjs/amdjs-api/wiki/require _require = function (deps, callback) { var args, len, i; // 如果deps不是数组,则直接返回指定module if (typeof deps === 'string') { return getModule(deps); } else { args = []; for (len = deps.length, i = 0; i < len; i++) { args.push(getModule(deps[i])); } return callback.apply(null, args); } }, // 内部define,暂时不支持不指定id. _define = function (id, deps, factory) { if (arguments.length === 2) { factory = deps; deps = null; } _require(deps || [], function () { setModule(id, factory, arguments); }); }, // 设置module, 兼容CommonJs写法。 setModule = function (id, factory, args) { var module = { exports: factory }, returned; if (typeof factory === 'function') { args.length || (args = [_require, module.exports, module]); returned = factory.apply(null, args); returned !== undefined && (module.exports = returned); } modules[id] = module.exports; }, // 根据id获取module getModule = function (id) { var module = modules[id] || root[id]; if (!module) { throw new Error('`' + id + '` is undefined'); } return module; }, // 将所有modules,将路径ids装换成对象。 exportsTo = function (obj) { var key, host, parts, part, last, ucFirst; // make the first character upper case. ucFirst = function (str) { return str && (str.charAt(0).toUpperCase() + str.substr(1)); }; for (key in modules) { host = obj; if (!modules.hasOwnProperty(key)) { continue; } parts = key.split('/'); last = ucFirst(parts.pop()); while ((part = ucFirst(parts.shift()))) { host[part] = host[part] || {}; host = host[part]; } host[last] = modules[key]; } return obj; }, makeExport = function (dollar) { root.__dollar = dollar; // exports every module. return exportsTo(factory(root, _define, _require)); }, origin; if (typeof module === 'object' && typeof module.exports === 'object') { // For CommonJS and CommonJS-like environments where a proper window is present, module.exports = makeExport(); } else if (typeof define === 'function' && define.amd) { // Allow using this built library as an AMD module // in another project. That other project will only // see this AMD call, not the internal modules in // the closure below. define(['jquery'], makeExport); } else { // Browser globals case. Just assign the // result to a property on the global. origin = root.WebUploader; root.WebUploader = makeExport(); root.WebUploader.noConflict = function () { root.WebUploader = origin; }; } })(window, function (window, define, require) { /** * @fileOverview jQuery or Zepto * @require "jquery" * @require "zepto" */ define('dollar-third', [], function () { var req = window.require; var $ = window.__dollar || window.jQuery || window.Zepto || req('jquery') || req('zepto'); if (!$) { throw new Error('jQuery or Zepto not found!'); } return $; }); /** * @fileOverview Dom 操作相关 */ define('dollar', [ 'dollar-third' ], function (_) { return _; }); /** * 直接来源于jquery的代码。 * @fileOverview Promise/A+ * @beta */ define('promise-builtin', [ 'dollar' ], function ($) { var api; // 简单版Callbacks, 默认memory,可选once. function Callbacks(once) { var list = [], stack = !once && [], fire = function (data) { memory = data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for (; list && firingIndex < firingLength; firingIndex++) { list[firingIndex].apply(data[0], data[1]); } firing = false; if (list) { if (stack) { stack.length && fire(stack.shift()); } else { list = []; } } }, self = { add: function () { if (list) { var start = list.length; (function add(args) { $.each(args, function (_, arg) { var type = $.type(arg); if (type === 'function') { list.push(arg); } else if (arg && arg.length && type !== 'string') { add(arg); } }); })(arguments); if (firing) { firingLength = list.length; } else if (memory) { firingStart = start; fire(memory); } } return this; }, disable: function () { list = stack = memory = undefined; return this; }, // Lock the list in its current state lock: function () { stack = undefined; if (!memory) { self.disable(); } return this; }, fireWith: function (context, args) { if (list && (!fired || stack)) { args = args || []; args = [context, args.slice ? args.slice() : args]; if (firing) { stack.push(args); } else { fire(args); } } return this; }, fire: function () { self.fireWith(this, arguments); return this; } }, fired, firing, firingStart, firingLength, firingIndex, memory; return self; } function Deferred(func) { var tuples = [ // action, add listener, listener list, final state ['resolve', 'done', Callbacks(true), 'resolved'], ['reject', 'fail', Callbacks(true), 'rejected'], ['notify', 'progress', Callbacks()] ], state = 'pending', promise = { state: function () { return state; }, always: function () { deferred.done(arguments).fail(arguments); return this; }, then: function (/* fnDone, fnFail, fnProgress */) { var fns = arguments; return Deferred(function (newDefer) { $.each(tuples, function (i, tuple) { var action = tuple[0], fn = $.isFunction(fns[i]) && fns[i]; // deferred[ done | fail | progress ] for // forwarding actions to newDefer deferred[tuple[1]](function () { var returned; returned = fn && fn.apply(this, arguments); if (returned && $.isFunction(returned.promise)) { returned.promise() .done(newDefer.resolve) .fail(newDefer.reject) .progress(newDefer.notify); } else { newDefer[action + 'With']( this === promise ? newDefer.promise() : this, fn ? [returned] : arguments); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If dbhandle is provided, the promise aspect is added to the object promise: function (obj) { return obj != null ? $.extend(obj, promise) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods $.each(tuples, function (i, tuple) { var list = tuple[2], stateString = tuple[3]; // promise[ done | fail | progress ] = list.add promise[tuple[1]] = list.add; // Handle state if (stateString) { list.add(function () { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[i ^ 1][2].disable, tuples[2][2].lock); } // deferred[ resolve | reject | notify ] deferred[tuple[0]] = function () { deferred[tuple[0] + 'With'](this === deferred ? promise : this, arguments); return this; }; deferred[tuple[0] + 'With'] = list.fireWith; }); // Make the deferred a promise promise.promise(deferred); // Call given func if any if (func) { func.call(deferred, deferred); } // All done! return deferred; } api = { /** * 创建一个[Deferred](http://api.jquery.com/category/deferred-object/)对象。 * 详细的Deferred用法说明,请参照jQuery的API文档。 * * Deferred对象在钩子回掉函数中经常要用到,用来处理需要等待的异步操作。 * * @for Base * @method Deferred * @grammar Base.Deferred() => Deferred * @example * // 在文件开始发送前做些异步操作。 * // WebUploader会等待此异步操作完成后,开始发送文件。 * Uploader.register({ * 'before-send-file': 'doSomthingAsync' * }, { * * doSomthingAsync: function() { * var deferred = Base.Deferred(); * * // 模拟一次异步操作。 * setTimeout(deferred.resolve, 2000); * * return deferred.promise(); * } * }); */ Deferred: Deferred, /** * 判断传入的参数是否为一个promise对象。 * @method isPromise * @grammar Base.isPromise( anything ) => Boolean * @param {*} anything 检测对象。 * @return {Boolean} * @for Base * @example * console.log( Base.isPromise() ); // => false * console.log( Base.isPromise({ key: '123' }) ); // => false * console.log( Base.isPromise( Base.Deferred().promise() ) ); // => true * * // Deferred也是一个Promise * console.log( Base.isPromise( Base.Deferred() ) ); // => true */ isPromise: function (anything) { return anything && typeof anything.then === 'function'; }, /** * 返回一个promise,此promise在所有传入的promise都完成了后完成。 * 详细请查看[这里](http://api.jquery.com/jQuery.when/)。 * * @method when * @for Base * @grammar Base.when( promise1[, promise2[, promise3...]] ) => Promise */ when: function (subordinate /* , ..., subordinateN */) { var i = 0, slice = [].slice, resolveValues = slice.call(arguments), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || (subordinate && $.isFunction(subordinate.promise)) ? length : 0, // the master Deferred. If resolveValues consist of // only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : Deferred(), // Update function for both resolve and progress values updateFunc = function (i, contexts, values) { return function (value) { contexts[i] = this; values[i] = arguments.length > 1 ? slice.call(arguments) : value; if (values === progressValues) { deferred.notifyWith(contexts, values); } else if (!(--remaining)) { deferred.resolveWith(contexts, values); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if (length > 1) { progressValues = new Array(length); progressContexts = new Array(length); resolveContexts = new Array(length); for (; i < length; i++) { if (resolveValues[i] && $.isFunction(resolveValues[i].promise)) { resolveValues[i].promise() .done(updateFunc(i, resolveContexts, resolveValues)) .fail(deferred.reject) .progress(updateFunc(i, progressContexts, progressValues)); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if (!remaining) { deferred.resolveWith(resolveContexts, resolveValues); } return deferred.promise(); } }; return api; }); define('promise', [ 'promise-builtin' ], function ($) { return $; }); /** * @fileOverview 基础类方法。 */ /** * Web Uploader内部类的详细说明,以下提及的功能类,都可以在`WebUploader`这个变量中访问到。 * * As you know, Web Uploader的每个文件都是用过[AMD](https://github.com/amdjs/amdjs-api/wiki/AMD)规范中的`define`组织起来的, 每个Module都会有个module id. * 默认module id为该文件的路径,而此路径将会转化成名字空间存放在WebUploader中。如: * * * module `base`:WebUploader.Base * * module `file`: WebUploader.File * * module `lib/dnd`: WebUploader.Lib.Dnd * * module `runtime/html5/dnd`: WebUploader.Runtime.Html5.Dnd * * * 以下文档中对类的使用可能省略掉了`WebUploader`前缀。 * @module WebUploader * @title WebUploader API文档 */ define('base', [ 'dollar', 'promise' ], function ($, promise) { var noop = function () { }, call = Function.call; // http://jsperf.com/uncurrythis // 反科里化 function uncurryThis(fn) { return function () { return call.apply(fn, arguments); }; } function bindFn(fn, context) { return function () { return fn.apply(context, arguments); }; } function createObject(proto) { var f; if (Object.create) { return Object.create(proto); } else { f = function () { }; f.prototype = proto; return new f(); } } /** * 基础类,提供一些简单常用的方法。 * @class Base */ return { /** * @property {String} version 当前版本号。 */ version: '0.1.6', /** * @property {jQuery|Zepto} $ 引用依赖的jQuery或者Zepto对象。 */ $: $, Deferred: promise.Deferred, isPromise: promise.isPromise, when: promise.when, /** * @description 简单的浏览器检查结果。 * * * `webkit` webkit版本号,如果浏览器为非webkit内核,此属性为`undefined`。 * * `chrome` chrome浏览器版本号,如果浏览器为chrome,此属性为`undefined`。 * * `ie` ie浏览器版本号,如果浏览器为非ie,此属性为`undefined`。**暂不支持ie10+** * * `firefox` firefox浏览器版本号,如果浏览器为非firefox,此属性为`undefined`。 * * `safari` safari浏览器版本号,如果浏览器为非safari,此属性为`undefined`。 * * `opera` opera浏览器版本号,如果浏览器为非opera,此属性为`undefined`。 * * @property {Object} [browser] */ browser: (function (ua) { var ret = {}, webkit = ua.match(/WebKit\/([\d.]+)/), chrome = ua.match(/Chrome\/([\d.]+)/) || ua.match(/CriOS\/([\d.]+)/), ie = ua.match(/MSIE\s([\d\.]+)/) || ua.match(/(?:trident)(?:.*rv:([\w.]+))?/i), firefox = ua.match(/Firefox\/([\d.]+)/), safari = ua.match(/Safari\/([\d.]+)/), opera = ua.match(/OPR\/([\d.]+)/); webkit && (ret.webkit = parseFloat(webkit[1])); chrome && (ret.chrome = parseFloat(chrome[1])); ie && (ret.ie = parseFloat(ie[1])); firefox && (ret.firefox = parseFloat(firefox[1])); safari && (ret.safari = parseFloat(safari[1])); opera && (ret.opera = parseFloat(opera[1])); return ret; })(navigator.userAgent), /** * @description 操作系统检查结果。 * * * `android` 如果在android浏览器环境下,此值为对应的android版本号,否则为`undefined`。 * * `ios` 如果在ios浏览器环境下,此值为对应的ios版本号,否则为`undefined`。 * @property {Object} [os] */ os: (function (ua) { var ret = {}, // osx = !!ua.match( /\(Macintosh\; Intel / ), android = ua.match(/(?:Android);?[\s\/]+([\d.]+)?/), ios = ua.match(/(?:iPad|iPod|iPhone).*OS\s([\d_]+)/); // osx && (ret.osx = true); android && (ret.android = parseFloat(android[1])); ios && (ret.ios = parseFloat(ios[1].replace(/_/g, '.'))); return ret; })(navigator.userAgent), /** * 实现类与类之间的继承。 * @method inherits * @grammar Base.inherits( super ) => child * @grammar Base.inherits( super, protos ) => child * @grammar Base.inherits( super, protos, statics ) => child * @param {Class} super 父类 * @param {Object | Function} [protos] 子类或者对象。如果对象中包含constructor,子类将是用此属性值。 * @param {Function} [protos.constructor] 子类构造器,不指定的话将创建个临时的直接执行父类构造器的方法。 * @param {Object} [statics] 静态属性或方法。 * @return {Class} 返回子类。 * @example * function Person() { * console.log( 'Super' ); * } * Person.prototype.hello = function() { * console.log( 'hello' ); * }; * * var Manager = Base.inherits( Person, { * world: function() { * console.log( 'World' ); * } * }); * * // 因为没有指定构造器,父类的构造器将会执行。 * var instance = new Manager(); // => Super * * // 继承子父类的方法 * instance.hello(); // => hello * instance.world(); // => World * * // 子类的__super__属性指向父类 * console.log( Manager.__super__ === Person ); // => true */ inherits: function (Super, protos, staticProtos) { var child; if (typeof protos === 'function') { child = protos; protos = null; } else if (protos && protos.hasOwnProperty('constructor')) { child = protos.constructor; } else { child = function () { return Super.apply(this, arguments); }; } // 复制静态方法 $.extend(true, child, Super, staticProtos || {}); /* jshint camelcase: false */ // 让子类的__super__属性指向父类。 child.__super__ = Super.prototype; // 构建原型,添加原型方法或属性。 // 暂时用Object.create实现。 child.prototype = createObject(Super.prototype); protos && $.extend(true, child.prototype, protos); return child; }, /** * 一个不做任何事情的方法。可以用来赋值给默认的callback. * @method noop */ noop: noop, /** * 返回一个新的方法,此方法将已指定的`context`来执行。 * @grammar Base.bindFn( fn, context ) => Function * @method bindFn * @example * var doSomething = function() { * console.log( this.name ); * }, * dbhandle = { * name: 'Object Name' * }, * aliasFn = Base.bind( doSomething, dbhandle ); * * aliasFn(); // => Object Name * */ bindFn: bindFn, /** * 引用Console.log如果存在的话,否则引用一个[空函数noop](#WebUploader:Base.noop)。 * @grammar Base.log( args... ) => undefined * @method log */ log: (function () { if (window.console) { return bindFn(console.log, console); } return noop; })(), nextTick: (function () { return function (cb) { setTimeout(cb, 1); }; // @bug 当浏览器不在当前窗口时就停了。 // var next = window.requestAnimationFrame || // window.webkitRequestAnimationFrame || // window.mozRequestAnimationFrame || // function( cb ) { // window.setTimeout( cb, 1000 / 60 ); // }; // // fix: Uncaught TypeError: Illegal invocation // return bindFn( next, window ); })(), /** * 被[uncurrythis](http://www.2ality.com/2011/11/uncurrying-this.html)的数组slice方法。 * 将用来将非数组对象转化成数组对象。 * @grammar Base.slice( target, start[, end] ) => Array * @method slice * @example * function doSomthing() { * var args = Base.slice( arguments, 1 ); * console.log( args ); * } * * doSomthing( 'ignored', 'arg2', 'arg3' ); // => Array ["arg2", "arg3"] */ slice: uncurryThis([].slice), /** * 生成唯一的ID * @method guid * @grammar Base.guid() => String * @grammar Base.guid( prefx ) => String */ guid: (function () { var counter = 0; return function (prefix) { var guid = (+new Date()).toString(32), i = 0; for (; i < 5; i++) { guid += Math.floor(Math.random() * 65535).toString(32); } return (prefix || 'wu_') + guid + (counter++).toString(32); }; })(), /** * 格式化文件大小, 输出成带单位的字符串 * @method formatSize * @grammar Base.formatSize( size ) => String * @grammar Base.formatSize( size, pointLength ) => String * @grammar Base.formatSize( size, pointLength, units ) => String * @param {Number} size 文件大小 * @param {Number} [pointLength=2] 精确到的小数点数。 * @param {Array} [units=[ 'B', 'K', 'M', 'G', 'TB' ]] 单位数组。从字节,到千字节,一直往上指定。如果单位数组里面只指定了到了K(千字节),同时文件大小大于M, 此方法的输出将还是显示成多少K. * @example * console.log( Base.formatSize( 100 ) ); // => 100B * console.log( Base.formatSize( 1024 ) ); // => 1.00K * console.log( Base.formatSize( 1024, 0 ) ); // => 1K * console.log( Base.formatSize( 1024 * 1024 ) ); // => 1.00M * console.log( Base.formatSize( 1024 * 1024 * 1024 ) ); // => 1.00G * console.log( Base.formatSize( 1024 * 1024 * 1024, 0, ['B', 'KB', 'MB'] ) ); // => 1024MB */ formatSize: function (size, pointLength, units) { var unit; units = units || ['B', 'K', 'M', 'G', 'TB']; while ((unit = units.shift()) && size > 1024) { size = size / 1024; } return (unit === 'B' ? size : size.toFixed(pointLength || 2)) + unit; } }; }); /** * 事件处理类,可以独立使用,也可以扩展给对象使用。 * @fileOverview Mediator */ define('mediator', [ 'base' ], function (Base) { var $ = Base.$, slice = [].slice, separator = /\s+/, protos; // 根据条件过滤出事件handlers. function findHandlers(arr, name, callback, context) { return $.grep(arr, function (handler) { return handler && (!name || handler.e === name) && (!callback || handler.cb === callback || handler.cb._cb === callback) && (!context || handler.ctx === context); }); } function eachEvent(events, callback, iterator) { // 不支持对象,只支持多个event用空格隔开 $.each((events || '').split(separator), function (_, key) { iterator(key, callback); }); } function triggerHanders(events, args) { var stoped = false, i = -1, len = events.length, handler; while (++i < len) { handler = events[i]; if (handler.cb.apply(handler.ctx2, args) === false) { stoped = true; break; } } return !stoped; } protos = { /** * 绑定事件。 * * `callback`方法在执行时,arguments将会来源于trigger的时候携带的参数。如 * ```javascript * var dbhandle = {}; * * // 使得obj有事件行为 * Mediator.installTo( dbhandle ); * * dbhandle.on( 'testa', function( arg1, arg2 ) { * console.log( arg1, arg2 ); // => 'arg1', 'arg2' * }); * * dbhandle.trigger( 'testa', 'arg1', 'arg2' ); * ``` * * 如果`callback`中,某一个方法`return false`了,则后续的其他`callback`都不会被执行到。 * 切会影响到`trigger`方法的返回值,为`false`。 * * `on`还可以用来添加一个特殊事件`all`, 这样所有的事件触发都会响应到。同时此类`callback`中的arguments有一个不同处, * 就是第一个参数为`type`,记录当前是什么事件在触发。此类`callback`的优先级比脚低,会再正常`callback`执行完后触发。 * ```javascript * dbhandle.on( 'all', function( type, arg1, arg2 ) { * console.log( type, arg1, arg2 ); // => 'testa', 'arg1', 'arg2' * }); * ``` * * @method on * @grammar on( name, callback[, context] ) => self * @param {String} name 事件名,支持多个事件用空格隔开 * @param {Function} callback 事件处理器 * @param {Object} [context] 事件处理器的上下文。 * @return {self} 返回自身,方便链式 * @chainable * @class Mediator */ on: function (name, callback, context) { var me = this, set; if (!callback) { return this; } set = this._events || (this._events = []); eachEvent(name, callback, function (name, callback) { var handler = {e: name}; handler.cb = callback; handler.ctx = context; handler.ctx2 = context || me; handler.id = set.length; set.push(handler); }); return this; }, /** * 绑定事件,且当handler执行完后,自动解除绑定。 * @method once * @grammar once( name, callback[, context] ) => self * @param {String} name 事件名 * @param {Function} callback 事件处理器 * @param {Object} [context] 事件处理器的上下文。 * @return {self} 返回自身,方便链式 * @chainable */ once: function (name, callback, context) { var me = this; if (!callback) { return me; } eachEvent(name, callback, function (name, callback) { var once = function () { me.off(name, once); return callback.apply(context || me, arguments); }; once._cb = callback; me.on(name, once, context); }); return me; }, /** * 解除事件绑定 * @method off * @grammar off( [name[, callback[, context] ] ] ) => self * @param {String} [name] 事件名 * @param {Function} [callback] 事件处理器 * @param {Object} [context] 事件处理器的上下文。 * @return {self} 返回自身,方便链式 * @chainable */ off: function (name, cb, ctx) { var events = this._events; if (!events) { return this; } if (!name && !cb && !ctx) { this._events = []; return this; } eachEvent(name, cb, function (name, cb) { $.each(findHandlers(events, name, cb, ctx), function () { delete events[this.id]; }); }); return this; }, /** * 触发事件 * @method trigger * @grammar trigger( name[, args...] ) => self * @param {String} type 事件名 * @param {*} [...] 任意参数 * @return {Boolean} 如果handler中return false了,则返回false, 否则返回true */ trigger: function (type) { var args, events, allEvents; if (!this._events || !type) { return this; } args = slice.call(arguments, 1); events = findHandlers(this._events, type); allEvents = findHandlers(this._events, 'all'); return triggerHanders(events, args) && triggerHanders(allEvents, arguments); } }; /** * 中介者,它本身是个单例,但可以通过[installTo](#WebUploader:Mediator:installTo)方法,使任何对象具备事件行为。 * 主要目的是负责模块与模块之间的合作,降低耦合度。 * * @class Mediator */ return $.extend({ /** * 可以通过这个接口,使任何对象具备事件功能。 * @method installTo * @param {Object} obj 需要具备事件行为的对象。 * @return {Object} 返回obj. */ installTo: function (obj) { return $.extend(obj, protos); } }, protos); }); /** * @fileOverview Uploader上传类 */ define('uploader', [ 'base', 'mediator' ], function (Base, Mediator) { var $ = Base.$; /** * 上传入口类。 * @class Uploader * @constructor * @grammar new Uploader( opts ) => Uploader * @example * var uploader = WebUploader.Uploader({ * swf: 'path_of_swf/Uploader.swf', * * // 开起分片上传。 * chunked: true * }); */ function Uploader(opts) { this.options = $.extend(true, {}, Uploader.options, opts); this._init(this.options); } // default Options // widgets中有相应扩展 Uploader.options = {}; Mediator.installTo(Uploader.prototype); // 批量添加纯命令式方法。 $.each({ upload: 'start-upload', stop: 'stop-upload', getFile: 'get-file', getFiles: 'get-files', addFile: 'add-file', addFiles: 'add-file', sort: 'sort-files', removeFile: 'remove-file', cancelFile: 'cancel-file', skipFile: 'skip-file', retry: 'retry', isInProgress: 'is-in-progress', makeThumb: 'make-thumb', md5File: 'md5-file', getDimension: 'get-dimension', addButton: 'add-btn', predictRuntimeType: 'predict-runtime-type', refresh: 'refresh', disable: 'disable', enable: 'enable', reset: 'reset' }, function (fn, command) { Uploader.prototype[fn] = function () { return this.request(command, arguments); }; }); $.extend(Uploader.prototype, { state: 'pending', _init: function (opts) { var me = this; me.request('init', opts, function () { me.state = 'ready'; me.trigger('ready'); }); }, /** * 获取或者设置Uploader配置项。 * @method option * @grammar option( key ) => * * @grammar option( key, val ) => self * @example * * // 初始状态图片上传前不会压缩 * var uploader = new WebUploader.Uploader({ * compress: null; * }); * * // 修改后图片上传前,尝试将图片压缩到1600 * 1600 * uploader.option( 'compress', { * width: 1600, * height: 1600 * }); */ option: function (key, val) { var opts = this.options; // setter if (arguments.length > 1) { if ($.isPlainObject(val) && $.isPlainObject(opts[key])) { $.extend(opts[key], val); } else { opts[key] = val; } } else { // getter return key ? opts[key] : opts; } }, /** * 获取文件统计信息。返回一个包含一下信息的对象。 * * `successNum` 上传成功的文件数 * * `progressNum` 上传中的文件数 * * `cancelNum` 被删除的文件数 * * `invalidNum` 无效的文件数 * * `uploadFailNum` 上传失败的文件数 * * `queueNum` 还在队列中的文件数 * * `interruptNum` 被暂停的文件数 * @method getStats * @grammar getStats() => Object */ getStats: function () { // return this._mgr.getStats.apply( this._mgr, arguments ); var stats = this.request('get-stats'); return stats ? { successNum: stats.numOfSuccess, progressNum: stats.numOfProgress, // who care? // queueFailNum: 0, cancelNum: stats.numOfCancel, invalidNum: stats.numOfInvalid, uploadFailNum: stats.numOfUploadFailed, queueNum: stats.numOfQueue, interruptNum: stats.numofInterrupt } : {}; }, // 需要重写此方法来来支持opts.onEvent和instance.onEvent的处理器 trigger: function (type/*, args...*/) { var args = [].slice.call(arguments, 1), opts = this.options, name = 'on' + type.substring(0, 1).toUpperCase() + type.substring(1); if ( // 调用通过on方法注册的handler. Mediator.trigger.apply(this, arguments) === false || // 调用opts.onEvent $.isFunction(opts[name]) && opts[name].apply(this, args) === false || // 调用this.onEvent $.isFunction(this[name]) && this[name].apply(this, args) === false || // 广播所有uploader的事件。 Mediator.trigger.apply(Mediator, [this, type].concat(args)) === false) { return false; } return true; }, /** * 销毁 webuploader 实例 * @method destroy * @grammar destroy() => undefined */ destroy: function () { this.request('destroy', arguments); this.off(); }, // widgets/widget.js将补充此方法的详细文档。 request: Base.noop }); /** * 创建Uploader实例,等同于new Uploader( opts ); * @method create * @class Base * @static * @grammar Base.create( opts ) => Uploader */ Base.create = Uploader.create = function (opts) { return new Uploader(opts); }; // 暴露Uploader,可以通过它来扩展业务逻辑。 Base.Uploader = Uploader; return Uploader; }); /** * @fileOverview Runtime管理器,负责Runtime的选择, 连接 */ define('runtime/runtime', [ 'base', 'mediator' ], function (Base, Mediator) { var $ = Base.$, factories = {}, // 获取对象的第一个key getFirstKey = function (obj) { for (var key in obj) { if (obj.hasOwnProperty(key)) { return key; } } return null; }; // 接口类。 function Runtime(options) { this.options = $.extend({ container: document.body }, options); this.uid = Base.guid('rt_'); } $.extend(Runtime.prototype, { getContainer: function () { var opts = this.options, parent, container; if (this._container) { return this._container; } parent = $(opts.container || document.body); container = $(document.createElement('div')); container.attr('id', 'rt_' + this.uid); container.css({ position: 'absolute', top: '0px', left: '0px', width: '1px', height: '1px', overflow: 'hidden' }); parent.append(container); parent.addClass('webuploader-container'); this._container = container; this._parent = parent; return container; }, init: Base.noop, exec: Base.noop, destroy: function () { this._container && this._container.remove(); this._parent && this._parent.removeClass('webuploader-container'); this.off(); } }); Runtime.orders = 'html5,flash'; /** * 添加Runtime实现。 * @param {String} type 类型 * @param {Runtime} factory 具体Runtime实现。 */ Runtime.addRuntime = function (type, factory) { factories[type] = factory; }; Runtime.hasRuntime = function (type) { return !!(type ? factories[type] : getFirstKey(factories)); }; Runtime.create = function (opts, orders) { var type, runtime; orders = orders || Runtime.orders; $.each(orders.split(/\s*,\s*/g), function () { if (factories[this]) { type = this; return false; } }); type = type || getFirstKey(factories); if (!type) { throw new Error('Runtime Error'); } runtime = new factories[type](opts); return runtime; }; Mediator.installTo(Runtime.prototype); return Runtime; }); /** * @fileOverview Runtime管理器,负责Runtime的选择, 连接 */ define('runtime/client', [ 'base', 'mediator', 'runtime/runtime' ], function (Base, Mediator, Runtime) { var cache; cache = (function () { var obj = {}; return { add: function (runtime) { obj[runtime.uid] = runtime; }, get: function (ruid, standalone) { var i; if (ruid) { return obj[ruid]; } for (i in obj) { // 有些类型不能重用,比如filepicker. if (standalone && obj[i].__standalone) { continue; } return obj[i]; } return null; }, remove: function (runtime) { delete obj[runtime.uid]; } }; })(); function RuntimeClient(component, standalone) { var deferred = Base.Deferred(), runtime; this.uid = Base.guid('client_'); // 允许runtime没有初始化之前,注册一些方法在初始化后执行。 this.runtimeReady = function (cb) { return deferred.done(cb); }; this.connectRuntime = function (opts, cb) { // already connected. if (runtime) { throw new Error('already connected!'); } deferred.done(cb); if (typeof opts === 'string' && cache.get(opts)) { runtime = cache.get(opts); } // 像filePicker只能独立存在,不能公用。 runtime = runtime || cache.get(null, standalone); // 需要创建 if (!runtime) { runtime = Runtime.create(opts, opts.runtimeOrder); runtime.__promise = deferred.promise(); runtime.once('ready', deferred.resolve); runtime.init(); cache.add(runtime); runtime.__client = 1; } else { // 来自cache Base.$.extend(runtime.options, opts); runtime.__promise.then(deferred.resolve); runtime.__client++; } standalone && (runtime.__standalone = standalone); return runtime; }; this.getRuntime = function () { return runtime; }; this.disconnectRuntime = function () { if (!runtime) { return; } runtime.__client--; if (runtime.__client <= 0) { cache.remove(runtime); delete runtime.__promise; runtime.destroy(); } runtime = null; }; this.exec = function () { if (!runtime) { return; } var args = Base.slice(arguments); component && args.unshift(component); return runtime.exec.apply(this, args); }; this.getRuid = function () { return runtime && runtime.uid; }; this.destroy = (function (destroy) { return function () { destroy && destroy.apply(this, arguments); this.trigger('destroy'); this.off(); this.exec('destroy'); this.disconnectRuntime(); }; })(this.destroy); } Mediator.installTo(RuntimeClient.prototype); return RuntimeClient; }); /** * @fileOverview Blob */ define('lib/blob', [ 'base', 'runtime/client' ], function (Base, RuntimeClient) { function Blob(ruid, source) { var me = this; me.source = source; me.ruid = ruid; this.size = source.size || 0; // 如果没有指定 mimetype, 但是知道文件后缀。 if (!source.type && this.ext && ~'jpg,jpeg,png,gif,bmp'.indexOf(this.ext)) { this.type = 'image/' + (this.ext === 'jpg' ? 'jpeg' : this.ext); } else { this.type = source.type || 'application/octet-stream'; } RuntimeClient.call(me, 'Blob'); this.uid = source.uid || this.uid; if (ruid) { me.connectRuntime(ruid); } } Base.inherits(RuntimeClient, { constructor: Blob, slice: function (start, end) { return this.exec('slice', start, end); }, getSource: function () { return this.source; } }); return Blob; }); /** * 为了统一化Flash的File和HTML5的File而存在。 * 以至于要调用Flash里面的File,也可以像调用HTML5版本的File一下。 * @fileOverview File */ define('lib/file', [ 'base', 'lib/blob' ], function (Base, Blob) { var uid = 1, rExt = /\.([^.]+)$/; function File(ruid, file) { var ext; this.name = file.name || ('untitled' + uid++); ext = rExt.exec(file.name) ? RegExp.$1.toLowerCase() : ''; // todo 支持其他类型文件的转换。 // 如果有 mimetype, 但是文件名里面没有找出后缀规律 if (!ext && file.type) { ext = /\/(jpg|jpeg|png|gif|bmp)$/i.exec(file.type) ? RegExp.$1.toLowerCase() : ''; this.name += '.' + ext; } this.ext = ext; this.lastModifiedDate = file.lastModifiedDate || (new Date()).toLocaleString(); Blob.apply(this, arguments); } return Base.inherits(Blob, File); }); /** * @fileOverview 错误信息 */ define('lib/filepicker', [ 'base', 'runtime/client', 'lib/file' ], function (Base, RuntimeClient, File) { var $ = Base.$; function FilePicker(opts) { opts = this.options = $.extend({}, FilePicker.options, opts); opts.container = $(opts.id); if (!opts.container.length) { throw new Error('按钮指定错误'); } opts.innerHTML = opts.innerHTML || opts.label || opts.container.html() || ''; opts.button = $(opts.button || document.createElement('div')); opts.button.html(opts.innerHTML); opts.container.html(opts.button); RuntimeClient.call(this, 'FilePicker', true); } FilePicker.options = { button: null, container: null, label: null, innerHTML: null, multiple: true, accept: null, name: 'file', style: 'webuploader-pick' //pick element class attribute, default is "webuploader-pick" }; Base.inherits(RuntimeClient, { constructor: FilePicker, init: function () { var me = this, opts = me.options, button = opts.button, style = opts.style; if (style) button.addClass('webuploader-pick'); me.on('all', function (type) { var files; switch (type) { case 'mouseenter': if (style) button.addClass('webuploader-pick-hover'); break; case 'mouseleave': if (style) button.removeClass('webuploader-pick-hover'); break; case 'change': files = me.exec('getFiles'); me.trigger('select', $.map(files, function (file) { file = new File(me.getRuid(), file); // 记录来源。 file._refer = opts.container; return file; }), opts.container); break; } }); me.connectRuntime(opts, function () { me.refresh(); me.exec('init', opts); me.trigger('ready'); }); this._resizeHandler = Base.bindFn(this.refresh, this); $(window).on('resize', this._resizeHandler); }, refresh: function () { var shimContainer = this.getRuntime().getContainer(), button = this.options.button, width = button.outerWidth ? button.outerWidth() : button.width(), height = button.outerHeight ? button.outerHeight() : button.height(), pos = button.offset(); width && height && shimContainer.css({ bottom: 'auto', right: 'auto', width: width + 'px', height: height + 'px' }).offset(pos); }, enable: function () { var btn = this.options.button; btn.removeClass('webuploader-pick-disable'); this.refresh(); }, disable: function () { var btn = this.options.button; this.getRuntime().getContainer().css({ top: '-99999px' }); btn.addClass('webuploader-pick-disable'); }, destroy: function () { var btn = this.options.button; $(window).off('resize', this._resizeHandler); btn.removeClass('webuploader-pick-disable webuploader-pick-hover ' + 'webuploader-pick'); } }); return FilePicker; }); /** * @fileOverview 组件基类。 */ define('widgets/widget', [ 'base', 'uploader' ], function (Base, Uploader) { var $ = Base.$, _init = Uploader.prototype._init, _destroy = Uploader.prototype.destroy, IGNORE = {}, widgetClass = []; function isArrayLike(obj) { if (!obj) { return false; } var length = obj.length, type = $.type(obj); if (obj.nodeType === 1 && length) { return true; } return type === 'array' || type !== 'function' && type !== 'string' && (length === 0 || typeof length === 'number' && length > 0 && (length - 1) in obj); } function Widget(uploader) { this.owner = uploader; this.options = uploader.options; } $.extend(Widget.prototype, { init: Base.noop, // 类Backbone的事件监听声明,监听uploader实例上的事件 // widget直接无法监听事件,事件只能通过uploader来传递 invoke: function (apiName, args) { /* { 'make-thumb': 'makeThumb' } */ var map = this.responseMap; // 如果无API响应声明则忽略 if (!map || !(apiName in map) || !(map[apiName] in this) || !$.isFunction(this[map[apiName]])) { return IGNORE; } return this[map[apiName]].apply(this, args); }, /** * 发送命令。当传入`callback`或者`handler`中返回`promise`时。返回一个当所有`handler`中的promise都完成后完成的新`promise`。 * @method request * @grammar request( command, args ) => * | Promise * @grammar request( command, args, callback ) => Promise * @for Uploader */ request: function () { return this.owner.request.apply(this.owner, arguments); } }); // 扩展Uploader. $.extend(Uploader.prototype, { /** * @property {String | Array} [disableWidgets=undefined] * @namespace options * @for Uploader * @description 默认所有 Uploader.register 了的 widget 都会被加载,如果禁用某一部分,请通过此 option 指定黑名单。 */ // 覆写_init用来初始化widgets _init: function () { var me = this, widgets = me._widgets = [], deactives = me.options.disableWidgets || ''; $.each(widgetClass, function (_, klass) { (!deactives || !~deactives.indexOf(klass._name)) && widgets.push(new klass(me)); }); return _init.apply(me, arguments); }, request: function (apiName, args, callback) { var i = 0, widgets = this._widgets, len = widgets && widgets.length, rlts = [], dfds = [], widget, rlt, promise, key; args = isArrayLike(args) ? args : [args]; for (; i < len; i++) { widget = widgets[i]; rlt = widget.invoke(apiName, args); if (rlt !== IGNORE) { // Deferred对象 if (Base.isPromise(rlt)) { dfds.push(rlt); } else { rlts.push(rlt); } } } // 如果有callback,则用异步方式。 if (callback || dfds.length) { promise = Base.when.apply(Base, dfds); key = promise.pipe ? 'pipe' : 'then'; // 很重要不能删除。删除了会死循环。 // 保证执行顺序。让callback总是在下一个 tick 中执行。 return promise[key](function () { var deferred = Base.Deferred(), args = arguments; if (args.length === 1) { args = args[0]; } setTimeout(function () { deferred.resolve(args); }, 1); return deferred.promise(); })[callback ? key : 'done'](callback || Base.noop); } else { return rlts[0]; } }, destroy: function () { _destroy.apply(this, arguments); this._widgets = null; } }); /** * 添加组件 * @grammar Uploader.register(proto); * @grammar Uploader.register(map, proto); * @param {object} responseMap API 名称与函数实现的映射 * @param {object} proto 组件原型,构造函数通过 constructor 属性定义 * @method Uploader.register * @for Uploader * @example * Uploader.register({ * 'make-thumb': 'makeThumb' * }, { * init: function( options ) {}, * makeThumb: function() {} * }); * * Uploader.register({ * 'make-thumb': function() { * * } * }); */ Uploader.register = Widget.register = function (responseMap, widgetProto) { var map = {init: 'init', destroy: 'destroy', name: 'anonymous'}, klass; if (arguments.length === 1) { widgetProto = responseMap; // 自动生成 map 表。 $.each(widgetProto, function (key) { if (key[0] === '_' || key === 'name') { key === 'name' && (map.name = widgetProto.name); return; } map[key.replace(/[A-Z]/g, '-$&').toLowerCase()] = key; }); } else { map = $.extend(map, responseMap); } widgetProto.responseMap = map; klass = Base.inherits(Widget, widgetProto); klass._name = map.name; widgetClass.push(klass); return klass; }; /** * 删除插件,只有在注册时指定了名字的才能被删除。 * @grammar Uploader.unRegister(name); * @param {string} name 组件名字 * @method Uploader.unRegister * @for Uploader * @example * * Uploader.register({ * name: 'custom', * * 'make-thumb': function() { * * } * }); * * Uploader.unRegister('custom'); */ Uploader.unRegister = Widget.unRegister = function (name) { if (!name || name === 'anonymous') { return; } // 删除指定的插件。 for (var i = widgetClass.length; i--;) { if (widgetClass[i]._name === name) { widgetClass.splice(i, 1) } } }; return Widget; }); /** * @fileOverview 文件选择相关 */ define('widgets/filepicker', [ 'base', 'uploader', 'lib/filepicker', 'widgets/widget' ], function (Base, Uploader, FilePicker) { var $ = Base.$; $.extend(Uploader.options, { /** * @property {Selector | Object} [pick=undefined] * @namespace options * @for Uploader * @description 指定选择文件的按钮容器,不指定则不创建按钮。 * * * `id` {Seletor|dom} 指定选择文件的按钮容器,不指定则不创建按钮。**注意** 这里虽然写的是 id, 但是不是只支持 id, 还支持 class, 或者 dom 节点。 * * `label` {String} 请采用 `innerHTML` 代替 * * `innerHTML` {String} 指定按钮文字。不指定时优先从指定的容器中看是否自带文字。 * * `multiple` {Boolean} 是否开起同时选择多个文件能力。 */ pick: null, /** * @property {Arroy} [accept=null] * @namespace options * @for Uploader * @description 指定接受哪些类型的文件。 由于目前还有ext转mimeType表,所以这里需要分开指定。 * * * `title` {String} 文字描述 * * `extensions` {String} 允许的文件后缀,不带点,多个用逗号分割。 * * `mimeTypes` {String} 多个用逗号分割。 * * 如: * * ``` * { * title: 'Images', * extensions: 'gif,jpg,jpeg,bmp,png', * mimeTypes: 'image/*' * } * ``` */ accept: null/*{ title: 'Images', extensions: 'gif,jpg,jpeg,bmp,png', mimeTypes: 'image/*' }*/ }); return Uploader.register({ name: 'picker', init: function (opts) { this.pickers = []; return opts.pick && this.addBtn(opts.pick); }, refresh: function () { $.each(this.pickers, function () { this.refresh(); }); }, /** * @method addBtn * @for Uploader * @grammar addBtn( pick ) => Promise * @description * 添加文件选择按钮,如果一个按钮不够,需要调用此方法来添加。参数跟[options.pick](#WebUploader:Uploader:options)一致。 * @example * uploader.addBtn({ * id: '#btnContainer', * innerHTML: '选择文件' * }); */ addBtn: function (pick) { var me = this, opts = me.options, accept = opts.accept, promises = []; if (!pick) { return; } $.isPlainObject(pick) || (pick = { id: pick }); $(pick.id).each(function () { var options, picker, deferred; deferred = Base.Deferred(); options = $.extend({}, pick, { accept: $.isPlainObject(accept) ? [accept] : accept, swf: opts.swf, runtimeOrder: opts.runtimeOrder, id: this }); picker = new FilePicker(options); picker.once('ready', deferred.resolve); picker.on('select', function (files) { me.owner.request('add-file', [files]); }); picker.on('dialogopen', function () { me.owner.trigger('dialogOpen', picker.button); }); picker.init(); me.pickers.push(picker); promises.push(deferred.promise()); }); return Base.when.apply(Base, promises); }, disable: function () { $.each(this.pickers, function () { this.disable(); }); }, enable: function () { $.each(this.pickers, function () { this.enable(); }); }, destroy: function () { $.each(this.pickers, function () { this.destroy(); }); this.pickers = null; } }); }); /** * @fileOverview Image */ define('lib/image', [ 'base', 'runtime/client', 'lib/blob' ], function (Base, RuntimeClient, Blob) { var $ = Base.$; // 构造器。 function Image(opts) { this.options = $.extend({}, Image.options, opts); RuntimeClient.call(this, 'Image'); this.on('load', function () { this._info = this.exec('info'); this._meta = this.exec('meta'); }); } // 默认选项。 Image.options = { // 默认的图片处理质量 quality: 90, // 是否裁剪 crop: false, // 是否保留头部信息 preserveHeaders: false, // 是否允许放大。 allowMagnify: false }; // 继承RuntimeClient. Base.inherits(RuntimeClient, { constructor: Image, info: function (val) { // setter if (val) { this._info = val; return this; } // getter return this._info; }, meta: function (val) { // setter if (val) { this._meta = val; return this; } // getter return this._meta; }, loadFromBlob: function (blob) { var me = this, ruid = blob.getRuid(); this.connectRuntime(ruid, function () { me.exec('init', me.options); me.exec('loadFromBlob', blob); }); }, resize: function () { var args = Base.slice(arguments); return this.exec.apply(this, ['resize'].concat(args)); }, crop: function () { var args = Base.slice(arguments); return this.exec.apply(this, ['crop'].concat(args)); }, getAsDataUrl: function (type) { return this.exec('getAsDataUrl', type); }, getAsBlob: function (type) { var blob = this.exec('getAsBlob', type); return new Blob(this.getRuid(), blob); } }); return Image; }); /** * @fileOverview 图片操作, 负责预览图片和上传前压缩图片 */ define('widgets/image', [ 'base', 'uploader', 'lib/image', 'widgets/widget' ], function (Base, Uploader, Image) { var $ = Base.$, throttle; // 根据要处理的文件大小来节流,一次不能处理太多,会卡。 throttle = (function (max) { var occupied = 0, waiting = [], tick = function () { var item; while (waiting.length && occupied < max) { item = waiting.shift(); occupied += item[0]; item[1](); } }; return function (emiter, size, cb) { waiting.push([size, cb]); emiter.once('destroy', function () { occupied -= size; setTimeout(tick, 1); }); setTimeout(tick, 1); }; })(5 * 1024 * 1024); $.extend(Uploader.options, { /** * @property {Object} [thumb] * @namespace options * @for Uploader * @description 配置生成缩略图的选项。 * * 默认为: * * ```javascript * { * width: 110, * height: 110, * * // 图片质量,只有type为`image/jpeg`的时候才有效。 * quality: 70, * * // 是否允许放大,如果想要生成小图的时候不失真,此选项应该设置为false. * allowMagnify: true, * * // 是否允许裁剪。 * crop: true, * * // 为空的话则保留原有图片格式。 * // 否则强制转换成指定的类型。 * type: 'image/jpeg' * } * ``` */ thumb: { width: 110, height: 110, quality: 70, allowMagnify: true, crop: true, preserveHeaders: false, // 为空的话则保留原有图片格式。 // 否则强制转换成指定的类型。 // IE 8下面 base64 大小不能超过 32K 否则预览失败,而非 jpeg 编码的图片很可 // 能会超过 32k, 所以这里设置成预览的时候都是 image/jpeg type: 'image/jpeg' }, /** * @property {Object} [compress] * @namespace options * @for Uploader * @description 配置压缩的图片的选项。如果此选项为`false`, 则图片在上传前不进行压缩。 * * 默认为: * * ```javascript * { * width: 1600, * height: 1600, * * // 图片质量,只有type为`image/jpeg`的时候才有效。 * quality: 90, * * // 是否允许放大,如果想要生成小图的时候不失真,此选项应该设置为false. * allowMagnify: false, * * // 是否允许裁剪。 * crop: false, * * // 是否保留头部meta信息。 * preserveHeaders: true, * * // 如果发现压缩后文件大小比原来还大,则使用原来图片 * // 此属性可能会影响图片自动纠正功能 * noCompressIfLarger: false, * * // 单位字节,如果图片大小小于此值,不会采用压缩。 * compressSize: 0 * } * ``` */ compress: { width: 1600, height: 1600, quality: 90, allowMagnify: false, crop: false, preserveHeaders: true } }); return Uploader.register({ name: 'image', /** * 生成缩略图,此过程为异步,所以需要传入`callback`。 * 通常情况在图片加入队里后调用此方法来生成预览图以增强交互效果。 * * 当 width 或者 height 的值介于 0 - 1 时,被当成百分比使用。 * * `callback`中可以接收到两个参数。 * * 第一个为error,如果生成缩略图有错误,此error将为真。 * * 第二个为ret, 缩略图的Data URL值。 * * **注意** * Date URL在IE6/7中不支持,所以不用调用此方法了,直接显示一张暂不支持预览图片好了。 * 也可以借助服务端,将 base64 数据传给服务端,生成一个临时文件供预览。 * * @method makeThumb * @grammar makeThumb( file, callback ) => undefined * @grammar makeThumb( file, callback, width, height ) => undefined * @for Uploader * @example * * uploader.on( 'fileQueued', function( file ) { * var $li = ...; * * uploader.makeThumb( file, function( error, ret ) { * if ( error ) { * $li.text('预览错误'); * } else { * $li.append('<img alt="" src="' + ret + '" />'); * } * }); * * }); */ makeThumb: function (file, cb, width, height) { var opts, image; file = this.request('get-file', file); // 只预览图片格式。 if (!file.type.match(/^image/)) { cb(true); return; } opts = $.extend({}, this.options.thumb); // 如果传入的是object. if ($.isPlainObject(width)) { opts = $.extend(opts, width); width = null; } width = width || opts.width; height = height || opts.height; image = new Image(opts); image.once('load', function () { file._info = file._info || image.info(); file._meta = file._meta || image.meta(); // 如果 width 的值介于 0 - 1 // 说明设置的是百分比。 if (width <= 1 && width > 0) { width = file._info.width * width; } // 同样的规则应用于 height if (height <= 1 && height > 0) { height = file._info.height * height; } image.resize(width, height); }); // 当 resize 完后 image.once('complete', function () { cb(false, image.getAsDataUrl(opts.type)); image.destroy(); }); image.once('error', function (reason) { cb(reason || true); image.destroy(); }); throttle(image, file.source.size, function () { file._info && image.info(file._info); file._meta && image.meta(file._meta); image.loadFromBlob(file.source); }); }, beforeSendFile: function (file) { var opts = this.options.compress || this.options.resize, compressSize = opts && opts.compressSize || 0, noCompressIfLarger = opts && opts.noCompressIfLarger || false, image, deferred; file = this.request('get-file', file); // 只压缩 jpeg 图片格式。 // gif 可能会丢失针 // bmp png 基本上尺寸都不大,且压缩比比较小。 if (!opts || !~'image/jpeg,image/jpg'.indexOf(file.type) || file.size < compressSize || file._compressed) { return; } opts = $.extend({}, opts); deferred = Base.Deferred(); image = new Image(opts); deferred.always(function () { image.destroy(); image = null; }); image.once('error', deferred.reject); image.once('load', function () { var width = opts.width, height = opts.height; file._info = file._info || image.info(); file._meta = file._meta || image.meta(); // 如果 width 的值介于 0 - 1 // 说明设置的是百分比。 if (width <= 1 && width > 0) { width = file._info.width * width; } // 同样的规则应用于 height if (height <= 1 && height > 0) { height = file._info.height * height; } image.resize(width, height); }); image.once('complete', function () { var blob, size; // 移动端 UC / qq 浏览器的无图模式下 // ctx.getImageData 处理大图的时候会报 Exception // INDEX_SIZE_ERR: DOM Exception 1 try { blob = image.getAsBlob(opts.type); size = file.size; // 如果压缩后,比原来还大则不用压缩后的。 if (!noCompressIfLarger || blob.size < size) { // file.source.destroy && file.source.destroy(); file.source = blob; file.size = blob.size; file.trigger('resize', blob.size, size); } // 标记,避免重复压缩。 file._compressed = true; deferred.resolve(); } catch (e) { // 出错了直接继续,让其上传原始图片 deferred.resolve(); } }); file._info && image.info(file._info); file._meta && image.meta(file._meta); image.loadFromBlob(file.source); return deferred.promise(); } }); }); /** * @fileOverview 文件属性封装 */ define('file', [ 'base', 'mediator' ], function (Base, Mediator) { var $ = Base.$, idPrefix = 'WU_FILE_', idSuffix = 0, rExt = /\.([^.]+)$/, statusMap = {}; function gid() { return idPrefix + idSuffix++; } /** * 文件类 * @class File * @constructor 构造函数 * @grammar new File( source ) => File * @param {Lib.File} source [lib.File](#Lib.File)实例, 此source对象是带有Runtime信息的。 */ function WUFile(source) { /** * 文件名,包括扩展名(后缀) * @property name * @type {string} */ this.name = source.name || 'Untitled'; /** * 文件体积(字节) * @property size * @type {uint} * @default 0 */ this.size = source.size || 0; /** * 文件MIMETYPE类型,与文件类型的对应关系请参考[http://t.cn/z8ZnFny](http://t.cn/z8ZnFny) * @property type * @type {string} * @default 'application/octet-stream' */ this.type = source.type || 'application/octet-stream'; /** * 文件最后修改日期 * @property lastModifiedDate * @type {int} * @default 当前时间戳 */ this.lastModifiedDate = source.lastModifiedDate || (new Date() * 1); /** * 文件ID,每个对象具有唯一ID,与文件名无关 * @property id * @type {string} */ this.id = gid(); /** * 文件扩展名,通过文件名获取,例如test.png的扩展名为png * @property ext * @type {string} */ this.ext = rExt.exec(this.name) ? RegExp.$1 : ''; /** * 状态文字说明。在不同的status语境下有不同的用途。 * @property statusText * @type {string} */ this.statusText = ''; // 存储文件状态,防止通过属性直接修改 statusMap[this.id] = WUFile.Status.INITED; this.source = source; this.loaded = 0; this.on('error', function (msg) { this.setStatus(WUFile.Status.ERROR, msg); }); } $.extend(WUFile.prototype, { /** * 设置状态,状态变化时会触发`change`事件。 * @method setStatus * @grammar setStatus( status[, statusText] ); * @param {File.Status|String} status [文件状态值](#WebUploader:File:File.Status) * @param {String} [statusText=''] 状态说明,常在error时使用,用http, abort,server等来标记是由于什么原因导致文件错误。 */ setStatus: function (status, text) { var prevStatus = statusMap[this.id]; typeof text !== 'undefined' && (this.statusText = text); if (status !== prevStatus) { statusMap[this.id] = status; /** * 文件状态变化 * @event statuschange */ this.trigger('statuschange', status, prevStatus); } }, /** * 获取文件状态 * @return {File.Status} * @example 文件状态具体包括以下几种类型: { // 初始化 INITED: 0, // 已入队列 QUEUED: 1, // 正在上传 PROGRESS: 2, // 上传出错 ERROR: 3, // 上传成功 COMPLETE: 4, // 上传取消 CANCELLED: 5 } */ getStatus: function () { return statusMap[this.id]; }, /** * 获取文件原始信息。 * @return {*} */ getSource: function () { return this.source; }, destroy: function () { this.off(); delete statusMap[this.id]; } }); Mediator.installTo(WUFile.prototype); /** * 文件状态值,具体包括以下几种类型: * * `inited` 初始状态 * * `queued` 已经进入队列, 等待上传 * * `progress` 上传中 * * `complete` 上传完成。 * * `error` 上传出错,可重试 * * `interrupt` 上传中断,可续传。 * * `invalid` 文件不合格,不能重试上传。会自动从队列中移除。 * * `cancelled` 文件被移除。 * @property {Object} Status * @namespace File * @class File * @static */ WUFile.Status = { INITED: 'inited', // 初始状态 QUEUED: 'queued', // 已经进入队列, 等待上传 PROGRESS: 'progress', // 上传中 ERROR: 'error', // 上传出错,可重试 COMPLETE: 'complete', // 上传完成。 CANCELLED: 'cancelled', // 上传取消。 INTERRUPT: 'interrupt', // 上传中断,可续传。 INVALID: 'invalid' // 文件不合格,不能重试上传。 }; return WUFile; }); /** * @fileOverview 文件队列 */ define('queue', [ 'base', 'mediator', 'file' ], function (Base, Mediator, WUFile) { var $ = Base.$, STATUS = WUFile.Status; /** * 文件队列, 用来存储各个状态中的文件。 * @class Queue * @extends Mediator */ function Queue() { /** * 统计文件数。 * * `numOfQueue` 队列中的文件数。 * * `numOfSuccess` 上传成功的文件数 * * `numOfCancel` 被取消的文件数 * * `numOfProgress` 正在上传中的文件数 * * `numOfUploadFailed` 上传错误的文件数。 * * `numOfInvalid` 无效的文件数。 * * `numofDeleted` 被移除的文件数。 * @property {Object} stats */ this.stats = { numOfQueue: 0, numOfSuccess: 0, numOfCancel: 0, numOfProgress: 0, numOfUploadFailed: 0, numOfInvalid: 0, numofDeleted: 0, numofInterrupt: 0 }; // 上传队列,仅包括等待上传的文件 this._queue = []; // 存储所有文件 this._map = {}; } $.extend(Queue.prototype, { /** * 将新文件加入对队列尾部 * * @method append * @param {File} file 文件对象 */ append: function (file) { this._queue.push(file); this._fileAdded(file); return this; }, /** * 将新文件加入对队列头部 * * @method prepend * @param {File} file 文件对象 */ prepend: function (file) { this._queue.unshift(file); this._fileAdded(file); return this; }, /** * 获取文件对象 * * @method getFile * @param {String} fileId 文件ID * @return {File} */ getFile: function (fileId) { if (typeof fileId !== 'string') { return fileId; } return this._map[fileId]; }, /** * 从队列中取出一个指定状态的文件。 * @grammar fetch( status ) => File * @method fetch * @param {String} status [文件状态值](#WebUploader:File:File.Status) * @return {File} [File](#WebUploader:File) */ fetch: function (status) { var len = this._queue.length, i, file; status = status || STATUS.QUEUED; for (i = 0; i < len; i++) { file = this._queue[i]; if (status === file.getStatus()) { return file; } } return null; }, /** * 对队列进行排序,能够控制文件上传顺序。 * @grammar sort( fn ) => undefined * @method sort * @param {Function} fn 排序方法 */ sort: function (fn) { if (typeof fn === 'function') { this._queue.sort(fn); } }, /** * 获取指定类型的文件列表, 列表中每一个成员为[File](#WebUploader:File)对象。 * @grammar getFiles( [status1[, status2 ...]] ) => Array * @method getFiles * @param {String} [status] [文件状态值](#WebUploader:File:File.Status) */ getFiles: function () { var sts = [].slice.call(arguments, 0), ret = [], i = 0, len = this._queue.length, file; for (; i < len; i++) { file = this._queue[i]; if (sts.length && !~$.inArray(file.getStatus(), sts)) { continue; } ret.push(file); } return ret; }, /** * 在队列中删除文件。 * @grammar removeFile( file ) => Array * @method removeFile * @param {File} 文件对象。 */ removeFile: function (file) { var me = this, existing = this._map[file.id]; if (existing) { delete this._map[file.id]; file.destroy(); this.stats.numofDeleted++; } }, _fileAdded: function (file) { var me = this, existing = this._map[file.id]; if (!existing) { this._map[file.id] = file; file.on('statuschange', function (cur, pre) { me._onFileStatusChange(cur, pre); }); } }, _onFileStatusChange: function (curStatus, preStatus) { var stats = this.stats; switch (preStatus) { case STATUS.PROGRESS: stats.numOfProgress--; break; case STATUS.QUEUED: stats.numOfQueue--; break; case STATUS.ERROR: stats.numOfUploadFailed--; break; case STATUS.INVALID: stats.numOfInvalid--; break; case STATUS.INTERRUPT: stats.numofInterrupt--; break; } switch (curStatus) { case STATUS.QUEUED: stats.numOfQueue++; break; case STATUS.PROGRESS: stats.numOfProgress++; break; case STATUS.ERROR: stats.numOfUploadFailed++; break; case STATUS.COMPLETE: stats.numOfSuccess++; break; case STATUS.CANCELLED: stats.numOfCancel++; break; case STATUS.INVALID: stats.numOfInvalid++; break; case STATUS.INTERRUPT: stats.numofInterrupt++; break; } } }); Mediator.installTo(Queue.prototype); return Queue; }); /** * @fileOverview 队列 */ define('widgets/queue', [ 'base', 'uploader', 'queue', 'file', 'lib/file', 'runtime/client', 'widgets/widget' ], function (Base, Uploader, Queue, WUFile, File, RuntimeClient) { var $ = Base.$, rExt = /\.\w+$/, Status = WUFile.Status; return Uploader.register({ name: 'queue', init: function (opts) { var me = this, deferred, len, i, item, arr, accept, runtime; if ($.isPlainObject(opts.accept)) { opts.accept = [opts.accept]; } // accept中的中生成匹配正则。 if (opts.accept) { arr = []; for (i = 0, len = opts.accept.length; i < len; i++) { item = opts.accept[i].extensions; item && arr.push(item); } if (arr.length) { accept = '\\.' + arr.join(',') .replace(/,/g, '$|\\.') .replace(/\*/g, '.*') + '$'; } me.accept = new RegExp(accept, 'i'); } me.queue = new Queue(); me.stats = me.queue.stats; // 如果当前不是html5运行时,那就算了。 // 不执行后续操作 if (this.request('predict-runtime-type') !== 'html5') { return; } // 创建一个 html5 运行时的 placeholder // 以至于外部添加原生 File 对象的时候能正确包裹一下供 webuploader 使用。 deferred = Base.Deferred(); this.placeholder = runtime = new RuntimeClient('Placeholder'); runtime.connectRuntime({ runtimeOrder: 'html5' }, function () { me._ruid = runtime.getRuid(); deferred.resolve(); }); return deferred.promise(); }, // 为了支持外部直接添加一个原生File对象。 _wrapFile: function (file) { if (!(file instanceof WUFile)) { if (!(file instanceof File)) { if (!this._ruid) { throw new Error('Can\'t add external files.'); } file = new File(this._ruid, file); } file = new WUFile(file); } return file; }, // 判断文件是否可以被加入队列 acceptFile: function (file) { var invalid = !file || !file.size || this.accept && // 如果名字中有后缀,才做后缀白名单处理。 rExt.exec(file.name) && !this.accept.test(file.name); return !invalid; }, /** * @event beforeFileQueued * @param {File} file File对象 * @description 当文件被加入队列之前触发,此事件的handler返回值为`false`,则此文件不会被添加进入队列。 * @for Uploader */ /** * @event fileQueued * @param {File} file File对象 * @description 当文件被加入队列以后触发。 * @for Uploader */ _addFile: function (file) { var me = this; file = me._wrapFile(file); // 不过类型判断允许不允许,先派送 `beforeFileQueued` if (!me.owner.trigger('beforeFileQueued', file)) { return; } // 类型不匹配,则派送错误事件,并返回。 if (!me.acceptFile(file)) { me.owner.trigger('error', 'Q_TYPE_DENIED', file); return; } me.queue.append(file); me.owner.trigger('fileQueued', file); return file; }, getFile: function (fileId) { return this.queue.getFile(fileId); }, /** * @event filesQueued * @param {File} files 数组,内容为原始File(lib/File)对象。 * @description 当一批文件添加进队列以后触发。 * @for Uploader */ /** * @property {Boolean} [auto=false] * @namespace options * @for Uploader * @description 设置为 true 后,不需要手动调用上传,有文件选择即开始上传。 * */ /** * @method addFiles * @grammar addFiles( file ) => undefined * @grammar addFiles( [file1, file2 ...] ) => undefined * @param {Array of File or File} [files] Files 对象 数组 * @description 添加文件到队列 * @for Uploader */ addFile: function (files) { var me = this; if (!files.length) { files = [files]; } files = $.map(files, function (file) { return me._addFile(file); }); if (files.length) { me.owner.trigger('filesQueued', files); if (me.options.auto) { setTimeout(function () { me.request('start-upload'); }, 20); } } }, getStats: function () { return this.stats; }, /** * @event fileDequeued * @param {File} file File对象 * @description 当文件被移除队列后触发。 * @for Uploader */ /** * @method removeFile * @grammar removeFile( file ) => undefined * @grammar removeFile( id ) => undefined * @grammar removeFile( file, true ) => undefined * @grammar removeFile( id, true ) => undefined * @param {File|id} file File对象或这File对象的id * @description 移除某一文件, 默认只会标记文件状态为已取消,如果第二个参数为 `true` 则会从 queue 中移除。 * @for Uploader * @example * * $li.on('click', '.remove-this', function() { * uploader.removeFile( file ); * }) */ removeFile: function (file, remove) { var me = this; file = file.id ? file : me.queue.getFile(file); this.request('cancel-file', file); if (remove) { this.queue.removeFile(file); } }, /** * @method getFiles * @grammar getFiles() => Array * @grammar getFiles( status1, status2, status... ) => Array * @description 返回指定状态的文件集合,不传参数将返回所有状态的文件。 * @for Uploader * @example * console.log( uploader.getFiles() ); // => all files * console.log( uploader.getFiles('error') ) // => all error files. */ getFiles: function () { return this.queue.getFiles.apply(this.queue, arguments); }, fetchFile: function () { return this.queue.fetch.apply(this.queue, arguments); }, /** * @method retry * @grammar retry() => undefined * @grammar retry( file ) => undefined * @description 重试上传,重试指定文件,或者从出错的文件开始重新上传。 * @for Uploader * @example * function retry() { * uploader.retry(); * } */ retry: function (file, noForceStart) { var me = this, files, i, len; if (file) { file = file.id ? file : me.queue.getFile(file); file.setStatus(Status.QUEUED); noForceStart || me.request('start-upload'); return; } files = me.queue.getFiles(Status.ERROR); i = 0; len = files.length; for (; i < len; i++) { file = files[i]; file.setStatus(Status.QUEUED); } me.request('start-upload'); }, /** * @method sort * @grammar sort( fn ) => undefined * @description 排序队列中的文件,在上传之前调整可以控制上传顺序。 * @for Uploader */ sortFiles: function () { return this.queue.sort.apply(this.queue, arguments); }, /** * @event reset * @description 当 uploader 被重置的时候触发。 * @for Uploader */ /** * @method reset * @grammar reset() => undefined * @description 重置uploader。目前只重置了队列。 * @for Uploader * @example * uploader.reset(); */ reset: function () { this.owner.trigger('reset'); this.queue = new Queue(); this.stats = this.queue.stats; }, destroy: function () { this.reset(); this.placeholder && this.placeholder.destroy(); } }); }); /** * @fileOverview 添加获取Runtime相关信息的方法。 */ define('widgets/runtime', [ 'uploader', 'runtime/runtime', 'widgets/widget' ], function (Uploader, Runtime) { Uploader.support = function () { return Runtime.hasRuntime.apply(Runtime, arguments); }; /** * @property {Object} [runtimeOrder=html5,flash] * @namespace options * @for Uploader * @description 指定运行时启动顺序。默认会想尝试 html5 是否支持,如果支持则使用 html5, 否则则使用 flash. * * 可以将此值设置成 `flash`,来强制使用 flash 运行时。 */ return Uploader.register({ name: 'runtime', init: function () { if (!this.predictRuntimeType()) { throw Error('Runtime Error'); } }, /** * 预测Uploader将采用哪个`Runtime` * @grammar predictRuntimeType() => String * @method predictRuntimeType * @for Uploader */ predictRuntimeType: function () { var orders = this.options.runtimeOrder || Runtime.orders, type = this.type, i, len; if (!type) { orders = orders.split(/\s*,\s*/g); for (i = 0, len = orders.length; i < len; i++) { if (Runtime.hasRuntime(orders[i])) { this.type = type = orders[i]; break; } } } return type; } }); }); /** * @fileOverview Transport */ define('lib/transport', [ 'base', 'runtime/client', 'mediator' ], function (Base, RuntimeClient, Mediator) { var $ = Base.$; function Transport(opts) { var me = this; opts = me.options = $.extend(true, {}, Transport.options, opts || {}); RuntimeClient.call(this, 'Transport'); this._blob = null; this._formData = opts.formData || {}; this._headers = opts.headers || {}; this.on('progress', this._timeout); this.on('load error', function () { me.trigger('progress', 1); clearTimeout(me._timer); }); } Transport.options = { server: '', method: 'POST', // 跨域时,是否允许携带cookie, 只有html5 runtime才有效 withCredentials: false, fileVal: 'file', timeout: 2 * 60 * 1000, // 2分钟 formData: {}, headers: {}, sendAsBinary: false }; $.extend(Transport.prototype, { // 添加Blob, 只能添加一次,最后一次有效。 appendBlob: function (key, blob, filename) { var me = this, opts = me.options; if (me.getRuid()) { me.disconnectRuntime(); } // 连接到blob归属的同一个runtime. me.connectRuntime(blob.ruid, function () { me.exec('init'); }); me._blob = blob; opts.fileVal = key || opts.fileVal; opts.filename = filename || opts.filename; }, // 添加其他字段 append: function (key, value) { if (typeof key === 'object') { $.extend(this._formData, key); } else { this._formData[key] = value; } }, setRequestHeader: function (key, value) { if (typeof key === 'object') { $.extend(this._headers, key); } else { this._headers[key] = value; } }, send: function (method) { this.exec('send', method); this._timeout(); }, abort: function () { clearTimeout(this._timer); return this.exec('abort'); }, destroy: function () { this.trigger('destroy'); this.off(); this.exec('destroy'); this.disconnectRuntime(); }, getResponse: function () { return this.exec('getResponse'); }, getResponseAsJson: function () { return this.exec('getResponseAsJson'); }, getStatus: function () { return this.exec('getStatus'); }, _timeout: function () { var me = this, duration = me.options.timeout; if (!duration) { return; } clearTimeout(me._timer); me._timer = setTimeout(function () { me.abort(); me.trigger('error', 'timeout'); }, duration); } }); // 让Transport具备事件功能。 Mediator.installTo(Transport.prototype); return Transport; }); /** * @fileOverview 负责文件上传相关。 */ define('widgets/upload', [ 'base', 'uploader', 'file', 'lib/transport', 'widgets/widget' ], function (Base, Uploader, WUFile, Transport) { var $ = Base.$, isPromise = Base.isPromise, Status = WUFile.Status; // 添加默认配置项 $.extend(Uploader.options, { /** * @property {Boolean} [prepareNextFile=false] * @namespace options * @for Uploader * @description 是否允许在文件传输时提前把下一个文件准备好。 * 对于一个文件的准备工作比较耗时,比如图片压缩,md5序列化。 * 如果能提前在当前文件传输期处理,可以节省总体耗时。 */ prepareNextFile: false, /** * @property {Boolean} [chunked=false] * @namespace options * @for Uploader * @description 是否要分片处理大文件上传。 */ chunked: false, /** * @property {Boolean} [chunkSize=5242880] * @namespace options * @for Uploader * @description 如果要分片,分多大一片? 默认大小为5M. */ chunkSize: 5 * 1024 * 1024, /** * @property {Boolean} [chunkRetry=2] * @namespace options * @for Uploader * @description 如果某个分片由于网络问题出错,允许自动重传多少次? */ chunkRetry: 2, /** * @property {Boolean} [threads=3] * @namespace options * @for Uploader * @description 上传并发数。允许同时最大上传进程数。 */ threads: 3, /** * @property {Object} [formData={}] * @namespace options * @for Uploader * @description 文件上传请求的参数表,每次发送都会发送此对象中的参数。 */ formData: {} /** * @property {Object} [fileVal='file'] * @namespace options * @for Uploader * @description 设置文件上传域的name。 */ /** * @property {Object} [sendAsBinary=false] * @namespace options * @for Uploader * @description 是否已二进制的流的方式发送文件,这样整个上传内容`php://input`都为文件内容, * 其他参数在$_GET数组中。 */ }); // 负责将文件切片。 function CuteFile(file, chunkSize) { var pending = [], blob = file.source, total = blob.size, chunks = chunkSize ? Math.ceil(total / chunkSize) : 1, start = 0, index = 0, len, api; api = { file: file, has: function () { return !!pending.length; }, shift: function () { return pending.shift(); }, unshift: function (block) { pending.unshift(block); } }; while (index < chunks) { len = Math.min(chunkSize, total - start); pending.push({ file: file, start: start, end: chunkSize ? (start + len) : total, total: total, chunks: chunks, chunk: index++, cuted: api }); start += len; } file.blocks = pending.concat(); file.remaning = pending.length; return api; } Uploader.register({ name: 'upload', init: function () { var owner = this.owner, me = this; this.runing = false; this.progress = false; owner .on('startUpload', function () { me.progress = true; }) .on('uploadFinished', function () { me.progress = false; }); // 记录当前正在传的数据,跟threads相关 this.pool = []; // 缓存分好片的文件。 this.stack = []; // 缓存即将上传的文件。 this.pending = []; // 跟踪还有多少分片在上传中但是没有完成上传。 this.remaning = 0; this.__tick = Base.bindFn(this._tick, this); // 销毁上传相关的属性。 owner.on('uploadComplete', function (file) { // 把其他块取消了。 file.blocks && $.each(file.blocks, function (_, v) { v.transport && (v.transport.abort(), v.transport.destroy()); delete v.transport; }); delete file.blocks; delete file.remaning; }); }, reset: function () { this.request('stop-upload', true); this.runing = false; this.pool = []; this.stack = []; this.pending = []; this.remaning = 0; this._trigged = false; this._promise = null; }, /** * @event startUpload * @description 当开始上传流程时触发。 * @for Uploader */ /** * 开始上传。此方法可以从初始状态调用开始上传流程,也可以从暂停状态调用,继续上传流程。 * * 可以指定开始某一个文件。 * @grammar upload() => undefined * @grammar upload( file | fileId) => undefined * @method upload * @for Uploader */ startUpload: function (file) { var me = this; // 移出invalid的文件 $.each(me.request('get-files', Status.INVALID), function () { me.request('remove-file', this); }); // 如果指定了开始某个文件,则只开始指定的文件。 if (file) { file = file.id ? file : me.request('get-file', file); if (file.getStatus() === Status.INTERRUPT) { file.setStatus(Status.QUEUED); $.each(me.pool, function (_, v) { // 之前暂停过。 if (v.file !== file) { return; } v.transport && v.transport.send(); file.setStatus(Status.PROGRESS); }); } else if (file.getStatus() !== Status.PROGRESS) { file.setStatus(Status.QUEUED); } } else { $.each(me.request('get-files', [Status.INITED]), function () { this.setStatus(Status.QUEUED); }); } if (me.runing) { return Base.nextTick(me.__tick); } me.runing = true; var files = []; // 如果有暂停的,则续传 file || $.each(me.pool, function (_, v) { var file = v.file; if (file.getStatus() === Status.INTERRUPT) { me._trigged = false; files.push(file); v.transport && v.transport.send(); } }); $.each(files, function () { this.setStatus(Status.PROGRESS); }); file || $.each(me.request('get-files', Status.INTERRUPT), function () { this.setStatus(Status.PROGRESS); }); me._trigged = false; Base.nextTick(me.__tick); me.owner.trigger('startUpload'); }, /** * @event stopUpload * @description 当开始上传流程暂停时触发。 * @for Uploader */ /** * 暂停上传。第一个参数为是否中断上传当前正在上传的文件。 * * 如果第一个参数是文件,则只暂停指定文件。 * @grammar stop() => undefined * @grammar stop( true ) => undefined * @grammar stop( file ) => undefined * @method stop * @for Uploader */ stopUpload: function (file, interrupt) { var me = this, block; if (file === true) { interrupt = file; file = null; } if (me.runing === false) { return; } // 如果只是暂停某个文件。 if (file) { file = file.id ? file : me.request('get-file', file); if (file.getStatus() !== Status.PROGRESS && file.getStatus() !== Status.QUEUED) { return; } file.setStatus(Status.INTERRUPT); $.each(me.pool, function (_, v) { // 只 abort 指定的文件。 if (v.file === file) { block = v; return false; } }); block.transport && block.transport.abort(); if (interrupt) { me._putback(block); me._popBlock(block); } return Base.nextTick(me.__tick); } me.runing = false; // 正在准备中的文件。 if (this._promise && this._promise.file) { this._promise.file.setStatus(Status.INTERRUPT); } interrupt && $.each(me.pool, function (_, v) { v.transport && v.transport.abort(); v.file.setStatus(Status.INTERRUPT); }); me.owner.trigger('stopUpload'); }, /** * @method cancelFile * @grammar cancelFile( file ) => undefined * @grammar cancelFile( id ) => undefined * @param {File|id} file File对象或这File对象的id * @description 标记文件状态为已取消, 同时将中断文件传输。 * @for Uploader * @example * * $li.on('click', '.remove-this', function() { * uploader.cancelFile( file ); * }) */ cancelFile: function (file) { file = file.id ? file : this.request('get-file', file); // 如果正在上传。 file.blocks && $.each(file.blocks, function (_, v) { var _tr = v.transport; if (_tr) { _tr.abort(); _tr.destroy(); delete v.transport; } }); file.setStatus(Status.CANCELLED); this.owner.trigger('fileDequeued', file); }, /** * 判断`Uplaode`r是否正在上传中。 * @grammar isInProgress() => Boolean * @method isInProgress * @for Uploader */ isInProgress: function () { return !!this.progress; }, _getStats: function () { return this.request('get-stats'); }, /** * 掉过一个文件上传,直接标记指定文件为已上传状态。 * @grammar skipFile( file ) => undefined * @method skipFile * @for Uploader */ skipFile: function (file, status) { file = file.id ? file : this.request('get-file', file); file.setStatus(status || Status.COMPLETE); file.skipped = true; // 如果正在上传。 file.blocks && $.each(file.blocks, function (_, v) { var _tr = v.transport; if (_tr) { _tr.abort(); _tr.destroy(); delete v.transport; } }); this.owner.trigger('uploadSkip', file); }, /** * @event uploadFinished * @description 当所有文件上传结束时触发。 * @for Uploader */ _tick: function () { var me = this, opts = me.options, fn, val; // 上一个promise还没有结束,则等待完成后再执行。 if (me._promise) { return me._promise.always(me.__tick); } // 还有位置,且还有文件要处理的话。 if (me.pool.length < opts.threads && (val = me._nextBlock())) { me._trigged = false; fn = function (val) { me._promise = null; // 有可能是reject过来的,所以要检测val的类型。 val && val.file && me._startSend(val); Base.nextTick(me.__tick); }; me._promise = isPromise(val) ? val.always(fn) : fn(val); // 没有要上传的了,且没有正在传输的了。 } else if (!me.remaning && !me._getStats().numOfQueue && !me._getStats().numofInterrupt) { me.runing = false; me._trigged || Base.nextTick(function () { me.owner.trigger('uploadFinished'); }); me._trigged = true; } }, _putback: function (block) { var idx; block.cuted.unshift(block); idx = this.stack.indexOf(block.cuted); if (!~idx) { this.stack.unshift(block.cuted); } }, _getStack: function () { var i = 0, act; while ((act = this.stack[i++])) { if (act.has() && act.file.getStatus() === Status.PROGRESS) { return act; } else if (!act.has() || act.file.getStatus() !== Status.PROGRESS && act.file.getStatus() !== Status.INTERRUPT) { // 把已经处理完了的,或者,状态为非 progress(上传中)、 // interupt(暂停中) 的移除。 this.stack.splice(--i, 1); } } return null; }, _nextBlock: function () { var me = this, opts = me.options, act, next, done, preparing; // 如果当前文件还有没有需要传输的,则直接返回剩下的。 if ((act = this._getStack())) { // 是否提前准备下一个文件 if (opts.prepareNextFile && !me.pending.length) { me._prepareNextFile(); } return act.shift(); // 否则,如果正在运行,则准备下一个文件,并等待完成后返回下个分片。 } else if (me.runing) { // 如果缓存中有,则直接在缓存中取,没有则去queue中取。 if (!me.pending.length && me._getStats().numOfQueue) { me._prepareNextFile(); } next = me.pending.shift(); done = function (file) { if (!file) { return null; } act = CuteFile(file, opts.chunked ? opts.chunkSize : 0); me.stack.push(act); return act.shift(); }; // 文件可能还在prepare中,也有可能已经完全准备好了。 if (isPromise(next)) { preparing = next.file; next = next[next.pipe ? 'pipe' : 'then'](done); next.file = preparing; return next; } return done(next); } }, /** * @event uploadStart * @param {File} file File对象 * @description 某个文件开始上传前触发,一个文件只会触发一次。 * @for Uploader */ _prepareNextFile: function () { var me = this, file = me.request('fetch-file'), pending = me.pending, promise; if (file) { promise = me.request('before-send-file', file, function () { // 有可能文件被skip掉了。文件被skip掉后,状态坑定不是Queued. if (file.getStatus() === Status.PROGRESS || file.getStatus() === Status.INTERRUPT) { return file; } return me._finishFile(file); }); me.owner.trigger('uploadStart', file); file.setStatus(Status.PROGRESS); promise.file = file; // 如果还在pending中,则替换成文件本身。 promise.done(function () { var idx = $.inArray(promise, pending); ~idx && pending.splice(idx, 1, file); }); // befeore-send-file的钩子就有错误发生。 promise.fail(function (reason) { file.setStatus(Status.ERROR, reason); me.owner.trigger('uploadError', file, reason); me.owner.trigger('uploadComplete', file); }); pending.push(promise); } }, // 让出位置了,可以让其他分片开始上传 _popBlock: function (block) { var idx = $.inArray(block, this.pool); this.pool.splice(idx, 1); block.file.remaning--; this.remaning--; }, // 开始上传,可以被掉过。如果promise被reject了,则表示跳过此分片。 _startSend: function (block) { var me = this, file = block.file, promise; // 有可能在 before-send-file 的 promise 期间改变了文件状态。 // 如:暂停,取消 // 我们不能中断 promise, 但是可以在 promise 完后,不做上传操作。 if (file.getStatus() !== Status.PROGRESS) { // 如果是中断,则还需要放回去。 if (file.getStatus() === Status.INTERRUPT) { me._putback(block); } return; } me.pool.push(block); me.remaning++; // 如果没有分片,则直接使用原始的。 // 不会丢失content-type信息。 block.blob = block.chunks === 1 ? file.source : file.source.slice(block.start, block.end); // hook, 每个分片发送之前可能要做些异步的事情。 promise = me.request('before-send', block, function () { // 有可能文件已经上传出错了,所以不需要再传输了。 if (file.getStatus() === Status.PROGRESS) { me._doSend(block); } else { me._popBlock(block); Base.nextTick(me.__tick); } }); // 如果为fail了,则跳过此分片。 promise.fail(function () { if (file.remaning === 1) { me._finishFile(file).always(function () { block.percentage = 1; me._popBlock(block); me.owner.trigger('uploadComplete', file); Base.nextTick(me.__tick); }); } else { block.percentage = 1; me.updateFileProgress(file); me._popBlock(block); Base.nextTick(me.__tick); } }); }, /** * @event uploadBeforeSend * @param {Object} object * @param {Object} data 默认的上传参数,可以扩展此对象来控制上传参数。 * @param {Object} headers 可以扩展此对象来控制上传头部。 * @description 当某个文件的分块在发送前触发,主要用来询问是否要添加附带参数,大文件在开起分片上传的前提下此事件可能会触发多次。 * @for Uploader */ /** * @event uploadAccept * @param {Object} object * @param {Object} ret 服务端的返回数据,json格式,如果服务端不是json格式,从ret._raw中取数据,自行解析。 * @description 当某个文件上传到服务端响应后,会派送此事件来询问服务端响应是否有效。如果此事件handler返回值为`false`, 则此文件将派送`server`类型的`uploadError`事件。 * @for Uploader */ /** * @event uploadProgress * @param {File} file File对象 * @param {Number} percentage 上传进度 * @description 上传过程中触发,携带上传进度。 * @for Uploader */ /** * @event uploadError * @param {File} file File对象 * @param {String} reason 出错的code * @description 当文件上传出错时触发。 * @for Uploader */ /** * @event uploadSuccess * @param {File} file File对象 * @param {Object} response 服务端返回的数据 * @description 当文件上传成功时触发。 * @for Uploader */ /** * @event uploadComplete * @param {File} [file] File对象 * @description 不管成功或者失败,文件上传完成时触发。 * @for Uploader */ // 做上传操作。 _doSend: function (block) { var me = this, owner = me.owner, opts = me.options, file = block.file, tr = new Transport(opts), data = $.extend({}, opts.formData), headers = $.extend({}, opts.headers), requestAccept, ret; block.transport = tr; tr.on('destroy', function () { delete block.transport; me._popBlock(block); Base.nextTick(me.__tick); }); // 广播上传进度。以文件为单位。 tr.on('progress', function (percentage) { block.percentage = percentage; me.updateFileProgress(file); }); // 用来询问,是否返回的结果是有错误的。 requestAccept = function (reject) { var fn; ret = tr.getResponseAsJson() || {}; ret._raw = tr.getResponse(); fn = function (value) { reject = value; }; // 服务端响应了,不代表成功了,询问是否响应正确。 if (!owner.trigger('uploadAccept', block, ret, fn)) { reject = reject || 'server'; } return reject; }; // 尝试重试,然后广播文件上传出错。 tr.on('error', function (type, flag) { block.retried = block.retried || 0; // 自动重试 if (block.chunks > 1 && ~'http,abort'.indexOf(type) && block.retried < opts.chunkRetry) { block.retried++; tr.send(); } else { // http status 500 ~ 600 if (!flag && type === 'server') { type = requestAccept(type); } file.setStatus(Status.ERROR, type); owner.trigger('uploadError', file, type); owner.trigger('uploadComplete', file); } }); // 上传成功 tr.on('load', function () { var reason; // 如果非预期,转向上传出错。 if ((reason = requestAccept())) { tr.trigger('error', reason, true); return; } // 全部上传完成。 if (file.remaning === 1) { me._finishFile(file, ret); } else { tr.destroy(); } }); // 配置默认的上传字段。 data = $.extend(data, { id: file.id, name: file.name, type: file.type, lastModifiedDate: file.lastModifiedDate, size: file.size }); block.chunks > 1 && $.extend(data, { chunks: block.chunks, chunk: block.chunk }); // 在发送之间可以添加字段什么的。。。 // 如果默认的字段不够使用,可以通过监听此事件来扩展 owner.trigger('uploadBeforeSend', block, data, headers); // 开始发送。 tr.appendBlob(opts.fileVal, block.blob, file.name); tr.append(data); tr.setRequestHeader(headers); tr.send(); }, // 完成上传。 _finishFile: function (file, ret, hds) { var owner = this.owner; return owner .request('after-send-file', arguments, function () { file.setStatus(Status.COMPLETE); owner.trigger('uploadSuccess', file, ret, hds); }) .fail(function (reason) { // 如果外部已经标记为invalid什么的,不再改状态。 if (file.getStatus() === Status.PROGRESS) { file.setStatus(Status.ERROR, reason); } owner.trigger('uploadError', file, reason); }) .always(function () { owner.trigger('uploadComplete', file); }); }, updateFileProgress: function (file) { var totalPercent = 0, uploaded = 0; if (!file.blocks) { return; } $.each(file.blocks, function (_, v) { uploaded += (v.percentage || 0) * (v.end - v.start); }); totalPercent = uploaded / file.size; this.owner.trigger('uploadProgress', file, totalPercent || 0); } }); }); /** * @fileOverview 日志组件,主要用来收集错误信息,可以帮助 webuploader 更好的定位问题和发展。 * * 如果您不想要启用此功能,请在打包的时候去掉 log 模块。 * * 或者可以在初始化的时候通过 options.disableWidgets 属性禁用。 * * 如: * WebUploader.create({ * ... * * disableWidgets: 'log', * * ... * }) */ define('widgets/log', [ 'base', 'uploader', 'widgets/widget' ], function (Base, Uploader) { var $ = Base.$, logUrl = ' http://static.tieba.baidu.com/tb/pms/img/st.gif??', product = (location.hostname || location.host || 'protected').toLowerCase(), // 只针对 baidu 内部产品用户做统计功能。 enable = product && /baidu/i.exec(product), base; if (!enable) { return; } base = { dv: 3, master: 'webuploader', online: /test/.exec(product) ? 0 : 1, module: '', product: product, type: 0 }; function send(data) { var obj = $.extend({}, base, data), url = logUrl.replace(/^(.*)\?/, '$1' + $.param(obj)), image = new Image(); image.src = url; } return Uploader.register({ name: 'log', init: function () { var owner = this.owner, count = 0, size = 0; owner .on('error', function (code) { send({ type: 2, c_error_code: code }); }) .on('uploadError', function (file, reason) { send({ type: 2, c_error_code: 'UPLOAD_ERROR', c_reason: '' + reason }); }) .on('uploadComplete', function (file) { count++; size += file.size; }).on('uploadFinished', function () { send({ c_count: count, c_size: size }); count = size = 0; }); send({ c_usage: 1 }); } }); }); /** * @fileOverview Runtime管理器,负责Runtime的选择, 连接 */ define('runtime/compbase', [], function () { function CompBase(owner, runtime) { this.owner = owner; this.options = owner.options; this.getRuntime = function () { return runtime; }; this.getRuid = function () { return runtime.uid; }; this.trigger = function () { return owner.trigger.apply(owner, arguments); }; } return CompBase; }); /** * @fileOverview Html5Runtime */ define('runtime/html5/runtime', [ 'base', 'runtime/runtime', 'runtime/compbase' ], function (Base, Runtime, CompBase) { var type = 'html5', components = {}; function Html5Runtime() { var pool = {}, me = this, destroy = this.destroy; Runtime.apply(me, arguments); me.type = type; // 这个方法的调用者,实际上是RuntimeClient me.exec = function (comp, fn/*, args...*/) { var client = this, uid = client.uid, args = Base.slice(arguments, 2), instance; if (components[comp]) { instance = pool[uid] = pool[uid] || new components[comp](client, me); if (instance[fn]) { return instance[fn].apply(instance, args); } } }; me.destroy = function () { // @todo 删除池子中的所有实例 return destroy && destroy.apply(this, arguments); }; } Base.inherits(Runtime, { constructor: Html5Runtime, // 不需要连接其他程序,直接执行callback init: function () { var me = this; setTimeout(function () { me.trigger('ready'); }, 1); } }); // 注册Components Html5Runtime.register = function (name, component) { var klass = components[name] = Base.inherits(CompBase, component); return klass; }; // 注册html5运行时。 // 只有在支持的前提下注册。 if (window.Blob && window.FileReader && window.DataView) { Runtime.addRuntime(type, Html5Runtime); } return Html5Runtime; }); /** * @fileOverview Blob Html实现 */ define('runtime/html5/blob', [ 'runtime/html5/runtime', 'lib/blob' ], function (Html5Runtime, Blob) { return Html5Runtime.register('Blob', { slice: function (start, end) { var blob = this.owner.source, slice = blob.slice || blob.webkitSlice || blob.mozSlice; blob = slice.call(blob, start, end); return new Blob(this.getRuid(), blob); } }); }); /** * @fileOverview FilePicker */ define('runtime/html5/filepicker', [ 'base', 'runtime/html5/runtime' ], function (Base, Html5Runtime) { var $ = Base.$; return Html5Runtime.register('FilePicker', { init: function () { var container = this.getRuntime().getContainer(), me = this, owner = me.owner, opts = me.options, label = this.label = $(document.createElement('label')), input = this.input = $(document.createElement('input')), arr, i, len, mouseHandler; input.attr('type', 'file'); input.attr('capture', 'camera'); input.attr('name', opts.name); input.addClass('webuploader-element-invisible'); label.on('click', function (e) { input.trigger('click'); e.stopPropagation(); owner.trigger('dialogopen'); }); label.css({ opacity: 0, width: '100%', height: '100%', display: 'block', cursor: 'pointer', background: '#ffffff' }); if (opts.multiple) { input.attr('multiple', 'multiple'); } // @todo Firefox不支持单独指定后缀 if (opts.accept && opts.accept.length > 0) { arr = []; for (i = 0, len = opts.accept.length; i < len; i++) { arr.push(opts.accept[i].mimeTypes); } input.attr('accept', arr.join(',')); } container.append(input); container.append(label); mouseHandler = function (e) { owner.trigger(e.type); }; input.on('change', function (e) { var fn = arguments.callee, clone; me.files = e.target.files; // reset input clone = this.cloneNode(true); clone.value = null; this.parentNode.replaceChild(clone, this); input.off(); input = $(clone).on('change', fn) .on('mouseenter mouseleave', mouseHandler); owner.trigger('change'); }); label.on('mouseenter mouseleave', mouseHandler); }, getFiles: function () { return this.files; }, destroy: function () { this.input.off(); this.label.off(); } }); }); /** * Terms: * * Uint8Array, FileReader, BlobBuilder, atob, ArrayBuffer * @fileOverview Image控件 */ define('runtime/html5/util', [ 'base' ], function (Base) { var urlAPI = window.createObjectURL && window || window.URL && URL.revokeObjectURL && URL || window.webkitURL, createObjectURL = Base.noop, revokeObjectURL = createObjectURL; if (urlAPI) { // 更安全的方式调用,比如android里面就能把context改成其他的对象。 createObjectURL = function () { return urlAPI.createObjectURL.apply(urlAPI, arguments); }; revokeObjectURL = function () { return urlAPI.revokeObjectURL.apply(urlAPI, arguments); }; } return { createObjectURL: createObjectURL, revokeObjectURL: revokeObjectURL, dataURL2Blob: function (dataURI) { var byteStr, intArray, ab, i, mimetype, parts; parts = dataURI.split(','); if (~parts[0].indexOf('base64')) { byteStr = atob(parts[1]); } else { byteStr = decodeURIComponent(parts[1]); } ab = new ArrayBuffer(byteStr.length); intArray = new Uint8Array(ab); for (i = 0; i < byteStr.length; i++) { intArray[i] = byteStr.charCodeAt(i); } mimetype = parts[0].split(':')[1].split(';')[0]; return this.arrayBufferToBlob(ab, mimetype); }, dataURL2ArrayBuffer: function (dataURI) { var byteStr, intArray, i, parts; parts = dataURI.split(','); if (~parts[0].indexOf('base64')) { byteStr = atob(parts[1]); } else { byteStr = decodeURIComponent(parts[1]); } intArray = new Uint8Array(byteStr.length); for (i = 0; i < byteStr.length; i++) { intArray[i] = byteStr.charCodeAt(i); } return intArray.buffer; }, arrayBufferToBlob: function (buffer, type) { var builder = window.BlobBuilder || window.WebKitBlobBuilder, bb; // android不支持直接new Blob, 只能借助blobbuilder. if (builder) { bb = new builder(); bb.append(buffer); return bb.getBlob(type); } return new Blob([buffer], type ? {type: type} : {}); }, // 抽出来主要是为了解决android下面canvas.toDataUrl不支持jpeg. // 你得到的结果是png. canvasToDataUrl: function (canvas, type, quality) { return canvas.toDataURL(type, quality / 100); }, // imagemeat会复写这个方法,如果用户选择加载那个文件了的话。 parseMeta: function (blob, callback) { callback(false, {}); }, // imagemeat会复写这个方法,如果用户选择加载那个文件了的话。 updateImageHead: function (data) { return data; } }; }); /** * Terms: * * Uint8Array, FileReader, BlobBuilder, atob, ArrayBuffer * @fileOverview Image控件 */ define('runtime/html5/imagemeta', [ 'runtime/html5/util' ], function (Util) { var api; api = { parsers: { 0xffe1: [] }, maxMetaDataSize: 262144, parse: function (blob, cb) { var me = this, fr = new FileReader(); fr.onload = function () { cb(false, me._parse(this.result)); fr = fr.onload = fr.onerror = null; }; fr.onerror = function (e) { cb(e.message); fr = fr.onload = fr.onerror = null; }; blob = blob.slice(0, me.maxMetaDataSize); fr.readAsArrayBuffer(blob.getSource()); }, _parse: function (buffer, noParse) { if (buffer.byteLength < 6) { return; } var dataview = new DataView(buffer), offset = 2, maxOffset = dataview.byteLength - 4, headLength = offset, ret = {}, markerBytes, markerLength, parsers, i; if (dataview.getUint16(0) === 0xffd8) { while (offset < maxOffset) { markerBytes = dataview.getUint16(offset); if (markerBytes >= 0xffe0 && markerBytes <= 0xffef || markerBytes === 0xfffe) { markerLength = dataview.getUint16(offset + 2) + 2; if (offset + markerLength > dataview.byteLength) { break; } parsers = api.parsers[markerBytes]; if (!noParse && parsers) { for (i = 0; i < parsers.length; i += 1) { parsers[i].call(api, dataview, offset, markerLength, ret); } } offset += markerLength; headLength = offset; } else { break; } } if (headLength > 6) { if (buffer.slice) { ret.imageHead = buffer.slice(2, headLength); } else { // Workaround for IE10, which does not yet // support ArrayBuffer.slice: ret.imageHead = new Uint8Array(buffer) .subarray(2, headLength); } } } return ret; }, updateImageHead: function (buffer, head) { var data = this._parse(buffer, true), buf1, buf2, bodyoffset; bodyoffset = 2; if (data.imageHead) { bodyoffset = 2 + data.imageHead.byteLength; } if (buffer.slice) { buf2 = buffer.slice(bodyoffset); } else { buf2 = new Uint8Array(buffer).subarray(bodyoffset); } buf1 = new Uint8Array(head.byteLength + 2 + buf2.byteLength); buf1[0] = 0xFF; buf1[1] = 0xD8; buf1.set(new Uint8Array(head), 2); buf1.set(new Uint8Array(buf2), head.byteLength + 2); return buf1.buffer; } }; Util.parseMeta = function () { return api.parse.apply(api, arguments); }; Util.updateImageHead = function () { return api.updateImageHead.apply(api, arguments); }; return api; }); /** * 代码来自于:https://github.com/blueimp/JavaScript-Load-Image * 暂时项目中只用了orientation. * * 去除了 Exif Sub IFD Pointer, GPS Info IFD Pointer, Exif Thumbnail. * @fileOverview EXIF解析 */ // Sample // ==================================== // Make : Apple // Model : iPhone 4S // Orientation : 1 // XResolution : 72 [72/1] // YResolution : 72 [72/1] // ResolutionUnit : 2 // Software : QuickTime 7.7.1 // DateTime : 2013:09:01 22:53:55 // ExifIFDPointer : 190 // ExposureTime : 0.058823529411764705 [1/17] // FNumber : 2.4 [12/5] // ExposureProgram : Normal program // ISOSpeedRatings : 800 // ExifVersion : 0220 // DateTimeOriginal : 2013:09:01 22:52:51 // DateTimeDigitized : 2013:09:01 22:52:51 // ComponentsConfiguration : YCbCr // ShutterSpeedValue : 4.058893515764426 // ApertureValue : 2.5260688216892597 [4845/1918] // BrightnessValue : -0.3126686601998395 // MeteringMode : Pattern // Flash : Flash did not fire, compulsory flash mode // FocalLength : 4.28 [107/25] // SubjectArea : [4 values] // FlashpixVersion : 0100 // ColorSpace : 1 // PixelXDimension : 2448 // PixelYDimension : 3264 // SensingMethod : One-chip color area sensor // ExposureMode : 0 // WhiteBalance : Auto white balance // FocalLengthIn35mmFilm : 35 // SceneCaptureType : Standard define('runtime/html5/imagemeta/exif', [ 'base', 'runtime/html5/imagemeta' ], function (Base, ImageMeta) { var EXIF = {}; EXIF.ExifMap = function () { return this; }; EXIF.ExifMap.prototype.map = { 'Orientation': 0x0112 }; EXIF.ExifMap.prototype.get = function (id) { return this[id] || this[this.map[id]]; }; EXIF.exifTagTypes = { // byte, 8-bit unsigned int: 1: { getValue: function (dataView, dataOffset) { return dataView.getUint8(dataOffset); }, size: 1 }, // ascii, 8-bit byte: 2: { getValue: function (dataView, dataOffset) { return String.fromCharCode(dataView.getUint8(dataOffset)); }, size: 1, ascii: true }, // short, 16 bit int: 3: { getValue: function (dataView, dataOffset, littleEndian) { return dataView.getUint16(dataOffset, littleEndian); }, size: 2 }, // long, 32 bit int: 4: { getValue: function (dataView, dataOffset, littleEndian) { return dataView.getUint32(dataOffset, littleEndian); }, size: 4 }, // rational = two long values, // first is numerator, second is denominator: 5: { getValue: function (dataView, dataOffset, littleEndian) { return dataView.getUint32(dataOffset, littleEndian) / dataView.getUint32(dataOffset + 4, littleEndian); }, size: 8 }, // slong, 32 bit signed int: 9: { getValue: function (dataView, dataOffset, littleEndian) { return dataView.getInt32(dataOffset, littleEndian); }, size: 4 }, // srational, two slongs, first is numerator, second is denominator: 10: { getValue: function (dataView, dataOffset, littleEndian) { return dataView.getInt32(dataOffset, littleEndian) / dataView.getInt32(dataOffset + 4, littleEndian); }, size: 8 } }; // undefined, 8-bit byte, value depending on field: EXIF.exifTagTypes[7] = EXIF.exifTagTypes[1]; EXIF.getExifValue = function (dataView, tiffOffset, offset, type, length, littleEndian) { var tagType = EXIF.exifTagTypes[type], tagSize, dataOffset, values, i, str, c; if (!tagType) { Base.log('Invalid Exif data: Invalid tag type.'); return; } tagSize = tagType.size * length; // Determine if the value is contained in the dataOffset bytes, // or if the value at the dataOffset is a pointer to the actual data: dataOffset = tagSize > 4 ? tiffOffset + dataView.getUint32(offset + 8, littleEndian) : (offset + 8); if (dataOffset + tagSize > dataView.byteLength) { Base.log('Invalid Exif data: Invalid data offset.'); return; } if (length === 1) { return tagType.getValue(dataView, dataOffset, littleEndian); } values = []; for (i = 0; i < length; i += 1) { values[i] = tagType.getValue(dataView, dataOffset + i * tagType.size, littleEndian); } if (tagType.ascii) { str = ''; // Concatenate the chars: for (i = 0; i < values.length; i += 1) { c = values[i]; // Ignore the terminating NULL byte(s): if (c === '\u0000') { break; } str += c; } return str; } return values; }; EXIF.parseExifTag = function (dataView, tiffOffset, offset, littleEndian, data) { var tag = dataView.getUint16(offset, littleEndian); data.exif[tag] = EXIF.getExifValue(dataView, tiffOffset, offset, dataView.getUint16(offset + 2, littleEndian), // tag type dataView.getUint32(offset + 4, littleEndian), // tag length littleEndian); }; EXIF.parseExifTags = function (dataView, tiffOffset, dirOffset, littleEndian, data) { var tagsNumber, dirEndOffset, i; if (dirOffset + 6 > dataView.byteLength) { Base.log('Invalid Exif data: Invalid directory offset.'); return; } tagsNumber = dataView.getUint16(dirOffset, littleEndian); dirEndOffset = dirOffset + 2 + 12 * tagsNumber; if (dirEndOffset + 4 > dataView.byteLength) { Base.log('Invalid Exif data: Invalid directory size.'); return; } for (i = 0; i < tagsNumber; i += 1) { this.parseExifTag(dataView, tiffOffset, dirOffset + 2 + 12 * i, // tag offset littleEndian, data); } // Return the offset to the next directory: return dataView.getUint32(dirEndOffset, littleEndian); }; // EXIF.getExifThumbnail = function(dataView, offset, length) { // var hexData, // i, // b; // if (!length || offset + length > dataView.byteLength) { // Base.log('Invalid Exif data: Invalid thumbnail data.'); // return; // } // hexData = []; // for (i = 0; i < length; i += 1) { // b = dataView.getUint8(offset + i); // hexData.push((b < 16 ? '0' : '') + b.toString(16)); // } // return 'data:image/jpeg,%' + hexData.join('%'); // }; EXIF.parseExifData = function (dataView, offset, length, data) { var tiffOffset = offset + 10, littleEndian, dirOffset; // Check for the ASCII code for "Exif" (0x45786966): if (dataView.getUint32(offset + 4) !== 0x45786966) { // No Exif data, might be XMP data instead return; } if (tiffOffset + 8 > dataView.byteLength) { Base.log('Invalid Exif data: Invalid segment size.'); return; } // Check for the two null bytes: if (dataView.getUint16(offset + 8) !== 0x0000) { Base.log('Invalid Exif data: Missing byte alignment offset.'); return; } // Check the byte alignment: switch (dataView.getUint16(tiffOffset)) { case 0x4949: littleEndian = true; break; case 0x4D4D: littleEndian = false; break; default: Base.log('Invalid Exif data: Invalid byte alignment marker.'); return; } // Check for the TIFF tag marker (0x002A): if (dataView.getUint16(tiffOffset + 2, littleEndian) !== 0x002A) { Base.log('Invalid Exif data: Missing TIFF marker.'); return; } // Retrieve the directory offset bytes, usually 0x00000008 or 8 decimal: dirOffset = dataView.getUint32(tiffOffset + 4, littleEndian); // Create the exif object to store the tags: data.exif = new EXIF.ExifMap(); // Parse the tags of the main image directory and retrieve the // offset to the next directory, usually the thumbnail directory: dirOffset = EXIF.parseExifTags(dataView, tiffOffset, tiffOffset + dirOffset, littleEndian, data); // 尝试读取缩略图 // if ( dirOffset ) { // thumbnailData = {exif: {}}; // dirOffset = EXIF.parseExifTags( // dataView, // tiffOffset, // tiffOffset + dirOffset, // littleEndian, // thumbnailData // ); // // Check for JPEG Thumbnail offset: // if (thumbnailData.exif[0x0201]) { // data.exif.Thumbnail = EXIF.getExifThumbnail( // dataView, // tiffOffset + thumbnailData.exif[0x0201], // thumbnailData.exif[0x0202] // Thumbnail data length // ); // } // } }; ImageMeta.parsers[0xffe1].push(EXIF.parseExifData); return EXIF; }); /** * @fileOverview Image */ define('runtime/html5/image', [ 'base', 'runtime/html5/runtime', 'runtime/html5/util' ], function (Base, Html5Runtime, Util) { var BLANK = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D'; return Html5Runtime.register('Image', { // flag: 标记是否被修改过。 modified: false, init: function () { var me = this, img = new Image(); img.onload = function () { me._info = { type: me.type, width: this.width, height: this.height }; //debugger; // 读取meta信息。 if (!me._metas && 'image/jpeg' === me.type) { Util.parseMeta(me._blob, function (error, ret) { me._metas = ret; me.owner.trigger('load'); }); } else { me.owner.trigger('load'); } }; img.onerror = function () { me.owner.trigger('error'); }; me._img = img; }, loadFromBlob: function (blob) { var me = this, img = me._img; me._blob = blob; me.type = blob.type; img.src = Util.createObjectURL(blob.getSource()); me.owner.once('load', function () { Util.revokeObjectURL(img.src); }); }, resize: function (width, height) { var canvas = this._canvas || (this._canvas = document.createElement('canvas')); this._resize(this._img, canvas, width, height); this._blob = null; // 没用了,可以删掉了。 this.modified = true; this.owner.trigger('complete', 'resize'); }, crop: function (x, y, w, h, s) { var cvs = this._canvas || (this._canvas = document.createElement('canvas')), opts = this.options, img = this._img, iw = img.naturalWidth, ih = img.naturalHeight, orientation = this.getOrientation(); s = s || 1; // todo 解决 orientation 的问题。 // values that require 90 degree rotation // if ( ~[ 5, 6, 7, 8 ].indexOf( orientation ) ) { // switch ( orientation ) { // case 6: // tmp = x; // x = y; // y = iw * s - tmp - w; // console.log(ih * s, tmp, w) // break; // } // (w ^= h, h ^= w, w ^= h); // } cvs.width = w; cvs.height = h; opts.preserveHeaders || this._rotate2Orientaion(cvs, orientation); this._renderImageToCanvas(cvs, img, -x, -y, iw * s, ih * s); this._blob = null; // 没用了,可以删掉了。 this.modified = true; this.owner.trigger('complete', 'crop'); }, getAsBlob: function (type) { var blob = this._blob, opts = this.options, canvas; type = type || this.type; // blob需要重新生成。 if (this.modified || this.type !== type) { canvas = this._canvas; if (type === 'image/jpeg') { blob = Util.canvasToDataUrl(canvas, type, opts.quality); if (opts.preserveHeaders && this._metas && this._metas.imageHead) { blob = Util.dataURL2ArrayBuffer(blob); blob = Util.updateImageHead(blob, this._metas.imageHead); blob = Util.arrayBufferToBlob(blob, type); return blob; } } else { blob = Util.canvasToDataUrl(canvas, type); } blob = Util.dataURL2Blob(blob); } return blob; }, getAsDataUrl: function (type) { var opts = this.options; type = type || this.type; if (type === 'image/jpeg') { return Util.canvasToDataUrl(this._canvas, type, opts.quality); } else { return this._canvas.toDataURL(type); } }, getOrientation: function () { return this._metas && this._metas.exif && this._metas.exif.get('Orientation') || 1; }, info: function (val) { // setter if (val) { this._info = val; return this; } // getter return this._info; }, meta: function (val) { // setter if (val) { this._metas = val; return this; } // getter return this._metas; }, destroy: function () { var canvas = this._canvas; this._img.onload = null; if (canvas) { canvas.getContext('2d') .clearRect(0, 0, canvas.width, canvas.height); canvas.width = canvas.height = 0; this._canvas = null; } // 释放内存。非常重要,否则释放不了image的内存。 this._img.src = BLANK; this._img = this._blob = null; }, _resize: function (img, cvs, width, height) { var opts = this.options, naturalWidth = img.width, naturalHeight = img.height, orientation = this.getOrientation(), scale, w, h, x, y; // values that require 90 degree rotation if (~[5, 6, 7, 8].indexOf(orientation)) { // 交换width, height的值。 width ^= height; height ^= width; width ^= height; } scale = Math[opts.crop ? 'max' : 'min'](width / naturalWidth, height / naturalHeight); // 不允许放大。 opts.allowMagnify || (scale = Math.min(1, scale)); w = naturalWidth * scale; h = naturalHeight * scale; if (opts.crop) { cvs.width = width; cvs.height = height; } else { cvs.width = w; cvs.height = h; } x = (cvs.width - w) / 2; y = (cvs.height - h) / 2; opts.preserveHeaders || this._rotate2Orientaion(cvs, orientation); this._renderImageToCanvas(cvs, img, x, y, w, h); }, _rotate2Orientaion: function (canvas, orientation) { var width = canvas.width, height = canvas.height, ctx = canvas.getContext('2d'); switch (orientation) { case 5: case 6: case 7: case 8: canvas.width = height; canvas.height = width; break; } switch (orientation) { case 2: // horizontal flip ctx.translate(width, 0); ctx.scale(-1, 1); break; case 3: // 180 rotate left ctx.translate(width, height); ctx.rotate(Math.PI); break; case 4: // vertical flip ctx.translate(0, height); ctx.scale(1, -1); break; case 5: // vertical flip + 90 rotate right ctx.rotate(0.5 * Math.PI); ctx.scale(1, -1); break; case 6: // 90 rotate right ctx.rotate(0.5 * Math.PI); ctx.translate(0, -height); break; case 7: // horizontal flip + 90 rotate right ctx.rotate(0.5 * Math.PI); ctx.translate(width, -height); ctx.scale(-1, 1); break; case 8: // 90 rotate left ctx.rotate(-0.5 * Math.PI); ctx.translate(-width, 0); break; } }, // https://github.com/stomita/ios-imagefile-megapixel/ // blob/master/src/megapix-image.js _renderImageToCanvas: (function () { // 如果不是ios, 不需要这么复杂! if (!Base.os.ios) { return function (canvas) { var args = Base.slice(arguments, 1), ctx = canvas.getContext('2d'); ctx.drawImage.apply(ctx, args); }; } /** * Detecting vertical squash in loaded image. * Fixes a bug which squash image vertically while drawing into * canvas for some images. */ function detectVerticalSquash(img, iw, ih) { var canvas = document.createElement('canvas'), ctx = canvas.getContext('2d'), sy = 0, ey = ih, py = ih, data, alpha, ratio; canvas.width = 1; canvas.height = ih; ctx.drawImage(img, 0, 0); data = ctx.getImageData(0, 0, 1, ih).data; // search image edge pixel position in case // it is squashed vertically. while (py > sy) { alpha = data[(py - 1) * 4 + 3]; if (alpha === 0) { ey = py; } else { sy = py; } py = (ey + sy) >> 1; } ratio = (py / ih); return (ratio === 0) ? 1 : ratio; } // fix ie7 bug // http://stackoverflow.com/questions/11929099/ // html5-canvas-drawimage-ratio-bug-ios if (Base.os.ios >= 7) { return function (canvas, img, x, y, w, h) { var iw = img.naturalWidth, ih = img.naturalHeight, vertSquashRatio = detectVerticalSquash(img, iw, ih); return canvas.getContext('2d').drawImage(img, 0, 0, iw * vertSquashRatio, ih * vertSquashRatio, x, y, w, h); }; } /** * Detect subsampling in loaded image. * In iOS, larger images than 2M pixels may be * subsampled in rendering. */ function detectSubsampling(img) { var iw = img.naturalWidth, ih = img.naturalHeight, canvas, ctx; // subsampling may happen overmegapixel image if (iw * ih > 1024 * 1024) { canvas = document.createElement('canvas'); canvas.width = canvas.height = 1; ctx = canvas.getContext('2d'); ctx.drawImage(img, -iw + 1, 0); // subsampled image becomes half smaller in rendering size. // check alpha channel value to confirm image is covering // edge pixel or not. if alpha value is 0 // image is not covering, hence subsampled. return ctx.getImageData(0, 0, 1, 1).data[3] === 0; } else { return false; } } return function (canvas, img, x, y, width, height) { var iw = img.naturalWidth, ih = img.naturalHeight, ctx = canvas.getContext('2d'), subsampled = detectSubsampling(img), doSquash = this.type === 'image/jpeg', d = 1024, sy = 0, dy = 0, tmpCanvas, tmpCtx, vertSquashRatio, dw, dh, sx, dx; if (subsampled) { iw /= 2; ih /= 2; } ctx.save(); tmpCanvas = document.createElement('canvas'); tmpCanvas.width = tmpCanvas.height = d; tmpCtx = tmpCanvas.getContext('2d'); vertSquashRatio = doSquash ? detectVerticalSquash(img, iw, ih) : 1; dw = Math.ceil(d * width / iw); dh = Math.ceil(d * height / ih / vertSquashRatio); while (sy < ih) { sx = 0; dx = 0; while (sx < iw) { tmpCtx.clearRect(0, 0, d, d); tmpCtx.drawImage(img, -sx, -sy); ctx.drawImage(tmpCanvas, 0, 0, d, d, x + dx, y + dy, dw, dh); sx += d; dx += dw; } sy += d; dy += dh; } ctx.restore(); tmpCanvas = tmpCtx = null; }; })() }); }); /** * 这个方式性能不行,但是可以解决android里面的toDataUrl的bug * android里面toDataUrl('image/jpege')得到的结果却是png. * * 所以这里没辙,只能借助这个工具 * @fileOverview jpeg encoder */ define('runtime/html5/jpegencoder', [], function (require, exports, module) { /* Copyright (c) 2008, Adobe Systems Incorporated 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 Adobe Systems Incorporated 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. */ /* JPEG encoder ported to JavaScript and optimized by Andreas Ritter, www.bytestrom.eu, 11/2009 Basic GUI blocking jpeg encoder */ function JPEGEncoder(quality) { var self = this; var fround = Math.round; var ffloor = Math.floor; var YTable = new Array(64); var UVTable = new Array(64); var fdtbl_Y = new Array(64); var fdtbl_UV = new Array(64); var YDC_HT; var UVDC_HT; var YAC_HT; var UVAC_HT; var bitcode = new Array(65535); var category = new Array(65535); var outputfDCTQuant = new Array(64); var DU = new Array(64); var byteout = []; var bytenew = 0; var bytepos = 7; var YDU = new Array(64); var UDU = new Array(64); var VDU = new Array(64); var clt = new Array(256); var RGB_YUV_TABLE = new Array(2048); var currentQuality; var ZigZag = [ 0, 1, 5, 6, 14, 15, 27, 28, 2, 4, 7, 13, 16, 26, 29, 42, 3, 8, 12, 17, 25, 30, 41, 43, 9, 11, 18, 24, 31, 40, 44, 53, 10, 19, 23, 32, 39, 45, 52, 54, 20, 22, 33, 38, 46, 51, 55, 60, 21, 34, 37, 47, 50, 56, 59, 61, 35, 36, 48, 49, 57, 58, 62, 63 ]; var std_dc_luminance_nrcodes = [0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0]; var std_dc_luminance_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; var std_ac_luminance_nrcodes = [0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d]; var std_ac_luminance_values = [ 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa ]; var std_dc_chrominance_nrcodes = [0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]; var std_dc_chrominance_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; var std_ac_chrominance_nrcodes = [0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77]; var std_ac_chrominance_values = [ 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa ]; function initQuantTables(sf) { var YQT = [ 16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57, 69, 56, 14, 17, 22, 29, 51, 87, 80, 62, 18, 22, 37, 56, 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113, 92, 49, 64, 78, 87, 103, 121, 120, 101, 72, 92, 95, 98, 112, 100, 103, 99 ]; for (var i = 0; i < 64; i++) { var t = ffloor((YQT[i] * sf + 50) / 100); if (t < 1) { t = 1; } else if (t > 255) { t = 255; } YTable[ZigZag[i]] = t; } var UVQT = [ 17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, 24, 26, 56, 99, 99, 99, 99, 99, 47, 66, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99 ]; for (var j = 0; j < 64; j++) { var u = ffloor((UVQT[j] * sf + 50) / 100); if (u < 1) { u = 1; } else if (u > 255) { u = 255; } UVTable[ZigZag[j]] = u; } var aasf = [ 1.0, 1.387039845, 1.306562965, 1.175875602, 1.0, 0.785694958, 0.541196100, 0.275899379 ]; var k = 0; for (var row = 0; row < 8; row++) { for (var col = 0; col < 8; col++) { fdtbl_Y[k] = (1.0 / (YTable [ZigZag[k]] * aasf[row] * aasf[col] * 8.0)); fdtbl_UV[k] = (1.0 / (UVTable[ZigZag[k]] * aasf[row] * aasf[col] * 8.0)); k++; } } } function computeHuffmanTbl(nrcodes, std_table) { var codevalue = 0; var pos_in_table = 0; var HT = new Array(); for (var k = 1; k <= 16; k++) { for (var j = 1; j <= nrcodes[k]; j++) { HT[std_table[pos_in_table]] = []; HT[std_table[pos_in_table]][0] = codevalue; HT[std_table[pos_in_table]][1] = k; pos_in_table++; codevalue++; } codevalue *= 2; } return HT; } function initHuffmanTbl() { YDC_HT = computeHuffmanTbl(std_dc_luminance_nrcodes, std_dc_luminance_values); UVDC_HT = computeHuffmanTbl(std_dc_chrominance_nrcodes, std_dc_chrominance_values); YAC_HT = computeHuffmanTbl(std_ac_luminance_nrcodes, std_ac_luminance_values); UVAC_HT = computeHuffmanTbl(std_ac_chrominance_nrcodes, std_ac_chrominance_values); } function initCategoryNumber() { var nrlower = 1; var nrupper = 2; for (var cat = 1; cat <= 15; cat++) { //Positive numbers for (var nr = nrlower; nr < nrupper; nr++) { category[32767 + nr] = cat; bitcode[32767 + nr] = []; bitcode[32767 + nr][1] = cat; bitcode[32767 + nr][0] = nr; } //Negative numbers for (var nrneg = -(nrupper - 1); nrneg <= -nrlower; nrneg++) { category[32767 + nrneg] = cat; bitcode[32767 + nrneg] = []; bitcode[32767 + nrneg][1] = cat; bitcode[32767 + nrneg][0] = nrupper - 1 + nrneg; } nrlower <<= 1; nrupper <<= 1; } } function initRGBYUVTable() { for (var i = 0; i < 256; i++) { RGB_YUV_TABLE[i] = 19595 * i; RGB_YUV_TABLE[(i + 256) >> 0] = 38470 * i; RGB_YUV_TABLE[(i + 512) >> 0] = 7471 * i + 0x8000; RGB_YUV_TABLE[(i + 768) >> 0] = -11059 * i; RGB_YUV_TABLE[(i + 1024) >> 0] = -21709 * i; RGB_YUV_TABLE[(i + 1280) >> 0] = 32768 * i + 0x807FFF; RGB_YUV_TABLE[(i + 1536) >> 0] = -27439 * i; RGB_YUV_TABLE[(i + 1792) >> 0] = -5329 * i; } } // IO functions function writeBits(bs) { var value = bs[0]; var posval = bs[1] - 1; while (posval >= 0) { if (value & (1 << posval)) { bytenew |= (1 << bytepos); } posval--; bytepos--; if (bytepos < 0) { if (bytenew == 0xFF) { writeByte(0xFF); writeByte(0); } else { writeByte(bytenew); } bytepos = 7; bytenew = 0; } } } function writeByte(value) { byteout.push(clt[value]); // write char directly instead of converting later } function writeWord(value) { writeByte((value >> 8) & 0xFF); writeByte((value ) & 0xFF); } // DCT & quantization core function fDCTQuant(data, fdtbl) { var d0, d1, d2, d3, d4, d5, d6, d7; /* Pass 1: process rows. */ var dataOff = 0; var i; var I8 = 8; var I64 = 64; for (i = 0; i < I8; ++i) { d0 = data[dataOff]; d1 = data[dataOff + 1]; d2 = data[dataOff + 2]; d3 = data[dataOff + 3]; d4 = data[dataOff + 4]; d5 = data[dataOff + 5]; d6 = data[dataOff + 6]; d7 = data[dataOff + 7]; var tmp0 = d0 + d7; var tmp7 = d0 - d7; var tmp1 = d1 + d6; var tmp6 = d1 - d6; var tmp2 = d2 + d5; var tmp5 = d2 - d5; var tmp3 = d3 + d4; var tmp4 = d3 - d4; /* Even part */ var tmp10 = tmp0 + tmp3; /* phase 2 */ var tmp13 = tmp0 - tmp3; var tmp11 = tmp1 + tmp2; var tmp12 = tmp1 - tmp2; data[dataOff] = tmp10 + tmp11; /* phase 3 */ data[dataOff + 4] = tmp10 - tmp11; var z1 = (tmp12 + tmp13) * 0.707106781; /* c4 */ data[dataOff + 2] = tmp13 + z1; /* phase 5 */ data[dataOff + 6] = tmp13 - z1; /* Odd part */ tmp10 = tmp4 + tmp5; /* phase 2 */ tmp11 = tmp5 + tmp6; tmp12 = tmp6 + tmp7; /* The rotator is modified from fig 4-8 to avoid extra negations. */ var z5 = (tmp10 - tmp12) * 0.382683433; /* c6 */ var z2 = 0.541196100 * tmp10 + z5; /* c2-c6 */ var z4 = 1.306562965 * tmp12 + z5; /* c2+c6 */ var z3 = tmp11 * 0.707106781; /* c4 */ var z11 = tmp7 + z3; /* phase 5 */ var z13 = tmp7 - z3; data[dataOff + 5] = z13 + z2; /* phase 6 */ data[dataOff + 3] = z13 - z2; data[dataOff + 1] = z11 + z4; data[dataOff + 7] = z11 - z4; dataOff += 8; /* advance pointer to next row */ } /* Pass 2: process columns. */ dataOff = 0; for (i = 0; i < I8; ++i) { d0 = data[dataOff]; d1 = data[dataOff + 8]; d2 = data[dataOff + 16]; d3 = data[dataOff + 24]; d4 = data[dataOff + 32]; d5 = data[dataOff + 40]; d6 = data[dataOff + 48]; d7 = data[dataOff + 56]; var tmp0p2 = d0 + d7; var tmp7p2 = d0 - d7; var tmp1p2 = d1 + d6; var tmp6p2 = d1 - d6; var tmp2p2 = d2 + d5; var tmp5p2 = d2 - d5; var tmp3p2 = d3 + d4; var tmp4p2 = d3 - d4; /* Even part */ var tmp10p2 = tmp0p2 + tmp3p2; /* phase 2 */ var tmp13p2 = tmp0p2 - tmp3p2; var tmp11p2 = tmp1p2 + tmp2p2; var tmp12p2 = tmp1p2 - tmp2p2; data[dataOff] = tmp10p2 + tmp11p2; /* phase 3 */ data[dataOff + 32] = tmp10p2 - tmp11p2; var z1p2 = (tmp12p2 + tmp13p2) * 0.707106781; /* c4 */ data[dataOff + 16] = tmp13p2 + z1p2; /* phase 5 */ data[dataOff + 48] = tmp13p2 - z1p2; /* Odd part */ tmp10p2 = tmp4p2 + tmp5p2; /* phase 2 */ tmp11p2 = tmp5p2 + tmp6p2; tmp12p2 = tmp6p2 + tmp7p2; /* The rotator is modified from fig 4-8 to avoid extra negations. */ var z5p2 = (tmp10p2 - tmp12p2) * 0.382683433; /* c6 */ var z2p2 = 0.541196100 * tmp10p2 + z5p2; /* c2-c6 */ var z4p2 = 1.306562965 * tmp12p2 + z5p2; /* c2+c6 */ var z3p2 = tmp11p2 * 0.707106781; /* c4 */ var z11p2 = tmp7p2 + z3p2; /* phase 5 */ var z13p2 = tmp7p2 - z3p2; data[dataOff + 40] = z13p2 + z2p2; /* phase 6 */ data[dataOff + 24] = z13p2 - z2p2; data[dataOff + 8] = z11p2 + z4p2; data[dataOff + 56] = z11p2 - z4p2; dataOff++; /* advance pointer to next column */ } // Quantize/descale the coefficients var fDCTQuant; for (i = 0; i < I64; ++i) { // Apply the quantization and scaling factor & Round to nearest integer fDCTQuant = data[i] * fdtbl[i]; outputfDCTQuant[i] = (fDCTQuant > 0.0) ? ((fDCTQuant + 0.5) | 0) : ((fDCTQuant - 0.5) | 0); //outputfDCTQuant[i] = fround(fDCTQuant); } return outputfDCTQuant; } function writeAPP0() { writeWord(0xFFE0); // marker writeWord(16); // length writeByte(0x4A); // J writeByte(0x46); // F writeByte(0x49); // I writeByte(0x46); // F writeByte(0); // = "JFIF",'\0' writeByte(1); // versionhi writeByte(1); // versionlo writeByte(0); // xyunits writeWord(1); // xdensity writeWord(1); // ydensity writeByte(0); // thumbnwidth writeByte(0); // thumbnheight } function writeSOF0(width, height) { writeWord(0xFFC0); // marker writeWord(17); // length, truecolor YUV JPG writeByte(8); // precision writeWord(height); writeWord(width); writeByte(3); // nrofcomponents writeByte(1); // IdY writeByte(0x11); // HVY writeByte(0); // QTY writeByte(2); // IdU writeByte(0x11); // HVU writeByte(1); // QTU writeByte(3); // IdV writeByte(0x11); // HVV writeByte(1); // QTV } function writeDQT() { writeWord(0xFFDB); // marker writeWord(132); // length writeByte(0); for (var i = 0; i < 64; i++) { writeByte(YTable[i]); } writeByte(1); for (var j = 0; j < 64; j++) { writeByte(UVTable[j]); } } function writeDHT() { writeWord(0xFFC4); // marker writeWord(0x01A2); // length writeByte(0); // HTYDCinfo for (var i = 0; i < 16; i++) { writeByte(std_dc_luminance_nrcodes[i + 1]); } for (var j = 0; j <= 11; j++) { writeByte(std_dc_luminance_values[j]); } writeByte(0x10); // HTYACinfo for (var k = 0; k < 16; k++) { writeByte(std_ac_luminance_nrcodes[k + 1]); } for (var l = 0; l <= 161; l++) { writeByte(std_ac_luminance_values[l]); } writeByte(1); // HTUDCinfo for (var m = 0; m < 16; m++) { writeByte(std_dc_chrominance_nrcodes[m + 1]); } for (var n = 0; n <= 11; n++) { writeByte(std_dc_chrominance_values[n]); } writeByte(0x11); // HTUACinfo for (var o = 0; o < 16; o++) { writeByte(std_ac_chrominance_nrcodes[o + 1]); } for (var p = 0; p <= 161; p++) { writeByte(std_ac_chrominance_values[p]); } } function writeSOS() { writeWord(0xFFDA); // marker writeWord(12); // length writeByte(3); // nrofcomponents writeByte(1); // IdY writeByte(0); // HTY writeByte(2); // IdU writeByte(0x11); // HTU writeByte(3); // IdV writeByte(0x11); // HTV writeByte(0); // Ss writeByte(0x3f); // Se writeByte(0); // Bf } function processDU(CDU, fdtbl, DC, HTDC, HTAC) { var EOB = HTAC[0x00]; var M16zeroes = HTAC[0xF0]; var pos; var I16 = 16; var I63 = 63; var I64 = 64; var DU_DCT = fDCTQuant(CDU, fdtbl); //ZigZag reorder for (var j = 0; j < I64; ++j) { DU[ZigZag[j]] = DU_DCT[j]; } var Diff = DU[0] - DC; DC = DU[0]; //Encode DC if (Diff == 0) { writeBits(HTDC[0]); // Diff might be 0 } else { pos = 32767 + Diff; writeBits(HTDC[category[pos]]); writeBits(bitcode[pos]); } //Encode ACs var end0pos = 63; // was const... which is crazy for (; (end0pos > 0) && (DU[end0pos] == 0); end0pos--) { } ; //end0pos = first element in reverse order !=0 if (end0pos == 0) { writeBits(EOB); return DC; } var i = 1; var lng; while (i <= end0pos) { var startpos = i; for (; (DU[i] == 0) && (i <= end0pos); ++i) { } var nrzeroes = i - startpos; if (nrzeroes >= I16) { lng = nrzeroes >> 4; for (var nrmarker = 1; nrmarker <= lng; ++nrmarker) writeBits(M16zeroes); nrzeroes = nrzeroes & 0xF; } pos = 32767 + DU[i]; writeBits(HTAC[(nrzeroes << 4) + category[pos]]); writeBits(bitcode[pos]); i++; } if (end0pos != I63) { writeBits(EOB); } return DC; } function initCharLookupTable() { var sfcc = String.fromCharCode; for (var i = 0; i < 256; i++) { ///// ACHTUNG // 255 clt[i] = sfcc(i); } } this.encode = function (image, quality) // image data object { // var time_start = new Date().getTime(); if (quality) setQuality(quality); // Initialize bit writer byteout = new Array(); bytenew = 0; bytepos = 7; // Add JPEG headers writeWord(0xFFD8); // SOI writeAPP0(); writeDQT(); writeSOF0(image.width, image.height); writeDHT(); writeSOS(); // Encode 8x8 macroblocks var DCY = 0; var DCU = 0; var DCV = 0; bytenew = 0; bytepos = 7; this.encode.displayName = "_encode_"; var imageData = image.data; var width = image.width; var height = image.height; var quadWidth = width * 4; var tripleWidth = width * 3; var x, y = 0; var r, g, b; var start, p, col, row, pos; while (y < height) { x = 0; while (x < quadWidth) { start = quadWidth * y + x; p = start; col = -1; row = 0; for (pos = 0; pos < 64; pos++) { row = pos >> 3;// /8 col = ( pos & 7 ) * 4; // %8 p = start + ( row * quadWidth ) + col; if (y + row >= height) { // padding bottom p -= (quadWidth * (y + 1 + row - height)); } if (x + col >= quadWidth) { // padding right p -= ((x + col) - quadWidth + 4) } r = imageData[p++]; g = imageData[p++]; b = imageData[p++]; /* // calculate YUV values dynamically YDU[pos]=((( 0.29900)*r+( 0.58700)*g+( 0.11400)*b))-128; //-0x80 UDU[pos]=(((-0.16874)*r+(-0.33126)*g+( 0.50000)*b)); VDU[pos]=((( 0.50000)*r+(-0.41869)*g+(-0.08131)*b)); */ // use lookup table (slightly faster) YDU[pos] = ((RGB_YUV_TABLE[r] + RGB_YUV_TABLE[(g + 256) >> 0] + RGB_YUV_TABLE[(b + 512) >> 0]) >> 16) - 128; UDU[pos] = ((RGB_YUV_TABLE[(r + 768) >> 0] + RGB_YUV_TABLE[(g + 1024) >> 0] + RGB_YUV_TABLE[(b + 1280) >> 0]) >> 16) - 128; VDU[pos] = ((RGB_YUV_TABLE[(r + 1280) >> 0] + RGB_YUV_TABLE[(g + 1536) >> 0] + RGB_YUV_TABLE[(b + 1792) >> 0]) >> 16) - 128; } DCY = processDU(YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT); DCU = processDU(UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT); DCV = processDU(VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT); x += 32; } y += 8; } //////////////////////////////////////////////////////////////// // Do the bit alignment of the EOI marker if (bytepos >= 0) { var fillbits = []; fillbits[1] = bytepos + 1; fillbits[0] = (1 << (bytepos + 1)) - 1; writeBits(fillbits); } writeWord(0xFFD9); //EOI var jpegDataUri = 'data:image/jpeg;base64,' + btoa(byteout.join('')); byteout = []; // benchmarking // var duration = new Date().getTime() - time_start; // console.log('Encoding time: '+ currentQuality + 'ms'); // return jpegDataUri } function setQuality(quality) { if (quality <= 0) { quality = 1; } if (quality > 100) { quality = 100; } if (currentQuality == quality) return // don't recalc if unchanged var sf = 0; if (quality < 50) { sf = Math.floor(5000 / quality); } else { sf = Math.floor(200 - quality * 2); } initQuantTables(sf); currentQuality = quality; // console.log('Quality set to: '+quality +'%'); } function init() { // var time_start = new Date().getTime(); if (!quality) quality = 50; // Create tables initCharLookupTable() initHuffmanTbl(); initCategoryNumber(); initRGBYUVTable(); setQuality(quality); // var duration = new Date().getTime() - time_start; // console.log('Initialization '+ duration + 'ms'); } init(); }; JPEGEncoder.encode = function (data, quality) { var encoder = new JPEGEncoder(quality); return encoder.encode(data); } return JPEGEncoder; }); /** * @fileOverview Fix android canvas.toDataUrl bug. */ define('runtime/html5/androidpatch', [ 'runtime/html5/util', 'runtime/html5/jpegencoder', 'base' ], function (Util, encoder, Base) { var origin = Util.canvasToDataUrl, supportJpeg; Util.canvasToDataUrl = function (canvas, type, quality) { var ctx, w, h, fragement, parts; // 非android手机直接跳过。 if (!Base.os.android) { return origin.apply(null, arguments); } // 检测是否canvas支持jpeg导出,根据数据格式来判断。 // JPEG 前两位分别是:255, 216 if (type === 'image/jpeg' && typeof supportJpeg === 'undefined') { fragement = origin.apply(null, arguments); parts = fragement.split(','); if (~parts[0].indexOf('base64')) { fragement = atob(parts[1]); } else { fragement = decodeURIComponent(parts[1]); } fragement = fragement.substring(0, 2); supportJpeg = fragement.charCodeAt(0) === 255 && fragement.charCodeAt(1) === 216; } // 只有在android环境下才修复 if (type === 'image/jpeg' && !supportJpeg) { w = canvas.width; h = canvas.height; ctx = canvas.getContext('2d'); return encoder.encode(ctx.getImageData(0, 0, w, h), quality); } return origin.apply(null, arguments); }; }); /** * @fileOverview Transport * @todo 支持chunked传输,优势: * 可以将大文件分成小块,挨个传输,可以提高大文件成功率,当失败的时候,也只需要重传那小部分, * 而不需要重头再传一次。另外断点续传也需要用chunked方式。 */ define('runtime/html5/transport', [ 'base', 'runtime/html5/runtime' ], function (Base, Html5Runtime) { var noop = Base.noop, $ = Base.$; return Html5Runtime.register('Transport', { init: function () { this._status = 0; this._response = null; }, send: function () { var owner = this.owner, opts = this.options, xhr = this._initAjax(), blob = owner._blob, server = opts.server, formData, binary, fr; if (opts.sendAsBinary) { server += (/\?/.test(server) ? '&' : '?') + $.param(owner._formData); binary = blob.getSource(); } else { formData = new FormData(); $.each(owner._formData, function (k, v) { formData.append(k, v); }); formData.append(opts.fileVal, blob.getSource(), opts.filename || owner._formData.name || ''); } if (opts.withCredentials && 'withCredentials' in xhr) { xhr.open(opts.method, server, true); xhr.withCredentials = true; } else { xhr.open(opts.method, server); } this._setRequestHeader(xhr, opts.headers); if (binary) { // 强制设置成 content-type 为文件流。 xhr.overrideMimeType && xhr.overrideMimeType('application/octet-stream'); // android直接发送blob会导致服务端接收到的是空文件。 // bug详情。 // https://code.google.com/p/android/issues/detail?id=39882 // 所以先用fileReader读取出来再通过arraybuffer的方式发送。 if (Base.os.android) { fr = new FileReader(); fr.onload = function () { xhr.send(this.result); fr = fr.onload = null; }; fr.readAsArrayBuffer(binary); } else { xhr.send(binary); } } else { xhr.send(formData); } }, getResponse: function () { return this._response; }, getResponseAsJson: function () { return this._parseJson(this._response); }, getStatus: function () { return this._status; }, abort: function () { var xhr = this._xhr; if (xhr) { xhr.upload.onprogress = noop; xhr.onreadystatechange = noop; xhr.abort(); this._xhr = xhr = null; } }, destroy: function () { this.abort(); }, _initAjax: function () { var me = this, xhr = new XMLHttpRequest(), opts = this.options; if (opts.withCredentials && !('withCredentials' in xhr) && typeof XDomainRequest !== 'undefined') { xhr = new XDomainRequest(); } xhr.upload.onprogress = function (e) { var percentage = 0; if (e.lengthComputable) { percentage = e.loaded / e.total; } return me.trigger('progress', percentage); }; xhr.onreadystatechange = function () { if (xhr.readyState !== 4) { return; } xhr.upload.onprogress = noop; xhr.onreadystatechange = noop; me._xhr = null; me._status = xhr.status; if (xhr.status >= 200 && xhr.status < 300) { me._response = xhr.responseText; return me.trigger('load'); } else if (xhr.status >= 500 && xhr.status < 600) { me._response = xhr.responseText; return me.trigger('error', 'server'); } return me.trigger('error', me._status ? 'http' : 'abort'); }; me._xhr = xhr; return xhr; }, _setRequestHeader: function (xhr, headers) { $.each(headers, function (key, val) { xhr.setRequestHeader(key, val); }); }, _parseJson: function (str) { var json; try { json = JSON.parse(str); } catch (ex) { json = {}; } return json; } }); }); define('webuploader', [ 'base', 'widgets/filepicker', 'widgets/image', 'widgets/queue', 'widgets/runtime', 'widgets/upload', 'widgets/log', 'runtime/html5/blob', 'runtime/html5/filepicker', 'runtime/html5/imagemeta/exif', 'runtime/html5/image', 'runtime/html5/androidpatch', 'runtime/html5/transport' ], function (Base) { return Base; }); return require('webuploader'); });
asofdate/batch-scheduler
bootstrap/src/main/resources/static/webuploader/webuploader.custom.js
JavaScript
mit
222,959
// https://www.creare.co.uk/blog/js/js-eu-cookie-law-banner // Creare's 'Implied Consent' EU Cookie Law Banner v:2.4 // Conceived by Robert Kent, James Bavington & Tom Foyster var cookieDuration = 365; // Number of days before the cookie expires, and the banner reappears var cookieName = 'EuCookieLawCompliance'; // Name of our cookie var cookieValue = 'on'; // Value of cookie function createBanner() { var bodytag = document.getElementsByTagName('body')[0]; var div = document.createElement('div'); div.setAttribute('id', 'cookie-law-banner'); div.innerHTML = '<i class="icon-info-circle distanced"></i>This website uses cookies. We do not use cookies for evil. By continuing we assume your permission to deploy cookies. <button type="button" onclick="createCookie();">Alright</button>'; bodytag.appendChild(div); // Adds the Cookie Law Banner just before the closing </body> tag // or // bodytag.insertBefore(div, bodytag.firstChild); // Adds the Cookie Law Banner just after the opening <body> tag // document.getElementsByTagName('body')[0].className += ' cookiebanner'; //Adds a class tothe <body> tag when the banner is visible } function createCookie() { var expires; if (window.cookieDuration) { var date = new Date(); date.setTime(date.getTime() + (window.cookieDuration * 24 * 60 * 60 * 1000)); expires = '; expires=' + date.toGMTString(); } else { expires = ''; } document.cookie = window.cookieName + '=' + window.cookieValue + expires + '; path=/'; var element = document.getElementById('cookie-law-banner'); element.parentNode.removeChild(element); } function checkCookie(name) { var nameEQ = name + '='; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') c = c.substring(1, c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length); } return null; } function eraseCookie(name) { createCookie(name, '', -1); } window.onload = function () { if (checkCookie(window.cookieName) != window.cookieValue) { createBanner(); } };
davidtimovski/my-routine
MyRoutine.Web/JS/cookie-consent.js
JavaScript
mit
2,253
import { OcticonSymbol } from '../octicons' import { Repository } from '../../models/repository' import { CloningRepository } from '../../models/cloning-repository' /** * Determine the octicon to display for a given repository. */ export function iconForRepository(repository: Repository | CloningRepository) { if (repository instanceof CloningRepository) { return OcticonSymbol.desktopDownload } const gitHubRepo = repository.gitHubRepository if (!gitHubRepo) { return OcticonSymbol.deviceDesktop } if (gitHubRepo.private) { return OcticonSymbol.lock } if (gitHubRepo.fork) { return OcticonSymbol.repoForked } return OcticonSymbol.repo }
gengjiawen/desktop
app/src/ui/octicons/repository.ts
TypeScript
mit
681
<h1 dir="rtl">مشارکت در رنگ‌برند</h1> <p dir="rtl">دوست دارید در بهبود رنگ‌برند، همکاری کنید؟ شما به روش‌های زیر می‌تونید به این پروژه کمک کنید:</p> <h2 dir="rtl">درخواست اضافه کردن برند</h2> <p dir="rtl"> رنگ‌برند یه پروژه جمعی هست و یک سری از استاندارد‌ها برای اون تعریف شده که باید رعایت بشن. لطفا قبل از این که درخواست یک برند جدید رو بدین، مسائل زیر رو چک کنید:<p> <h3 dir="rtl">سرشناس بودن</h3> <p dir="rtl">هدف رنگ‌برند لیست کردن <em>برندهای مطرح در ایران</em> هست. بنابراین، هر برندی در این لیست جا نداره. لطفا قبل از این که درخواستی مبتنی بر اضافه شدن برندی رو ثبت کنید، از <b>مطرح بودن</b> اون برند <b>در ایران</b> اطمینان پیدا کنید. در واقع سرشناسی برند، اهمیت زیادی داره.</p> <p dir="rtl"> به قول ویکیپدیا: <br> <q>اگر داشتن کد رنگی در رنگ‌برند، باعث اعتبار پیدا کردن بیشتر برند کربلایی اکبرخان مجاهد می‌شود، برند مزبور سرشناسی ندارد!</q></p> <h3 dir="rtl">درخواست مرتب و منظم</h3> <p dir="rtl">ما قراره کلی issue رو بررسی کنیم. به همین خاطر و برای سرعت بخشیدن به کار‌ها لطفا درخواست‌ها رو مرتب ارائه بدین:</p> <p dir="rtl">۱. <b>عنوان درخواست</b> رو مثل نام کلاس‌های CSS انتخاب کنید. مثلا اگه می‌خواهید برند پشمک رو درخواست کنید، نام issue رو <b>rb-pashmak</b> بذارید. <br> ۲. در یک درخواست باید <b>فقط یک برند</b> ارئه بشه. اگه میخوایید چند برند رو درخواست بدین، لطفا اون‌ها را جداگونه مطح کنید. <br> ۳. حتما کد برند مورد نظرتون رو <b>به همراه منبعی</b> که ازش رنگ رو گرفتید، عنوان کنید. بهترین جا برای پیدا کردن رنگ رسمی، <b>لوگوی اون برند</b> هست؛ لوگو رو توی برنامه‌هایی مثل فتوشاپ باز کنید و کد رنگش رو پیدا کنید. (البته لوگوهایی که گرادینت دارن، مناسب این کار نیستن.). البته گاها شرکت‌ها خودشون کد رنگ اصلیشون رو اعلام می‌کنن. </p> <p dir="rtl"><b>مهم</b>: اگه شما نماینده‌ی یک برند هستید، با در دست داشتن مدارک شناسایی (!) این موضوع رو اعلام کنید.</p> <h2 dir="rtl">گزارش باگ</h2> <p dir="rtl">توی هر کاری ممکنه اشتباهاتی پیش بیاد. اگه متوجه شدین که کد رنگ یک برندی اشتباه هست یا کلا یک باگ توی سیستم پیدا کردید، لطفا گزارش کنید.</p> <h2 dir="rtl">حمایت کنید</h2> <p dir="rtl">این پروژه زمانی میتونه موفق باشه که بقیه اون رو بشناسن. به همین خاطر اگه به گیت‌هاب رنگ‌برند ستاره بدین، یا اونو توی تویئتر دنبال کنید و یا حتی خیلی ساده اون رو به بقیه نشون بدین، کمک خیلی بزرگی کردین.</p> <p dir="rtl">اگه هم میخوایین به صورت خاصی از این پروژه حمایت کنید، به ما ایمیل بزنید: <a href="mailto:rangebrand@ikacc.ir">RangeBrand@ikacc.ir</a></p>
IKAcc/RangeBrand
CONTRIBUTING.md
Markdown
mit
3,874
<?php namespace PorkChopSandwiches\Doctrine\Utilities; /** * An interface guaranteeing to provide a method that can be used as a comparison between two objects to see if they represent the same data. * * Used (for example) to compare to objects that may represent the same Database entity. */ interface IdentifiableInterface { /** * Should return a globally unique identifier of the object, for example the database table and unique ID of a DB entity. * * @return mixed */ public function getIdentifier (); }
porkchopsandwiches/doctrine-utilities
lib/src/PorkChopSandwiches/Doctrine/Utilities/IdentifiableInterface.php
PHP
mit
526
// Package maths provides basic operations with floats and vectors package maths
DexterLB/traytor
maths/doc.go
GO
mit
81
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::DevTestLabs::Mgmt::V2016_05_15 module Models # # Properties of an artifact source. # class ArtifactSource < Resource include MsRestAzure # @return [String] The artifact source's display name. attr_accessor :display_name # @return [String] The artifact source's URI. attr_accessor :uri # @return [SourceControlType] The artifact source's type. Possible values # include: 'VsoGit', 'GitHub' attr_accessor :source_type # @return [String] The folder containing artifacts. attr_accessor :folder_path # @return [String] The folder containing Azure Resource Manager # templates. attr_accessor :arm_template_folder_path # @return [String] The artifact source's branch reference. attr_accessor :branch_ref # @return [String] The security token to authenticate to the artifact # source. attr_accessor :security_token # @return [EnableStatus] Indicates if the artifact source is enabled # (values: Enabled, Disabled). Possible values include: 'Enabled', # 'Disabled' attr_accessor :status # @return [DateTime] The artifact source's creation date. attr_accessor :created_date # @return [String] The provisioning status of the resource. attr_accessor :provisioning_state # @return [String] The unique immutable identifier of a resource (Guid). attr_accessor :unique_identifier # # Mapper for ArtifactSource class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'ArtifactSource', type: { name: 'Composite', class_name: 'ArtifactSource', model_properties: { id: { client_side_validation: true, required: false, read_only: true, serialized_name: 'id', type: { name: 'String' } }, name: { client_side_validation: true, required: false, read_only: true, serialized_name: 'name', type: { name: 'String' } }, type: { client_side_validation: true, required: false, read_only: true, serialized_name: 'type', type: { name: 'String' } }, location: { client_side_validation: true, required: false, serialized_name: 'location', type: { name: 'String' } }, tags: { client_side_validation: true, required: false, serialized_name: 'tags', type: { name: 'Dictionary', value: { client_side_validation: true, required: false, serialized_name: 'StringElementType', type: { name: 'String' } } } }, display_name: { client_side_validation: true, required: false, serialized_name: 'properties.displayName', type: { name: 'String' } }, uri: { client_side_validation: true, required: false, serialized_name: 'properties.uri', type: { name: 'String' } }, source_type: { client_side_validation: true, required: false, serialized_name: 'properties.sourceType', type: { name: 'String' } }, folder_path: { client_side_validation: true, required: false, serialized_name: 'properties.folderPath', type: { name: 'String' } }, arm_template_folder_path: { client_side_validation: true, required: false, serialized_name: 'properties.armTemplateFolderPath', type: { name: 'String' } }, branch_ref: { client_side_validation: true, required: false, serialized_name: 'properties.branchRef', type: { name: 'String' } }, security_token: { client_side_validation: true, required: false, serialized_name: 'properties.securityToken', type: { name: 'String' } }, status: { client_side_validation: true, required: false, serialized_name: 'properties.status', type: { name: 'String' } }, created_date: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.createdDate', type: { name: 'DateTime' } }, provisioning_state: { client_side_validation: true, required: false, serialized_name: 'properties.provisioningState', type: { name: 'String' } }, unique_identifier: { client_side_validation: true, required: false, serialized_name: 'properties.uniqueIdentifier', type: { name: 'String' } } } } } end end end end
Azure/azure-sdk-for-ruby
management/azure_mgmt_devtestlabs/lib/2016-05-15/generated/azure_mgmt_devtestlabs/models/artifact_source.rb
Ruby
mit
6,581
\documentclass[a0,portrait]{a0poster} \renewcommand\refname{} \usepackage{multicol} \usepackage{subfloat} \columnsep=100pt \columnseprule=3pt \let\chapter\section \let\section\subsection \let\subsection\subsubsection \let\subsubsection\paragraph \usepackage[svgnames]{xcolor} \usepackage{tcolorbox} \usepackage{graphicx} \usepackage[font=large,labelfont=bf]{caption} \usepackage{url} \begin{document} % Logo Its \begin{minipage}[b]{0.25\linewidth} \includegraphics[width=\linewidth]{logo-its} \end{minipage} \begin{minipage}[b]{0.75\linewidth} % Judul \veryHuge \color{NavyBlue} \textbf{Metode Pengaliran Data Audio melalui Sistem Penyeimbang Muat berbasis HAProxy} \\ \huge \color{black} \textbf{Putu Wiramaswara Widya \& Bahrul Halimi} \\ \Huge Jurusan Teknik Informatika \\ Institut Teknologi Sepuluh Nopember \end{minipage} \hline \begin{multicols}{2} \LARGE \begin{tcolorbox}[colback=blue!5!white,colframe=blue!75!black,title=Pendahuluan] Radio Internet adalah salah satu aplikasi Internet yang semakin banyak digunakan. Berbeda dengan radio konvensional yang mengirimkan suara dalam bentuk gelombang radio analog, radio Internet dikirimkan secara digital ke setiap penerima satu per satu menggunakan jaringan Internet berbasis TCP/IP. Dengan kata lain, semakin banyak suatu radio Internet maka semakin padat juga penggunaan jaringan dan beban server yang menyokongknya. Dalam penelitian ini, dilakukan proses implementasi server radio Internet menggunakan teknik pembagi muat (\textbf{load balancer}) berbasis HAProxy. Perangkat lunak server radio Internet yang digunakan adalah IceCast yang berlisensi terbuka. \end{tcolorbox} \begin{tcolorbox}[colback=blue!5!white,colframe=red!75!black,title=Pengujian] Hasil pengujian dengan metode pengujian disamping menghasilkan data beragam. Di bawah ini data yang dihasilkan dari pengujian server yang diakses tanpa melalui load balancer. \ \\ \begin{center} \begin{tabular}{|c|c|c|} \hline \textbf{Pengakses} & \textbf{Terpenuhi} & \textbf{Gagal} \\ \hline 90 & 90 & 0 \\ \hline 150 & 150 & 0 \\ \hline 300 & 300 & 0 \\ \hline 450 & 346 & 104 \\ \hline 600 & 243 & 357 \\ \hline \end{tabular} \end{center} \ \\ Sementara itu, berikut data yang dihasilkan dari pengujian akses melalui load balancer. \ \\ % Diakses melalui HAProxy \begin{center} \begin{tabular}{|c|c|c|} \hline \textbf{Pengakses} & \textbf{Terpenuhi} & \textbf{Gagal} \\ \hline 90 & 90 & 0 \\ \hline 150 & 150 & 0 \\ \hline 300 & 300 & 0 \\ \hline 450 & 434 & 16 \\ \hline 600 & 485 & 115 \\ \hline \end{tabular} \end{center} \ \\ \textbf{\underline{Analisis}.} Pengujian dengan klien berjumlah 90, 150, dan 300 memiliki tingkat keberhasilan 100\% dan tingkat kegagalan 0\%. Angka ini berubah ketika jumlah pengakses ditingkatkan. Pada saat klien berjumlah 450, tingkat keberhasilan 76,8\% dan tingkat kegagalan 23.2\% untuk akses tanpa load balancer. Sementara itu untuk akses melalui load balancer memberikan tingkat keberhasilan 96,4\% dan tingkat kegagalan 3,6\% dengan jumlah pengakses yang sama. Perbadaan keberhasilan dan kegagalan ini juga terjadi ketika terdapat 600 pengakses dalam waktu yang hampir bersamaan. \end{tcolorbox} \begin{tcolorbox}[colback=blue!5!white,colframe=green!75!black,title=Metode] \textbf{\underline{Permasalahan}.} Bagaimana menyeimbangkan muatan kerja server yang menyiarkan audio ke pendengar ketika ada banyak permintaan secara bersamaan? Bagaimana menyediakan banyak server untuk melayani permintaan pendengar dengan satu sumber aliran dari pengirim? \begin{center} \includegraphics[width=0.7\linewidth]{arsitektur} \end{center} \textbf{\underline{Arsitektur Jaringan}.} Terdapat tiga server radio Internet yang nantinya akan digunakan dengan metode penyeimbang muat, satu server utama di bagian \textbf{Frontend\textit{}}, dan satu server utama di bagian \textbf{Backend\textit{}}. Server utama di bagian Frontend berhadapan dengan pendengar, sedangkan server utama di bagian Backend berhadapan dengan pengirim. \ \\ \textbf{\underline{Pengujian}.} Dua mekanisme disiapkan yaitu akses melalui load balancer dan akses tanpa load balancer. Perhitungan dilakukan dengan melakukan uji \texttt{stress test} pada load balancer atau langsung ke server radio Internet. Akses dilakukan melalui tiga komputer penguji beban dengan jumlah klien yang disimulasikan adalah 90,150,300,450, dan 600. \end{tcolorbox} \begin{tcolorbox}[colback=blue!5!white,colframe=blue!75!black,title=Referensi,fontupper=\normalsize] \begin{thebibliography}{9} \bibitem{setupice} Xiph.Org \textbf{Icecast 2.4.1 Docs — Basic Setup},[Online], \url{http://icecast.org/docs/icecast-2.4.1/basic-setup.html}, diakses tanggal 23 Desember 2014 \bibitem{ice} Xiph.Org \textbf{Icecast is free server software for streaming multimedia},[Online], \url{http://icecast.org/}, diakses tanggal 1 September 2014 \bibitem{halebih} Mark Imbriaco \textbf{Nuts \& Bolts: HAproxy},[Online], \url{https://signalvnoise.com/posts/1073-nuts-bolts-haproxy}, diakses tanggal 1 September 2014 \bibitem{haproxy} HAProxy \textbf{Description},[Online], \url{http://www.haproxy.org/#desc}, diakses tanggal 1 September 2014 \bibitem{hause} HAProxy \textbf{They use it !},[Online], \url{http://www.haproxy.org/they-use-it.html}, diakses 1 September 2014 \bibitem{nodejs} Joyent, Inc \textbf{Node.js v0.10.35 Manual \& Documentation},[Online], \url{http://nodejs.org/api/stream.html}, diakses tanggal 23 Desember 2014 \bibitem{nodejsieee} Stefan Tilkov, Steve Vinoski, \textbf{Node.js: Using JavaScript to Build High-Perfomace Network Programs}, IEEE Computer Society Issue 06, Nov-Dec 2010, pp 80-83, 2010 \end{thebibliography} \end{tcolorbox} \end{multicols} \LARGE \begin{tcolorbox}[colback=blue!5!white,colframe=red!75!white,title= ] \includegraphics[width=0.25\linewidth]{logo-haproxy} \hfill \includegraphics[width=0.25\linewidth]{logo-nodejs} \hfill \includegraphics[width=0.25\linewidth]{logo-icecast} \end{tcolorbox} \end{document}
initrunlevel0/icecastMiddleware
laporan/poster.tex
TeX
mit
6,123
### バリデーション モデルにバリデーションを定義
mshige1979/cakephp3-sample
03_validation/README.md
Markdown
mit
71
<?php namespace Fisharebest\Localization\Territory; /** * Class AbstractTerritory - Representation of the territory MR - Mauritania. * * @author Greg Roach <fisharebest@gmail.com> * @copyright (c) 2015 Greg Roach * @license GPLv3+ */ class TerritoryMr extends AbstractTerritory implements TerritoryInterface { public function code() { return 'MR'; } }
fweber1/Annies-Ancestors
webtrees/vendor/fisharebest/localization/src/Territory/TerritoryMr.php
PHP
mit
368
// The MIT License(MIT) // // Copyright(c) 2015 Andreas Sjöberg // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files(the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and / or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions : // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #ifndef PLAYER_CONTROLLER_HPP_INCLUDED #define PLAYER_CONTROLLER_HPP_INCLUDED #include <SFML/Graphics.hpp> #include "System.hpp" namespace ai2 { /////////////////////////////////////////////////////////////////////////// /// /////////////////////////////////////////////////////////////////////////// class PlayerController : public System { public: /////////////////////////////////////////////////////////////////////// /// /////////////////////////////////////////////////////////////////////// PlayerController(); /////////////////////////////////////////////////////////////////////// /// /////////////////////////////////////////////////////////////////////// virtual ~PlayerController(); /////////////////////////////////////////////////////////////////////// /// /////////////////////////////////////////////////////////////////////// virtual void initialize(); /////////////////////////////////////////////////////////////////////// /// /////////////////////////////////////////////////////////////////////// virtual void update(float updateTime, Entity& entity, EntityManager& entities); }; } #endif // PLAYER_CONTROLLER_HPP_INCLUDED
addelajnen/AddeInvaders-II
PlayerController.hpp
C++
mit
2,337
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>idxassoc: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.8.1 / idxassoc - 8.6.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> idxassoc <small> 8.6.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-02-10 07:56:43 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-02-10 07:56:43 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 2 Virtual package relying on perl coq 8.8.1 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.07.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.07.1 Official release 4.07.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.3 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/idxassoc&quot; license: &quot;BSD with advertising clause&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/IdxAssoc&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.6&quot; &amp; &lt; &quot;8.7~&quot;} ] tags: [ &quot;keyword: associative arrays&quot; &quot;keyword: search operator&quot; &quot;keyword: data structures&quot; &quot;category: Computer Science/Data Types and Data Structures&quot; &quot;date: April 2001&quot; ] authors: [ &quot;Dominique Quatravaux&quot; &quot;François-René Ridaux&quot; &quot;Gérald Macinenti&quot; ] bug-reports: &quot;https://github.com/coq-contribs/idxassoc/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/idxassoc.git&quot; synopsis: &quot;Associative Arrays&quot; description: &quot;&quot;&quot; We define the associative array (key -&gt; value associations) datatype as list of couples, providing definitions of standards operations such as adding, deleting. We introduce predicates for membership of a key and of couples. Finally we define a search operator (&quot;find&quot;) which returns the value associated with a key or the &quot;none&quot; option (see file Option.v which should be part of this contribution) on failure. Lemmas we prove about these concepts were motivated by our needs at the moment we created this file. We hope they&#39;ll suit your needs too but anyway, feel free to communicate any wish or remark.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/idxassoc/archive/v8.6.0.tar.gz&quot; checksum: &quot;md5=41b1f85ac6eba8353a9c645b5d2d0966&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-idxassoc.8.6.0 coq.8.8.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.8.1). The following dependencies couldn&#39;t be met: - coq-idxassoc -&gt; coq &lt; 8.7~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-idxassoc.8.6.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.07.1-2.0.6/released/8.8.1/idxassoc/8.6.0.html
HTML
mit
7,511
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>elpi: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.14.0 / elpi - 1.9.2</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> elpi <small> 1.9.2 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2021-12-01 03:43:22 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2021-12-01 03:43:22 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 3 Virtual package relying on a GMP lib system installation coq 8.14.0 Formal proof management system dune 2.9.1 Fast, portable, and opinionated build system ocaml 4.05.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.05.0 Official 4.05.0 release ocaml-config 1 OCaml Switch Configuration ocaml-secondary-compiler 4.08.1-1 OCaml 4.08.1 Secondary Switch Compiler ocamlfind 1.9.1 A library manager for OCaml ocamlfind-secondary 1.9.1 Adds support for ocaml-secondary-compiler to ocamlfind zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Enrico Tassi &lt;enrico.tassi@inria.fr&gt;&quot; authors: [ &quot;Enrico Tassi&quot; ] license: &quot;LGPL-2.1-or-later&quot; homepage: &quot;https://github.com/LPCIC/coq-elpi&quot; bug-reports: &quot;https://github.com/LPCIC/coq-elpi/issues&quot; dev-repo: &quot;git+https://github.com/LPCIC/coq-elpi&quot; build: [ [ make &quot;build&quot; &quot;COQBIN=%{bin}%/&quot; &quot;ELPIDIR=%{prefix}%/lib/elpi&quot; ] [ make &quot;test&quot; &quot;COQBIN=%{bin}%/&quot; &quot;ELPIDIR=%{prefix}%/lib/elpi&quot; ] {with-test} ] install: [ make &quot;install&quot; &quot;COQBIN=%{bin}%/&quot; &quot;ELPIDIR=%{prefix}%/lib/elpi&quot; ] depends: [ &quot;elpi&quot; {= &quot;1.13.0&quot;} &quot;coq&quot; {&gt;= &quot;8.13&quot; &amp; &lt; &quot;8.14~&quot; } &quot;ocaml&quot; {&lt; &quot;4.12~&quot;} ] tags: [ &quot;logpath:elpi&quot; ] synopsis: &quot;Elpi extension language for Coq&quot; description: &quot;&quot;&quot; Coq-elpi provides a Coq plugin that embeds ELPI. It also provides a way to embed Coq&#39;s terms into λProlog using the Higher-Order Abstract Syntax approach and a way to read terms back. In addition to that it exports to ELPI a set of Coq&#39;s primitives, e.g. printing a message, accessing the environment of theorems and data types, defining a new constant and so on. For convenience it also provides a quotation and anti-quotation for Coq&#39;s syntax in λProlog. E.g. `{{nat}}` is expanded to the type name of natural numbers, or `{{A -&gt; B}}` to the representation of a product by unfolding the `-&gt;` notation. Finally it provides a way to define new vernacular commands and new tactics.&quot;&quot;&quot; url { src: &quot;https://github.com/LPCIC/coq-elpi/archive/v1.9.2.tar.gz&quot; checksum: &quot;sha256=b88d997410e9ee8a71d924931249d8e9769d6851bd5e9eee55d56fb2122aebe3&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-elpi.1.9.2 coq.8.14.0</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.14.0). The following dependencies couldn&#39;t be met: - coq-elpi -&gt; coq &lt; 8.14~ -&gt; ocaml &lt; 4.03.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-elpi.1.9.2</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.05.0-2.0.1/released/8.14.0/elpi/1.9.2.html
HTML
mit
7,914
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>presburger: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.5.2 / presburger - 8.9.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> presburger <small> 8.9.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-01-22 05:26:13 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-01-22 05:26:13 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 1 Virtual package relying on perl coq 8.5.2 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.03.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.03.0 Official 4.03.0 release ocaml-config 1 OCaml Switch Configuration # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/presburger&quot; license: &quot;LGPL 2.1&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Presburger&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.9&quot; &amp; &lt; &quot;8.10~&quot;} ] tags: [ &quot;keyword: integers&quot; &quot;keyword: arithmetic&quot; &quot;keyword: decision procedure&quot; &quot;keyword: Presburger&quot; &quot;category: Mathematics/Logic/Foundations&quot; &quot;category: Mathematics/Arithmetic and Number Theory/Miscellaneous&quot; &quot;category: Computer Science/Decision Procedures and Certified Algorithms/Decision procedures&quot; &quot;date: March 2002&quot; ] authors: [ &quot;Laurent Théry&quot; ] bug-reports: &quot;https://github.com/coq-contribs/presburger/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/presburger.git&quot; synopsis: &quot;Presburger&#39;s algorithm&quot; description: &quot;&quot;&quot; A formalization of Presburger&#39;s algorithm as stated in the initial paper by Presburger.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/presburger/archive/v8.9.0.tar.gz&quot; checksum: &quot;md5=f3c4e9c316149a8bc03bde86b6c4a2bf&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-presburger.8.9.0 coq.8.5.2</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.5.2). The following dependencies couldn&#39;t be met: - coq-presburger -&gt; coq &gt;= 8.9 -&gt; ocaml &gt;= 4.05.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-presburger.8.9.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.03.0-2.0.5/released/8.5.2/presburger/8.9.0.html
HTML
mit
7,222
require 'wiringpi2' module Pi class SegmentDisplay class << self SEGMENTS = { A: 8, B: 12, C: 2, D: 0, E: 7, F: 9, G: 3, DP: 13 }.freeze def display(number) digit = number.to_i % 10 map = MAPS[digit] display_map(map) end def decimal_place(on: true) value = on ? WiringPi::LOW : WiringPi::HIGH gpio.digital_write(SEGMENTS[:DP], value) end private def display_map(map) map.each do |segment, value| pin = SEGMENTS[segment] gpio.digital_write(pin, value) end end def gpio @gpio ||= WiringPi::GPIO.new do |gpio| SEGMENTS.values.each do |pin| gpio.pin_mode(pin, WiringPi::OUTPUT) end end end MAPS = { 0 => { A: WiringPi::LOW, B: WiringPi::LOW, C: WiringPi::LOW, D: WiringPi::LOW, E: WiringPi::LOW, F: WiringPi::LOW, G: WiringPi::HIGH }, 1 => { A: WiringPi::HIGH, B: WiringPi::LOW, C: WiringPi::LOW, D: WiringPi::HIGH, E: WiringPi::HIGH, F: WiringPi::HIGH, G: WiringPi::HIGH }, 2 => { A: WiringPi::LOW, B: WiringPi::LOW, C: WiringPi::HIGH, D: WiringPi::LOW, E: WiringPi::LOW, F: WiringPi::HIGH, G: WiringPi::LOW }, 3 => { A: WiringPi::LOW, B: WiringPi::LOW, C: WiringPi::LOW, D: WiringPi::LOW, E: WiringPi::HIGH, F: WiringPi::HIGH, G: WiringPi::LOW }, 4 => { A: WiringPi::HIGH, B: WiringPi::LOW, C: WiringPi::LOW, D: WiringPi::HIGH, E: WiringPi::HIGH, F: WiringPi::LOW, G: WiringPi::LOW }, 5 => { A: WiringPi::LOW, B: WiringPi::HIGH, C: WiringPi::LOW, D: WiringPi::LOW, E: WiringPi::HIGH, F: WiringPi::LOW, G: WiringPi::LOW }, 6 => { A: WiringPi::LOW, B: WiringPi::LOW, C: WiringPi::LOW, D: WiringPi::LOW, E: WiringPi::LOW, F: WiringPi::LOW, G: WiringPi::LOW }, 7 => { A: WiringPi::HIGH, B: WiringPi::HIGH, C: WiringPi::LOW, D: WiringPi::LOW, E: WiringPi::LOW, F: WiringPi::LOW, G: WiringPi::LOW }, 8 => { A: WiringPi::LOW, B: WiringPi::LOW, C: WiringPi::LOW, D: WiringPi::LOW, E: WiringPi::LOW, F: WiringPi::LOW, G: WiringPi::LOW }, 9 => { A: WiringPi::LOW, B: WiringPi::LOW, C: WiringPi::LOW, D: WiringPi::HIGH, E: WiringPi::HIGH, F: WiringPi::LOW, G: WiringPi::LOW } }.freeze end end end
NGMarmaduke/pi
lib/pi/segment_display.rb
Ruby
mit
3,128
# encoding: utf-8 # # Jekyll category pagination. # https://github.com/MrWerewolf/jekyll-category-pagination # # Copyright (c) 2012 Ryan Seto <mr.werewolf@gmail.com> # Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php) # # Place this script into the _plugins directory of your Jekyll site. # module Jekyll # Change the Page object so it puts the path in the url. This makes the dir # method work as intended. class Page # The template of the permalink. # # Returns the template String. def template if self.site.permalink_style == :pretty && !index? && html? "/:path/:basename/" else "/:path/:basename:output_ext" end end # The generated relative url of this page. e.g. /about.html. # # Returns the String url. def url return @url if @url url = if permalink permalink else { "path" => @dir, "basename" => self.basename, "output_ext" => self.output_ext, }.inject(template) { |result, token| result.gsub(/:#{token.first}/, token.last) }.gsub(/\/\//, "/") end # sanitize url @url = url.split('/').reject{ |part| part =~ /^\.+$/ }.join('/') @url += "/" if url =~ /\/$/ @url end # Convert this Page's data to a Hash suitable for use by Liquid. # # Returns the Hash representation of this Page. def to_liquid self.data.deep_merge({ "url" => self.url, "content" => self.content }) end # Obtain destination path. # # dest - The String path to the destination dir. # # Returns the destination file path String. def destination(dest) # The url needs to be unescaped in order to preserve the correct # filename. path = File.join(dest, CGI.unescape(self.url)) path = File.join(path, "index.html") if self.url =~ /\/$/ path end end class Pagination < Generator # This generator is safe from arbitrary code execution. safe true # Paginates the blog's posts. Renders the index.html file into paginated # directories, e.g.: page2/index.html, page3/index.html, etc and adds more # site-wide data. # # site - The Site. # page - The index.html Page that requires pagination. # # {"paginator" => { "page" => <Number>, # "per_page" => <Number>, # "posts" => [<Post>], # "total_posts" => <Number>, # "total_pages" => <Number>, # "previous_page" => <Number>, # "next_page" => <Number> }} def paginate(site, page) category = page.dir.split('/').last if category != nil and site.site_payload['site']['categories'].has_key? category # If we're in a category's folder, paginate by category. all_posts = site.site_payload['site']['categories'][category] else all_posts = site.site_payload['site']['posts'] end pages = Pager.calculate_pages(all_posts, site.config['paginate'].to_i) (1..pages).each do |num_page| pager = Pager.new(site.config, num_page, all_posts, pages) if num_page > 1 newpage = Page.new(site, site.source, page.dir, page.name) newpage.pager = pager newpage.dir = File.join(page.dir, "page#{num_page}") site.pages << newpage else page.pager = pager end end end end end
qiruiyin/qiruiyin.github.io
plugins/category_pagination.rb
Ruby
mit
3,552
using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Numerics; public class Myon { public Myon() { } public static int Main() { new Myon().calc(); return 0; } Scanner cin; int Polygon; int N; int M; Point[] pt; Point[] pt2; Num xmin; Num ymin; List<Point> bpoints; List<Point> points; Dictionary<Point, int> pdic = new Dictionary<Point, int>(); List<List<int>> polys = new List<List<int>>(); int[] rev = new int[100000]; void calc() { cin = new Scanner(); Polygon = cin.nextInt(); /* if (Polygon != 1) { Console.Error.WriteLine("giveup!(many polygons)"); return; } */ N = cin.nextInt(); pt = new Point[N]; for (int i = 0; i < N; i++) { string[] st = cin.next().Split(','); pt[i] = new Point(new Num(st[0]), new Num(st[1])); Console.Error.WriteLine(pt[i]); var nextb = 1000; var nexta = pt[i].x.a * nextb / pt[i].x.b; var nextx = new Num(nexta, nextb); nextb = 1000; nexta = pt[i].y.a * nextb / pt[i].y.b; var nexty = new Num(nexta, nextb); pt[i] = new Point(nextx, nexty); //Console.Error.WriteLine(pt[i]); } for (int i = 1; i < Polygon; i++) { int tempn = cin.nextInt(); for (int j = 0; j < tempn; j++) { cin.next(); } } int fff = (1 << 6); while (true) { List<Point> temppt = new List<Point>(); for (int i = 0; i < pt.Length; i++) { if ((fff>>i) %2 == 0) temppt.Add(pt[i]); } pt = temppt.ToArray(); N = pt.Length; break; } //pt[6].x = pt[6].x.Sub(new Num(1, 12)); while (true) { bool flag = false; List<Point> temppt = new List<Point>(); for (int i = 0; i < pt.Length; i++) { var P1 = pt[i]; var P2 = pt[(i + pt.Length - 1) % pt.Length]; var P3 = pt[(i + 1) % pt.Length]; Num nn = Point.S(P2.Sub(P1), P3.Sub(P1)); if (nn.a < 0) temppt.Add(pt[i]); else flag = true; } pt = temppt.ToArray(); N = pt.Length; if (!flag) break; } Console.Error.WriteLine("N : " + N); for (int i = 0; i < N; i++) { if (i == 0) { xmin = pt[i].x; ymin = pt[i].y; } else { if (pt[i].x.CompareTo(xmin) < 0) xmin = pt[i].x; if (pt[i].y.CompareTo(ymin) < 0) ymin = pt[i].y; } } xmin = new Num(-1, 3); ymin = new Num(0); pt2 = new Point[N]; for (int i = 0; i < N; i++) { pt2[i] = pt[i].Sub(new Point(xmin, ymin)); if (pt2[i].x.a > pt2[i].x.b) { pt2[i].x.a = pt2[i].x.b; //Console.Error.WriteLine("giveup!(big)"); //return; } if (pt2[i].y.a > pt2[i].y.b) { pt2[i].y.a = pt2[i].y.b; //Console.Error.WriteLine("giveup!(big)"); //return; } } M = cin.nextInt(); points = new List<Point>(); bpoints = new List<Point>(); points.Add(new Point(new Num(0), new Num(0))); points.Add(new Point(new Num(0), new Num(1))); points.Add(new Point(new Num(1), new Num(1))); points.Add(new Point(new Num(1), new Num(0))); List<int> firstl = new List<int>(); for (int i = 0; i < points.Count; i++) { firstl.Add(i); bpoints.Add(points[i]); pdic[points[i]] = i; } polys.Add(firstl); string ans = ""; string anstemp = ""; anstemp += (points.Count); anstemp += '\n'; foreach (var item in bpoints) { anstemp += item + "\n"; } //skelton //Console.WriteLine(polys.Count); anstemp += polys.Count + "\n"; foreach (var poly in polys) { anstemp += (poly.Count + " "); anstemp += (String.Join(" ", poly)) + "\n"; } //realPoint foreach (var item in points) { //Console.WriteLine(item.Add(new Point(xmin, ymin))); anstemp += item.Add(new Point(xmin, ymin)) + "\n"; } if (anstemp.Length < 5000) ans = anstemp; else Console.Error.WriteLine(anstemp.Length); pt2 = new Point[4]; pt2[1] = new Point(new Num(8, 9), new Num(0)); pt2[0] = new Point(new Num(0), new Num(8, 9)); pt2[2] = new Point(new Num(1), new Num(1, 9)); pt2[3] = new Point(new Num(1, 9), new Num(1)); while (true) { bool flag = false; for (int ii = 0; ii < pt2.Length; ii += 2) { //int i = (ii * 2) % N; //if (ii * 2 >= N && N % 2 == 0) i++; int i = ii; Point P1 = pt2[i]; Point P2 = pt2[(i + 1) % pt2.Length]; for (int j = 0; j < points.Count; j++) { Point P3 = points[j]; Num SS = Point.S(P3.Sub(P1), P3.Sub(P2)); rev[j] = 0; if (SS.a < 0) rev[j] = 1; //Console.Error.WriteLine("S " + SS); } List<List<int>> nextpoly = new List<List<int>>(); foreach (var poly in polys) { List<int> normallist = new List<int>(); List<int> revlist = new List<int>(); int pre = poly[poly.Count - 1]; int prerev = rev[pre]; foreach (var j in poly) { if (prerev != rev[j]) { int nextp = getp(pre, j, P1, P2); normallist.Add(nextp); revlist.Add(nextp); } if (rev[j] == 0) normallist.Add(j); else revlist.Add(j); pre = j; prerev = rev[j]; } revlist.Reverse(0, revlist.Count); normallist = doublecheck(normallist); revlist = doublecheck(revlist); if (normallist.Count >= 3) nextpoly.Add(normallist); if (revlist.Count >= 3) { flag = true; nextpoly.Add(revlist); } } polys = nextpoly; int revcnt = 0; Point diff = P2.Sub(P1); Num[,] rot = Point.reflect(diff); for (int j = 0; j < points.Count; j++) { if (rev[j] == 1) { revcnt++; points[j] = Point.apply(rot, points[j].Sub(P1)).Add(P1); } } Console.Error.WriteLine("revcount : " + i + " " + revcnt); anstemp = ""; anstemp += (points.Count); anstemp += '\n'; foreach (var item in bpoints) { anstemp += item + "\n"; } //skelton //Console.WriteLine(polys.Count); anstemp += polys.Count + "\n"; foreach (var poly in polys) { anstemp += (poly.Count + " "); anstemp += (String.Join(" ", poly)) + "\n"; } //realPoint foreach (var item in points) { //Console.WriteLine(item.Add(new Point(xmin, ymin))); anstemp += item.Add(new Point(xmin, ymin)) + "\n"; } if (anstemp.Length < 5000) ans = anstemp; else Console.Error.WriteLine(anstemp.Length); /* else { anstemp = ""; anstemp += (points.Count); anstemp += '\n'; foreach (var item in bpoints) { anstemp += item + "\n"; } //skelton //Console.WriteLine(polys.Count); anstemp += polys.Count + "\n"; foreach (var poly in polys) { anstemp += (poly.Count + " "); anstemp += (String.Join(" ", poly)) + "\n"; } //realPoint var xmin2 = xmin; var ymin2 = ymin; while (xmin2.b >= 1000) { xmin2.a /= 10; xmin2.b /= 10; } while (ymin2.b >= 1000) { ymin2.a /= 10; ymin2.b /= 10; } foreach (var item in points) { //Console.WriteLine(item.Add(new Point(xmin, ymin))); anstemp += item.Add(new Point(xmin2, ymin2)) + "\n"; } if (anstemp.Length < 4900) ans = anstemp; else Console.Error.WriteLine(anstemp.Length); } */ } if (!flag) break; } pt2 = new Point[4]; pt2[0] = new Point(new Num(15, 18), new Num(1)); pt2[1] = new Point(new Num(15, 18), new Num(0)); pt2[2] = new Point(new Num(1), new Num(0)); pt2[3] = new Point(new Num(1), new Num(1)); while (true) { bool flag = false; for (int ii = 0; ii < pt2.Length; ii += 2) { //int i = (ii * 2) % N; //if (ii * 2 >= N && N % 2 == 0) i++; int i = ii; Point P1 = pt2[i]; Point P2 = pt2[(i + 1) % pt2.Length]; for (int j = 0; j < points.Count; j++) { Point P3 = points[j]; Num SS = Point.S(P3.Sub(P1), P3.Sub(P2)); rev[j] = 0; if (SS.a < 0) rev[j] = 1; //Console.Error.WriteLine("S " + SS); } List<List<int>> nextpoly = new List<List<int>>(); foreach (var poly in polys) { List<int> normallist = new List<int>(); List<int> revlist = new List<int>(); int pre = poly[poly.Count - 1]; int prerev = rev[pre]; foreach (var j in poly) { if (prerev != rev[j]) { int nextp = getp(pre, j, P1, P2); normallist.Add(nextp); revlist.Add(nextp); } if (rev[j] == 0) normallist.Add(j); else revlist.Add(j); pre = j; prerev = rev[j]; } revlist.Reverse(0, revlist.Count); normallist = doublecheck(normallist); revlist = doublecheck(revlist); if (normallist.Count >= 3) nextpoly.Add(normallist); if (revlist.Count >= 3) { flag = true; nextpoly.Add(revlist); } } polys = nextpoly; int revcnt = 0; Point diff = P2.Sub(P1); Num[,] rot = Point.reflect(diff); for (int j = 0; j < points.Count; j++) { if (rev[j] == 1) { revcnt++; points[j] = Point.apply(rot, points[j].Sub(P1)).Add(P1); } } Console.Error.WriteLine("revcount : " + i + " " + revcnt); anstemp = ""; anstemp += (points.Count); anstemp += '\n'; foreach (var item in bpoints) { anstemp += item + "\n"; } //skelton //Console.WriteLine(polys.Count); anstemp += polys.Count + "\n"; foreach (var poly in polys) { anstemp += (poly.Count + " "); anstemp += (String.Join(" ", poly)) + "\n"; } //realPoint foreach (var item in points) { //Console.WriteLine(item.Add(new Point(xmin, ymin))); anstemp += item.Add(new Point(xmin, ymin)) + "\n"; } if (anstemp.Length < 5000) ans = anstemp; else Console.Error.WriteLine(anstemp.Length); /* else { anstemp = ""; anstemp += (points.Count); anstemp += '\n'; foreach (var item in bpoints) { anstemp += item + "\n"; } //skelton //Console.WriteLine(polys.Count); anstemp += polys.Count + "\n"; foreach (var poly in polys) { anstemp += (poly.Count + " "); anstemp += (String.Join(" ", poly)) + "\n"; } //realPoint var xmin2 = xmin; var ymin2 = ymin; while (xmin2.b >= 1000) { xmin2.a /= 10; xmin2.b /= 10; } while (ymin2.b >= 1000) { ymin2.a /= 10; ymin2.b /= 10; } foreach (var item in points) { //Console.WriteLine(item.Add(new Point(xmin, ymin))); anstemp += item.Add(new Point(xmin2, ymin2)) + "\n"; } if (anstemp.Length < 4900) ans = anstemp; else Console.Error.WriteLine(anstemp.Length); } */ } if (!flag) break; } Console.Write(ans); /* //basepoint Console.WriteLine(points.Count); foreach (var item in bpoints) { Console.WriteLine(item); } //skelton Console.WriteLine(polys.Count); foreach (var poly in polys) { Console.Write(poly.Count + " "); Console.WriteLine(String.Join(" ", poly)); } //realPoint foreach (var item in points) { Console.WriteLine(item.Add(new Point(xmin, ymin))); } */ } int getp(int i, int j, Point P1, Point P2) { Num A = Point.S(points[i].Sub(P1), points[i].Sub(P2)).Abs(); Num B = Point.S(points[j].Sub(P1), points[j].Sub(P2)).Abs(); Point BP = bpoints[i].Mul(B.Div(A.Add(B))).Add(bpoints[j].Mul(A.Div(A.Add(B)))); Point P = points[i].Mul(B.Div(A.Add(B))).Add(points[j].Mul(A.Div(A.Add(B))) ); if (pdic.ContainsKey(BP)) return pdic[BP]; pdic[BP] = points.Count; bpoints.Add(BP); points.Add(P); return pdic[BP]; } List<int> doublecheck(List<int> a) { if (a.Count == 0) return a; List<int> r = new List<int>(); int pre = a[a.Count - 1]; foreach (var item in a) { if (pre != item) r.Add(item); pre = item; } return r; } static public bool isSqrtable(BigInteger a) { if (a < 0) return false; BigInteger high = a + 1; BigInteger low = 0; while (high - low > 1) { var mid = high - low; if (mid * mid <= a) low = a; else high = a; } return low * low == a; } static public BigInteger BigSqrt(BigInteger a) { BigInteger high = a + 1; BigInteger low = 0; while (high - low > 1) { var mid = high - low; if (mid * mid <= a) low = a; else high = a; } return low; } } class Point : IComparable<Point>, IEquatable<Point> { public Num x, y; public Point() { this.x = new Num(0); this.y = new Num(0); } public Point(Num x, Num y) { this.x = x; this.y = y; } public Point(string x, string y) { this.x = new Num(x); this.y = new Num(y); } public Point Add(Point t) { return new Point(x.Add(t.x), y.Add(t.y)); } public Point Sub(Point t) { return new Point(x.Sub(t.x), y.Sub(t.y)); } public Point Mul(Num d) { return new Point(x.Mul(d), y.Mul(d)); } public Point Div(Num d) { return new Point(x.Div(d), y.Div(d)); } public Num Dot(Point p) { return x.Mul(p.x).Add(y.Mul(p.y)); } public Num Det(Point p) { return x.Mul(p.y).Sub(y.Mul(p.x)); } public Num Abs2() { return x.Mul(x).Add(y.Mul(y)); } override public string ToString() { return x.ToString() + "," + y.ToString(); } public int CompareTo(Point t) { int r = x.CompareTo(t.x); if (r != 0) return r; return y.CompareTo(t.y); } public bool Equals(Point t) { return x.Equals(t.x) && y.Equals(t.y); } override public int GetHashCode() { int xCode = x.GetHashCode(); int yCode = y.GetHashCode(); int hCode = (xCode << 11) ^ (xCode >> 5) ^ (yCode); return hCode.GetHashCode(); } public bool IsEndPoint() { return x.IsEndPoint() || y.IsEndPoint(); } // aをbの方向に回転 public static Num[,] rotate(Point a, Point b) { Num ab2 = a.Abs2().Mul(b.Abs2()); if (!ab2.IsSqrtable()) return null; Num ab = ab2.Sqrt(); Num cos = a.Dot(b).Div(ab), sin = a.Det(b).Div(ab); return new Num[,] { { cos, sin.Neg() }, { sin, cos } }; } // d方向を軸に反転 public static Num[,] reflect(Point d) { Num d2 = d.Dot(d); Num cos = d.x.Mul(d.x).Sub(d.y.Mul(d.y)).Div(d2), sin = Num.TWO.Mul(d.x).Mul(d.y).Div(d2); return new Num[,] { { cos, sin }, { sin, cos.Neg() } }; } //回転を適用 public static Point[] apply(Num[,] A, Point[] ps) { Point[] qs = new Point[ps.Length]; for (int i = 0; i < ps.Length; i++) { qs[i] = new Point(A[0, 0].Mul(ps[i].x).Add(A[0, 1].Mul(ps[i].y)), A[1, 0].Mul(ps[i].x).Add(A[1, 1].Mul(ps[i].y))); } return qs; } public static Point apply(Num[,] A, Point ps) { Point qs = new Point(A[0, 0].Mul(ps.x).Add(A[0, 1].Mul(ps.y)), A[1, 0].Mul(ps.x).Add(A[1, 1].Mul(ps.y))); return qs; } //符号付面積 public static Num S(Point P1, Point P2) { return P1.x.Mul(P2.y).Sub(P1.y.Mul(P2.x)); } public bool inside() { return x.inside() && y.inside(); } } class Num : IComparable<Num>, IEquatable<Num> { public BigInteger a; //bunbo public BigInteger b; //bunsi public Num(string st) { string[] st2; st2 = st.Split('/'); a = BigInteger.Parse(st2[0]); if (st2.Length == 1) { b = 1; } else { b = BigInteger.Parse(st2[1]); } Yakubun(); } public Num(BigInteger a, BigInteger b) { this.a = a; this.b = b; Yakubun(); } public Num(BigInteger a) { this.a = a; this.b = 1; Yakubun(); } public Num Add(Num t) { BigInteger nextB = b * t.b; BigInteger nextA = a * t.b + t.a * b; var ret = new Num(nextA, nextB); ret.Yakubun(); return ret; } public Num Sub(Num t) { BigInteger nextB = b * t.b; BigInteger nextA = a * t.b - t.a * b; var ret = new Num(nextA, nextB); ret.Yakubun(); return ret; } public Num Mul(Num t) { BigInteger nextB = b * t.b; BigInteger nextA = a * t.a; var ret = new Num(nextA, nextB); ret.Yakubun(); return ret; } public Num Div(Num t) { BigInteger nextB = b * t.a; BigInteger nextA = a * t.b; var ret = new Num(nextA, nextB); ret.Yakubun(); return ret; } public Num Neg() { return new Num(-a, b); } public static Num TWO = new Num(2); public void Yakubun() { BigInteger g = BigInteger.GreatestCommonDivisor(BigInteger.Abs(a), b); a /= g; b /= g; } public int CompareTo(Num t) { return (a * t.b).CompareTo(t.a * b); } public bool IsSqrtable() { return Myon.isSqrtable(a) && Myon.isSqrtable(b); } public Num Sqrt() { return new Num(Myon.BigSqrt(a), Myon.BigSqrt(b)); } override public string ToString() { if (b != 1) return a.ToString() + "/" + b.ToString(); else return a.ToString(); } public bool Equals(Num p) { return a == p.a && b == p.b; } override public int GetHashCode() { int xCode = a.GetHashCode(); int yCode = b.GetHashCode(); int hCode = (xCode << 13) ^ (xCode >> 7) ^ (yCode); return hCode.GetHashCode(); } public bool IsEndPoint() { return b == 1; } public bool inside() { return a >= 0 && a <= b; } internal Num Abs() { if (a < 0) return this.Neg(); else return this; } } class Scanner { string[] s; int i; char[] cs = new char[] { ' ' }; public Scanner() { s = new string[0]; i = 0; } public string next() { if (i < s.Length) return s[i++]; string st = Console.ReadLine(); while (st == "") st = Console.ReadLine(); s = st.Split(cs, StringSplitOptions.RemoveEmptyEntries); i = 0; return s[i++]; } public int nextInt() { return int.Parse(next()); } public long nextLong() { return long.Parse(next()); } public double nextDouble() { return double.Parse(next()); } }
imos/icfpc2016
chokudai/85.cs
C#
mit
24,774
<!doctype html> <html lang="en"> <head> <title>Code coverage report for src/components/</title> <meta charset="utf-8" /> <link rel="stylesheet" href="../../prettify.css" /> <link rel="stylesheet" href="../../base.css" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <style type='text/css'> .coverage-summary .sorter { background-image: url(../../sort-arrow-sprite.png); } </style> </head> <body> <div class='wrapper'> <div class='pad1'> <h1> <a href="../../index.html">all files</a> src/components/ </h1> <div class='clearfix'> <div class='fl pad1y space-right2'> <span class="strong">56.67% </span> <span class="quiet">Statements</span> <span class='fraction'>17/30</span> </div> <div class='fl pad1y space-right2'> <span class="strong">44.44% </span> <span class="quiet">Branches</span> <span class='fraction'>4/9</span> </div> <div class='fl pad1y space-right2'> <span class="strong">33.33% </span> <span class="quiet">Functions</span> <span class='fraction'>1/3</span> </div> <div class='fl pad1y space-right2'> <span class="strong">47.06% </span> <span class="quiet">Lines</span> <span class='fraction'>8/17</span> </div> </div> </div> <div class='status-line medium'></div> <div class="pad1"> <table class="coverage-summary"> <thead> <tr> <th data-col="file" data-fmt="html" data-html="true" class="file">File</th> <th data-col="pic" data-type="number" data-fmt="html" data-html="true" class="pic"></th> <th data-col="statements" data-type="number" data-fmt="pct" class="pct">Statements</th> <th data-col="statements_raw" data-type="number" data-fmt="html" class="abs"></th> <th data-col="branches" data-type="number" data-fmt="pct" class="pct">Branches</th> <th data-col="branches_raw" data-type="number" data-fmt="html" class="abs"></th> <th data-col="functions" data-type="number" data-fmt="pct" class="pct">Functions</th> <th data-col="functions_raw" data-type="number" data-fmt="html" class="abs"></th> <th data-col="lines" data-type="number" data-fmt="pct" class="pct">Lines</th> <th data-col="lines_raw" data-type="number" data-fmt="html" class="abs"></th> </tr> </thead> <tbody><tr> <td class="file medium" data-value="app.js"><a href="app.js.html">app.js</a></td> <td data-value="56.67" class="pic medium"><div class="chart"><div class="cover-fill" style="width: 56%;"></div><div class="cover-empty" style="width:44%;"></div></div></td> <td data-value="56.67" class="pct medium">56.67%</td> <td data-value="30" class="abs medium">17/30</td> <td data-value="44.44" class="pct low">44.44%</td> <td data-value="9" class="abs low">4/9</td> <td data-value="33.33" class="pct low">33.33%</td> <td data-value="3" class="abs low">1/3</td> <td data-value="47.06" class="pct low">47.06%</td> <td data-value="17" class="abs low">8/17</td> </tr> </tbody> </table> </div><div class='push'></div><!-- for sticky footer --> </div><!-- /wrapper --> <div class='footer quiet pad2 space-top1 center small'> Code coverage generated by <a href="http://istanbul-js.org/" target="_blank">istanbul</a> at Wed Mar 22 2017 23:40:09 GMT-0500 (CDT) </div> </div> <script src="../../prettify.js"></script> <script> window.onload = function () { if (typeof prettyPrint === 'function') { prettyPrint(); } }; </script> <script src="../../sorter.js"></script> </body> </html>
MinZhou2016/comp531
hw5/coverage/src/components/index.html
HTML
mit
3,585
package ftc.electronvolts.test.util; import static org.junit.Assert.*; import org.junit.Test; import ftc.electronvolts.util.ControlLoop; import ftc.electronvolts.util.ProportionalController; public class ProportionalControllerTest { @Test public void testProportionalController() { new ProportionalController(0.1, 0.3, 0.5, 0.7); } @Test(expected = IllegalArgumentException.class) public void testProportionalController1() { new ProportionalController(-0.1, 0.3, 0.5, 0.7); } @Test(expected = IllegalArgumentException.class) public void testProportionalController2() { new ProportionalController(0.1, -0.3, 0.5, 0.7); } @Test(expected = IllegalArgumentException.class) public void testProportionalController3() { new ProportionalController(0.1, 0.3, -0.5, 0.7); } @Test(expected = IllegalArgumentException.class) public void testProportionalController4() { new ProportionalController(0.1, 0.3, 0.5, -0.7); } @Test(expected = IllegalArgumentException.class) public void testProportionalController5() { new ProportionalController(0.1, 0.3, 0.5, 0.4); } @Test public void testProportionalController6() { new ProportionalController(0.1, 0.3, 0.4, 0.5, 0.7); } @Test(expected = IllegalArgumentException.class) public void testProportionalController7() { new ProportionalController(0.1, 0.3, -0.4, 0.5, 0.7); } @Test(expected = IllegalArgumentException.class) public void testProportionalController8() { new ProportionalController(0.1, 0.4, 0.3, 0.5, 0.7); } @Test public void testComputeCorrection() { ControlLoop c = new ProportionalController(0.1, 3.1, 0.5, 0.7); assertEquals(0, c.computeCorrection(0, 1), 0); assertEquals(0, c.computeCorrection(0, 2), 0); assertEquals(0, c.computeCorrection(0, 3), 0); assertEquals(-0.5, c.computeCorrection(0, 4), 0); assertEquals(-0.5, c.computeCorrection(0, 5), 0); assertEquals(-0.6, c.computeCorrection(0, 6), 1e-10); assertEquals(-0.7, c.computeCorrection(0, 7), 0); assertEquals(-0.7, c.computeCorrection(0, 8), 0); assertEquals(-0.7, c.computeCorrection(0, 9), 0); assertEquals(0, c.computeCorrection(0, -1), 0); assertEquals(0, c.computeCorrection(0, -2), 0); assertEquals(0, c.computeCorrection(0, -3), 0); assertEquals(0.5, c.computeCorrection(0, -4), 0); assertEquals(0.5, c.computeCorrection(0, -5), 0); assertEquals(0.6, c.computeCorrection(0, -6), 1e-10); assertEquals(0.7, c.computeCorrection(0, -7), 0); assertEquals(0.7, c.computeCorrection(0, -8), 0); assertEquals(0.7, c.computeCorrection(0, -9), 0); } @Test public void testComputeCorrection1() { ControlLoop c = new ProportionalController(0.1, 3.1, 6, 0.5, 0.7); assertEquals(0, c.computeCorrection(0, 1), 0); assertEquals(0, c.computeCorrection(0, 2), 0); assertEquals(0, c.computeCorrection(0, 3), 0); assertEquals(-0.5, c.computeCorrection(0, 4), 0); assertEquals(-0.5, c.computeCorrection(0, 5), 0); assertEquals(-0.7, c.computeCorrection(0, 6), 1e-10); assertEquals(-0.7, c.computeCorrection(0, 7), 0); assertEquals(-0.7, c.computeCorrection(0, 8), 0); assertEquals(-0.7, c.computeCorrection(0, 9), 0); assertEquals(0, c.computeCorrection(0, -1), 0); assertEquals(0, c.computeCorrection(0, -2), 0); assertEquals(0, c.computeCorrection(0, -3), 0); assertEquals(0.5, c.computeCorrection(0, -4), 0); assertEquals(0.5, c.computeCorrection(0, -5), 0); assertEquals(0.7, c.computeCorrection(0, -6), 1e-10); assertEquals(0.7, c.computeCorrection(0, -7), 0); assertEquals(0.7, c.computeCorrection(0, -8), 0); assertEquals(0.7, c.computeCorrection(0, -9), 0); } }
FTC7393/state-machine-framework
src/ftc/electronvolts/test/util/ProportionalControllerTest.java
Java
mit
3,989
module Metro class Model # # A model property maintains a reference to another model. This property # allows for an existing model to be more easily composed with other models. # # The model is stored as a hash which describes the model. # # @example Defining a model property with a block # # class ScoreBoard < Metro::Model # property :position # property :score # property :label, type: :model do # create "metro::ui::label", text: "", position: position # end # end # # @example Defining a model property with a hash # # class ScoreBoard < Metro::Model # property :position # property :score # property :label, type: :model, default: { model: "metro::ui::label", # text: "", position: position } # end # end # class ModelProperty < Property # When retrieving a model and the type is unsupported generate the # model instance from the default. get do default_model end # When retrieving a hash representation of the model, convert it into # a Metro::Model instance. get Hash do |params| create_model params end # When setting the property with an unsupported type, simply save an # empty hash. Which later, if retrieved, it will generate a generic # model. set do {} end # When setting the property with a hash, assume that the hash is a # valid description of a Metro::Model. set Hash, HashWithIndifferentAccess do |hash| hash end # When setting the property with a Metro::Model, convert the model into # a hash. set Metro::Model do |model| model.to_hash end # # Allow for a model property to be defined with a block initialization or # a default hash. # def default_model if block model.instance_eval(&block) else create_model options[:default] end end # @return [Metro::Model] return a model created by the current model that # owns the property. def create_model model.create params[:model], params.except(:model) end end end end
burtlo/metro
lib/metro/models/properties/model_property.rb
Ruby
mit
2,322
<html> <head> <script> // WAYS OF CREATING OBJECTS --- // ----------------- // Mixture of Constructor and Prototype pattern // ----------------- // declare data in Constructor and Methods in prototype function Person() { this.name = "Nicholas"; this.friends = ["Sam","Molly"]; } Person.prototype.foo = function() {alert("hi");}; var p1 = new Person(); p1.name = "Sally"; var p2 = new Person(); // alert("p1's constructor is " + p1.constructor); // alert("p1's prototype is " + p1.prototype); // alert("p2's constructor is " + p2.constructor); // alert("p2's prototype is " + p2.prototype); console.log("p1's constructor is " + p1.constructor); console.log("p1's prototype is " + p1.prototype); console.log("p2's constructor is " + p2.constructor); console.log("p2's prototype is " + p2.prototype); p1.friends.push("Jerry"); // alert("p1's friends are: " + p1.friends // + "\np2's friends are: " + p2.friends); console.log("p1's friends are: " + p1.friends + "\np2's friends are: " + p2.friends); // --- END --- YAY! ------ </script> </head> <body> </body> </html>
jkrajcir/SE319
lab4/02_Examples/ex08_obj_objects.html
HTML
mit
1,081
// flow-typed signature: 715c8753230e19bbaff4d8c2ee503f1a // flow-typed version: <<STUB>>/babel-preset-stage-0_v^6.22.0/flow_v0.47.0 /** * This is an autogenerated libdef stub for: * * 'babel-preset-stage-0' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'babel-preset-stage-0' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'babel-preset-stage-0/lib/index' { declare module.exports: any; } // Filename aliases declare module 'babel-preset-stage-0/lib/index.js' { declare module.exports: $Exports<'babel-preset-stage-0/lib/index'>; }
hannupekka/cocheck
flow-typed/npm/babel-preset-stage-0_vx.x.x.js
JavaScript
mit
906
using System; using System.IO; using System.Linq; using System.Web; using System.Xml.Linq; using SitecoreCognitiveServices.Feature.OleChat.Areas.SitecoreCognitiveServices.Models; using SitecoreCognitiveServices.Foundation.SCSDK.Wrappers; using SitecoreCognitiveServices.Foundation.MSSDK.Models.Language.Luis; using SitecoreCognitiveServices.Feature.OleChat.Dialog; using SitecoreCognitiveServices.Feature.OleChat.Factories; using SitecoreCognitiveServices.Feature.OleChat.Models; using SitecoreCognitiveServices.Feature.OleChat.Statics; namespace SitecoreCognitiveServices.Feature.OleChat.Intents { public class VersionIntent : BaseOleIntent { protected readonly HttpContextBase Context; public override string Name => "version"; public override string Description => Translator.Text("Chat.Intents.Version.Name"); public override bool RequiresConfirmation => false; public VersionIntent( HttpContextBase context, IIntentOptionSetFactory optionSetFactory, IConversationResponseFactory responseFactory, IOleSettings settings) : base(optionSetFactory, responseFactory, settings) { Context = context; } public override ConversationResponse Respond(LuisResult result, ItemContextParameters parameters, IConversation conversation) { var path = Context.Server.MapPath("~/sitecore/shell/sitecore.version.xml"); if (!File.Exists(path)) return ConversationResponseFactory.Create(string.Empty); string xmlText = File.ReadAllText(path); XDocument xdoc = XDocument.Parse(xmlText); var version = xdoc.Descendants("version").First(); var major = version.Descendants("major").First().Value; var minor = version.Descendants("minor").First().Value; var revision = version.Descendants("revision").First().Value; return ConversationResponseFactory.Create(string.Format(Translator.Text("Chat.Intents.Version.Response"), major, minor, revision)); } } }
markstiles/SitecoreCognitiveServices
src/Feature/OleChat/code/Intents/VersionIntent.cs
C#
mit
2,115
"""nubrain URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import patterns, include, url from django.contrib import admin from nubrain.settings import BASE_URL, APP_NAME from django.views.generic import RedirectView from django.utils.translation import ugettext_lazy urlpatterns = patterns('', (r'^$', RedirectView.as_view(url='%s/admin/' % BASE_URL)), url(r'^admin/', include(admin.site.urls)), ) admin.site.site_title = ugettext_lazy(APP_NAME) admin.site.site_header = ugettext_lazy('%s Admin' % APP_NAME) admin.site.index_title = ugettext_lazy('%s Dashboard' % APP_NAME) admin.autodiscover()
NuChwezi/nubrain
nubrain/urls.py
Python
mit
1,184
require_relative 'module' module Scan class SlackPoster def run(results) return if Scan.config[:skip_slack] return if Scan.config[:slack_only_on_failure] && results[:failures] == 0 return if Scan.config[:slack_url].to_s.empty? if Scan.config[:slack_channel].to_s.length > 0 channel = Scan.config[:slack_channel] channel = ('#' + channel) unless ['#', '@'].include?(channel[0]) # send message to channel by default end require 'slack-notifier' notifier = Slack::Notifier.new(Scan.config[:slack_url]) do defaults(channel: channel, username: 'fastlane') end attachments = [] if Scan.config[:slack_message] attachments << { text: Scan.config[:slack_message].to_s, color: "good" } end attachments << { text: "Build Errors: #{results[:build_errors] || 0}", color: results[:build_errors].to_i > 0 ? "danger" : "good", short: true } if results[:failures] attachments << { text: "Test Failures: #{results[:failures]}", color: results[:failures].to_i > 0 ? "danger" : "good", short: true } end if results[:tests] and results[:failures] attachments << { text: "Successful Tests: #{results[:tests] - results[:failures]}", color: "good", short: true } end result = notifier.ping("#{Scan.project.app_name} Tests:", icon_url: 'https://s3-eu-west-1.amazonaws.com/fastlane.tools/fastlane.png', attachments: attachments) result = result.first if result.code.to_i == 200 UI.success('Successfully sent Slack notification') elsif result.code.to_i == 404 UI.error("The Slack URL you provided could not be reached (404)") else UI.error("The Slack notification could not be sent:") UI.error(result.to_s) end end end end
luongm/fastlane
scan/lib/scan/slack_poster.rb
Ruby
mit
2,038
using System; using System.Collections.Generic; using System.Linq; using System.Text; using LispStyleExpressions; namespace LispStyleExpressions.Functions { class Greater : LispStyleFunction { //pass to base class public Greater(LispStyleExpressionEvaluator lang) : base(lang) { } public override string key() { return ">"; } public override FunctionType type() { return FunctionType.Logical; } public override float eval(string[] args) { //only 2 args argumentCheck(args.Length, 2, ArgumentRestriction.MustEqual); //grab first arguement float a = lang.Evaluate(args[0]); float b = lang.Evaluate(args[1]); if (a > b) { return 1; } else { return 0; } }//end eval } }
t-c-/ExpressionEvaluators
src/ExpressionEvaluation/LispStyleExpressions/Functions/Greater.cs
C#
mit
906
[![Stories in Ready](https://badge.waffle.io/vapkarian/borderlands_parser.png?label=ready&title=Ready)](https://waffle.io/vapkarian/borderlands_parser) Borderlands SHiFT codes parser ================== Script for parsing Borderlands 2 and Borderlands Pre-Sequel SHiFT Codes from social networks and sending them by email. **About SHiFT Codes**: http://borderlands.wikia.com/wiki/SHiFT You can use script either by command-line or from another python script. In first case you can call it like:<br> `python borderlands_parser/main.py <user@example.com> <password> [option parameters]`<br> You can also see help with:<br> `python borderlands_parser/main.py -h`<br> If you want use script from another python script, you should import it and calling function "main" with parameters. In both case you can provide next parameters: - user (required): username to use for the SMTP server - password (required): password to use for the SMTP server - host (optional): the host to use for sending email (default: "smtp.gmail.com") - port (optional): port to use for the SMTP server (default: 587) - email_to (optional): list of email recipients separated by space (default: own user) - subject (optional): subject of the message (default: "SHiFT Codes") - ps (optional): find and parse Pre-Sequel codes instead of Borderland 2 (default: False) If you import this module, you can override next parameters: - EMAIL_HOST: default of "host" parameter - EMAIL_PORT: default of "port" parameter - EMAIL_SUBJECT: default of "subject" parameter - BL2_SOURCES or BLPS_SOURCES: tuple of ("url", "prefix_re"), where "url" is url of page where SHiFT Codes are placed and "prefix_re" is pattern of special prefix of SHiFT codes for this page Example of usage:<br> `import borderlands_parser`<br> `borderlands_parser.EMAIL_HOST = '127.0.0.1'`<br> `borderlands_parser.SOURCES += (('<url>', '<prefix_re>'),)`<br> `borderlands_parser.main('<user'>, '<password>', **kwargs)`<br>
vapkarian/borderlands_parser
README.md
Markdown
mit
1,972
#region License information /* The MIT License (MIT) Copyright (c) 2015 Luiz Fernando Silva Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.IO; using System.Linq; using System.Windows.Forms; using System.Xml; using Antlr4.Runtime; using ICSharpCode.TextEditor; using ICSharpCode.TextEditor.Document; using ZIDE.Utils; using ZIDE.Views.Controls; using ZScript.CodeGeneration; using ZScript.CodeGeneration.Analysis; using ZScript.CodeGeneration.Definitions; using ZScript.CodeGeneration.Messages; using ZScript.Parsing.ANTLR; namespace ZIDE.Services.Scripting { /// <summary> /// Service that provides realtime syntax checking functionalities for script document forms /// </summary> public class RealtimeSyntaxCheckService { /// <summary> /// The first to provide syntax checking service to /// </summary> private readonly IScriptForm _form; /// <summary> /// Gets the document associated with this realtime syntax check service /// </summary> private IDocument Document => _form.TextEditorControl.Document; /// <summary> /// Gets the runtime generator for the realtime syntax check service /// </summary> public ZRuntimeGenerator RuntimeGenerator { get; private set; } /// <summary> /// The container for the error messages found during parsing /// </summary> private MessageContainer _messageContainer; /// <summary> /// The code scope for the current document /// </summary> private CodeScope _codeScope; /// <summary> /// Instance of the messages margin for placing messages into /// </summary> private readonly MessagesMargin _messagesMargin; /// <summary> /// Timer used to introduce a delay in parsing during keystrokes /// </summary> private readonly Timer _parseTimer; /// <summary> /// The background worker used to parse the script /// </summary> private readonly BackgroundWorker _backgroundWorker; /// <summary> /// Default interval before the parse timer performs the script parsing /// </summary> private const int ParseInterval = 100; /// <summary> /// Delegate for the ScriptParsed event /// </summary> /// <param name="sender">The sender for the event</param> /// <param name="eventArgs">The arguments for the event</param> public delegate void ScriptParsedEventHandler(object sender, ScriptParsedEventArgs eventArgs); /// <summary> /// Occurs whenever the parsing of a script has finished /// </summary> public event ScriptParsedEventHandler ScriptParsed; /// <summary> /// Initialzies a new instance of the RealtimeSyntaxCheckService class /// </summary> /// <param name="form">The form to provide the syntax checking service to</param> public RealtimeSyntaxCheckService(IScriptForm form) { _form = form; // Hookup the events Document.DocumentChanged += Document_OnDocumentChanged; _messageContainer = new MessageContainer(); _parseTimer = new Timer { Interval = ParseInterval }; _parseTimer.Tick += ParseTimer_OnTick; _backgroundWorker = new BackgroundWorker(); _backgroundWorker.DoWork += BackgroundWorker_OnDoWork; _backgroundWorker.RunWorkerCompleted += BackgroundWorker_OnRunWorkerCompleted; _messagesMargin = new MessagesMargin(_form.TextEditorControl.ActiveTextAreaControl.TextArea); _form.TextEditorControl.ActiveTextAreaControl.TextArea.InsertLeftMargin(0, _messagesMargin); InitializeSyntaxHighlighting(); } /// <summary> /// Initializes the syntax highlighting on this form /// </summary> void InitializeSyntaxHighlighting() { // Setup the text editor on the document _form.TextEditorControl.Document.TextEditorProperties.ConvertTabsToSpaces = true; _form.TextEditorControl.Document.TextEditorProperties.ShowSpaces = true; _form.TextEditorControl.Document.TextEditorProperties.ShowTabs = true; HighlightingManager.Manager.AddSyntaxModeFileProvider(new ZScriptSyntaxModeProvider()); // Attach to the text editor _form.TextEditorControl.SetHighlighting("ZScript"); // Activate the highlighting, use the name from the SyntaxDefinition node } // // Parse Timer Tick event // private void ParseTimer_OnTick(object sender, EventArgs eventArgs) { _parseTimer.Stop(); StartScriptParse(); } // // BackgroundWorker's DoWork event // private void BackgroundWorker_OnDoWork(object sender, DoWorkEventArgs doWorkEventArgs) { RefreshScript(); } // // BackgroundWorker's RunWorkerCompleted event // private void BackgroundWorker_OnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs runWorkerCompletedEventArgs) { lock (Document) { ScriptParsed?.Invoke(this, new ScriptParsedEventArgs(_codeScope != null, _codeScope, RuntimeGenerator)); _messageContainer = RuntimeGenerator.MessageContainer; _messagesMargin.MessageContainer = RuntimeGenerator.MessageContainer; UpdateDisplay(); } } /// <summary> /// Parses the script /// </summary> public void Parse() { StartScriptParse(); } /// <summary> /// Starts the script parsing, preparing the runtime generator and starting the parsing background worker /// </summary> void StartScriptParse() { // Quit if an operation is already in process on the background worker if (_backgroundWorker.IsBusy) return; // Parse the script RuntimeGenerator = new ZRuntimeGenerator(Document.TextContent); _backgroundWorker.RunWorkerAsync(); } /// <summary> /// Refreshes the script currently opened /// </summary> void RefreshScript() { RuntimeGenerator.ParseSources(); if (!RuntimeGenerator.MessageContainer.HasSyntaxErrors) { // TODO: See how to deal with multiple scopes coming from multiple sources merged into one _codeScope = RuntimeGenerator.CollectDefinitions(); //_codeScope = generator.SourceProvider.Sources[0].Definitions.CollectedBaseScope; } else { _codeScope = null; } } /// <summary> /// Updates the display of the syntax /// </summary> void UpdateDisplay() { Document.RequestUpdate(new TextAreaUpdate(TextAreaUpdateType.WholeTextArea)); Document.CommitUpdate(); // Clear markers on document Document.MarkerStrategy.RemoveAll(m => true); if(_codeScope != null) AddMemberMarkers(_codeScope); if (!_messageContainer.HasMessages) { return; } AddMessageMarkers(); } /// <summary> /// Adds the message markers to the text /// </summary> private void AddMessageMarkers() { // Add markers around warnings foreach (var warning in _messageContainer.Warnings) { Color color = Color.YellowGreen; string message = warning.Message; var locationStart = new TextLocation(warning.Column, warning.Line - 1); var locationEnd = new TextLocation(warning.Column + 1, warning.Line - 1); var context = IdentifierContextForContext(warning.Context); if (context != null) { locationStart = new TextLocation(context.Start.Column, context.Start.Line - 1); locationEnd = new TextLocation(context.Stop.Column + context.Stop.Text.Length, context.Stop.Line - 1); } var offsetStart = Document.PositionToOffset(locationStart); var offsetEnd = Document.PositionToOffset(locationEnd); var marker = new TextMarker(offsetStart, offsetEnd - offsetStart, TextMarkerType.WaveLine, color) { ToolTip = message }; Document.MarkerStrategy.AddMarker(marker); } // Add markers around code errors foreach (var codeError in _messageContainer.CodeErrors) { var locationStart = new TextLocation(codeError.Column, codeError.Line - 1); var locationEnd = new TextLocation(codeError.Column + 1, codeError.Line - 1); var context = IdentifierContextForContext(codeError.Context); if (context != null) { locationStart = new TextLocation(context.Start.Column, context.Start.Line - 1); locationEnd = new TextLocation(context.Stop.Column + context.Stop.Text.Length, context.Stop.Line - 1); } var offsetStart = Document.PositionToOffset(locationStart); var offsetEnd = Document.PositionToOffset(locationEnd); var marker = new TextMarker(offsetStart, offsetEnd - offsetStart, TextMarkerType.WaveLine, Color.Blue) { ToolTip = codeError.Message }; Document.MarkerStrategy.AddMarker(marker); } // Add markers around syntax errors foreach (var syntaxError in _messageContainer.SyntaxErrors) { var locationStart = new TextLocation(syntaxError.Column, syntaxError.Line - 1); var locationEnd = new TextLocation(syntaxError.Column + 1, syntaxError.Line - 1); if (syntaxError.Token != null) { locationStart = new TextLocation(syntaxError.Token.Column, syntaxError.Token.Line - 1); locationEnd = new TextLocation(syntaxError.Token.Column + syntaxError.Token.Text.Length, syntaxError.Token.Line - 1); } var offsetStart = Document.PositionToOffset(locationStart); var offsetEnd = Document.PositionToOffset(locationEnd); var marker = new TextMarker(offsetStart, offsetEnd - offsetStart, TextMarkerType.WaveLine) { ToolTip = syntaxError.Message }; Document.MarkerStrategy.AddMarker(marker); } } /// <summary> /// Returns a parse rule context that is the identifier of a given parse rule context object. /// If no valid identifier parse rule contexts are found, the given context is returned instead. /// Identifier contexts are found when the context is either a class, sequence, function, method, type field or type alias context /// </summary> /// <param name="context">The context to get the identifier out of</param> /// <returns>The identifier context for the context; or itself, if none could be found</returns> static ParserRuleContext IdentifierContextForContext(ParserRuleContext context) { if (context == null) return null; // Function var funcContext = context as ZScriptParser.FunctionDefinitionContext; if (funcContext != null) { return funcContext.functionName(); } // Class var classContext = context as ZScriptParser.ClassDefinitionContext; if (classContext != null) { return classContext.className(); } // Sequence var sequenceContext = context as ZScriptParser.SequenceBlockContext; if (sequenceContext != null) { return sequenceContext.sequenceName(); } // Method var methodContext = context as ZScriptParser.ClassMethodContext; if (methodContext != null) { return methodContext.functionDefinition().functionName(); } // Type alias var typeAlias = context as ZScriptParser.TypeAliasContext; if (typeAlias != null) { return typeAlias.typeAliasName(); } // Type field var typeField = context as ZScriptParser.TypeAliasVariableContext; if (typeField != null) { return typeField.valueDeclareStatement().valueHolderDecl().valueHolderDefine().valueHolderName(); } return context; } /// <summary> /// Adds markers on the text base on a given code scope's contents /// </summary> private void AddMemberMarkers(CodeScope scope) { // Add the definition markers var definitions = scope.GetAllDefinitionsRecursive(); foreach (var definition in definitions.OfType<ValueHolderDefinition>().Where(d => d.ValueDefineContext != null && d.Context != null)) { string message = definition.Type.ToString(); var context = definition.ValueDefineContext; var declContext = context.let ?? context.var; var locationStart = new TextLocation(context.Start.Column, context.Start.Line - 1); var locationEnd = new TextLocation(context.Start.Column + declContext.Text.Length, context.Start.Line - 1); var offsetStart = Document.PositionToOffset(locationStart); var offsetEnd = Document.PositionToOffset(locationEnd); var marker = new TextMarker(offsetStart, offsetEnd - offsetStart, TextMarkerType.Invisible) { ToolTip = message }; Document.MarkerStrategy.AddMarker(marker); } var usages = scope.GetAllUsagesRecursive().ToArray(); // Register valid usages foreach (var usage in usages.Where(u => u.Definition != null && u.Context != null)) { string message = usage.Definition.ToString(); var context = usage.Context; var locationStart = new TextLocation(context.Start.Column, context.Start.Line - 1); var locationEnd = new TextLocation(context.Stop.Column + context.Stop.Text.Length, context.Start.Line - 1); var offsetStart = Document.PositionToOffset(locationStart); var offsetEnd = Document.PositionToOffset(locationEnd); var marker = new TextMarker(offsetStart, offsetEnd - offsetStart, TextMarkerType.Invisible) { ToolTip = message }; Document.MarkerStrategy.AddMarker(marker); } } // // TextContentChanged event handler // private void Document_OnDocumentChanged(object sender, DocumentEventArgs eventArgs) { _parseTimer.Stop(); _parseTimer.Start(); _parseTimer.Interval = ParseInterval; } /// <summary> /// Text editor margin class used to display little icons for the messages /// </summary> class MessagesMargin : AbstractMargin { /// <summary> /// Gets or sets the message container to pull the messages from /// </summary> public MessageContainer MessageContainer { get; set; } /// <summary> /// Tooltip used to show the warning/error under the line the user is pointing at /// </summary> private readonly ToolTip _toolTip; // // AbstractMargin.Size override // public override Size Size => new Size(20, -1); /// <summary> /// Initializes a new instance of the MessagesMargin class /// </summary> /// <param name="textArea">The text area to attach this messages margin to</param> public MessagesMargin(TextArea textArea) : base(textArea) { _toolTip = new ToolTip(); textArea.MouseHover += TextArea_OnMouseHover; } private void TextArea_OnMouseHover(object sender, EventArgs eventArgs) { // Check if the mouse is over any error/message if (MessageContainer == null) return; Point mousepos = TextArea.PointToClient(Control.MousePosition); foreach (var message in MessageContainer.AllMessages.Reverse()) { int lineNumber = textArea.Document.GetVisibleLine(message.Line - 1); int lineHeight = textArea.TextView.FontHeight; int yPos = (lineNumber * lineHeight) - textArea.VirtualTop.Y; if (IsLineInsideRegion(yPos, yPos + lineHeight, 0, TextArea.Size.Height)) { if (lineNumber == textArea.Document.GetVisibleLine(message.Line - 2)) { // marker is inside folded region, do not draw it continue; } Rectangle target = new Rectangle(2, yPos, 16, 16); if (target.Contains(mousepos)) { _toolTip.Show(message.Message, TextArea, new Point(0, yPos + lineHeight), 500); break; } } } } // // AbstractMargin.HandleMouseDown override // public override void HandleMouseDown(Point mousepos, MouseButtons mouseButtons) { // Check if the mouse is over any error/message if (MessageContainer == null) return; foreach (var message in MessageContainer.AllMessages) { int lineNumber = textArea.Document.GetVisibleLine(message.Line - 1); int lineHeight = textArea.TextView.FontHeight; int yPos = (lineNumber * lineHeight) - textArea.VirtualTop.Y; if (IsLineInsideRegion(yPos, yPos + lineHeight, 0, TextArea.Size.Height)) { if (lineNumber == textArea.Document.GetVisibleLine(message.Line - 2)) { // marker is inside folded region, do not draw it continue; } Rectangle target = new Rectangle(2, yPos, 16, 16); var context = IdentifierContextForContext(message.Context); if (target.Contains(mousepos)) { if (context != null) { var locationStart = new TextLocation(context.Start.Column, context.Start.Line - 1); var locationEnd = new TextLocation(context.Stop.Column + context.GetText().Length, context.Stop.Line - 1); var startOffset = TextArea.Document.PositionToOffset(locationStart); var endOffset = TextArea.Document.PositionToOffset(locationEnd); TextArea.MotherTextEditorControl.Select(startOffset, endOffset - startOffset); } else if (message.Token != null) { var locationStart = new TextLocation(message.Token.Column, message.Token.Line - 1); var locationEnd = new TextLocation(message.Token.Column + message.Token.Text.Length, message.Token.Line - 1); var startOffset = TextArea.Document.PositionToOffset(locationStart); var endOffset = TextArea.Document.PositionToOffset(locationEnd); TextArea.MotherTextEditorControl.Select(startOffset, endOffset - startOffset); } else { var locationStart = new TextLocation(message.Column, message.Line - 1); var startOffset = TextArea.Document.PositionToOffset(locationStart); TextArea.MotherTextEditorControl.Select(startOffset, 0); } break; } } } } // // AbstractMargin.HandleMouseLeave override // public override void HandleMouseLeave(EventArgs e) { base.HandleMouseLeave(e); _toolTip.Hide(TextArea); } // // AbstractMargin.Paint override // public override void Paint(Graphics g, Rectangle rect) { if (rect.Width <= 0 || rect.Height <= 0) { return; } // paint background g.FillRectangle(SystemBrushes.Control, new Rectangle(drawingPosition.X, rect.Top, drawingPosition.Width - 1, rect.Height)); g.DrawLine(SystemPens.ControlDark, drawingPosition.Right - 1, rect.Top, drawingPosition.Right - 1, rect.Bottom); // paint icons if (MessageContainer != null) { foreach (var message in MessageContainer.AllMessages) { int lineNumber = textArea.Document.GetVisibleLine(message.Line - 1); int lineHeight = textArea.TextView.FontHeight; int yPos = (lineNumber * lineHeight) - textArea.VirtualTop.Y; if (IsLineInsideRegion(yPos, yPos + lineHeight, rect.Y, rect.Bottom)) { if (lineNumber == textArea.Document.GetVisibleLine(message.Line - 2)) { // marker is inside folded region, do not draw it continue; } Rectangle origin = new Rectangle(0, 0, 16, 16); Rectangle target = new Rectangle(2, yPos, 16, 16); Image image = message is Warning ? Properties.Resources.code_warning : Properties.Resources.code_error; g.DrawImage(image, target, origin, GraphicsUnit.Pixel); //mark.Draw(this, g, new Point(0, yPos)); } } } base.Paint(g, rect); } static bool IsLineInsideRegion(int top, int bottom, int regionTop, int regionBottom) { if (top >= regionTop && top <= regionBottom) { // Region overlaps the line's top edge. return true; } if (regionTop > top && regionTop < bottom) { // Region's top edge inside line. return true; } return false; } } /// <summary> /// Basic syntax mode provider /// </summary> class ZScriptSyntaxModeProvider : ISyntaxModeFileProvider { /// <summary> /// List of syntax modes provided by this ZScriptSyntaxModeProvider /// </summary> List<SyntaxMode> _syntaxModes; /// <summary> /// Gets a collection of syntax modes provided by this ZScriptSyntaxModeProvider /// </summary> public ICollection<SyntaxMode> SyntaxModes => _syntaxModes; /// <summary> /// Initializes a new instance of the ZScriptSyntaxModeProvider class /// </summary> public ZScriptSyntaxModeProvider() { UpdateSyntaxModeList(); } /// <summary> /// Updates the syntax mode list /// </summary> public void UpdateSyntaxModeList() { _syntaxModes = new List<SyntaxMode> { new SyntaxMode("ZScript", "ZScript", ".xshd") }; } /// <summary> /// Gets an XML reader for the contents ofthe given syntax mode file /// </summary> /// <param name="syntaxMode">The syntax mode to get</param> /// <returns>An XML reader for the given syntax mode</returns> public XmlTextReader GetSyntaxModeFile(SyntaxMode syntaxMode) { var bytes = Properties.Resources.ZScript_Mode; return new XmlTextReader(new MemoryStream(bytes)); } } } /// <summary> /// Event arguments for a ScriptParsed event /// </summary> public class ScriptParsedEventArgs : EventArgs { /// <summary> /// Gets a value specifying whether the script parsing was successfull /// </summary> public bool Succeeded { get; private set; } /// <summary> /// Gets the code scope that was parsed. /// When the script parse is successful, this value describes the collected base scope for the script. /// This value is null, if the parsing was unsuccessful /// </summary> public CodeScope BaseScope { get; private set; } /// <summary> /// Gets the runtime generator that was used to parse the code scope /// </summary> public ZRuntimeGenerator RuntimeGenerator { get; private set; } /// <summary> /// Initializes a new instance of the ScriptParsedEventArgs class /// </summary> /// <param name="succeeded">Whether the script parsing was successfull</param> /// <param name="baseScope">The base scope for the script parsed</param> /// <param name="runtimeGenerator">The runtime generator that was usd to parse the code scope</param> public ScriptParsedEventArgs(bool succeeded, CodeScope baseScope, ZRuntimeGenerator runtimeGenerator) { Succeeded = succeeded; BaseScope = baseScope; RuntimeGenerator = runtimeGenerator; } } }
LuizZak/ZIDE
ZIDE/Services/Scripting/RealtimeSyntaxCheckService.cs
C#
mit
28,523
local stringx = require 'pl.stringx' local utils = require 'pl.utils' local asserteq = require 'pl.test' . asserteq local T = require 'pl.test'.tuple local function FIX(s) io.stderr:write('FIX:' .. s .. '\n') end -- isalpha asserteq(T(stringx.isalpha''), T(false)) asserteq(T(stringx.isalpha' '), T(false)) asserteq(T(stringx.isalpha'0'), T(false)) asserteq(T(stringx.isalpha'\0'), T(false)) asserteq(T(stringx.isalpha'azAZ'), T(true)) asserteq(T(stringx.isalpha'az9AZ'), T(false)) -- isdigit asserteq(T(stringx.isdigit''), T(false)) asserteq(T(stringx.isdigit' '), T(false)) asserteq(T(stringx.isdigit'a'), T(false)) asserteq(T(stringx.isdigit'0123456789'), T(true)) -- isalnum asserteq(T(stringx.isalnum''), T(false)) asserteq(T(stringx.isalnum' '), T(false)) asserteq(T(stringx.isalnum('azAZ01234567890')), T(true)) -- isspace asserteq(T(stringx.isspace''), T(false)) asserteq(T(stringx.isspace' '), T(true)) asserteq(T(stringx.isspace' \r\n\f\t'), T(true)) asserteq(T(stringx.isspace' \r\n-\f\t'), T(false)) -- islower asserteq(T(stringx.islower''), T(false)) asserteq(T(stringx.islower'az'), T(true)) asserteq(T(stringx.islower'aMz'), T(false)) asserteq(T(stringx.islower'a z'), T(true)) -- isupper asserteq(T(stringx.isupper''), T(false)) asserteq(T(stringx.isupper'AZ'), T(true)) asserteq(T(stringx.isupper'AmZ'), T(false)) asserteq(T(stringx.isupper'A Z'), T(true)) -- startswith local startswith = stringx.startswith asserteq(T(startswith('', '')), T(true)) asserteq(T(startswith('', 'a')), T(false)) asserteq(T(startswith('a', '')), T(true)) asserteq(T(startswith('a', 'a')), T(true)) asserteq(T(startswith('a', 'b')), T(false)) asserteq(T(startswith('a', 'ab')), T(false)) asserteq(T(startswith('abc', 'ab')), T(true)) asserteq(T(startswith('abc', 'bc')), T(false)) -- off by one asserteq(T(startswith('abc', '.')), T(false)) -- Lua pattern char asserteq(T(startswith('a\0bc', 'a\0b')), T(true)) -- '\0' asserteq(startswith('abcfoo',{'abc','def'}),true) asserteq(startswith('deffoo',{'abc','def'}),true) asserteq(startswith('cdefoo',{'abc','def'}),false) -- endswith -- http://snippets.luacode.org/sputnik.lua?p=snippets/Check_string_ends_with_other_string_74 local endswith = stringx.endswith asserteq(T(endswith("", "")), T(true)) asserteq(T(endswith("", "a")), T(false)) asserteq(T(endswith("a", "")), T(true)) asserteq(T(endswith("a", "a")), T(true)) asserteq(T(endswith("a", "A")), T(false)) -- case sensitive asserteq(T(endswith("a", "aa")), T(false)) asserteq(T(endswith("abc", "")), T(true)) asserteq(T(endswith("abc", "ab")), T(false)) -- off by one asserteq(T(endswith("abc", "c")), T(true)) asserteq(T(endswith("abc", "bc")), T(true)) asserteq(T(endswith("abc", "abc")), T(true)) asserteq(T(endswith("abc", " abc")), T(false)) asserteq(T(endswith("abc", "a")), T(false)) asserteq(T(endswith("abc", ".")), T(false)) -- Lua pattern char asserteq(T(endswith("ab\0c", "b\0c")), T(true)) -- \0 asserteq(T(endswith("ab\0c", "b\0d")), T(false)) -- \0 asserteq(endswith('dollar.dot',{'.dot','.txt'}),true) asserteq(endswith('dollar.txt',{'.dot','.txt'}),true) asserteq(endswith('dollar.rtxt',{'.dot','.txt'}),false) -- join asserteq(stringx.join(' ', {1,2,3}), '1 2 3') -- splitlines asserteq(stringx.splitlines(''), {}) asserteq(stringx.splitlines('a'), {'a'}) asserteq(stringx.splitlines('\n'), {''}) asserteq(stringx.splitlines('\n\n'), {'', ''}) asserteq(stringx.splitlines('\r\r'), {'', ''}) asserteq(stringx.splitlines('\r\n'), {''}) asserteq(stringx.splitlines('ab\ncd\n'), {'ab', 'cd'}) asserteq(stringx.splitlines('ab\ncd\n', true), {'ab\n', 'cd\n'}) asserteq(stringx.splitlines('\nab\r\r\ncd\n', true), {'\n', 'ab\r', '\r\n', 'cd\n'}) -- expandtabs ---FIX[[raises error asserteq(T(stringx.expandtabs('',0)), T('')) asserteq(T(stringx.expandtabs('',1)), T('')) asserteq(T(stringx.expandtabs(' ',1)), T(' ')) -- expandtabs now works like Python's str.expandtabs (up to next tab stop) asserteq(T(stringx.expandtabs(' \t ')), T((' '):rep(1+8))) asserteq(T(stringx.expandtabs(' \t ',2)), T(' ')) --]] -- lfind asserteq(T(stringx.lfind('', '')), T(1)) asserteq(T(stringx.lfind('a', '')), T(1)) asserteq(T(stringx.lfind('ab', 'b')), T(2)) asserteq(T(stringx.lfind('abc', 'cd')), T(nil)) asserteq(T(stringx.lfind('abcbc', 'bc')), T(2)) asserteq(T(stringx.lfind('ab..cd', '.')), T(3)) -- pattern char asserteq(T(stringx.lfind('abcbcbbc', 'bc', 3)), T(4)) asserteq(T(stringx.lfind('abcbcbbc', 'bc', 3, 4)), T(nil)) asserteq(T(stringx.lfind('abcbcbbc', 'bc', 3, 5)), T(4)) asserteq(T(stringx.lfind('abcbcbbc', 'bc', nil, 5)), T(2)) -- rfind asserteq(T(stringx.rfind('', '')), T(1)) asserteq(T(stringx.rfind('ab', '')), T(3)) asserteq(T(stringx.rfind('abc', 'cd')), T(nil)) asserteq(T(stringx.rfind('abcbc', 'bc')), T(4)) asserteq(T(stringx.rfind('abcbcb', 'bc')), T(4)) asserteq(T(stringx.rfind('ab..cd', '.')), T(4)) -- pattern char asserteq(T(stringx.rfind('abcbcbbc', 'bc', 3)), T(7)) asserteq(T(stringx.rfind('abcbcbbc', 'bc', 3, 4)), T(nil)) asserteq(T(stringx.rfind('abcbcbbc', 'bc', 3, 5)), T(4)) asserteq(T(stringx.rfind('abcbcbbc', 'bc', nil, 5)), T(4)) asserteq(T(stringx.rfind('banana', 'ana')), T(4)) -- replace asserteq(T(stringx.replace('', '', '')), T('')) asserteq(T(stringx.replace(' ', '', '')), T(' ')) asserteq(T(stringx.replace(' ', '', ' ')), T(' ')) asserteq(T(stringx.replace(' ', ' ', '')), T('')) asserteq(T(stringx.replace('abcabcabc', 'bc', 'BC')), T('aBCaBCaBC')) asserteq(T(stringx.replace('abcabcabc', 'bc', 'BC', 1)), T('aBCabcabc')) asserteq(T(stringx.replace('abcabcabc', 'bc', 'BC', 0)), T('abcabcabc')) asserteq(T(stringx.replace('abc', 'd', 'e')), T('abc')) asserteq(T(stringx.replace('a.b', '.', '%d')), T('a%db')) -- split local split = stringx.split asserteq(split('', ''), {''}) asserteq(split('', 'z'), {}) --FIX:intended and specified behavior? asserteq(split('a', ''), {'a'}) --FIX:intended and specified behavior? asserteq(split('a', 'a'), {''}) -- stringx.split now follows the Python pattern, so it uses a substring, not a pattern. -- If you need to split on a pattern, use utils.split() -- asserteq(split('ab1cd23ef%d', '%d+'), {'ab', 'cd', 'ef%d'}) -- pattern chars -- note that leading space is ignored by the default asserteq(split(' 1 2 3 '),{'1','2','3'}) asserteq(split('a*bb*c*ddd','*'),{'a','bb','c','ddd'}) asserteq(split('dog:fred:bonzo:alice',':',3), {'dog','fred','bonzo:alice'}) asserteq(split('dog:fred:bonzo:alice:',':',3), {'dog','fred','bonzo:alice:'}) asserteq(split('///','/'),{'','','',''}) -- capitalize asserteq(T(stringx.capitalize('')), T('')) asserteq(T(stringx.capitalize('abC deF1')), T('Abc Def1')) -- Python behaviour -- count asserteq(T(stringx.count('', '')), T(0)) --infinite loop]] asserteq(T(stringx.count(' ', '')), T(2)) --infinite loop]] asserteq(T(stringx.count('a..c', '.')), T(2)) -- pattern chars asserteq(T(stringx.count('a1c', '%d')), T(0)) -- pattern chars asserteq(T(stringx.count('Anna Anna Anna', 'Anna')), T(3)) -- no overlap asserteq(T(stringx.count('banana', 'ana', false)), T(1)) -- no overlap asserteq(T(stringx.count('banana', 'ana', true)), T(2)) -- overlap -- ljust asserteq(T(stringx.ljust('', 0)), T('')) asserteq(T(stringx.ljust('', 2)), T(' ')) asserteq(T(stringx.ljust('ab', 3)), T('ab ')) asserteq(T(stringx.ljust('ab', 3, '%')), T('ab%')) asserteq(T(stringx.ljust('abcd', 3)), T('abcd')) -- agrees with Python -- rjust asserteq(T(stringx.rjust('', 0)), T('')) asserteq(T(stringx.rjust('', 2)), T(' ')) asserteq(T(stringx.rjust('ab', 3)), T(' ab')) asserteq(T(stringx.rjust('ab', 3, '%')), T('%ab')) asserteq(T(stringx.rjust('abcd', 3)), T('abcd')) -- agrees with Python -- center asserteq(T(stringx.center('', 0)), T('')) asserteq(T(stringx.center('', 1)), T(' ')) asserteq(T(stringx.center('', 2)), T(' ')) asserteq(T(stringx.center('a', 1)), T('a')) asserteq(T(stringx.center('a', 2)), T('a ')) asserteq(T(stringx.center('a', 3)), T(' a ')) -- ltrim -- http://snippets.luacode.org/sputnik.lua?p=snippets/trim_whitespace_from_string_76 local trim = stringx.lstrip asserteq(T(trim''), T'') asserteq(T(trim' '), T'') asserteq(T(trim' '), T'') asserteq(T(trim'a'), T'a') asserteq(T(trim' a'), T'a') asserteq(T(trim'a '), T'a ') asserteq(T(trim' a '), T'a ') asserteq(T(trim' a '), T'a ') asserteq(T(trim' ab cd '), T'ab cd ') asserteq(T(trim' \t\r\n\f\va\000b \r\t\n\f\v'), T'a\000b \r\t\n\f\v') -- more -- rtrim -- http://snippets.luacode.org/sputnik.lua?p=snippets/trim_whitespace_from_string_76 local trim = stringx.rstrip asserteq(T(trim''), T'') asserteq(T(trim' '), T'') asserteq(T(trim' '), T'') asserteq(T(trim'a'), T'a') asserteq(T(trim' a'), T' a') asserteq(T(trim'a '), T'a') asserteq(T(trim' a '), T' a') asserteq(T(trim' a '), T' a') asserteq(T(trim' ab cd '), T' ab cd') asserteq(T(trim' \t\r\n\f\va\000b \r\t\n\f\v'), T' \t\r\n\f\va\000b') -- more -- trim -- http://snippets.luacode.org/sputnik.lua?p=snippets/trim_whitespace_from_string_76 local trim = stringx.strip asserteq(T(trim''), T'') asserteq(T(trim' '), T'') asserteq(T(trim' '), T'') asserteq(T(trim'a'), T'a') asserteq(T(trim' a'), T'a') asserteq(T(trim'a '), T'a') asserteq(T(trim' a '), T'a') asserteq(T(trim' a '), T'a') asserteq(T(trim' ab cd '), T'ab cd') asserteq(T(trim' \t\r\n\f\va\000b \r\t\n\f\v'), T'a\000b') local long = 'a' .. string.rep(' ', 200000) .. 'a' asserteq(T(trim(long)), T(long)) -- more asserteq({stringx.splitv("hello dolly")}, {"hello", "dolly"}) -- partition -- as per str.partition in Python, delimiter must be non-empty; -- interpreted as a plain string --asserteq(T(stringx.partition('', '')), T('', '', '')) -- error]] --asserteq(T(stringx.partition('a', '')), T('', '', 'a')) --error]] asserteq(T(stringx.partition('a', 'a')), T('', 'a', '')) asserteq(T(stringx.partition('abc', 'b')), T('a', 'b', 'c')) asserteq(T(stringx.partition('abc', '.+')), T('abc','','')) asserteq(T(stringx.partition('a,b,c', ',')), T('a',',','b,c')) asserteq(T(stringx.partition('abc', '/')), T('abc', '', '')) -- rpartition asserteq(T(stringx.rpartition('a/b/c', '/')), T('a/b', '/', 'c')) asserteq(T(stringx.rpartition('abc', 'b')), T('a', 'b', 'c')) asserteq(T(stringx.rpartition('a', 'a')), T('', 'a', '')) asserteq(T(stringx.rpartition('abc', '/')), T('', '', 'abc')) -- at (works like s:sub(idx,idx), so negative indices allowed asserteq(T(stringx.at('a', 1)), T('a')) asserteq(T(stringx.at('ab', 2)), T('b')) asserteq(T(stringx.at('abcd', -1)), T('d')) asserteq(T(stringx.at('abcd', 10)), T('')) -- not found -- lines local function merge(it, ...) assert(select('#', ...) == 0) local ts = {} for val in it do ts[#ts+1] = val end return ts end asserteq(merge(stringx.lines('')), {''}) asserteq(merge(stringx.lines('ab')), {'ab'}) asserteq(merge(stringx.lines('ab\ncd')), {'ab', 'cd'}) asserteq(stringx.capitalize("hello world"), "Hello World") asserteq(stringx.title("hello world"), "Hello World") -- shorten -- The returned string is always equal or less to the given size. asserteq(T(stringx.shorten('', 0)), T'') asserteq(T(stringx.shorten('a', 1)), T'a') asserteq(T(stringx.shorten('ab', 1)), T'.') --FIX:ok? asserteq(T(stringx.shorten('abc', 3)), T'abc') asserteq(T(stringx.shorten('abcd', 3)), T'...') asserteq(T(stringx.shorten('abcde', 5)), T'abcde') asserteq(T(stringx.shorten('abcde', 4)), T'a...') asserteq(T(stringx.shorten('abcde', 3)), T'...') asserteq(T(stringx.shorten('abcde', 2)), T'..') asserteq(T(stringx.shorten('abcde', 0)), T'') asserteq(T(stringx.shorten('', 0, true)), T'') asserteq(T(stringx.shorten('a', 1, true)), T'a') asserteq(T(stringx.shorten('ab', 1, true)), T'.') asserteq(T(stringx.shorten('abcde', 5, true)), T'abcde') asserteq(T(stringx.shorten('abcde', 4, true)), T'...e') asserteq(T(stringx.shorten('abcde', 3, true)), T'...') asserteq(T(stringx.shorten('abcde', 2, true)), T'..') asserteq(T(stringx.shorten('abcde', 0, true)), T'') -- strip asserteq(stringx.strip(' hello '),'hello') asserteq(stringx.strip('--[hello] -- - ','-[] '),'hello') asserteq(stringx.rstrip('--[hello] -- - ','-[] '),'--[hello') asserteq(stringx.strip('hello'..((" "):rep(500))), "hello") -- local assert_str_round_trip = function(s) local qs = stringx.quote_string(s) local compiled, err = utils.load("return "..qs) if not compiled then print( ("stringx.quote_string assert failed: invalid string created: Received:\n%s\n\nCompiled to\n%s\n\nError:\t%s\n"): format(s, qs, err) ) error() else compiled = compiled() end if compiled ~= s then print("stringx.quote_string assert Failed: String compiled but did not round trip.") print("input string:\t\t",s, #s) print("compiled string:\t", compiled, #compiled) print("output string:\t\t",qs, #qs) error() else -- print("input string:\t\t",s) -- print("compiled string:\t", compiled) -- print("output string:\t\t",qs) end end assert_str_round_trip( "normal string with nothing weird.") assert_str_round_trip( "Long string quoted with escaped quote \\\" and a long string pattern match [==[ found near the end.") assert_str_round_trip( "Unescapped quote \" in the middle") assert_str_round_trip( "[[Embedded long quotes \\\". Escaped must stay! ]]") assert_str_round_trip( [[Long quoted string with a slash prior to quote \\\". ]]) assert_str_round_trip( "[[Completely normal\n long quote. ]]") assert_str_round_trip( "String with a newline\nending with a closing bracket]") assert_str_round_trip( "[[String with opening brackets ending with part of a long closing bracket]=") assert_str_round_trip( "\n[[Completely normal\n long quote. Except that we lead with a return! Tricky! ]]") assert_str_round_trip( '"balance [======[ doesn\'t ]====] mater when searching for embedded long-string quotes.') assert_str_round_trip( "Any\0 \t control character other than a return will be handled by the %q mechanism.") assert_str_round_trip( "This\tincludes\ttabs.") assert_str_round_trip( "But not returns.\n Returns are easier to see using long quotes.") assert_str_round_trip( "The \z escape does not trigger a control pattern, however.") assert_str_round_trip( "[==[If a string is long-quoted, escaped \\\" quotes have to stay! ]==]") assert_str_round_trip('"A quoted string looks like what?"') assert_str_round_trip( "'I think that it should be quoted, anyway.'") assert_str_round_trip( "[[Even if they're long quoted.]]") assert_str_round_trip( "]=]==]") assert_str_round_trip( "\"\\\"\\' pathalogical:starts with a quote ]\"\\']=]]==][[]]]=========]") assert_str_round_trip( "\\\"\\\"\\' pathalogical: quote is after this text with a quote ]\"\\']=]]==][[]]]=========]") assert_str_round_trip( "\\\"\\\"\\' pathalogical: quotes are all escaped. ]\\\"\\']=]]==][[]]]=========]") assert_str_round_trip( "") assert_str_round_trip( " ") assert_str_round_trip( "\n") --tricky. assert_str_round_trip( "\r") assert_str_round_trip( "\r\n") assert_str_round_trip( "\r1\n") assert_str_round_trip( "[[") assert_str_round_trip( "''") assert_str_round_trip( '""')
stevedonovan/Penlight
tests/test-stringx.lua
Lua
mit
15,082
@extends('templatePetugas') @section('content') <!-- ********************************************************************************************************************************************************** MAIN SIDEBAR MENU *********************************************************************************************************************************************************** --> <!--sidebar start--> <aside> <div id="sidebar" class="nav-collapse "> <!-- sidebar menu start--> <ul class="sidebar-menu" id="nav-accordion"> <p class="centered"><img src="{{asset('img/ui-sam.jpg')}}" class="img-circle" width="60"></p> <h5 class="centered"><?php echo Session::get('name')?></h5> <li class="mt"> <a href="{{url('petugas')}}"> <i class="fa fa-dashboard"></i> <span>Dashboard</span> </a> </li> <li class="sub-menu"> <a href="{{url('viewScheduleSelf')}}" > <i class="fa fa-calendar"></i> <span>Jadwal</span> </a> </li> <li class="sub-menu"> <a class="active" href="{{url('isiVolume')}}" > <i class="fa fa-download"></i> <span>Volume</span> </a> </li> </ul> <!-- sidebar menu end--> </div> </aside> <!--sidebar end--> <!-- MAIN CONTENT --> <!-- ********************************************************************************************************************************************************** MAIN CONTENT *********************************************************************************************************************************************************** --> <!--main content start--> <section id="main-content"> <section class="wrapper site-min-height"> <h3><i class="fa fa-angle-right"></i><a href="{{url('petugas')}}">Dashboard</a> / Isi Volume</h3> <div class="row mt"> <div class="col-md-12"> <form method="post" name="formVolume"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="editModalLabel">Isi Volume</h4> </div> <div class="modal-body"> <input name="_token" hidden value="{!! csrf_token() !!}" /> <div class="form-group"> <label for="recipient-name" class="control-label">Nama TPS/TPA:</label> <select name="lokasi" class="form-control"> <option value="" selected disabled>Lokasi</option> <optgroup label="---TPA---"></optgroup> @foreach ($tpa as $tpaElement) <option>{{$tpaElement->nama}}</option> @endforeach <optgroup label="---TPS---"></optgroup> @foreach ($tps as $tpsElement) <option>{{$tpsElement->nama}}</option> @endforeach </select> </div> <div class="form-group"> <label for="recipient-name" class="control-label">Volume TPS/TPA:</label> <input type="text" class="form-control" id="recipient-name" name="volume" placeholder="<?php echo Session::get('volumeTPA')?>"> </div> </div> <div class="modal-footer"> <button type="reset" class="btn btn-default" data-dismiss="modal" style="margin-left:0px;">Reset</button> <button type="submit" class="btn btn-default" onclick="return validateForm()">Simpan</button> </div> </div> </form> </div><!-- /col-md-12 --> </div><!-- /row --> </section><!--/wrapper --> </section><!-- /MAIN CONTENT --> <script type="text/javascript"> function validateForm() { var tempat = document.forms["formVolume"]["lokasi"].value; var volume = document.forms["formVolume"]["volume"].value; if (tempat=="") { //kasus tempat salah if (volume=="" || volume==null) { alert("Input tempat dan volume tidak boleh kosong!"); } else { alert("Input tempat tidak boleh kosong!"); } return false; } else { //kasus tempat benar if (volume < 0) { alert("Input volume tidak boleh negatif!"); return false; } else if (volume=="" || volume==null) { alert("Input volume tidak boleh kosong!"); } } } </script> @endsection
andresusanto/pplforbandung
9sampah/resources/views/formIsiVolume.blade.php
PHP
mit
5,571
$(document).ready(function() { // <editor-fold defaultstate="collapsed" desc="Fonctions globales"> function addAjaxLoading(element, id) { var loadingImage = $('#loading-image-path').attr('value'); element.parent('div').append('<img id="' + id + '" src="' + loadingImage + '" alt="loading" />'); } function eraseLocal() { document.getElementById("caesar_resourceBundle_resourceType_local").value = ""; } function eraseURL() { document.getElementById("caesar_resourceBundle_resourceType_url").value = ""; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Chargement de l'image"> function handleFileSelect(evt) { var files = evt.target.files; // FileList object // Loop through the FileList and render image files as thumbnails. for (var i = 0, f; i < files.length; i++) { f = files[i]; // Only process image files. if (!f.type.match('image.*')) { continue; } var reader = new FileReader(); // Closure to capture the file information. reader.onload = (function(theFile) { return function(e) { // Render thumbnail. var img = document.getElementById('resource-img'); img.src = e.target.result; document.getElementById('caesar_resourceBundle_resourceType_path').value = e.target.result; img.title = escape(theFile.name); }; })(f); // Read in the image file as a data URL. reader.readAsDataURL(f); } } document.getElementById('caesar_resourceBundle_resourceType_local').addEventListener('change', handleFileSelect, false); document.getElementById("caesar_resourceBundle_resourceType_url").addEventListener('click', eraseURL); document.getElementById('apply-image').addEventListener('click', function() { var a = document.getElementById('caesar_resourceBundle_resourceType_url'); eraseLocal(); var img = document.getElementById('resource-img'); img.src = a.value; document.getElementById('caesar_resourceBundle_resourceType_path').value = a.value; }, false); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Webmining"> var webmining = false; var disabled = false; function isWebminingPossible() { var code = $('.resource-code').val(); if (code === "" || !isValidIsbn(code)) { disabled = true; $("a.web-mining-button").removeClass("bubble-button"); $("a.web-mining-button").addClass("disabled-webmining-button"); } else { $("a.web-mining-button").addClass("bubble-button"); $("a.web-mining-button").removeClass("disabled-webmining-button"); disabled = false; } } $('.resource-code').keyup(isWebminingPossible); isWebminingPossible(); //On cache la fenêtre modale si on appuie sur le bouton close. $(".btn").click(function(e) { $("#modal").removeClass("modal-visible"); e.preventDefault(); return false; }); $('.web-mining-button').hover(function() { if (!$('a.web-mining-button').hasClass('disabled-webmining-button')) { $(".web-mining-to-color").addClass('notify-web-mining'); $(".web-mining-to-color").removeClass('unnotify-web-mining'); } }, function() { $(".web-mining-to-color").removeClass('notify-web-mining'); $(".web-mining-to-color").addClass('unnotify-web-mining'); }); $("a.web-mining-button").on('click.webmining', function(e) { if (webmining || disabled) { return; } webmining = true; addAjaxLoading($('a.web-mining-button'), 'loading-webmining'); $("a.web-mining-button").addClass("disabled-webmining-button"); $("a.web-mining-button").removeClass("bubble-button"); var url = $('.webmining-url').attr('value'); url += '/' + $('.resource-code').val(); $.ajax({ type: "POST", url: url, cache: false, success: function(json) { var resource = JSON && JSON.parse(json) || $.parseJSON(json); if (resource.description.length === 0) { $(".web-mining-image-url").attr('value', ""); $(".web-mining-description").val(""); $("#modal").addClass("modal-visible"); } else { $(".web-mining-image-url").attr('value', resource.image); $(".web-mining-description").val(resource.description); } $(".web-mining-long-description").text(resource.longDescription.replace(/\\r\\n/g, '\r\n')); $("a.web-mining-button").removeClass("disabled-webmining-button"); $("a.web-mining-button").addClass("bubble-button"); if ($('#apply-image').attr('value') !== "") { $('#apply-image').click(); } else { document.getElementById('caesar_resourceBundle_resourceType_path').value = ""; } $('#loading-webmining').remove(); webmining = false; }, error: function() { $("a.web-mining-button").removeClass("disabled-webmining-button"); $("a.web-mining-button").addClass("bubble-button"); $('#loading-webmining').remove(); webmining = false; } }); e.preventDefault(); return false; }); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Skeleton"> $("#clearSkeleton").on('click', function(e) { var url = $('.empty-skeleton-url').attr('value'); $.ajax({ type: "POST", url: url, cache: false, success: function(skeleton) { $(".web-mining-long-description").text(skeleton.replace(/\\r\\n/g, '\r\n')); } }); e.preventDefault(); return false; }); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Chargement description emplacement"> var onChange = false; $("select.shelf-selection").change(function(e) { if (!onChange) { onChange = true; addAjaxLoading($('.shelf-selection'), 'loading-description'); var url = $('.shelf-description-url').attr('value'); url += '/' + $(this).find(":selected").attr('value'); $.ajax({ type: "POST", url: url, cache: false, success: function(data) { $('.shelf-description').html(data); $('.shelf-description').css('display', 'block'); $('#loading-description').remove(); onChange = false; }, error: function(xhr, ajaxOptions, thrownError) { $('.shelf-description').css('display', 'none'); $('#loading-description').remove(); onChange = false; } }); } e.preventDefault(); return false; }); // </editor-fold> });
omegas27/CAeSAR
web/js/adminResources.js
JavaScript
mit
7,461
--- layout: post category : reading notes title: "unix环境高级编程" tagline: "" tags : [apue, unix] ---
zswood/zswood.github.io
_posts/书籍笔记/unix环境高级编程.md
Markdown
mit
115
<!DOCTYPE html> <html lang="sv"> <head> <meta charset="utf-8" /> <title>jkw at internet</title> <link rel="stylesheet" href="/theme/css/main.css" /> <!--[if IE]> <script src="https://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body id="index" class="home"> <header id="banner" class="body"> <h1><a href="/">jkw at internet </a></h1> <nav><ul> <li><a href="/p/about">About</a></li> <li><a href="/p/computer-setup">Computer Setup</a></li> </ul></nav> </header><!-- /#banner --> <section id="content" class="body"> <h1>Archives for 27 maj 2018</h1> <dl> <dt>sön 27 maj 2018</dt> <dd><a href="/a/180527-urgh.html">Urgh...</a></dd> </dl> </section> <section id="extras" class="body"> <div class="blogroll"> <h2>links</h2> <ul> <li><a href="https://python.org">Python</a></li> <li><a href="https://getpelican.com">Pelican</a></li> </ul> </div><!-- /.blogroll --> <div class="social"> <h2>social</h2> <ul> <li><a href="https://github.com/jkw">Github</a></li> <li><a href="https://hashnode.com/@jkw">Hashnode</a></li> <li><a href="https://gitlab.com/jkw">GitLab</a></li> </ul> </div><!-- /.social --> </section><!-- /#extras --> <footer id="contentinfo" class="body"> <address id="about" class="vcard body"> Proudly powered by <a href="http://getpelican.com/">Pelican</a>, which takes great advantage of <a href="http://python.org">Python</a>. </address><!-- /#about --> <p>The theme is by <a href="http://coding.smashingmagazine.com/2009/08/04/designing-a-html-5-layout-from-scratch/">Smashing Magazine</a>, thanks!</p> </footer><!-- /#contentinfo --> </body> </html>
jkw/jkw.github.io
d/27.html
HTML
mit
2,209
<!DOCTYPE html> <?php /** * @var \Spiral\Debug\Snapshot $snapshot * @var \Spiral\Core\ContainerInterface $container * @var \Spiral\Debug\Debugger $debugger */ $highlighter = new \Spiral\Tokenizer\Hightligher( $container->get(\Spiral\Tokenizer\TokenizerInterface::class), [ 'styles' => [ 'color: #C26230; font-weight: bold;' => [ T_STATIC, T_PUBLIC, T_PRIVATE, T_PROTECTED, T_CLASS, T_NEW, T_FINAL, T_ABSTRACT, T_IMPLEMENTS, T_CONST, T_ECHO, T_CASE, T_FUNCTION, T_GOTO, T_INCLUDE, T_INCLUDE_ONCE, T_REQUIRE, T_REQUIRE_ONCE, T_VAR, T_INSTANCEOF, T_INTERFACE, T_THROW, T_ARRAY, T_IF, T_ELSE, T_ELSEIF, T_TRY, T_CATCH, T_CLONE, T_WHILE, T_FOR, T_DO, T_UNSET, T_FOREACH, T_RETURN, T_EXIT, T_EXTENDS ], 'color: black; font: weight: bold;' => [ T_OPEN_TAG, T_CLOSE_TAG, T_OPEN_TAG_WITH_ECHO ], 'color: #BC9458;' => [ T_COMMENT, T_DOC_COMMENT ], 'color: #A5C261;' => [ T_CONSTANT_ENCAPSED_STRING, T_ENCAPSED_AND_WHITESPACE, T_DNUMBER, T_LNUMBER ], 'color: #D0D0FF;' => [ T_VARIABLE ] ] ]); $dumper = new \Spiral\Debug\Dumper($container->get(\Spiral\Debug\Debugger::class), [ 'container' => '<pre style="background-color: #232323; font-family: Monospace;">{dump}</pre>', 'styles' => [ 'common' => '#E6E1DC', 'name' => '#E6E1DC', 'indent' => 'gray', 'indent-(' => '#E6E1DC', 'indent-)' => '#E6E1DC', 'recursion' => '#ff9900', 'value-string' => '#A5C261', 'value-integer' => '#A5C261', 'value-double' => '#A5C261', 'value-boolean' => '#C26230; font-weight: bold;', 'type' => '#E6E1DC', 'type-object' => '#E6E1DC', 'type-array' => '#C26230;', 'type-null' => '#C26230;', 'type-resource' => '#color: #C26230;', 'access' => '#666', 'access-public' => '#8dc17d', 'access-private' => '#c18c7d', 'access-protected' => '#7d95c1' ] ]); $dumps = []; /** * Format arguments and create data dumps. * * @param array $arguments * @return array */ $argumenter = function (array $arguments) use ($dumper, &$dumps) { $result = []; foreach ($arguments as $argument) { $display = $type = strtolower(gettype($argument)); if (is_numeric($argument)) { $result[] = $dumper->style($argument, 'value', $type); continue; } elseif (is_bool($argument)) { $result[] = $dumper->style($argument ? 'true' : 'false', 'value', $type); continue; } elseif (is_null($argument)) { $result[] = $dumper->style('null', 'value', $type); continue; } if (is_object($argument)) { $reflection = new ReflectionClass($argument); $display = interpolate( "<span title=\"{title}\">{class}</span>", [ 'title' => $reflection->getName(), 'class' => $reflection->getShortName() ] ); } //Colorizing $display = $dumper->style($display, 'value', $type); if (($dumpID = array_search($argument, $dumps)) === false) { $dumps[] = $dumper->dump($argument, \Spiral\Debug\Dumper::OUTPUT_RETURN); $dumpID = count($dumps) - 1; } $display = interpolate( "<span onclick=\"_da({dumpID})\">{display}</span>", compact('display', 'dumpID') ); $result[] = $display; } return $result; } ?> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title> <?= $snapshot->getMessage() ?> </title> <style> body.spiral-exception { font-family: Helvetica, sans-serif; background-color: #e0e0e0; font-size: 14px; padding: 5px; color: #a1a1a1; } .spiral-exception .wrapper { padding: 5px; box-shadow: 0 0 10px rgba(0, 0, 0, .7); background-color: #3a3a3a; } .spiral-exception .wrapper strong { font-weight: bold; } .spiral-exception .wrapper i { font-style: italic; } .spiral-exception .dump { padding: 5px; background-color: #232323; margin-top: 0; display: none; overflow-x: auto; } .spiral-exception .wrapper .header { margin-bottom: 5px; background: #d34646; border: 2px solid #d34646; padding: 8px 13px 8px 18px; color: #fff; box-shadow: inset 0 0 8px rgba(0, 0, 0, .2); } .spiral-exception .wrapper .stacktrace { display: inline-block; width: 100%; } .spiral-exception .wrapper .stacktrace .trace { font-family: Monospace; float: left; width: 60%; } .spiral-exception .wrapper .stacktrace .trace .container { padding: 15px; background-color: #2e2e2e; margin-bottom: 5px; overflow-x: auto; box-shadow: inset 0 0 20px rgba(0, 0, 0, .2); } .spiral-exception .wrapper .stacktrace .trace .container.no-trace { color: #6bbdff; } .spiral-exception .wrapper .stacktrace .trace .container.no-trace .arguments span { cursor: pointer; } .spiral-exception .wrapper .stacktrace .trace .container.no-trace .arguments span:hover { text-decoration: underline; } .spiral-exception .wrapper .stacktrace .trace .location { color: #6bbdff; margin-bottom: 5px; } .spiral-exception .wrapper .stacktrace .trace .location .arguments span:hover { text-decoration: underline; cursor: pointer; } .spiral-exception .wrapper .stacktrace .trace .location em { color: #a1a1a1; font-style: normal; } .spiral-exception .wrapper .stacktrace .trace .lines div { white-space: pre; color: #E6E1DC; } .spiral-exception .wrapper .stacktrace .trace .lines div .number { display: inline-block; width: 50px; color: #757575; } .spiral-exception .wrapper .stacktrace .trace .lines div:hover { background-color: #404040; } .spiral-exception .wrapper .stacktrace .trace .lines div.highlighted { background-color: #404040; } .spiral-exception .wrapper .stacktrace .chain { width: 40%; float: right; } .spiral-exception .wrapper .stacktrace .chain .calls { padding: 10px 10px 10px 10px; margin-left: 5px; background-color: #2e2e2e; margin-bottom: 5px; overflow-x: auto; box-shadow: inset 0 0 20px rgba(0, 0, 0, .2); } .spiral-exception .wrapper .stacktrace .chain .call .function { font-size: 11px; color: #6bbdff; } .spiral-exception .wrapper .stacktrace .chain .call .function .arguments span { cursor: pointer; } .spiral-exception .wrapper .stacktrace .chain .call .function .arguments span:hover { text-decoration: underline; } .spiral-exception .wrapper .stacktrace .chain .call .location { margin-bottom: 10px; font-size: 10px; } .spiral-exception .wrapper .stacktrace .chain .dumper { padding-left: 5px; padding-bottom: 5px; display: none; } .spiral-exception .wrapper .stacktrace .chain .dumper .close { text-align: right; padding: 2px; color: #fff; cursor: pointer; font-size: 12px; background-color: #232323; } .spiral-exception .wrapper .stacktrace .chain .dumper .close:hover { background-color: #2c2c2c; } .spiral-exception .wrapper .environment .container { margin-bottom: 9px; } .spiral-exception .wrapper .environment .title, .spiral-exception .wrapper .messages .title { padding: 10px 10px 10px 5px; background-color: #e7c35e; font-weight: bold; color: #444; cursor: pointer; } .spiral-exception .wrapper .messages { margin-bottom: 5px; } .spiral-exception .wrapper .messages .data { display: none; background-color: #2e2e2e; } .spiral-exception .wrapper .messages .data .message { padding: 5px; color: #fff; } .spiral-exception .wrapper .messages .data .message:nth-child(2n) { background-color: #2e2e2e; } .spiral-exception .wrapper .messages .data .message .channel { display: inline-block; font-weight: bold; width: 200px; float: left; } .spiral-exception .wrapper .messages .data .message .level { display: inline-block; font-weight: bold; width: 70px; float: left; text-transform: uppercase; } .spiral-exception .wrapper .messages .data .message .body { margin-left: 200px; unicode-bidi: embed; white-space: pre; } .spiral-exception .wrapper .messages .data .message:hover { background-color: #1e1e1e; } .spiral-exception .wrapper .messages .data .message.warning, .spiral-exception .wrapper .messages .data .message.notice { background-color: #2e2e25; } .spiral-exception .wrapper .messages .data .message.error { background-color: #2e0e16; } .spiral-exception .wrapper .messages .data .message.critical, .spiral-exception .wrapper .messages .data .message.alert, .spiral-exception .wrapper .messages .data .message.emergency { background-color: #4c001f; } .spiral-exception .wrapper .footer { margin-top: 10px; margin-bottom: 5px; font-size: 12px; } .spiral-exception .wrapper .footer .date { color: #fafafa; } </style> <script type="text/javascript"> function toggle(id) { var block = document.getElementById(id); block.style.display = (block.style.display == 'none' ? 'block' : 'none'); } function _da(id) { var dump = document.getElementById('argument-dumper'); dump.style.display = 'block'; dump.innerHTML = '<div class="close" onclick="toggle(\'argument-dumper\')"> &cross; close</div> ' + '<div class="dump" style="display: block">' + document.getElementById('argument-' + id).innerHTML + '</div>'; window.location.href = "#dump-top"; } </script> </head> <body class="spiral-exception"> <a name="dump-top"></a> <div class="wrapper"> <a name="dump-top"></a> <div class="header"> <?= $snapshot->getClass() ?>: <strong title="You have to catch them all!"><?= $snapshot->getException()->getMessage() ?></strong> in <i><?= $snapshot->getFile() ?></i> at <strong>line <?= $snapshot->getLine() ?></strong> </div> <div class="stacktrace"> <div class="trace"> <?php $stacktrace = $snapshot->getTrace(); //Let's let's clarify exception location $header = [ 'file' => $snapshot->getFile(), 'line' => $snapshot->getLine() ] + $stacktrace[0]; if ($stacktrace[0] != $header) { array_unshift($stacktrace, $header); } //If endpoint was described $endpoint = false; foreach ($stacktrace as $trace) { $arguments = []; if (isset($trace['args'])) { $arguments = $argumenter($trace['args']); } $function = '<strong>' . $trace['function'] . '</strong>'; if (isset($trace['type']) && isset($trace['class'])) { $reflection = new ReflectionClass($trace['class']); $function = interpolate( "<span title=\"{title}\">{class}</span>{type}{function}", [ 'title' => $reflection->getName(), 'class' => $reflection->getShortName(), 'type' => $trace['type'], 'function' => $function ] ); } if (!isset($trace['file'])) { ?> <div class="container no-trace"> <?= $function ?>(<span class="arguments"><? echo join(', ', $arguments) ?></span>) </div> <?php continue; } ?> <div class="container"> <div class="location"> <?= $function ?>(<span class="arguments"><? echo join(', ', $arguments) ?></span>) <em> In <?= $trace['file'] ?> at <strong>line <?= $trace['line'] ?></strong> </em> </div> <div class="lines"> <?= $highlighter->highlight($trace['file'], $trace['line']) ?> </div> </div> <?php } ?> </div> <div class="chain"> <div class="dumper" id="argument-dumper"></div> <div class="calls"> <?php $stacktrace = array_reverse($stacktrace); foreach ($stacktrace as $index => $trace) { if (empty($trace['file']) && isset($stacktrace[$index - 1]['file'])) { $trace['file'] = $stacktrace[$index - 1]['file']; $trace['line'] = $stacktrace[$index - 1]['line']; } if (!isset($stacktrace[$index + 1])) { $trace['file'] = $snapshot->getFile(); $trace['line'] = $snapshot->getLine(); } if (!isset($trace['function'])) { continue; } $function = '<strong>' . $trace['function'] . '</strong>'; if (isset($trace['type']) && isset($trace['class'])) { $reflection = new ReflectionClass($trace['class']); $function = interpolate( "<span title=\"{title}\">{class}</span>{type}{function}", [ 'title' => $reflection->getName(), 'class' => $reflection->getShortName(), 'type' => $trace['type'], 'function' => $function ] ); } $arguments = []; if (isset($trace['args'])) { $arguments = $argumenter($trace['args']); } ?> <div class="call"> <div class="function"> <?= $function ?>(<span class="arguments"><? echo join(', ', $arguments) ?></span>) </div> <div class="location"> <i><?= $trace['file'] ?></i> at <strong>line <?= $trace['line'] ?></strong> </div> </div> <?php } ?> </div> </div> </div> <div class="environment"> <?php $variables = [ 'GET' => '_GET', 'POST' => '_POST', 'COOKIES' => '_COOKIE', 'SESSION' => '_SESSION', 'SERVER' => '_SERVER', ]; foreach ($variables as $name => $variable) { if (!empty($GLOBALS[$variable])) { if ($name == 'SERVER' && isset($_SERVER['PATH']) && is_string($_SERVER['PATH'])) { $_SERVER['PATH'] = explode(PATH_SEPARATOR, $_SERVER['PATH']); } ?> <div class="container"> <div class="title" onclick="toggle('environment-<?= $name ?>')"> <?= $name ?> (<?= number_format(count($GLOBALS[$variable])) ?>) </div> <div class="dump" id="environment-<?= $name ?>" style="display: none;"> <?= $dumper->dump($GLOBALS[$variable], \Spiral\Debug\Dumper::OUTPUT_RETURN) ?> </div> </div> <?php } } ?> </div> <?php if (!empty($messages = $debugger->globalMessages())) { ?> <div class="messages"> <div class="title" onclick="toggle('logger-messages')"> Logger Messages (<?= number_format(count($messages)) ?>) </div> <div class="data" id="logger-messages" style="display: none;"> <?php foreach ($messages as $message) { $channel = $message[\Spiral\Debug\Logger::MESSAGE_CHANNEL]; if (class_exists($channel)) { $reflection = new ReflectionClass($channel); $channel = $reflection->getShortName(); } ?> <div class="message <?= $message[\Spiral\Debug\Logger::MESSAGE_LEVEL] ?>"> <div class="channel" title=" <?= $message[\Spiral\Debug\Logger::MESSAGE_CHANNEL] ?>"> <?= $channel ?> </div> <div class="level"><?= $message[\Spiral\Debug\Logger::MESSAGE_LEVEL] ?></div> <div class="body"><?= $message[\Spiral\Debug\Logger::MESSAGE_BODY] ?></div> </div> <?php } ?> </div> </div> <?php } ?> <div class="footer"> <div class="date"><?= date('r') ?></div> <div class="elapsed time"> <span>Elapsed:</span> <?= number_format(microtime(true) - SPIRAL_INITIAL_TIME, 3) ?> seconds </div> <div class="elapsed memory"> <span>Memory:</span> <?= number_format(memory_get_peak_usage() / 1024, 2) ?> Kb </div> </div> <?php foreach ($dumps as $argumentID => $dump) { echo "<div id=\"argument-{$argumentID}\" style=\"display: none\">{$dump}</div>"; } ?> </div> </body> </html>
jwdeitch/spiral
source/views/exception.php
PHP
mit
20,697
<!DOCTYPE html> <html lang="en"> <head> <!--5ETOOLS_CMP--> <!--5ETOOLS_ANALYTICS--> <!--5ETOOLS_ADCODE--> <meta charset="utf-8"> <meta name="description" content=""> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="apple-mobile-web-app-capable" content="yes"> <title>Races - 5etools</title> <link rel="stylesheet" href="css/bootstrap.css"> <link rel="stylesheet" href="css/main.css"> <!-- Favicons --> <link rel="icon" type="image/svg+xml" href="favicon.svg?v=1.115"> <link rel="icon" type="image/png" sizes="256x256" href="favicon-256x256.png"> <link rel="icon" type="image/png" sizes="144x144" href="favicon-144x144.png"> <link rel="icon" type="image/png" sizes="128x128" href="favicon-128x128.png"> <link rel="icon" type="image/png" sizes="64x64" href="favicon-64x64.png"> <link rel="icon" type="image/png" sizes="48x48" href="favicon-48x48.png"> <link rel="icon" type="image/png" sizes="32x32" href="favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="favicon-16x16.png"> <!-- Chrome Web App Icons --> <link rel="manifest" href="manifest.webmanifest"> <meta name="application-name" content="5etools"> <meta name="theme-color" content="#006bc4"> <!-- Windows Start Menu tiles --> <meta name="msapplication-config" content="browserconfig.xml"/> <meta name="msapplication-TileColor" content="#006bc4"> <!-- Apple Touch Icons --> <link rel="apple-touch-icon" sizes="180x180" href="apple-touch-icon-180x180.png"> <link rel="apple-touch-icon" sizes="360x360" href="apple-touch-icon-360x360.png"> <link rel="apple-touch-icon" sizes="167x167" href="apple-touch-icon-167x167.png"> <link rel="apple-touch-icon" sizes="152x152" href="apple-touch-icon-152x152.png"> <link rel="apple-touch-icon" sizes="120x120" href="apple-touch-icon-120x120.png"> <meta name="apple-mobile-web-app-title" content="5etools"> <!-- macOS Safari Pinned Tab and Touch Bar --> <link rel="mask-icon" href="safari-pinned-tab.svg" color="#006bc4"> <script>if ("serviceWorker" in navigator) navigator.serviceWorker.register("/sw.js");</script> <script type="text/javascript" src="js/styleswitch.js"></script> <script type="text/javascript" src="js/navigation.js"></script> <script type="text/javascript" src="js/browsercheck.js"></script> </head> <body> <div class="cancer__wrp-sidebar-rhs cancer__anchor"><div class="cancer__disp-cancer"></div><div class="cancer__sidebar-rhs-inner cancer__sidebar-rhs-inner--top"><!--5ETOOLS_AD_RIGHT_1--></div><div class="cancer__sidebar-rhs-inner cancer__sidebar-rhs-inner--bottom"><!--5ETOOLS_AD_RIGHT_2--></div></div> <div class="viewport-wrapper"> <div class="cancer__wrp-leaderboard cancer__anchor"><div class="cancer__disp-cancer"></div><div class="cancer__wrp-leaderboard-inner"><!--5ETOOLS_AD_LEADERBOARD--></div></div> <header class="hidden-xs hidden-sm page__header"> <div class="container"> <h1 class="page__title">Races</h1> <p class="page__subtitle">Search by name on the left, click race name to display on the right.</p> </div> </header> <nav class="container page__nav" id="navigation"> <ul class="nav page__nav-inner" id="navbar"></ul> </nav> <div class="view-col-group--cancer h-100 mh-0"> <div class="container view-col-wrapper view-col-wrapper--cancer"> <div class="view-col" id="listcontainer"> <div class="lst__form-top" id="filter-search-group"> <div class="w-100 relative"> <input type="search" id="lst__search" autocomplete="off" autocapitalize="off" spellcheck="false" class="search form-control lst__search lst__search--no-border-h"> <div id="lst__search-glass" class="lst__wrp-search-glass no-events flex-vh-center"><span class="glyphicon glyphicon-search"></span></div> <div class="lst__wrp-search-visible no-events flex-vh-center"></div> </div> <button class="btn btn-default" id="reset">Reset</button> </div> <div id="filtertools" class="input-group input-group--bottom flex no-shrink"> <button class="col-4 sort btn btn-default btn-xs" data-sort="name">Name <span class="caret_wrp"></span></button> <button class="col-4 sort btn btn-default btn-xs" data-sort="ability">Ability <span class="caret_wrp"></span></button> <button class="col-2 sort btn btn-default btn-xs" data-sort="size">Size <span class="caret_wrp"></span></button> <button class="sort btn btn-default btn-xs ve-grow" data-sort="source">Source <span class="caret_wrp"></span></button> </div> <div class="list list--stats races"></div> </div> <div class="cancer__wrp-mobile-1 cancer__anchor"><div class="cancer__disp-cancer"></div><!--5ETOOLS_AD_MOB_PLAYER_1--></div> <div id="contentwrapper" class="view-col"> <div id="sublistcontainer" class="sublist sublist--resizable"> <div id="sublistsort" class="btn-group sublist__wrp-cols"> <button class="col-5 sort btn btn-default btn-xs" data-sort="name">Name <span class="caret_wrp"></span></button> <button class="col-5 sort btn btn-default btn-xs" data-sort="ability">Ability <span class="caret_wrp"></span></button> <button class="col-2 sort btn btn-default btn-xs" data-sort="size">Size <span class="caret_wrp"></span></button> </div> <div class="list list--stats subraces"> <!-- populate with JS --> </div> </div> <div class="wrp-stat-tab" id="stat-tabs"> <div id="tabs-right"></div> </div> <div class="wrp-stats-table"> <table id="pagecontent" class="stats"> <tr><th class="border" colspan="6"></th></tr> <tr><td colspan="6" class="initial-message">Select a race from the list to view it here</td></tr> <tr><th class="border" colspan="6"></th></tr> </table> </div> <div class="text-center mt-2 no-print"> <button class="btn btn-xs btn-info" id="manage-brew">Manage Homebrew</button> </div> </div> </div> </div> </div> <!--5ETOOLS_SCRIPT_ANCHOR--> <!--5ETOOLS_AD_ADHESION--> <script type="text/javascript" src="lib/jquery.js"></script> <script type="text/javascript" src="js/parser.js"></script> <script type="text/javascript" src="js/utils.js"></script> <script type="text/javascript" src="js/utils-list.js"></script> <script type="text/javascript" src="js/utils-ui.js"></script> <script type="text/javascript" src="lib/localforage.js"></script> <script type="text/javascript" src="js/omnidexer.js"></script> <script type="text/javascript" src="js/omnisearch.js"></script> <script type="text/javascript" src="js/filter.js"></script> <script type="text/javascript" src="js/render.js"></script> <script type="text/javascript" src="js/render-dice.js"></script> <script type="text/javascript" src="js/render-races.js"></script> <script type="text/javascript" src="js/scalecreature.js"></script> <script type="text/javascript" src="js/hist.js"></script> <script type="text/javascript" src="js/listpage.js"></script> <script type="text/javascript" src="js/filter-races.js"></script> <script type="text/javascript" src="js/races.js"></script> <script type="text/javascript" src="js/list2.js"></script> <script type="text/javascript" src="lib/elasticlunr.js"></script> </body> </html>
TheGiddyLimit/astranauta.github.io
races.html
HTML
mit
7,224
Remember to amend JSON filename: first char - "_" should be replaced with "." and store the file in user's home directory.
AndrewB82/web-home-automation-remote
Prerequisites/PS4-waker/Reminder.md
Markdown
mit
123
import copySitecoreLibraries from './tasks/copy-sitecore-libraries'; import deploy from './tasks/deploy'; import nugetRestore from './tasks/nuget-restore'; import publishProjects from './tasks/publish-projects'; import publishTDS from './tasks/publish-tds'; export { copySitecoreLibraries, deploy, nugetRestore, publishProjects, publishTDS, };
jscarmona/gulp-ignite-sitecore
src/index.js
JavaScript
mit
355
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>18 --> 19</title> <link href="./../../assets/style.css" rel="stylesheet"> </head> <body> <h2>You have to be fast</h2> <a href="./3c475ff64bd9d9aefe458c5a77aa79d8454da2d5f6a95cd55304f838671e6571.html">Teleport</a> <hr> <a href="./../../about.md">About</a> (Spoilers! ) <script src="./../../assets/md5.js"></script> <script> window.currentLevel = 7; </script> <script src="./../../assets/script.js"></script> </body> </html>
simonmysun/praxis
TAIHAO2019/pub/SmallGame/AsFastAsYouCan2/5ae70ba787da82030cc35888532ca28e69baf8da9a9e68245cf8bc71950292b6.html
HTML
mit
550
'use strict' const path = require('path') const utils = require('./utils') const webpack = require('webpack') const config = require('../config') const merge = require('webpack-merge') const baseWebpackConfig = require('./webpack.base.conf') const CopyWebpackPlugin = require('copy-webpack-plugin') const HtmlWebpackPlugin = require('html-webpack-plugin') const MiniCssExtractPlugin = require("mini-css-extract-plugin") const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin') const VueLoaderPlugin = require("vue-loader/lib/plugin"); const pp = require('../package') const env = process.env.NODE_ENV === 'testing' ? require('../config/test.env') : config.build.env const webpackConfig = merge(baseWebpackConfig, { mode: 'production', module: { rules: utils.styleLoaders({ sourceMap: config.build.productionSourceMap, extract: true }) }, devtool: config.build.productionSourceMap ? '#source-map' : false, output: { path: config.build.assetsRoot, filename: utils.assetsPath('js/[name].[chunkhash].js'), chunkFilename: utils.assetsPath('js/[id].[chunkhash].js'), publicPath: ['/', pp.aliasName, '/'].join('') }, optimization: { // minimize: true, splitChunks: { cacheGroups: { commons: { test: /[\\/]node_modules[\\/]/, name: "vendor", chunks: "all" } } } }, plugins: [ new VueLoaderPlugin(), // http://vuejs.github.io/vue-loader/en/workflow/production.html new webpack.DefinePlugin({ 'process.env': env }), // UglifyJs do not support ES6+, you can also use babel-minify for better treeshaking: https://github.com/babel/minify // new webpack.optimize.UglifyJsPlugin({ // compress: { // warnings: false // }, // sourceMap: true // }), // extract css into its own file new MiniCssExtractPlugin({ filename: utils.assetsPath('css/[name].[contenthash].css'), //utils.assetsPath('css/[name].[contenthash].css') chunkFilename: utils.assetsPath('css/[name].[contenthash].css') }), // Compress extracted CSS. We are using this plugin so that possible // duplicated CSS from different components can be deduped. new OptimizeCSSPlugin({ cssProcessorOptions: { safe: true } }), // generate dist index.html with correct asset hash for caching. // you can customize output by editing /index.html // see https://github.com/ampedandwired/html-webpack-plugin new HtmlWebpackPlugin({ filename: process.env.NODE_ENV === 'testing' ? 'index.html' : config.build.index, template: 'index.html', inject: true, minify: { removeComments: true, collapseWhitespace: true, removeAttributeQuotes: true // more options: // https://github.com/kangax/html-minifier#options-quick-reference }, chunks: ['vendor', 'manifest', 'index'], // necessary to consistently work with multiple chunks via CommonsChunkPlugin chunksSortMode: 'dependency' }), new HtmlWebpackPlugin({ filename: process.env.NODE_ENV === 'testing' ? 'index.html' : config.build.demo, template: 'index.html', inject: true, minify: { removeComments: true, collapseWhitespace: true, removeAttributeQuotes: true // more options: // https://github.com/kangax/html-minifier#options-quick-reference }, chunks: ['vendor', 'manifest', 'demo/index'], // necessary to consistently work with multiple chunks via CommonsChunkPlugin chunksSortMode: 'dependency' }), // keep module.id stable when vender modules does not change new webpack.HashedModuleIdsPlugin(), // split vendor js into its own file // new webpack.optimize.CommonsChunkPlugin({ // name: 'vendor', // minChunks: function (module) { // if(module.resource && (/^.*\.(css|scss)$/).test(module.resource)) { // return false; // } // // any required modules inside node_modules are extracted to vendor // return ( // module.resource && // /\.js$/.test(module.resource) && // module.resource.indexOf( // path.join(__dirname, '../node_modules') // ) === 0 // ) // } // }), // extract webpack runtime and module manifest to its own file in order to // prevent vendor hash from being updated whenever app bundle is updated // new webpack.optimize.CommonsChunkPlugin({ // name: 'manifest', // chunks: ['vendor'] // }), // copy custom static assets new CopyWebpackPlugin([ { from: path.resolve(__dirname, '../static'), to: config.build.assetsSubDirectory, ignore: ['.*'] } ]) ] }) if (config.build.productionGzip) { // const CompressionWebpackPlugin = require('compression-webpack-plugin') // webpackConfig.plugins.push( // new CompressionWebpackPlugin({ // asset: '[path].gz[query]', // algorithm: 'gzip', // test: new RegExp( // '\\.(' + // config.build.productionGzipExtensions.join('|') + // ')$' // ), // threshold: 10240, // minRatio: 0.8 // }) // ) } if (config.build.bundleAnalyzerReport) { const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin webpackConfig.plugins.push(new BundleAnalyzerPlugin()) } module.exports = webpackConfig
icai/vue2-calendar
build/webpack.prod.conf.js
JavaScript
mit
5,546
require 'rake' namespace :alphred do desc 'Prepare a release, named after the directory' task :release, [:version] => [:tag, :package] desc 'Tag the current commit in git with VERSION' task :tag, [:version] do |t, args| version = args.fetch(:version) git_status = `git status --porcelain` fail <<-FAIL unless git_status.empty? Can't tag #{version}: dirty working directory. FAIL sh "git tag #{version}" sh 'git push --tags' end desc 'Create an alfredworkflow package with vendored dependencies' task :package do restore_bundler_config do cmd = 'bundle install --standalone --path vendor/bundle --without development test' sh "chruby-exec 2.0.0 -- #{cmd}" end sh "zip -r #{application_dir.pathmap('%n.alfredworkflow')} *" rm_rf 'vendor' end def application_dir Rake.application.original_dir end def restore_bundler_config path = File.join(application_dir, '.bundle', 'config') config = File.read(path) yield ensure File.write(path, config, mode: ?w) end end
joshuajharris/dotfiles
Alfred.alfredpreferences/workflows/user.workflow.7CC242B6-984A-48B5-8B68-DA9C29C0EC44/vendor/bundle/ruby/2.0.0/gems/alphred-2.0.0/lib/alphred/tasks.rb
Ruby
mit
1,062
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_25) on Thu Dec 03 23:38:17 CST 2015 --> <title>Uses of Class Controller.EditStateOKListener</title> <meta name="date" content="2015-12-03"> <link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style"> <script type="text/javascript" src="../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class Controller.EditStateOKListener"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../package-summary.html">Package</a></li> <li><a href="../Controller.EditStateOKListener.html" title="class in &lt;Unnamed&gt;">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li><a href="../index-files/index-1.html">Index</a></li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../index.html?class-use/Controller.EditStateOKListener.html" target="_top">Frames</a></li> <li><a href="Controller.EditStateOKListener.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class Controller.EditStateOKListener" class="title">Uses of Class<br>Controller.EditStateOKListener</h2> </div> <div class="classUseContainer">No usage of Controller.EditStateOKListener</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../package-summary.html">Package</a></li> <li><a href="../Controller.EditStateOKListener.html" title="class in &lt;Unnamed&gt;">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li><a href="../index-files/index-1.html">Index</a></li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../index.html?class-use/Controller.EditStateOKListener.html" target="_top">Frames</a></li> <li><a href="Controller.EditStateOKListener.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
jakemanning/basketball-teams
Project5/doc/class-use/Controller.EditStateOKListener.html
HTML
mit
4,038
/** * Модуль класса точек двухмерной плоскости * * @module */ ; /** * Класс точек двухмерной плоскости */ class Point { /** * Координата по оси абсцисс */ public x: number; /** * Координата по оси ординат */ public y: number; /** * Класс точек двухмерной плоскости * * @param x Координата по оси абсцисс * @param y Координата по оси ординат */ public constructor( x: number, y: number ) { this.x = x; this.y = y; } } /** * Модуль */ export { Point as default, };
EgorovRoom/study
scripts/src/moduls/point.ts
TypeScript
mit
729
import {h, div, h1, h2} from '@cycle/dom' const view = props$ => { return props$.map(x => { return div('.page2', [ h1('.content-subhead', ['Page 2']), h1([`This is the second Page`]), h2(['Counter : ' + x]) ]) }); }; export default view
rmoliva/cycle_js1
src/dialogue/pages/page2/page2-view.js
JavaScript
mit
269
package com.rgi.suite.cli; import com.rgi.suite.cli.tilestoreadapter.HeadlessTileStoreAdapter; import org.gdal.osr.SpatialReference; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; import org.kohsuke.args4j.Option; import javax.activation.MimeType; import javax.activation.MimeTypeParseException; import java.io.File; import java.util.logging.Level; import java.util.logging.Logger; /** * Business Logic for Running SWAGD in a headless environment. contains logic to * support Args4J command line arguments * -h : show help * --inputsrs <epsg int> : Input Spatial reference system EPSG identifier (ie 4326) * --outputsrs <epsg int value> : Desired output SRS EPSG identifier,eg 3857 * -c (--compression) <jpeg> : Compression type for image tiling,default is jpeg * -d (--description) <text description> : Tile set description * -f (--format) <image/png or image/jpg> : Image format for tiling operations,default is png (options are png,jpeg,etc.) * -H (--height) <Height: 1-10000> : Tile height in pixels; default is 256 * -i (-in) <Input File Path> : REQUIRED! Input source for tiling/Packaging operation * -ti (--intileset, --intilesetname) : Tile Set name for GeoPackages (input), default is short name of output geopackage. * -to (--outtileset, --outtilesetname) :Tile set name for geopackage output * -o (-out) <Output File Path> : Full output path for tiling/Packaging operation * -q (--compressionQuality) <1-100> : Compression compressionQuality for jpeg compression, between 0-100 * -W (--width) <1-10000> : Tile width in pixels; default is 256 * * @author matthew.moran */ public class HeadlessOptions { public static final int MAGIC_MAX_VALUE = 10000; private static final int DEFAULT_DIMENSION = 256; public static final int GLOBAL_WEB_MERCATOR = 3857; public static final int GLOBAL_GEODETIC = 4326; // set to true when isValid is called private HeadlessOptionsValidator validator; private boolean showHelp; private boolean isValid; // variables to hold command line arguments private File inputFile; private File outputFile; private int outputSrs = HeadlessOptions.GLOBAL_WEB_MERCATOR; private int inputSrs = HeadlessOptions.GLOBAL_GEODETIC; private String tileSetNameIn = ""; private String tileSetNameOut = ""; private String tileSetDescription = ""; private MimeType imageFormat; private int tileWidth = HeadlessOptions.DEFAULT_DIMENSION; private int tileHeight = HeadlessOptions.DEFAULT_DIMENSION; private String compressionType = "jpeg"; @SuppressWarnings("MagicNumber") private int compressionQuality = 75; private final Logger logger; /** * Constructor * * @param logger - logger to write progress out to */ public HeadlessOptions(final Logger logger) { this.logger = logger; try { this.imageFormat = new MimeType("image/jpeg"); } catch(final MimeTypeParseException error) { this.logger.log(Level.SEVERE, "Error creating default image format: " + error.getMessage()); } } /** * path to the input file/directory for packaging/tiling. * * @param filePath - path to the input file or directory to read from * @throws IllegalArgumentException if filePath leads to a non-existent file, is null, or is empty. */ @Option(required = true, name = "-i", aliases = "-in", metaVar = "<Input File Path>", usage = "Input source for tiling orPackaging operation") public void setInputFile(final String filePath) { final String path = HeadlessOptions.getFullPath(filePath); final File file = new File(path); if(file.exists()) { this.inputFile = new File(path); } else { throw new IllegalArgumentException(String.format("FilePath: %s does not exist, input files must exist!", filePath)); } } @Option(required = false, help = true, name = "-h", aliases = "--help", usage = "Show Help") public void showHelp(final boolean show) throws CmdLineException { this.showHelp = show; if(show) { final CmdLineParser parser = new CmdLineParser(this); parser.printUsage(System.out); } } /** * path to the output file/directory for packaging/tiling * * @param filePath - output file path * @throws IllegalArgumentException - if output path is null or empty */ @Option(required = true, name = "-o", aliases = "-out", metaVar = "<Output File Path>", usage = "Full output path for tiling or Packaging operation") public void setOutputFile(final String filePath) { final String path = HeadlessOptions.getFullPath(filePath); this.outputFile = new File(path); } /** * EPSG output SRS number * * @param outSrs - input SRS * @throws IllegalArgumentException if unrecognized spatial reference. */ @Option(name = "--outputsrs", metaVar = "<epsg srs int>", usage = "Desired output SRS EPSG identifier, eg 3857") public void setOutputSrs(final int outSrs) { // special case for TMS. final SpatialReference srs = new SpatialReference(); try { if(srs.ImportFromEPSG(outSrs) == 0) { this.outputSrs = outSrs; } } catch(final RuntimeException ignored) { throw new IllegalArgumentException(String.format("Error: Output SRS %d is not a GDAL supported EPSG value.", outSrs)); } } /** * EPSG input SRS number, required if input is a tms cache * * @param inSrs - input SRS * @throws IllegalArgumentException if unrecognized spatial reference. */ @Option(name = "--inputsrs", metaVar = "<epsg srs int>", usage = "Input Spatial reference system EPSG identifier (ie 4326)") public void setInputSRS(final int inSrs) { // special case for TMS. final SpatialReference srs = new SpatialReference(); try { if(srs.ImportFromEPSG(inSrs) == 0) { this.inputSrs = inSrs; } } catch(final RuntimeException ignored) { throw new IllegalArgumentException(String.format("Error: input SRS %d is not a GDAL supported EPSG value.", inSrs)); } } /** * Tile set Name * * @param name - name of the tileset to read from * @throws IllegalArgumentException - name is null, or longer than 10000 characters */ @Option(name = "-ti", metaVar = "<Tile Set Name>", aliases = {"--intileset", "--intilesetname"}, usage = "Input Tile Set for GeoPackages, default is short name of output geopackage.") public void setTileSetNameIn(final String name) { if(name != null && name.length() <= HeadlessOptions.MAGIC_MAX_VALUE) { this.tileSetNameIn = name; } else { throw new IllegalArgumentException("Provided Name is invalid, must be a " + "non-null string shorter than MAGIC_MAX_VALUE characters"); } } /** * Tile set Name * * @param name - tile set name to write out to * @throws IllegalArgumentException - name is null, or longer than 10000 characters */ @Option(name = "-to", metaVar = "<Tile Set Name>", aliases = {"--outtileset", "--outtilesetname"}, usage = "Input Tile Set for GeoPackages, default is short name of output geopackage.") public void setTileSetNameOut(final String name) { if(name != null && name.length() <= HeadlessOptions.MAGIC_MAX_VALUE) { this.tileSetNameOut = name; } else { throw new IllegalArgumentException("Provided Name is invalid, must be a " + "non-null string shorter than MAGIC_MAX_VALUE characters"); } } /** * Tile Set Description * * @param description - test description of tileset */ @Option(name = "-d", aliases = "--description", metaVar = "<text tile set description>", usage = "Tile set description") public void setTileSetDescription(final String description) { if(description != null && description.length() <= HeadlessOptions.MAGIC_MAX_VALUE) { this.tileSetDescription = description; } else { throw new IllegalArgumentException("Provided Description is invalid, must be a " + "non-null string shorter than MAGIC_MAX_VALUE characters"); } } /** * tile width * * @param width - tile width * @throws IllegalArgumentException value must be between 1 - MAGIC_MAX_VALUE */ @Option(name = "-W", aliases = "--width", metaVar = "<1-9999>", usage = "Tile width in pixels; default is 256") public void setTileWidth(final int width) { if(width > 0 && width < HeadlessOptions.MAGIC_MAX_VALUE) { this.tileWidth = width; } else { throw new IllegalArgumentException(String.format("error setting tile Width to %d, " + "value must be greater than 0 and less than MAGIC_MAX_VALUE", width)); } } /** * Tile Height * * @param height - tile height * @throws IllegalArgumentException - value must be between 1 and MAGIC_MAX_VALUE */ @Option(name = "-H", aliases = "--height", metaVar = "<1-9999>", usage = "Tile height in pixels; default is 256") public void setTileHeight(final int height) { if(height > 0 && height < HeadlessOptions.MAGIC_MAX_VALUE) { this.tileHeight = height; } else { throw new IllegalArgumentException(String.format("error setting tile height to %d, " + "value must be greater than 0 and less than MAGIC_MAX_VALUE", height)); } } // image settings @SuppressWarnings("HardcodedFileSeparator") @Option(name = "-f", aliases = "--format", metaVar = "image/png or image/jpeg", usage = "Image format for tiling operations, default is png (options are png, jpeg,etc.)") private void setImageFormat(final String formatString) throws MimeTypeParseException { if(formatString.equalsIgnoreCase("image/jpeg") || formatString.equalsIgnoreCase("image/png")) { this.imageFormat = new MimeType(formatString.toLowerCase()); } else { //noinspection HardcodedFileSeparator throw new IllegalArgumentException(String.format("error setting image format to %s! must be 'image/jpeg' or 'image/png'", formatString)); } } @Option(name = "-c", aliases = "--compression", metaVar = "<jpeg>", usage = "Compression type for image tiling, default is jpeg") public void setCompressionType(final String compressionType) { if(compressionType.equalsIgnoreCase("jpeg")) { this.compressionType = compressionType.toLowerCase(); } else { throw new IllegalArgumentException(String.format("error setting image compression to %s! must be jpeg", compressionType)); } } /** * quality of compression as a percentage (1-100%) * * @param compressionQuality - quality of compression as a percentage */ @Option(name = "-q", aliases = "--quality", metaVar = "<1-100>", usage = "Compression quality for jpeg compression, between 0-100") public void setCompressionQuality(final int compressionQuality) { if(compressionQuality > 0 && compressionQuality <= 100) { this.compressionQuality = compressionQuality; } else { throw new IllegalArgumentException("Error: Compression Quality must be between 1-100"); } } //Getters public int getTileWidth() { return this.tileWidth; } public int getTileHeight() { return this.tileHeight; } public int getOutputSrs() { return this.outputSrs; } public int getInputSrs() { return this.inputSrs; } public File getInputFile() { return this.inputFile; } public MimeType getImageFormat() { return this.imageFormat; } public boolean getShowHelp() { return this.showHelp; } /** * returns the tilestore adaptor for input * * @return - adaptor, or null if validation has not yet occured, OR if an error was thrown. * @throws IllegalArgumentException */ public HeadlessTileStoreAdapter getInputAdapter() { if(this.validator != null) { return this.validator.getInputAdapter(); } throw new IllegalArgumentException("Validation has not occurred"); } /** * returns the tilestore adaptor for output * * @return - adaptor, or null if validation has not yet occured, OR if an error was thrown. * @throws IllegalArgumentException - if validation failed or has not yet occured */ public HeadlessTileStoreAdapter getOutputAdapter() { if(this.validator != null) { return this.validator.getOutputAdapter(); } throw new IllegalArgumentException("Validation has not occurred"); } public File getOutputFile() { return this.outputFile; } public String getTileSetNameIn() { return this.tileSetNameIn; } public String getTileSetNameOut() { return this.tileSetNameOut; } public String getTileSetDescription() { return this.tileSetDescription; } public String getCompressionType() { return this.compressionType; } public int getCompressionQuality() { return this.compressionQuality; } public boolean isValid() { if(this.validator == null) { this.validator = new HeadlessOptionsValidator(this, this.logger); } return this.validator.isValid(); } /** * returns a full path to the specified file, replacing cmdline based shortcuts * * @param filePath - filepath to replace local charaters in * @return absolute path of string * @throws IllegalArgumentException */ @SuppressWarnings("AccessOfSystemProperties") private static String getFullPath(final String filePath) { if(filePath != null && !filePath.isEmpty()) { String path = filePath; if(path.startsWith('~' + File.separator)) { path = String.format("%s%s", System.getProperty("user.home"), path.substring(1)); } else if(path.startsWith('.' + File.separator)) { path = String.format("%s%s", System.getProperty("user.dir"), path.substring(1)); } return path; } throw new IllegalArgumentException("File Path provided is null or empty!"); } }
GitHubRGI/swagd
RGISuite/src/main/java/com/rgi/suite/cli/HeadlessOptions.java
Java
mit
13,871
--- description: Next.js supports including CSS files as Global CSS or CSS Modules, using `styled-jsx` for CSS-in-JS, or any other CSS-in-JS solution! Learn more here. --- # Built-In CSS Support <details open> <summary><b>Examples</b></summary> <ul> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/basic-css">Basic CSS Example</a></li> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/with-tailwindcss">With Tailwind CSS</a></li> </ul> </details> Next.js allows you to import CSS files from a JavaScript file. This is possible because Next.js extends the concept of [`import`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) beyond JavaScript. ## Adding a Global Stylesheet To add a stylesheet to your application, import the CSS file within `pages/_app.js`. For example, consider the following stylesheet named `styles.css`: ```css body { font-family: 'SF Pro Text', 'SF Pro Icons', 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif; padding: 20px 20px 60px; max-width: 680px; margin: 0 auto; } ``` Create a [`pages/_app.js` file](/docs/advanced-features/custom-app.md) if not already present. Then, [`import`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) the `styles.css` file. ```jsx import '../styles.css' // This default export is required in a new `pages/_app.js` file. export default function MyApp({ Component, pageProps }) { return <Component {...pageProps} /> } ``` These styles (`styles.css`) will apply to all pages and components in your application. Due to the global nature of stylesheets, and to avoid conflicts, you may **only import them inside [`pages/_app.js`](/docs/advanced-features/custom-app.md)**. In development, expressing stylesheets this way allows your styles to be hot reloaded as you edit them—meaning you can keep application state. In production, all CSS files will be automatically concatenated into a single minified `.css` file. ### Import styles from `node_modules` Since Next.js **9.5.4**, importing a CSS file from `node_modules` is permitted anywhere in your application. For global stylesheets, like `bootstrap` or `nprogress`, you should import the file inside `pages/_app.js`. For example: ```jsx // pages/_app.js import 'bootstrap/dist/css/bootstrap.css' export default function MyApp({ Component, pageProps }) { return <Component {...pageProps} /> } ``` For importing CSS required by a third party component, you can do so in your component. For example: ```tsx // components/ExampleDialog.js import { useState } from 'react' import { Dialog } from '@reach/dialog' import '@reach/dialog/styles.css' function ExampleDialog(props) { const [showDialog, setShowDialog] = useState(false) const open = () => setShowDialog(true) const close = () => setShowDialog(false) return ( <div> <button onClick={open}>Open Dialog</button> <Dialog isOpen={showDialog} onDismiss={close}> <button className="close-button" onClick={close}> <VisuallyHidden>Close</VisuallyHidden> <span aria-hidden>×</span> </button> <p>Hello there. I am a dialog</p> </Dialog> </div> ) } ``` ## Adding Component-Level CSS Next.js supports [CSS Modules](https://github.com/css-modules/css-modules) using the `[name].module.css` file naming convention. CSS Modules locally scope CSS by automatically creating a unique class name. This allows you to use the same CSS class name in different files without worrying about collisions. This behavior makes CSS Modules the ideal way to include component-level CSS. CSS Module files **can be imported anywhere in your application**. For example, consider a reusable `Button` component in the `components/` folder: First, create `components/Button.module.css` with the following content: ```css /* You do not need to worry about .error {} colliding with any other `.css` or `.module.css` files! */ .error { color: white; background-color: red; } ``` Then, create `components/Button.js`, importing and using the above CSS file: ```jsx import styles from './Button.module.css' export function Button() { return ( <button type="button" // Note how the "error" class is accessed as a property on the imported // `styles` object. className={styles.error} > Destroy </button> ) } ``` CSS Modules are an _optional feature_ and are **only enabled for files with the `.module.css` extension**. Regular `<link>` stylesheets and global CSS files are still supported. In production, all CSS Module files will be automatically concatenated into **many minified and code-split** `.css` files. These `.css` files represent hot execution paths in your application, ensuring the minimal amount of CSS is loaded for your application to paint. ## Sass Support Next.js allows you to import Sass using both the `.scss` and `.sass` extensions. You can use component-level Sass via CSS Modules and the `.module.scss` or `.module.sass` extension. Before you can use Next.js' built-in Sass support, be sure to install [`sass`](https://github.com/sass/sass): ```bash npm install sass ``` Sass support has the same benefits and restrictions as the built-in CSS support detailed above. > **Note**: Sass supports [two different syntaxes](https://sass-lang.com/documentation/syntax), each with their own extension. > The `.scss` extension requires you use the [SCSS syntax](https://sass-lang.com/documentation/syntax#scss), > while the `.sass` extension requires you use the [Indented Syntax ("Sass")](https://sass-lang.com/documentation/syntax#the-indented-syntax). > > If you're not sure which to choose, start with the `.scss` extension which is a superset of CSS, and doesn't require you learn the > Indented Syntax ("Sass"). ### Customizing Sass Options If you want to configure the Sass compiler you can do so by using `sassOptions` in `next.config.js`. For example to add `includePaths`: ```js const path = require('path') module.exports = { sassOptions: { includePaths: [path.join(__dirname, 'styles')], }, } ``` ## Less and Stylus Support To support importing `.less` or `.styl` files you can use the following plugins: - [@zeit/next-less](https://github.com/vercel/next-plugins/tree/master/packages/next-less) - [@zeit/next-stylus](https://github.com/vercel/next-plugins/tree/master/packages/next-stylus) If using the less plugin, don't forget to add a dependency on less as well, otherwise you'll see an error like: ```bash Error: Cannot find module 'less' ``` ## CSS-in-JS <details> <summary><b>Examples</b></summary> <ul> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/with-styled-jsx">Styled JSX</a></li> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/with-styled-components">Styled Components</a></li> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/with-emotion">Emotion</a></li> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/with-tailwindcss-emotion">Tailwind CSS + Emotion</a></li> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/with-styletron">Styletron</a></li> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/with-glamor">Glamor</a></li> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/with-cxs">Cxs</a></li> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/with-aphrodite">Aphrodite</a></li> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/with-fela">Fela</a></li> </ul> </details> It's possible to use any existing CSS-in-JS solution. The simplest one is inline styles: ```jsx function HiThere() { return <p style={{ color: 'red' }}>hi there</p> } export default HiThere ``` We bundle [styled-jsx](https://github.com/vercel/styled-jsx) to provide support for isolated scoped CSS. The aim is to support "shadow CSS" similar to Web Components, which unfortunately [do not support server-rendering and are JS-only](https://github.com/w3c/webcomponents/issues/71). See the above examples for other popular CSS-in-JS solutions (like Styled Components). A component using `styled-jsx` looks like this: ```jsx function HelloWorld() { return ( <div> Hello world <p>scoped!</p> <style jsx>{` p { color: blue; } div { background: red; } @media (max-width: 600px) { div { background: blue; } } `}</style> <style global jsx>{` body { background: black; } `}</style> </div> ) } export default HelloWorld ``` Please see the [styled-jsx documentation](https://github.com/vercel/styled-jsx) for more examples. ## FAQ ### Does it work with JavaScript disabled? Yes, if you disable JavaScript the CSS will still be loaded in the production build (`next start`). During development, we require JavaScript to be enabled to provide the best developer experience with [Fast Refresh](https://nextjs.org/blog/next-9-4#fast-refresh). ## Related For more information on what to do next, we recommend the following sections: <div class="card"> <a href="/docs/advanced-features/customizing-postcss-config.md"> <b>Customizing PostCSS Config:</b> <small>Extend the PostCSS config and plugins added by Next.js with your own.</small> </a> </div>
flybayer/next.js
docs/basic-features/built-in-css-support.md
Markdown
mit
9,536
using System; using System.Collections.Generic; using System.Diagnostics.Contracts; namespace East.Tool.UseCaseTranslator.Controllers { /// <summary> /// UseCaseTranslator操作種別 /// </summary> public sealed class UseCaseTranslatorOperationType : OperationType { // // クラスフィールド・プロパティ // /// <summary> /// 種別の列挙 /// </summary> internal static UseCaseTranslatorOperationType[] OperationTypes { get { return new[] { new UseCaseTranslatorOperationType("UseCaseCatalog", Resources.Resources.CommandDescription_UseCaseCatalog, UseCaseTranslatorOperator.CommonParameters, (parameters => new MarkdownConverter(parameters))), new UseCaseTranslatorOperationType("TestSuite", Resources.Resources.CommandDescription_TestSuite, UseCaseTranslatorOperator.CommonParameters, (parameters => new ExcelTestSuiteBuilder(parameters))), new UseCaseTranslatorOperationType("Help", Resources.Resources.CommandDescription_Help, UseCaseTranslatorOperator.CommonParameters, (parameters => new HelpReporter(parameters))), }; } } // // クラスメソッド // /// <summary> /// 表記から種別を返す /// </summary> /// <param name="typeLiteral">表記</param> /// <returns>種別(存在しないときnull)</returns> public static UseCaseTranslatorOperationType ValueOf(string typeLiteral) { Contract.Requires(string.IsNullOrWhiteSpace(typeLiteral) == false); return ValueOf(OperationTypes, typeLiteral); } // // メソッド // /// <summary> /// コンストラクタ /// </summary> /// <param name="typeLiteral">操作の表記</param> /// <param name="description">説明</param> /// <param name="paramDefs">パラメーター定義</param> /// <param name="createOperatorFunction">オペレーター生成関数</param> private UseCaseTranslatorOperationType(string typeLiteral, string description, IEnumerable<ParameterDefinition> paramDefs, Func<IDictionary<string, object>, Operator> createOperatorFunction) : base(typeLiteral, description, paramDefs, createOperatorFunction) { } } }
east-pmo/UseCaseTranslator
UseCaseTranslator/Controllers/UseCaseTranslatorOperationType.cs
C#
mit
2,464
--- layout: page title: "Plugin Hooks" categories: [plugins] ---
euantorano/MyBB-Hook-Finder
src/header.md
Markdown
mit
67
<?php /** * The WordPress Plugin Boilerplate. * * A foundation off of which to build well-documented WordPress plugins that also follow * WordPress coding standards and PHP best practices. * * @package Post_Type_Contactos * @author Matias Esteban <estebanmatias92@gmail.com> * @license MIT License * @link http://example.com * @copyright 2013 Matias Esteban * * @wordpress-plugin * Plugin Name: Post Type Contactos * Plugin URI: TODO * Description: TODO * Version: 0.1.0 * Author: TODO * Author URI: TODO * Text Domain: post_type_contactos-locale * License: MIT License * License URI: http://opensource.org/licenses/MIT * Domain Path: /lang */ // If this file is called directly, abort. if ( ! defined( 'WPINC' ) ) { die; } // Define root path of this plugin if ( ! defined( 'PTC_PLUGIN_ROOT' ) ) { define( 'PTC_PLUGIN_ROOT', plugin_dir_path( __FILE__ ) ); } if ( ! defined( 'PTC_PLUGIN_URL' ) ) { define( 'PTC_PLUGIN_URL', plugin_dir_url( __FILE__ ) ); } // Includes require_once( plugin_dir_path( __FILE__ ) . 'class-post-type-contactos.php' ); // Register hooks that are fired when the plugin is activated, deactivated, and uninstalled, respectively. register_activation_hook( __FILE__, array( 'Post_Type_Contactos', 'activate' ) ); register_deactivation_hook( __FILE__, array( 'Post_Type_Contactos', 'deactivate' ) ); // Plugin class instance Post_Type_Contactos::get_instance();
estebanmatias92/post-type-contactos
post-type-contactos.php
PHP
mit
1,443
/** global registry for CLI commands ***************************************** * * * Copyright (c) 2018 Florian Oetke * * This file is distributed under the MIT License * * See LICENSE file for details. * \*****************************************************************************/ #pragma once #include <mirrage/utils/func_traits.hpp> #include <mirrage/utils/log.hpp> #include <mirrage/utils/string_utils.hpp> #include <functional> #include <regex> #include <string> #include <string_view> #include <unordered_map> #include <vector> namespace mirrage::util { /* * auto commands = Console_command_container{}; * commands.add("show <window>", [&](auto& window) { * // stuff * }); */ class Console_command { public: using Func = std::function<void(std::string_view)>; Console_command(std::string name, std::string api, Func exec) : _id(gen_id()), _name(std::move(name)), _api(std::move(api)), _exec(std::move(exec)) { } auto id() const noexcept { return _id; } auto name() const noexcept -> auto& { return _name; } auto api() const noexcept -> auto& { return _api; } void call(std::string_view args) const { _exec(args); } private: static auto gen_id() -> std::int64_t { static auto next = std::int64_t(0); return next++; } std::int64_t _id; std::string _name; std::string _api; Func _exec; }; namespace detail { template <typename T> struct Default_var_setter { void operator()(T& org, T new_val) { org = new_val; } }; } // namespace detail class Console_command_container { public: ~Console_command_container(); template <typename F> auto add(std::string api, F &&) -> Console_command_container&; template <typename T, typename F = detail::Default_var_setter<T>> auto add_var(const std::string& name, T& var, F setter = {}) { add_property( name, [&var, setter = std::move(setter)](T new_val) mutable { setter(var, new_val); }, [&var, name = name]() -> decltype(auto) { return var; }); } template <typename FS, typename FG> auto add_property(const std::string& name, FS&& setter, FG&& getter) { add("set." + name + " <value> | Sets the value of the property", std::forward<FS>(setter)); add("get." + name + " | Gets the value of the property", [name = name, getter = std::forward<FG>(getter)] { LOG(plog::info) << "Value of " << name << ": " << util::to_string(getter()); }); } /// returns false if no such command could be found static auto call(std::string_view cmd) -> bool; static auto complete(std::string_view input) -> std::vector<Console_command*>; static auto list_all_commands() -> const auto& { return all_commands(); } private: static auto all_commands() -> std::unordered_multimap<std::string, std::unique_ptr<Console_command>>& { static std::unordered_multimap<std::string, std::unique_ptr<Console_command>> cmds; return cmds; } std::vector<std::int64_t> _command_ids; }; namespace detail { template <typename T> struct Type_wrapper { }; } // namespace detail template <typename F> auto Console_command_container::add(std::string api, F&& f) -> Console_command_container& { static const auto split_args_regex = std::regex(R"xxx(\"((?:[^"]|\\")+(?!\\).)\"|([^ ]+))xxx", std::regex::optimize); auto name = api.substr(0, api.find(" ")); auto cmd_callback = [api, f = std::forward<F>(f)](std::string_view cmd) mutable { auto arg_iter = std::cregex_iterator(cmd.data(), cmd.data() + cmd.size(), split_args_regex); auto arg_end = std::cregex_iterator(); util::foreach_function_arg_call( f, [&](auto type) -> util::maybe<typename decltype(type)::type> { if(arg_iter == arg_end) { LOG(plog::error) << "Not enough arguments."; return util::nothing; } auto curr = *arg_iter; arg_iter++; if(curr[1].length() == 0) { return util::from_string<typename decltype(type)::type>( cmd.substr(std::size_t(curr.position()), std::size_t(curr.length()))); } else { // quoted auto arg = std::string_view(curr[1].first, std::size_t(curr[1].length())); if(!arg.find("\\")) return util::from_string<typename decltype(type)::type>(arg); else { // contains escape sequences we have to replace auto arg_str = std::string(arg); util::replace_inplace(arg_str, "\\\"", "\""); util::replace_inplace(arg_str, "\\\\", "\\"); return util::from_string<typename decltype(type)::type>(arg_str); } } }); }; auto c = all_commands().emplace(std::move(name), std::make_unique<Console_command>(name, api, cmd_callback)); _command_ids.emplace_back(c->second->id()); return *this; } } // namespace mirrage::util
lowkey42/mirrage
src/mirrage/utils/include/mirrage/utils/console_command.hpp
C++
mit
5,182
using System.Linq; using uWebshop.Common; using uWebshop.Domain; using uWebshop.Domain.Helpers; using uWebshop.Domain.Interfaces; namespace uWebshop.Umbraco.Businesslogic { internal class OrderEvents { public static void OrderStatusChanged(OrderInfo orderInfo, AfterOrderStatusChangedEventArgs e) { Log.Instance.LogDebug("AfterOrderStatusChanged Start"); if (orderInfo == null || orderInfo.OrderLines.Count == 0) return; Log.Instance.LogDebug("AfterOrderStatusChanged e.OrderStatus: " + e.OrderStatus); Log.Instance.LogDebug("AfterOrderStatusChanged e.SendEmails: " + e.SendEmails); switch (e.OrderStatus) { case OrderStatus.Incomplete: break; case OrderStatus.Confirmed: // copy customerdata to shipping data if there is no shippingdata on the order OrderHelper.CopyCustomerToShipping(orderInfo); if (orderInfo.OrderNodeId == 0) { if (orderInfo.CustomerInfo.CustomerInformation != null) { string customerEmail = null, customerFirstName = null, customerLastName = null; foreach (var customerProperty in IO.Container.Resolve<ICMSDocumentTypeService>().GetByAlias(Order.NodeAlias).Properties.Where(x => x.Alias.StartsWith("customer"))) { var element = orderInfo.CustomerInfo.CustomerInformation.Element(customerProperty.Alias); if (element != null) { if (element.Name == "customerEmail") { customerEmail = element.Value; } else if (element.Name == "customerFirstName") { customerFirstName = element.Value; } else if (element.Name == "customerLastName") { customerLastName = element.Value; } } } IO.Container.Resolve<IOrderRepository>().SetCustomerInfo(orderInfo.UniqueOrderId, customerEmail, customerFirstName, customerLastName); } // remove guid from cookie and expire it immediately //OrderHelper.RemoveOrderCookie(orderInfo); // set completed order id cookie to have access to old order after payment OrderHelper.SetCompletedOrderCookie(orderInfo); // update stock when no payment provider is chosen if (orderInfo.PaymentInfo.Id == 0 || orderInfo.PaymentInfo.PaymentType == PaymentProviderType.OfflinePaymentInStore || orderInfo.PaymentInfo.PaymentType == PaymentProviderType.OfflinePaymentAtCustomer || orderInfo.PaymentInfo.PaymentType == PaymentProviderType.Unknown) { OrderHelper.UpdateStock(orderInfo); } } #region send emails if (e.SendEmails) { int customerEmailNodeId; int.TryParse(orderInfo.StoreInfo.Store.ConfirmationEmailCustomer, out customerEmailNodeId); if (customerEmailNodeId != 0) { EmailHelper.SendOrderEmailCustomer(customerEmailNodeId, orderInfo); } int storeEmailNodeId; int.TryParse(orderInfo.StoreInfo.Store.ConfirmationEmailStore, out storeEmailNodeId); if (storeEmailNodeId != 0) { EmailHelper.SendOrderEmailStore(storeEmailNodeId, orderInfo); } } else { Log.Instance.LogDebug("AfterOrderStatusChanged Confirmed e.SendEmails == false"); } if (orderInfo.PaymentInfo.Id == 0 && orderInfo.Status != OrderStatus.Confirmed) { orderInfo.Status = OrderStatus.Confirmed; } if (orderInfo.PaymentInfo.PaymentType == PaymentProviderType.OfflinePaymentAtCustomer || orderInfo.PaymentInfo.PaymentType == PaymentProviderType.OfflinePaymentInStore) { orderInfo.Status = OrderStatus.OfflinePayment; } // if online payment set status to waiting for payment if (orderInfo.PaymentInfo.PaymentType == PaymentProviderType.OnlinePayment) { orderInfo.Status = OrderStatus.WaitingForPayment; if (orderInfo.PaymentInfo.TransactionMethod == PaymentTransactionMethod.Inline) { var paymentProvider = PaymentProviderHelper.GetAllPaymentProviders() .FirstOrDefault(x => x.Id == orderInfo.PaymentInfo.Id); orderInfo = new PaymentRequestHandler().HandleuWebshopPaymentResponse(paymentProvider, orderInfo); } } orderInfo.Save(); #endregion break; case OrderStatus.Cancelled: // return stock OrderHelper.ReturnStock(orderInfo); if (e.SendEmails) { int customerEmailNodeId; int.TryParse(orderInfo.StoreInfo.Store.CancelEmailCustomer, out customerEmailNodeId); int storeEmailNodeId; int.TryParse(orderInfo.StoreInfo.Store.CancelEmailStore, out storeEmailNodeId); if (customerEmailNodeId != 0) { EmailHelper.SendOrderEmailCustomer(customerEmailNodeId, orderInfo); } if (storeEmailNodeId != 0) { EmailHelper.SendOrderEmailStore(storeEmailNodeId, orderInfo); } } else { Log.Instance.LogDebug("AfterOrderStatusChanged Cancelled e.SendEmails == false"); } break; case OrderStatus.Closed: if (e.SendEmails) { int customerEmailNodeId; int.TryParse(orderInfo.StoreInfo.Store.ClosedEmailCustomer, out customerEmailNodeId); int storeEmailNodeId; int.TryParse(orderInfo.StoreInfo.Store.ClosedEmailStore, out storeEmailNodeId); if (customerEmailNodeId != 0) { EmailHelper.SendOrderEmailCustomer(customerEmailNodeId, orderInfo); } if (storeEmailNodeId != 0) { EmailHelper.SendOrderEmailStore(storeEmailNodeId, orderInfo); } } else { Log.Instance.LogDebug("AfterOrderStatusChanged Closed e.SendEmails == false"); } break; case OrderStatus.PaymentFailed: if (e.SendEmails) { int customerEmailNodeId; int.TryParse(orderInfo.StoreInfo.Store.PaymentFailedEmailCustomer, out customerEmailNodeId); int storeEmailNodeId; int.TryParse(orderInfo.StoreInfo.Store.PaymentFailedEmailStore, out storeEmailNodeId); if (customerEmailNodeId != 0) { EmailHelper.SendOrderEmailCustomer(customerEmailNodeId, orderInfo); } if (storeEmailNodeId != 0) { EmailHelper.SendOrderEmailStore(storeEmailNodeId, orderInfo); } } else { Log.Instance.LogDebug("AfterOrderStatusChanged PaymentFailed e.SendEmails == false"); } break; case OrderStatus.OfflinePayment: OrderHelper.UpdateStock(orderInfo); if (e.SendEmails) { int customerEmailNodeId; int.TryParse(orderInfo.StoreInfo.Store.OfflinePaymentEmailCustomer, out customerEmailNodeId); int storeEmailNodeId; int.TryParse(orderInfo.StoreInfo.Store.OfflinePaymentEmailStore, out storeEmailNodeId); if (customerEmailNodeId != 0) { EmailHelper.SendOrderEmailCustomer(customerEmailNodeId, orderInfo); } if (storeEmailNodeId != 0) { EmailHelper.SendOrderEmailStore(storeEmailNodeId, orderInfo); } } else { Log.Instance.LogDebug("AfterOrderStatusChanged OfflinePayment e.SendEmails == false"); } break; case OrderStatus.Pending: if (e.SendEmails) { int customerEmailNodeId; int.TryParse(orderInfo.StoreInfo.Store.PendingEmailCustomer, out customerEmailNodeId); int storeEmailNodeId; int.TryParse(orderInfo.StoreInfo.Store.PendingEmailStore, out storeEmailNodeId); if (customerEmailNodeId != 0) { EmailHelper.SendOrderEmailCustomer(customerEmailNodeId, orderInfo); } if (storeEmailNodeId != 0) { EmailHelper.SendOrderEmailStore(storeEmailNodeId, orderInfo); } } else { Log.Instance.LogDebug("AfterOrderStatusChanged Pending e.SendEmails == false"); } break; case OrderStatus.ReadyForDispatch: Log.Instance.LogDebug("AfterOrderStatusChanged ReadyForDispatch orderInfo.PaymentInfo.PaymentType: " + orderInfo.PaymentInfo.PaymentType); if (orderInfo.PaymentInfo.PaymentType == PaymentProviderType.OnlinePayment) { OrderHelper.UpdateStock(orderInfo); Log.Instance.LogDebug("AfterOrderStatusChanged ReadyForDispatch after update stock"); } Log.Instance.LogDebug("AfterOrderStatusChanged ReadyForDispatch before send emails"); if (e.SendEmails) { int customerEmailNodeId; int.TryParse(orderInfo.StoreInfo.Store.OnlinePaymentEmailCustomer, out customerEmailNodeId); int storeEmailNodeId; int.TryParse(orderInfo.StoreInfo.Store.OnlinePaymentEmailStore, out storeEmailNodeId); if (customerEmailNodeId != 0) { EmailHelper.SendOrderEmailCustomer(customerEmailNodeId, orderInfo); } if (storeEmailNodeId != 0) { EmailHelper.SendOrderEmailStore(storeEmailNodeId, orderInfo); } } else { Log.Instance.LogDebug("AfterOrderStatusChanged ReadyForDispatch e.SendEmails == false"); } Log.Instance.LogDebug("AfterOrderStatusChanged ReadyForDispatch after send emails"); break; case OrderStatus.ReadyForDispatchWhenStockArrives: if (e.SendEmails) { int customerEmailNodeId; int.TryParse(orderInfo.StoreInfo.Store.TemporaryOutOfStockEmailCustomer, out customerEmailNodeId); int storeEmailNodeId; int.TryParse(orderInfo.StoreInfo.Store.TemporaryOutOfStockEmailStore, out storeEmailNodeId); if (customerEmailNodeId != 0) { EmailHelper.SendOrderEmailCustomer(customerEmailNodeId, orderInfo); } if (storeEmailNodeId != 0) { EmailHelper.SendOrderEmailStore(storeEmailNodeId, orderInfo); } } else { Log.Instance.LogDebug("AfterOrderStatusChanged ReadyForDispatchWhenStockArrives e.SendEmails == false"); } break; case OrderStatus.Dispatched: if (e.SendEmails) { int customerEmailNodeId; int.TryParse(orderInfo.StoreInfo.Store.DispatchEmailCustomer, out customerEmailNodeId); int storeEmailNodeId; int.TryParse(orderInfo.StoreInfo.Store.DispatchedEmailStore, out storeEmailNodeId); if (customerEmailNodeId != 0) { EmailHelper.SendOrderEmailCustomer(customerEmailNodeId, orderInfo); } if (storeEmailNodeId != 0) { EmailHelper.SendOrderEmailStore(storeEmailNodeId, orderInfo); } } else { Log.Instance.LogDebug("AfterOrderStatusChanged Dispatched e.SendEmails == false"); } break; case OrderStatus.Undeliverable: if (e.SendEmails) { int customerEmailNodeId; int.TryParse(orderInfo.StoreInfo.Store.UndeliverableEmailCustomer, out customerEmailNodeId); int storeEmailNodeId; int.TryParse(orderInfo.StoreInfo.Store.UndeliverableEmailStore, out storeEmailNodeId); if (customerEmailNodeId != 0) { EmailHelper.SendOrderEmailCustomer(customerEmailNodeId, orderInfo); } if (storeEmailNodeId != 0) { EmailHelper.SendOrderEmailStore(storeEmailNodeId, orderInfo); } } else { Log.Instance.LogDebug("AfterOrderStatusChanged Undeliverable e.SendEmails == false"); } break; case OrderStatus.WaitingForPayment: break; case OrderStatus.Returned: // return stock OrderHelper.ReturnStock(orderInfo); if (e.SendEmails) { int customerEmailNodeId; int.TryParse(orderInfo.StoreInfo.Store.ReturnedEmailCustomer, out customerEmailNodeId); int storeEmailNodeId; int.TryParse(orderInfo.StoreInfo.Store.ReturnedEmailStore, out storeEmailNodeId); if (customerEmailNodeId != 0) { EmailHelper.SendOrderEmailCustomer(customerEmailNodeId, orderInfo); } if (storeEmailNodeId != 0) { EmailHelper.SendOrderEmailStore(storeEmailNodeId, orderInfo); } } else { Log.Instance.LogDebug("AfterOrderStatusChanged Returned e.SendEmails == false"); } break; } } } }
uWebshop/uWebshop-Releases
Umbraco/uWebshop.Umbraco/Businesslogic/OrderEvents.cs
C#
mit
12,003
function Update-DbaMaintenanceSolution { <# .SYNOPSIS Download and Update SQL Server Maintenance Solution created by Ola Hallengren (https://ola.hallengren.com) .DESCRIPTION This script will download and update the latest version of SQL Server Maintenance Solution created by Ola Hallengren. Only the stored procedure will be updated. All tables and jobs will stay untouched. So this can only be used until a new version of the procedures need a new version of the tables or jobs. In this case you have to completely reinstall the SQL Server Maintenance Solution with Install-DbaMaintenanceSolution. .PARAMETER SqlInstance The target SQL Server instance onto which the Maintenance Solution will be updated. .PARAMETER SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. .PARAMETER Database The database where Ola Hallengren's solution is currently installed. Defaults to master. .PARAMETER Solution Specifies which portion of the Maintenance solution to update. Valid values are All (full solution), Backup, IntegrityCheck and IndexOptimize. Defaults to All, but only existing procedures will be replaced. .PARAMETER LocalFile Specifies the path to a local file to install Ola's solution from. This *should* be the zip file as distributed by the maintainers. If this parameter is not specified, the latest version will be downloaded from https://github.com/olahallengren/sql-server-maintenance-solution .PARAMETER Force If this switch is enabled, the Ola's solution will be downloaded from the internet even if previously cached. .PARAMETER WhatIf If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run. .PARAMETER Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. .PARAMETER EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch. .NOTES Tags: Community, OlaHallengren Author: Andreas Jordan, @JordanOrdix Website: https://dbatools.io Copyright: (c) 2021 by dbatools, licensed under MIT License: MIT https://opensource.org/licenses/MIT https://ola.hallengren.com .LINK https://dbatools.io/Update-DbaMaintenanceSolution .EXAMPLE PS C:\> Update-DbaMaintenanceSolution -SqlInstance RES14224 -Database DBA Updates Ola Hallengren's Solution objects on RES14224 in the DBA database. .EXAMPLE PS C:\> Install-DbaMaintenanceSolution -SqlInstance RES14224 -Database DBA -Solution Backup This will update the stored procedure DatabaseBackup only, even if other parts of the solution are also installed. #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Medium")] [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "", Justification = "Internal functions are ignored")] param ( [parameter(Mandatory, ValueFromPipeline)] [DbaInstance[]]$SqlInstance, [PSCredential]$SqlCredential, [string]$Database = "master", [ValidateSet('All', 'Backup', 'IntegrityCheck', 'IndexOptimize', 'CommandExecute')] [string[]]$Solution = 'All', [string]$LocalFile, [switch]$Force, [switch]$EnableException ) begin { if ($Force) { $ConfirmPreference = 'none' } if ($Solution -contains 'All') { $Solution = @('CommandExecute', 'Backup', 'IntegrityCheck', 'IndexOptimize'); } elseif ($Solution -contains 'CommandExecute') { # Take care that CommandExecute is the first procedure to update $Solution = @('CommandExecute') + ($Solution | Where-Object { $_ -ne 'CommandExecute' }) } # Do we need a new local cached version of the software? $dbatoolsData = Get-DbatoolsConfigValue -FullName 'Path.DbatoolsData' $localCachedCopy = Join-DbaPath -Path $dbatoolsData -Child 'sql-server-maintenance-solution-master' if ($Force -or $LocalFile -or -not (Test-Path -Path $localCachedCopy)) { if ($PSCmdlet.ShouldProcess('MaintenanceSolution', 'Update local cached copy of the software')) { try { Save-DbaCommunitySoftware -Software MaintenanceSolution -LocalFile $LocalFile -EnableException } catch { Stop-Function -Message 'Failed to update local cached copy' -ErrorRecord $_ } } } } process { if (Test-FunctionInterrupt) { return } foreach ($instance in $SqlInstance) { try { $server = Connect-DbaInstance -SqlInstance $instance -SqlCredential $SqlCredential -NonPooledConnection } catch { Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue } $db = $server.Databases[$Database] if ($null -eq $db) { Stop-Function -Message "Database $Database not found on $instance. Skipping." -Target $instance -Continue } $installedProcedures = Get-DbaModule -SqlInstance $server -Database $Database | Where-Object Name -in 'CommandExecute', 'DatabaseBackup', 'DatabaseIntegrityCheck', 'IndexOptimize' foreach ($solutionName in $Solution) { if ($solutionName -in 'Backup', 'IntegrityCheck') { $procedureName = 'Database' + $solutionName } else { $procedureName = $solutionName } if ($PSCmdlet.ShouldProcess($instance, "Update $solutionName with script $procedureName.sql")) { $output = [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName Solution = $solutionName Procedure = $procedureName IsUpdated = $false Results = $null } if ($procedureName -notin $installedProcedures.Name) { $output.Results = 'Procedure not installed' } else { $file = Get-ChildItem -Path $localCachedCopy -Recurse -File "$procedureName.sql" if ($null -eq $file) { $output.Results = 'File not found' } else { Write-Message -Level Verbose -Message "Updating $procedureName from $($file.FullName)." try { $null = Invoke-DbaQuery -SqlInstance $server -File $file $output.IsUpdated = $true $output.Results = 'Updated' } catch { $output.Results = $_ } } } $output } } # Close non-pooled connection as this is not done automatically. If it is a reused Server SMO, connection will be opened again automatically on next request. $null = $server | Disconnect-DbaInstance } } }
wsmelton/dbatools
functions/Update-DbaMaintenanceSolution.ps1
PowerShell
mit
8,199
[简体中文介绍](https://github.com/cielpy/build_ipa/blob/master/README-zh.md) A build tool use automation build ipa and distrabution to test. ### Feature - Pull code scheduled, build depend on lastest Git commit message - Pull code before build - Filter log between two build - Upload IPA to fir.im after build succces - Upload symbol file to bugly after build succces - Copy to somewhere after build succces - Send mail after build success(optional you can send filter log) - Send Dingtalk message after build success(optional you can send filter log) - Send mail after build failure, build log as attachment - Optional you can use the tool manual, only upload to fir.im and bulgy support ### Requirement - Xcode 9 - Python3 - Git - fir gem - bugly jar file and Java installed This tool only support python3, and it has several platform tool dependency, you should install them manually. ### Setup on a new machine 1. Install Xcode 9 2. Install python3 3. Install Java runtime (download JDK and install) 4. Install fir-cli 5. Test manual mode 6. Add launchctl task (if need) ### Usage First you should install the python dependencies ``` https://github.com/cielpy/build_ipa.git cd build_ipa [sudo]pip3 install -r requirements.txt ``` ``` Usage: build.py [options] arg Options: -h, --help show this help message and exit -c CONFIG, --config=CONFIG config file path -a, --auto use auto mode, defalut False, you must set target option with valid value when defalut value -t TARGET, --target=TARGET build target, will be ignored when auto option is True ``` Usage example ``` path/to/python3 path/to/build.py -c path/to/config -t 'dev' ``` There is a config example, use YAML format ``` yaml # =========================================== # Build config file # =========================================== # Project path, absolute path project_path: 'path log project' # Workspace name, file name under project path worspace_name: 'Example.xcworkspace' # Log path, absolute path log_path: 'path of log' # Build file (archive, ipa etc) path, absolute path builds_path: 'path of builds, for IPA' # Build log file name, build log located in builds_path's log folder builg_log: build.log # Git info git: pull_before_build: true # Which branch to build, if not set, will use the local repo's current brach branch: # Dingtalk preferences send_ding_msg_after_build: enable: false # Dingtalks tokens to send message tokens: - cbd71be588ejldjaf232311b2551ad6dae09b47549aef7e2dd513d906d64c77a - 736df1d522fee3f7cc29d0joalfja11sll4df9351589be32d7dfabca7637677d # Option send filter log send_filter_log: true # Filter info, use to fileter log filter_log: prefix: "[" # Fir info upload_to_fir: enable: true # custom fir path path: '/usr/local/bin/fir' token: 7lkjljlkaaab0ed4322a685c1d61f # Copy ipa to path copy_to: enable: true # Path to copy, absolute path path: 'path to copy' # Bugly info bugly: enable: true # Jar file location, absolute path jar_file: 'file path of bugly Jar file' # Mail login info, must suppport ssl login mail_info: server: smtp.example.com user: admin@example.com password: password # Mail preferences email_after_build: enable: true # Option send filter log send_filter_log: true # Mail receiver send_to: - send_to@example.com # Mail cc to cc_to: - cc_to@example.com # Mail preferences when build failure email_after_failure: enable: false # Mail receiver send_to: - send_to@example.com cc_to: - cc_to@example.com cc_to: # Build info, dictionary build: dev: info_plist: Example/Info.plist bugly_key: cac0689a-lkkk-11212-a120-4e0118f8d462 bugly_id: i1400012222 download_url: https://fir.im/abcd app_name: Example team_id: JLKJJ3333 export_mothod: development scheme: Example bundle_id: com.example provisioning_profile: 'iOS Development Dev' # Extra provisioning profile, use for project have extentions extra_provisioning_profile: - bundle_id: com.example.extention provisioning_profile: 'iOS Development Dev Extention' resign: enable: true provisioning_profile: '/Users/xxx/Documents/xxx.mobileprovision' certificate: 'iPhone Distribution xxx Net Co., Ltd.' # Change app display nama app_name: # Change bundle id, if not config, use provisioning profile's instead bundle_id: extentions: # Extentsion's scheme - scheme: xxx provisioning_profile: '/Users/xxx/Documents/xxx.mobileprovision' bundle_id: # Identifier use to detect a build, must unique among all build info build_identifier: BUILDIPA_DEV dis: info_plist: Example/Info.plist bugly_key: jlkjlkjaa-7c5c-41e3-b54f-8dabd4c4da2b bugly_id: i1400111110 download_url: https://fir.im/efgh app_name: Example-PROD team_id: JLKJLFDS11 export_mothod: ad-hoc scheme: Example_PROD bundle_id: com.example.prod provisioning_profile: 'iOS Distribution Prod' # Identifier use to detect a build, must unique among all build info build_identifier: BUILDIPA_PROD ``` ### WARMING! It's recomment use auto mode with launchctl, there has two benifit 1. launchctl environment can aceess login keychain, THIS IS A HUGE BENIFIT, you can save many time deal the cetificate issue. 2. launchctl run one instance at a time, you do not need warry about to many install run at same time. There has a launchctl example plist file ``` xml <?xml version="1.0" encoding="UTF-8"?> <plist version="1.0"> <dict> <key>EnvironmentVariables</key> <dict> <key>PATH</key> <string>/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin</string> <key>PYTHONIOENCODING</key> <string>UTF-8</string> </dict> <key>Label</key> <string>com.cielpy.ipa</string> <key>ProgramArguments</key> <array> <string>/usr/local/bin/python3</string> <string>path/to/build.py</string> <string>-u</string> <string>-a</string> <string>-c</string> <string>path/to/build.yaml</string> </array> <key>RunAtLoad</key> <true /> <key>StartInterval</key> <integer>60</integer> <key>StandardErrorPath</key> <string>/tmp/AlTest1.err</string> <key>StandardOutPath</key> <string>/tmp/AlTest1.out</string> </dict> </plist> ``` Move it to `~/Library/LaunchAgents/` and run this command: ``` launchctl load ~/Library/LaunchAgents/com.cielpy.build_ipa.plist ``` Python script will run every 60 second, you change the parameters as you like. After these config, you can commit with message `BUILDIPA`(set in build info), launchctl will run script automatically to build IPA and upload to third party platform.
cielpy/build_ipa
README.md
Markdown
mit
7,014
from django.contrib import admin from .models import SimpleModel, Type, FKModel admin.site.register(SimpleModel) admin.site.register(Type) admin.site.register(FKModel)
wq/django-data-wizard
tests/data_app/admin.py
Python
mit
170
public abstract class Pieza { public int Valor; public byte Color; public byte ColorOp; public bool Generar; //¿Debe generar movimientos en el destino? public int[][][] BdMov; public abstract void GenerarBdMov(); public abstract void DeterminarDireccion(int esq,int orides,out int dir, out int cmz); public virtual void GenerarMovProtectores(int esq, Movimiento mv, Tablero tab){} public virtual void GenerarMovOrigen(int esq, Movimiento mov, Tablero tab) { int dirOrigen; int cmzOrigen; int dirDestino; int cmzDestino; this.DeterminarDireccion(esq,mov.Origen,out dirOrigen, out cmzOrigen); this.DeterminarDireccion(esq,mov.Destino,out dirDestino, out cmzDestino); if(dirOrigen!=dirDestino) { for(int i=cmzOrigen; i < BdMov[esq][dirOrigen].Length; i++) { int casPosible = BdMov[esq][dirOrigen][i]; tab[casPosible].Movs[this.Color].Insertar(esq,tab); if(tab[casPosible].Tipo != null) break; } } else { if(cmzOrigen < cmzDestino) { for(int i=cmzOrigen; i < cmzDestino; i++) { tab[BdMov[esq][dirOrigen][i]].Movs[this.Color].Insertar(esq,tab); this.Generar = false; } } else { for(int i=cmzDestino-1; i > cmzOrigen; i--) { int posicion = tab[BdMov[esq][dirOrigen][i]].Movs[this.Color].Eliminar(esq); if(posicion==-1) break; } } } } public virtual void GenerarMovDestino(int esq, Movimiento mov, Tablero tab) { if(this.Generar == false) { this.Generar = true; return; } int dirDestino; int cmzDestino; this.DeterminarDireccion(esq,mov.Destino,out dirDestino,out cmzDestino); for(int i=cmzDestino; i < BdMov[esq][dirDestino].Length; i++) { int posicion = tab[BdMov[esq][dirDestino][i]].Movs[this.Color].Eliminar(esq); if(posicion==-1) break; } } public virtual void GenerarMovLegales(int esq, Tablero tab) { for(int dir=0; dir < BdMov[esq].Length; dir++) { for(int j=0; j < BdMov[esq][dir].Length; j++) { int casPosible = BdMov[esq][dir][j]; tab[casPosible].Movs[this.Color].Insertar(esq,tab); if(tab[casPosible].Tipo != null) { break; } } } } public virtual void EliminarMovimientos(int esq, Tablero tab) { for(int dir=0; dir < BdMov[esq].Length; dir++) { for(int j=0; j < BdMov[esq][dir].Length; j++) { int posicion = tab[BdMov[esq][dir][j]].Movs[this.Color].Eliminar(esq); if(posicion==-1) break; } } } } public class Rey : Pieza { public Rey(byte cl) { this.Valor = 100000; this.Generar=true; this.Color = cl; this.BdMov = new int[64][][]; if(cl==0) ColorOp = 1; else ColorOp = 0; for(int i=0; i < BdMov.Length; i++) { BdMov[i] = new int[2][]; } this.GenerarBdMov(); } public override void GenerarMovLegales(int esq, Tablero tab) { int casPosible; for(int i=0; i < BdMov[esq][0].Length; i++) { casPosible = BdMov[esq][0][i]; Lista movsOp = tab[casPosible].Movs[this.ColorOp]; if(tab[casPosible].Tipo==null) { if((movsOp.Cuenta==0 || (movsOp.Cuenta==1 && tab[movsOp[0]].Tipo is Peon)) && tab[casPosible].Protectores[this.ColorOp].Cuenta==0) { tab[casPosible].Movs[this.Color].Insertar(esq,tab); } } else if(movsOp.Cuenta==0 && tab[casPosible].Protectores[this.ColorOp].Cuenta==0) { tab[casPosible].Movs[this.Color].Insertar(esq,tab); } } if(BdMov[esq][1].Length>0) { if(tab[esq + 1].Tipo == null && tab[esq + 2].Tipo == null) { if(tab[esq+3].Tipo!=null && tab[esq + 3].Tipo is Torre) tab[BdMov[esq][1][0]].Movs[this.Color].Insertar(esq,tab); } if(tab[esq - 1].Tipo == null && tab[esq - 2].Tipo == null && tab[esq - 3].Tipo==null) { if(tab[esq-4].Tipo!=null && tab[esq - 4].Tipo is Torre) tab[BdMov[esq][1][1]].Movs[this.Color].Insertar(esq,tab); } } } public override void GenerarMovOrigen(int esq, Movimiento mov, Tablero tab){ return; } public override void GenerarMovDestino(int cas, Movimiento mov, Tablero tab){return;} public override void DeterminarDireccion(int esq,int orides,out int dir, out int cmz){ dir = -1; cmz = -1; } public override void EliminarMovimientos(int esq, Tablero tab){ for(int dir=0; dir < BdMov[esq].Length; dir++) { for(int j=0; j < BdMov[esq][dir].Length; j++) { tab[BdMov[esq][dir][j]].Movs[this.Color].Eliminar(esq); } } } public override void GenerarBdMov() { int[] sumas = {-9,-8,-7,7,8,9,-1,1}; int maxMovs, filRey, esqPosible, a, filaPosible, numMov; for(int i=0; i < 64; i++) { //Si el rey está en un borde, su número máximo de movs se reduce. maxMovs = 8; filRey = (i-i%8)/8; if(i%8==0 || i%8==7) maxMovs -= 3; if(filRey==0 || filRey==7) { if(maxMovs==5) maxMovs -= 2; else maxMovs -= 3; } BdMov[i][0] = new int[maxMovs]; a = 1; numMov = 0; for(int k=0; k < sumas.Length; k++) { esqPosible = i + sumas[k]; if(k==6) a = 0; if(esqPosible < 64 && esqPosible >= 0) { filaPosible = (esqPosible - esqPosible%8)/8; if(filaPosible == filRey + a || filaPosible == filRey - a) { BdMov[i][0][numMov] = esqPosible; numMov++; } } } //¿Está en casilla inicial? // 0: Enroque pequeño, 1: Enroque grande. /*if(i==4 && this.Color==0) { BdMov[4][1] = new int[2]; BdMov[4][1][0] = 6; BdMov[4][1][1] = 2; } else if(i==60 && this.Color==1) { BdMov[i][1] = new int[2]; BdMov[i][1][0] = 62; BdMov[i][1][1] = 58; } else {*/ BdMov[i][1] = new int[0]; //} } } } public class Dama : Pieza { public Dama(byte cl) { this.Valor = 800; this.Generar = true; this.BdMov = new int[64][][]; this.Color = cl; if(cl==0) this.ColorOp = 1; else this.ColorOp = 0; for(int i=0; i < BdMov.Length; i++) { BdMov[i] = new int[8][]; } this.GenerarBdMov(); } public override void DeterminarDireccion(int esq,int cas,out int direccion, out int comienzo) { int colC = cas%8; int colE = esq%8; if(colC==colE) { if(cas>esq) { direccion = 0; comienzo = (cas - esq)/8; } else { direccion = 1; comienzo = (esq - cas)/8; } } else if(cas-colC == esq-colE) { if(cas>esq) { direccion=2; comienzo = cas - esq; } else { direccion=3; comienzo = esq - cas; } } else if(esq%9==cas%9) { if(cas > esq) { direccion = 4; comienzo = (cas-esq)/9; } else { direccion = 5; comienzo = (esq-cas)/9; } } else if(esq%7==cas%7) { if(cas > esq) { direccion = 6; comienzo = (cas-esq)/7; } else { direccion = 7; comienzo = (esq-cas)/7; } } else { direccion = -1; comienzo = -1; } } public override void GenerarBdMov() { //BdMov[esq][dir]: dir tiene 8 valores: //0>arr. 1>aba. 2>der. 3>izq. 4>arr-der. 5>aba-izq. 6>arr-izq. 7>aba-der. int[] sumas = {8, -8, 1, -1, 9, -9, 7, -7}; int[] longitudes = new int[8]; int esqPosible, filDama, colDama; for(int i=0; i < 64; i++) { filDama = (i-i%8)/8; colDama = i%8; longitudes[0] = 7-filDama; longitudes[1] = filDama; longitudes[2] = 7-colDama; longitudes[3] = colDama; longitudes[4] = System.Math.Min(7-filDama, 7-colDama); longitudes[5] = System.Math.Min(filDama, colDama); longitudes[6] = System.Math.Min(7-filDama, colDama); longitudes[7] = System.Math.Min(filDama, 7-colDama); for(int k=0; k < 8; k++) { BdMov[i][k] = new int[longitudes[k]]; } for(int j=0; j < BdMov[i].Length; j++) { esqPosible = i; for(int k=0; k < BdMov[i][j].Length; k++) { esqPosible += sumas[j]; BdMov[i][j][k] = esqPosible; } } } } } public class Torre : Pieza { public Torre(byte cl) { this.Valor = 450; this.BdMov = new int[64][][]; this.Color = cl; this.Generar = true; if(cl==0) this.ColorOp = 1; else this.ColorOp = 0; for(int i=0; i < BdMov.Length; i++) { BdMov[i] = new int[4][]; } this.GenerarBdMov(); } public override void DeterminarDireccion(int esq,int cas,out int direccion,out int comienzo) { int colC = cas%8; int colE = esq%8; if(colC==colE) { if(cas>esq) { direccion = 0; comienzo = (cas - esq)/8; } else { direccion = 1; comienzo = (esq - cas)/8; } } else if(cas-colC == esq-colE) { if(cas>esq) { direccion=2; comienzo = cas - esq; } else { direccion=3; comienzo = esq - cas; } } else { direccion = -1; comienzo = -1; } } public override void GenerarBdMov() { //BdMov[esq][dir]: dir puede tomar 4 valores: //0 > arriba. 1 > abajo. 2 > derecha. 3 > izquierda int[] sumas = {8, -8, 1, -1}; int filTor, esqPosible,colTor; int max = 7; for(int i=0; i < 64; i++) { filTor = (i-i%8)/8; colTor = i%8; BdMov[i][0] = new int[max-filTor]; BdMov[i][1] = new int[filTor]; BdMov[i][2] = new int[max-colTor]; BdMov[i][3] = new int[colTor]; for(int j=0; j < BdMov[i].Length; j++) { esqPosible = i; for(int k=0; k < BdMov[i][j].Length; k++) { esqPosible += sumas[j]; BdMov[i][j][k] = esqPosible; } } } } } public class Alfil : Pieza { public Alfil(byte cl) { this.Valor = 305; this.Generar = true; this.BdMov = new int[64][][]; this.Color = cl; if(cl==0) this.ColorOp = 1; else this.ColorOp = 0; for(int i=0; i < BdMov.Length; i++) { BdMov[i] = new int[4][]; } this.GenerarBdMov(); } public override void DeterminarDireccion(int esq,int cas,out int direccion, out int comienzo) { if(esq%9==cas%9) { if(cas > esq) { direccion = 0; comienzo = (cas-esq)/9; } else { direccion = 1; comienzo = (esq-cas)/9; } } else if(esq%7==cas%7) { if(cas > esq) { direccion = 2; comienzo = (cas-esq)/7; } else { direccion = 3; comienzo = (esq-cas)/7; } } else { direccion = -1; comienzo = -1; } } public override void GenerarBdMov() { //BdMov[esq][dir]: dir puede tomar 4 valores. //0 > arr-der. 1 > aba-izq. 2 > arr-izq. 3 > aba-der. int[] sumas = {9, -9, 7, -7}; int filAlf, colAlf, esqPosible; for(int i=0; i < 64; i++) { filAlf = (i-i%8)/8; colAlf = i%8; int tamDir0 = System.Math.Min(7-filAlf, 7-colAlf); int tamDir1 = System.Math.Min(filAlf, colAlf); int tamDir2 = System.Math.Min(7-filAlf, colAlf); int tamDir3 = System.Math.Min(filAlf, 7-colAlf); BdMov[i][0] = new int[tamDir0]; BdMov[i][1] = new int[tamDir1]; BdMov[i][2] = new int[tamDir2]; BdMov[i][3] = new int[tamDir3]; for(int j=0; j < BdMov[i].Length; j++) { esqPosible = i; for(int k=0; k < BdMov[i][j].Length; k++) { esqPosible += sumas[j]; BdMov[i][j][k] = esqPosible; } } } } } public class Caballo : Pieza { public Caballo(byte cl) { this.Valor = 300; this.BdMov = new int[64][][]; this.Color = cl; if(cl==0) this.ColorOp = 1; else this.ColorOp = 0; for(int i=0; i < BdMov.Length; i++) { BdMov[i] = new int[1][]; } this.GenerarBdMov(); } public override void GenerarMovLegales(int esq, Tablero tab) { for(int j=0; j < BdMov[esq][0].Length; j++) { int casPosible = BdMov[esq][0][j]; if(tab[casPosible].Tipo == null) { tab[casPosible].Movs[this.Color].Insertar(esq,tab); } else { tab[casPosible].Movs[this.Color].Insertar(esq,tab); } } } public override void EliminarMovimientos(int esq, Tablero tab) { for(int j=0; j < BdMov[esq][0].Length; j++) { tab[BdMov[esq][0][j]].Movs[this.Color].Eliminar(esq); } } public override void GenerarMovOrigen(int esq, Movimiento mov, Tablero tab){return;} public override void GenerarMovDestino(int esq, Movimiento mov, Tablero tab){return;} public override void DeterminarDireccion(int esq,int orides,out int dir, out int cmz){ dir=-1; cmz=-1; return; } public override void GenerarBdMov() { int[] sumas = {-17,-15,15,17,-10,-6,6,10}; int aux, filCab, colCab, esqPosible, filaPosible, maxMovs, indice; for(int i=0; i < 64; i++) { filCab = (i-i%8)/8; colCab = i%8; maxMovs = 0; if(filCab >= 2 && filCab <= 5) maxMovs += 4; if(colCab >= 2 && colCab <= 5) maxMovs += 4; if(filCab == 1 || filCab == 6) maxMovs += 2; if(colCab == 1 || colCab == 6) maxMovs += 2; if((filCab == 0 || filCab == 7) && maxMovs < 4) maxMovs += 1; if((colCab == 0 || colCab == 7) && maxMovs < 4) maxMovs += 1; BdMov[i][0] = new int[maxMovs]; aux = 2; indice = 0; for(int k=0; k < sumas.Length; k++) { esqPosible = i + sumas[k]; if(k==4) { aux = 1; } if(esqPosible <= 63 && esqPosible >= 0) { filaPosible = (esqPosible - esqPosible%8)/8; if(filaPosible == filCab + aux || filaPosible == filCab - aux) { BdMov[i][0][indice] = esqPosible; indice++; } } } } } } public class Peon : Pieza { public Peon(byte cl) { this.Valor = 75; this.Generar = true; this.BdMov = new int[64][][]; this.Color = cl; if(cl==0) this.ColorOp = 1; else this.ColorOp = 0; for(int i=0; i < BdMov.Length; i++) { BdMov[i] = new int[3][]; //3 direcciones: adelante y 2 diagonales. } this.GenerarBdMov(); } public override void GenerarMovLegales(int esq, Tablero tab) { int casPosible; for(int j=0; j < BdMov[esq][0].Length; j++) { casPosible = BdMov[esq][0][j]; if(tab[casPosible].Tipo == null) { tab[casPosible].Movs[this.Color].Insertar(esq,tab); } else { tab[casPosible].Bloqueados.Insertar(esq,tab); break; } } for(int k=1; k <= 2; k++) { if(BdMov[esq][k].Length > 0) { casPosible = BdMov[esq][k][0]; if(tab[casPosible].Tipo == null) { tab[casPosible].Protectores[this.Color].Insertar(esq,tab); } else { if(tab[casPosible].Tipo.Color == this.ColorOp) tab[casPosible].Movs[this.Color].Insertar(esq,tab); else tab[casPosible].Protectores[this.Color].Insertar(esq,tab); } } } } public override void EliminarMovimientos(int esq, Tablero tab) { for(int j=0; j < BdMov[esq][0].Length; j++) { tab[BdMov[esq][0][j]].Movs[this.Color].Eliminar(esq); tab[BdMov[esq][0][j]].Bloqueados.Eliminar(esq); } for(int k=1; k <= 2; k++) { if(BdMov[esq][k].Length > 0) { int posicion = tab[BdMov[esq][k][0]].Protectores[this.Color].Eliminar(esq); if(posicion==-1) tab[BdMov[esq][k][0]].Movs[this.Color].Eliminar(esq); } } for(int i=0; i < 64; i++) { if(tab[i].Movs[this.Color].Buscar(esq)!=-1) Dpr.Log("quedan Movs"); if(tab[i].Protectores[this.Color].Buscar(esq)!=-1) Dpr.Log("quedan Protectores"); if(tab[i].Bloqueados.Buscar(esq)!=-1) { Dpr.Log("quedan Bloqueados"); Dpr.Log(i + ", " + esq); } } } public override void GenerarMovOrigen(int esq, Movimiento mov, Tablero tab){ //Sólo es posible llegar aquí si la pieza movida es del color opuesto. tab[mov.Origen].Movs[this.Color].Eliminar(esq); tab[mov.Origen].Protectores[this.Color].Insertar(esq,tab); } public void Desbloquear(int esq, int origen, Tablero tab) { tab[origen].Bloqueados.Eliminar(esq); tab[origen].Movs[this.Color].Insertar(esq,tab); int fila = (esq-esq%8)/8; if(this.Color==0 && fila==1 && origen==esq+8) tab[esq+16].Movs[this.Color].Insertar(esq,tab); else if(this.Color==1 && fila==6 && origen==esq-8) tab[esq-16].Movs[this.Color].Insertar(esq,tab); } public override void GenerarMovDestino(int esq, Movimiento mov, Tablero tab) { tab[mov.Destino].Movs[this.Color].Eliminar(esq); tab[mov.Destino].Bloqueados.Insertar(esq,tab); int fila = (esq-esq%8)/8; if(this.Color==0 && fila==1 && mov.Destino==esq+8) tab[esq+16].Movs[this.Color].Eliminar(esq); else if(this.Color==1 && fila==6 && mov.Destino==esq-8) tab[esq-16].Movs[this.Color].Eliminar(esq); } public override void GenerarMovProtectores(int esq, Movimiento mov, Tablero tab) { //Se requiere que solamente se llame a esta función si la pieza movida es del //color opuesto, es decir, cuando se revisen los protectores de la casilla destino. tab[mov.Destino].Protectores[this.Color].Eliminar(esq); tab[mov.Destino].Movs[this.Color].Insertar(esq,tab); } public override void DeterminarDireccion(int esq, int cas, out int dir, out int cmz) { dir = -1; cmz = -1; return; } public override void GenerarBdMov() { int filPeon, colPeon, maxAdelante = 0, maxDgIzq = 0, maxDgDer = 0, aux, aux2; for(int i=0; i <64; i++) { filPeon = (i-i%8)/8; colPeon = i%8; if(filPeon!=0 && filPeon != 7) { if(this.Color == 0) { if(filPeon==1) maxAdelante = 2; else maxAdelante = 1; } else { if(filPeon==6) maxAdelante = 2; else maxAdelante = 1; } } else { maxAdelante = 0; } if(filPeon==0 || filPeon==7) { maxDgIzq = 0; maxDgDer = 0; } else if(colPeon!=0 && colPeon!=7) { maxDgDer = 1; maxDgIzq = 1; } else if(colPeon == 0) { if(this.Color == 0) { maxDgIzq = 0; maxDgDer = 1; } else { maxDgDer = 0; maxDgIzq = 1; } } else { if(this.Color == 0) { maxDgIzq = 1; maxDgDer = 0; } else { maxDgIzq = 0; maxDgDer = 1; } } BdMov[i][0] = new int[maxAdelante]; BdMov[i][1] = new int[maxDgIzq]; BdMov[i][2] = new int[maxDgDer]; if(this.Color == 0) aux = 1; else aux = -1; aux2 = aux*8; for(int k=0; k < BdMov[i][0].Length; k++) { BdMov[i][0][k] = i+aux2; aux2 += aux2; } if(BdMov[i][1].Length > 0) { BdMov[i][1][0] = i + aux*7; } if(BdMov[i][2].Length > 0) { BdMov[i][2][0] = i + aux*9; } } } }
sideral/aledrez
Servicio/piezas.cs
C#
mit
18,967
// -*- C++ -*- // $Id: Signature.h 80826 2008-03-04 14:51:23Z wotte $ // File: Signature.h // Author: Phil Mesnier #ifndef _SIGNATURE_H_ #define _SIGNATURE_H_ // Signature class encapsulates a single line of nm output. This line may be // either an "undefined" name to be resolved, or text or data which resolves // the unknowns. Some of the features of the Signature class are currently // unused, such as owner_, which is anticipation of analysis that may lead to // further code reduction. The premise being that unresolved symbols that are // defined within otherwise unused code should not be resolved. However this // information is not available in the output of nm. Further research is // required. // // Signatures are reference counted to avoid duplication. #include <ace/SString.h> class Signature { public: enum Kind { text_, undef_ }; Signature (const ACE_CString &); void used (); int used_count() const; const ACE_CString &name() const; Signature *dup(); void release(); private: ACE_CString name_; int ref_count_; int used_; Signature * owner_; Kind kind_; }; #endif
binghuo365/BaseLab
3rd/ACE-5.7.0/ACE_wrappers/apps/soreduce/Signature.h
C
mit
1,140
<?php namespace Caravane\Bundle\EstateBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class PhotoType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder //->add('filename') ->add('file') ; } /** * @param OptionsResolverInterface $resolver */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'Caravane\Bundle\EstateBundle\Entity\Photo' )); } /** * @return string */ public function getName() { return 'caravane_bundle_estatebundle_photo'; } }
EricGrivilers/lion
src/Caravane/Bundle/EstateBundle/Form/PhotoType.php
PHP
mit
925
<?php /** * Moduł ogólny * * */ /** * Kontroler bazowy do dziedziczenia * * PHP version 7.0 * * * @category PHP * @package Default * @author Mariusz Wintoch <biuro@informatio.pl> * @copyright 2016 (c) Informatio, Mariusz Wintoch */ abstract class BaseController extends Zend_Controller_Action { public function init() { parent::init(); $this->view->styles = array( '/libs/jquery-ui-1.12.1.custom/jquery-ui.min' ); $this->view->scripts = array( '/libs/jquery-3.1.1.min', '/libs/jquery-ui-1.12.1.custom/jquery-ui.min' ); $this->view->scriptVars = array(); } /** * Jak ktoś błądzi, to przekierowujemy na początek * */ public function indexAction() { $this->_helper->redirector->gotoSimple('index', 'index', 'index'); } /** * Dodaje styl do widoku * * @param string $file bez rozszerzenia */ protected function addStyle($file) { $this->view->styles[] = $file; } /** * Dodaje skrypt do widoku * * @param string $file bez rozszerzenia */ protected function addScript($file) { $this->view->scripts[] = $file; } /** * Dodaje zmienną JS do widoku * * @param string $nazwa * @param mixed $wartosc */ protected function setScriptVar($nazwa, $wartosc) { $this->view->scriptVars[$nazwa] = $wartosc; } }
Faqqundo/quiz
application/controllers/BaseController.php
PHP
mit
1,510
#!/bin/sh [ -z $1 ] && echo "usage: sh check-list-2.sh iplist\" " && exit for svrlist in `grep "^[^#]" $1` do echo -e "\033[35;2m>>Check [$svrlist]\033[0m" remote=`echo $svrlist | awk -F : '{print $2}'` ssh -q root@$remote "ps -ef | grep -i resin | grep -v grep" > /dev/null if [ 0 -eq $? ]; then echo -e " resin OK" else echo -e " resin \033[31;2mNO\033[0m" fi ssh -q root@$remote "ps -ef | grep httpd | grep -v grep" > /dev/null if [ 0 -eq $? ]; then echo -e " httpd OK" else echo -e " httpd \033[31;2mNO\033[0m" fi :<<REM ssh -q root@$remote "ps -ef | grep -i mysql | grep -v grep" > /dev/null if [ 0 -eq $? ]; then echo -e " mysql OK" else echo -e " mysql \033[31;2mNO\033[0m" fi REM ssh -q root@$remote "ps -ef | grep ruby | grep -v grep" > /dev/null if [ 0 -eq $? ]; then echo -e " ruby OK" else echo -e " ruby \033[31;2mNO\033[0m" fi ssh -q root@$remote "ps -ef|grep -i keeplive|grep -v grep" > /dev/null if [ 0 -eq $? ]; then echo -e " keeplive OK" else echo -e " keeplive \033[31;2mNO\033[0m" fi ssh -q root@$remote "ps -ef|grep -i screen|grep -v grep" > /dev/null if [ 0 -eq $? ]; then echo -e " screen OK" else echo -e " screen \033[31;2mNO\033[0m" fi done
lgh8820/ansible-test
OperationsShell/getserverinfo/check-list-2.sh
Shell
mit
1,168
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ModClient.Attributes { /// <summary> /// A method-level attribute indicating that the annotated method is to be used as a replacement for the method /// specified in the attribute. /// </summary> /// <see cref="PatchAttribute"/> /// <remarks> /// Replacement methods are inserted in place of the method body of the patched method. Arguments to the /// replacement method must match exactly the arguments of the method being replaced. Note that replacement methods /// have a marginally higher cost than the original method, since the original method acts solely as a proxy to the /// replacement method post patching. In other words, a method which is patched with a replacement will look like /// the following after patching: /// <code> /// public void PatchedMethod(String someArg, int anotherArg) /// { /// ReplacementMethod(someArg, anotherArg); /// } /// </code> /// </remarks> [AttributeUsage(AttributeTargets.Method)] public class ReplaceAttribute : PatchAttribute { public ReplaceAttribute(Type type, String method) : base(type, method) {} } }
msmith57/7dtd-mods
ModdingFramework/ModClient/Attributes/ReplaceAttribute.cs
C#
mit
1,253
/* * Interface.cpp * * Created on: Jun 25, 2015 * Author: jiabin */ #include <strings.h> #include "Interface.h" namespace gwc { namespace server { char Interface::lastErr[128]; Interface::Interface() { id = 0; sock = -1; channelType = 0; lastErr[0] = 0; bzero(&timestamp, sizeof(timestamp)); bzero(&bindAddr, sizeof(bindAddr)); } Interface::~Interface() { } } /* namespace server */ } /* namespace gwc */
jiabinruan/gowithcool
server/Interface.cpp
C++
mit
428
--- layout: publication type: "conference" authors: "Ekram, F., Barazandegan, K.E. Kwok, R. Bhushan Gopaluni" order: 52 year: 2015 title: "Evaluation of treatment regimens for blood glucose control in type II diabetic patients using mathematical modeling" journal: "In proceedings of 34th Chinese Control Conference, Nanjing, China" pagenum: "8519 – 8524" ---
daisubc/daisubc.github.io
_papers/2015-ekram-evaluation-of-treatment-regimens-for-in.md
Markdown
mit
362
package com.cezarykluczynski.stapi.etl.content_language.dto; import lombok.AllArgsConstructor; import lombok.Data; @Data @AllArgsConstructor(staticName = "of") public class ContentLanguageDTO { private String name; private String code; }
cezarykluczynski/stapi
etl/src/main/java/com/cezarykluczynski/stapi/etl/content_language/dto/ContentLanguageDTO.java
Java
mit
245
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { Store, StoreModule } from '@ngrx/store'; import { AppComponent } from './app.component'; import { Child } from './child.component'; import { Child2 } from './child2.component'; import { appState } from './reducer.appstate'; @NgModule({ imports: [ BrowserModule, StoreModule.provideStore({appState}) ], declarations: [ AppComponent, Child, Child2 ], bootstrap: [ AppComponent ] }) export class AppModule { }
patrickkee/angular2-sandbox
app/app.module.ts
TypeScript
mit
562
For documentation please visit the following URL: https://devkit.tiwiconnect.com/advanced/liftserver-python/
lsresearch/liftserver-python
README.md
Markdown
mit
110
<?php namespace Gis\Domain\Spatial\Model\Layer; use Gis\Core\DataProvider\BaseDataProvider; use Gis\Core\DataProvider\QueryBuilder; use Gis\Core\DataProvider\IDataStruct; use Gis\Core\Connection\IConnectionFactory; /** * The DataProvider used to run SQL queries against the layers table */ class LayerDataProvider extends BaseDataProvider implements ILayerDataProvider { /** * @param IConnectionFactory $connectionFactory */ public function __construct(IConnectionFactory $connectionFactory) { parent::__construct($connectionFactory); } /** * This method is required if we want to use the boilerplate getById method that is provided * * @param int $id * @return string */ public function getSelectSQL($id) { $query = "SELECT id, name, X(min_lat_long) as minX, Y(min_lat_long) as minY, X(max_lat_long) as maxX, Y(max_lat_long) as maxY, color, enabled, position, zoom_min, zoom_max FROM layers WHERE id = :id"; $qb = new QueryBuilder($query); $qb->bindInt('id', $id); return $qb->prepare(); } /** * Used to map the table to the struct * * @param object $row - The record from the database * @return IDataStruct */ public function mapRow($row) { $layerStruct = new LayerStruct(); $layerStruct->id = $row->id; $layerStruct->description = $row->description; $layerStruct->minX = $row->minX; $layerStruct->minY = $row->minY; $layerStruct->maxX = $row->maxX; $layerStruct->maxY = $row->maxY; $layerStruct->color = $row->color; $layerStruct->enabled = $row->enabled; $layerStruct->position = $row->position; $layerStruct->zoomMin = $row->zoom_min; $layerStruct->zoomMax = $row->zoom_max; return $layerStruct; } /** * @param IDataStruct $struct * @return int - The primary Key */ public function insert(IDataStruct $struct) { $query = "INSERT INTO layers ( `name`, `min_lat_long`, `max_lat_long`, `color`, `enabled`, `position`, `zoom_min`, `zoom_max`) VALUES ( :name, GeomFromText('POINT(:minx :miny)'), GeomFromText('POINT(:maxx :maxy)'), :color, :enabled, :position, :zoom_min, :zoom_max)"; $qb = new QueryBuilder($query); $qb->bindString('name', $struct->name); $qb->bindFloat('minx', $struct->minX); $qb->bindFloat('miny', $struct->minY); $qb->bindFloat('maxx', $struct->maxX); $qb->bindFloat('maxy', $struct->maxY); $qb->bindString('color', $struct->color); $qb->bindInt('enabled', $struct->enabled); $qb->bindInt('position', $struct->position); $qb->bindInt('zoom_min', $struct->zoomMin); $qb->bindInt('zoom_max', $struct->zoomMax); $this->getConnectionFactory() ->getWriteConnection() ->query($qb->prepare()); return $this->getConnectionFactory() ->getWriteConnection() ->lastInsertId(); } /** * @param IDataStruct $struct */ public function update(IDataStruct $struct) { $query = "UPDATE layers SET name=:name, min_lat_long=GeomFromText('POINT(:minx :miny)'), max_lat_long=GeomFromText('POINT(:maxx :maxy)'), color=:color, enabled=:enabled, position=:position, zoom_min=:zoom_min, zoom_max=:zoom_max WHERE id=:id"; $qb = new QueryBuilder($query); $qb->bindString('name', $struct->description); $qb->bindFloat('minx', $struct->minX); $qb->bindFloat('miny', $struct->minY); $qb->bindFloat('maxx', $struct->maxX); $qb->bindFloat('maxy', $struct->maxY); $qb->bindString('color', $struct->color); $qb->bindInt('enabled', $struct->enabled); $qb->bindInt('position', $struct->position); $qb->bindInt('zoom_min', $struct->zoomMin); $qb->bindInt('zoom_max', $struct->zoomMax); $qb->bindInt('id', $struct->id); $this->getConnectionFactory() ->getWriteConnection() ->query($qb->prepare()); } /** * @TODO - This is horrible. Need to add the type to the layer table * @param [type] $layerId [description] * @return [type] [description] */ public function getLayerType($layerId) { $query = "SELECT type FROM sets WHERE layer=:layerId LIMIT 1"; $qb = new QueryBuilder($query); $qb->bindInt('layerId', $layerId); $res = $this->getConnectionFactory() ->getReadConnection() ->query($qb->prepare()); return $res[0]->type; } /** * Fetch all of the active layers to be drawn ordered by * position, id * * @param int $zoom If passed in this will filter the result based on zoom_min & zoom_max * @return LayerStruct */ public function getActive($zoom = null) { $query = "SELECT * FROM layers WHERE enabled=1 "; if(!is_null($zoom)) { $query .= " AND zoom_min<=:zoom AND zoom_max >=:zoom "; } $query .= "order by position, id"; $qb = new QueryBuilder($query); $qb->bindInt('zoom', $zoom); $res = $this->getConnectionFactory() ->getReadConnection() ->query($qb->prepare()); return $this->createDataStructs($res); } }
manatok/gis
src/Gis/Domain/Spatial/Model/Layer/LayerDataProvider.php
PHP
mit
5,206
/********************************************************************** Copyright (c) 2016 Advanced Micro Devices, Inc. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ********************************************************************/ #include "cl_uberv2_generator.h" using namespace Baikal; inline int popcount(std::uint32_t value) { int count = value ? 1 : 0; while (value &= (value - 1)) { ++count; } return count; } CLUberV2Generator::CLUberV2Generator() { } CLUberV2Generator::~CLUberV2Generator() { } void CLUberV2Generator::AddMaterial(UberV2Material::Ptr material) { std::uint32_t layers = material->GetLayers(); // Check if we already have such material type processed if (m_materials.find(layers) != m_materials.end()) { return; } UberV2Sources src; MaterialGeneratePrepareInputs(material, &src); MaterialGenerateGetPdf(material, &src); MaterialGenerateSample(material, &src); MaterialGenerateGetBxDFType(material, &src); MaterialGenerateEvaluate(material, &src); m_materials[layers] = src; } void CLUberV2Generator::MaterialGeneratePrepareInputs(UberV2Material::Ptr material, UberV2Sources *sources) { static const std::string reader_function_arguments("material_attributes[offset++], dg, input_map_values, TEXTURE_ARGS"); struct LayerReader { std::string variable; std::string reader; }; // Should have same order as in ClwSceneController::WriteMaterial static const std::vector<std::pair<UberV2Material::Layers, std::vector<LayerReader>>> readers = { { UberV2Material::Layers::kEmissionLayer, { {"data->emission_color", "GetInputMapFloat4"} } }, { UberV2Material::Layers::kCoatingLayer, { {"data->coating_color", "GetInputMapFloat4"}, {"data->coating_ior", "GetInputMapFloat"} } }, { UberV2Material::Layers::kReflectionLayer, { {"data->reflection_color", "GetInputMapFloat4"}, {"data->reflection_roughness", "GetInputMapFloat"}, {"data->reflection_anisotropy", "GetInputMapFloat"}, {"data->reflection_anisotropy_rotation", "GetInputMapFloat"}, {"data->reflection_ior", "GetInputMapFloat"}, {"data->reflection_metalness", "GetInputMapFloat"} } }, { UberV2Material::Layers::kDiffuseLayer, { {"data->diffuse_color", "GetInputMapFloat4"} } }, { UberV2Material::Layers::kRefractionLayer, { {"data->refraction_color", "GetInputMapFloat4"}, {"data->refraction_roughness", "GetInputMapFloat"}, {"data->refraction_ior", "GetInputMapFloat"} } }, { UberV2Material::Layers::kTransparencyLayer, { {"data->transparency", "GetInputMapFloat"} } }, { UberV2Material::Layers::kShadingNormalLayer, { {"data->shading_normal", "GetInputMapFloat4"}, } }, { UberV2Material::Layers::kSSSLayer, { {"data->sss_absorption_color", "GetInputMapFloat4"}, {"data->sss_scatter_color", "GetInputMapFloat4"}, {"data->sss_subsurface_color", "GetInputMapFloat4"}, {"data->sss_absorption_distance", "GetInputMapFloat"}, {"data->sss_scatter_distance", "GetInputMapFloat"}, {"data->sss_scatter_direction", "GetInputMapFloat"}, } } }; // Reserve 4k. This should be enought for maximum configuration sources->m_prepare_inputs.reserve(4096); // Write base code std::uint32_t layers = material->GetLayers(); sources->m_prepare_inputs = "void UberV2PrepareInputs" + std::to_string(layers) + "(" "DifferentialGeometry const* dg, GLOBAL InputMapData const* restrict input_map_values," "GLOBAL int const* restrict material_attributes, TEXTURE_ARG_LIST, UberV2ShaderData *data)\n" "{\n" "\tint offset = dg->mat.offset + 1;\n"; // Write code for each layer for (auto &reader: readers) { // If current layer exist in material - write it if ((layers & reader.first) == reader.first) { for (auto &r : reader.second) { sources->m_prepare_inputs += std::string("\t") + r.variable + " = " + r.reader + "(" + reader_function_arguments + ");\n"; } } } sources->m_prepare_inputs += "\n}"; } std::string CLUberV2Generator::GenerateBlend(const BlendData &blend_data, bool is_float) { std::string fresnel_function = is_float ? "Fresnel_Blend_F" : "Fresnel_Blend"; std::string result = is_float ? "0.0f" : "(float3)(0.0f)"; result.reserve(1024); //1k should be enought std::string brdf; brdf.reserve(1024); auto GenerateFresnelBlend = [&](const std::string &top_ior, const std::string &bottom_ior, const std::string &top_value, const std::string &bottom_value) -> std::string { std::string value = fresnel_function; value += "(" + top_ior + ", " + bottom_ior + ", " + top_value + ", " + bottom_value + ", wi)"; return value; }; // Generate BRDF first if (!blend_data.m_brdf_values.empty()) { brdf = "(" + blend_data.m_brdf_values[blend_data.m_brdf_values.size() - 1] + ")"; for (size_t a = blend_data.m_brdf_iors.size() - 1; a > 0 ; --a) { brdf = "(" + GenerateFresnelBlend(blend_data.m_brdf_iors[a - 1], blend_data.m_brdf_iors[a], blend_data.m_brdf_values[a -1], brdf) + ")"; } } // Btdf std::string bxdf(brdf); if (!blend_data.m_btdf_ior.empty()) { if (brdf.empty()) { bxdf = "(" + blend_data.m_btdf_value + ")"; } else { bxdf = "(" + GenerateFresnelBlend("1.0f", blend_data.m_btdf_ior, brdf, blend_data.m_btdf_value) + ")"; } } if (!bxdf.empty()) { result = bxdf; } // Mix for transparency if (!blend_data.m_transparency_value.empty()) { if (!bxdf.empty()) { result = "mix(" + result + ", 0.f" + ", " + blend_data.m_transparency_value + ")"; } else if (!brdf.empty()) { result = "mix(" + result + ", 0.f" + ", " + blend_data.m_transparency_value + ")"; } else { result = "0.f"; } } return result; } void CLUberV2Generator::MaterialGenerateGetPdf(UberV2Material::Ptr material, UberV2Sources *sources) { std::uint32_t layers = material->GetLayers(); sources->m_get_pdf = "float UberV2_GetPdf" + std::to_string(layers) + "(" "DifferentialGeometry const* dg, float3 wi, float3 wo, TEXTURE_ARG_LIST, UberV2ShaderData const* shader_data)\n" "{\n"; BlendData blend; blend.m_brdf_iors.push_back("1.0f"); // BRDF layers if ((layers & UberV2Material::Layers::kCoatingLayer) == UberV2Material::Layers::kCoatingLayer) { blend.m_brdf_iors.push_back("shader_data->coating_ior"); blend.m_brdf_values.push_back("UberV2_IdealReflect_GetPdf(shader_data, wi, wo, TEXTURE_ARGS)"); } if ((layers & UberV2Material::Layers::kReflectionLayer) == UberV2Material::Layers::kReflectionLayer) { blend.m_brdf_iors.push_back("shader_data->reflection_ior"); blend.m_brdf_values.push_back("UberV2_Reflection_GetPdf(shader_data, wi, wo, TEXTURE_ARGS)"); } if ((layers & UberV2Material::Layers::kDiffuseLayer) == UberV2Material::Layers::kDiffuseLayer) { blend.m_brdf_values.push_back("UberV2_Lambert_GetPdf(shader_data, wi, wo, TEXTURE_ARGS)"); } // BTDF if ((layers & UberV2Material::Layers::kRefractionLayer) == UberV2Material::Layers::kRefractionLayer) { blend.m_btdf_ior = "shader_data->refraction_ior"; blend.m_btdf_value = "UberV2_Refraction_GetPdf(shader_data, wi, wo, TEXTURE_ARGS)"; } //Transparency if ((layers & UberV2Material::Layers::kTransparencyLayer) == UberV2Material::Layers::kTransparencyLayer) { blend.m_transparency_value = "shader_data->transparency"; } sources->m_get_pdf += "\treturn " + GenerateBlend(blend, true) + ";\n}\n"; } void CLUberV2Generator::MaterialGenerateSample(UberV2Material::Ptr material, UberV2Sources *sources) { std::uint32_t layers = material->GetLayers(); sources->m_sample = "float3 UberV2_Sample" + std::to_string(layers) + "(DifferentialGeometry const* dg, float3 wi, TEXTURE_ARG_LIST, float2 sample, float3* wo, float* pdf," "UberV2ShaderData const* shader_data)\n" "{\n" "\tconst int sampledComponent = Bxdf_UberV2_GetSampledComponent(dg);\n" "\tfloat3 result;\n" "\tswitch(sampledComponent)\n" "\t{\n"; std::vector<std::pair<std::uint32_t, std::string>> component_sampling = { {UberV2Material::Layers::kTransparencyLayer, "\t\tcase kBxdfUberV2SampleTransparency: result = UberV2_Passthrough_Sample(shader_data, wi, TEXTURE_ARGS, sample, wo, pdf);\n\t\t\tbreak;\n"}, {UberV2Material::Layers::kCoatingLayer, "\t\tcase kBxdfUberV2SampleCoating: result = UberV2_Coating_Sample(shader_data, wi, TEXTURE_ARGS, wo, pdf);\n\t\t\tbreak;\n"}, {UberV2Material::Layers::kReflectionLayer, "\t\tcase kBxdfUberV2SampleReflection: result = UberV2_Reflection_Sample(shader_data, wi, TEXTURE_ARGS, sample, wo, pdf);\n\t\t\tbreak;\n" }, {UberV2Material::Layers::kRefractionLayer, "\t\tcase kBxdfUberV2SampleRefraction: result = UberV2_Refraction_Sample(shader_data, wi, TEXTURE_ARGS, sample, wo, pdf);\n\t\t\tbreak;\n"}, {UberV2Material::Layers::kDiffuseLayer, "\t\tcase kBxdfUberV2SampleDiffuse: result = UberV2_Lambert_Sample(shader_data, wi, TEXTURE_ARGS, sample, wo, pdf);\n\t\t\tbreak;\n" } }; for (auto &component : component_sampling) { if ((layers & component.first) == component.first) { sources->m_sample += component.second; } } sources->m_sample += "\t}\n" // Temporaty disable this code. It leads to incorrect work in UberV2Test // "\tif (!Bxdf_IsSingular(dg))\n" "\tif (false)\n" "\t{\n" "\t\t*pdf = UberV2_GetPdf" + std::to_string(layers) + "(dg, wi, *wo, TEXTURE_ARGS, shader_data);\n" "\t\treturn UberV2_Evaluate" + std::to_string(layers) + "(dg, wi, *wo, TEXTURE_ARGS, shader_data);\n" "\t}\n" "\treturn result;\n" "}\n"; } void CLUberV2Generator::MaterialGenerateGetBxDFType(UberV2Material::Ptr material, UberV2Sources *sources) { std::uint32_t layers = material->GetLayers(); sources->m_get_bxdf_type = "void GetMaterialBxDFType" + std::to_string(layers) + "(" "float3 wi, Sampler* sampler, SAMPLER_ARG_LIST, DifferentialGeometry* dg, UberV2ShaderData const* shader_data)\n" "{\n" "\tint bxdf_flags = 0;\n"; // If we have layer that requires fresnel blend (reflection/refraction/coating) if ((layers & (UberV2Material::Layers::kReflectionLayer | UberV2Material::Layers::kRefractionLayer | UberV2Material::Layers::kCoatingLayer )) != 0) { sources->m_get_bxdf_type += "\tconst float ndotwi = dot(dg->n, wi);\n"; } if ((layers & UberV2Material::Layers::kEmissionLayer) == UberV2Material::Layers::kEmissionLayer) { sources->m_get_bxdf_type += "\tbxdf_flags |= kBxdfFlagsEmissive;\n"; } //Check if blend layers have underlying layers bool transparency_has_underlying_layer = popcount(layers & ( UberV2Material::Layers::kRefractionLayer | UberV2Material::Layers::kCoatingLayer | UberV2Material::Layers::kReflectionLayer | UberV2Material::Layers::kDiffuseLayer)) != 0; bool refraction_has_underlying_layer = popcount(layers & ( UberV2Material::Layers::kCoatingLayer | UberV2Material::Layers::kReflectionLayer | UberV2Material::Layers::kDiffuseLayer)) != 0; bool coating_has_underlying_layer = popcount(layers & ( UberV2Material::Layers::kReflectionLayer | UberV2Material::Layers::kDiffuseLayer)) != 0; bool reflection_has_underlying_layer = popcount(layers & ( UberV2Material::Layers::kDiffuseLayer)) != 0; if ((layers & UberV2Material::Layers::kTransparencyLayer) == UberV2Material::Layers::kTransparencyLayer) { // If layer have transparency check in OpenCL if we sample it and if we sample it - return sources->m_get_bxdf_type += (transparency_has_underlying_layer ? "\tconst float sample = Sampler_Sample1D(sampler, SAMPLER_ARGS);\n" "\tif (sample < shader_data->transparency)\n" "\t{\n" : "") + std::string( "\t\tbxdf_flags |= (kBxdfFlagsTransparency | kBxdfFlagsSingular);\n" "\t\tBxdf_SetFlags(dg, bxdf_flags);\n" "\t\tBxdf_UberV2_SetSampledComponent(dg, kBxdfUberV2SampleTransparency);\n" "\t\treturn;\n") + (transparency_has_underlying_layer ? "\t}\n" : ""); } // Check refraction layer. If we have it and plan to sample it - set flags and sampled component if ((layers & UberV2Material::Layers::kRefractionLayer) == UberV2Material::Layers::kRefractionLayer) { sources->m_get_bxdf_type += (refraction_has_underlying_layer ? "\tconst float sample1 = Sampler_Sample1D(sampler, SAMPLER_ARGS);\n" "\tconst float fresnel = CalculateFresnel(1.0f, shader_data->refraction_ior, ndotwi);\n" "\tif (sample1 >= fresnel)\n" "\t{\n" : "") + std::string("\t\tBxdf_UberV2_SetSampledComponent(dg, kBxdfUberV2SampleRefraction);\n" "\t\tif (shader_data->refraction_roughness < ROUGHNESS_EPS)\n" "\t\t{\n" "\t\t\tbxdf_flags |= kBxdfFlagsSingular;\n" "\t\t}\n" "\t\tBxdf_SetFlags(dg, bxdf_flags);\n" "\t\treturn;\n") + (refraction_has_underlying_layer ? "\t}\n" : ""); } if ((layers & (UberV2Material::Layers::kReflectionLayer | UberV2Material::Layers::kRefractionLayer | UberV2Material::Layers::kCoatingLayer )) != 0) { sources->m_get_bxdf_type += "\tbxdf_flags |= kBxdfFlagsBrdf;\n" "\tfloat top_ior = 1.0f;\n"; } if ((layers & UberV2Material::Layers::kCoatingLayer) == UberV2Material::Layers::kCoatingLayer) { sources->m_get_bxdf_type += (coating_has_underlying_layer ? "\tconst float sample3 = Sampler_Sample1D(sampler, SAMPLER_ARGS);\n" "\tconst float fresnel1 = CalculateFresnel(top_ior, shader_data->coating_ior, ndotwi);\n" "\tif (sample3 < fresnel1)\n" "\t{\n" : "") + std::string( "\t\tbxdf_flags |= kBxdfFlagsSingular;\n" "\t\tBxdf_SetFlags(dg, bxdf_flags);\n" "\t\tBxdf_UberV2_SetSampledComponent(dg, kBxdfUberV2SampleCoating);\n" "\t\treturn;\n") + (coating_has_underlying_layer ? "\t}\n" "\ttop_ior = shader_data->coating_ior;\n" : ""); } if ((layers & UberV2Material::Layers::kReflectionLayer) == UberV2Material::Layers::kReflectionLayer) { sources->m_get_bxdf_type += (reflection_has_underlying_layer ? "\tconst float fresnel2 = CalculateFresnel(top_ior, shader_data->reflection_ior, ndotwi);\n" "\tconst float sample4 = Sampler_Sample1D(sampler, SAMPLER_ARGS);\n" "\tif (sample4 < fresnel2)\n" "\t{\n" : "") + std::string( "\t\tif (shader_data->reflection_roughness < ROUGHNESS_EPS)\n" "\t\t{\n" "\t\t\tbxdf_flags |= kBxdfFlagsSingular;\n" "\t\t}\n" "\t\tBxdf_UberV2_SetSampledComponent(dg, kBxdfUberV2SampleReflection);\n" "\t\tBxdf_SetFlags(dg, bxdf_flags);\n" "\t\treturn;\n") + (reflection_has_underlying_layer ? "\t}\n" : ""); } if ((layers & UberV2Material::Layers::kDiffuseLayer) == UberV2Material::Layers::kDiffuseLayer) { sources->m_get_bxdf_type += "\tBxdf_UberV2_SetSampledComponent(dg, kBxdfUberV2SampleDiffuse);\n" "\tbxdf_flags |= kBxdfFlagsBrdf;\n"; } sources->m_get_bxdf_type += "\tBxdf_SetFlags(dg, bxdf_flags);\n" "return;\n" "}\n"; } void CLUberV2Generator::MaterialGenerateEvaluate(UberV2Material::Ptr material, UberV2Sources *sources) { std::uint32_t layers = material->GetLayers(); sources->m_evaluate = "float3 UberV2_Evaluate" + std::to_string(layers) + "(" "DifferentialGeometry const* dg, float3 wi, float3 wo, TEXTURE_ARG_LIST, UberV2ShaderData const* shader_data)\n" "{\n"; BlendData blend; blend.m_brdf_iors.push_back("1.0f"); // BRDF layers if ((layers & UberV2Material::Layers::kCoatingLayer) == UberV2Material::Layers::kCoatingLayer) { blend.m_brdf_iors.push_back("shader_data->coating_ior"); blend.m_brdf_values.push_back("UberV2_IdealReflect_Evaluate(shader_data, wi, wo, TEXTURE_ARGS)"); } if ((layers & UberV2Material::Layers::kReflectionLayer) == UberV2Material::Layers::kReflectionLayer) { blend.m_brdf_iors.push_back("shader_data->reflection_ior"); blend.m_brdf_values.push_back("UberV2_Reflection_Evaluate(shader_data, wi, wo, TEXTURE_ARGS)"); } if ((layers & UberV2Material::Layers::kDiffuseLayer) == UberV2Material::Layers::kDiffuseLayer) { blend.m_brdf_values.push_back("UberV2_Lambert_Evaluate(shader_data, wi, wo, TEXTURE_ARGS)"); } // BTDF if ((layers & UberV2Material::Layers::kRefractionLayer) == UberV2Material::Layers::kRefractionLayer) { blend.m_btdf_ior = "shader_data->refraction_ior"; blend.m_btdf_value = "UberV2_Refraction_Evaluate(shader_data, wi, wo, TEXTURE_ARGS)"; } //Transparency if ((layers & UberV2Material::Layers::kTransparencyLayer) == UberV2Material::Layers::kTransparencyLayer) { blend.m_transparency_value = "shader_data->transparency"; } sources->m_evaluate += "\treturn " + GenerateBlend(blend, false) + ";\n}\n"; } std::string Baikal::CLUberV2Generator::BuildSource() { std::string source; source.reserve(10240); //10k should be enought // Merge all per-material sources for(auto material : m_materials) { source += material.second.m_get_bxdf_type + "\n"; source += material.second.m_evaluate + "\n"; source += material.second.m_get_pdf + "\n"; source += material.second.m_prepare_inputs + "\n"; source += material.second.m_sample + "\n"; } source += GeneratePrepareInputsDispatcher(); source += GenerateGetBxDFTypeDispatcher(); source += GenerateGetPdfDispatcher(); source += GenerateEvaluateDispatcher(); source += GenerateSampleDispatcher(); return source; } std::string Baikal::CLUberV2Generator::GenerateEvaluateDispatcher() { std::string source; source.reserve(1024); //10k should be enought source = "float3 UberV2_Evaluate" "(DifferentialGeometry const* dg, float3 wi, float3 wo, TEXTURE_ARG_LIST, UberV2ShaderData const* shader_data)\n" "{\n" "\tfloat3 wi_t = matrix_mul_vector3(dg->world_to_tangent, wi);\n" "\tfloat3 wo_t = matrix_mul_vector3(dg->world_to_tangent, wo);\n" "\tswitch (dg->mat.layers)\n" "\t{\n"; for(auto material : m_materials) { source += "\t\tcase " + std::to_string(material.first) + ":\n" + "\t\t\treturn UberV2_Evaluate" + std::to_string(material.first) + "(dg, wi_t, wo_t, TEXTURE_ARGS, shader_data);\n"; } source += "\t}\n\treturn (float3)(0.0f);\n}\n"; return source; } std::string Baikal::CLUberV2Generator::GenerateGetPdfDispatcher() { std::string source; source.reserve(1024); //10k should be enought source = "float UberV2_GetPdf" "(DifferentialGeometry const* dg, float3 wi, float3 wo, TEXTURE_ARG_LIST, UberV2ShaderData const* shader_data)\n" "{\n" "\tfloat3 wi_t = matrix_mul_vector3(dg->world_to_tangent, wi);\n" "\tfloat3 wo_t = matrix_mul_vector3(dg->world_to_tangent, wo);\n" "\tswitch (dg->mat.layers)\n" "\t{\n"; for(auto material : m_materials) { source += "\t\tcase " + std::to_string(material.first) + ":\n" + "\t\t\treturn UberV2_GetPdf" + std::to_string(material.first) + "(dg, wi_t, wo_t, TEXTURE_ARGS, shader_data);\n"; } source += "\t}\n\treturn 0.0f;\n}\n"; return source; } std::string Baikal::CLUberV2Generator::GenerateSampleDispatcher() { std::string source; source.reserve(1024); //10k should be enought source = "float3 UberV2_Sample" "(DifferentialGeometry const* dg, float3 wi, TEXTURE_ARG_LIST, float2 sample, " "float3 *wo, float *pdf, UberV2ShaderData const* shader_data)\n" "{\n" "\tfloat3 wi_t = matrix_mul_vector3(dg->world_to_tangent, wi);\n" "\tfloat3 wo_t;\n" "\tfloat3 res = 0.f;\n" "\tswitch (dg->mat.layers)\n" "\t{\n"; for(auto material : m_materials) { source += "\t\tcase " + std::to_string(material.first) + ":\n" + "\t\t\tres = UberV2_Sample" + std::to_string(material.first) + "(dg, wi_t, TEXTURE_ARGS, sample, &wo_t, pdf, shader_data);\n" "\t\t\tbreak;\n"; } source += "\t}\n" "\t*wo = matrix_mul_vector3(dg->tangent_to_world, wo_t);" "\treturn res;\n" "}\n"; return source; } std::string Baikal::CLUberV2Generator::GeneratePrepareInputsDispatcher() { std::string source = "void UberV2PrepareInputs(" "DifferentialGeometry const* dg, GLOBAL InputMapData const* restrict input_map_values," "GLOBAL int const* restrict material_attributes, TEXTURE_ARG_LIST, UberV2ShaderData *shader_data)\n" "{\n" "\tswitch(dg->mat.layers)\n" "\t{\n"; for(auto material : m_materials) { source += "\t\tcase " + std::to_string(material.first) + ":\n" + "\t\t\treturn UberV2PrepareInputs" + std::to_string(material.first) + "(dg, input_map_values, material_attributes, TEXTURE_ARGS, shader_data);\n"; } source += "\t}\n" "}\n"; return source; } std::string Baikal::CLUberV2Generator::GenerateGetBxDFTypeDispatcher() { std::string source = "void GetMaterialBxDFType(" "float3 wi, Sampler* sampler, SAMPLER_ARG_LIST, DifferentialGeometry* dg, UberV2ShaderData const* shader_data)" "{\n" "\tswitch(dg->mat.layers)\n" "\t{\n"; for(auto material : m_materials) { source += "\t\tcase " + std::to_string(material.first) + ":\n" + "\t\t\treturn GetMaterialBxDFType" + std::to_string(material.first) + "(wi, sampler, SAMPLER_ARGS, dg, shader_data);\n" "\t\t\tbreak;\n"; } source += "\t}\n" "}\n"; return source; }
GPUOpen-LibrariesAndSDKs/RadeonProRender-Baikal
Baikal/Utils/cl_uberv2_generator.cpp
C++
mit
24,981