text
stringlengths
2
1.04M
meta
dict
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>cantor: 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.12.0 / cantor - 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> cantor <small> 8.6.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-09-13 14:50:05 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-09-13 14:50:05 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 coq 8.12.0 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.10.2 The OCaml compiler (virtual package) ocaml-base-compiler 4.10.2 Official release 4.10.2 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.5 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;[email protected]&quot; homepage: &quot;https://github.com/coq-contribs/cantor&quot; license: &quot;LGPL&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Cantor&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.6&quot; &amp; &lt; &quot;8.7~&quot;} ] tags: [ &quot;keyword: ordinal numbers&quot; &quot;keyword: well-foundedness&quot; &quot;keyword: termination&quot; &quot;keyword: rpo&quot; &quot;keyword: Goodstein sequences&quot; &quot;category: Mathematics/Logic&quot; &quot;category: Mathematics/Arithmetic and Number Theory/Number theory&quot; &quot;date: 2006-05-22&quot; ] authors: [ &quot;Pierre Castéran &lt;[email protected]&gt; [http://www.labri.fr/~casteran/]&quot; &quot;Évelyne Contejean &lt;[email protected]&gt; [http://www.lri.fr/~contejea]&quot; ] bug-reports: &quot;https://github.com/coq-contribs/cantor/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/cantor.git&quot; synopsis: &quot;On Ordinal Notations&quot; description: &quot;&quot;&quot; This contribution contains data structures for ordinals less than Gamma0 under Cantor and Veblen normal forms. Well-foundedness is established thanks to RPO with status for generic terms. This contribution also includes termination proofs of Hydra battles and Goodstein sequences as well as a computation of the length of the Goodstein sequence starting from 4 in base 2. This work is supported by INRIA-Futurs (Logical project-team), CNRS and the French ANR via the A3PAT project (http://www3.iie.cnam.fr/~urbain/a3pat/).&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/cantor/archive/v8.6.0.tar.gz&quot; checksum: &quot;md5=0d9dd2dbc4113114badd1eacec30748c&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-cantor.8.6.0 coq.8.12.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.12.0). The following dependencies couldn&#39;t be met: - coq-cantor -&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-cantor.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>
{ "content_hash": "d6e2efa279e99106ada3c574879490ce", "timestamp": "", "source": "github", "line_count": 177, "max_line_length": 190, "avg_line_length": 41.847457627118644, "alnum_prop": 0.5596057783178074, "repo_name": "coq-bench/coq-bench.github.io", "id": "d76343a4962bbc6f055c426cb3ea236dfb0c7883", "size": "7434", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.10.2-2.0.6/released/8.12.0/cantor/8.6.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
/* Ported to JavaScript by Lazar Laszlo 2011 [email protected], www.lazarsoft.info */ /* * * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var FORMAT_INFO_MASK_QR = 0x5412; var FORMAT_INFO_DECODE_LOOKUP = [ [0x5412, 0x00], [0x5125, 0x01], [0x5E7C, 0x02], [0x5B4B, 0x03], [0x45F9, 0x04], [0x40CE, 0x05], [0x4F97, 0x06], [0x4AA0, 0x07], [0x77C4, 0x08], [0x72F3, 0x09], [0x7DAA, 0x0A], [0x789D, 0x0B], [0x662F, 0x0C], [0x6318, 0x0D], [0x6C41, 0x0E], [0x6976, 0x0F], [0x1689, 0x10], [0x13BE, 0x11], [0x1CE7, 0x12], [0x19D0, 0x13], [0x0762, 0x14], [0x0255, 0x15], [0x0D0C, 0x16], [0x083B, 0x17], [0x355F, 0x18], [0x3068, 0x19], [0x3F31, 0x1A], [0x3A06, 0x1B], [0x24B4, 0x1C], [0x2183, 0x1D], [0x2EDA, 0x1E], [0x2BED, 0x1F], ]; var BITS_SET_IN_HALF_BYTE = [ 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 ]; function FormatInformation(formatInfo) { this.errorCorrectionLevel = ErrorCorrectionLevel.forBits((formatInfo >> 3) & 0x03); this.dataMask = (formatInfo & 0x07); this.__defineGetter__("ErrorCorrectionLevel", function() { return this.errorCorrectionLevel; }); this.__defineGetter__("DataMask", function() { return this.dataMask; }); this.GetHashCode=function() { return (this.errorCorrectionLevel.ordinal() << 3) | this.dataMask; } this.Equals=function( o) { var other = o; return this.errorCorrectionLevel == other.errorCorrectionLevel && this.dataMask == other.dataMask; } } FormatInformation.numBitsDiffering=function( a, b) { a ^= b; // a now has a 1 bit exactly where its bit differs with b's // Count bits set quickly with a series of lookups: return BITS_SET_IN_HALF_BYTE[a & 0x0F] + BITS_SET_IN_HALF_BYTE[(URShift(a, 4) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 8) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 12) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 16) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 20) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 24) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 28) & 0x0F)]; } FormatInformation.decodeFormatInformation=function( maskedFormatInfo) { var formatInfo = FormatInformation.doDecodeFormatInformation(maskedFormatInfo); if (formatInfo != null) { return formatInfo; } // Should return null, but, some QR codes apparently // do not mask this info. Try again by actually masking the pattern // first return FormatInformation.doDecodeFormatInformation(maskedFormatInfo ^ FORMAT_INFO_MASK_QR); } FormatInformation.doDecodeFormatInformation=function( maskedFormatInfo) { // Find the int in FORMAT_INFO_DECODE_LOOKUP with fewest bits differing var bestDifference = 0xffffffff; var bestFormatInfo = 0; for (var i = 0; i < FORMAT_INFO_DECODE_LOOKUP.length; i++) { var decodeInfo = FORMAT_INFO_DECODE_LOOKUP[i]; var targetInfo = decodeInfo[0]; if (targetInfo == maskedFormatInfo) { // Found an exact match return new FormatInformation(decodeInfo[1]); } var bitsDifference = this.numBitsDiffering(maskedFormatInfo, targetInfo); if (bitsDifference < bestDifference) { bestFormatInfo = decodeInfo[1]; bestDifference = bitsDifference; } } // Hamming distance of the 32 masked codes is 7, by construction, so <= 3 bits // differing means we found a match if (bestDifference <= 3) { return new FormatInformation(bestFormatInfo); } return null; }
{ "content_hash": "ba24036102b8b243df668eeae8ac6442", "timestamp": "", "source": "github", "line_count": 114, "max_line_length": 381, "avg_line_length": 34.73684210526316, "alnum_prop": 0.6833333333333333, "repo_name": "fantaclaus/jsqrcode", "id": "bb60be66bfc3f72559d6074d4a768e61293b01ac", "size": "3960", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/formatinf.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "5909" }, { "name": "JavaScript", "bytes": "124382" } ], "symlink_target": "" }
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-m-rel-xr-w32-bld/build/content/base/public/nsIXMLHttpRequest.idl */ #ifndef __gen_nsIXMLHttpRequest_h__ #define __gen_nsIXMLHttpRequest_h__ #ifndef __gen_nsIDOMEventTarget_h__ #include "nsIDOMEventTarget.h" #endif #include "jspubtd.h" /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif class nsIChannel; /* forward declaration */ class nsIDOMDocument; /* forward declaration */ class nsIDOMEventListener; /* forward declaration */ class nsIPrincipal; /* forward declaration */ class nsIScriptContext; /* forward declaration */ class nsIURI; /* forward declaration */ class nsIVariant; /* forward declaration */ class nsPIDOMWindow; /* forward declaration */ class nsIInputStream; /* forward declaration */ class nsIDOMBlob; /* forward declaration */ // for jsval #include "jsapi.h" /* starting interface: nsIXMLHttpRequestEventTarget */ #define NS_IXMLHTTPREQUESTEVENTTARGET_IID_STR "dea238a1-240f-45f4-9f07-7769bc69eb76" #define NS_IXMLHTTPREQUESTEVENTTARGET_IID \ {0xdea238a1, 0x240f, 0x45f4, \ { 0x9f, 0x07, 0x77, 0x69, 0xbc, 0x69, 0xeb, 0x76 }} class NS_NO_VTABLE NS_SCRIPTABLE nsIXMLHttpRequestEventTarget : public nsIDOMEventTarget { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IXMLHTTPREQUESTEVENTTARGET_IID) /* attribute nsIDOMEventListener onabort; */ NS_SCRIPTABLE NS_IMETHOD GetOnabort(nsIDOMEventListener * *aOnabort) = 0; NS_SCRIPTABLE NS_IMETHOD SetOnabort(nsIDOMEventListener *aOnabort) = 0; /* attribute nsIDOMEventListener onerror; */ NS_SCRIPTABLE NS_IMETHOD GetOnerror(nsIDOMEventListener * *aOnerror) = 0; NS_SCRIPTABLE NS_IMETHOD SetOnerror(nsIDOMEventListener *aOnerror) = 0; /* attribute nsIDOMEventListener onload; */ NS_SCRIPTABLE NS_IMETHOD GetOnload(nsIDOMEventListener * *aOnload) = 0; NS_SCRIPTABLE NS_IMETHOD SetOnload(nsIDOMEventListener *aOnload) = 0; /* attribute nsIDOMEventListener onloadstart; */ NS_SCRIPTABLE NS_IMETHOD GetOnloadstart(nsIDOMEventListener * *aOnloadstart) = 0; NS_SCRIPTABLE NS_IMETHOD SetOnloadstart(nsIDOMEventListener *aOnloadstart) = 0; /* attribute nsIDOMEventListener onprogress; */ NS_SCRIPTABLE NS_IMETHOD GetOnprogress(nsIDOMEventListener * *aOnprogress) = 0; NS_SCRIPTABLE NS_IMETHOD SetOnprogress(nsIDOMEventListener *aOnprogress) = 0; /* attribute nsIDOMEventListener onloadend; */ NS_SCRIPTABLE NS_IMETHOD GetOnloadend(nsIDOMEventListener * *aOnloadend) = 0; NS_SCRIPTABLE NS_IMETHOD SetOnloadend(nsIDOMEventListener *aOnloadend) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIXMLHttpRequestEventTarget, NS_IXMLHTTPREQUESTEVENTTARGET_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIXMLHTTPREQUESTEVENTTARGET \ NS_SCRIPTABLE NS_IMETHOD GetOnabort(nsIDOMEventListener * *aOnabort); \ NS_SCRIPTABLE NS_IMETHOD SetOnabort(nsIDOMEventListener *aOnabort); \ NS_SCRIPTABLE NS_IMETHOD GetOnerror(nsIDOMEventListener * *aOnerror); \ NS_SCRIPTABLE NS_IMETHOD SetOnerror(nsIDOMEventListener *aOnerror); \ NS_SCRIPTABLE NS_IMETHOD GetOnload(nsIDOMEventListener * *aOnload); \ NS_SCRIPTABLE NS_IMETHOD SetOnload(nsIDOMEventListener *aOnload); \ NS_SCRIPTABLE NS_IMETHOD GetOnloadstart(nsIDOMEventListener * *aOnloadstart); \ NS_SCRIPTABLE NS_IMETHOD SetOnloadstart(nsIDOMEventListener *aOnloadstart); \ NS_SCRIPTABLE NS_IMETHOD GetOnprogress(nsIDOMEventListener * *aOnprogress); \ NS_SCRIPTABLE NS_IMETHOD SetOnprogress(nsIDOMEventListener *aOnprogress); \ NS_SCRIPTABLE NS_IMETHOD GetOnloadend(nsIDOMEventListener * *aOnloadend); \ NS_SCRIPTABLE NS_IMETHOD SetOnloadend(nsIDOMEventListener *aOnloadend); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIXMLHTTPREQUESTEVENTTARGET(_to) \ NS_SCRIPTABLE NS_IMETHOD GetOnabort(nsIDOMEventListener * *aOnabort) { return _to GetOnabort(aOnabort); } \ NS_SCRIPTABLE NS_IMETHOD SetOnabort(nsIDOMEventListener *aOnabort) { return _to SetOnabort(aOnabort); } \ NS_SCRIPTABLE NS_IMETHOD GetOnerror(nsIDOMEventListener * *aOnerror) { return _to GetOnerror(aOnerror); } \ NS_SCRIPTABLE NS_IMETHOD SetOnerror(nsIDOMEventListener *aOnerror) { return _to SetOnerror(aOnerror); } \ NS_SCRIPTABLE NS_IMETHOD GetOnload(nsIDOMEventListener * *aOnload) { return _to GetOnload(aOnload); } \ NS_SCRIPTABLE NS_IMETHOD SetOnload(nsIDOMEventListener *aOnload) { return _to SetOnload(aOnload); } \ NS_SCRIPTABLE NS_IMETHOD GetOnloadstart(nsIDOMEventListener * *aOnloadstart) { return _to GetOnloadstart(aOnloadstart); } \ NS_SCRIPTABLE NS_IMETHOD SetOnloadstart(nsIDOMEventListener *aOnloadstart) { return _to SetOnloadstart(aOnloadstart); } \ NS_SCRIPTABLE NS_IMETHOD GetOnprogress(nsIDOMEventListener * *aOnprogress) { return _to GetOnprogress(aOnprogress); } \ NS_SCRIPTABLE NS_IMETHOD SetOnprogress(nsIDOMEventListener *aOnprogress) { return _to SetOnprogress(aOnprogress); } \ NS_SCRIPTABLE NS_IMETHOD GetOnloadend(nsIDOMEventListener * *aOnloadend) { return _to GetOnloadend(aOnloadend); } \ NS_SCRIPTABLE NS_IMETHOD SetOnloadend(nsIDOMEventListener *aOnloadend) { return _to SetOnloadend(aOnloadend); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIXMLHTTPREQUESTEVENTTARGET(_to) \ NS_SCRIPTABLE NS_IMETHOD GetOnabort(nsIDOMEventListener * *aOnabort) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetOnabort(aOnabort); } \ NS_SCRIPTABLE NS_IMETHOD SetOnabort(nsIDOMEventListener *aOnabort) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetOnabort(aOnabort); } \ NS_SCRIPTABLE NS_IMETHOD GetOnerror(nsIDOMEventListener * *aOnerror) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetOnerror(aOnerror); } \ NS_SCRIPTABLE NS_IMETHOD SetOnerror(nsIDOMEventListener *aOnerror) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetOnerror(aOnerror); } \ NS_SCRIPTABLE NS_IMETHOD GetOnload(nsIDOMEventListener * *aOnload) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetOnload(aOnload); } \ NS_SCRIPTABLE NS_IMETHOD SetOnload(nsIDOMEventListener *aOnload) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetOnload(aOnload); } \ NS_SCRIPTABLE NS_IMETHOD GetOnloadstart(nsIDOMEventListener * *aOnloadstart) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetOnloadstart(aOnloadstart); } \ NS_SCRIPTABLE NS_IMETHOD SetOnloadstart(nsIDOMEventListener *aOnloadstart) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetOnloadstart(aOnloadstart); } \ NS_SCRIPTABLE NS_IMETHOD GetOnprogress(nsIDOMEventListener * *aOnprogress) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetOnprogress(aOnprogress); } \ NS_SCRIPTABLE NS_IMETHOD SetOnprogress(nsIDOMEventListener *aOnprogress) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetOnprogress(aOnprogress); } \ NS_SCRIPTABLE NS_IMETHOD GetOnloadend(nsIDOMEventListener * *aOnloadend) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetOnloadend(aOnloadend); } \ NS_SCRIPTABLE NS_IMETHOD SetOnloadend(nsIDOMEventListener *aOnloadend) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetOnloadend(aOnloadend); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsXMLHttpRequestEventTarget : public nsIXMLHttpRequestEventTarget { public: NS_DECL_ISUPPORTS NS_DECL_NSIXMLHTTPREQUESTEVENTTARGET nsXMLHttpRequestEventTarget(); private: ~nsXMLHttpRequestEventTarget(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsXMLHttpRequestEventTarget, nsIXMLHttpRequestEventTarget) nsXMLHttpRequestEventTarget::nsXMLHttpRequestEventTarget() { /* member initializers and constructor code */ } nsXMLHttpRequestEventTarget::~nsXMLHttpRequestEventTarget() { /* destructor code */ } /* attribute nsIDOMEventListener onabort; */ NS_IMETHODIMP nsXMLHttpRequestEventTarget::GetOnabort(nsIDOMEventListener * *aOnabort) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsXMLHttpRequestEventTarget::SetOnabort(nsIDOMEventListener *aOnabort) { return NS_ERROR_NOT_IMPLEMENTED; } /* attribute nsIDOMEventListener onerror; */ NS_IMETHODIMP nsXMLHttpRequestEventTarget::GetOnerror(nsIDOMEventListener * *aOnerror) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsXMLHttpRequestEventTarget::SetOnerror(nsIDOMEventListener *aOnerror) { return NS_ERROR_NOT_IMPLEMENTED; } /* attribute nsIDOMEventListener onload; */ NS_IMETHODIMP nsXMLHttpRequestEventTarget::GetOnload(nsIDOMEventListener * *aOnload) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsXMLHttpRequestEventTarget::SetOnload(nsIDOMEventListener *aOnload) { return NS_ERROR_NOT_IMPLEMENTED; } /* attribute nsIDOMEventListener onloadstart; */ NS_IMETHODIMP nsXMLHttpRequestEventTarget::GetOnloadstart(nsIDOMEventListener * *aOnloadstart) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsXMLHttpRequestEventTarget::SetOnloadstart(nsIDOMEventListener *aOnloadstart) { return NS_ERROR_NOT_IMPLEMENTED; } /* attribute nsIDOMEventListener onprogress; */ NS_IMETHODIMP nsXMLHttpRequestEventTarget::GetOnprogress(nsIDOMEventListener * *aOnprogress) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsXMLHttpRequestEventTarget::SetOnprogress(nsIDOMEventListener *aOnprogress) { return NS_ERROR_NOT_IMPLEMENTED; } /* attribute nsIDOMEventListener onloadend; */ NS_IMETHODIMP nsXMLHttpRequestEventTarget::GetOnloadend(nsIDOMEventListener * *aOnloadend) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsXMLHttpRequestEventTarget::SetOnloadend(nsIDOMEventListener *aOnloadend) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif /* starting interface: nsIXMLHttpRequestUpload */ #define NS_IXMLHTTPREQUESTUPLOAD_IID_STR "09ff3682-7759-4441-a765-f70e1a1fabcf" #define NS_IXMLHTTPREQUESTUPLOAD_IID \ {0x09ff3682, 0x7759, 0x4441, \ { 0xa7, 0x65, 0xf7, 0x0e, 0x1a, 0x1f, 0xab, 0xcf }} class NS_NO_VTABLE NS_SCRIPTABLE nsIXMLHttpRequestUpload : public nsIXMLHttpRequestEventTarget { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IXMLHTTPREQUESTUPLOAD_IID) }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIXMLHttpRequestUpload, NS_IXMLHTTPREQUESTUPLOAD_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIXMLHTTPREQUESTUPLOAD \ /* no methods! */ /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIXMLHTTPREQUESTUPLOAD(_to) \ /* no methods! */ /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIXMLHTTPREQUESTUPLOAD(_to) \ /* no methods! */ #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsXMLHttpRequestUpload : public nsIXMLHttpRequestUpload { public: NS_DECL_ISUPPORTS NS_DECL_NSIXMLHTTPREQUESTUPLOAD nsXMLHttpRequestUpload(); private: ~nsXMLHttpRequestUpload(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsXMLHttpRequestUpload, nsIXMLHttpRequestUpload) nsXMLHttpRequestUpload::nsXMLHttpRequestUpload() { /* member initializers and constructor code */ } nsXMLHttpRequestUpload::~nsXMLHttpRequestUpload() { /* destructor code */ } /* End of implementation class template. */ #endif /* starting interface: nsIXMLHttpRequest */ #define NS_IXMLHTTPREQUEST_IID_STR "5cf8d518-51d0-4cd6-a69a-c3674c2de599" #define NS_IXMLHTTPREQUEST_IID \ {0x5cf8d518, 0x51d0, 0x4cd6, \ { 0xa6, 0x9a, 0xc3, 0x67, 0x4c, 0x2d, 0xe5, 0x99 }} class NS_SCRIPTABLE nsIXMLHttpRequest : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IXMLHTTPREQUEST_IID) /* readonly attribute nsIChannel channel; */ NS_SCRIPTABLE NS_IMETHOD GetChannel(nsIChannel * *aChannel) = 0; /* readonly attribute nsIDOMDocument responseXML; */ NS_SCRIPTABLE NS_IMETHOD GetResponseXML(nsIDOMDocument * *aResponseXML) = 0; /* readonly attribute AString responseText; */ NS_SCRIPTABLE NS_IMETHOD GetResponseText(nsAString & aResponseText) = 0; /* attribute AString responseType; */ NS_SCRIPTABLE NS_IMETHOD GetResponseType(nsAString & aResponseType) = 0; NS_SCRIPTABLE NS_IMETHOD SetResponseType(const nsAString & aResponseType) = 0; /* [implicit_jscontext] readonly attribute jsval response; */ NS_SCRIPTABLE NS_IMETHOD GetResponse(JSContext* cx, JS::Value *aResponse) = 0; /* readonly attribute unsigned long status; */ NS_SCRIPTABLE NS_IMETHOD GetStatus(PRUint32 *aStatus) = 0; /* readonly attribute AUTF8String statusText; */ NS_SCRIPTABLE NS_IMETHOD GetStatusText(nsACString & aStatusText) = 0; /* void abort (); */ NS_SCRIPTABLE NS_IMETHOD Abort(void) = 0; /* string getAllResponseHeaders (); */ NS_SCRIPTABLE NS_IMETHOD GetAllResponseHeaders(char * *_retval NS_OUTPARAM) = 0; /* ACString getResponseHeader (in AUTF8String header); */ NS_SCRIPTABLE NS_IMETHOD GetResponseHeader(const nsACString & header, nsACString & _retval NS_OUTPARAM) = 0; // note this is NOT virtual so this won't muck with the vtable! inline nsresult Open(const nsACString& method, const nsACString& url, bool async, const nsAString& user, const nsAString& password) { return Open(method, url, async, user, password, 3); } /* [optional_argc] void open (in AUTF8String method, in AUTF8String url, [optional] in boolean async, [optional, Undefined (Empty)] in DOMString user, [optional, Undefined (Empty)] in DOMString password); */ NS_SCRIPTABLE NS_IMETHOD Open(const nsACString & method, const nsACString & url, bool async, const nsAString & user, const nsAString & password, PRUint8 _argc) = 0; /* void send ([optional] in nsIVariant body); */ NS_SCRIPTABLE NS_IMETHOD Send(nsIVariant *body) = 0; /* void sendAsBinary (in DOMString body); */ NS_SCRIPTABLE NS_IMETHOD SendAsBinary(const nsAString & body) = 0; /* void setRequestHeader (in AUTF8String header, in AUTF8String value); */ NS_SCRIPTABLE NS_IMETHOD SetRequestHeader(const nsACString & header, const nsACString & value) = 0; enum { UNSENT = 0U }; enum { OPENED = 1U }; enum { HEADERS_RECEIVED = 2U }; enum { LOADING = 3U }; enum { DONE = 4U }; /* readonly attribute unsigned short readyState; */ NS_SCRIPTABLE NS_IMETHOD GetReadyState(PRUint16 *aReadyState) = 0; /* void overrideMimeType (in AUTF8String mimetype); */ NS_SCRIPTABLE NS_IMETHOD OverrideMimeType(const nsACString & mimetype) = 0; /* attribute boolean multipart; */ NS_SCRIPTABLE NS_IMETHOD GetMultipart(bool *aMultipart) = 0; NS_SCRIPTABLE NS_IMETHOD SetMultipart(bool aMultipart) = 0; /* attribute boolean mozBackgroundRequest; */ NS_SCRIPTABLE NS_IMETHOD GetMozBackgroundRequest(bool *aMozBackgroundRequest) = 0; NS_SCRIPTABLE NS_IMETHOD SetMozBackgroundRequest(bool aMozBackgroundRequest) = 0; /* attribute boolean withCredentials; */ NS_SCRIPTABLE NS_IMETHOD GetWithCredentials(bool *aWithCredentials) = 0; NS_SCRIPTABLE NS_IMETHOD SetWithCredentials(bool aWithCredentials) = 0; /* [noscript] void init (in nsIPrincipal principal, in nsIScriptContext scriptContext, in nsPIDOMWindow ownerWindow, in nsIURI baseURI); */ NS_IMETHOD Init(nsIPrincipal *principal, nsIScriptContext *scriptContext, nsPIDOMWindow *ownerWindow, nsIURI *baseURI) = 0; /* readonly attribute nsIXMLHttpRequestUpload upload; */ NS_SCRIPTABLE NS_IMETHOD GetUpload(nsIXMLHttpRequestUpload * *aUpload) = 0; /* attribute nsIDOMEventListener onreadystatechange; */ NS_SCRIPTABLE NS_IMETHOD GetOnreadystatechange(nsIDOMEventListener * *aOnreadystatechange) = 0; NS_SCRIPTABLE NS_IMETHOD SetOnreadystatechange(nsIDOMEventListener *aOnreadystatechange) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIXMLHttpRequest, NS_IXMLHTTPREQUEST_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIXMLHTTPREQUEST \ NS_SCRIPTABLE NS_IMETHOD GetChannel(nsIChannel * *aChannel); \ NS_SCRIPTABLE NS_IMETHOD GetResponseXML(nsIDOMDocument * *aResponseXML); \ NS_SCRIPTABLE NS_IMETHOD GetResponseText(nsAString & aResponseText); \ NS_SCRIPTABLE NS_IMETHOD GetResponseType(nsAString & aResponseType); \ NS_SCRIPTABLE NS_IMETHOD SetResponseType(const nsAString & aResponseType); \ NS_SCRIPTABLE NS_IMETHOD GetResponse(JSContext* cx, JS::Value *aResponse); \ NS_SCRIPTABLE NS_IMETHOD GetStatus(PRUint32 *aStatus); \ NS_SCRIPTABLE NS_IMETHOD GetStatusText(nsACString & aStatusText); \ NS_SCRIPTABLE NS_IMETHOD Abort(void); \ NS_SCRIPTABLE NS_IMETHOD GetAllResponseHeaders(char * *_retval NS_OUTPARAM); \ NS_SCRIPTABLE NS_IMETHOD GetResponseHeader(const nsACString & header, nsACString & _retval NS_OUTPARAM); \ NS_SCRIPTABLE NS_IMETHOD Open(const nsACString & method, const nsACString & url, bool async, const nsAString & user, const nsAString & password, PRUint8 _argc); \ NS_SCRIPTABLE NS_IMETHOD Send(nsIVariant *body); \ NS_SCRIPTABLE NS_IMETHOD SendAsBinary(const nsAString & body); \ NS_SCRIPTABLE NS_IMETHOD SetRequestHeader(const nsACString & header, const nsACString & value); \ NS_SCRIPTABLE NS_IMETHOD GetReadyState(PRUint16 *aReadyState); \ NS_SCRIPTABLE NS_IMETHOD OverrideMimeType(const nsACString & mimetype); \ NS_SCRIPTABLE NS_IMETHOD GetMultipart(bool *aMultipart); \ NS_SCRIPTABLE NS_IMETHOD SetMultipart(bool aMultipart); \ NS_SCRIPTABLE NS_IMETHOD GetMozBackgroundRequest(bool *aMozBackgroundRequest); \ NS_SCRIPTABLE NS_IMETHOD SetMozBackgroundRequest(bool aMozBackgroundRequest); \ NS_SCRIPTABLE NS_IMETHOD GetWithCredentials(bool *aWithCredentials); \ NS_SCRIPTABLE NS_IMETHOD SetWithCredentials(bool aWithCredentials); \ NS_IMETHOD Init(nsIPrincipal *principal, nsIScriptContext *scriptContext, nsPIDOMWindow *ownerWindow, nsIURI *baseURI); \ NS_SCRIPTABLE NS_IMETHOD GetUpload(nsIXMLHttpRequestUpload * *aUpload); \ NS_SCRIPTABLE NS_IMETHOD GetOnreadystatechange(nsIDOMEventListener * *aOnreadystatechange); \ NS_SCRIPTABLE NS_IMETHOD SetOnreadystatechange(nsIDOMEventListener *aOnreadystatechange); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIXMLHTTPREQUEST(_to) \ NS_SCRIPTABLE NS_IMETHOD GetChannel(nsIChannel * *aChannel) { return _to GetChannel(aChannel); } \ NS_SCRIPTABLE NS_IMETHOD GetResponseXML(nsIDOMDocument * *aResponseXML) { return _to GetResponseXML(aResponseXML); } \ NS_SCRIPTABLE NS_IMETHOD GetResponseText(nsAString & aResponseText) { return _to GetResponseText(aResponseText); } \ NS_SCRIPTABLE NS_IMETHOD GetResponseType(nsAString & aResponseType) { return _to GetResponseType(aResponseType); } \ NS_SCRIPTABLE NS_IMETHOD SetResponseType(const nsAString & aResponseType) { return _to SetResponseType(aResponseType); } \ NS_SCRIPTABLE NS_IMETHOD GetResponse(JSContext* cx, JS::Value *aResponse) { return _to GetResponse(cx, aResponse); } \ NS_SCRIPTABLE NS_IMETHOD GetStatus(PRUint32 *aStatus) { return _to GetStatus(aStatus); } \ NS_SCRIPTABLE NS_IMETHOD GetStatusText(nsACString & aStatusText) { return _to GetStatusText(aStatusText); } \ NS_SCRIPTABLE NS_IMETHOD Abort(void) { return _to Abort(); } \ NS_SCRIPTABLE NS_IMETHOD GetAllResponseHeaders(char * *_retval NS_OUTPARAM) { return _to GetAllResponseHeaders(_retval); } \ NS_SCRIPTABLE NS_IMETHOD GetResponseHeader(const nsACString & header, nsACString & _retval NS_OUTPARAM) { return _to GetResponseHeader(header, _retval); } \ NS_SCRIPTABLE NS_IMETHOD Open(const nsACString & method, const nsACString & url, bool async, const nsAString & user, const nsAString & password, PRUint8 _argc) { return _to Open(method, url, async, user, password, _argc); } \ NS_SCRIPTABLE NS_IMETHOD Send(nsIVariant *body) { return _to Send(body); } \ NS_SCRIPTABLE NS_IMETHOD SendAsBinary(const nsAString & body) { return _to SendAsBinary(body); } \ NS_SCRIPTABLE NS_IMETHOD SetRequestHeader(const nsACString & header, const nsACString & value) { return _to SetRequestHeader(header, value); } \ NS_SCRIPTABLE NS_IMETHOD GetReadyState(PRUint16 *aReadyState) { return _to GetReadyState(aReadyState); } \ NS_SCRIPTABLE NS_IMETHOD OverrideMimeType(const nsACString & mimetype) { return _to OverrideMimeType(mimetype); } \ NS_SCRIPTABLE NS_IMETHOD GetMultipart(bool *aMultipart) { return _to GetMultipart(aMultipart); } \ NS_SCRIPTABLE NS_IMETHOD SetMultipart(bool aMultipart) { return _to SetMultipart(aMultipart); } \ NS_SCRIPTABLE NS_IMETHOD GetMozBackgroundRequest(bool *aMozBackgroundRequest) { return _to GetMozBackgroundRequest(aMozBackgroundRequest); } \ NS_SCRIPTABLE NS_IMETHOD SetMozBackgroundRequest(bool aMozBackgroundRequest) { return _to SetMozBackgroundRequest(aMozBackgroundRequest); } \ NS_SCRIPTABLE NS_IMETHOD GetWithCredentials(bool *aWithCredentials) { return _to GetWithCredentials(aWithCredentials); } \ NS_SCRIPTABLE NS_IMETHOD SetWithCredentials(bool aWithCredentials) { return _to SetWithCredentials(aWithCredentials); } \ NS_IMETHOD Init(nsIPrincipal *principal, nsIScriptContext *scriptContext, nsPIDOMWindow *ownerWindow, nsIURI *baseURI) { return _to Init(principal, scriptContext, ownerWindow, baseURI); } \ NS_SCRIPTABLE NS_IMETHOD GetUpload(nsIXMLHttpRequestUpload * *aUpload) { return _to GetUpload(aUpload); } \ NS_SCRIPTABLE NS_IMETHOD GetOnreadystatechange(nsIDOMEventListener * *aOnreadystatechange) { return _to GetOnreadystatechange(aOnreadystatechange); } \ NS_SCRIPTABLE NS_IMETHOD SetOnreadystatechange(nsIDOMEventListener *aOnreadystatechange) { return _to SetOnreadystatechange(aOnreadystatechange); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIXMLHTTPREQUEST(_to) \ NS_SCRIPTABLE NS_IMETHOD GetChannel(nsIChannel * *aChannel) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetChannel(aChannel); } \ NS_SCRIPTABLE NS_IMETHOD GetResponseXML(nsIDOMDocument * *aResponseXML) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetResponseXML(aResponseXML); } \ NS_SCRIPTABLE NS_IMETHOD GetResponseText(nsAString & aResponseText) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetResponseText(aResponseText); } \ NS_SCRIPTABLE NS_IMETHOD GetResponseType(nsAString & aResponseType) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetResponseType(aResponseType); } \ NS_SCRIPTABLE NS_IMETHOD SetResponseType(const nsAString & aResponseType) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetResponseType(aResponseType); } \ NS_SCRIPTABLE NS_IMETHOD GetResponse(JSContext* cx, JS::Value *aResponse) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetResponse(cx, aResponse); } \ NS_SCRIPTABLE NS_IMETHOD GetStatus(PRUint32 *aStatus) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetStatus(aStatus); } \ NS_SCRIPTABLE NS_IMETHOD GetStatusText(nsACString & aStatusText) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetStatusText(aStatusText); } \ NS_SCRIPTABLE NS_IMETHOD Abort(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->Abort(); } \ NS_SCRIPTABLE NS_IMETHOD GetAllResponseHeaders(char * *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetAllResponseHeaders(_retval); } \ NS_SCRIPTABLE NS_IMETHOD GetResponseHeader(const nsACString & header, nsACString & _retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetResponseHeader(header, _retval); } \ NS_SCRIPTABLE NS_IMETHOD Open(const nsACString & method, const nsACString & url, bool async, const nsAString & user, const nsAString & password, PRUint8 _argc) { return !_to ? NS_ERROR_NULL_POINTER : _to->Open(method, url, async, user, password, _argc); } \ NS_SCRIPTABLE NS_IMETHOD Send(nsIVariant *body) { return !_to ? NS_ERROR_NULL_POINTER : _to->Send(body); } \ NS_SCRIPTABLE NS_IMETHOD SendAsBinary(const nsAString & body) { return !_to ? NS_ERROR_NULL_POINTER : _to->SendAsBinary(body); } \ NS_SCRIPTABLE NS_IMETHOD SetRequestHeader(const nsACString & header, const nsACString & value) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetRequestHeader(header, value); } \ NS_SCRIPTABLE NS_IMETHOD GetReadyState(PRUint16 *aReadyState) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetReadyState(aReadyState); } \ NS_SCRIPTABLE NS_IMETHOD OverrideMimeType(const nsACString & mimetype) { return !_to ? NS_ERROR_NULL_POINTER : _to->OverrideMimeType(mimetype); } \ NS_SCRIPTABLE NS_IMETHOD GetMultipart(bool *aMultipart) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetMultipart(aMultipart); } \ NS_SCRIPTABLE NS_IMETHOD SetMultipart(bool aMultipart) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetMultipart(aMultipart); } \ NS_SCRIPTABLE NS_IMETHOD GetMozBackgroundRequest(bool *aMozBackgroundRequest) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetMozBackgroundRequest(aMozBackgroundRequest); } \ NS_SCRIPTABLE NS_IMETHOD SetMozBackgroundRequest(bool aMozBackgroundRequest) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetMozBackgroundRequest(aMozBackgroundRequest); } \ NS_SCRIPTABLE NS_IMETHOD GetWithCredentials(bool *aWithCredentials) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetWithCredentials(aWithCredentials); } \ NS_SCRIPTABLE NS_IMETHOD SetWithCredentials(bool aWithCredentials) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetWithCredentials(aWithCredentials); } \ NS_IMETHOD Init(nsIPrincipal *principal, nsIScriptContext *scriptContext, nsPIDOMWindow *ownerWindow, nsIURI *baseURI) { return !_to ? NS_ERROR_NULL_POINTER : _to->Init(principal, scriptContext, ownerWindow, baseURI); } \ NS_SCRIPTABLE NS_IMETHOD GetUpload(nsIXMLHttpRequestUpload * *aUpload) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetUpload(aUpload); } \ NS_SCRIPTABLE NS_IMETHOD GetOnreadystatechange(nsIDOMEventListener * *aOnreadystatechange) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetOnreadystatechange(aOnreadystatechange); } \ NS_SCRIPTABLE NS_IMETHOD SetOnreadystatechange(nsIDOMEventListener *aOnreadystatechange) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetOnreadystatechange(aOnreadystatechange); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsXMLHttpRequest : public nsIXMLHttpRequest { public: NS_DECL_ISUPPORTS NS_DECL_NSIXMLHTTPREQUEST nsXMLHttpRequest(); private: ~nsXMLHttpRequest(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsXMLHttpRequest, nsIXMLHttpRequest) nsXMLHttpRequest::nsXMLHttpRequest() { /* member initializers and constructor code */ } nsXMLHttpRequest::~nsXMLHttpRequest() { /* destructor code */ } /* readonly attribute nsIChannel channel; */ NS_IMETHODIMP nsXMLHttpRequest::GetChannel(nsIChannel * *aChannel) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute nsIDOMDocument responseXML; */ NS_IMETHODIMP nsXMLHttpRequest::GetResponseXML(nsIDOMDocument * *aResponseXML) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute AString responseText; */ NS_IMETHODIMP nsXMLHttpRequest::GetResponseText(nsAString & aResponseText) { return NS_ERROR_NOT_IMPLEMENTED; } /* attribute AString responseType; */ NS_IMETHODIMP nsXMLHttpRequest::GetResponseType(nsAString & aResponseType) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsXMLHttpRequest::SetResponseType(const nsAString & aResponseType) { return NS_ERROR_NOT_IMPLEMENTED; } /* [implicit_jscontext] readonly attribute jsval response; */ NS_IMETHODIMP nsXMLHttpRequest::GetResponse(JSContext* cx, JS::Value *aResponse) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute unsigned long status; */ NS_IMETHODIMP nsXMLHttpRequest::GetStatus(PRUint32 *aStatus) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute AUTF8String statusText; */ NS_IMETHODIMP nsXMLHttpRequest::GetStatusText(nsACString & aStatusText) { return NS_ERROR_NOT_IMPLEMENTED; } /* void abort (); */ NS_IMETHODIMP nsXMLHttpRequest::Abort() { return NS_ERROR_NOT_IMPLEMENTED; } /* string getAllResponseHeaders (); */ NS_IMETHODIMP nsXMLHttpRequest::GetAllResponseHeaders(char * *_retval NS_OUTPARAM) { return NS_ERROR_NOT_IMPLEMENTED; } /* ACString getResponseHeader (in AUTF8String header); */ NS_IMETHODIMP nsXMLHttpRequest::GetResponseHeader(const nsACString & header, nsACString & _retval NS_OUTPARAM) { return NS_ERROR_NOT_IMPLEMENTED; } /* [optional_argc] void open (in AUTF8String method, in AUTF8String url, [optional] in boolean async, [optional, Undefined (Empty)] in DOMString user, [optional, Undefined (Empty)] in DOMString password); */ NS_IMETHODIMP nsXMLHttpRequest::Open(const nsACString & method, const nsACString & url, bool async, const nsAString & user, const nsAString & password, PRUint8 _argc) { return NS_ERROR_NOT_IMPLEMENTED; } /* void send ([optional] in nsIVariant body); */ NS_IMETHODIMP nsXMLHttpRequest::Send(nsIVariant *body) { return NS_ERROR_NOT_IMPLEMENTED; } /* void sendAsBinary (in DOMString body); */ NS_IMETHODIMP nsXMLHttpRequest::SendAsBinary(const nsAString & body) { return NS_ERROR_NOT_IMPLEMENTED; } /* void setRequestHeader (in AUTF8String header, in AUTF8String value); */ NS_IMETHODIMP nsXMLHttpRequest::SetRequestHeader(const nsACString & header, const nsACString & value) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute unsigned short readyState; */ NS_IMETHODIMP nsXMLHttpRequest::GetReadyState(PRUint16 *aReadyState) { return NS_ERROR_NOT_IMPLEMENTED; } /* void overrideMimeType (in AUTF8String mimetype); */ NS_IMETHODIMP nsXMLHttpRequest::OverrideMimeType(const nsACString & mimetype) { return NS_ERROR_NOT_IMPLEMENTED; } /* attribute boolean multipart; */ NS_IMETHODIMP nsXMLHttpRequest::GetMultipart(bool *aMultipart) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsXMLHttpRequest::SetMultipart(bool aMultipart) { return NS_ERROR_NOT_IMPLEMENTED; } /* attribute boolean mozBackgroundRequest; */ NS_IMETHODIMP nsXMLHttpRequest::GetMozBackgroundRequest(bool *aMozBackgroundRequest) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsXMLHttpRequest::SetMozBackgroundRequest(bool aMozBackgroundRequest) { return NS_ERROR_NOT_IMPLEMENTED; } /* attribute boolean withCredentials; */ NS_IMETHODIMP nsXMLHttpRequest::GetWithCredentials(bool *aWithCredentials) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsXMLHttpRequest::SetWithCredentials(bool aWithCredentials) { return NS_ERROR_NOT_IMPLEMENTED; } /* [noscript] void init (in nsIPrincipal principal, in nsIScriptContext scriptContext, in nsPIDOMWindow ownerWindow, in nsIURI baseURI); */ NS_IMETHODIMP nsXMLHttpRequest::Init(nsIPrincipal *principal, nsIScriptContext *scriptContext, nsPIDOMWindow *ownerWindow, nsIURI *baseURI) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute nsIXMLHttpRequestUpload upload; */ NS_IMETHODIMP nsXMLHttpRequest::GetUpload(nsIXMLHttpRequestUpload * *aUpload) { return NS_ERROR_NOT_IMPLEMENTED; } /* attribute nsIDOMEventListener onreadystatechange; */ NS_IMETHODIMP nsXMLHttpRequest::GetOnreadystatechange(nsIDOMEventListener * *aOnreadystatechange) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsXMLHttpRequest::SetOnreadystatechange(nsIDOMEventListener *aOnreadystatechange) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif /* starting interface: nsIXHRSendable */ #define NS_IXHRSENDABLE_IID_STR "840d0d00-e83e-4a29-b3c7-67e96e90a499" #define NS_IXHRSENDABLE_IID \ {0x840d0d00, 0xe83e, 0x4a29, \ { 0xb3, 0xc7, 0x67, 0xe9, 0x6e, 0x90, 0xa4, 0x99 }} class NS_NO_VTABLE NS_SCRIPTABLE nsIXHRSendable : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IXHRSENDABLE_IID) /* void getSendInfo (out nsIInputStream body, out ACString contentType, out ACString charset); */ NS_SCRIPTABLE NS_IMETHOD GetSendInfo(nsIInputStream * *body NS_OUTPARAM, nsACString & contentType NS_OUTPARAM, nsACString & charset NS_OUTPARAM) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIXHRSendable, NS_IXHRSENDABLE_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIXHRSENDABLE \ NS_SCRIPTABLE NS_IMETHOD GetSendInfo(nsIInputStream * *body NS_OUTPARAM, nsACString & contentType NS_OUTPARAM, nsACString & charset NS_OUTPARAM); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIXHRSENDABLE(_to) \ NS_SCRIPTABLE NS_IMETHOD GetSendInfo(nsIInputStream * *body NS_OUTPARAM, nsACString & contentType NS_OUTPARAM, nsACString & charset NS_OUTPARAM) { return _to GetSendInfo(body, contentType, charset); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIXHRSENDABLE(_to) \ NS_SCRIPTABLE NS_IMETHOD GetSendInfo(nsIInputStream * *body NS_OUTPARAM, nsACString & contentType NS_OUTPARAM, nsACString & charset NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetSendInfo(body, contentType, charset); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsXHRSendable : public nsIXHRSendable { public: NS_DECL_ISUPPORTS NS_DECL_NSIXHRSENDABLE nsXHRSendable(); private: ~nsXHRSendable(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsXHRSendable, nsIXHRSendable) nsXHRSendable::nsXHRSendable() { /* member initializers and constructor code */ } nsXHRSendable::~nsXHRSendable() { /* destructor code */ } /* void getSendInfo (out nsIInputStream body, out ACString contentType, out ACString charset); */ NS_IMETHODIMP nsXHRSendable::GetSendInfo(nsIInputStream * *body NS_OUTPARAM, nsACString & contentType NS_OUTPARAM, nsACString & charset NS_OUTPARAM) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif /* starting interface: nsIJSXMLHttpRequest */ #define NS_IJSXMLHTTPREQUEST_IID_STR "423fdd3d-41c9-4149-8fe5-b14a1d3912a0" #define NS_IJSXMLHTTPREQUEST_IID \ {0x423fdd3d, 0x41c9, 0x4149, \ { 0x8f, 0xe5, 0xb1, 0x4a, 0x1d, 0x39, 0x12, 0xa0 }} class NS_NO_VTABLE NS_SCRIPTABLE MOZ_DEPRECATED nsIJSXMLHttpRequest : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IJSXMLHTTPREQUEST_IID) /* attribute nsIDOMEventListener onuploadprogress; */ NS_SCRIPTABLE NS_IMETHOD GetOnuploadprogress(nsIDOMEventListener * *aOnuploadprogress) = 0; NS_SCRIPTABLE NS_IMETHOD SetOnuploadprogress(nsIDOMEventListener *aOnuploadprogress) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIJSXMLHttpRequest, NS_IJSXMLHTTPREQUEST_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIJSXMLHTTPREQUEST \ NS_SCRIPTABLE NS_IMETHOD GetOnuploadprogress(nsIDOMEventListener * *aOnuploadprogress); \ NS_SCRIPTABLE NS_IMETHOD SetOnuploadprogress(nsIDOMEventListener *aOnuploadprogress); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIJSXMLHTTPREQUEST(_to) \ NS_SCRIPTABLE NS_IMETHOD GetOnuploadprogress(nsIDOMEventListener * *aOnuploadprogress) { return _to GetOnuploadprogress(aOnuploadprogress); } \ NS_SCRIPTABLE NS_IMETHOD SetOnuploadprogress(nsIDOMEventListener *aOnuploadprogress) { return _to SetOnuploadprogress(aOnuploadprogress); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIJSXMLHTTPREQUEST(_to) \ NS_SCRIPTABLE NS_IMETHOD GetOnuploadprogress(nsIDOMEventListener * *aOnuploadprogress) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetOnuploadprogress(aOnuploadprogress); } \ NS_SCRIPTABLE NS_IMETHOD SetOnuploadprogress(nsIDOMEventListener *aOnuploadprogress) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetOnuploadprogress(aOnuploadprogress); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsJSXMLHttpRequest : public nsIJSXMLHttpRequest { public: NS_DECL_ISUPPORTS NS_DECL_NSIJSXMLHTTPREQUEST nsJSXMLHttpRequest(); private: ~nsJSXMLHttpRequest(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsJSXMLHttpRequest, nsIJSXMLHttpRequest) nsJSXMLHttpRequest::nsJSXMLHttpRequest() { /* member initializers and constructor code */ } nsJSXMLHttpRequest::~nsJSXMLHttpRequest() { /* destructor code */ } /* attribute nsIDOMEventListener onuploadprogress; */ NS_IMETHODIMP nsJSXMLHttpRequest::GetOnuploadprogress(nsIDOMEventListener * *aOnuploadprogress) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsJSXMLHttpRequest::SetOnuploadprogress(nsIDOMEventListener *aOnuploadprogress) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #define NS_XMLHTTPREQUEST_CID \ { /* d164e770-4157-11d4-9a42-000064657374 */ \ 0xd164e770, 0x4157, 0x11d4, \ {0x9a, 0x42, 0x00, 0x00, 0x64, 0x65, 0x73, 0x74} } #define NS_XMLHTTPREQUEST_CONTRACTID \ "@mozilla.org/xmlextras/xmlhttprequest;1" #endif /* __gen_nsIXMLHttpRequest_h__ */
{ "content_hash": "7ccf74eeb13edb0328566c9d4e67fe78", "timestamp": "", "source": "github", "line_count": 828, "max_line_length": 259, "avg_line_length": 45.14975845410628, "alnum_prop": 0.7658891504386903, "repo_name": "bwp/SeleniumWebDriver", "id": "628875b11c291ddd3e9425f5512c25fd5e8012b3", "size": "37384", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "third_party/gecko-10/win32/include/nsIXMLHttpRequest.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "22162" }, { "name": "C", "bytes": "302788" }, { "name": "C#", "bytes": "2090580" }, { "name": "C++", "bytes": "771128" }, { "name": "Java", "bytes": "7874195" }, { "name": "JavaScript", "bytes": "14218193" }, { "name": "Objective-C", "bytes": "368823" }, { "name": "Python", "bytes": "634315" }, { "name": "Ruby", "bytes": "757466" }, { "name": "Shell", "bytes": "6429" } ], "symlink_target": "" }
public class B { }
{ "content_hash": "169517c48a4caee68192f1b8d7949d68", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 16, "avg_line_length": 5.25, "alnum_prop": 0.5714285714285714, "repo_name": "Mayo-WE01051879/mayosapp", "id": "bc7b7d24f20993f66d25a056c1222e9b3c062244", "size": "781", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "Build/src/etc/testcases/taskdefs/optional/depend/src5/B.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "27841" }, { "name": "CSS", "bytes": "6179" }, { "name": "GAP", "bytes": "36428" }, { "name": "HTML", "bytes": "2189621" }, { "name": "Java", "bytes": "8854706" }, { "name": "JavaScript", "bytes": "34849" }, { "name": "Perl", "bytes": "9844" }, { "name": "Python", "bytes": "3299" }, { "name": "Shell", "bytes": "25265" }, { "name": "XSLT", "bytes": "371927" } ], "symlink_target": "" }
using System; using System.Runtime.InteropServices; namespace BlackBerry.Screen { /// <summary> /// A screen context used to identify the scope of the relationship with the underlying windowing system. /// </summary> [AvailableSince(10, 0)] public sealed class ScreenContext : IDisposable { internal ScreenContext(IntPtr ptr) { //TODO } //TODO internal IntPtr Handle { get { throw new NotSupportedException(); } } /// <summary> /// Dispose screen context. /// </summary> [AvailableSince(10, 0)] public void Dispose() { throw new NotImplementedException(); } } }
{ "content_hash": "1fe4b3b01e2c7ccc7c7dc8d98dd6b5fd", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 109, "avg_line_length": 21.75, "alnum_prop": 0.5300127713920817, "repo_name": "rcmaniac25/DotBlackBerry", "id": "777801295fb8cb84321b0a40e0a30dca1b13c670", "size": "785", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "DotBlackBerry/Screen/ScreenContext.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "632645" }, { "name": "PowerShell", "bytes": "8436" } ], "symlink_target": "" }
[Preface](./preface.md) - [Primers](./01-primers/abstract.md) - [Introduction to Lambda Calculus](./01-primers/intro.md) - [Supercombinators](./01-primers/supercombinators.md) - [SK combinators](./01-primers/sk.md) - [`SK` geometric semantic operators](./01-primers/sk-gsgp.md) - [Literature](./02-lit/SUMMARY.md) - [Evolving Lambda-expressions](./02-lit/evo-lambda.md) - [Evolving Supercombinators](./02-lit/evo-super.md) - [Evolving Combinators](./02-lit/evo-combos.md) - [Proposed algo](./03-pro/pro.md) [loose notes](./un.md) I can't wait for the weekend to begin.
{ "content_hash": "5b27af0fce04015366fbad3508148d04", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 70, "avg_line_length": 43, "alnum_prop": 0.6710963455149501, "repo_name": "bgalvao/fgsgp-notes", "id": "fc8f2d39376509a282490b74c9e039ae9aed9984", "size": "655", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/SUMMARY.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "18147" }, { "name": "HTML", "bytes": "128480" }, { "name": "JavaScript", "bytes": "7227" } ], "symlink_target": "" }
package org.apache.livy.repl import org.scalatest._ import org.apache.livy.LivyBaseUnitTestSuite class SparkInterpreterSpec extends FunSpec with Matchers with LivyBaseUnitTestSuite { describe("SparkInterpreter") { val interpreter = new SparkInterpreter(null) it("should parse Scala compile error.") { // Regression test for LIVY-. val error = """<console>:27: error: type mismatch; | found : Int | required: String | sc.setJobGroup(groupName, groupName, true) | ^ |<console>:27: error: type mismatch; | found : Int | required: String | sc.setJobGroup(groupName, groupName, true) | ^ |""".stripMargin val parsedError = AbstractSparkInterpreter.KEEP_NEWLINE_REGEX.split(error) val expectedTraceback = parsedError.tail val (ename, traceback) = interpreter.parseError(error) ename shouldBe "<console>:27: error: type mismatch;" traceback shouldBe expectedTraceback } it("should parse Scala runtime error.") { val error = """java.lang.RuntimeException: message | ... 48 elided | |Tailing message""".stripMargin val parsedError = AbstractSparkInterpreter.KEEP_NEWLINE_REGEX.split(error) val expectedTraceback = parsedError.tail val (ename, traceback) = interpreter.parseError(error) ename shouldBe "java.lang.RuntimeException: message" traceback shouldBe expectedTraceback } } }
{ "content_hash": "da81cdc15a2f326a8370e3ddbe1785f6", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 85, "avg_line_length": 30.30188679245283, "alnum_prop": 0.6176836861768369, "repo_name": "ajbozarth/incubator-livy", "id": "d92203473a4fbb4bfc913d908f9cbf2891872a87", "size": "2406", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "repl/scala-2.11/src/test/scala/org/apache/livy/repl/SparkInterpreterSpec.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1140" }, { "name": "FreeMarker", "bytes": "2384" }, { "name": "HTML", "bytes": "7669" }, { "name": "Java", "bytes": "356022" }, { "name": "JavaScript", "bytes": "13484" }, { "name": "Python", "bytes": "95336" }, { "name": "R", "bytes": "1211" }, { "name": "Scala", "bytes": "799790" }, { "name": "Shell", "bytes": "19871" } ], "symlink_target": "" }
package export import ( "bufio" "compress/gzip" "flag" "fmt" "io" "math" "os" "path/filepath" "sort" "strconv" "strings" "sync" "time" "github.com/influxdata/influxdb/models" "github.com/influxdata/influxdb/pkg/escape" "github.com/influxdata/influxdb/tsdb/engine/tsm1" "github.com/influxdata/influxql" ) // Command represents the program execution for "influx_inspect export". type Command struct { // Standard input/output, overridden for testing. Stderr io.Writer Stdout io.Writer dataDir string walDir string out string database string retentionPolicy string startTime int64 endTime int64 compress bool manifest map[string]struct{} tsmFiles map[string][]string walFiles map[string][]string } // NewCommand returns a new instance of Command. func NewCommand() *Command { return &Command{ Stderr: os.Stderr, Stdout: os.Stdout, manifest: make(map[string]struct{}), tsmFiles: make(map[string][]string), walFiles: make(map[string][]string), } } // Run executes the command. func (cmd *Command) Run(args ...string) error { var start, end string fs := flag.NewFlagSet("export", flag.ExitOnError) fs.StringVar(&cmd.dataDir, "datadir", os.Getenv("HOME")+"/.influxdb/data", "Data storage path") fs.StringVar(&cmd.walDir, "waldir", os.Getenv("HOME")+"/.influxdb/wal", "WAL storage path") fs.StringVar(&cmd.out, "out", os.Getenv("HOME")+"/.influxdb/export", "Destination file to export to") fs.StringVar(&cmd.database, "database", "", "Optional: the database to export") fs.StringVar(&cmd.retentionPolicy, "retention", "", "Optional: the retention policy to export (requires -database)") fs.StringVar(&start, "start", "", "Optional: the start time to export (RFC3339 format)") fs.StringVar(&end, "end", "", "Optional: the end time to export (RFC3339 format)") fs.BoolVar(&cmd.compress, "compress", false, "Compress the output") fs.SetOutput(cmd.Stdout) fs.Usage = func() { fmt.Fprintf(cmd.Stdout, "Exports TSM files into InfluxDB line protocol format.\n\n") fmt.Fprintf(cmd.Stdout, "Usage: %s export [flags]\n\n", filepath.Base(os.Args[0])) fs.PrintDefaults() } if err := fs.Parse(args); err != nil { return err } // set defaults if start != "" { s, err := time.Parse(time.RFC3339, start) if err != nil { return err } cmd.startTime = s.UnixNano() } else { cmd.startTime = math.MinInt64 } if end != "" { e, err := time.Parse(time.RFC3339, end) if err != nil { return err } cmd.endTime = e.UnixNano() } else { // set end time to max if it is not set. cmd.endTime = math.MaxInt64 } if err := cmd.validate(); err != nil { return err } return cmd.export() } func (cmd *Command) validate() error { if cmd.retentionPolicy != "" && cmd.database == "" { return fmt.Errorf("must specify a db") } if cmd.startTime != 0 && cmd.endTime != 0 && cmd.endTime < cmd.startTime { return fmt.Errorf("end time before start time") } return nil } func (cmd *Command) export() error { if err := cmd.walkTSMFiles(); err != nil { return err } if err := cmd.walkWALFiles(); err != nil { return err } return cmd.write() } func (cmd *Command) walkTSMFiles() error { return filepath.Walk(cmd.dataDir, func(path string, f os.FileInfo, err error) error { if err != nil { return err } // check to see if this is a tsm file if filepath.Ext(path) != "."+tsm1.TSMFileExtension { return nil } relPath, err := filepath.Rel(cmd.dataDir, path) if err != nil { return err } dirs := strings.Split(relPath, string(byte(os.PathSeparator))) if len(dirs) < 2 { return fmt.Errorf("invalid directory structure for %s", path) } if dirs[0] == cmd.database || cmd.database == "" { if dirs[1] == cmd.retentionPolicy || cmd.retentionPolicy == "" { key := filepath.Join(dirs[0], dirs[1]) cmd.manifest[key] = struct{}{} cmd.tsmFiles[key] = append(cmd.tsmFiles[key], path) } } return nil }) } func (cmd *Command) walkWALFiles() error { return filepath.Walk(cmd.walDir, func(path string, f os.FileInfo, err error) error { if err != nil { return err } // check to see if this is a wal file fileName := filepath.Base(path) if filepath.Ext(path) != "."+tsm1.WALFileExtension || !strings.HasPrefix(fileName, tsm1.WALFilePrefix) { return nil } relPath, err := filepath.Rel(cmd.walDir, path) if err != nil { return err } dirs := strings.Split(relPath, string(byte(os.PathSeparator))) if len(dirs) < 2 { return fmt.Errorf("invalid directory structure for %s", path) } if dirs[0] == cmd.database || cmd.database == "" { if dirs[1] == cmd.retentionPolicy || cmd.retentionPolicy == "" { key := filepath.Join(dirs[0], dirs[1]) cmd.manifest[key] = struct{}{} cmd.walFiles[key] = append(cmd.walFiles[key], path) } } return nil }) } func (cmd *Command) write() error { // open our output file and create an output buffer f, err := os.Create(cmd.out) if err != nil { return err } defer f.Close() // Because calling (*os.File).Write is relatively expensive, // and we don't *need* to sync to disk on every written line of export, // use a sized buffered writer so that we only sync the file every megabyte. bw := bufio.NewWriterSize(f, 1024*1024) defer bw.Flush() var w io.Writer = bw if cmd.compress { gzw := gzip.NewWriter(w) defer gzw.Close() w = gzw } s, e := time.Unix(0, cmd.startTime).Format(time.RFC3339), time.Unix(0, cmd.endTime).Format(time.RFC3339) fmt.Fprintf(w, "# INFLUXDB EXPORT: %s - %s\n", s, e) // Write out all the DDL fmt.Fprintln(w, "# DDL") for key := range cmd.manifest { keys := strings.Split(key, string(os.PathSeparator)) db, rp := influxql.QuoteIdent(keys[0]), influxql.QuoteIdent(keys[1]) fmt.Fprintf(w, "CREATE DATABASE %s WITH NAME %s\n", db, rp) } fmt.Fprintln(w, "# DML") for key := range cmd.manifest { keys := strings.Split(key, string(os.PathSeparator)) fmt.Fprintf(w, "# CONTEXT-DATABASE:%s\n", keys[0]) fmt.Fprintf(w, "# CONTEXT-RETENTION-POLICY:%s\n", keys[1]) if files, ok := cmd.tsmFiles[key]; ok { fmt.Fprintf(cmd.Stdout, "writing out tsm file data for %s...", key) if err := cmd.writeTsmFiles(w, files); err != nil { return err } fmt.Fprintln(cmd.Stdout, "complete.") } if _, ok := cmd.walFiles[key]; ok { fmt.Fprintf(cmd.Stdout, "writing out wal file data for %s...", key) if err := cmd.writeWALFiles(w, cmd.walFiles[key], key); err != nil { return err } fmt.Fprintln(cmd.Stdout, "complete.") } } return nil } func (cmd *Command) writeTsmFiles(w io.Writer, files []string) error { fmt.Fprintln(w, "# writing tsm data") // we need to make sure we write the same order that the files were written sort.Strings(files) for _, f := range files { if err := cmd.exportTSMFile(f, w); err != nil { return err } } return nil } func (cmd *Command) exportTSMFile(tsmFilePath string, w io.Writer) error { f, err := os.Open(tsmFilePath) if err != nil { if os.IsNotExist(err) { fmt.Fprintf(w, "skipped missing file: %s", tsmFilePath) return nil } return err } defer f.Close() r, err := tsm1.NewTSMReader(f) if err != nil { fmt.Fprintf(cmd.Stderr, "unable to read %s, skipping: %s\n", tsmFilePath, err.Error()) return nil } defer r.Close() if sgStart, sgEnd := r.TimeRange(); sgStart > cmd.endTime || sgEnd < cmd.startTime { return nil } for i := 0; i < r.KeyCount(); i++ { key, _ := r.KeyAt(i) values, err := r.ReadAll(key) if err != nil { fmt.Fprintf(cmd.Stderr, "unable to read key %q in %s, skipping: %s\n", string(key), tsmFilePath, err.Error()) continue } measurement, field := tsm1.SeriesAndFieldFromCompositeKey(key) field = escape.Bytes(field) if err := cmd.writeValues(w, measurement, string(field), values); err != nil { // An error from writeValues indicates an IO error, which should be returned. return err } } return nil } func (cmd *Command) writeWALFiles(w io.Writer, files []string, key string) error { fmt.Fprintln(w, "# writing wal data") // we need to make sure we write the same order that the wal received the data sort.Strings(files) var once sync.Once warnDelete := func() { once.Do(func() { msg := fmt.Sprintf(`WARNING: detected deletes in wal file. Some series for %q may be brought back by replaying this data. To resolve, you can either let the shard snapshot prior to exporting the data or manually editing the exported file. `, key) fmt.Fprintln(cmd.Stderr, msg) }) } for _, f := range files { if err := cmd.exportWALFile(f, w, warnDelete); err != nil { return err } } return nil } // exportWAL reads every WAL entry from r and exports it to w. func (cmd *Command) exportWALFile(walFilePath string, w io.Writer, warnDelete func()) error { f, err := os.Open(walFilePath) if err != nil { if os.IsNotExist(err) { fmt.Fprintf(w, "skipped missing file: %s", walFilePath) return nil } return err } defer f.Close() r := tsm1.NewWALSegmentReader(f) defer r.Close() for r.Next() { entry, err := r.Read() if err != nil { n := r.Count() fmt.Fprintf(cmd.Stderr, "file %s corrupt at position %d", walFilePath, n) break } switch t := entry.(type) { case *tsm1.DeleteWALEntry, *tsm1.DeleteRangeWALEntry: warnDelete() continue case *tsm1.WriteWALEntry: for key, values := range t.Values { measurement, field := tsm1.SeriesAndFieldFromCompositeKey([]byte(key)) // measurements are stored escaped, field names are not field = escape.Bytes(field) if err := cmd.writeValues(w, measurement, string(field), values); err != nil { // An error from writeValues indicates an IO error, which should be returned. return err } } } } return nil } // writeValues writes every value in values to w, using the given series key and field name. // If any call to w.Write fails, that error is returned. func (cmd *Command) writeValues(w io.Writer, seriesKey []byte, field string, values []tsm1.Value) error { buf := []byte(string(seriesKey) + " " + field + "=") prefixLen := len(buf) for _, value := range values { ts := value.UnixNano() if (ts < cmd.startTime) || (ts > cmd.endTime) { continue } // Re-slice buf to be "<series_key> <field>=". buf = buf[:prefixLen] // Append the correct representation of the value. switch v := value.Value().(type) { case float64: buf = strconv.AppendFloat(buf, v, 'g', -1, 64) case int64: buf = strconv.AppendInt(buf, v, 10) buf = append(buf, 'i') case uint64: buf = strconv.AppendUint(buf, v, 10) buf = append(buf, 'u') case bool: buf = strconv.AppendBool(buf, v) case string: buf = append(buf, '"') buf = append(buf, models.EscapeStringField(v)...) buf = append(buf, '"') default: // This shouldn't be possible, but we'll format it anyway. buf = append(buf, fmt.Sprintf("%v", v)...) } // Now buf has "<series_key> <field>=<value>". // Append the timestamp and a newline, then write it. buf = append(buf, ' ') buf = strconv.AppendInt(buf, ts, 10) buf = append(buf, '\n') if _, err := w.Write(buf); err != nil { // Underlying IO error needs to be returned. return err } } return nil }
{ "content_hash": "e78a38fd6b4cfedf158c0f64a34e411e", "timestamp": "", "source": "github", "line_count": 418, "max_line_length": 117, "avg_line_length": 26.97846889952153, "alnum_prop": 0.6521237917885963, "repo_name": "anhowe/acs-engine", "id": "fa2f4ecb4fee65092dae4c888668658b4ac6e52f", "size": "11349", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "vendor/github.com/influxdata/influxdb/cmd/influx_inspect/export/export.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "1002664" }, { "name": "Groovy", "bytes": "24761" }, { "name": "Makefile", "bytes": "5600" }, { "name": "Perl", "bytes": "49849" }, { "name": "Perl 6", "bytes": "264171" }, { "name": "PowerShell", "bytes": "41535" }, { "name": "Python", "bytes": "5994" }, { "name": "Shell", "bytes": "116135" } ], "symlink_target": "" }
package bucky; public class Fish extends Animal { public void noise(){ System.out.println("Fish's noise method called."); } }
{ "content_hash": "68721f2e0111fcfd880159eded9cf7c0", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 52, "avg_line_length": 18.714285714285715, "alnum_prop": 0.7099236641221374, "repo_name": "willem-vanheemstrasystems/java-headstart", "id": "afacdde32333ddf6e4af3d8b6c33e37edfcfda9e", "size": "131", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bucky/src/bucky/Fish.java", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "2250" }, { "name": "Java", "bytes": "146893" } ], "symlink_target": "" }
package com.intellij.vcs.log.ui.filter; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.SizedIcon; import com.intellij.ui.popup.KeepingPopupOpenAction; import com.intellij.util.NotNullFunction; import com.intellij.util.PlatformIcons; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.ColorIcon; import com.intellij.util.ui.EmptyIcon; import com.intellij.util.ui.JBUI; import com.intellij.vcs.log.VcsLogDataPack; import com.intellij.vcs.log.VcsLogRootFilter; import com.intellij.vcs.log.VcsLogStructureFilter; import com.intellij.vcs.log.data.VcsLogStructureFilterImpl; import com.intellij.vcs.log.impl.MainVcsLogUiProperties; import com.intellij.vcs.log.impl.VcsLogFileFilter; import com.intellij.vcs.log.impl.VcsLogRootFilterImpl; import com.intellij.vcs.log.ui.VcsLogColorManager; import com.intellij.vcs.log.ui.table.VcsLogGraphTable; import com.intellij.vcs.log.util.VcsLogUtil; import org.intellij.lang.annotations.JdkConstants; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.util.List; import java.util.*; class StructureFilterPopupComponent extends FilterPopupComponent<VcsLogFileFilter> { private static final int FILTER_LABEL_LENGTH = 30; private static final int CHECKBOX_ICON_SIZE = 15; private static final FileByNameComparator FILE_BY_NAME_COMPARATOR = new FileByNameComparator(); private static final FilePathByPathComparator FILE_PATH_BY_PATH_COMPARATOR = new FilePathByPathComparator(); @NotNull private final MainVcsLogUiProperties myUiProperties; @NotNull private final VcsLogColorManager myColorManager; StructureFilterPopupComponent(@NotNull MainVcsLogUiProperties uiProperties, @NotNull FilterModel<VcsLogFileFilter> filterModel, @NotNull VcsLogColorManager colorManager) { super("Paths", filterModel); myUiProperties = uiProperties; myColorManager = colorManager; } @NotNull @Override protected String getText(@NotNull VcsLogFileFilter filter) { Collection<VirtualFile> roots = filter.getRootFilter() == null ? getAllRoots() : filter.getRootFilter().getRoots(); Collection<FilePath> files = filter.getStructureFilter() == null ? Collections.emptySet() : filter.getStructureFilter().getFiles(); Collection<VirtualFile> visibleRoots = VcsLogUtil.getAllVisibleRoots(getAllRoots(), filter.getRootFilter(), filter.getStructureFilter()); if (files.isEmpty()) { return getTextFromRoots(roots, visibleRoots.size() == getAllRoots().size()); } return getTextFromFilePaths(files, "folders", false); } @NotNull private static String getTextFromRoots(@NotNull Collection<VirtualFile> files, boolean full) { return getText(files, "roots", FILE_BY_NAME_COMPARATOR, VirtualFile::getName, full); } @NotNull private static String getTextFromFilePaths(@NotNull Collection<FilePath> files, @NotNull String category, boolean full) { return getText(files, category, FILE_PATH_BY_PATH_COMPARATOR, file -> StringUtil.shortenPathWithEllipsis(file.getPresentableUrl(), FILTER_LABEL_LENGTH), full); } @NotNull private static <F> String getText(@NotNull Collection<F> files, @NotNull String category, @NotNull Comparator<F> comparator, @NotNull NotNullFunction<F, String> getText, boolean full) { if (full) { return ALL; } else if (files.isEmpty()) { return "No " + category; } else { F firstFile = Collections.min(files, comparator); String firstFileName = getText.fun(firstFile); if (files.size() == 1) { return firstFileName; } return firstFileName + " + " + (files.size() - 1); } } @Nullable @Override protected String getToolTip(@NotNull VcsLogFileFilter filter) { return getToolTip(filter.getRootFilter() == null ? getAllRoots() : filter.getRootFilter().getRoots(), filter.getStructureFilter() == null ? Collections.emptySet() : filter.getStructureFilter().getFiles()); } @NotNull private String getToolTip(@NotNull Collection<VirtualFile> roots, @NotNull Collection<FilePath> files) { String tooltip = ""; if (roots.isEmpty()) { tooltip += "No Roots Selected"; } else if (roots.size() != getAllRoots().size()) { tooltip += "Roots:\n" + getTooltipTextForRoots(roots); } if (!files.isEmpty()) { if (!tooltip.isEmpty()) tooltip += "\n"; tooltip += "Folders:\n" + getTooltipTextForFilePaths(files); } return tooltip; } @NotNull private static String getTooltipTextForRoots(@NotNull Collection<VirtualFile> files) { return getTooltipTextForFiles(files, FILE_BY_NAME_COMPARATOR, VirtualFile::getName); } @NotNull private static String getTooltipTextForFilePaths(@NotNull Collection<FilePath> files) { return getTooltipTextForFiles(files, FILE_PATH_BY_PATH_COMPARATOR, FilePath::getPresentableUrl); } @NotNull private static <F> String getTooltipTextForFiles(@NotNull Collection<F> files, @NotNull Comparator<F> comparator, @NotNull NotNullFunction<F, String> getText) { List<F> filesToDisplay = ContainerUtil.sorted(files, comparator); if (files.size() > 10) { filesToDisplay = filesToDisplay.subList(0, 10); } String tooltip = StringUtil.join(filesToDisplay, getText, "\n"); if (files.size() > 10) { tooltip += "\n..."; } return tooltip; } @Override protected ActionGroup createActionGroup() { Set<VirtualFile> roots = getAllRoots(); List<AnAction> rootActions = new ArrayList<>(); if (myColorManager.isMultipleRoots()) { for (VirtualFile root : ContainerUtil.sorted(roots, FILE_BY_NAME_COMPARATOR)) { rootActions.add(new SelectVisibleRootAction(root)); } } List<AnAction> structureActions = new ArrayList<>(); for (VcsLogStructureFilter filter : getRecentFilters()) { structureActions.add(new SelectFromHistoryAction(filter)); } if (roots.size() > 15) { return new DefaultActionGroup(createAllAction(), new SelectFoldersAction(), new Separator("Recent"), new DefaultActionGroup(structureActions), new Separator("Roots"), new DefaultActionGroup(rootActions)); } return new DefaultActionGroup(createAllAction(), new SelectFoldersAction(), new Separator("Roots"), new DefaultActionGroup(rootActions), new Separator("Recent"), new DefaultActionGroup(structureActions)); } @NotNull private List<VcsLogStructureFilter> getRecentFilters() { List<List<String>> filterValues = myUiProperties.getRecentlyFilteredGroups(myName); return ContainerUtil.map2List(filterValues, values -> VcsLogClassicFilterUi.FileFilterModel.createStructureFilter(values)); } private Set<VirtualFile> getAllRoots() { return myFilterModel.getDataPack().getLogProviders().keySet(); } private boolean isVisible(@NotNull VirtualFile root) { VcsLogFileFilter filter = myFilterModel.getFilter(); if (filter != null && filter.getRootFilter() != null) { return filter.getRootFilter().getRoots().contains(root); } return true; } private void setVisible(@NotNull VirtualFile root, boolean visible) { Set<VirtualFile> roots = getAllRoots(); VcsLogFileFilter previousFilter = myFilterModel.getFilter(); VcsLogRootFilter rootFilter = previousFilter != null ? previousFilter.getRootFilter() : null; Collection<VirtualFile> visibleRoots; if (rootFilter == null) { visibleRoots = visible ? roots : ContainerUtil.subtract(roots, Collections.singleton(root)); } else { visibleRoots = visible ? ContainerUtil.union(new HashSet<>(rootFilter.getRoots()), Collections.singleton(root)) : ContainerUtil.subtract(rootFilter.getRoots(), Collections.singleton(root)); } myFilterModel.setFilter(new VcsLogFileFilter(null, new VcsLogRootFilterImpl(visibleRoots))); } private void setVisibleOnly(@NotNull VirtualFile root) { myFilterModel.setFilter(new VcsLogFileFilter(null, new VcsLogRootFilterImpl(Collections.singleton(root)))); } @NotNull private static String getStructureActionText(@NotNull VcsLogStructureFilter filter) { return getTextFromFilePaths(filter.getFiles(), "items", filter.getFiles().isEmpty()); } private static class FileByNameComparator implements Comparator<VirtualFile> { @Override public int compare(VirtualFile o1, VirtualFile o2) { return o1.getName().compareTo(o2.getName()); } } private static class FilePathByPathComparator implements Comparator<FilePath> { @Override public int compare(FilePath o1, FilePath o2) { return o1.getPresentableUrl().compareTo(o2.getPresentableUrl()); } } private class SelectVisibleRootAction extends ToggleAction implements DumbAware, KeepingPopupOpenAction { @NotNull private final CheckboxColorIcon myIcon; @NotNull private final VirtualFile myRoot; private SelectVisibleRootAction(@NotNull VirtualFile root) { super(root.getName(), root.getPresentableUrl(), null); myRoot = root; myIcon = JBUI.scale(new CheckboxColorIcon(CHECKBOX_ICON_SIZE, VcsLogGraphTable.getRootBackgroundColor(myRoot, myColorManager))); getTemplatePresentation().setIcon(JBUI.scale(EmptyIcon.create(CHECKBOX_ICON_SIZE))); // see PopupFactoryImpl.calcMaxIconSize } @Override public boolean isSelected(@NotNull AnActionEvent e) { return isVisible(myRoot); } @Override public void setSelected(@NotNull AnActionEvent e, boolean state) { if (!isEnabled()) { setVisibleOnly(myRoot); } else { if ((e.getModifiers() & getMask()) != 0) { setVisibleOnly(myRoot); } else { setVisible(myRoot, state); } } } @JdkConstants.InputEventMask private int getMask() { return SystemInfo.isMac ? InputEvent.META_MASK : InputEvent.CTRL_MASK; } @Override public void update(@NotNull AnActionEvent e) { super.update(e); updateIcon(); e.getPresentation().setIcon(myIcon); e.getPresentation().putClientProperty(TOOL_TIP_TEXT_KEY, KeyEvent.getKeyModifiersText(getMask()) + "+Click to see only \"" + e.getPresentation().getText() + "\""); } private void updateIcon() { myIcon.prepare(isVisible(myRoot) && isEnabled()); } private boolean isEnabled() { return myFilterModel.getFilter() == null || myFilterModel.getFilter().getStructureFilter() == null; } } private static class CheckboxColorIcon extends ColorIcon { private final int mySize; private boolean mySelected; private SizedIcon mySizedIcon; CheckboxColorIcon(int size, @NotNull Color color) { super(size, color); mySize = size; mySizedIcon = new SizedIcon(PlatformIcons.CHECK_ICON_SMALL, mySize, mySize); } public void prepare(boolean selected) { mySelected = selected; } @NotNull @Override public CheckboxColorIcon withIconPreScaled(boolean preScaled) { mySizedIcon = (SizedIcon)mySizedIcon.withIconPreScaled(preScaled); return (CheckboxColorIcon)super.withIconPreScaled(preScaled); } @Override public void paintIcon(Component component, Graphics g, int i, int j) { super.paintIcon(component, g, i, j); if (mySelected) { mySizedIcon.paintIcon(component, g, i, j); } } } private class SelectFoldersAction extends DumbAwareAction { static final String STRUCTURE_FILTER_TEXT = "Select Folders..."; SelectFoldersAction() { super(STRUCTURE_FILTER_TEXT); } @Override public void actionPerformed(@NotNull AnActionEvent e) { Project project = e.getRequiredData(CommonDataKeys.PROJECT); VcsLogDataPack dataPack = myFilterModel.getDataPack(); VcsLogFileFilter filter = myFilterModel.getFilter(); Collection<VirtualFile> files; if (filter == null || filter.getStructureFilter() == null) { files = Collections.emptySet(); } else { // for now, ignoring non-existing paths files = ContainerUtil.mapNotNull(filter.getStructureFilter().getFiles(), FilePath::getVirtualFile); } VcsStructureChooser chooser = new VcsStructureChooser(project, "Select Files or Folders to Filter by", files, new ArrayList<>(dataPack.getLogProviders().keySet())); if (chooser.showAndGet()) { VcsLogStructureFilterImpl structureFilter = new VcsLogStructureFilterImpl(new HashSet<VirtualFile>(chooser.getSelectedFiles())); myFilterModel.setFilter(new VcsLogFileFilter(structureFilter, null)); myUiProperties.addRecentlyFilteredGroup(myName, VcsLogClassicFilterUi.FileFilterModel.getFilterValues(structureFilter)); } } @Override public void update(@NotNull AnActionEvent e) { e.getPresentation().setEnabledAndVisible(e.getProject() != null); } } private class SelectFromHistoryAction extends ToggleAction implements DumbAware { @NotNull private final VcsLogStructureFilter myFilter; @NotNull private final Icon myIcon; @NotNull private final Icon myEmptyIcon; private SelectFromHistoryAction(@NotNull VcsLogStructureFilter filter) { super(getStructureActionText(filter), getTooltipTextForFilePaths(filter.getFiles()).replace("\n", " "), null); myFilter = filter; myIcon = JBUI.scale(new SizedIcon(PlatformIcons.CHECK_ICON_SMALL, CHECKBOX_ICON_SIZE, CHECKBOX_ICON_SIZE)); myEmptyIcon = JBUI.scale(EmptyIcon.create(CHECKBOX_ICON_SIZE)); } @Override public boolean isSelected(@NotNull AnActionEvent e) { return myFilterModel.getFilter() != null && myFilterModel.getFilter().getStructureFilter() == myFilter; } @Override public void setSelected(@NotNull AnActionEvent e, boolean state) { myFilterModel.setFilter(new VcsLogFileFilter(myFilter, null)); } @Override public void update(@NotNull AnActionEvent e) { super.update(e); Presentation presentation = e.getPresentation(); if (isSelected(e)) { presentation.setIcon(myIcon); } else { presentation.setIcon(myEmptyIcon); } } } }
{ "content_hash": "aee746080ad3874f13b356a5715d3644", "timestamp": "", "source": "github", "line_count": 401, "max_line_length": 136, "avg_line_length": 38.576059850374065, "alnum_prop": 0.6812334346111578, "repo_name": "mdanielwork/intellij-community", "id": "ac71d06a114e0b483aeba48a7f2c8af433636eb8", "size": "16069", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "platform/vcs-log/impl/src/com/intellij/vcs/log/ui/filter/StructureFilterPopupComponent.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" /> <link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/> <link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/> <!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]--> <style type="text/css" media="all"> @import url('../../../../../style.css'); @import url('../../../../../tree.css'); </style> <script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script> <script src="../../../../../package-nodes-tree.js" type="text/javascript"></script> <script src="../../../../../clover-tree.js" type="text/javascript"></script> <script src="../../../../../clover.js" type="text/javascript"></script> <script src="../../../../../clover-descriptions.js" type="text/javascript"></script> <script src="../../../../../cloud.js" type="text/javascript"></script> <title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title> </head> <body> <div id="page"> <header id="header" role="banner"> <nav class="aui-header aui-dropdown2-trigger-group" role="navigation"> <div class="aui-header-inner"> <div class="aui-header-primary"> <h1 id="logo" class="aui-header-logo aui-header-logo-clover"> <a href="http://openclover.org" title="Visit OpenClover home page"><span class="aui-header-logo-device">OpenClover</span></a> </h1> </div> <div class="aui-header-secondary"> <ul class="aui-nav"> <li id="system-help-menu"> <a class="aui-nav-link" title="Open online documentation" target="_blank" href="http://openclover.org/documentation"> <span class="aui-icon aui-icon-small aui-iconfont-help">&#160;Help</span> </a> </li> </ul> </div> </div> </nav> </header> <div class="aui-page-panel"> <div class="aui-page-panel-inner"> <div class="aui-page-panel-nav aui-page-panel-nav-clover"> <div class="aui-page-header-inner" style="margin-bottom: 20px;"> <div class="aui-page-header-image"> <a href="http://cardatechnologies.com" target="_top"> <div class="aui-avatar aui-avatar-large aui-avatar-project"> <div class="aui-avatar-inner"> <img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/> </div> </div> </a> </div> <div class="aui-page-header-main" > <h1> <a href="http://cardatechnologies.com" target="_top"> ABA Route Transit Number Validator 1.0.1-SNAPSHOT </a> </h1> </div> </div> <nav class="aui-navgroup aui-navgroup-vertical"> <div class="aui-navgroup-inner"> <ul class="aui-nav"> <li class=""> <a href="../../../../../dashboard.html">Project overview</a> </li> </ul> <div class="aui-nav-heading packages-nav-heading"> <strong>Packages</strong> </div> <div class="aui-nav project-packages"> <form method="get" action="#" class="aui package-filter-container"> <input type="text" autocomplete="off" class="package-filter text" placeholder="Type to filter packages..." name="package-filter" id="package-filter" title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/> </form> <p class="package-filter-no-results-message hidden"> <small>No results found.</small> </p> <div class="packages-tree-wrapper" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator"> <div class="packages-tree-container"></div> <div class="clover-packages-lozenges"></div> </div> </div> </div> </nav> </div> <section class="aui-page-panel-content"> <div class="aui-page-panel-content-clover"> <div class="aui-page-header-main"><ol class="aui-nav aui-nav-breadcrumbs"> <li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li> <li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li> <li><a href="test-Test_AbaRouteValidator_06.html">Class Test_AbaRouteValidator_06</a></li> </ol></div> <h1 class="aui-h2-clover"> Test testAbaNumberCheck_11007_good </h1> <table class="aui"> <thead> <tr> <th>Test</th> <th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th> <th><label title="When the test execution was started">Start time</label></th> <th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th> <th><label title="A failure or error message if the test is not successful.">Message</label></th> </tr> </thead> <tbody> <tr> <td> <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_06.html?line=24232#src-24232" >testAbaNumberCheck_11007_good</a> </td> <td> <span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span> </td> <td> 7 Aug 12:36:20 </td> <td> 0.0 </td> <td> <div></div> <div class="errorMessage"></div> </td> </tr> </tbody> </table> <div>&#160;</div> <table class="aui aui-table-sortable"> <thead> <tr> <th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th> <th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> testAbaNumberCheck_11007_good</th> </tr> </thead> <tbody> <tr> <td> <span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span> &#160;&#160;<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=35214#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a> </td> <td> <span class="sortValue">0.7352941</span>73.5% </td> <td class="align-middle" style="width: 100%" colspan="3"> <div> <div title="73.5% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:73.5%"></div></div></div> </td> </tr> </tbody> </table> </div> <!-- class="aui-page-panel-content-clover" --> <footer id="footer" role="contentinfo"> <section class="footer-body"> <ul> <li> Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1 on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT. </li> </ul> <ul> <li>OpenClover is free and open-source software. </li> </ul> </section> </footer> </section> <!-- class="aui-page-panel-content" --> </div> <!-- class="aui-page-panel-inner" --> </div> <!-- class="aui-page-panel" --> </div> <!-- id="page" --> </body> </html>
{ "content_hash": "3f88057c173449f7fd292c7e5aed33c5", "timestamp": "", "source": "github", "line_count": 209, "max_line_length": 297, "avg_line_length": 43.92822966507177, "alnum_prop": 0.5097483934211959, "repo_name": "dcarda/aba.route.validator", "id": "c512661523cd5b3ff3a594a5e71bc301bdefb257", "size": "9181", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "target13/site/clover/com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_06_testAbaNumberCheck_11007_good_r66.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "18715254" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection.Emit; using System.Runtime.InteropServices; using System.Text; namespace Yanitta { /// <summary> /// Предоставляет методы для записи, чтения и выполнение в процессе. /// </summary> public class ProcessMemory { #region API [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass"), SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", MessageId = "2"), DllImport("kernel32", SetLastError = true, ExactSpelling = true)] static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, int dwSize, AllocationType flAllocationType, MemoryProtection flProtect); [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass"), DllImport("kernel32", SetLastError = true)] static extern IntPtr OpenThread(ThreadAccess DesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, int dwThreadId); [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass"), SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", MessageId = "2"), DllImport("kernel32", SetLastError = true, ExactSpelling = true)] static extern bool VirtualFreeEx(IntPtr hProcess, IntPtr lpAddress, int dwSize, FreeType dwFreeType); [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass"), SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", MessageId = "2"), DllImport("kernel32", SetLastError = true)] static extern bool VirtualProtectEx(IntPtr hProcess, IntPtr lpAddress, int dwSize, MemoryProtection flNewProtect, out MemoryProtection lpflOldProtect); [SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", MessageId = "3"), SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass"), DllImport("kernel32", SetLastError = true)] static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, int nSize, IntPtr lpNumberOfBytesWritten); [SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", MessageId = "3"), SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass"), DllImport("kernel32", SetLastError = true)] static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, IntPtr lpBuffer, int nSize, IntPtr lpNumberOfBytesWritten); [SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", MessageId = "3"), SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass"), DllImport("kernel32", SetLastError = true)] static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, [Out] byte[] lpBuffer, int dwSize, IntPtr lpNumberOfBytesRead); [SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", MessageId = "3"), SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass"), DllImport("kernel32", SetLastError = true)] static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, [Out] IntPtr lpBuffer, int dwSize, IntPtr lpNumberOfBytesRead); [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass"), DllImport("kernel32", SetLastError = true)] static extern uint SuspendThread(IntPtr thandle); [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass"), DllImport("kernel32", SetLastError = true)] static extern uint ResumeThread(IntPtr thandle); [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass"), DllImport("kernel32", SetLastError = true)] static extern bool GetThreadContext(IntPtr thandle, ref WOW64_CONTEXT context); [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass"), DllImport("kernel32", SetLastError = true)] static extern bool SetThreadContext(IntPtr thandle, ref WOW64_CONTEXT context); [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass"), DllImport("user32")] static extern IntPtr GetForegroundWindow(); [DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool IsWow64Process([In] IntPtr process, [Out] out bool wow64Process); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] static extern bool FlushInstructionCache(IntPtr hProcess, IntPtr lpBaseAddress, int dwSize); [DllImport("user32.dll", SetLastError = true)] static extern uint GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId); [DllImport("user32.dll", CharSet = CharSet.Auto)] static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam); #endregion /// <summary> /// Возвращает текущий процесс. /// </summary> public Process Process { get; private set; } /// <summary> /// Инициализирует новый экземпляр класса <see cref="ProcessMemory"/>. /// </summary> /// <param name="process"></param> public ProcessMemory(Process process) { Process = process; Process.EnableRaisingEvents = true; } /// <summary> /// Выделяет в процессе участок памяти. /// </summary> /// <param name="size">Размер выделяемой памяти.</param> /// <param name="allocType">Тип выделяемой памяти.</param> /// <param name="memProtect">Тип защиты памяти.</param> /// <returns>Указатель на выделенный участок памяти.</returns> public IntPtr Alloc(int size, AllocationType allocType = AllocationType.Commit, MemoryProtection memProtect = MemoryProtection.ExecuteReadWrite) { if (size <= 0) throw new ArgumentNullException(nameof(size)); var address = VirtualAllocEx(Process.Handle, IntPtr.Zero, size, allocType, memProtect); if (address == IntPtr.Zero) throw new Win32Exception(); return address; } /// <summary> /// Осводождает ранее выделенный участок памяти. /// </summary> /// <param name="address">Указатель на выделенный участок памяти.</param> /// <param name="freeType">Тип осводождения памяти.</param> public void Free(IntPtr address, FreeType freeType = FreeType.Release) { if (address == IntPtr.Zero) throw new ArgumentNullException(nameof(address)); if (!VirtualFreeEx(Process.Handle, address, 0, freeType)) throw new Win32Exception(); } /// <summary> /// Считывает массив байт из текущего процесса. /// </summary> /// <param name="address">Указатель на участок памяти с которого надо начать считывание.</param> /// <param name="count">Размер считываемого массива.</param> /// <returns>Считанный из процесса масив.</returns> public unsafe byte[] ReadBytes(IntPtr address, int count) { var bytes = new byte[count]; if(!ReadProcessMemory(Process.Handle, address, bytes, count, IntPtr.Zero)) throw new Win32Exception(); return bytes; } /// <summary> /// Считывает из процесса значение указанного типа. /// </summary> /// <typeparam name="T">Тип считываемого значения.</typeparam> /// <param name="address">Указатель на участок памяти от куда надо считать значение.</param> /// <returns>Значение указанного типа.</returns> public unsafe T Read<T>(IntPtr address) where T : struct { fixed (byte* pointer = new byte[MarshalCache<T>.Size]) { ReadProcessMemory(Process.Handle, address, new IntPtr(pointer), MarshalCache<T>.Size, IntPtr.Zero); return (T)Marshal.PtrToStructure(new IntPtr(pointer), MarshalCache<T>.RealType); } } /// <summary> /// Считывает из процесса строку заканчивающуюся 0 в кодировке utf-8. /// </summary> /// <param name="addess">Указатель на участок памяти от куда надо считать значение.</param> /// <param name="length">Длинна строки (ограничение).</param> /// <returns>Считанная строка</returns> public string ReadString(IntPtr addess, int length = 100) { var result = new byte[length]; if (!ReadProcessMemory(Process.Handle, addess, result, length, IntPtr.Zero)) throw new Win32Exception(); return Encoding.UTF8.GetString(result.TakeWhile(ret => ret != 0).ToArray()); } /// <summary> /// Записывает в память процесса значение указанного типа. /// </summary> /// <typeparam name="T">Тип записываемого значения.</typeparam> /// <param name="value">Значение, которое надо записать в память процесса.</param> /// <returns>Указатель на участок памяти куда записано значение.</returns> public IntPtr Write<T>(T value) where T : struct { var address = Alloc(MarshalCache<T>.Size); if (address == IntPtr.Zero) throw new Win32Exception(); try { Write(address, value); } catch { Free(address); address = IntPtr.Zero; } return address; } /// <summary> /// Записывает в память процесса значение указанного типа. /// </summary> /// <typeparam name="T">Тип записываемого значения.</typeparam> /// <param name="address">Указатель на участок памяти куда надо записать значение.</param> /// <param name="value">Значение, которое надо записать в память процесса.</param> public unsafe void Write<T>(IntPtr address, T value) where T : struct { void* pointer = MarshalCache<T>.GetUnsafePtr(ref value); if (!WriteProcessMemory(Process.Handle, address, new IntPtr(pointer), MarshalCache<T>.Size, IntPtr.Zero)) throw new Win32Exception(); } /// <summary> /// Записывает массив байт в память процесса. /// </summary> /// <param name="buffer">Массив байт.</param> /// <returns>Указатель на участок памяти куда записан массив.</returns> public IntPtr Write(byte[] buffer) { var addr = Alloc(buffer.Length); if (addr == IntPtr.Zero) throw new Win32Exception(); Write(addr, buffer); return addr; } /// <summary> /// Записывает массив байт в память процесса. /// </summary> /// <param name="address">Указатель на участок памяти куда надо записать массив.</param> /// <param name="buffer">Массив байт.</param> public void Write(IntPtr address, byte[] buffer) { if (!WriteProcessMemory(Process.Handle, address, buffer, buffer.Length, IntPtr.Zero)) throw new Win32Exception(); } /// <summary> /// Записывает в память процесса строку по указанному аддрессу в кодировке utf-8. /// </summary> /// <param name="address">Указатель на участок памяти куда надо записать строку.</param> /// <param name="str">Записываемая строка.</param> public void WriteCString(IntPtr address, string str) { var buffer = Encoding.UTF8.GetBytes(str + '\0'); if (!WriteProcessMemory(Process.Handle, address, buffer, buffer.Length, IntPtr.Zero)) throw new Win32Exception(); } /// <summary> /// Записывает в память процесса указанную строку. /// </summary> /// <param name="str">Строка для записи в память.</param> /// <returns>Указатель на строку в памяти.</returns> public IntPtr WriteCString(string str) { var buffer = Encoding.UTF8.GetBytes(str + '\0'); var address = Alloc(buffer.Length); if (!WriteProcessMemory(Process.Handle, address, buffer, buffer.Length, IntPtr.Zero)) throw new Win32Exception(); return address; } /// <summary> /// Выполняет функцию по указанному адрессу с указанным списком аргуметов. /// </summary> /// <param name="injAddress">Адрес в памяти куда записывается исполнимый байткод.</param> /// <param name="callAddress">Относительный адресс выполняемой функции.</param> /// <param name="funcArgs"> /// Параметры функции. /// Параметрами могут выступать как и значения так и указатели на значения. /// </param> public void Call(IntPtr injAddress, IntPtr callAddress, params int[] funcArgs) { var tHandle = OpenThread(ThreadAccess.All, false, Process.Threads[0].Id); if (SuspendThread(tHandle) == 0xFFFFFFFF) throw new Win32Exception(); var context = new WOW64_CONTEXT { ContextFlags = 0x10001 /*CONTROL*/ }; if (!GetThreadContext(tHandle, ref context)) throw new Win32Exception(); var retaddr = Write<uint>(0xDEAD); var bytes = new List<byte>(); #region ASM // push eip (stored refernse to next inctruction) bytes.Add(0x68); bytes.AddRange(BitConverter.GetBytes(context.Eip)); // pushad (stored general registers) bytes.Add(0x60); // pushfd (stored flags) bytes.Add(0x9C); // pushed to the stack function arguments for (int i = funcArgs.Length - 1; i >= 0; --i) { // push param address bytes.Add(0x68); bytes.AddRange(BitConverter.GetBytes(funcArgs[i])); } // mov eax, callAddress bytes.Add(0xB8); bytes.AddRange(BitConverter.GetBytes(callAddress.ToInt32())); // call eax bytes.Add(0xFF); bytes.Add(0xD0); // add esp, arg_count * pointersize (__cdecl correct stack) bytes.Add(0x83); bytes.Add(0xC4); bytes.Add((byte)(funcArgs.Length * IntPtr.Size)); // mov [retaddr], eax bytes.Add(0xA3); bytes.AddRange(BitConverter.GetBytes(retaddr.ToInt32())); // popfd (restore flags) bytes.Add(0x9D); // popad (restore general registers) bytes.Add(0x61); // retn bytes.Add(0xC3); #endregion var oldProtect = MemoryProtection.ReadOnly; // Save original code and disable protect var oldCode = ReadBytes(injAddress, bytes.Count); if (!VirtualProtectEx(Process.Handle, injAddress, bytes.Count, MemoryProtection.ExecuteReadWrite, out oldProtect)) throw new Win32Exception(); Write(injAddress, bytes.ToArray()); context.Eip = (uint)injAddress.ToInt32(); if (!SetThreadContext(tHandle, ref context) || ResumeThread(tHandle) == 0xFFFFFFFF) throw new Win32Exception(); for (int i = 0; i < 0x100; ++i) { System.Threading.Thread.Sleep(15); if (Read<uint>(retaddr) != 0xDEAD) break; } // restore protection and original code Write(injAddress, oldCode); if (!FlushInstructionCache(Process.Handle, injAddress, bytes.Count)) throw new Win32Exception(); if (!VirtualProtectEx(Process.Handle, injAddress, bytes.Count, oldProtect, out oldProtect)) throw new Win32Exception(); Free(retaddr); } /// <summary> /// Возвращает абсолютный аддресс в процессе. /// </summary> /// <param name="offset">Относительный аддресс.</param> /// <returns>абсолютный аддресс в процессе.</returns> public IntPtr Rebase(long offset) { return new IntPtr(offset + Process.MainModule.BaseAddress.ToInt64()); } public IntPtr SendMessage(uint msg, IntPtr wParam, IntPtr lParam) { return SendMessage(Process.MainWindowHandle, msg, wParam, lParam); } /// <summary> /// Указывает что главное окно процесса находится на переднем плане. /// </summary> public bool IsFocusMainWindow { get { int id; GetWindowThreadProcessId(GetForegroundWindow(), out id); return id == Process.Id; } } } public unsafe static class MarshalCache<T> { internal unsafe delegate void* GetUnsafePtrDelegate(ref T value); public static Type RealType { get; } public static int Size { get; } public static TypeCode TypeCode { get; } internal static GetUnsafePtrDelegate GetUnsafePtr { get; } static MarshalCache() { RealType = typeof(T); TypeCode = Type.GetTypeCode(RealType); if (RealType == typeof(bool)) { Size = 1; } else if (RealType.IsEnum) { var underlying = RealType.GetEnumUnderlyingType(); Size = Marshal.SizeOf(underlying); RealType = underlying; TypeCode = Type.GetTypeCode(RealType); } else { Size = Marshal.SizeOf(RealType); } var name = $"GetPinnedPtr<{typeof(T).FullName}>"; var method = new DynamicMethod(name, typeof(void*), new[] { typeof(T).MakeByRefType() }, typeof(MarshalCache<>).Module); var il = method.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); if (IntPtr.Size == 4) il.Emit(OpCodes.Conv_U); else il.Emit(OpCodes.Conv_U8); il.Emit(OpCodes.Ret); GetUnsafePtr = (GetUnsafePtrDelegate)method.CreateDelegate(typeof(GetUnsafePtrDelegate)); } } #region Enums /// <summary> /// Тип выделения памяти. /// </summary> [Flags] public enum AllocationType : uint { Commit = 0x00001000, Reserve = 0x00002000, Decommit = 0x00004000, Release = 0x00008000, Reset = 0x00080000, TopDown = 0x00100000, WriteWatch = 0x00200000, Physical = 0x00400000, LargePages = 0x20000000, } /// <summary> /// Тип защиты памяти. /// </summary> [Flags] public enum MemoryProtection : uint { NoAccess = 0x001, ReadOnly = 0x002, ReadWrite = 0x004, WriteCopy = 0x008, Execute = 0x010, ExecuteRead = 0x020, ExecuteReadWrite = 0x040, ExecuteWriteCopy = 0x080, GuardModifierflag = 0x100, NoCacheModifierflag = 0x200, WriteCombineModifierflag = 0x400, } /// <summary> /// Тип освобождения памяти. /// </summary> [Flags] public enum FreeType : uint { Decommit = 0x4000, Release = 0x8000, } /// <summary> /// Тип доступа к процессу. /// </summary> [Flags] public enum ThreadAccess : uint { Terminate = 0x00001, SuspendResume = 0x00002, GetContext = 0x00008, SetContext = 0x00010, SetInformation = 0x00020, QueryInformation = 0x00040, SetThreadToken = 0x00080, Impersonate = 0x00100, DirectImpersonation = 0x00200, All = 0x1F03FF } /// <summary> /// Contains processor-specific register data. /// </summary> [StructLayout(LayoutKind.Explicit, Size = 716)] public struct WOW64_CONTEXT { /// <summary> /// Context flag. /// </summary> [FieldOffset(0x00)] public uint ContextFlags; /// <summary> /// Next instruction pointer. /// </summary> [FieldOffset(0xB8)] public uint Eip; }; #endregion }
{ "content_hash": "9abcdd4c3df40e8c29b77b9c70ca5700", "timestamp": "", "source": "github", "line_count": 505, "max_line_length": 259, "avg_line_length": 41.48514851485149, "alnum_prop": 0.6046300715990454, "repo_name": "Konctantin/Yanitta", "id": "2c5331d94520c777c4312c56c6bb8222436851fa", "size": "22824", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Yanitta/Misk/ProcessMemory.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "238" }, { "name": "C#", "bytes": "134413" }, { "name": "Python", "bytes": "5364" } ], "symlink_target": "" }
**Twilight Knife** **School** evocation [force]; **Level** sorcerer/wizard 3, witch 3 **Casting Time** 1 standard action **Components** V, S, F (a small knife) **Range** close (25 ft. + 5 ft./2 levels) **Effect** floating knife of force **Duration** 1 round/level (D) **Saving Throw** none; **Spell Resistance** yes You create a darkly sinister floating knife that attacks the same creature as you each round. If you choose not to attack a creature, or you make an attack that affects multiple opponents, the knife makes no attack during that round. The knife uses your base attack bonus modified by either your Intelligence or Charisma bonus (whichever is higher) when making this attack. Unless you specifically will it to do otherwise, or it proves impossible to do so, the knife always maneuvers itself so that it can flank your opponent before making the attack. The knife deals 1d4 points of force damage on a successful hit and has the same threat range and critical multipliers as a normal dagger. In addition, if the target is denied a Dexterity bonus to AC or the knife flanks the target, the knife can make sneak attacks as a rogue, inflicting an extra 1d6 points of force damage per four caster levels on a successful attack. A _twilight knife_ cannot be attacked or harmed by physical attacks, but _ [dispel magic](../../spells/dispelMagic#_dispel-magic)_, _ [disintegrate](../../spells/disintegrate#_disintegrate)_, a _sphere of annihilation_, or a _ [rod of cancellation](../../magicItems/rods#_rod-of-cancellation)_ affects it. A _twilight knife_'s AC against touch attacks is 12 (10 + size bonus for Tiny object) plus your Dexterity modifier. If an attacked creature has spell resistance, you make a caster level check (1d20 + caster level) against that spell resistance the first time the _twilight knife_ strikes it. If the knife is successfully resisted, the spell is dispelled. If not, the weapon has its normal full effect on that creature for the duration of the spell.
{ "content_hash": "9f1195d7e8c363aa5460109f682972bb", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 921, "avg_line_length": 91.13636363636364, "alnum_prop": 0.7635910224438903, "repo_name": "brunokoga/pathfinder-markdown", "id": "4107e21416f3dd1656caff2dcf426c1e0625c4d3", "size": "2005", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "prd_markdown/advanced/spells/twilightKnife.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "58168" }, { "name": "JavaScript", "bytes": "97828" }, { "name": "Ruby", "bytes": "2456" } ], "symlink_target": "" }
from django.contrib.gis import forms from django.contrib.gis.db.models.lookups import gis_lookups from django.contrib.gis.db.models.proxy import SpatialProxy from django.contrib.gis.gdal import HAS_GDAL from django.contrib.gis.geometry.backend import Geometry, GeometryException from django.core.exceptions import ImproperlyConfigured from django.db.models.expressions import Expression from django.db.models.fields import Field from django.utils import six from django.utils.translation import ugettext_lazy as _ # Local cache of the spatial_ref_sys table, which holds SRID data for each # spatial database alias. This cache exists so that the database isn't queried # for SRID info each time a distance query is constructed. _srid_cache = {} def get_srid_info(srid, connection): """ Returns the units, unit name, and spheroid WKT associated with the given SRID from the `spatial_ref_sys` (or equivalent) spatial database table for the given database connection. These results are cached. """ global _srid_cache try: # The SpatialRefSys model for the spatial backend. SpatialRefSys = connection.ops.spatial_ref_sys() except NotImplementedError: # No `spatial_ref_sys` table in spatial backend (e.g., MySQL). return None, None, None if connection.alias not in _srid_cache: # Initialize SRID dictionary for database if it doesn't exist. _srid_cache[connection.alias] = {} if srid not in _srid_cache[connection.alias]: # Use `SpatialRefSys` model to query for spatial reference info. sr = SpatialRefSys.objects.using(connection.alias).get(srid=srid) units, units_name = sr.units spheroid = SpatialRefSys.get_spheroid(sr.wkt) _srid_cache[connection.alias][srid] = (units, units_name, spheroid) return _srid_cache[connection.alias][srid] class GeoSelectFormatMixin(object): def select_format(self, compiler, sql, params): """ Returns the selection format string, depending on the requirements of the spatial backend. For example, Oracle and MySQL require custom selection formats in order to retrieve geometries in OGC WKT. For all other fields a simple '%s' format string is returned. """ connection = compiler.connection srid = compiler.query.get_context('transformed_srid') if srid: sel_fmt = '%s(%%s, %s)' % (connection.ops.transform, srid) else: sel_fmt = '%s' if connection.ops.select: # This allows operations to be done on fields in the SELECT, # overriding their values -- used by the Oracle and MySQL # spatial backends to get database values as WKT, and by the # `transform` method. sel_fmt = connection.ops.select % sel_fmt return sel_fmt % sql, params class BaseSpatialField(Field): """ The Base GIS Field. It's used as a base class for GeometryField and RasterField. Defines properties that are common to all GIS fields such as the characteristics of the spatial reference system of the field. """ description = _("The base GIS field.") # Geodetic units. geodetic_units = ('decimal degree', 'degree') def __init__(self, verbose_name=None, srid=4326, spatial_index=True, **kwargs): """ The initialization function for base spatial fields. Takes the following as keyword arguments: srid: The spatial reference system identifier, an OGC standard. Defaults to 4326 (WGS84). spatial_index: Indicates whether to create a spatial index. Defaults to True. Set this instead of 'db_index' for geographic fields since index creation is different for geometry columns. """ # Setting the index flag with the value of the `spatial_index` keyword. self.spatial_index = spatial_index # Setting the SRID and getting the units. Unit information must be # easily available in the field instance for distance queries. self.srid = srid # Setting the verbose_name keyword argument with the positional # first parameter, so this works like normal fields. kwargs['verbose_name'] = verbose_name super(BaseSpatialField, self).__init__(**kwargs) def deconstruct(self): name, path, args, kwargs = super(BaseSpatialField, self).deconstruct() # Always include SRID for less fragility; include spatial index if it's # not the default value. kwargs['srid'] = self.srid if self.spatial_index is not True: kwargs['spatial_index'] = self.spatial_index return name, path, args, kwargs def db_type(self, connection): return connection.ops.geo_db_type(self) # The following functions are used to get the units, their name, and # the spheroid corresponding to the SRID of the BaseSpatialField. def _get_srid_info(self, connection): # Get attributes from `get_srid_info`. self._units, self._units_name, self._spheroid = get_srid_info(self.srid, connection) def spheroid(self, connection): if not hasattr(self, '_spheroid'): self._get_srid_info(connection) return self._spheroid def units(self, connection): if not hasattr(self, '_units'): self._get_srid_info(connection) return self._units def units_name(self, connection): if not hasattr(self, '_units_name'): self._get_srid_info(connection) return self._units_name def geodetic(self, connection): """ Returns true if this field's SRID corresponds with a coordinate system that uses non-projected units (e.g., latitude/longitude). """ units_name = self.units_name(connection) # Some backends like MySQL cannot determine units name. In that case, # test if srid is 4326 (WGS84), even if this is over-simplification. return units_name.lower() in self.geodetic_units if units_name else self.srid == 4326 def get_placeholder(self, value, compiler, connection): """ Returns the placeholder for the spatial column for the given value. """ return connection.ops.get_geom_placeholder(self, value, compiler) class GeometryField(GeoSelectFormatMixin, BaseSpatialField): """ The base Geometry field -- maps to the OpenGIS Specification Geometry type. """ description = _("The base Geometry field -- maps to the OpenGIS Specification Geometry type.") form_class = forms.GeometryField # The OpenGIS Geometry name. geom_type = 'GEOMETRY' def __init__(self, verbose_name=None, dim=2, geography=False, **kwargs): """ The initialization function for geometry fields. In addition to the parameters from BaseSpatialField, it takes the following as keyword arguments: dim: The number of dimensions for this geometry. Defaults to 2. extent: Customize the extent, in a 4-tuple of WGS 84 coordinates, for the geometry field entry in the `USER_SDO_GEOM_METADATA` table. Defaults to (-180.0, -90.0, 180.0, 90.0). tolerance: Define the tolerance, in meters, to use for the geometry field entry in the `USER_SDO_GEOM_METADATA` table. Defaults to 0.05. """ # Setting the dimension of the geometry field. self.dim = dim # Is this a geography rather than a geometry column? self.geography = geography # Oracle-specific private attributes for creating the entry in # `USER_SDO_GEOM_METADATA` self._extent = kwargs.pop('extent', (-180.0, -90.0, 180.0, 90.0)) self._tolerance = kwargs.pop('tolerance', 0.05) super(GeometryField, self).__init__(verbose_name=verbose_name, **kwargs) def deconstruct(self): name, path, args, kwargs = super(GeometryField, self).deconstruct() # Include kwargs if they're not the default values. if self.dim != 2: kwargs['dim'] = self.dim if self.geography is not False: kwargs['geography'] = self.geography return name, path, args, kwargs # ### Routines specific to GeometryField ### def get_distance(self, value, lookup_type, connection): """ Returns a distance number in units of the field. For example, if `D(km=1)` was passed in and the units of the field were in meters, then 1000 would be returned. """ return connection.ops.get_distance(self, value, lookup_type) def get_prep_value(self, value): """ Spatial lookup values are either a parameter that is (or may be converted to) a geometry, or a sequence of lookup values that begins with a geometry. This routine will setup the geometry value properly, and preserve any other lookup parameters before returning to the caller. """ value = super(GeometryField, self).get_prep_value(value) if isinstance(value, Expression): return value elif isinstance(value, (tuple, list)): geom = value[0] seq_value = True else: geom = value seq_value = False # When the input is not a GEOS geometry, attempt to construct one # from the given string input. if isinstance(geom, Geometry): pass elif isinstance(geom, (bytes, six.string_types)) or hasattr(geom, '__geo_interface__'): try: geom = Geometry(geom) except GeometryException: raise ValueError('Could not create geometry from lookup value.') else: raise ValueError('Cannot use object with type %s for a geometry lookup parameter.' % type(geom).__name__) # Assigning the SRID value. geom.srid = self.get_srid(geom) if seq_value: lookup_val = [geom] lookup_val.extend(value[1:]) return tuple(lookup_val) else: return geom def from_db_value(self, value, expression, connection, context): if value: if not isinstance(value, Geometry): value = Geometry(value) srid = value.srid if not srid and self.srid != -1: value.srid = self.srid return value def get_srid(self, geom): """ Returns the default SRID for the given geometry, taking into account the SRID set for the field. For example, if the input geometry has no SRID, then that of the field will be returned. """ gsrid = geom.srid # SRID of given geometry. if gsrid is None or self.srid == -1 or (gsrid == -1 and self.srid != -1): return self.srid else: return gsrid # ### Routines overloaded from Field ### def contribute_to_class(self, cls, name, **kwargs): super(GeometryField, self).contribute_to_class(cls, name, **kwargs) # Setup for lazy-instantiated Geometry object. setattr(cls, self.attname, SpatialProxy(Geometry, self)) def formfield(self, **kwargs): defaults = {'form_class': self.form_class, 'geom_type': self.geom_type, 'srid': self.srid, } defaults.update(kwargs) if (self.dim > 2 and 'widget' not in kwargs and not getattr(defaults['form_class'].widget, 'supports_3d', False)): defaults['widget'] = forms.Textarea return super(GeometryField, self).formfield(**defaults) def get_db_prep_lookup(self, lookup_type, value, connection, prepared=False): """ Prepare for the database lookup, and return any spatial parameters necessary for the query. This includes wrapping any geometry parameters with a backend-specific adapter and formatting any distance parameters into the correct units for the coordinate system of the field. """ # special case for isnull lookup if lookup_type == 'isnull': return [] elif lookup_type in self.class_lookups: # Populating the parameters list, and wrapping the Geometry # with the Adapter of the spatial backend. if isinstance(value, (tuple, list)): params = [connection.ops.Adapter(value[0])] if self.class_lookups[lookup_type].distance: # Getting the distance parameter in the units of the field. params += self.get_distance(value[1:], lookup_type, connection) elif lookup_type in connection.ops.truncate_params: # Lookup is one where SQL parameters aren't needed from the # given lookup value. pass else: params += value[1:] elif isinstance(value, Expression): params = [] else: params = [connection.ops.Adapter(value)] return params else: raise ValueError('%s is not a valid spatial lookup for %s.' % (lookup_type, self.__class__.__name__)) def get_prep_lookup(self, lookup_type, value): if lookup_type == 'contains': # 'contains' name might conflict with the "normal" contains lookup, # for which the value is not prepared, but left as-is. return self.get_prep_value(value) return super(GeometryField, self).get_prep_lookup(lookup_type, value) def get_db_prep_save(self, value, connection): "Prepares the value for saving in the database." if not value: return None else: return connection.ops.Adapter(self.get_prep_value(value)) for klass in gis_lookups.values(): GeometryField.register_lookup(klass) # The OpenGIS Geometry Type Fields class PointField(GeometryField): geom_type = 'POINT' form_class = forms.PointField description = _("Point") class LineStringField(GeometryField): geom_type = 'LINESTRING' form_class = forms.LineStringField description = _("Line string") class PolygonField(GeometryField): geom_type = 'POLYGON' form_class = forms.PolygonField description = _("Polygon") class MultiPointField(GeometryField): geom_type = 'MULTIPOINT' form_class = forms.MultiPointField description = _("Multi-point") class MultiLineStringField(GeometryField): geom_type = 'MULTILINESTRING' form_class = forms.MultiLineStringField description = _("Multi-line string") class MultiPolygonField(GeometryField): geom_type = 'MULTIPOLYGON' form_class = forms.MultiPolygonField description = _("Multi polygon") class GeometryCollectionField(GeometryField): geom_type = 'GEOMETRYCOLLECTION' form_class = forms.GeometryCollectionField description = _("Geometry collection") class ExtentField(GeoSelectFormatMixin, Field): "Used as a return value from an extent aggregate" description = _("Extent Aggregate Field") def get_internal_type(self): return "ExtentField" class RasterField(BaseSpatialField): """ Raster field for GeoDjango -- evaluates into GDALRaster objects. """ description = _("Raster Field") geom_type = 'RASTER' def __init__(self, *args, **kwargs): if not HAS_GDAL: raise ImproperlyConfigured('RasterField requires GDAL.') super(RasterField, self).__init__(*args, **kwargs) def _check_connection(self, connection): # Make sure raster fields are used only on backends with raster support. if not connection.features.gis_enabled or not connection.features.supports_raster: raise ImproperlyConfigured('Raster fields require backends with raster support.') def db_type(self, connection): self._check_connection(connection) return super(RasterField, self).db_type(connection) def from_db_value(self, value, expression, connection, context): return connection.ops.parse_raster(value) def get_db_prep_value(self, value, connection, prepared=False): self._check_connection(connection) # Prepare raster for writing to database. if not prepared: value = connection.ops.deconstruct_raster(value) return super(RasterField, self).get_db_prep_value(value, connection, prepared) def contribute_to_class(self, cls, name, **kwargs): super(RasterField, self).contribute_to_class(cls, name, **kwargs) # Importing GDALRaster raises an exception on systems without gdal. from django.contrib.gis.gdal import GDALRaster # Setup for lazy-instantiated Raster object. For large querysets, the # instantiation of all GDALRasters can potentially be expensive. This # delays the instantiation of the objects to the moment of evaluation # of the raster attribute. setattr(cls, self.attname, SpatialProxy(GDALRaster, self))
{ "content_hash": "769c26983b4b2d3ead0b9a924c553d15", "timestamp": "", "source": "github", "line_count": 444, "max_line_length": 117, "avg_line_length": 39.86486486486486, "alnum_prop": 0.6248587570621469, "repo_name": "yephper/django", "id": "20b6a50687e68059ccbc6ac8d0811d5dd49d6e54", "size": "17700", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "django/contrib/gis/db/models/fields.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "1538" }, { "name": "CSS", "bytes": "1697381" }, { "name": "HTML", "bytes": "390772" }, { "name": "Java", "bytes": "588" }, { "name": "JavaScript", "bytes": "3172126" }, { "name": "Makefile", "bytes": "134" }, { "name": "PHP", "bytes": "19336" }, { "name": "Python", "bytes": "13365273" }, { "name": "Shell", "bytes": "837" }, { "name": "Smarty", "bytes": "133" } ], "symlink_target": "" }
<?php /** * Downloadable Product Samples resource model * * @category Mage * @package Mage_Downloadable * @author Magento Core Team <[email protected]> */ class Mage_Downloadable_Model_Resource_Sample extends Mage_Core_Model_Resource_Db_Abstract { /** * Initialize connection * */ protected function _construct() { $this->_init('downloadable/sample', 'sample_id'); } /** * Save title of sample item in store scope * * @param Mage_Downloadable_Model_Sample $sampleObject * @return Mage_Downloadable_Model_Resource_Sample */ public function saveItemTitle($sampleObject) { $writeAdapter = $this->_getWriteAdapter(); $sampleTitleTable = $this->getTable('downloadable/sample_title'); $bind = array( ':sample_id' => $sampleObject->getId(), ':store_id' => (int)$sampleObject->getStoreId() ); $select = $writeAdapter->select() ->from($sampleTitleTable) ->where('sample_id=:sample_id AND store_id=:store_id'); if ($writeAdapter->fetchOne($select, $bind)) { $where = array( 'sample_id = ?' => $sampleObject->getId(), 'store_id = ?' => (int)$sampleObject->getStoreId() ); if ($sampleObject->getUseDefaultTitle()) { $writeAdapter->delete( $sampleTitleTable, $where); } else { $writeAdapter->update( $sampleTitleTable, array('title' => $sampleObject->getTitle()), $where); } } else { if (!$sampleObject->getUseDefaultTitle()) { $writeAdapter->insert( $sampleTitleTable, array( 'sample_id' => $sampleObject->getId(), 'store_id' => (int)$sampleObject->getStoreId(), 'title' => $sampleObject->getTitle(), )); } } return $this; } /** * Delete data by item(s) * * @param Mage_Downloadable_Model_Sample|array|int $items * @return Mage_Downloadable_Model_Resource_Sample */ public function deleteItems($items) { $writeAdapter = $this->_getWriteAdapter(); $where = ''; if ($items instanceof Mage_Downloadable_Model_Sample) { $where = array('sample_id = ?' => $items->getId()); } else { $where = array('sample_id in (?)' => $items); } if ($where) { $writeAdapter->delete( $this->getMainTable(), $where); $writeAdapter->delete( $this->getTable('downloadable/sample_title'), $where); } return $this; } /** * Retrieve links searchable data * * @param int $productId * @param int $storeId * @return array */ public function getSearchableData($productId, $storeId) { $adapter = $this->_getReadAdapter(); $ifNullDefaultTitle = $adapter->getIfNullSql('st.title', 'd.title'); $select = $adapter->select() ->from(array('m' => $this->getMainTable()), null) ->join( array('d' => $this->getTable('downloadable/sample_title')), 'd.sample_id=m.sample_id AND d.store_id=0', array()) ->joinLeft( array('st' => $this->getTable('downloadable/sample_title')), 'st.sample_id=m.sample_id AND st.store_id=:store_id', array('title' => $ifNullDefaultTitle)) ->where('m.product_id=:product_id', $productId); $bind = array( ':store_id' => (int)$storeId, ':product_id' => $productId ); return $adapter->fetchCol($select, $bind); } }
{ "content_hash": "49f57edea5d85f2736b9571fdb3b18a8", "timestamp": "", "source": "github", "line_count": 121, "max_line_length": 90, "avg_line_length": 32.52066115702479, "alnum_prop": 0.5092757306226176, "repo_name": "cesarfelip3/cleverva", "id": "263c2973f8aec71a3502605e9d8e15da351ac284", "size": "4879", "binary": false, "copies": "14", "ref": "refs/heads/master", "path": "app/code/core/Mage/Downloadable/Model/Resource/Sample.php", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "20018" }, { "name": "ApacheConf", "bytes": "12014" }, { "name": "Batchfile", "bytes": "1036" }, { "name": "CSS", "bytes": "1998129" }, { "name": "HTML", "bytes": "5272065" }, { "name": "JavaScript", "bytes": "1126004" }, { "name": "PHP", "bytes": "47608047" }, { "name": "PowerShell", "bytes": "1028" }, { "name": "Ruby", "bytes": "288" }, { "name": "Shell", "bytes": "8761" }, { "name": "XSLT", "bytes": "2066" } ], "symlink_target": "" }
package com.uwetrottmann.tmdb2.services; import com.uwetrottmann.tmdb2.BaseTestCase; import com.uwetrottmann.tmdb2.TestData; import com.uwetrottmann.tmdb2.entities.AppendToResponse; import com.uwetrottmann.tmdb2.entities.Credits; import com.uwetrottmann.tmdb2.entities.ExternalIds; import com.uwetrottmann.tmdb2.entities.Images; import com.uwetrottmann.tmdb2.entities.TvEpisode; import com.uwetrottmann.tmdb2.entities.TvSeason; import com.uwetrottmann.tmdb2.entities.Videos; import com.uwetrottmann.tmdb2.enumerations.AppendToResponseItem; import org.junit.Test; import retrofit2.Call; import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat; public class TvSeasonsServiceTest extends BaseTestCase { @Test public void test_season() throws IOException { Call<TvSeason> call = getManager().tvSeasonsService().season(TestData.TVSHOW_ID, 1, null, null); TvSeason season = call.execute().body(); assertTvSeason(season); } @Test public void test_season_with_append_to_response() throws IOException { Call<TvSeason> call = getManager().tvSeasonsService().season( TestData.TVSHOW_ID, 1, null, new AppendToResponse(AppendToResponseItem.IMAGES, AppendToResponseItem.EXTERNAL_IDS, AppendToResponseItem.CREDITS) ); TvSeason season = call.execute().body(); assertTvSeason(season); // credits assertThat(season.credits).isNotNull(); assertCrewCredits(season.credits.crew); assertCastCredits(season.credits.cast); // images assertThat(season.images).isNotNull(); assertImages(season.images.posters); // external ids assertThat(season.external_ids).isNotNull(); assertThat(season.external_ids.freebase_id).isNotNull(); assertThat(season.external_ids.freebase_mid).isNotNull(); assertThat(season.external_ids.tvdb_id).isNotNull(); } @Test public void test_credits() throws IOException { Call<Credits> call = getManager().tvSeasonsService().credits(TestData.TVSHOW_ID, 1); Credits credits = call.execute().body(); assertThat(credits.id).isNotNull(); assertCrewCredits(credits.crew); assertCastCredits(credits.cast); } @Test public void test_externalIds() throws IOException { Call<ExternalIds> call = getManager().tvSeasonsService().externalIds(TestData.TVSHOW_ID, 1, null); ExternalIds ids = call.execute().body(); assertThat(ids.id).isNotNull(); assertThat(ids.freebase_id).isNotNull(); assertThat(ids.freebase_mid).isNotNull(); assertThat(ids.tvdb_id).isNotNull(); } @Test public void test_images() throws IOException { Call<Images> call = getManager().tvSeasonsService().images(TestData.TVSHOW_ID, 1, null); Images images = call.execute().body(); assertThat(images.id).isNotNull(); assertImages(images.posters); } @Test public void test_videos() throws IOException { Call<Videos> call = getManager().tvSeasonsService().videos(TestData.TVSHOW_ID, 1, null); Videos videos = call.execute().body(); assertVideos(videos); } private void assertTvSeason(TvSeason season) { assertThat(season.air_date).isNotNull(); assertThat(season.name).isEqualTo("Season 1"); assertThat(season.overview).isNotNull(); assertThat(season.id).isNotNull(); assertThat(season.poster_path).isNotEmpty(); assertThat(season.season_number).isEqualTo(1); assertThat(season.episodes).isNotEmpty(); for (TvEpisode episode : season.episodes) { assertCrewCredits(episode.crew); assertCastCredits(episode.guest_stars); assertThat(episode.air_date).isNotNull(); assertThat(episode.episode_number).isPositive(); assertThat(episode.name).isNotNull(); assertThat(episode.overview).isNotNull(); assertThat(episode.id).isNotNull(); assertThat(episode.season_number).isEqualTo(1); assertThat(episode.still_path).isNotNull(); assertThat(episode.vote_average).isGreaterThanOrEqualTo(0); assertThat(episode.vote_count).isGreaterThanOrEqualTo(0); } } }
{ "content_hash": "de1f1b4f76ab9e509eaae90b19637217", "timestamp": "", "source": "github", "line_count": 115, "max_line_length": 106, "avg_line_length": 38.02608695652174, "alnum_prop": 0.6780242396524125, "repo_name": "utwyko/tmdb-java", "id": "9f441ad2004f655faebe635fcb4385f3b7b06a51", "size": "4970", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/com/uwetrottmann/tmdb2/services/TvSeasonsServiceTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "164090" }, { "name": "PowerShell", "bytes": "308" } ], "symlink_target": "" }
import { ComponentMeta, ComponentStory } from '@storybook/react'; import { Typography } from '@mui/material'; import Panel from '.'; export default { component: Panel, title: 'Panel' } as ComponentMeta<typeof Panel>; const header = <Typography>Header</Typography>; const tab = <Typography>Tab</Typography>; const TemplatePanel: ComponentStory<typeof Panel> = (args) => ( <Story {...args} /> ); export const DynamicPanel = TemplatePanel.bind({}); const Story = (props): JSX.Element => { return ( <div style={{ display: 'flex', flexDirection: 'row-reverse', height: '100vh' }} > <Panel header={header} selectedTab={tab} {...props} /> </div> ); }; export const normal = (): JSX.Element => <Story />;
{ "content_hash": "1095ac90b9166c42ade7e836936c5d5d", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 80, "avg_line_length": 23.838709677419356, "alnum_prop": 0.6481732070365359, "repo_name": "centreon/centreon", "id": "463d0d79abc8f44587f4e82cd01d5100816bb834", "size": "739", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "centreon/packages/ui/src/Panel/index.stories.tsx", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "210043" }, { "name": "Gherkin", "bytes": "174313" }, { "name": "HTML", "bytes": "1276734" }, { "name": "JavaScript", "bytes": "865312" }, { "name": "Makefile", "bytes": "25883" }, { "name": "NewLisp", "bytes": "621" }, { "name": "PHP", "bytes": "15602217" }, { "name": "Perl", "bytes": "1866808" }, { "name": "Python", "bytes": "32748" }, { "name": "Raku", "bytes": "122" }, { "name": "Shell", "bytes": "473416" }, { "name": "Smarty", "bytes": "42689" }, { "name": "TypeScript", "bytes": "1698281" }, { "name": "XSLT", "bytes": "124586" } ], "symlink_target": "" }
<?php namespace atn\PlaceBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritdoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('atn_place'); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } }
{ "content_hash": "69f4ff77a18cf0ca16948c5274092325", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 131, "avg_line_length": 30.103448275862068, "alnum_prop": 0.7147766323024055, "repo_name": "somaizouhaier/allemni", "id": "90118e7a194bca200b999d58facf866d15288616", "size": "873", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/atn/PlaceBundle/DependencyInjection/Configuration.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3073" }, { "name": "CSS", "bytes": "147104" }, { "name": "HTML", "bytes": "62029" }, { "name": "JavaScript", "bytes": "2" }, { "name": "PHP", "bytes": "112294" } ], "symlink_target": "" }
from flask import _app_ctx_stack from flask import current_app as app from flask import Flask, request, session, url_for, redirect, \ render_template, abort, g, flash, _app_ctx_stack from sqlite3 import dbapi2 as sqlite3 from hashlib import md5 from datetime import datetime def get_db(): """Opens a new database connection if there is none yet for the current application context. """ top = _app_ctx_stack.top if not hasattr(top, 'sqlite_db'): top.sqlite_db = sqlite3.connect(app.config['DATABASE']) top.sqlite_db.row_factory = sqlite3.Row return top.sqlite_db def close_database(exception): """Closes the database again at the end of the request.""" top = _app_ctx_stack.top if hasattr(top, 'sqlite_db'): top.sqlite_db.close() def init_db(): """Initializes the database.""" db = get_db() with app.open_resource('schema.sql', mode='r') as f: db.cursor().executescript(f.read()) db.commit() def initdb_command(): """Creates the database tables.""" init_db() print('Initialized the database.') def query_db(query, args=(), one=False): """Queries the database and returns a list of dictionaries.""" cur = get_db().execute(query, args) rv = cur.fetchall() return (rv[0] if rv else None) if one else rv def get_user_id(username): """Convenience method to look up the id for a username.""" rv = query_db('select user_id from user where username = ?', [username], one=True) return rv[0] if rv else None def format_datetime(timestamp): """Format a timestamp for display.""" return datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d @ %H:%M') def gravatar_url(email, size=80): """Return the gravatar image for the given email address.""" return 'http://www.gravatar.com/avatar/%s?d=identicon&s=%d' % \ (md5(email.strip().lower().encode('utf-8')).hexdigest(), size) def url_for(string, data=None): if data is not None: return (string) % data else: return string
{ "content_hash": "67eba6559bd22efa73f741226b1286a9", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 76, "avg_line_length": 32.25, "alnum_prop": 0.6501937984496124, "repo_name": "bridgetnoelleee/project2", "id": "e2b3a92eba2fe4c95b358c2246d3622aa8572d97", "size": "2064", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "helpers/functions.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "3080" }, { "name": "HTML", "bytes": "4141" }, { "name": "Python", "bytes": "10284" } ], "symlink_target": "" }
package org.apache.kafka.server.policy; import org.apache.kafka.common.config.ConfigResource; import org.apache.kafka.common.config.ConfigResource.Type; import org.apache.kafka.server.policy.AlterConfigPolicy.RequestMetadata; import org.junit.jupiter.api.Test; import java.util.Collections; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; public class AlterConfigPolicyTest { @Test public void testRequestMetadataEquals() { RequestMetadata requestMetadata = new RequestMetadata( new ConfigResource(Type.BROKER, "0"), Collections.singletonMap("foo", "bar") ); assertEquals(requestMetadata, requestMetadata); assertNotEquals(requestMetadata, null); assertNotEquals(requestMetadata, new Object()); assertNotEquals(requestMetadata, new RequestMetadata( new ConfigResource(Type.BROKER, "1"), Collections.singletonMap("foo", "bar") )); assertNotEquals(requestMetadata, new RequestMetadata( new ConfigResource(Type.BROKER, "0"), Collections.emptyMap() )); } }
{ "content_hash": "c435d952cb931e12a2049f5ee94af5ee", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 72, "avg_line_length": 33.166666666666664, "alnum_prop": 0.7068676716917923, "repo_name": "apache/kafka", "id": "13971effe9ec105eeb90ba06fce0cf3009835bb7", "size": "1992", "binary": false, "copies": "4", "ref": "refs/heads/trunk", "path": "clients/src/test/java/org/apache/kafka/server/policy/AlterConfigPolicyTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "32930" }, { "name": "Dockerfile", "bytes": "9184" }, { "name": "HTML", "bytes": "3739" }, { "name": "Java", "bytes": "33868408" }, { "name": "Python", "bytes": "1153808" }, { "name": "Roff", "bytes": "39396" }, { "name": "Scala", "bytes": "10004229" }, { "name": "Shell", "bytes": "107622" }, { "name": "XSLT", "bytes": "7116" } ], "symlink_target": "" }
/** * This object contains all possible options. It will check if the types are correct, if required if the option is one * of the allowed values. * * __any__ means that the name of the property does not matter. * __type__ is a required field for all objects and contains the allowed types of all objects */ let string = 'string'; let boolean = 'boolean'; let number = 'number'; let array = 'array'; let date = 'date'; let object = 'object'; // should only be in a __type__ property let dom = 'dom'; let moment = 'moment'; let any = 'any'; let allOptions = { configure: { enabled: {boolean}, filter: {boolean,'function': 'function'}, container: {dom}, __type__: {object,boolean,'function': 'function'} }, //globals : yAxisOrientation: {string:['left','right']}, defaultGroup: {string}, sort: {boolean}, sampling: {boolean}, stack:{boolean}, graphHeight: {string, number}, shaded: { enabled: {boolean}, orientation: {string:['bottom','top','zero','group']}, // top, bottom, zero, group groupId: {object}, __type__: {boolean,object} }, style: {string:['line','bar','points']}, // line, bar barChart: { width: {number}, minWidth: {number}, sideBySide: {boolean}, align: {string:['left','center','right']}, __type__: {object} }, interpolation: { enabled: {boolean}, parametrization: {string:['centripetal', 'chordal','uniform']}, // uniform (alpha = 0.0), chordal (alpha = 1.0), centripetal (alpha = 0.5) alpha: {number}, __type__: {object,boolean} }, drawPoints: { enabled: {boolean}, onRender: { 'function': 'function' }, size: {number}, style: {string:['square','circle']}, // square, circle __type__: {object,boolean,'function': 'function'} }, dataAxis: { showMinorLabels: {boolean}, showMajorLabels: {boolean}, icons: {boolean}, width: {string, number}, visible: {boolean}, alignZeros: {boolean}, left:{ range: {min:{number},max:{number},__type__: {object}}, format: {'function': 'function'}, title: {text:{string,number},style:{string},__type__: {object}}, __type__: {object} }, right:{ range: {min:{number},max:{number},__type__: {object}}, format: {'function': 'function'}, title: {text:{string,number},style:{string},__type__: {object}}, __type__: {object} }, __type__: {object} }, legend: { enabled: {boolean}, icons: {boolean}, left: { visible: {boolean}, position: {string:['top-right','bottom-right','top-left','bottom-left']}, __type__: {object} }, right: { visible: {boolean}, position: {string:['top-right','bottom-right','top-left','bottom-left']}, __type__: {object} }, __type__: {object,boolean} }, groups: { visibility: {any}, __type__: {object} }, autoResize: {boolean}, clickToUse: {boolean}, end: {number, date, string, moment}, format: { minorLabels: { millisecond: {string,'undefined': 'undefined'}, second: {string,'undefined': 'undefined'}, minute: {string,'undefined': 'undefined'}, hour: {string,'undefined': 'undefined'}, weekday: {string,'undefined': 'undefined'}, day: {string,'undefined': 'undefined'}, month: {string,'undefined': 'undefined'}, year: {string,'undefined': 'undefined'}, __type__: {object} }, majorLabels: { millisecond: {string,'undefined': 'undefined'}, second: {string,'undefined': 'undefined'}, minute: {string,'undefined': 'undefined'}, hour: {string,'undefined': 'undefined'}, weekday: {string,'undefined': 'undefined'}, day: {string,'undefined': 'undefined'}, month: {string,'undefined': 'undefined'}, year: {string,'undefined': 'undefined'}, __type__: {object} }, __type__: {object} }, moment: {'function': 'function'}, height: {string, number}, hiddenDates: { start: {date, number, string, moment}, end: {date, number, string, moment}, repeat: {string}, __type__: {object, array} }, locale:{string}, locales:{ __any__: {any}, __type__: {object} }, max: {date, number, string, moment}, maxHeight: {number, string}, maxMinorChars: {number}, min: {date, number, string, moment}, minHeight: {number, string}, moveable: {boolean}, multiselect: {boolean}, orientation: {string}, showCurrentTime: {boolean}, showMajorLabels: {boolean}, showMinorLabels: {boolean}, start: {date, number, string, moment}, timeAxis: { scale: {string,'undefined': 'undefined'}, step: {number,'undefined': 'undefined'}, __type__: {object} }, width: {string, number}, zoomable: {boolean}, zoomKey: {string: ['ctrlKey', 'altKey', 'metaKey', '']}, zoomMax: {number}, zoomMin: {number}, zIndex: {number}, __type__: {object} }; let configureOptions = { global: { //yAxisOrientation: ['left','right'], // TDOO: enable as soon as Grahp2d doesn't crash when changing this on the fly sort: true, sampling: true, stack:false, shaded: { enabled: false, orientation: ['zero','top','bottom','group'] // zero, top, bottom }, style: ['line','bar','points'], // line, bar barChart: { width: [50,5,100,5], minWidth: [50,5,100,5], sideBySide: false, align: ['left','center','right'] // left, center, right }, interpolation: { enabled: true, parametrization: ['centripetal','chordal','uniform'] // uniform (alpha = 0.0), chordal (alpha = 1.0), centripetal (alpha = 0.5) }, drawPoints: { enabled: true, size: [6,2,30,1], style: ['square', 'circle'] // square, circle }, dataAxis: { showMinorLabels: true, showMajorLabels: true, icons: false, width: [40,0,200,1], visible: true, alignZeros: true, left:{ //range: {min:'undefined': 'undefined'ined,max:'undefined': 'undefined'ined}, //format: function (value) {return value;}, title: {text:'',style:''} }, right:{ //range: {min:'undefined': 'undefined'ined,max:'undefined': 'undefined'ined}, //format: function (value) {return value;}, title: {text:'',style:''} } }, legend: { enabled: false, icons: true, left: { visible: true, position: ['top-right','bottom-right','top-left','bottom-left'] // top/bottom - left,right }, right: { visible: true, position: ['top-right','bottom-right','top-left','bottom-left'] // top/bottom - left,right } }, autoResize: true, clickToUse: false, end: '', format: { minorLabels: { millisecond:'SSS', second: 's', minute: 'HH:mm', hour: 'HH:mm', weekday: 'ddd D', day: 'D', month: 'MMM', year: 'YYYY' }, majorLabels: { millisecond:'HH:mm:ss', second: 'D MMMM HH:mm', minute: 'ddd D MMMM', hour: 'ddd D MMMM', weekday: 'MMMM YYYY', day: 'MMMM YYYY', month: 'YYYY', year: '' } }, height: '', locale: '', max: '', maxHeight: '', maxMinorChars: [7, 0, 20, 1], min: '', minHeight: '', moveable:true, orientation: ['both', 'bottom', 'top'], showCurrentTime: false, showMajorLabels: true, showMinorLabels: true, start: '', width: '100%', zoomable: true, zoomKey: ['ctrlKey', 'altKey', 'metaKey', ''], zoomMax: [315360000000000, 10, 315360000000000, 1], zoomMin: [10, 10, 315360000000000, 1], zIndex: 0 } }; export {allOptions, configureOptions};
{ "content_hash": "45944a4ce4b41f7604dc03846909b818", "timestamp": "", "source": "github", "line_count": 274, "max_line_length": 142, "avg_line_length": 28.463503649635037, "alnum_prop": 0.5599435825105783, "repo_name": "bounswe/bounswe2016group12", "id": "30b27b75d41e3a6c76c461f13999fea59a11fc48", "size": "7799", "binary": false, "copies": "2", "ref": "refs/heads/dev", "path": "WEB-BACKEND/Meanco/MeancoApp/static/vis-4.17.0/lib/timeline/optionsGraph2d.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "677" }, { "name": "CSS", "bytes": "93989" }, { "name": "HTML", "bytes": "6643972" }, { "name": "Java", "bytes": "288015" }, { "name": "JavaScript", "bytes": "1588264" }, { "name": "Makefile", "bytes": "508" }, { "name": "PHP", "bytes": "3338" }, { "name": "PostScript", "bytes": "7628" }, { "name": "Python", "bytes": "57508" }, { "name": "TeX", "bytes": "40817" } ], "symlink_target": "" }
 #include <aws/ds/model/DirectoryDoesNotExistException.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace DirectoryService { namespace Model { DirectoryDoesNotExistException::DirectoryDoesNotExistException() : m_messageHasBeenSet(false), m_requestIdHasBeenSet(false) { } DirectoryDoesNotExistException::DirectoryDoesNotExistException(JsonView jsonValue) : m_messageHasBeenSet(false), m_requestIdHasBeenSet(false) { *this = jsonValue; } DirectoryDoesNotExistException& DirectoryDoesNotExistException::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("Message")) { m_message = jsonValue.GetString("Message"); m_messageHasBeenSet = true; } if(jsonValue.ValueExists("RequestId")) { m_requestId = jsonValue.GetString("RequestId"); m_requestIdHasBeenSet = true; } return *this; } JsonValue DirectoryDoesNotExistException::Jsonize() const { JsonValue payload; if(m_messageHasBeenSet) { payload.WithString("Message", m_message); } if(m_requestIdHasBeenSet) { payload.WithString("RequestId", m_requestId); } return payload; } } // namespace Model } // namespace DirectoryService } // namespace Aws
{ "content_hash": "b30bbaa9590318483cb3e93514686da5", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 94, "avg_line_length": 18.253521126760564, "alnum_prop": 0.7384259259259259, "repo_name": "cedral/aws-sdk-cpp", "id": "b14442b7a46fe66aafd4f030f0b5db5fa5a9047c", "size": "1415", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "aws-cpp-sdk-ds/source/model/DirectoryDoesNotExistException.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "294220" }, { "name": "C++", "bytes": "428637022" }, { "name": "CMake", "bytes": "862025" }, { "name": "Dockerfile", "bytes": "11688" }, { "name": "HTML", "bytes": "7904" }, { "name": "Java", "bytes": "352201" }, { "name": "Python", "bytes": "106761" }, { "name": "Shell", "bytes": "10891" } ], "symlink_target": "" }
- [`9`, `latest`, `9.0.10` (*9/Dockerfile*)](https://github.com/andreptb/Dockerfiles/blob/master/tomcat/9/Dockerfile) - [`8.5-jdk8`, `8.5`, `8.5.32-jdk8` (*8.5-jdk8/Dockerfile*)](https://github.com/andreptb/Dockerfiles/blob/master/tomcat/8.5-jdk8/Dockerfile) - [`7-jdk7`, `7.0.90-jdk7` (*7-jdk7/Dockerfile*)](https://github.com/andreptb/Dockerfiles/blob/master/tomcat/7-jdk7/Dockerfile) - [`7-jdk8`, `7`, `7.0.90-jdk8` (*7-jdk8/Dockerfile*)](https://github.com/andreptb/Dockerfiles/blob/master/tomcat/7-jdk8/Dockerfile) # What is Tomcat? Apache Tomcat (or simply Tomcat) is an open source web server and servlet container developed by the Apache Software Foundation (ASF). Tomcat implements the Java Servlet and the JavaServer Pages (JSP) specifications from Oracle, and provides a "pure Java" HTTP web server environment for Java code to run in. In the simplest config Tomcat runs in a single operating system process. The process runs a Java virtual machine (JVM). Every single HTTP request from a browser to Tomcat is processed in the Tomcat process in a separate thread. > [wikipedia.org/wiki/Apache_Tomcat](https://en.wikipedia.org/wiki/Apache_Tomcat) ![logo](https://raw.githubusercontent.com/docker-library/docs/master/tomcat/logo.png)Logo &copy; Apache Software Fountation # How to use this image. Run the default Tomcat server (`CMD ["catalina.sh", "run"]`): ```console $ docker run -it --rm andreptb/tomcat ``` You can test it by visiting `http://container-ip:8080` in a browser or, if you need access outside the host, on port 8080: ```console $ docker run -it --rm -p 8080:8080 andreptb/tomcat ``` You can then go to `http://localhost:8080` or `http://host-ip:8080` in a browser. The default Tomcat environment in the image for versions 7 and 8 is: CATALINA_BASE: /usr/local/tomcat CATALINA_HOME: /usr/local/tomcat CATALINA_TMPDIR: /usr/local/tomcat/temp jdk_HOME: /usr CLASSPATH: /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar The default Tomcat environment in the image for version 6 is: CATALINA_BASE: /usr/local/tomcat CATALINA_HOME: /usr/local/tomcat CATALINA_TMPDIR: /usr/local/tomcat/temp jdk_HOME: /usr CLASSPATH: /usr/local/tomcat/bin/bootstrap.jar The configuration files are available in `/usr/local/tomcat/conf/`. By default, no user is included in the "manager-gui" role required to operate the "/manager/html" web application. If you wish to use this app, you must define such a user in `tomcat-users.xml`. ## What are the differences between this image and [docker-library/tomcat](https://github.com/docker-library/tomcat)? * Uses andreptb/oracle-java](https://github.com/andreptb/Dockerfiles/blob/master/oracle-java) instead of [docker-library/java](https://github.com/docker-library/java). * Provides base images with [Oracle JDK](http://www.oracle.com/technetwork/pt/java/javase/downloads/index.html) 6 (only tomcat 6), 7 and 8. * [Alpine](http://alpinelinux.org) images with [APR](https://apr.apache.org/) support. Check below for more information. # Alpine image This image is based on the popular [Alpine Linux project](http://alpinelinux.org), available in [the `alpine` official image](https://hub.docker.com/_/alpine). Alpine Linux is much smaller than most distribution base images (~5MB), and thus leads to much slimmer images in general. This variant is highly recommended when final image size being as small as possible is desired. See [this Hacker News comment thread](https://news.ycombinator.com/item?id=10782897) for more discussion of the issues that might arise and some pro/con comparisons of using Alpine-based images. To minimize image size, it's uncommon for additional related tools (such as `git` or `bash`) to be included in Alpine-based images. Using this image as a base, add the things you need in your own Dockerfile (see the [`alpine` image description](https://hub.docker.com/_/alpine/) for examples of how to install packages if you are unfamiliar). # License View [license information](https://www.apache.org/licenses/LICENSE-2.0) for the software contained in this image. # Supported Docker versions This image is officially supported on Docker version 1.8.2. Support for older versions (down to 1.0) is provided on a best-effort basis. ## Issues If you have any problems with or questions about this image, please contact me through a [GitHub issue](https://github.com/andreptb/Dockerfiles/issues).
{ "content_hash": "d42c8ac601022357f1c99ffa4d6b869f", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 536, "avg_line_length": 60.2972972972973, "alnum_prop": 0.7519049753473779, "repo_name": "andreptb/Dockerfiles", "id": "adfcd66e9ebd4d5a05caa98c5e4c97e82fa2d1b8", "size": "4514", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tomcat/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "98" } ], "symlink_target": "" }
var exec = require('child_process').exec; // PUBLIC function executeListCommand(callback) { execute('forever list --plain', function(stdout) { // Get names var sysNames = stdout.match(/\S+\.js/g); if (!sysNames) { console.log('No scripts are currently running.'); callback([]); return; } // Get log paths var logPaths = stdout.match(/\/\S+\.log/g); // Get scripts ID's var idsWithExtraCharacters = stdout.match(/\s\d+\s+\//g); var IDs = new Array(); for (var i=0; i<idsWithExtraCharacters.length; i++) { var id = idsWithExtraCharacters[i].match(/\d+/)[0]; IDs.push(id); } // Get script paths var pathForID = {}; execute('ps aux | grep forever', function(stdout) { var rows = stdout.split('\n'); for (var i=0; i<rows.length; i++) { var row = rows[i]; // Get script path var scriptPathArray = row.match(/\/\S+.js/); if (scriptPathArray == null) { // If the current row does not contain a script path, move to next row continue; } var scriptPath = scriptPathArray[0]; // Get script ID var scriptID = row.match(/^\w+\s+\d+/)[0].match(/\d+/)[0]; // Store pathForID[scriptID] = scriptPath; } // Construct Script objects with parsed data var scripts = new Array(); for (var i=0; i<sysNames.length; i++) { var script = { id : IDs[i], name : 'Unnamed', sysname : sysNames[i], status : 1, path : pathForID[IDs[i]], log : logPaths[i] } scripts.push(script); } callback(scripts); }); }); } function startScriptWithPath(scriptPath, callback) { execute('forever start ' + scriptPath, function(stdout) { callback(); }); } function stopScriptWithSysName(scriptSysName, callback) { execute('forever stop ' + scriptSysName, function(stdout) { callback(); }); } function stopAllScripts(callback) { execute('forever stopall', function() { callback(); }); } exports.executeListCommand = executeListCommand; exports.startScriptWithPath = startScriptWithPath; exports.stopScriptWithSysName = stopScriptWithSysName; exports.stopAllScripts= stopAllScripts; // PRIVATE function execute(command, callback) { exec(command, function(error, stdout, stderr) { callback(stdout); }); }; //execute('forever ' + req.body.cmd + ' ' + req.body.args + ' --plain', function(result) { // var names = result.match(/\S+\.js/g); // var logPaths = result.match(/\/\S+\.log/g); // // // var response = JSON.stringify({ // "logPaths" : logPaths, // "names" : names // }); // // console.log(logPaths); // // res.end(response); //});
{ "content_hash": "803158128b5e64a10c2d73cdfebc94c9", "timestamp": "", "source": "github", "line_count": 121, "max_line_length": 117, "avg_line_length": 26.06611570247934, "alnum_prop": 0.5161699429296132, "repo_name": "nikolaydyankov/node-forever-gui", "id": "0f14429d615edaf1def914866b5b560056689945", "size": "3154", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "forever-gui/app_modules/exec-manager.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "437471" }, { "name": "JavaScript", "bytes": "1410148" }, { "name": "Shell", "bytes": "2387" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.9.1"/> <title>labyrinth2015: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">labyrinth2015 &#160;<span id="projectnumber">1.0</span> </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.9.1 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">Ui_QMain Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="classUi__QMain.html">Ui_QMain</a>, including all inherited members.</p> <table class="directory"> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>action_About</b> (defined in <a class="el" href="classUi__QMain.html">Ui_QMain</a>)</td><td class="entry"><a class="el" href="classUi__QMain.html">Ui_QMain</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>actionConnect</b> (defined in <a class="el" href="classUi__QMain.html">Ui_QMain</a>)</td><td class="entry"><a class="el" href="classUi__QMain.html">Ui_QMain</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>actionDebug</b> (defined in <a class="el" href="classUi__QMain.html">Ui_QMain</a>)</td><td class="entry"><a class="el" href="classUi__QMain.html">Ui_QMain</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>actionDisconnect</b> (defined in <a class="el" href="classUi__QMain.html">Ui_QMain</a>)</td><td class="entry"><a class="el" href="classUi__QMain.html">Ui_QMain</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>actionExit</b> (defined in <a class="el" href="classUi__QMain.html">Ui_QMain</a>)</td><td class="entry"><a class="el" href="classUi__QMain.html">Ui_QMain</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>actionInvite_players</b> (defined in <a class="el" href="classUi__QMain.html">Ui_QMain</a>)</td><td class="entry"><a class="el" href="classUi__QMain.html">Ui_QMain</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>actionLoad_game</b> (defined in <a class="el" href="classUi__QMain.html">Ui_QMain</a>)</td><td class="entry"><a class="el" href="classUi__QMain.html">Ui_QMain</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>actionNew_game</b> (defined in <a class="el" href="classUi__QMain.html">Ui_QMain</a>)</td><td class="entry"><a class="el" href="classUi__QMain.html">Ui_QMain</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>actionSave_game</b> (defined in <a class="el" href="classUi__QMain.html">Ui_QMain</a>)</td><td class="entry"><a class="el" href="classUi__QMain.html">Ui_QMain</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>centralWidget</b> (defined in <a class="el" href="classUi__QMain.html">Ui_QMain</a>)</td><td class="entry"><a class="el" href="classUi__QMain.html">Ui_QMain</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>menu_Help</b> (defined in <a class="el" href="classUi__QMain.html">Ui_QMain</a>)</td><td class="entry"><a class="el" href="classUi__QMain.html">Ui_QMain</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>menu_Menu</b> (defined in <a class="el" href="classUi__QMain.html">Ui_QMain</a>)</td><td class="entry"><a class="el" href="classUi__QMain.html">Ui_QMain</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>menuBar</b> (defined in <a class="el" href="classUi__QMain.html">Ui_QMain</a>)</td><td class="entry"><a class="el" href="classUi__QMain.html">Ui_QMain</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>retranslateUi</b>(QMainWindow *QMain) (defined in <a class="el" href="classUi__QMain.html">Ui_QMain</a>)</td><td class="entry"><a class="el" href="classUi__QMain.html">Ui_QMain</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>setupUi</b>(QMainWindow *QMain) (defined in <a class="el" href="classUi__QMain.html">Ui_QMain</a>)</td><td class="entry"><a class="el" href="classUi__QMain.html">Ui_QMain</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>statusBar</b> (defined in <a class="el" href="classUi__QMain.html">Ui_QMain</a>)</td><td class="entry"><a class="el" href="classUi__QMain.html">Ui_QMain</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>toolBar</b> (defined in <a class="el" href="classUi__QMain.html">Ui_QMain</a>)</td><td class="entry"><a class="el" href="classUi__QMain.html">Ui_QMain</a></td><td class="entry"></td></tr> </table></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Sun May 10 2015 17:58:40 for labyrinth2015 by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.9.1 </small></address> </body> </html>
{ "content_hash": "4da774d3ed961cd38046d43f870be55a", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 299, "avg_line_length": 70.40677966101696, "alnum_prop": 0.646605681271064, "repo_name": "fkolacek/FIT-VUT", "id": "20617185cdcf8438e527f44cdd966de37df8b0e8", "size": "8308", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "mess/ICP-Labyrinth/doc/html/classUi__QMain-members.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "455326" }, { "name": "Awk", "bytes": "8724" }, { "name": "Batchfile", "bytes": "201" }, { "name": "Brainfuck", "bytes": "83" }, { "name": "C", "bytes": "5006938" }, { "name": "C++", "bytes": "1835332" }, { "name": "CSS", "bytes": "301045" }, { "name": "CoffeeScript", "bytes": "46327" }, { "name": "Groff", "bytes": "46766" }, { "name": "HTML", "bytes": "937735" }, { "name": "Java", "bytes": "552132" }, { "name": "JavaScript", "bytes": "1742225" }, { "name": "Lua", "bytes": "39700" }, { "name": "Makefile", "bytes": "381793" }, { "name": "Objective-C", "bytes": "4618" }, { "name": "PHP", "bytes": "108701" }, { "name": "PLSQL", "bytes": "22886" }, { "name": "Perl", "bytes": "60353" }, { "name": "Python", "bytes": "22084026" }, { "name": "QMake", "bytes": "2660" }, { "name": "R", "bytes": "1370" }, { "name": "Ragel in Ruby Host", "bytes": "17993" }, { "name": "Ruby", "bytes": "21607145" }, { "name": "Shell", "bytes": "611321" }, { "name": "Tcl", "bytes": "4920" }, { "name": "TeX", "bytes": "561423" }, { "name": "VHDL", "bytes": "49180" }, { "name": "Visual Basic", "bytes": "481" }, { "name": "XSLT", "bytes": "154638" }, { "name": "Yacc", "bytes": "32788" } ], "symlink_target": "" }
layout: page title: Shepherd Tough Aerospace Executive Retreat date: 2016-05-24 author: Margaret Navarro tags: weekly links, java status: published summary: Praesent enim orci, consectetur nec odio ut, laoreet tempus magna. banner: images/banner/office-01.jpg booking: startDate: 01/23/2017 endDate: 01/24/2017 ctyhocn: BRSNEHX groupCode: STAER published: true --- Praesent tristique odio eget urna malesuada dapibus. Ut at fermentum enim. Etiam ut purus metus. Nulla facilisi. Ut posuere ex purus, vitae convallis libero lacinia sit amet. Vivamus eget orci dignissim, ornare arcu eget, bibendum justo. Suspendisse orci lorem, viverra et ullamcorper at, vulputate nec libero. * Etiam accumsan arcu lobortis risus eleifend iaculis * Aliquam nec enim sed ex viverra sollicitudin ac eu orci * Nunc eget nunc mollis ligula bibendum ultrices. Morbi aliquam tempor semper. Proin a fringilla libero, in dapibus nibh. Vivamus et euismod nulla. Vivamus in varius elit. Aliquam libero metus, luctus eu massa quis, fermentum maximus nulla. Morbi lacinia sagittis justo, eget ultrices nulla pharetra sed. Praesent sagittis, orci eget pulvinar sollicitudin, eros est imperdiet tellus, nec pellentesque sem erat eget purus. Mauris faucibus lectus sit amet placerat ultrices. Proin venenatis purus eget sem fermentum, et blandit quam eleifend. Aliquam dignissim laoreet tempor. Praesent vitae hendrerit quam. Proin id faucibus felis. Quisque vitae ipsum a velit egestas rhoncus vel et sem. Aenean neque risus, pharetra eu lorem sed, dignissim iaculis est. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin condimentum, elit in fermentum lacinia, ante dolor finibus orci, mattis gravida eros quam sit amet libero.
{ "content_hash": "45626569716d1fb2e4e98542039a7695", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 909, "avg_line_length": 79.9090909090909, "alnum_prop": 0.8088737201365188, "repo_name": "KlishGroup/prose-pogs", "id": "9f55ae2062e745119f5f01cebe3200e691204062", "size": "1762", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "pogs/B/BRSNEHX/STAER/index.md", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<!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_60) on Mon Mar 28 17:12:00 AEST 2016 --> <title>net.jini.jeri.connection Class Hierarchy (River-Internet vtrunk API Documentation (internals))</title> <meta name="date" content="2016-03-28"> <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="net.jini.jeri.connection Class Hierarchy (River-Internet vtrunk API Documentation (internals))"; } } 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="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../net/jini/jeri/package-tree.html">Prev</a></li> <li><a href="../../../../net/jini/jeri/http/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?net/jini/jeri/connection/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.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"> <h1 class="title">Hierarchy For Package net.jini.jeri.connection</h1> <span class="packageHierarchyLabel">Package Hierarchies:</span> <ul class="horizontal"> <li><a href="../../../../overview-tree.html">All Packages</a></li> </ul> </div> <div class="contentContainer"> <h2 title="Class Hierarchy">Class Hierarchy</h2> <ul> <li type="circle">java.lang.<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Object</span></a> <ul> <li type="circle">net.jini.jeri.connection.<a href="../../../../net/jini/jeri/connection/ConnectionManager.html" title="class in net.jini.jeri.connection"><span class="typeNameLink">ConnectionManager</span></a></li> <li type="circle">net.jini.jeri.connection.<a href="../../../../net/jini/jeri/connection/ConnectionManager.Outbound.html" title="class in net.jini.jeri.connection"><span class="typeNameLink">ConnectionManager.Outbound</span></a> (implements net.jini.jeri.<a href="../../../../net/jini/jeri/OutboundRequest.html" title="interface in net.jini.jeri">OutboundRequest</a>)</li> <li type="circle">net.jini.jeri.connection.<a href="../../../../net/jini/jeri/connection/ConnectionManager.Reaper.html" title="class in net.jini.jeri.connection"><span class="typeNameLink">ConnectionManager.Reaper</span></a> (implements java.lang.<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Runnable.html?is-external=true" title="class or interface in java.lang">Runnable</a>)</li> <li type="circle">net.jini.jeri.connection.<a href="../../../../net/jini/jeri/connection/ConnectionManager.ReqIterator.html" title="class in net.jini.jeri.connection"><span class="typeNameLink">ConnectionManager.ReqIterator</span></a> (implements net.jini.jeri.<a href="../../../../net/jini/jeri/OutboundRequestIterator.html" title="interface in net.jini.jeri">OutboundRequestIterator</a>)</li> <li type="circle">java.io.<a href="http://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html?is-external=true" title="class or interface in java.io"><span class="typeNameLink">InputStream</span></a> (implements java.io.<a href="http://docs.oracle.com/javase/8/docs/api/java/io/Closeable.html?is-external=true" title="class or interface in java.io">Closeable</a>) <ul> <li type="circle">net.jini.jeri.connection.<a href="../../../../net/jini/jeri/connection/ConnectionManager.Outbound.Input.html" title="class in net.jini.jeri.connection"><span class="typeNameLink">ConnectionManager.Outbound.Input</span></a></li> </ul> </li> <li type="circle">org.apache.river.jeri.internal.mux.<a href="../../../../org/apache/river/jeri/internal/mux/Mux.html" title="class in org.apache.river.jeri.internal.mux"><span class="typeNameLink">Mux</span></a> <ul> <li type="circle">org.apache.river.jeri.internal.mux.<a href="../../../../org/apache/river/jeri/internal/mux/MuxClient.html" title="class in org.apache.river.jeri.internal.mux"><span class="typeNameLink">MuxClient</span></a> <ul> <li type="circle">net.jini.jeri.connection.<a href="../../../../net/jini/jeri/connection/ConnectionManager.OutboundMux.html" title="class in net.jini.jeri.connection"><span class="typeNameLink">ConnectionManager.OutboundMux</span></a></li> </ul> </li> <li type="circle">org.apache.river.jeri.internal.mux.<a href="../../../../org/apache/river/jeri/internal/mux/MuxServer.html" title="class in org.apache.river.jeri.internal.mux"><span class="typeNameLink">MuxServer</span></a> <ul> <li type="circle">net.jini.jeri.connection.<a href="../../../../net/jini/jeri/connection/ServerConnectionManager.InboundMux.html" title="class in net.jini.jeri.connection"><span class="typeNameLink">ServerConnectionManager.InboundMux</span></a></li> </ul> </li> </ul> </li> <li type="circle">net.jini.jeri.connection.<a href="../../../../net/jini/jeri/connection/ServerConnectionManager.html" title="class in net.jini.jeri.connection"><span class="typeNameLink">ServerConnectionManager</span></a></li> <li type="circle">net.jini.jeri.connection.<a href="../../../../net/jini/jeri/connection/ServerConnectionManager.Dispatcher.html" title="class in net.jini.jeri.connection"><span class="typeNameLink">ServerConnectionManager.Dispatcher</span></a> (implements net.jini.jeri.<a href="../../../../net/jini/jeri/RequestDispatcher.html" title="interface in net.jini.jeri">RequestDispatcher</a>)</li> <li type="circle">net.jini.jeri.connection.<a href="../../../../net/jini/jeri/connection/ServerConnectionManager.Inbound.html" title="class in net.jini.jeri.connection"><span class="typeNameLink">ServerConnectionManager.Inbound</span></a> (implements net.jini.jeri.<a href="../../../../net/jini/jeri/InboundRequest.html" title="interface in net.jini.jeri">InboundRequest</a>)</li> </ul> </li> </ul> <h2 title="Interface Hierarchy">Interface Hierarchy</h2> <ul> <li type="circle">net.jini.jeri.connection.<a href="../../../../net/jini/jeri/connection/Connection.html" title="interface in net.jini.jeri.connection"><span class="typeNameLink">Connection</span></a></li> <li type="circle">net.jini.jeri.connection.<a href="../../../../net/jini/jeri/connection/ConnectionEndpoint.html" title="interface in net.jini.jeri.connection"><span class="typeNameLink">ConnectionEndpoint</span></a></li> <li type="circle">net.jini.jeri.connection.<a href="../../../../net/jini/jeri/connection/InboundRequestHandle.html" title="interface in net.jini.jeri.connection"><span class="typeNameLink">InboundRequestHandle</span></a></li> <li type="circle">net.jini.jeri.connection.<a href="../../../../net/jini/jeri/connection/OutboundRequestHandle.html" title="interface in net.jini.jeri.connection"><span class="typeNameLink">OutboundRequestHandle</span></a></li> <li type="circle">net.jini.jeri.connection.<a href="../../../../net/jini/jeri/connection/ServerConnection.html" title="interface in net.jini.jeri.connection"><span class="typeNameLink">ServerConnection</span></a></li> </ul> </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="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../net/jini/jeri/package-tree.html">Prev</a></li> <li><a href="../../../../net/jini/jeri/http/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?net/jini/jeri/connection/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.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 ======= --> <p class="legalCopy"><small>Copyright 2007-2013, multiple authors.<br>Licensed under the <a href=http://www.apache.org/licenses/LICENSE-2.0 target=child >Apache License, Version 2.0</a>, see the <a href=../../../../doc-files/NOTICE target=child >NOTICE</a> file for attributions.</small></p> </body> </html>
{ "content_hash": "1be9364212528e3b567580453c922eb1", "timestamp": "", "source": "github", "line_count": 171, "max_line_length": 397, "avg_line_length": 60.44444444444444, "alnum_prop": 0.680921052631579, "repo_name": "pfirmstone/JGDMS", "id": "86cf918b72c40d1493e11be51f15bd3595f3a87f", "size": "10336", "binary": false, "copies": "2", "ref": "refs/heads/trunk", "path": "JGDMS/src/site/resources/old-static-site/doc/internals/net/jini/jeri/connection/package-tree.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "38260" }, { "name": "Groovy", "bytes": "30510" }, { "name": "HTML", "bytes": "107806458" }, { "name": "Java", "bytes": "24863323" }, { "name": "JavaScript", "bytes": "1702" }, { "name": "Makefile", "bytes": "3032" }, { "name": "Roff", "bytes": "863" }, { "name": "Shell", "bytes": "68247" } ], "symlink_target": "" }
var util = require('../util.test'); module.exports = function() { util.request({ url: 'https://resreplace.test.whistlejs.com/?resBody=123test', method: 'post' }, function(res, body) { body.should.equal('123abc'); }); util.request('http://resreplace.test.whistlejs.com/?resBody=test123', function(res, body) { body.should.equal('abc123'); }); };
{ "content_hash": "dab115101d78a465f41be8d6d6b0d3cd", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 93, "avg_line_length": 26.642857142857142, "alnum_prop": 0.6407506702412868, "repo_name": "avwo/whistle", "id": "5d243695ef7fc40f4c881cea97c1ade5104eee54", "size": "373", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/units/resReplace.test.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "70705" }, { "name": "HTML", "bytes": "25764" }, { "name": "JavaScript", "bytes": "1739389" } ], "symlink_target": "" }
Title: Exercise 5 Date: 2014-11-11 1:14AM Another late night with Python. Tonight was [exercise 5](https://learnpythonthehardway.org/book/ex5.html) and it covered string formatting and replacement. I entered these lines into a `.py` file and ran it with `python ex05.py`: ``` # Exercise 5 # https://learnpythonthehardway.org/book/ex5.html name = 'Zed A. Shaw' age = 35 # not a lie height = 74 # inches weight = 180 # lbs eyes = 'Blue' teeth = 'White' hair = 'Brown' print "Let's talk about %s." % name print "He's %d inches tall." % height print "He's %d pounds heavy." % weight print "Actually that's not too heavy." print "He's got %s eyes and %s hair." % (eyes, hair) print "His teeth are usually %s depending on the coffee." % teeth # this line is tricky, try to get it exactly right print "If I add %d, %d, and %d I get %d." % ( age, height, weight, age + height + weight) # Study drills height_cm = height * 2.54 # cm weight_kg = weight * 0.453592 # kg print "He's %d centimeters tall." % height_cm print "He's %d kilograms heavy." % weight_kg # %r format character r = "Print this no matter what" print "Here is what %%r does: %r" % r ``` ![Exercise 05]({filename}/images/ex05.png "Exercise 05") Nothing too crazy, just some string formatting, specifically decimal, `%d`, representation, `%r`, and string, `%s`. Here are all of the [Python format characters](https://docs.python.org/2/library/stdtypes.html#string-formatting-operations). A quick search on Google brings up all of the Imperial-Metric conversions that I forgot from middle school: - 1 in = 2.54 cm - 1 lb = 0.453592 kg Now, can anyone go back and do formatting and replacing of all my traumatic middle school memories? Because that would be fabulous.
{ "content_hash": "f35717bb6ca1a00b3d465bd26a58c9b4", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 241, "avg_line_length": 32.867924528301884, "alnum_prop": 0.7049368541905855, "repo_name": "richardcornish/lpthw", "id": "4adb3229142bc026f15006dbe36b2d2b45af3024", "size": "1742", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "pelican/content/ex05.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "14760" }, { "name": "HTML", "bytes": "15173" }, { "name": "Python", "bytes": "24295" }, { "name": "Shell", "bytes": "2201" } ], "symlink_target": "" }
layout: null section-type: about title: About --- ## About Defenestrate is a guild located on Tarren mill intent on maintaining a 2 day a week raiding , <i>Monday</i> and <i>Thursday</i>. In our first raid tier we successfully achieved cutting edge. <h3>Attendance</h3> <p>We prefer people to have as close to 100% attendance as possible for raids, however we understand that real life is always priority.</p> <h3>Loot Distribution</h3> <p>All loot is distributed, via a 3 man loot council, with all loot being awarded to the player able to most benefit from said loot.</p> We're currently recruiting talented players to join our ranks in preparation for Antorus, the burning throne. Please see our <a href="#contact">Contact Section</a> for our current recruitment options. <div class="row"> <div class="col-xs-6 col-xs-offset-3"> <a href="https://wowprogress.com/"><img alt="WoW Guild Rankings" src="https://wowprogress.com/guild_img/1454005/out/type.site" border="0"/></a> </div> </div>
{ "content_hash": "874ad1a6fda4a26c9129eb588251eb29", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 200, "avg_line_length": 48.857142857142854, "alnum_prop": 0.7222222222222222, "repo_name": "defenestrate-tarrenmill/defenestrate-tarrenmill.github.io", "id": "2c7b5276a4a5ff2b65f2ac56a488e82cfff84c80", "size": "1030", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "about.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "14620" }, { "name": "HTML", "bytes": "115907" }, { "name": "Ruby", "bytes": "2490" }, { "name": "Shell", "bytes": "462" } ], "symlink_target": "" }
#ifndef ContentData_h #define ContentData_h #include "CounterContent.h" #include "StyleImage.h" #include "RenderPtr.h" namespace WebCore { class Document; class RenderObject; class RenderStyle; class ContentData { WTF_MAKE_FAST_ALLOCATED; public: enum Type { CounterDataType, ImageDataType, QuoteDataType, TextDataType }; virtual ~ContentData() { } Type type() const { return m_type; } bool isCounter() const { return type() == CounterDataType; } bool isImage() const { return type() == ImageDataType; } bool isQuote() const { return type() == QuoteDataType; } bool isText() const { return type() == TextDataType; } virtual RenderPtr<RenderObject> createContentRenderer(Document&, const RenderStyle&) const = 0; std::unique_ptr<ContentData> clone() const; ContentData* next() const { return m_next.get(); } void setNext(std::unique_ptr<ContentData> next) { m_next = WTF::move(next); } void setAltText(const String& alt) { m_altText = alt; } const String& altText() const { return m_altText; } protected: explicit ContentData(Type type) : m_type(type) { } private: virtual std::unique_ptr<ContentData> cloneInternal() const = 0; std::unique_ptr<ContentData> m_next; String m_altText; Type m_type; }; #define CONTENT_DATA_TYPE_CASTS(ToClassName, FromClassName, ContentDataName) \ TYPE_CASTS_BASE(ToClassName, FromClassName, resource, resource->is##ContentDataName(), resource.is##ContentDataName()) class ImageContentData final : public ContentData { public: explicit ImageContentData(PassRefPtr<StyleImage> image) : ContentData(ImageDataType) , m_image(image) { ASSERT(m_image); } const StyleImage& image() const { return *m_image; } void setImage(PassRefPtr<StyleImage> image) { ASSERT(image); m_image = image; } virtual RenderPtr<RenderObject> createContentRenderer(Document&, const RenderStyle&) const override; private: virtual std::unique_ptr<ContentData> cloneInternal() const override { return std::make_unique<ImageContentData>(m_image.get()); } RefPtr<StyleImage> m_image; }; CONTENT_DATA_TYPE_CASTS(ImageContentData, ContentData, Image) inline bool operator==(const ImageContentData& a, const ImageContentData& b) { return a.image() == b.image(); } inline bool operator!=(const ImageContentData& a, const ImageContentData& b) { return !(a == b); } class TextContentData final : public ContentData { public: explicit TextContentData(const String& text) : ContentData(TextDataType) , m_text(text) { } const String& text() const { return m_text; } void setText(const String& text) { m_text = text; } virtual RenderPtr<RenderObject> createContentRenderer(Document&, const RenderStyle&) const override; private: virtual std::unique_ptr<ContentData> cloneInternal() const override { return std::make_unique<TextContentData>(text()); } String m_text; }; CONTENT_DATA_TYPE_CASTS(TextContentData, ContentData, Text) inline bool operator==(const TextContentData& a, const TextContentData& b) { return a.text() == b.text(); } inline bool operator!=(const TextContentData& a, const TextContentData& b) { return !(a == b); } class CounterContentData final : public ContentData { public: explicit CounterContentData(std::unique_ptr<CounterContent> counter) : ContentData(CounterDataType) , m_counter(WTF::move(counter)) { ASSERT(m_counter); } const CounterContent& counter() const { return *m_counter; } void setCounter(std::unique_ptr<CounterContent> counter) { ASSERT(counter); m_counter = WTF::move(counter); } virtual RenderPtr<RenderObject> createContentRenderer(Document&, const RenderStyle&) const override; private: virtual std::unique_ptr<ContentData> cloneInternal() const override { auto counterData = std::make_unique<CounterContent>(counter()); return std::make_unique<CounterContentData>(WTF::move(counterData)); } std::unique_ptr<CounterContent> m_counter; }; CONTENT_DATA_TYPE_CASTS(CounterContentData, ContentData, Counter) inline bool operator==(const CounterContentData& a, const CounterContentData& b) { return a.counter() == b.counter(); } inline bool operator!=(const CounterContentData& a, const CounterContentData& b) { return !(a == b); } class QuoteContentData final : public ContentData { public: explicit QuoteContentData(QuoteType quote) : ContentData(QuoteDataType) , m_quote(quote) { } QuoteType quote() const { return m_quote; } void setQuote(QuoteType quote) { m_quote = quote; } virtual RenderPtr<RenderObject> createContentRenderer(Document&, const RenderStyle&) const override; private: virtual std::unique_ptr<ContentData> cloneInternal() const override { return std::make_unique<QuoteContentData>(quote()); } QuoteType m_quote; }; CONTENT_DATA_TYPE_CASTS(QuoteContentData, ContentData, Quote) inline bool operator==(const QuoteContentData& a, const QuoteContentData& b) { return a.quote() == b.quote(); } inline bool operator!=(const QuoteContentData& a, const QuoteContentData& b) { return !(a == b); } inline bool operator==(const ContentData& a, const ContentData& b) { if (a.type() != b.type()) return false; switch (a.type()) { case ContentData::CounterDataType: return toCounterContentData(a) == toCounterContentData(b); case ContentData::ImageDataType: return toImageContentData(a) == toImageContentData(b); case ContentData::QuoteDataType: return toQuoteContentData(a) == toQuoteContentData(b); case ContentData::TextDataType: return toTextContentData(a) == toTextContentData(b); } ASSERT_NOT_REACHED(); return false; } inline bool operator!=(const ContentData& a, const ContentData& b) { return !(a == b); } } // namespace WebCore #endif // ContentData_h
{ "content_hash": "321bd843832dab88b06736857ec1855c", "timestamp": "", "source": "github", "line_count": 229, "max_line_length": 127, "avg_line_length": 26.59825327510917, "alnum_prop": 0.6857658840912823, "repo_name": "aosm/WebCore", "id": "c065cbea4529154f53748065f194481a3209c0c0", "size": "7179", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "rendering/style/ContentData.h", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Assembly", "bytes": "3242" }, { "name": "C", "bytes": "3457587" }, { "name": "C++", "bytes": "37868918" }, { "name": "CSS", "bytes": "121894" }, { "name": "JavaScript", "bytes": "131375" }, { "name": "Objective-C", "bytes": "392661" }, { "name": "Objective-C++", "bytes": "2868092" }, { "name": "Perl", "bytes": "643657" }, { "name": "Python", "bytes": "39670" }, { "name": "Ruby", "bytes": "2718" }, { "name": "Shell", "bytes": "12541" } ], "symlink_target": "" }
Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Name** | **string** | | [optional] **Value** | **string** | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
{ "content_hash": "19fa1dae7268d9285958ff1841443d75", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 161, "avg_line_length": 42.375, "alnum_prop": 0.5162241887905604, "repo_name": "UltraCart/rest_api_v2_sdk_csharp", "id": "72c82bfc20e763422e0876ad86403a017606099a", "size": "418", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/ScreenRecordingPageViewParameter.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "951" }, { "name": "C#", "bytes": "11743806" }, { "name": "Shell", "bytes": "4486" } ], "symlink_target": "" }
[![Build Status](https://secure.travis-ci.org/codeforamerica/adopt-a-hydrant.png?branch=master)][travis] [![Dependency Status](https://gemnasium.com/codeforamerica/adopt-a-hydrant.png?travis)][gemnasium] [![Coverage Status](https://coveralls.io/repos/codeforamerica/adopt-a-hydrant/badge.png?branch=master)][coveralls] [travis]: http://travis-ci.org/codeforamerica/adopt-a-hydrant [gemnasium]: https://gemnasium.com/codeforamerica/adopt-a-hydrant [coveralls]: https://coveralls.io/r/codeforamerica/adopt-a-hydrant Claim responsibility for shoveling out a fire hydrant after it snows. ## Screenshot ![Adopt-a-Hydrant](https://github.com/codeforamerica/adopt-a-hydrant/raw/master/screenshot.png "Adopt-a-Hydrant") ## Demo You can see a running version of the application at [http://adopt-a-hydrant.herokuapp.com/][demo]. [demo]: http://adopt-a-hydrant.herokuapp.com/ ## Installation This application requires [Postgres](http://www.postgresql.org/) to be installed git clone git://github.com/codeforamerica/adopt-a-hydrant.git cd adopt-a-hydrant bundle install bundle exec rake db:create bundle exec rake db:schema:load ## Usage rails server ## Seed Data bundle exec rake db:seed ## Deploying to Heroku A successful deployment to Heroku requires a few setup steps: 1. Generate a new secret token: ``` rake secret ``` 2. Set the token on Heroku: ``` heroku config:set SECRET_TOKEN=the_token_you_generated ``` 3. [Precompile your assets](https://devcenter.heroku.com/articles/rails3x-asset-pipeline-cedar) ``` RAILS_ENV=production bundle exec rake assets:precompile git add public/assets git commit -m "vendor compiled assets" ``` 4. Add a production database to config/database.yml 5. Seed the production db: `heroku run bundle exec rake db:seed` 6. Keep in mind that the Heroku free Postgres plan only allows up to 10,000 rows, so if your city has more than 10,000 fire hydrants (or other thing to be adopted), you will need to upgrade to the $9/month plan. ## Contributing In the spirit of [free software][free-sw], **everyone** is encouraged to help improve this project. [free-sw]: http://www.fsf.org/licensing/essays/free-sw.html Here are some ways *you* can contribute: * by using alpha, beta, and prerelease versions * by reporting bugs * by suggesting new features * by [translating to a new language][locales] * by writing or editing documentation * by writing specifications * by writing code (**no patch is too small**: fix typos, add comments, clean up inconsistent whitespace) * by refactoring code * by closing [issues][] * by reviewing patches * [financially][] [locales]: https://github.com/codeforamerica/adopt-a-hydrant/tree/master/config/locales [issues]: https://github.com/codeforamerica/adopt-a-hydrant/issues [financially]: https://secure.codeforamerica.org/page/contribute ## Submitting an Issue We use the [GitHub issue tracker][issues] to track bugs and features. Before submitting a bug report or feature request, check to make sure it hasn't already been submitted. When submitting a bug report, please include a [Gist][] that includes a stack trace and any details that may be necessary to reproduce the bug, including your gem version, Ruby version, and operating system. Ideally, a bug report should include a pull request with failing specs. [gist]: https://gist.github.com/ ## Submitting a Pull Request 1. [Fork the repository.][fork] 2. [Create a topic branch.][branch] 3. Add specs for your unimplemented feature or bug fix. 4. Run `bundle exec rake test`. If your specs pass, return to step 3. 5. Implement your feature or bug fix. 6. Run `bundle exec rake test`. If your specs fail, return to step 5. 7. Run `open coverage/index.html`. If your changes are not completely covered by your tests, return to step 3. 8. Add, commit, and push your changes. 9. [Submit a pull request.][pr] [fork]: http://help.github.com/fork-a-repo/ [branch]: http://learn.github.com/p/branching.html [pr]: http://help.github.com/send-pull-requests/ ## Supported Ruby Version This library aims to support and is [tested against][travis] Ruby version 1.9.3. If something doesn't work on this version, it should be considered a bug. This library may inadvertently work (or seem to work) on other Ruby implementations, however support will only be provided for the version above. If you would like this library to support another Ruby version, you may volunteer to be a maintainer. Being a maintainer entails making sure all tests run and pass on that implementation. When something breaks on your implementation, you will be personally responsible for providing patches in a timely fashion. If critical issues for a particular implementation exist at the time of a major release, support for that Ruby version may be dropped. ## Copyright Copyright (c) 2012 Code for America. See [LICENSE][] for details. [license]: https://github.com/codeforamerica/adopt-a-hydrant/blob/master/LICENSE.md [![Code for America Tracker](http://stats.codeforamerica.org/codeforamerica/adopt-a-hydrant.png)][tracker] [tracker]: http://stats.codeforamerica.org/projects/adopt-a-hydrant
{ "content_hash": "e922b5d58b85d2ddae2b54ecf2157509", "timestamp": "", "source": "github", "line_count": 142, "max_line_length": 211, "avg_line_length": 36.570422535211264, "alnum_prop": 0.7548623146543424, "repo_name": "0111001101111010/adopt-a-spot-odu", "id": "0096a2f5a3f579cc392ad79a96f46da5881d1b89", "size": "5212", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "4115" }, { "name": "JavaScript", "bytes": "599" }, { "name": "Ruby", "bytes": "880993" } ], "symlink_target": "" }
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.sps.data; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.datastore.Query; import com.google.appengine.api.datastore.Query.FilterOperator; import com.google.appengine.api.datastore.Query.FilterPredicate; import com.google.appengine.api.datastore.Query.Filter; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import com.google.gson.Gson; /** Class that stores sample Tutor objects for testing. */ public final class SampleData { private final int TIME_0800AM = TimeRange.getTimeInMinutes(8, 00); private final int TIME_0900AM = TimeRange.getTimeInMinutes(9, 00); private final int TIME_1000AM = TimeRange.getTimeInMinutes(10, 00); private final int TIME_1100AM = TimeRange.getTimeInMinutes(11, 00); private final int TIME_1200AM = TimeRange.getTimeInMinutes(12, 00); private final int TIME_0100PM = TimeRange.getTimeInMinutes(13, 00); private final int TIME_0200PM = TimeRange.getTimeInMinutes(14, 00); private final int TIME_0300PM = TimeRange.getTimeInMinutes(15, 00); private final int TIME_0500PM = TimeRange.getTimeInMinutes(17, 00); private final Calendar MAY182020 = new Calendar.Builder() .setCalendarType("iso8601") .setDate(2020, 4, 18) .build(); private final Calendar AUGUST102020 = new Calendar.Builder() .setCalendarType("iso8601") .setDate(2020, 7, 10) .build(); private final Calendar AUGUST72020 = new Calendar.Builder() .setCalendarType("iso8601") .setDate(2020, 7, 7) .build(); private final Calendar AUGUST182020 = new Calendar.Builder() .setCalendarType("iso8601") .setDate(2020, 7, 18) .build(); private final Calendar NOV182020 = new Calendar.Builder() .setCalendarType("iso8601") .setDate(2020, 10, 18) .build(); private final Calendar DEC102020 = new Calendar.Builder() .setCalendarType("iso8601") .setDate(2020, 11, 10) .build(); //9 and 14 are the ids local datastore gives to these entities private final TutorSession bernardoSession = new TutorSession("1", "1", null, null, TimeRange.fromStartToEnd(540, 600, MAY182020), 9); private final TutorSession samSession = new TutorSession("2", "2", null, null, TimeRange.fromStartToEnd(540, 600, AUGUST182020), 14); private ArrayList<Tutor> tutors = new ArrayList<Tutor> (Arrays.asList( new Tutor("Kashish Arora", "Kashish\'s bio", "images/pfp.jpg", "[email protected]", new ArrayList<String> (Arrays.asList("math", "history")), new ArrayList<TimeRange> (Arrays.asList(TimeRange.fromStartToEnd(TIME_1200AM, TIME_0100PM, NOV182020), TimeRange.fromStartToEnd(TIME_0300PM,TIME_0500PM, DEC102020))), new ArrayList<TutorSession> (Arrays.asList()), "0"), new Tutor("Bernardo Eilert Trevisan", "Bernardo\'s bio", "images/pfp.jpg", "[email protected]", new ArrayList<String> (Arrays.asList("english", "physics")), new ArrayList<TimeRange> (Arrays.asList(TimeRange.fromStartToEnd(TIME_0800AM, TIME_1000AM, MAY182020), TimeRange.fromStartToEnd(TIME_1100AM,TIME_0100PM, AUGUST102020), TimeRange.fromStartToEnd(TIME_0100PM, TIME_0300PM, AUGUST72020))), new ArrayList<TutorSession> (Arrays.asList(bernardoSession)), "1"), new Tutor("Sam Falberg", "Sam\'s bio", "images/pfp.jpg", "[email protected]", new ArrayList<String> (Arrays.asList("geology", "english")), new ArrayList<TimeRange> (Arrays.asList(TimeRange.fromStartToEnd(TIME_1000AM, TIME_1200AM, MAY182020), TimeRange.fromStartToEnd(TIME_0100PM,TIME_0200PM, AUGUST102020))), new ArrayList<TutorSession> (Arrays.asList(samSession)), "2"), new Tutor("Anand Desai", "Anand\'s bio", "images/pfp.jpg", "[email protected]", new ArrayList<String> (Arrays.asList("finance", "chemistry")), new ArrayList<TimeRange> (Arrays.asList(TimeRange.fromStartToEnd(TIME_1000AM, TIME_1200AM, MAY182020), TimeRange.fromStartToEnd(TIME_0100PM,TIME_0200PM, AUGUST102020))), new ArrayList<TutorSession> (Arrays.asList()), "3"), new Tutor("Elian Dumitru", "Elian\'s bio", "images/pfp.jpg", "[email protected]", new ArrayList<String> (Arrays.asList("geology", "math")), new ArrayList<TimeRange> (Arrays.asList(TimeRange.fromStartToEnd(TIME_1000AM, TIME_1200AM, MAY182020), TimeRange.fromStartToEnd(TIME_0100PM,TIME_0200PM, AUGUST102020))), new ArrayList<TutorSession> (Arrays.asList()), "4") )); private ArrayList<Student> students = new ArrayList<Student> (Arrays.asList( new Student("Kashish Arora", "Kashish\'s bio", "images/pfp.jpg", "[email protected]", new ArrayList<String> (Arrays.asList("English", "Physics")), new ArrayList<String> (Arrays.asList()), new ArrayList<TutorSession> (Arrays.asList()), "0"), new Student("Bernardo Eilert Trevisan", "Bernardo\'s bio", "images/pfp.jpg", "[email protected]", new ArrayList<String> (Arrays.asList("Math", "History")), new ArrayList<String> (Arrays.asList("1")), new ArrayList<TutorSession> (Arrays.asList(bernardoSession)), "1"), new Student("Sam Falberg", "Sam\'s bio", "images/pfp.jpg", "[email protected]", new ArrayList<String> (Arrays.asList("Finance", "Chemistry")), new ArrayList<String> (Arrays.asList("2")), new ArrayList<TutorSession> (Arrays.asList(samSession)), "2"), new Student("Anand Desai", "Anand\'s bio", "images/pfp.jpg", "[email protected]", new ArrayList<String> (Arrays.asList("Geology", "English")), new ArrayList<String> (Arrays.asList("0")), new ArrayList<TutorSession> (Arrays.asList()), "3"), new Student("Elian Dumitru", "Elian\'s bio", "images/pfp.jpg", "[email protected]", new ArrayList<String> (Arrays.asList("Finance", "Chemistry")), new ArrayList<String> (Arrays.asList("0")), new ArrayList<TutorSession> (Arrays.asList()), "4") )); private ArrayList<User> users = new ArrayList<User> (Arrays.asList( new User("Test Tester", "0"), new User("Tester Test", "1") )); /** * Finds and returns a tutor that has the given email. If no such tutor is found, returns null. * @return Tutor */ public Tutor getTutorByEmail(String email) { for(Tutor tutor : tutors) { if(tutor.getEmail().toLowerCase().equals(email.toLowerCase())) { return tutor; } } return null; } /** * Finds and returns a student that has the given email. If no such student is found, returns null. * @return Student */ public Student getStudentByEmail(String email) { for(Student student : students) { if(student.getEmail().toLowerCase().equals(email.toLowerCase())) { return student; } } return null; } /** * Adds all the sample Tutor objects to datastore. */ public void addTutorsToDatastore() { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); for(Tutor tutor : tutors) { Entity entity = new Entity("Tutor"); entity.setProperty("name", tutor.getName()); entity.setProperty("bio", tutor.getBio()); entity.setProperty("pfp", tutor.getPfp()); entity.setProperty("email", tutor.getEmail()); entity.setProperty("topics", tutor.getSkills()); entity.setProperty("ratingSum", 0); entity.setProperty("ratingCount", 0); entity.setProperty("rating", 0); entity.setProperty("userId", tutor.getUserId()); datastore.put(entity); addTutorAvailabilityToDatastore(datastore, tutor.getAvailability(), tutor.getUserId()); addTutorSessionsToDatastore(datastore, tutor.getScheduledSessions()); } } /** * Adds all the sample Student objects to datastore. */ public void addStudentsToDatastore() { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); for(Student student : students) { Entity entity = new Entity("Student"); entity.setProperty("name", student.getName()); entity.setProperty("bio", student.getBio()); entity.setProperty("pfp", student.getPfp()); entity.setProperty("email", student.getEmail()); entity.setProperty("learning", student.getLearning()); entity.setProperty("tutors", student.getTutors()); entity.setProperty("userId", student.getUserId()); datastore.put(entity); } } /** * Adds all sample User objects to datastore. */ public void addUsersToDatastore() { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); for (User user : users) { Entity entity = new Entity("User"); entity.setProperty("userId", user.getUserId()); String fullName = user.getName(); entity.setProperty("fullName", fullName.toLowerCase()); String[] nameSplit = fullName.split(" ", 2); entity.setProperty("firstName", nameSplit[0].toLowerCase()); entity.setProperty("lastName", nameSplit[1].toLowerCase()); datastore.put(entity); } } /** * Rates a sample tutor with the given rating. */ public void rateTutor(String userId, int rating) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); //get tutor with user id Filter filter = new FilterPredicate("userId", FilterOperator.EQUAL, userId); Query query = new Query("Tutor").setFilter(filter); PreparedQuery pq = datastore.prepare(query); Entity tutorEntity = pq.asSingleEntity(); int ratingSum = Math.toIntExact((long) tutorEntity.getProperty("ratingSum")) + rating; int ratingCount = Math.toIntExact((long) tutorEntity.getProperty("ratingCount")) + 1; tutorEntity.setProperty("ratingSum", ratingSum); tutorEntity.setProperty("ratingCount", ratingCount); tutorEntity.setProperty("rating", Math.round(ratingSum/ratingCount)); datastore.put(tutorEntity); Tutor tutor = getTutorByEmail((String) tutorEntity.getProperty("email")); tutor.addRating(rating); } private void addTutorAvailabilityToDatastore(DatastoreService datastore, ArrayList<TimeRange> times, String userId) { for(TimeRange time : times) { addTimeRangeToDatastore(datastore, time, userId); } } private void addTutorSessionsToDatastore(DatastoreService datastore, ArrayList<TutorSession> sessions) { for(TutorSession session : sessions) { Entity sessionEntity = new Entity("TutorSession"); sessionEntity.setProperty("tutorID", session.getTutorID()); sessionEntity.setProperty("studentID", session.getStudentID()); sessionEntity.setProperty("subtopics", session.getSubtopics()); sessionEntity.setProperty("questions", session.getQuestions()); sessionEntity.setProperty("rated", session.isRated()); sessionEntity.setProperty("rating", session.getRating()); sessionEntity.setProperty("timeslot", addTimeRangeToDatastore(datastore, session.getTimeslot(), String.valueOf(session.getId()))); datastore.put(sessionEntity); } } private long addTimeRangeToDatastore(DatastoreService datastore, TimeRange time, String id) { Entity timeEntity = new Entity("TimeRange"); timeEntity.setProperty("tutorID", id); timeEntity.setProperty("start", time.getStart()); timeEntity.setProperty("end", time.getEnd()); timeEntity.setProperty("date", new Gson().toJson(time.getDate())); datastore.put(timeEntity); return (long) timeEntity.getKey().getId(); } }
{ "content_hash": "9cb387957b8c57ae51000c4b779b5c1b", "timestamp": "", "source": "github", "line_count": 271, "max_line_length": 167, "avg_line_length": 51.464944649446494, "alnum_prop": 0.6161898616189861, "repo_name": "googleinterns/step132-2020", "id": "735e5d22e9365bace0d5688ae7354089d4424528", "size": "13947", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/google/sps/data/SampleData.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "12189" }, { "name": "HTML", "bytes": "113318" }, { "name": "Java", "bytes": "412817" }, { "name": "JavaScript", "bytes": "506731" } ], "symlink_target": "" }
#import <UIKit/UIKit.h> #define WBImage UIImage #else #import <AppKit/AppKit.h> #define WBImage NSImage #endif @interface TestEntity : NSObject <NSCopying> @property (nonatomic, copy) NSString *tile; @end @interface TestClassEntity : TestEntity @property (nonatomic, copy) NSString *testClassName; @end @interface TestCaseEntity : TestEntity @property (nonatomic, strong) TestClassEntity *classEntity; @property (nonatomic, copy) NSString *tmxFile; @property (nonatomic, strong) WBImage *thumbnailImage; @end
{ "content_hash": "41d03d2a5d822eff9188510a2c32962f", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 59, "avg_line_length": 19.107142857142858, "alnum_prop": 0.7495327102803738, "repo_name": "wbcyclist/SKTiledMap", "id": "57878b1110e7eab99b0ab669d7ad98ff52e5a18a", "size": "726", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Classes/Model/TestEntity.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "238469" }, { "name": "Python", "bytes": "3464" }, { "name": "Ruby", "bytes": "1836" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace Machete.Tests.CodeGeneratorTests { [TestFixture] public class If : CodeGeneratorTestFixture { [Test] public void No_Block() { string template = "@if (shouldGreet) {}"; this.AssertGeneratedMethodBody( template, "if (shouldGreet) {", "}" ); } [Test] public void Single_Literal_Block() { string template = "@if (shouldGreet) { Hello! }"; this.AssertGeneratedMethodBody( template, "if (shouldGreet) {", "WriteLiteral(@\" Hello! \");", "}" ); } [Test] public void Single_Expression_Block() { string template = "@if (shouldGreet) { @person.Name }"; this.AssertGeneratedMethodBody( template, "if (shouldGreet) {", "WriteLiteral(@\" \");", "Write(person.Name);", "WriteLiteral(@\" \");", "}" ); } [Test] public void Block_With_Multiple_Lines() { string template = "@if (shouldGreet) {" + _ + "Hello!" + _ + "}"; this.AssertGeneratedMethodBody( template, "if (shouldGreet) {", "WriteLiteral(@\"Hello!", "\");", "}" ); } } }
{ "content_hash": "cc809c41de8521bdc95ffd46ea9126af", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 68, "avg_line_length": 22.64179104477612, "alnum_prop": 0.47857613711272246, "repo_name": "smack0007/Machete", "id": "99d9536735642fbbcce38b8925e54d0d05709f9e", "size": "1519", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Source/Machete.Tests/CodeGeneratorTests/If.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "37706" } ], "symlink_target": "" }
using System; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; namespace NewsSystem.Data.Repositories { public class GenericRepository<T> : IRepository<T> where T : class { public GenericRepository(INewsSystemDbContext context) { if (context == null) { throw new ArgumentException("An instance of DbContext is required to use this repository.", "context"); } this.Context = context; this.DbSet = this.Context.Set<T>(); } protected IDbSet<T> DbSet { get; set; } protected INewsSystemDbContext Context { get; set; } public virtual IQueryable<T> All() { return this.DbSet.AsQueryable(); } public virtual T GetById(int id) { return this.DbSet.Find(id); } public virtual void Add(T entity) { DbEntityEntry entry = this.Context.Entry(entity); if (entry.State != EntityState.Detached) { entry.State = EntityState.Added; } else { this.DbSet.Add(entity); } } public virtual void Update(T entity) { DbEntityEntry entry = this.Context.Entry(entity); if (entry.State == EntityState.Detached) { this.DbSet.Attach(entity); } entry.State = EntityState.Modified; } public virtual void Delete(T entity) { DbEntityEntry entry = this.Context.Entry(entity); if (entry.State != EntityState.Deleted) { entry.State = EntityState.Deleted; } else { this.DbSet.Attach(entity); this.DbSet.Remove(entity); } } public virtual void Delete(int id) { var entity = this.GetById(id); if (entity != null) { this.Delete(entity); } } public virtual void Detach(T entity) { DbEntityEntry entry = this.Context.Entry(entity); entry.State = EntityState.Detached; } public int SaveChanges() { return this.Context.SaveChanges(); } public void Dispose() { this.Context.Dispose(); } public T GetByName(string name) { return this.DbSet.Find(name); } } }
{ "content_hash": "086c4ace3cf1fc6d2afecc39d33f32eb", "timestamp": "", "source": "github", "line_count": 105, "max_line_length": 119, "avg_line_length": 24.79047619047619, "alnum_prop": 0.5013446023818671, "repo_name": "dushka-dragoeva/TelerikSeson2016", "id": "485acca4a0fa8b71019dff5fb2cd74fd5a2e748e", "size": "2605", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Software Technologies/WebForms/NewsSystem.Web/NewsSystem.Data/Repositories/GenericRepository.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "203163" }, { "name": "C#", "bytes": "3221179" }, { "name": "CSS", "bytes": "92722" }, { "name": "CoffeeScript", "bytes": "3700" }, { "name": "HTML", "bytes": "514257" }, { "name": "JavaScript", "bytes": "2273440" }, { "name": "PHP", "bytes": "5957" }, { "name": "SQLPL", "bytes": "22723" }, { "name": "XSLT", "bytes": "3857" } ], "symlink_target": "" }
/* * This file is generated by jOOQ. */ package com.rpkit.store.bukkit.database.jooq.tables; import com.rpkit.store.bukkit.database.jooq.Keys; import com.rpkit.store.bukkit.database.jooq.RpkitStores; import com.rpkit.store.bukkit.database.jooq.tables.records.RpkitPermanentPurchaseRecord; import org.jooq.Field; import org.jooq.ForeignKey; import org.jooq.Identity; import org.jooq.Name; import org.jooq.Record; import org.jooq.Row2; import org.jooq.Schema; import org.jooq.Table; import org.jooq.TableField; import org.jooq.TableOptions; import org.jooq.UniqueKey; import org.jooq.impl.DSL; import org.jooq.impl.SQLDataType; import org.jooq.impl.TableImpl; /** * This class is generated by jOOQ. */ @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class RpkitPermanentPurchase extends TableImpl<RpkitPermanentPurchaseRecord> { private static final long serialVersionUID = 1L; /** * The reference instance of * <code>rpkit_stores.rpkit_permanent_purchase</code> */ public static final RpkitPermanentPurchase RPKIT_PERMANENT_PURCHASE = new RpkitPermanentPurchase(); /** * The class holding records for this type */ @Override public Class<RpkitPermanentPurchaseRecord> getRecordType() { return RpkitPermanentPurchaseRecord.class; } /** * The column <code>rpkit_stores.rpkit_permanent_purchase.id</code>. */ public final TableField<RpkitPermanentPurchaseRecord, Integer> ID = createField(DSL.name("id"), SQLDataType.INTEGER.nullable(false).identity(true), this, ""); /** * The column * <code>rpkit_stores.rpkit_permanent_purchase.purchase_id</code>. */ public final TableField<RpkitPermanentPurchaseRecord, Integer> PURCHASE_ID = createField(DSL.name("purchase_id"), SQLDataType.INTEGER.nullable(false), this, ""); private RpkitPermanentPurchase(Name alias, Table<RpkitPermanentPurchaseRecord> aliased) { this(alias, aliased, null); } private RpkitPermanentPurchase(Name alias, Table<RpkitPermanentPurchaseRecord> aliased, Field<?>[] parameters) { super(alias, null, aliased, parameters, DSL.comment(""), TableOptions.table()); } /** * Create an aliased <code>rpkit_stores.rpkit_permanent_purchase</code> * table reference */ public RpkitPermanentPurchase(String alias) { this(DSL.name(alias), RPKIT_PERMANENT_PURCHASE); } /** * Create an aliased <code>rpkit_stores.rpkit_permanent_purchase</code> * table reference */ public RpkitPermanentPurchase(Name alias) { this(alias, RPKIT_PERMANENT_PURCHASE); } /** * Create a <code>rpkit_stores.rpkit_permanent_purchase</code> table * reference */ public RpkitPermanentPurchase() { this(DSL.name("rpkit_permanent_purchase"), null); } public <O extends Record> RpkitPermanentPurchase(Table<O> child, ForeignKey<O, RpkitPermanentPurchaseRecord> key) { super(child, key, RPKIT_PERMANENT_PURCHASE); } @Override public Schema getSchema() { return aliased() ? null : RpkitStores.RPKIT_STORES; } @Override public Identity<RpkitPermanentPurchaseRecord, Integer> getIdentity() { return (Identity<RpkitPermanentPurchaseRecord, Integer>) super.getIdentity(); } @Override public UniqueKey<RpkitPermanentPurchaseRecord> getPrimaryKey() { return Keys.KEY_RPKIT_PERMANENT_PURCHASE_PRIMARY; } @Override public RpkitPermanentPurchase as(String alias) { return new RpkitPermanentPurchase(DSL.name(alias), this); } @Override public RpkitPermanentPurchase as(Name alias) { return new RpkitPermanentPurchase(alias, this); } /** * Rename this table */ @Override public RpkitPermanentPurchase rename(String name) { return new RpkitPermanentPurchase(DSL.name(name), null); } /** * Rename this table */ @Override public RpkitPermanentPurchase rename(Name name) { return new RpkitPermanentPurchase(name, null); } // ------------------------------------------------------------------------- // Row2 type methods // ------------------------------------------------------------------------- @Override public Row2<Integer, Integer> fieldsRow() { return (Row2) super.fieldsRow(); } }
{ "content_hash": "a2914b40c5683065925baba2783cd6ef", "timestamp": "", "source": "github", "line_count": 145, "max_line_length": 165, "avg_line_length": 30.26896551724138, "alnum_prop": 0.6689450899977216, "repo_name": "RP-Kit/RPKit", "id": "c813fe1e906bc8aab5e9876806bb4058206b646b", "size": "4389", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "bukkit/rpk-stores-bukkit/src/main/java/com/rpkit/store/bukkit/database/jooq/tables/RpkitPermanentPurchase.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "80874" }, { "name": "Kotlin", "bytes": "3599677" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in Trudy gos. nikit. bot. Sada 32: 135 (1960) #### Original name Gloeosporium metasequoiae Gucevic ### Remarks null
{ "content_hash": "5b4fbc7ff424076486e8d8a69eaae9c1", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 42, "avg_line_length": 13.538461538461538, "alnum_prop": 0.7159090909090909, "repo_name": "mdoering/backbone", "id": "c6ec0892d5f964ccb41dc326334ccad77824f051", "size": "233", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Leotiomycetes/Helotiales/Dermateaceae/Marssonina/Gloeosporium metasequoiae/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
/** * package-info class. * * @since 5.0.0 */ @javax.xml.bind.annotation.XmlSchema(namespace = "http://wso2.org/carbon/xmlns/v5.0.0", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) package org.wso2.carbon.deployment.engine.config;
{ "content_hash": "33bc4c36957401bddfe9c84d3567eacb", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 87, "avg_line_length": 29.444444444444443, "alnum_prop": 0.7169811320754716, "repo_name": "Shakila/carbon-deployment", "id": "1269a83cbfa38e9fc6959781936ae0980de84a09", "size": "911", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "components/org.wso2.carbon.deployment.engine/src/main/java/org/wso2/carbon/deployment/engine/config/package-info.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "232233" } ], "symlink_target": "" }
// // // // $Id$ // #include <string.h> #include <limits.h> #include <ctype.h> // #include <ctable.h> /* This helper function checks, whether the last "portion" bytes * of "needle" (which is "nlen" bytes long) exist within the "needle" * at offset "offset" (counted from the end of the string), * and whether the character preceding "offset" is not a match. * Notice that the range being checked may reach beyond the * beginning of the string. Such range is ignored. */ static int boyermoore_needlematch (const unsigned char* needle, int nlen, int portion, int offset) { int virtual_begin = nlen-offset-portion; int ignore = 0; if(virtual_begin < 0) { ignore = -virtual_begin; virtual_begin = 0; } if(virtual_begin > 0 && needle[virtual_begin-1] == needle[nlen-portion-1]) return 0; return memcmp(needle + nlen - portion + ignore, needle + virtual_begin, portion - ignore) == 0; } static int bm_max(int a, int b) { return a > b ? a : b; } static void boyer_moore_setup (struct ctableSearchMatchStruct *bm, const unsigned char *needle, size_t nlen, int nocase) { unsigned a; bm->skip = (int *)ckalloc ((nlen + 1) * sizeof (int)); bm->needle = (unsigned char *)ckalloc (nlen * sizeof (unsigned char)); bm->nlen = nlen; // initialize the occ table to a default value for (a = 0; a < UCHAR_MAX + 1; ++a) { bm->occ[a] = -1; } // squirrel off a copy of the needle; map to lowercase if case-insensitive. // simultaneously populate occ with the analysis of the needle, ignoring // the last character for (a = 0; a < nlen; ++a) { unsigned char c = needle[a]; if (nocase) { c = tolower(c); } bm->needle[a] = c; if (a < nlen - 1) { bm->occ[c] = a; } } // preprocess step 2, init skip[] for (a = 0; a < nlen; ++a) { unsigned value = 0; while (value < nlen && !boyermoore_needlematch (bm->needle, nlen, a, value)) { ++value; } bm->skip[nlen - a - 1] = value; } } CTABLE_INTERNAL void boyer_moore_teardown (struct ctableSearchMatchStruct *bm) { ckfree ((char *)bm->skip); ckfree ((char *)bm->needle); } CTABLE_INTERNAL const unsigned char * boyer_moore_search (struct ctableSearchMatchStruct *bm, const unsigned char *haystack, size_t hlen, int nocase) { unsigned hpos; if ((size_t)bm->nlen > hlen) return NULL; //fprintf(stderr, "bm needle '%s' %d haystack '%s' %d\n", bm->needle, bm->nlen, haystack, (int) hlen); for (hpos = 0; hpos <= hlen - bm->nlen; ) { int npos = bm->nlen - 1; unsigned char c; while ((!nocase && (bm->needle[npos] == haystack[npos + hpos])) || (nocase && (bm->needle[npos] == tolower(haystack[npos + hpos])))) { if (npos == 0) { //fprintf(stderr, "matched at %s (+%d)\n", haystack + hpos, (int) hpos); return haystack + hpos; } --npos; } c = !nocase ? haystack[npos + hpos] : tolower(haystack[npos + hpos]); hpos += bm_max(bm->skip[npos], npos - bm->occ[c]); } //fprintf(stderr, "no match\n"); return NULL; } #if 0 /* Returns a pointer to the first occurrence of "needle" * within "haystack", or NULL if not found. */ CTABLE_INTERNAL const unsigned char* memmem_boyermoore (const unsigned char* haystack, int hlen, const unsigned char* needle, int nlen) { int skip[nlen]; /* Array of shifts with self-substring match check */ int occ[UCHAR_MAX+1]; /* Array of last occurrence of each character */ int a, hpos; if(nlen > hlen || nlen <= 0 || !haystack || !needle) return NULL; /* Preprocess #1: init occ[]*/ /* Initialize the table to default value */ for(a=0; a<UCHAR_MAX+1; ++a) occ[a] = -1; /* Then populate it with the analysis of the needle */ /* But ignoring the last letter */ for(a=0; a<nlen-1; ++a) occ[needle[a]] = a; /* Preprocess #2: init skip[] */ /* Note: This step could be made a lot faster. * A simple implementation is shown here. */ for(a=0; a<nlen; ++a) { int value = 0; while(value < nlen && !boyermoore_needlematch(needle, nlen, a, value)) ++value; skip[nlen-a-1] = value; } /* Search: */ for(hpos=0; hpos <= hlen-nlen; ) { int npos=nlen-1; while(needle[npos] == haystack[npos+hpos]) { if(npos == 0) return haystack + hpos; --npos; } hpos += max(skip[npos], npos - occ[haystack[npos+hpos]]); } return NULL; } #endif // vim: set ts=8 sw=4 sts=4 noet :
{ "content_hash": "fdd1eb67fde7b46f2b4450e38922b4a7", "timestamp": "", "source": "github", "line_count": 161, "max_line_length": 142, "avg_line_length": 28.658385093167702, "alnum_prop": 0.5869094061551798, "repo_name": "flightaware/speedtables", "id": "841c19ba893564081264f35d20deef247c912680", "size": "4614", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ctables/boyer_moore.c", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "222925" }, { "name": "C++", "bytes": "8190" }, { "name": "CSS", "bytes": "5099" }, { "name": "HTML", "bytes": "283577" }, { "name": "M4", "bytes": "186034" }, { "name": "Makefile", "bytes": "59706" }, { "name": "Roff", "bytes": "39034" }, { "name": "Shell", "bytes": "43005" }, { "name": "Tcl", "bytes": "548693" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.IO; using Custom_Scenery.Decorators; using MiniJSON; using UnityEngine; namespace Custom_Scenery { internal class SceneryLoader : MonoBehaviour { private List<BuildableObject> _sceneryObjects = new List<BuildableObject>(); public string Path; public string Identifier; public void LoadScenery() { try { var dict = Json.Deserialize(File.ReadAllText(Path + @"/scenery.json")) as Dictionary<string, object>; GameObject hider = new GameObject(); char dsc = System.IO.Path.DirectorySeparatorChar; using (WWW www = new WWW("file://" + Path + dsc + "assetbundle" + dsc + "scenery")) { if (www.error != null) throw new Exception("Loading had an error:" + www.error); AssetBundle bundle = www.assetBundle; foreach (KeyValuePair<string, object> pair in dict) { try { var options = pair.Value as Dictionary<string, object>; GameObject asset = (new TypeDecorator((string)options["type"])).Decorate(options, bundle); (new PriceDecorator((double)options["price"])).Decorate(asset, options, bundle); (new NameDecorator(pair.Key)).Decorate(asset, options, bundle); if (options.ContainsKey("grid")) (new GridDecorator((bool)options["grid"])).Decorate(asset, options, bundle); if (options.ContainsKey("recolorable")) (new RecolorableDecorator((bool)options["recolorable"])).Decorate(asset, options, bundle); DontDestroyOnLoad(asset); BuildableObject buildableObject = asset.GetComponent<BuildableObject>(); buildableObject.dontSerialize = true; buildableObject.isPreview = true; AssetManager.Instance.registerObject(buildableObject); _sceneryObjects.Add(asset.GetComponent<BuildableObject>()); // hide it from view asset.transform.parent = hider.transform; } catch (Exception e) { Debug.Log(e); LogException(e); } } bundle.Unload(false); } hider.SetActive(false); } catch(Exception e) { LogException(e); } } private void LogException(Exception e) { StreamWriter sw = File.AppendText(Path + @"/mod.log"); sw.WriteLine(e); sw.Flush(); sw.Close(); } public void UnloadScenery() { foreach (BuildableObject deco in _sceneryObjects) { AssetManager.Instance.unregisterObject(deco); } } } }
{ "content_hash": "d4ef680215a3929570a89fd6e7af5264", "timestamp": "", "source": "github", "line_count": 101, "max_line_length": 122, "avg_line_length": 34.08910891089109, "alnum_prop": 0.46993900668022076, "repo_name": "JoecakeGameDev/FireMod", "id": "f4e929e2d5d6fa486e995166acde39d699368942", "size": "3445", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "CustomScenery/SceneryLoader.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "18566" } ], "symlink_target": "" }
module Game.LambdaHack.Core.Random ( -- * The @Rng@ monad Rnd -- * Random operations , randomR, randomR0, nextRandom, randomWord32 , oneOf, shuffle, invalidInformationCode, shuffleExcept, frequency -- * Fractional chance , Chance, chance -- * Casting dice scaled with level , castDice, oddsDice, castDiceXY -- * Specialized monadic folds , foldrM, foldlM' #ifdef EXPOSE_INTERNAL -- * Internal operations , rollFreq #endif ) where import Prelude () import Game.LambdaHack.Core.Prelude import qualified Control.Monad.Trans.State.Strict as St import Data.Int (Int32) import Data.Ratio import qualified Data.Vector.Unboxed as U import Data.Word (Word16, Word32) import qualified System.Random.SplitMix32 as SM import qualified Game.LambdaHack.Core.Dice as Dice import Game.LambdaHack.Core.Frequency -- | The monad of computations with random generator state. type Rnd a = St.State SM.SMGen a -- | Get a random object within a (inclusive) range with a uniform distribution. randomR :: (Integral a) => (a, a) -> Rnd a {-# INLINE randomR #-} randomR (0, h) = randomR0 h randomR (l, h) | l > h = error "randomR: empty range" randomR (l, h) = St.state $ \g -> let (x, g') = nextRandom (h - l) g in (x + l, g') -- | Generate random 'Integral' in @[0, x]@ range. randomR0 :: (Integral a) => a -> Rnd a {-# INLINE randomR0 #-} randomR0 h = St.state $ nextRandom h -- | Generate a random integral value in @[0, x]@ range, where @x@ is within -- @Int32@. -- -- The limitation to @Int32@ values is needed to keep it working on signed -- types. In package @random@, a much more complex scheme is used -- to keep it working for arbitrary fixed number of bits. nextRandom :: forall a. (Integral a) => a -> SM.SMGen -> (a, SM.SMGen) {-# INLINE nextRandom #-} nextRandom 0 g = (0, g) nextRandom h g = assert (h > 0 && toInteger h <= (toInteger :: Int32 -> Integer) maxBound) $ let (w32, g') = SM.bitmaskWithRejection32' ((fromIntegralWrap :: a -> Word32) h) g -- `fromIntegralWrap` is fine here, because wrapping is OK. x = (fromIntegralWrap :: Word32 -> a) w32 in if x > h then error $ "nextRandom internal error" `showFailure` (toInteger x, toInteger h, w32) else (x, g') -- | Get a random 'Word32' using full range. randomWord32 :: Rnd Word32 {-# INLINE randomWord32 #-} randomWord32 = St.state SM.nextWord32 -- | Get any element of a list with equal probability. oneOf :: [a] -> Rnd a oneOf [] = error $ "oneOf []" `showFailure` () oneOf [x] = return x oneOf xs = do r <- randomR0 (length xs - 1) return $! xs !! r -- | Generates a random permutation. Naive, but good enough for small inputs. shuffle :: Eq a => [a] -> Rnd [a] shuffle [] = return [] shuffle l = do x <- oneOf l (x :) <$> shuffle (delete x l) -- | Code that means the information (e.g., flavour or hidden kind index) -- should be regenerated, because it could not be transferred from -- previous playthrough (it's random in each playthrough or there was -- no previous playthrough). invalidInformationCode :: Word16 invalidInformationCode = maxBound -- | Generates a random permutation, except for the existing mapping. shuffleExcept :: U.Vector Word16 -> Int -> [Word16] -> Rnd [Word16] shuffleExcept v len l0 = assert (len == length l0) $ shuffleE 0 (l0 \\ filter (/= invalidInformationCode) (U.toList v)) where shuffleE :: Int -> [Word16] -> Rnd [Word16] shuffleE i _ | i == len = return [] shuffleE i l = do let a0 = v U.! i if a0 == invalidInformationCode then do a <- oneOf l (a :) <$> shuffleE (succ i) (delete a l) else (a0 :) <$> shuffleE (succ i) l -- | Gen an element according to a frequency distribution. frequency :: Show a => Frequency a -> Rnd a {-# INLINE frequency #-} frequency = St.state . rollFreq -- | Randomly choose an item according to the distribution. rollFreq :: Show a => Frequency a -> SM.SMGen -> (a, SM.SMGen) rollFreq fr g = case runFrequency fr of [] -> error $ "choice from an empty frequency" `showFailure` nameFrequency fr [(n, x)] | n <= 0 -> error $ "singleton void frequency" `showFailure` (nameFrequency fr, n, x) [(_, x)] -> (x, g) -- speedup fs -> let sumf = foldl' (\ !acc (!n, _) -> acc + n) 0 fs (r, ng) = nextRandom (pred sumf) g frec :: Int -> [(Int, a)] -> a frec !m [] = error $ "impossible roll" `showFailure` (nameFrequency fr, fs, m) frec m ((n, x) : _) | m < n = x frec m ((n, _) : xs) = frec (m - n) xs in assert (sumf > 0 `blame` "frequency with nothing to pick" `swith` (nameFrequency fr, fs)) (frec r fs, ng) -- | Fractional chance. type Chance = Rational -- | Give @True@, with probability determined by the fraction. chance :: Chance -> Rnd Bool chance r = do let n = numerator r d = denominator r k <- randomR (1, d) return (k <= n) -- | Cast dice scaled with current level depth. castDice :: Dice.AbsDepth -> Dice.AbsDepth -> Dice.Dice -> Rnd Int castDice = Dice.castDice randomR -- | Cast dice scaled with current level depth and return @True@ -- if the results is greater than 50. oddsDice :: Dice.AbsDepth -> Dice.AbsDepth -> Dice.Dice -> Rnd Bool oddsDice ldepth totalDepth dice = do c <- castDice ldepth totalDepth dice return $! c > 50 -- | Cast dice, scaled with current level depth, for coordinates. castDiceXY :: Dice.AbsDepth -> Dice.AbsDepth -> Dice.DiceXY -> Rnd (Int, Int) castDiceXY ldepth totalDepth (Dice.DiceXY dx dy) = do x <- castDice ldepth totalDepth dx y <- castDice ldepth totalDepth dy return (x, y) foldrM :: Foldable t => (a -> b -> Rnd b) -> b -> t a -> Rnd b foldrM f z0 xs = let f' x (z, g) = St.runState (f x z) g in St.state $ \g -> foldr f' (z0, g) xs foldlM' :: Foldable t => (b -> a -> Rnd b) -> b -> t a -> Rnd b foldlM' f z0 xs = let f' (z, g) x = St.runState (f z x) g in St.state $ \g -> foldl' f' (z0, g) xs
{ "content_hash": "3339615dc332231b147654f52827f52d", "timestamp": "", "source": "github", "line_count": 171, "max_line_length": 80, "avg_line_length": 36.05263157894737, "alnum_prop": 0.6194647201946472, "repo_name": "LambdaHack/LambdaHack", "id": "803932d49b8c16d1edf142ebfe31777e90429e8a", "size": "6227", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "definition-src/Game/LambdaHack/Core/Random.hs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Haskell", "bytes": "2489776" }, { "name": "JavaScript", "bytes": "145" }, { "name": "Makefile", "bytes": "27824" }, { "name": "NSIS", "bytes": "4410" } ], "symlink_target": "" }
package edu.northwestern.bioinformatics.ctmssuite.authorization.ruby; import edu.northwestern.bioinformatics.ctmssuite.authorization.ruby.internal.RubySuiteAuthorizationSourceFactory; import edu.northwestern.bioinformatics.studycalendar.tools.MapBasedDictionary; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.ServiceRegistration; import org.osgi.service.cm.ManagedServiceFactory; import java.util.Collections; public class Activator implements BundleActivator { private ServiceRegistration factoryRegistration; @Override public void start(BundleContext context) throws Exception { RubySuiteAuthorizationSourceFactory factory = new RubySuiteAuthorizationSourceFactory(context.getBundle()); factoryRegistration = context.registerService(ManagedServiceFactory.class.getName(), factory, new MapBasedDictionary<String, String>(Collections.singletonMap( Constants.SERVICE_PID, RubySuiteAuthorizationSourceFactory.FACTORY_PID))); } @Override public void stop(BundleContext context) throws Exception { factoryRegistration.unregister(); } }
{ "content_hash": "3a72fbcb56d2762fd518cb812ab3337d", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 113, "avg_line_length": 41.5, "alnum_prop": 0.7871485943775101, "repo_name": "NUBIC/suite_authorization_source.rb", "id": "2aa508f63819074a66a225ac6cb13dda63cd56f5", "size": "1245", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "source/src/main/java/edu/northwestern/bioinformatics/ctmssuite/authorization/ruby/Activator.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "36591" }, { "name": "Ruby", "bytes": "10051" } ], "symlink_target": "" }
require 'react/ext/string' module React class Element include Native alias_native :element_type, :type alias_native :props, :props attr_reader :type attr_reader :properties attr_reader :block attr_accessor :waiting_on_resources def initialize(native_element, type, properties, block) @type = type @properties = (`typeof #{properties} === 'undefined'` ? nil : properties) || {} @block = block @native = native_element end def on(event_name) name = event_name.to_s.event_camelize props = if React::Event::BUILT_IN_EVENTS.include?("on#{name}") {"on#{name}" => %x{ function(event){ #{yield React::Event.new(`event`)} } }} else {"_on#{name}" => %x{ function(){ #{yield *Array(`arguments`)} } }} end @native = `React.cloneElement(#{self.to_n}, #{props.to_n})` @properties.merge! props self end def render(props = {}) # for rendering children if props.empty? React::RenderingContext.render(self) else React::RenderingContext.render( Element.new( `React.cloneElement(#{self.to_n}, #{API.convert_props(props)})`, type, properties.merge(props), block ) ) end end def method_missing(class_name, args = {}, &new_block) class_name = class_name.split("__").collect { |s| s.gsub("_", "-") }.join("_") new_props = properties.dup new_props["class"] = "#{new_props['class']} #{class_name} #{args.delete("class")} #{args.delete('className')}".split(" ").uniq.join(" ") new_props.merge! args React::RenderingContext.replace( self, React::RenderingContext.build { React::RenderingContext.render(type, new_props, &new_block) } ) end def as_node React::RenderingContext.as_node(self) end def delete React::RenderingContext.delete(self) end end end
{ "content_hash": "a4cab115699cfcb5cf3308652f4f750a", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 142, "avg_line_length": 26.649350649350648, "alnum_prop": 0.5579922027290448, "repo_name": "zetachang/react.rb", "id": "86998c5652a02aa69e33b82e161a7fd87e091c10", "size": "2052", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/react/element.rb", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "751" }, { "name": "Ruby", "bytes": "147696" } ], "symlink_target": "" }
using Landis.Core; using Landis.SpatialModeling; using Landis.Utilities; using Landis.Library.BiomassCohorts; using System; using System.Collections.Generic; namespace Landis.Extension.Succession.Biomass { /// <summary> /// A helper class. /// </summary> public class HarvestReductions { private string prescription; private double coarseLitterReduction; private double fineLitterReduction; //private double somReduction; private double cohortWoodReduction; private double cohortLeafReduction; public string Name { get { return prescription; } set { if (value != null) prescription = value; } } public double CoarseLitterReduction { get { return coarseLitterReduction; } set { if (value < 0.0 || value > 1.0) throw new InputValueException(value.ToString(), "Coarse litter reduction due to fire must be between 0 and 1.0"); coarseLitterReduction = value; } } public double FineLitterReduction { get { return fineLitterReduction; } set { if (value < 0.0 || value > 1.0) throw new InputValueException(value.ToString(), "Fine litter reduction due to fire must be between 0 and 1.0"); fineLitterReduction = value; } } public double CohortWoodReduction { get { return cohortWoodReduction; } set { if (value < 0.0 || value > 1.0) throw new InputValueException(value.ToString(), "Cohort wood reduction due to fire must be between 0 and 1.0"); cohortWoodReduction = value; } } public double CohortLeafReduction { get { return cohortLeafReduction; } set { if (value < 0.0 || value > 1.0) throw new InputValueException(value.ToString(), "Cohort wood reduction due to fire must be between 0 and 1.0"); cohortLeafReduction = value; } } //public double SOMReduction //{ // get // { // return somReduction; // } // set // { // if (value < 0.0 || value > 1.0) // throw new InputValueException(value.ToString(), "Soil Organic Matter (SOM) reduction due to fire must be between 0 and 1.0"); // somReduction = value; // } //} //--------------------------------------------------------------------- public HarvestReductions() { this.prescription = ""; this.CoarseLitterReduction = 0.0; this.FineLitterReduction = 0.0; this.CohortLeafReduction = 0.0; this.CohortWoodReduction = 0.0; //this.SOMReduction = 0.0; } } public class HarvestEffects { public static double GetCohortWoodRemoval(ActiveSite site) { double woodRemoval = 1.0; // Default is 100% removal if (SiteVars.HarvestPrescriptionName == null) return woodRemoval; foreach (HarvestReductions prescription in PlugIn.Parameters.HarvestReductionsTable) { //PlugIn.ModelCore.UI.WriteLine(" PrescriptionName={0}, Site={1}.", prescription.PrescriptionName, site); if (ComparePrescriptionNames(prescription.Name, site)) //SiteVars.HarvestPrescriptionName[site].Trim() == prescription.Name.Trim()) { woodRemoval = prescription.CohortWoodReduction; } } return woodRemoval; } public static double GetCohortLeafRemoval(ActiveSite site) { double leafRemoval = 0.0; // Default is 0% removal if (SiteVars.HarvestPrescriptionName == null) return leafRemoval; foreach (HarvestReductions prescription in PlugIn.Parameters.HarvestReductionsTable) { if (ComparePrescriptionNames(prescription.Name, site)) //SiteVars.HarvestPrescriptionName[site].Trim() == prescription.Name.Trim()) { leafRemoval = prescription.CohortLeafReduction; } } return leafRemoval; } //--------------------------------------------------------------------- /// <summary> /// Computes fire effects on litter, coarse woody debris, duff layer. /// </summary> public static void ReduceLayers(Site site) { //PlugIn.ModelCore.UI.WriteLine(" Calculating harvest induced layer reductions..."); double litterLossMultiplier = 0.0; double woodLossMultiplier = 0.0; //double som_Multiplier = 0.0; string harvestPrescriptionName = SiteVars.HarvestPrescriptionName[site]; bool found = false; foreach (HarvestReductions prescriptionTableEntry in PlugIn.Parameters.HarvestReductionsTable) { if (SiteVars.HarvestPrescriptionName != null && ComparePrescriptionNames(prescriptionTableEntry.Name, site)) //prescriptionName.Trim() == prescriptionTableEntry.Name.Trim()) { litterLossMultiplier = prescriptionTableEntry.FineLitterReduction; woodLossMultiplier = prescriptionTableEntry.CoarseLitterReduction; //som_Multiplier = prescription.SOMReduction; found = true; } } if (!found) { PlugIn.ModelCore.UI.WriteLine(" WARNING: Prescription {0} not found in the Biomass Succession Harvest Effects Table", harvestPrescriptionName); return; } //PlugIn.ModelCore.UI.WriteLine(" LitterLoss={0:0.00}, woodLoss={1:0.00}, SOM_loss={2:0.00}, SITE={3}", litterLossMultiplier, woodLossMultiplier, som_Multiplier, site); // litter first SiteVars.Litter[site].ReduceMass(litterLossMultiplier); // Surface dead wood SiteVars.WoodyDebris[site].ReduceMass(woodLossMultiplier); } public static bool ComparePrescriptionNames(string prescriptionTableName, Site site) { string harvestPrescriptionName = SiteVars.HarvestPrescriptionName[site].Trim(); string tablePrescriptionName = prescriptionTableName.Trim(); if (harvestPrescriptionName == tablePrescriptionName) return true; else if (tablePrescriptionName.EndsWith("*")) { if (harvestPrescriptionName.Contains(tablePrescriptionName.TrimEnd())) return true; else return false; } else return false; } } }
{ "content_hash": "684fc60376454c325df46704ce5a6e8e", "timestamp": "", "source": "github", "line_count": 227, "max_line_length": 182, "avg_line_length": 32.881057268722465, "alnum_prop": 0.5266613076098606, "repo_name": "LANDIS-II-Foundation/Extension-Biomass-Succession", "id": "f10998b7451efcc0d7748b9b2286d324278c609d", "size": "7509", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/HarvestEffects.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "637" }, { "name": "C#", "bytes": "156798" }, { "name": "Inno Setup", "bytes": "8337" }, { "name": "PowerShell", "bytes": "1214" }, { "name": "Rich Text Format", "bytes": "44654" } ], "symlink_target": "" }
import fetch from '@/utils/fetch' export function addPerson(query) { // 添加区域人员 return fetch({ url: 'personfacilities/addPerson', method: 'post', data: query }) } export function GetPersonForId(query) { // 获取区域人员管理信息集合 return fetch({ url: 'personfacilities/GetPersonForId', method: 'post', data: query }) } export function addUpdatePersonInfo(query) { // 添加修改人员信息记录 return fetch({ url: 'personfacilities/addUpdatePersonInfo', method: 'post', data: query }) } export function GetpersonlogsList(query) { // 获取一条人员记录 return fetch({ url: 'personfacilities/GetpersonlogsList', method: 'post', data: query }) } export function updatePerson(query) { // 修改人员信息 return fetch({ url: 'personfacilities/updatePerson', method: 'post', data: query }) } /** * 下面是区域设施的请求接口地址 */ export function addFacilities(query) { // 添加区域设施信息 return fetch({ url: 'personfacilities/addFacilities', method: 'post', data: query }) } export function updateFacilities(query) { // 修改区域设施信息 return fetch({ url: 'personfacilities/updateFacilities', method: 'post', data: query }) } export function GetFacilitiesForId(query) { // 获取所有区域设施的信息 return fetch({ url: 'personfacilities/GetFacilitiesForId', method: 'post', data: query }) } export function addUpdateFacilitiesInfo(query) { // 添加修改区域设施的信息记录 return fetch({ url: 'personfacilities/addUpdateFacilitiesInfo', method: 'post', data: query }) } export function GetfacilitieslogsList(query) { // 获取一条区域设施的所有更新记录 return fetch({ url: 'personfacilities/GetfacilitieslogsList', method: 'post', data: query }) }
{ "content_hash": "90f74d40fbe8cdcca60f420128cf64af", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 65, "avg_line_length": 22.426666666666666, "alnum_prop": 0.6777645659928656, "repo_name": "Ardno/proadmin", "id": "5bdb4711eb2ca04e3e3153be3cd688d45d5461c5", "size": "1904", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/api/areaperson.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "61594" }, { "name": "HTML", "bytes": "3306" }, { "name": "JavaScript", "bytes": "1272931" }, { "name": "Vue", "bytes": "708787" } ], "symlink_target": "" }
import java.text.ParseException; import java.util.ArrayList; import java.util.List; import java.util.Random; import de.linearbits.objectselector.Selector; import de.linearbits.objectselector.SelectorBuilder; import de.linearbits.objectselector.util.IntArrayAccessor; /** * Example with accessor for arrays of primitives * * @author Fabian Prasser */ public class Example4 { /** * Main entry * @param args * @throws ParseException */ public static void main(String[] args) throws ParseException { // Create a set of 1000 elements Random random = new Random(); List<int[]> entries = new ArrayList<int[]>(); for (int i=0; i<1000; i++){ entries.add(Element.getRandomIntArray(random)); } // Create header IntArrayAccessor accessor = new IntArrayAccessor(new String[]{"field1", "field2", "field3"}); // Create a selector with the builder pattern Selector<int[]> selector = new SelectorBuilder<int[]>(accessor).field("field1").leq(20) .and() .field("field2").leq(20) .and() .field("field3").leq(20) .build(); // Print selector System.out.println(selector.toString()); // Print, which elements are selected for (int i=0; i<1000; i++) { if (selector.isSelected(entries.get(i))) { System.out.println("Is selected: "+i); } } // Create a selector by parsing a query string selector = new SelectorBuilder<int[]>(accessor, "'field1'<='20' and 'field2'<='20' and 'field3'<='20'") .build(); // Print selector System.out.println(selector.toString()); // Print, which elements are selected for (int i=0; i<1000; i++) { if (selector.isSelected(entries.get(i))) { System.out.println("Is selected: "+i); } } } }
{ "content_hash": "3e3fdac4de65df54c7b0398f89110e6b", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 101, "avg_line_length": 30.202898550724637, "alnum_prop": 0.550383877159309, "repo_name": "prasser/object-selector", "id": "cb167ee2590dc922954bca0f03fa6f82bbdb68ff", "size": "2760", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/examples/Example4.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "132106" } ], "symlink_target": "" }
package io.github.data4all.model.drawing; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.util.List; import org.junit.Before; import org.junit.Test; /** * Test cases for the DrawingMotion class * * @author tbrose */ public class DrawingMotionTest { /** * The instance for testing */ private DrawingMotion drawingMotion; @Test public void addPoint_addingPoints_sizeIncreasesCorrect() { for (int i = 1; i < 20; i++) { drawingMotion.addPoint(0, 0); assertThat(drawingMotion.getPathSize(), is(i)); } } /** * Adds points to the DrawingMotion:<br/> * Point_0 has coordinates (0,1)<br/> * Point_1 has coordinates (2,3)<br/> * And so on ... * * @param count * the amount of points to be added */ private void addPoints(int count) { for (int i = 0; i < count; i++) { drawingMotion.addPoint(2 * i, 2 * i + 1); } } // Tests for addPoint @Test public void average_manyEntries_exactAverage() { addPoints(10); Point average = drawingMotion.average(); assertThat(average.getX(), is(9f)); // 0,2,4,6,8,10,12,14,16,18 assertThat(average.getY(), is(10f)); // 1,3,5,7,9,11,13,15,17,19 } // Tests for isPath @Test public void average_noEntries_Null() { assertThat(drawingMotion.average(), is((Point) null)); } @Test public void average_oneEntrie_averageIsFirstPoint() { addPoints(1); assertThat(drawingMotion.average(), equalTo(drawingMotion.getStart())); } @Test public void average_twoEntries_exactAverage() { addPoints(2); Point average = drawingMotion.average(); assertThat(average.getX(), is(1f)); // 0,2 assertThat(average.getY(), is(2f)); // 1,3 } // Tests for isPoint @Test public void getEnd_noEntries_resultIsNull() { assertThat(drawingMotion.getEnd(), is((Point) null)); } @Test public void getEnd_someEntries_resultIsCorrect() { addPoints(10); drawingMotion.addPoint(-1, -1); assertThat(drawingMotion.getEnd().equalsTo(-1, -1), is(true)); } @Test public void getPathSize_noEntries_sizeIsZero() { assertThat(drawingMotion.getPathSize(), is(0)); } // Tests for getStart @Test public void getPathSize_someEntries_sizeIsCorrect() { addPoints(10); assertThat(drawingMotion.getPathSize(), is(10)); // Add some more points ... just to be on the safe side ... addPoints(10); assertThat(drawingMotion.getPathSize(), is(20)); } @Test(expected = IndexOutOfBoundsException.class) public void getPoint_noEntries_indexOutOfBoundsException() { drawingMotion.getPoint(0); } // Tests for getEnd @Test public void getPoint_someEntries_rightPointsAndOrder() { addPoints(10); for (int i = 0; i < 10; i++) { Point point = drawingMotion.getPoint(i); assertThat(point.getX(), is(2f * i)); assertThat(point.getY(), is(2f * i + 1)); } } @Test(expected = IndexOutOfBoundsException.class) public void getPoint_someEntriesIndexNegative_indexOutOfBoundsException() { addPoints(10); drawingMotion.getPoint(-1); } @Test(expected = IndexOutOfBoundsException.class) public void getPoint_someEntriesIndexToHigh_indexOutOfBoundsException() { addPoints(10); drawingMotion.getPoint(10); } // Tests for getPathSize @Test public void getPoints_noEntries_resultIsEmpty() { assertThat(drawingMotion.getPoints().isEmpty(), is(true)); } @Test public void getPoints_someEntries_rightPointsAndOrder() { addPoints(10); List<Point> points = drawingMotion.getPoints(); for (int i = 0; i < 10; i++) { Point point = points.get(i); assertThat(point.getX(), is(2f * i)); assertThat(point.getY(), is(2f * i + 1)); } } // Tests for getPoints @Test public void getStart_noEntries_resultIsNull() { assertThat(drawingMotion.getStart(), is((Point) null)); } @Test public void getStart_someEntries_resultIsCorrect() { drawingMotion.addPoint(-1, -1); addPoints(10); assertThat(drawingMotion.getStart().equalsTo(-1, -1), is(true)); } // Tests for getPoint @Test public void getStartGetEnd_oneEntries_samePoint() { drawingMotion.addPoint(-1, -1); assertThat(drawingMotion.getStart(), equalTo(drawingMotion.getEnd())); } @Test public void isPath_edgeEntries_resultIsFalse() { drawingMotion.addPoint(0, 0); drawingMotion.addPoint(DrawingMotion.POINT_TOLERANCE, 0); drawingMotion.addPoint(-DrawingMotion.POINT_TOLERANCE, 0); drawingMotion.addPoint(0, DrawingMotion.POINT_TOLERANCE); drawingMotion.addPoint(0, -DrawingMotion.POINT_TOLERANCE); assertThat(drawingMotion.isPath(), is(false)); } @Test public void isPath_noEntries_resultIsFalse() { assertThat(drawingMotion.isPath(), is(false)); } @Test public void isPath_overEdgeEntries_resultIsTrue() { drawingMotion.addPoint(0, 0); drawingMotion.addPoint(Math.nextUp(DrawingMotion.POINT_TOLERANCE), 0); drawingMotion.addPoint(-Math.nextUp(DrawingMotion.POINT_TOLERANCE), 0); drawingMotion.addPoint(0, Math.nextUp(DrawingMotion.POINT_TOLERANCE)); drawingMotion.addPoint(0, -Math.nextUp(DrawingMotion.POINT_TOLERANCE)); assertThat(drawingMotion.isPath(), is(true)); } // Tests for average() @Test public void isPoint_edgeEntries_resultIsTrue() { drawingMotion.addPoint(0, 0); drawingMotion.addPoint(DrawingMotion.POINT_TOLERANCE, 0); drawingMotion.addPoint(-DrawingMotion.POINT_TOLERANCE, 0); drawingMotion.addPoint(0, DrawingMotion.POINT_TOLERANCE); drawingMotion.addPoint(0, -DrawingMotion.POINT_TOLERANCE); assertThat(drawingMotion.isPoint(), is(true)); } @Test public void isPoint_noEntries_resultIsFalse() { assertThat(drawingMotion.isPoint(), is(false)); } @Test public void isPoint_overEdgeEntries_resultIsFalse() { drawingMotion.addPoint(0, 0); drawingMotion.addPoint(Math.nextUp(DrawingMotion.POINT_TOLERANCE), 0); drawingMotion.addPoint(-Math.nextUp(DrawingMotion.POINT_TOLERANCE), 0); drawingMotion.addPoint(0, Math.nextUp(DrawingMotion.POINT_TOLERANCE)); drawingMotion.addPoint(0, -Math.nextUp(DrawingMotion.POINT_TOLERANCE)); assertThat(drawingMotion.isPoint(), is(false)); } @Before public void setup() { drawingMotion = new DrawingMotion(); } }
{ "content_hash": "09f35df40b0201a2aa31cc2f415a8f91", "timestamp": "", "source": "github", "line_count": 239, "max_line_length": 79, "avg_line_length": 29.200836820083683, "alnum_prop": 0.6336151311076086, "repo_name": "Data4All/Data4All", "id": "2db14ead554f35147b941989b82d14f3cac69b37", "size": "7593", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/test/java/io/github/data4all/model/drawing/DrawingMotionTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "987726" } ], "symlink_target": "" }
import django_admin_blocks from linkcheck.views import get_status_message """Legacy internal helper""" def notification(): return get_status_message() django_admin_blocks.register({ 'errors': (notification,), })
{ "content_hash": "f856ba1cf70948710fa90a0af1e5adbe", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 46, "avg_line_length": 16.142857142857142, "alnum_prop": 0.7212389380530974, "repo_name": "claudep/django-linkcheck", "id": "e800fb31bbb144caf4c3e4aaacc2709d606dcf06", "size": "226", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "linkcheck/admin_blocks.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "11357" }, { "name": "Python", "bytes": "81297" } ], "symlink_target": "" }
<?php namespace Composer\Package\Archiver; use Symfony\Component\Finder; /** * @author Nils Adermann <[email protected]> */ abstract class BaseExcludeFilter { /** * @var string */ protected $sourcePath; /** * @var array */ protected $excludePatterns; /** * @param string $sourcePath Directory containing sources to be filtered */ public function __construct($sourcePath) { $this->sourcePath = $sourcePath; $this->excludePatterns = array(); } /** * Checks the given path against all exclude patterns in this filter * * Negated patterns overwrite exclude decisions of previous filters. * * @param string $relativePath The file's path relative to the sourcePath * @param bool $exclude Whether a previous filter wants to exclude this file * * @return bool Whether the file should be excluded */ public function filter($relativePath, $exclude) { foreach ($this->excludePatterns as $patternData) { list($pattern, $negate, $stripLeadingSlash) = $patternData; if ($stripLeadingSlash) { $path = substr($relativePath, 1); } else { $path = $relativePath; } if (@preg_match($pattern, $path)) { $exclude = !$negate; } } return $exclude; } /** * Processes a file containing exclude rules of different formats per line * * @param array $lines A set of lines to be parsed * @param callable $lineParser The parser to be used on each line * * @return array Exclude patterns to be used in filter() */ protected function parseLines(array $lines, $lineParser) { return array_filter( array_map( function ($line) use ($lineParser) { $line = trim($line); if (!$line || 0 === strpos($line, '#')) { return null; } return call_user_func($lineParser, $line); }, $lines ), function ($pattern) { return $pattern !== null; } ); } /** * Generates a set of exclude patterns for filter() from gitignore rules * * @param array $rules A list of exclude rules in gitignore syntax * * @return array Exclude patterns */ protected function generatePatterns($rules) { $patterns = array(); foreach ($rules as $rule) { $patterns[] = $this->generatePattern($rule); } return $patterns; } /** * Generates an exclude pattern for filter() from a gitignore rule * * @param string $rule An exclude rule in gitignore syntax * * @return array An exclude pattern */ protected function generatePattern($rule) { $negate = false; $pattern = '{'; if (strlen($rule) && $rule[0] === '!') { $negate = true; $rule = substr($rule, 1); } if (strlen($rule) && $rule[0] === '/') { $pattern .= '^/'; $rule = substr($rule, 1); } elseif (strlen($rule) - 1 === strpos($rule, '/')) { $pattern .= '/'; $rule = substr($rule, 0, -1); } elseif (false === strpos($rule, '/')) { $pattern .= '/'; } // remove delimiters as well as caret (^) and dollar sign ($) from the regex $pattern .= substr(Finder\Glob::toRegex($rule), 2, -2) . '(?=$|/)'; return array($pattern . '}', $negate, false); } }
{ "content_hash": "f4b3c7281404f21553a4d89a4af77b14", "timestamp": "", "source": "github", "line_count": 140, "max_line_length": 87, "avg_line_length": 26.65714285714286, "alnum_prop": 0.5163451232583065, "repo_name": "floverdevel/composer", "id": "8e69ed069c147fbb34357ef2bee2307eda40354c", "size": "3992", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Composer/Package/Archiver/BaseExcludeFilter.php", "mode": "33188", "license": "mit", "language": [ { "name": "Hack", "bytes": "154" }, { "name": "PHP", "bytes": "5565339" } ], "symlink_target": "" }
#include "../hb-set.hh" #include "../hb-priority-queue.hh" #include "../hb-serialize.hh" #ifndef GRAPH_GRAPH_HH #define GRAPH_GRAPH_HH namespace graph { /** * Represents a serialized table in the form of a graph. * Provides methods for modifying and reordering the graph. */ struct graph_t { struct vertex_t { hb_serialize_context_t::object_t obj; int64_t distance = 0 ; int64_t space = 0 ; hb_vector_t<unsigned> parents; unsigned start = 0; unsigned end = 0; unsigned priority = 0; friend void swap (vertex_t& a, vertex_t& b) { hb_swap (a.obj, b.obj); hb_swap (a.distance, b.distance); hb_swap (a.space, b.space); hb_swap (a.parents, b.parents); hb_swap (a.start, b.start); hb_swap (a.end, b.end); hb_swap (a.priority, b.priority); } bool is_shared () const { return parents.length > 1; } unsigned incoming_edges () const { return parents.length; } void remove_parent (unsigned parent_index) { for (unsigned i = 0; i < parents.length; i++) { if (parents[i] != parent_index) continue; parents.remove (i); break; } } void remove_real_link (unsigned child_index, const void* offset) { for (unsigned i = 0; i < obj.real_links.length; i++) { auto& link = obj.real_links[i]; if (link.objidx != child_index) continue; if ((obj.head + link.position) != offset) continue; obj.real_links.remove (i); return; } } void remap_parents (const hb_vector_t<unsigned>& id_map) { for (unsigned i = 0; i < parents.length; i++) parents[i] = id_map[parents[i]]; } void remap_parent (unsigned old_index, unsigned new_index) { for (unsigned i = 0; i < parents.length; i++) { if (parents[i] == old_index) parents[i] = new_index; } } bool is_leaf () const { return !obj.real_links.length && !obj.virtual_links.length; } bool raise_priority () { if (has_max_priority ()) return false; priority++; return true; } bool has_max_priority () const { return priority >= 3; } size_t table_size () const { return obj.tail - obj.head; } int64_t modified_distance (unsigned order) const { // TODO(garretrieger): once priority is high enough, should try // setting distance = 0 which will force to sort immediately after // it's parent where possible. int64_t modified_distance = hb_min (hb_max(distance + distance_modifier (), 0), 0x7FFFFFFFFFF); if (has_max_priority ()) { modified_distance = 0; } return (modified_distance << 18) | (0x003FFFF & order); } int64_t distance_modifier () const { if (!priority) return 0; int64_t table_size = obj.tail - obj.head; if (priority == 1) return -table_size / 2; return -table_size; } }; /* * A topological sorting of an object graph. Ordered * in reverse serialization order (first object in the * serialization is at the end of the list). This matches * the 'packed' object stack used internally in the * serializer */ template<typename T> graph_t (const T& objects) : parents_invalid (true), distance_invalid (true), positions_invalid (true), successful (true) { num_roots_for_space_.push (1); bool removed_nil = false; vertices_.alloc (objects.length); vertices_scratch_.alloc (objects.length); for (unsigned i = 0; i < objects.length; i++) { // TODO(grieger): check all links point to valid objects. // If this graph came from a serialization buffer object 0 is the // nil object. We don't need it for our purposes here so drop it. if (i == 0 && !objects[i]) { removed_nil = true; continue; } vertex_t* v = vertices_.push (); if (check_success (!vertices_.in_error ())) v->obj = *objects[i]; if (!removed_nil) continue; // Fix indices to account for removed nil object. for (auto& l : v->obj.all_links_writer ()) { l.objidx--; } } } ~graph_t () { vertices_.fini (); } bool in_error () const { return !successful || vertices_.in_error () || num_roots_for_space_.in_error (); } const vertex_t& root () const { return vertices_[root_idx ()]; } unsigned root_idx () const { // Object graphs are in reverse order, the first object is at the end // of the vector. Since the graph is topologically sorted it's safe to // assume the first object has no incoming edges. return vertices_.length - 1; } const hb_serialize_context_t::object_t& object (unsigned i) const { return vertices_[i].obj; } /* * Generates a new topological sorting of graph ordered by the shortest * distance to each node if positions are marked as invalid. */ void sort_shortest_distance_if_needed () { if (!positions_invalid) return; sort_shortest_distance (); } /* * Generates a new topological sorting of graph ordered by the shortest * distance to each node. */ void sort_shortest_distance () { positions_invalid = true; if (vertices_.length <= 1) { // Graph of 1 or less doesn't need sorting. return; } update_distances (); hb_priority_queue_t queue; hb_vector_t<vertex_t> &sorted_graph = vertices_scratch_; if (unlikely (!check_success (sorted_graph.resize (vertices_.length)))) return; hb_vector_t<unsigned> id_map; if (unlikely (!check_success (id_map.resize (vertices_.length)))) return; hb_vector_t<unsigned> removed_edges; if (unlikely (!check_success (removed_edges.resize (vertices_.length)))) return; update_parents (); queue.insert (root ().modified_distance (0), root_idx ()); int new_id = root_idx (); unsigned order = 1; while (!queue.in_error () && !queue.is_empty ()) { unsigned next_id = queue.pop_minimum().second; hb_swap (sorted_graph[new_id], vertices_[next_id]); const vertex_t& next = sorted_graph[new_id]; id_map[next_id] = new_id--; for (const auto& link : next.obj.all_links ()) { removed_edges[link.objidx]++; if (!(vertices_[link.objidx].incoming_edges () - removed_edges[link.objidx])) // Add the order that the links were encountered to the priority. // This ensures that ties between priorities objects are broken in a consistent // way. More specifically this is set up so that if a set of objects have the same // distance they'll be added to the topological order in the order that they are // referenced from the parent object. queue.insert (vertices_[link.objidx].modified_distance (order++), link.objidx); } } check_success (!queue.in_error ()); check_success (!sorted_graph.in_error ()); remap_all_obj_indices (id_map, &sorted_graph); hb_swap (vertices_, sorted_graph); if (!check_success (new_id == -1)) print_orphaned_nodes (); } /* * Finds the set of nodes (placed into roots) that should be assigned unique spaces. * More specifically this looks for the top most 24 bit or 32 bit links in the graph. * Some special casing is done that is specific to the layout of GSUB/GPOS tables. */ void find_space_roots (hb_set_t& visited, hb_set_t& roots) { int root_index = (int) root_idx (); for (int i = root_index; i >= 0; i--) { if (visited.has (i)) continue; // Only real links can form 32 bit spaces for (auto& l : vertices_[i].obj.real_links) { if (l.is_signed || l.width < 3) continue; if (i == root_index && l.width == 3) // Ignore 24bit links from the root node, this skips past the single 24bit // pointer to the lookup list. continue; if (l.width == 3) { // A 24bit offset forms a root, unless there is 32bit offsets somewhere // in it's subgraph, then those become the roots instead. This is to make sure // that extension subtables beneath a 24bit lookup become the spaces instead // of the offset to the lookup. hb_set_t sub_roots; find_32bit_roots (l.objidx, sub_roots); if (sub_roots) { for (unsigned sub_root_idx : sub_roots) { roots.add (sub_root_idx); find_subgraph (sub_root_idx, visited); } continue; } } roots.add (l.objidx); find_subgraph (l.objidx, visited); } } } unsigned index_for_offset(unsigned node_idx, const void* offset) const { const auto& node = object (node_idx); if (offset < node.head || offset >= node.tail) return -1; for (const auto& link : node.real_links) { if (offset != node.head + link.position) continue; return link.objidx; } return -1; } /* * Assign unique space numbers to each connected subgraph of 24 bit and/or 32 bit offset(s). * Currently, this is implemented specifically tailored to the structure of a GPOS/GSUB * (including with 24bit offsets) table. */ bool assign_spaces () { update_parents (); hb_set_t visited; hb_set_t roots; find_space_roots (visited, roots); // Mark everything not in the subgraphs of the roots as visited. This prevents // subgraphs from being connected via nodes not in those subgraphs. visited.invert (); if (!roots) return false; while (roots) { unsigned next = HB_SET_VALUE_INVALID; if (unlikely (!check_success (!roots.in_error ()))) break; if (!roots.next (&next)) break; hb_set_t connected_roots; find_connected_nodes (next, roots, visited, connected_roots); if (unlikely (!check_success (!connected_roots.in_error ()))) break; isolate_subgraph (connected_roots); if (unlikely (!check_success (!connected_roots.in_error ()))) break; unsigned next_space = this->next_space (); num_roots_for_space_.push (0); for (unsigned root : connected_roots) { DEBUG_MSG (SUBSET_REPACK, nullptr, "Subgraph %u gets space %u", root, next_space); vertices_[root].space = next_space; num_roots_for_space_[next_space] = num_roots_for_space_[next_space] + 1; distance_invalid = true; positions_invalid = true; } // TODO(grieger): special case for GSUB/GPOS use extension promotions to move 16 bit space // into the 32 bit space as needed, instead of using isolation. } return true; } /* * Isolates the subgraph of nodes reachable from root. Any links to nodes in the subgraph * that originate from outside of the subgraph will be removed by duplicating the linked to * object. * * Indices stored in roots will be updated if any of the roots are duplicated to new indices. */ bool isolate_subgraph (hb_set_t& roots) { update_parents (); hb_map_t subgraph; // incoming edges to root_idx should be all 32 bit in length so we don't need to de-dup these // set the subgraph incoming edge count to match all of root_idx's incoming edges hb_set_t parents; for (unsigned root_idx : roots) { subgraph.set (root_idx, wide_parents (root_idx, parents)); find_subgraph (root_idx, subgraph); } unsigned original_root_idx = root_idx (); hb_map_t index_map; bool made_changes = false; for (auto entry : subgraph.iter ()) { const auto& node = vertices_[entry.first]; unsigned subgraph_incoming_edges = entry.second; if (subgraph_incoming_edges < node.incoming_edges ()) { // Only de-dup objects with incoming links from outside the subgraph. made_changes = true; duplicate_subgraph (entry.first, index_map); } } if (!made_changes) return false; if (original_root_idx != root_idx () && parents.has (original_root_idx)) { // If the root idx has changed since parents was determined, update root idx in parents parents.add (root_idx ()); parents.del (original_root_idx); } auto new_subgraph = + subgraph.keys () | hb_map([&] (unsigned node_idx) { const unsigned *v; if (index_map.has (node_idx, &v)) return *v; return node_idx; }) ; remap_obj_indices (index_map, new_subgraph); remap_obj_indices (index_map, parents.iter (), true); // Update roots set with new indices as needed. unsigned next = HB_SET_VALUE_INVALID; while (roots.next (&next)) { const unsigned *v; if (index_map.has (next, &v)) { roots.del (next); roots.add (*v); } } return true; } void find_subgraph (unsigned node_idx, hb_map_t& subgraph) { for (const auto& link : vertices_[node_idx].obj.all_links ()) { const unsigned *v; if (subgraph.has (link.objidx, &v)) { subgraph.set (link.objidx, *v + 1); continue; } subgraph.set (link.objidx, 1); find_subgraph (link.objidx, subgraph); } } void find_subgraph (unsigned node_idx, hb_set_t& subgraph) { if (subgraph.has (node_idx)) return; subgraph.add (node_idx); for (const auto& link : vertices_[node_idx].obj.all_links ()) find_subgraph (link.objidx, subgraph); } size_t find_subgraph_size (unsigned node_idx, hb_set_t& subgraph, unsigned max_depth = -1) { if (subgraph.has (node_idx)) return 0; subgraph.add (node_idx); const auto& o = vertices_[node_idx].obj; size_t size = o.tail - o.head; if (max_depth == 0) return size; for (const auto& link : o.all_links ()) size += find_subgraph_size (link.objidx, subgraph, max_depth - 1); return size; } /* * Finds the topmost children of 32bit offsets in the subgraph starting * at node_idx. Found indices are placed into 'found'. */ void find_32bit_roots (unsigned node_idx, hb_set_t& found) { for (const auto& link : vertices_[node_idx].obj.all_links ()) { if (!link.is_signed && link.width == 4) { found.add (link.objidx); continue; } find_32bit_roots (link.objidx, found); } } /* * Moves the child of old_parent_idx pointed to by old_offset to a new * vertex at the new_offset. */ template<typename O> void move_child (unsigned old_parent_idx, const O* old_offset, unsigned new_parent_idx, const O* new_offset) { distance_invalid = true; positions_invalid = true; auto& old_v = vertices_[old_parent_idx]; auto& new_v = vertices_[new_parent_idx]; unsigned child_id = index_for_offset (old_parent_idx, old_offset); auto* new_link = new_v.obj.real_links.push (); new_link->width = O::static_size; new_link->objidx = child_id; new_link->position = (const char*) new_offset - (const char*) new_v.obj.head; auto& child = vertices_[child_id]; child.parents.push (new_parent_idx); old_v.remove_real_link (child_id, old_offset); child.remove_parent (old_parent_idx); } /* * duplicates all nodes in the subgraph reachable from node_idx. Does not re-assign * links. index_map is updated with mappings from old id to new id. If a duplication has already * been performed for a given index, then it will be skipped. */ void duplicate_subgraph (unsigned node_idx, hb_map_t& index_map) { if (index_map.has (node_idx)) return; index_map.set (node_idx, duplicate (node_idx)); for (const auto& l : object (node_idx).all_links ()) { duplicate_subgraph (l.objidx, index_map); } } /* * Creates a copy of node_idx and returns it's new index. */ unsigned duplicate (unsigned node_idx) { positions_invalid = true; distance_invalid = true; auto* clone = vertices_.push (); auto& child = vertices_[node_idx]; if (vertices_.in_error ()) { return -1; } clone->obj.head = child.obj.head; clone->obj.tail = child.obj.tail; clone->distance = child.distance; clone->space = child.space; clone->parents.reset (); unsigned clone_idx = vertices_.length - 2; for (const auto& l : child.obj.real_links) { clone->obj.real_links.push (l); vertices_[l.objidx].parents.push (clone_idx); } for (const auto& l : child.obj.virtual_links) { clone->obj.virtual_links.push (l); vertices_[l.objidx].parents.push (clone_idx); } check_success (!clone->obj.real_links.in_error ()); check_success (!clone->obj.virtual_links.in_error ()); // The last object is the root of the graph, so swap back the root to the end. // The root's obj idx does change, however since it's root nothing else refers to it. // all other obj idx's will be unaffected. hb_swap (vertices_[vertices_.length - 2], *clone); // Since the root moved, update the parents arrays of all children on the root. for (const auto& l : root ().obj.all_links ()) vertices_[l.objidx].remap_parent (root_idx () - 1, root_idx ()); return clone_idx; } /* * Creates a copy of child and re-assigns the link from * parent to the clone. The copy is a shallow copy, objects * linked from child are not duplicated. */ bool duplicate (unsigned parent_idx, unsigned child_idx) { update_parents (); unsigned links_to_child = 0; for (const auto& l : vertices_[parent_idx].obj.all_links ()) { if (l.objidx == child_idx) links_to_child++; } if (vertices_[child_idx].incoming_edges () <= links_to_child) { // Can't duplicate this node, doing so would orphan the original one as all remaining links // to child are from parent. DEBUG_MSG (SUBSET_REPACK, nullptr, " Not duplicating %d => %d", parent_idx, child_idx); return false; } DEBUG_MSG (SUBSET_REPACK, nullptr, " Duplicating %d => %d", parent_idx, child_idx); unsigned clone_idx = duplicate (child_idx); if (clone_idx == (unsigned) -1) return false; // duplicate shifts the root node idx, so if parent_idx was root update it. if (parent_idx == clone_idx) parent_idx++; auto& parent = vertices_[parent_idx]; for (auto& l : parent.obj.all_links_writer ()) { if (l.objidx != child_idx) continue; reassign_link (l, parent_idx, clone_idx); } return true; } /* * Adds a new node to the graph, not connected to anything. */ unsigned new_node (char* head, char* tail) { positions_invalid = true; distance_invalid = true; auto* clone = vertices_.push (); if (vertices_.in_error ()) { return -1; } clone->obj.head = head; clone->obj.tail = tail; clone->distance = 0; clone->space = 0; unsigned clone_idx = vertices_.length - 2; // The last object is the root of the graph, so swap back the root to the end. // The root's obj idx does change, however since it's root nothing else refers to it. // all other obj idx's will be unaffected. hb_swap (vertices_[vertices_.length - 2], *clone); // Since the root moved, update the parents arrays of all children on the root. for (const auto& l : root ().obj.all_links ()) vertices_[l.objidx].remap_parent (root_idx () - 1, root_idx ()); return clone_idx; } /* * Raises the sorting priority of all children. */ bool raise_childrens_priority (unsigned parent_idx) { DEBUG_MSG (SUBSET_REPACK, nullptr, " Raising priority of all children of %d", parent_idx); // This operation doesn't change ordering until a sort is run, so no need // to invalidate positions. It does not change graph structure so no need // to update distances or edge counts. auto& parent = vertices_[parent_idx].obj; bool made_change = false; for (auto& l : parent.all_links_writer ()) made_change |= vertices_[l.objidx].raise_priority (); return made_change; } void print_orphaned_nodes () { if (!DEBUG_ENABLED(SUBSET_REPACK)) return; DEBUG_MSG (SUBSET_REPACK, nullptr, "Graph is not fully connected."); parents_invalid = true; update_parents(); for (unsigned i = 0; i < root_idx (); i++) { const auto& v = vertices_[i]; if (!v.parents) DEBUG_MSG (SUBSET_REPACK, nullptr, "Node %u is orphaned.", i); } } unsigned num_roots_for_space (unsigned space) const { return num_roots_for_space_[space]; } unsigned next_space () const { return num_roots_for_space_.length; } void move_to_new_space (const hb_set_t& indices) { num_roots_for_space_.push (0); unsigned new_space = num_roots_for_space_.length - 1; for (unsigned index : indices) { auto& node = vertices_[index]; num_roots_for_space_[node.space] = num_roots_for_space_[node.space] - 1; num_roots_for_space_[new_space] = num_roots_for_space_[new_space] + 1; node.space = new_space; distance_invalid = true; positions_invalid = true; } } unsigned space_for (unsigned index, unsigned* root = nullptr) const { const auto& node = vertices_[index]; if (node.space) { if (root != nullptr) *root = index; return node.space; } if (!node.parents) { if (root) *root = index; return 0; } return space_for (node.parents[0], root); } void err_other_error () { this->successful = false; } size_t total_size_in_bytes () const { size_t total_size = 0; for (unsigned i = 0; i < vertices_.length; i++) { size_t size = vertices_[i].obj.tail - vertices_[i].obj.head; total_size += size; } return total_size; } private: /* * Returns the numbers of incoming edges that are 24 or 32 bits wide. */ unsigned wide_parents (unsigned node_idx, hb_set_t& parents) const { unsigned count = 0; hb_set_t visited; for (unsigned p : vertices_[node_idx].parents) { if (visited.has (p)) continue; visited.add (p); // Only real links can be wide for (const auto& l : vertices_[p].obj.real_links) { if (l.objidx == node_idx && (l.width == 3 || l.width == 4) && !l.is_signed) { count++; parents.add (p); } } } return count; } bool check_success (bool success) { return this->successful && (success || ((void) err_other_error (), false)); } public: /* * Creates a map from objid to # of incoming edges. */ void update_parents () { if (!parents_invalid) return; for (unsigned i = 0; i < vertices_.length; i++) vertices_[i].parents.reset (); for (unsigned p = 0; p < vertices_.length; p++) { for (auto& l : vertices_[p].obj.all_links ()) { vertices_[l.objidx].parents.push (p); } } parents_invalid = false; } /* * compute the serialized start and end positions for each vertex. */ void update_positions () { if (!positions_invalid) return; unsigned current_pos = 0; for (int i = root_idx (); i >= 0; i--) { auto& v = vertices_[i]; v.start = current_pos; current_pos += v.obj.tail - v.obj.head; v.end = current_pos; } positions_invalid = false; } /* * Finds the distance to each object in the graph * from the initial node. */ void update_distances () { if (!distance_invalid) return; // Uses Dijkstra's algorithm to find all of the shortest distances. // https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm // // Implementation Note: // Since our priority queue doesn't support fast priority decreases // we instead just add new entries into the queue when a priority changes. // Redundant ones are filtered out later on by the visited set. // According to https://www3.cs.stonybrook.edu/~rezaul/papers/TR-07-54.pdf // for practical performance this is faster then using a more advanced queue // (such as a fibonacci queue) with a fast decrease priority. for (unsigned i = 0; i < vertices_.length; i++) { if (i == vertices_.length - 1) vertices_[i].distance = 0; else vertices_[i].distance = hb_int_max (int64_t); } hb_priority_queue_t queue; queue.insert (0, vertices_.length - 1); hb_vector_t<bool> visited; visited.resize (vertices_.length); while (!queue.in_error () && !queue.is_empty ()) { unsigned next_idx = queue.pop_minimum ().second; if (visited[next_idx]) continue; const auto& next = vertices_[next_idx]; int64_t next_distance = vertices_[next_idx].distance; visited[next_idx] = true; for (const auto& link : next.obj.all_links ()) { if (visited[link.objidx]) continue; const auto& child = vertices_[link.objidx].obj; unsigned link_width = link.width ? link.width : 4; // treat virtual offsets as 32 bits wide int64_t child_weight = (child.tail - child.head) + ((int64_t) 1 << (link_width * 8)) * (vertices_[link.objidx].space + 1); int64_t child_distance = next_distance + child_weight; if (child_distance < vertices_[link.objidx].distance) { vertices_[link.objidx].distance = child_distance; queue.insert (child_distance, link.objidx); } } } check_success (!queue.in_error ()); if (!check_success (queue.is_empty ())) { print_orphaned_nodes (); return; } distance_invalid = false; } private: /* * Updates a link in the graph to point to a different object. Corrects the * parents vector on the previous and new child nodes. */ void reassign_link (hb_serialize_context_t::object_t::link_t& link, unsigned parent_idx, unsigned new_idx) { unsigned old_idx = link.objidx; link.objidx = new_idx; vertices_[old_idx].remove_parent (parent_idx); vertices_[new_idx].parents.push (parent_idx); } /* * Updates all objidx's in all links using the provided mapping. Corrects incoming edge counts. */ template<typename Iterator, hb_requires (hb_is_iterator (Iterator))> void remap_obj_indices (const hb_map_t& id_map, Iterator subgraph, bool only_wide = false) { if (!id_map) return; for (unsigned i : subgraph) { for (auto& link : vertices_[i].obj.all_links_writer ()) { const unsigned *v; if (!id_map.has (link.objidx, &v)) continue; if (only_wide && !(link.width == 4 && !link.is_signed)) continue; reassign_link (link, i, *v); } } } /* * Updates all objidx's in all links using the provided mapping. */ void remap_all_obj_indices (const hb_vector_t<unsigned>& id_map, hb_vector_t<vertex_t>* sorted_graph) const { for (unsigned i = 0; i < sorted_graph->length; i++) { (*sorted_graph)[i].remap_parents (id_map); for (auto& link : (*sorted_graph)[i].obj.all_links_writer ()) { link.objidx = id_map[link.objidx]; } } } /* * Finds all nodes in targets that are reachable from start_idx, nodes in visited will be skipped. * For this search the graph is treated as being undirected. * * Connected targets will be added to connected and removed from targets. All visited nodes * will be added to visited. */ void find_connected_nodes (unsigned start_idx, hb_set_t& targets, hb_set_t& visited, hb_set_t& connected) { if (unlikely (!check_success (!visited.in_error ()))) return; if (visited.has (start_idx)) return; visited.add (start_idx); if (targets.has (start_idx)) { targets.del (start_idx); connected.add (start_idx); } const auto& v = vertices_[start_idx]; // Graph is treated as undirected so search children and parents of start_idx for (const auto& l : v.obj.all_links ()) find_connected_nodes (l.objidx, targets, visited, connected); for (unsigned p : v.parents) find_connected_nodes (p, targets, visited, connected); } public: // TODO(garretrieger): make private, will need to move most of offset overflow code into graph. hb_vector_t<vertex_t> vertices_; hb_vector_t<vertex_t> vertices_scratch_; private: bool parents_invalid; bool distance_invalid; bool positions_invalid; bool successful; hb_vector_t<unsigned> num_roots_for_space_; }; } #endif // GRAPH_GRAPH_HH
{ "content_hash": "145e6ee227959816376946ef0ed62b3b", "timestamp": "", "source": "github", "line_count": 1022, "max_line_length": 102, "avg_line_length": 28.54794520547945, "alnum_prop": 0.5978201261310666, "repo_name": "akien-mga/godot", "id": "b3aef558a2018be184f6d941e04b2332a8cd028f", "size": "30281", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "thirdparty/harfbuzz/src/graph/graph.hh", "mode": "33188", "license": "mit", "language": [ { "name": "AIDL", "bytes": "1633" }, { "name": "C", "bytes": "1045182" }, { "name": "C#", "bytes": "1578818" }, { "name": "C++", "bytes": "38595824" }, { "name": "CMake", "bytes": "606" }, { "name": "GAP", "bytes": "62" }, { "name": "GDScript", "bytes": "66177" }, { "name": "GLSL", "bytes": "836566" }, { "name": "Java", "bytes": "596743" }, { "name": "JavaScript", "bytes": "188454" }, { "name": "Kotlin", "bytes": "84152" }, { "name": "Makefile", "bytes": "1421" }, { "name": "Objective-C", "bytes": "20550" }, { "name": "Objective-C++", "bytes": "371842" }, { "name": "PowerShell", "bytes": "2713" }, { "name": "Python", "bytes": "464605" }, { "name": "Shell", "bytes": "31057" } ], "symlink_target": "" }
A `MixRecipeManager` is used to modify existing high oven mix recipe, including those added by ModTweaker. ## Importing the package Better be safe than sorry and import the package ```zenscript import mods.tcomplement.highoven.MixRecipeManager; ``` ## Getting a `MixRecipeManager` The `HighOven` handler can give you a `MixRecipeManager`: ```zenscript // HighOven.manageMixRecipe(ILiquidStack output, ILiquidStack input); var manager = HighOven.manageMixRecipe(<liquid:steel>); ``` + `output` is the output of the mix recipe to modify + `input` (Optional) is the input of the mix recipe to modify. If `null` or unspecified, any mix recipe producing the output will be affected ## Removing additives You can use a `MixRecipeManager` to remove certain additives from the affected mix recipe. Be carefull, for removals are always enforced. This means whatever way to add an additive that would add an additive you remove, will be prevented. This may have surprising results with oredict entries. Since oredict entries are added as-is to the mix recipe (it is not expanded to a list of `IItemStack` but looked for when checking the recipes), removing an item will block all oredict entries it belongs to. Generally speaking, if you remove something specific (say, an `IItemStack` with transformers) but an (single) additive addition would allow what you removed plus some other things (say, a more generic `IItemStack`), the whole addition will be cancelled, preventing said other things from being accepted by the High Oven. | Method | Info | | ------ | ---- | | `removeOxidizer(IIngredient oxidizer)` | Forefully remove the oxidizer from the affected MixRecipe | | `removeReducer(IIngredient reducer) ` | Forefully remove the reducer from the affected MixRecipe | | `removePurifier(IIngredient reducer) ` | Forefully remove the purifier from the affected MixRecipe | All those methods return the same instance they were called one, allowing method chaining. ## Adding additives to existing MixRecipe You can add additives to all mix recipe matched by the `MixRecipeManager`. Be careful, as removals have priority (see above). | Method | Info | | ------ | ---- | | `addOxidizer(@NotNull IIngredient oxidizer, int consumeChance)` | Add the oxidizer with the specified consume chance (in percent) | | `addReducer(@NotNull IIngredient reducer, int consumeChance)` | Add the reducer with the specified consume chance (in percent) | | `addPurifier(@NotNull IIngredient purifier, int consumeChance)` | Add the purifier with the specified consume chance (in percent) | All those methods return the same instance they were called one, allowing method chaining. ## Warning Creating a `MixRecipeManager` that does not match any mix recipes will not trigger any warning, because there's no way to tell which mix recipes will be added (script parsing happens before mix recipe registration). If you're `MixRecipeManager` has no effect, first check it it actually matches a mix recipe
{ "content_hash": "957072f24d9ed6424ba8a5e96350852f", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 320, "avg_line_length": 60.89795918367347, "alnum_prop": 0.7771447721179625, "repo_name": "jaredlll08/CraftTweaker-Documentation", "id": "f506f1081b267992b79ff58a24a554ffdbf7c358", "size": "3004", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/Mods/Modtweaker/TComplement/Handlers/MixRecipeManager.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "195475" }, { "name": "HTML", "bytes": "11110" }, { "name": "JavaScript", "bytes": "155278" } ], "symlink_target": "" }
 #pragma once #include <aws/lambda/Lambda_EXPORTS.h> #include <aws/lambda/LambdaRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace Lambda { namespace Model { /** * <p/><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/PublishVersionRequest">AWS * API Reference</a></p> */ class AWS_LAMBDA_API PublishVersionRequest : public LambdaRequest { public: PublishVersionRequest(); Aws::String SerializePayload() const override; /** * <p>The Lambda function name. You can specify a function name (for example, * <code>Thumbnail</code>) or you can specify Amazon Resource Name (ARN) of the * function (for example, * <code>arn:aws:lambda:us-west-2:account-id:function:ThumbNail</code>). AWS Lambda * also allows you to specify a partial ARN (for example, * <code>account-id:Thumbnail</code>). Note that the length constraint applies only * to the ARN. If you specify only the function name, it is limited to 64 * characters in length. </p> */ inline const Aws::String& GetFunctionName() const{ return m_functionName; } /** * <p>The Lambda function name. You can specify a function name (for example, * <code>Thumbnail</code>) or you can specify Amazon Resource Name (ARN) of the * function (for example, * <code>arn:aws:lambda:us-west-2:account-id:function:ThumbNail</code>). AWS Lambda * also allows you to specify a partial ARN (for example, * <code>account-id:Thumbnail</code>). Note that the length constraint applies only * to the ARN. If you specify only the function name, it is limited to 64 * characters in length. </p> */ inline void SetFunctionName(const Aws::String& value) { m_functionNameHasBeenSet = true; m_functionName = value; } /** * <p>The Lambda function name. You can specify a function name (for example, * <code>Thumbnail</code>) or you can specify Amazon Resource Name (ARN) of the * function (for example, * <code>arn:aws:lambda:us-west-2:account-id:function:ThumbNail</code>). AWS Lambda * also allows you to specify a partial ARN (for example, * <code>account-id:Thumbnail</code>). Note that the length constraint applies only * to the ARN. If you specify only the function name, it is limited to 64 * characters in length. </p> */ inline void SetFunctionName(Aws::String&& value) { m_functionNameHasBeenSet = true; m_functionName = std::move(value); } /** * <p>The Lambda function name. You can specify a function name (for example, * <code>Thumbnail</code>) or you can specify Amazon Resource Name (ARN) of the * function (for example, * <code>arn:aws:lambda:us-west-2:account-id:function:ThumbNail</code>). AWS Lambda * also allows you to specify a partial ARN (for example, * <code>account-id:Thumbnail</code>). Note that the length constraint applies only * to the ARN. If you specify only the function name, it is limited to 64 * characters in length. </p> */ inline void SetFunctionName(const char* value) { m_functionNameHasBeenSet = true; m_functionName.assign(value); } /** * <p>The Lambda function name. You can specify a function name (for example, * <code>Thumbnail</code>) or you can specify Amazon Resource Name (ARN) of the * function (for example, * <code>arn:aws:lambda:us-west-2:account-id:function:ThumbNail</code>). AWS Lambda * also allows you to specify a partial ARN (for example, * <code>account-id:Thumbnail</code>). Note that the length constraint applies only * to the ARN. If you specify only the function name, it is limited to 64 * characters in length. </p> */ inline PublishVersionRequest& WithFunctionName(const Aws::String& value) { SetFunctionName(value); return *this;} /** * <p>The Lambda function name. You can specify a function name (for example, * <code>Thumbnail</code>) or you can specify Amazon Resource Name (ARN) of the * function (for example, * <code>arn:aws:lambda:us-west-2:account-id:function:ThumbNail</code>). AWS Lambda * also allows you to specify a partial ARN (for example, * <code>account-id:Thumbnail</code>). Note that the length constraint applies only * to the ARN. If you specify only the function name, it is limited to 64 * characters in length. </p> */ inline PublishVersionRequest& WithFunctionName(Aws::String&& value) { SetFunctionName(std::move(value)); return *this;} /** * <p>The Lambda function name. You can specify a function name (for example, * <code>Thumbnail</code>) or you can specify Amazon Resource Name (ARN) of the * function (for example, * <code>arn:aws:lambda:us-west-2:account-id:function:ThumbNail</code>). AWS Lambda * also allows you to specify a partial ARN (for example, * <code>account-id:Thumbnail</code>). Note that the length constraint applies only * to the ARN. If you specify only the function name, it is limited to 64 * characters in length. </p> */ inline PublishVersionRequest& WithFunctionName(const char* value) { SetFunctionName(value); return *this;} /** * <p>The SHA256 hash of the deployment package you want to publish. This provides * validation on the code you are publishing. If you provide this parameter value * must match the SHA256 of the $LATEST version for the publication to succeed.</p> */ inline const Aws::String& GetCodeSha256() const{ return m_codeSha256; } /** * <p>The SHA256 hash of the deployment package you want to publish. This provides * validation on the code you are publishing. If you provide this parameter value * must match the SHA256 of the $LATEST version for the publication to succeed.</p> */ inline void SetCodeSha256(const Aws::String& value) { m_codeSha256HasBeenSet = true; m_codeSha256 = value; } /** * <p>The SHA256 hash of the deployment package you want to publish. This provides * validation on the code you are publishing. If you provide this parameter value * must match the SHA256 of the $LATEST version for the publication to succeed.</p> */ inline void SetCodeSha256(Aws::String&& value) { m_codeSha256HasBeenSet = true; m_codeSha256 = std::move(value); } /** * <p>The SHA256 hash of the deployment package you want to publish. This provides * validation on the code you are publishing. If you provide this parameter value * must match the SHA256 of the $LATEST version for the publication to succeed.</p> */ inline void SetCodeSha256(const char* value) { m_codeSha256HasBeenSet = true; m_codeSha256.assign(value); } /** * <p>The SHA256 hash of the deployment package you want to publish. This provides * validation on the code you are publishing. If you provide this parameter value * must match the SHA256 of the $LATEST version for the publication to succeed.</p> */ inline PublishVersionRequest& WithCodeSha256(const Aws::String& value) { SetCodeSha256(value); return *this;} /** * <p>The SHA256 hash of the deployment package you want to publish. This provides * validation on the code you are publishing. If you provide this parameter value * must match the SHA256 of the $LATEST version for the publication to succeed.</p> */ inline PublishVersionRequest& WithCodeSha256(Aws::String&& value) { SetCodeSha256(std::move(value)); return *this;} /** * <p>The SHA256 hash of the deployment package you want to publish. This provides * validation on the code you are publishing. If you provide this parameter value * must match the SHA256 of the $LATEST version for the publication to succeed.</p> */ inline PublishVersionRequest& WithCodeSha256(const char* value) { SetCodeSha256(value); return *this;} /** * <p>The description for the version you are publishing. If not provided, AWS * Lambda copies the description from the $LATEST version.</p> */ inline const Aws::String& GetDescription() const{ return m_description; } /** * <p>The description for the version you are publishing. If not provided, AWS * Lambda copies the description from the $LATEST version.</p> */ inline void SetDescription(const Aws::String& value) { m_descriptionHasBeenSet = true; m_description = value; } /** * <p>The description for the version you are publishing. If not provided, AWS * Lambda copies the description from the $LATEST version.</p> */ inline void SetDescription(Aws::String&& value) { m_descriptionHasBeenSet = true; m_description = std::move(value); } /** * <p>The description for the version you are publishing. If not provided, AWS * Lambda copies the description from the $LATEST version.</p> */ inline void SetDescription(const char* value) { m_descriptionHasBeenSet = true; m_description.assign(value); } /** * <p>The description for the version you are publishing. If not provided, AWS * Lambda copies the description from the $LATEST version.</p> */ inline PublishVersionRequest& WithDescription(const Aws::String& value) { SetDescription(value); return *this;} /** * <p>The description for the version you are publishing. If not provided, AWS * Lambda copies the description from the $LATEST version.</p> */ inline PublishVersionRequest& WithDescription(Aws::String&& value) { SetDescription(std::move(value)); return *this;} /** * <p>The description for the version you are publishing. If not provided, AWS * Lambda copies the description from the $LATEST version.</p> */ inline PublishVersionRequest& WithDescription(const char* value) { SetDescription(value); return *this;} private: Aws::String m_functionName; bool m_functionNameHasBeenSet; Aws::String m_codeSha256; bool m_codeSha256HasBeenSet; Aws::String m_description; bool m_descriptionHasBeenSet; }; } // namespace Model } // namespace Lambda } // namespace Aws
{ "content_hash": "b8696593b8f53b06bd1a583728fe14a1", "timestamp": "", "source": "github", "line_count": 213, "max_line_length": 124, "avg_line_length": 47.948356807511736, "alnum_prop": 0.6906883383922452, "repo_name": "chiaming0914/awe-cpp-sdk", "id": "3a971b2e3567a2ab0cb819e53c9f364a62da5e81", "size": "10786", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "aws-cpp-sdk-lambda/include/aws/lambda/model/PublishVersionRequest.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2313" }, { "name": "C++", "bytes": "98158533" }, { "name": "CMake", "bytes": "437471" }, { "name": "HTML", "bytes": "4471" }, { "name": "Java", "bytes": "239297" }, { "name": "Python", "bytes": "72827" }, { "name": "Shell", "bytes": "2803" } ], "symlink_target": "" }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_COINS_H #define BITCOIN_COINS_H #include <compressor.h> #include <core_memusage.h> #include <crypto/siphash.h> #include <memusage.h> #include <primitives/transaction.h> #include <serialize.h> #include <uint256.h> #include <assert.h> #include <stdint.h> #include <functional> #include <unordered_map> /** * A UTXO entry. * * Serialized format: * - VARINT((coinbase ? 1 : 0) | (height << 1)) * - the non-spent CTxOut (via TxOutCompression) */ class Coin { public: //! unspent transaction output CTxOut out; //! whether containing transaction was a coinbase unsigned int fCoinBase : 1; //! at which height this containing transaction was included in the active block chain uint32_t nHeight : 31; //! construct a Coin from a CTxOut and height/coinbase information. Coin(CTxOut&& outIn, int nHeightIn, bool fCoinBaseIn) : out(std::move(outIn)), fCoinBase(fCoinBaseIn), nHeight(nHeightIn) {} Coin(const CTxOut& outIn, int nHeightIn, bool fCoinBaseIn) : out(outIn), fCoinBase(fCoinBaseIn),nHeight(nHeightIn) {} void Clear() { out.SetNull(); fCoinBase = false; nHeight = 0; } //! empty constructor Coin() : fCoinBase(false), nHeight(0) { } bool IsCoinBase() const { return fCoinBase; } template<typename Stream> void Serialize(Stream &s) const { assert(!IsSpent()); uint32_t code = nHeight * uint32_t{2} + fCoinBase; ::Serialize(s, VARINT(code)); ::Serialize(s, Using<TxOutCompression>(out)); } template<typename Stream> void Unserialize(Stream &s) { uint32_t code = 0; ::Unserialize(s, VARINT(code)); nHeight = code >> 1; fCoinBase = code & 1; ::Unserialize(s, Using<TxOutCompression>(out)); } /** Either this coin never existed (see e.g. coinEmpty in coins.cpp), or it * did exist and has been spent. */ bool IsSpent() const { return out.IsNull(); } size_t DynamicMemoryUsage() const { return memusage::DynamicUsage(out.scriptPubKey); } }; class SaltedOutpointHasher { private: /** Salt */ const uint64_t k0, k1; public: SaltedOutpointHasher(); /** * This *must* return size_t. With Boost 1.46 on 32-bit systems the * unordered_map will behave unpredictably if the custom hasher returns a * uint64_t, resulting in failures when syncing the chain (#4634). * * Having the hash noexcept allows libstdc++'s unordered_map to recalculate * the hash during rehash, so it does not have to cache the value. This * reduces node's memory by sizeof(size_t). The required recalculation has * a slight performance penalty (around 1.6%), but this is compensated by * memory savings of about 9% which allow for a larger dbcache setting. * * @see https://gcc.gnu.org/onlinedocs/gcc-9.2.0/libstdc++/manual/manual/unordered_associative.html */ size_t operator()(const COutPoint& id) const noexcept { return SipHashUint256Extra(k0, k1, id.hash, id.n); } }; /** * A Coin in one level of the coins database caching hierarchy. * * A coin can either be: * - unspent or spent (in which case the Coin object will be nulled out - see Coin.Clear()) * - DIRTY or not DIRTY * - FRESH or not FRESH * * Out of these 2^3 = 8 states, only some combinations are valid: * - unspent, FRESH, DIRTY (e.g. a new coin created in the cache) * - unspent, not FRESH, DIRTY (e.g. a coin changed in the cache during a reorg) * - unspent, not FRESH, not DIRTY (e.g. an unspent coin fetched from the parent cache) * - spent, FRESH, not DIRTY (e.g. a spent coin fetched from the parent cache) * - spent, not FRESH, DIRTY (e.g. a coin is spent and spentness needs to be flushed to the parent) */ struct CCoinsCacheEntry { Coin coin; // The actual cached data. unsigned char flags; enum Flags { /** * DIRTY means the CCoinsCacheEntry is potentially different from the * version in the parent cache. Failure to mark a coin as DIRTY when * it is potentially different from the parent cache will cause a * consensus failure, since the coin's state won't get written to the * parent when the cache is flushed. */ DIRTY = (1 << 0), /** * FRESH means the parent cache does not have this coin or that it is a * spent coin in the parent cache. If a FRESH coin in the cache is * later spent, it can be deleted entirely and doesn't ever need to be * flushed to the parent. This is a performance optimization. Marking a * coin as FRESH when it exists unspent in the parent cache will cause a * consensus failure, since it might not be deleted from the parent * when this cache is flushed. */ FRESH = (1 << 1), }; CCoinsCacheEntry() : flags(0) {} explicit CCoinsCacheEntry(Coin&& coin_) : coin(std::move(coin_)), flags(0) {} }; typedef std::unordered_map<COutPoint, CCoinsCacheEntry, SaltedOutpointHasher> CCoinsMap; /** Cursor for iterating over CoinsView state */ class CCoinsViewCursor { public: CCoinsViewCursor(const uint256 &hashBlockIn): hashBlock(hashBlockIn) {} virtual ~CCoinsViewCursor() {} virtual bool GetKey(COutPoint &key) const = 0; virtual bool GetValue(Coin &coin) const = 0; virtual unsigned int GetValueSize() const = 0; virtual bool Valid() const = 0; virtual void Next() = 0; //! Get best block at the time this cursor was created const uint256 &GetBestBlock() const { return hashBlock; } private: uint256 hashBlock; }; /** Abstract view on the open txout dataset. */ class CCoinsView { public: /** Retrieve the Coin (unspent transaction output) for a given outpoint. * Returns true only when an unspent coin was found, which is returned in coin. * When false is returned, coin's value is unspecified. */ virtual bool GetCoin(const COutPoint &outpoint, Coin &coin) const; //! Just check whether a given outpoint is unspent. virtual bool HaveCoin(const COutPoint &outpoint) const; //! Retrieve the block hash whose state this CCoinsView currently represents virtual uint256 GetBestBlock() const; //! Retrieve the range of blocks that may have been only partially written. //! If the database is in a consistent state, the result is the empty vector. //! Otherwise, a two-element vector is returned consisting of the new and //! the old block hash, in that order. virtual std::vector<uint256> GetHeadBlocks() const; //! Do a bulk modification (multiple Coin changes + BestBlock change). //! The passed mapCoins can be modified. virtual bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock); //! Get a cursor to iterate over the whole state virtual CCoinsViewCursor *Cursor() const; //! As we use CCoinsViews polymorphically, have a virtual destructor virtual ~CCoinsView() {} //! Estimate database size (0 if not implemented) virtual size_t EstimateSize() const { return 0; } }; /** CCoinsView backed by another CCoinsView */ class CCoinsViewBacked : public CCoinsView { protected: CCoinsView *base; public: CCoinsViewBacked(CCoinsView *viewIn); bool GetCoin(const COutPoint &outpoint, Coin &coin) const override; bool HaveCoin(const COutPoint &outpoint) const override; uint256 GetBestBlock() const override; std::vector<uint256> GetHeadBlocks() const override; void SetBackend(CCoinsView &viewIn); bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) override; CCoinsViewCursor *Cursor() const override; size_t EstimateSize() const override; }; /** CCoinsView that adds a memory cache for transactions to another CCoinsView */ class CCoinsViewCache : public CCoinsViewBacked { protected: /** * Make mutable so that we can "fill the cache" even from Get-methods * declared as "const". */ mutable uint256 hashBlock; mutable CCoinsMap cacheCoins; /* Cached dynamic memory usage for the inner Coin objects. */ mutable size_t cachedCoinsUsage; public: CCoinsViewCache(CCoinsView *baseIn); /** * By deleting the copy constructor, we prevent accidentally using it when one intends to create a cache on top of a base cache. */ CCoinsViewCache(const CCoinsViewCache &) = delete; // Standard CCoinsView methods bool GetCoin(const COutPoint &outpoint, Coin &coin) const override; bool HaveCoin(const COutPoint &outpoint) const override; uint256 GetBestBlock() const override; void SetBestBlock(const uint256 &hashBlock); bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) override; CCoinsViewCursor* Cursor() const override { throw std::logic_error("CCoinsViewCache cursor iteration not supported."); } /** * Check if we have the given utxo already loaded in this cache. * The semantics are the same as HaveCoin(), but no calls to * the backing CCoinsView are made. */ bool HaveCoinInCache(const COutPoint &outpoint) const; /** * Return a reference to Coin in the cache, or coinEmpty if not found. This is * more efficient than GetCoin. * * Generally, do not hold the reference returned for more than a short scope. * While the current implementation allows for modifications to the contents * of the cache while holding the reference, this behavior should not be relied * on! To be safe, best to not hold the returned reference through any other * calls to this cache. */ const Coin& AccessCoin(const COutPoint &output) const; /** * Add a coin. Set possible_overwrite to true if an unspent version may * already exist in the cache. */ void AddCoin(const COutPoint& outpoint, Coin&& coin, bool possible_overwrite); /** * Spend a coin. Pass moveto in order to get the deleted data. * If no unspent output exists for the passed outpoint, this call * has no effect. */ bool SpendCoin(const COutPoint &outpoint, Coin* moveto = nullptr); /** * Push the modifications applied to this cache to its base. * Failure to call this method before destruction will cause the changes to be forgotten. * If false is returned, the state of this cache (and its backing view) will be undefined. */ bool Flush(); /** * Removes the UTXO with the given outpoint from the cache, if it is * not modified. */ void Uncache(const COutPoint &outpoint); //! Calculate the size of the cache (in number of transaction outputs) unsigned int GetCacheSize() const; //! Calculate the size of the cache (in bytes) size_t DynamicMemoryUsage() const; /** * Amount of dash coming in to a transaction * Note that lightweight clients may not know anything besides the hash of previous transactions, * so may not be able to calculate this. * * @param[in] tx transaction for which we are checking input total * @return Sum of value of all inputs (scriptSigs) */ CAmount GetValueIn(const CTransaction& tx) const; //! Check whether all prevouts of the transaction are present in the UTXO set represented by this view bool HaveInputs(const CTransaction& tx) const; //! Force a reallocation of the cache map. This is required when downsizing //! the cache because the map's allocator may be hanging onto a lot of //! memory despite having called .clear(). //! //! See: https://stackoverflow.com/questions/42114044/how-to-release-unordered-map-memory void ReallocateCache(); private: /** * @note this is marked const, but may actually append to `cacheCoins`, increasing * memory usage. */ CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const; }; //! Utility function to add all of a transaction's outputs to a cache. //! When check is false, this assumes that overwrites are only possible for coinbase transactions. //! When check is true, the underlying view may be queried to determine whether an addition is //! an overwrite. // TODO: pass in a boolean to limit these possible overwrites to known // (pre-BIP34) cases. void AddCoins(CCoinsViewCache& cache, const CTransaction& tx, int nHeight, bool check = false); //! Utility function to find any unspent output with a given txid. //! This function can be quite expensive because in the event of a transaction //! which is not found in the cache, it can cause up to MAX_OUTPUTS_PER_BLOCK //! lookups to database, so it should be used with care. const Coin& AccessByTxid(const CCoinsViewCache& cache, const uint256& txid); /** * This is a minimally invasive approach to shutdown on LevelDB read errors from the * chainstate, while keeping user interface out of the common library, which is shared * between bitcoind, and bitcoin-qt and non-server tools. * * Writes do not need similar protection, as failure to write is handled by the caller. */ class CCoinsViewErrorCatcher final : public CCoinsViewBacked { public: explicit CCoinsViewErrorCatcher(CCoinsView* view) : CCoinsViewBacked(view) {} void AddReadErrCallback(std::function<void()> f) { m_err_callbacks.emplace_back(std::move(f)); } bool GetCoin(const COutPoint &outpoint, Coin &coin) const override; private: /** A list of callbacks to execute upon leveldb read error. */ std::vector<std::function<void()>> m_err_callbacks; }; #endif // BITCOIN_COINS_H
{ "content_hash": "3f7f088631efcb3a9a294b1087a7169c", "timestamp": "", "source": "github", "line_count": 387, "max_line_length": 132, "avg_line_length": 35.81395348837209, "alnum_prop": 0.6878066378066378, "repo_name": "dashpay/dash", "id": "14d6e9177b3f24c37e9e487cc0e1f847f90d4ef4", "size": "13860", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/coins.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "28178" }, { "name": "C", "bytes": "1866352" }, { "name": "C++", "bytes": "9729795" }, { "name": "CMake", "bytes": "32255" }, { "name": "CSS", "bytes": "113028" }, { "name": "Dockerfile", "bytes": "6344" }, { "name": "GDB", "bytes": "444" }, { "name": "HTML", "bytes": "21833" }, { "name": "M4", "bytes": "235904" }, { "name": "Makefile", "bytes": "128711" }, { "name": "Objective-C++", "bytes": "5478" }, { "name": "Python", "bytes": "1899906" }, { "name": "QMake", "bytes": "1389" }, { "name": "Sage", "bytes": "39795" }, { "name": "Shell", "bytes": "134642" } ], "symlink_target": "" }
require 'reform/form/orm' require 'reform/form/active_model' require 'reform/form/mongoid' require 'reform/form/active_model/model_reflections' # only load this in AR context as simple_form currently is bound to AR.
{ "content_hash": "125f68f63828c3c757cdf60cf52c60c3", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 124, "avg_line_length": 54, "alnum_prop": 0.7916666666666666, "repo_name": "trailblazer/reform-rails", "id": "a07093d8b764d8db3fd24ec2472253665dc7ff7a", "size": "216", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/reform/mongoid.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "87443" } ], "symlink_target": "" }
<?xml version="1.0"?> <!DOCTYPE article PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd"> <article xmlns="http://docbook.org/ns/docbook"> <section ID="all_known_directives"> <title>All known directives</title> <note> <para> Just a note!</para> </note> <tip> <para> You might want to use these more!</para> </tip> <warning> <para> Be careful about this!</para> </warning> <important> <para> Do not overdo it!</para> </important> <caution> <para> May have a bad impact on userexperience.</para> </caution> <blockquote> <para>Lets get something colorful!</para> </blockquote> <mediaobject> <imageobject> <imagedata fileref="test.png" width="256" depth="23" align="right"/> </imageobject> <textobject> Some alternative text.</textobject> <caption> <para>The figure actually shows nothing.</para> </caption> </mediaobject> <blockquote> <para>Figures may contain addition text!</para> </blockquote> <mediaobject> <imageobject> <imagedata fileref="test.png" width="256" depth="23" align="right"/> </imageobject> <textobject> Some alternative text.</textobject> </mediaobject> <para>And you can even inline other RST files.</para> <section ID="main_title"> <title>Main Title</title> <para>Hello world</para> <section ID="subsection"> <title>Subsection</title> <para>A bit more text, which exceeds one line to test for a simple paragraph with more then one line.</para> </section> </section> <para>but perhaps you want prevent them from being parsed...</para> <literallayout>========== Main Title ========== Hello world Subsection ========== A bit more text, which exceeds one line to test for a simple paragraph with more then one line. </literallayout> <para>That's all for now.</para> </section> </article>
{ "content_hash": "4b61aba06d7585c189aba182152e299c", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 119, "avg_line_length": 30.074626865671643, "alnum_prop": 0.6233250620347395, "repo_name": "lortnus/ezc", "id": "f039d45e403be4b85d0c9f634b886b44a7080210", "size": "2015", "binary": false, "copies": "25", "ref": "refs/heads/master", "path": "Document/tests/files/rst/docbook/s_027_all_directives.xml", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "4095" }, { "name": "PHP", "bytes": "24324049" }, { "name": "Python", "bytes": "54500" }, { "name": "SQL", "bytes": "8935" }, { "name": "Shell", "bytes": "71" } ], "symlink_target": "" }
<!-- This file is machine generated: DO NOT EDIT! --> # Wraps python functions Note: Functions taking `Tensor` arguments can also take anything accepted by [`tf.convert_to_tensor`](../../api_docs/python/framework.md#convert_to_tensor). [TOC] ## Script Language Operators. TensorFlow provides allows you to wrap python/numpy functions as TensorFlow operators. ## Other Functions and Classes - - - ### `tf.py_func(func, inp, Tout, name=None)` {#py_func} Wraps a python function and uses it as a tensorflow op. Given a python function `func`, which takes numpy arrays as its inputs and returns numpy arrays as its outputs. E.g., def my_func(x): return np.sinh(x) inp = tf.placeholder(..., tf.float32) y = py_func(my_func, [inp], [tf.float32]) The above snippet constructs a tf graph which invokes a numpy sinh(x) as an op in the graph. ##### Args: * <b>`func`</b>: A python function. * <b>`inp`</b>: A list of `Tensor`. * <b>`Tout`</b>: A list of tensorflow data types indicating what `func` returns. * <b>`name`</b>: A name for the operation (optional). ##### Returns: A list of `Tensor` which `func` computes.
{ "content_hash": "40e73b234e50729a4cd73dbaf9a06722", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 79, "avg_line_length": 25.02173913043478, "alnum_prop": 0.6794092093831451, "repo_name": "hlt-mt/tensorflow", "id": "aa1ff4c9c5fded559496b5d948b16703ea7ffc2d", "size": "1151", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "tensorflow/g3doc/api_docs/python/script_ops.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "151618" }, { "name": "C++", "bytes": "6163770" }, { "name": "CSS", "bytes": "107" }, { "name": "HTML", "bytes": "650431" }, { "name": "Java", "bytes": "50361" }, { "name": "JavaScript", "bytes": "6659" }, { "name": "Jupyter Notebook", "bytes": "766767" }, { "name": "Objective-C", "bytes": "1288" }, { "name": "Protocol Buffer", "bytes": "55681" }, { "name": "Python", "bytes": "3439349" }, { "name": "Shell", "bytes": "23913" }, { "name": "TypeScript", "bytes": "283668" } ], "symlink_target": "" }
<?php namespace Kit\SettingsBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class KitSettingsBundle extends Bundle { }
{ "content_hash": "68b518888cfdf2abdd7268c4ee0fb36b", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 47, "avg_line_length": 14.444444444444445, "alnum_prop": 0.8076923076923077, "repo_name": "lcp0578/kitcmf", "id": "2ee81398ddc9c3afd0ff435200ec08b8a8679cd1", "size": "130", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Kit/SettingsBundle/KitSettingsBundle.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3605" }, { "name": "CSS", "bytes": "58851" }, { "name": "HTML", "bytes": "169691" }, { "name": "JavaScript", "bytes": "2423326" }, { "name": "PHP", "bytes": "357681" } ], "symlink_target": "" }
"""Ops to manipulate lists of tensors.""" # pylint: disable=g-bad-name from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.core.framework import types_pb2 from tensorflow.python.framework import cpp_shape_inference_pb2 from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.framework import tensor_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import gen_list_ops from tensorflow.python.ops import handle_data_util # go/tf-wildcard-import # pylint: disable=wildcard-import from tensorflow.python.ops.gen_list_ops import * # pylint: enable=wildcard-import from tensorflow.python.util.lazy_loader import LazyLoader # list_ops -> control_flow_ops -> tensor_array_ops -> list_ops control_flow_ops = LazyLoader( "control_flow_ops", globals(), "tensorflow.python.ops.control_flow_ops") ops.NotDifferentiable("TensorListConcatLists") ops.NotDifferentiable("TensorListElementShape") ops.NotDifferentiable("TensorListLength") ops.NotDifferentiable("TensorListPushBackBatch") def empty_tensor_list(element_shape, element_dtype, max_num_elements=None, name=None): if max_num_elements is None: max_num_elements = -1 return gen_list_ops.empty_tensor_list( element_shape=_build_element_shape(element_shape), element_dtype=element_dtype, max_num_elements=max_num_elements, name=name) def _set_handle_data(list_handle, element_shape, element_dtype): """Sets type information on `list_handle` for consistency with graphs.""" # TODO(b/169968286): It would be better if we had a consistent story for # creating handle data from eager operations (shared with VarHandleOp). if isinstance(list_handle, ops.EagerTensor): if tensor_util.is_tensor(element_shape): element_shape = tensor_shape.TensorShape(None) elif not isinstance(element_shape, tensor_shape.TensorShape): element_shape = tensor_shape.TensorShape(element_shape) handle_data = cpp_shape_inference_pb2.CppShapeInferenceResult.HandleData() handle_data.is_set = True handle_data.shape_and_type.append( cpp_shape_inference_pb2.CppShapeInferenceResult.HandleShapeAndType( shape=element_shape.as_proto(), dtype=element_dtype.as_datatype_enum, specialized_type=types_pb2.ST_TENSOR_LIST)) list_handle._handle_data = handle_data # pylint: disable=protected-access def tensor_list_reserve(element_shape, num_elements, element_dtype, name=None): result = gen_list_ops.tensor_list_reserve( element_shape=_build_element_shape(element_shape), num_elements=num_elements, element_dtype=element_dtype, name=name) # TODO(b/169968286): gen_ops needs to ensure the metadata is properly # populated for eager operations. _set_handle_data(result, element_shape, element_dtype) return result def tensor_list_from_tensor(tensor, element_shape, name=None): tensor = ops.convert_to_tensor(tensor) result = gen_list_ops.tensor_list_from_tensor( tensor=tensor, element_shape=_build_element_shape(element_shape), name=name) _set_handle_data(result, tensor.shape, tensor.dtype) return result def tensor_list_get_item(input_handle, index, element_dtype, element_shape=None, name=None): return gen_list_ops.tensor_list_get_item( input_handle=input_handle, index=index, element_shape=_build_element_shape(element_shape), element_dtype=element_dtype, name=name) def tensor_list_pop_back(input_handle, element_dtype, name=None): return gen_list_ops.tensor_list_pop_back( input_handle=input_handle, element_shape=-1, element_dtype=element_dtype, name=name) def tensor_list_gather(input_handle, indices, element_dtype, element_shape=None, name=None): return gen_list_ops.tensor_list_gather( input_handle=input_handle, indices=indices, element_shape=_build_element_shape(element_shape), element_dtype=element_dtype, name=name) def tensor_list_scatter(tensor, indices, element_shape=None, input_handle=None, name=None): """Returns a TensorList created or updated by scattering `tensor`.""" tensor = ops.convert_to_tensor(tensor) if input_handle is not None: output_handle = gen_list_ops.tensor_list_scatter_into_existing_list( input_handle=input_handle, tensor=tensor, indices=indices, name=name) handle_data_util.copy_handle_data(input_handle, output_handle) return output_handle else: output_handle = gen_list_ops.tensor_list_scatter_v2( tensor=tensor, indices=indices, element_shape=_build_element_shape(element_shape), num_elements=-1, name=name) _set_handle_data(output_handle, element_shape, tensor.dtype) return output_handle def tensor_list_stack(input_handle, element_dtype, num_elements=-1, element_shape=None, name=None): return gen_list_ops.tensor_list_stack( input_handle=input_handle, element_shape=_build_element_shape(element_shape), element_dtype=element_dtype, num_elements=num_elements, name=name) def tensor_list_concat(input_handle, element_dtype, element_shape=None, name=None): # Ignore the lengths output of TensorListConcat. It is only used during # gradient computation. return gen_list_ops.tensor_list_concat_v2( input_handle=input_handle, element_dtype=element_dtype, element_shape=_build_element_shape(element_shape), leading_dims=ops.convert_to_tensor([], dtype=dtypes.int64), name=name)[0] def tensor_list_split(tensor, element_shape, lengths, name=None): return gen_list_ops.tensor_list_split( tensor=tensor, element_shape=_build_element_shape(element_shape), lengths=lengths, name=name) def tensor_list_set_item(input_handle, index, item, resize_if_index_out_of_bounds=False, name=None): """Sets `item` at `index` in input list.""" if resize_if_index_out_of_bounds: input_list_size = gen_list_ops.tensor_list_length(input_handle) # TODO(srbs): This could cause some slowdown. Consider fusing resize # functionality in the SetItem op. input_handle = control_flow_ops.cond( index >= input_list_size, lambda: gen_list_ops.tensor_list_resize( # pylint: disable=g-long-lambda input_handle, index + 1), lambda: input_handle) output_handle = gen_list_ops.tensor_list_set_item( input_handle=input_handle, index=index, item=item, name=name) handle_data_util.copy_handle_data(input_handle, output_handle) return output_handle @ops.RegisterGradient("TensorListPushBack") def _PushBackGrad(op, dresult): return gen_list_ops.tensor_list_pop_back( dresult, element_shape=array_ops.shape(op.inputs[1]), element_dtype=op.get_attr("element_dtype")) @ops.RegisterGradient("TensorListPopBack") def _PopBackGrad(op, dlist, delement): if dlist is None: dlist = empty_tensor_list( element_dtype=delement.dtype, element_shape=gen_list_ops.tensor_list_element_shape( op.outputs[0], shape_type=dtypes.int32)) if delement is None: delement = array_ops.zeros_like(op.outputs[1]) return gen_list_ops.tensor_list_push_back(dlist, delement), None @ops.RegisterGradient("TensorListStack") def _TensorListStackGrad(unused_op, dtensor): return tensor_list_from_tensor(dtensor, element_shape=dtensor.shape[1:]), None @ops.RegisterGradient("TensorListConcat") @ops.RegisterGradient("TensorListConcatV2") def _TensorListConcatGrad(op, dtensor, unused_dlengths): """Gradient function for TensorListConcat.""" dlist = tensor_list_split( dtensor, element_shape=gen_list_ops.tensor_list_element_shape( op.inputs[0], shape_type=dtypes.int32), lengths=op.outputs[1]) if op.type == "TensorListConcatV2": return dlist, None, None else: return dlist @ops.RegisterGradient("TensorListSplit") def _TensorListSplitGrad(op, dlist): tensor, _, lengths = op.inputs element_shape = array_ops.slice(array_ops.shape(tensor), [1], [-1]) element_shape = array_ops.concat([[-1], element_shape], axis=0) return gen_list_ops.tensor_list_concat_v2( dlist, element_shape=element_shape, leading_dims=lengths, element_dtype=op.inputs[0].dtype)[0], None, None @ops.RegisterGradient("TensorListFromTensor") def _TensorListFromTensorGrad(op, dlist): """Gradient for TensorListFromTensor.""" t = op.inputs[0] if t.shape.dims and t.shape.dims[0].value is not None: num_elements = t.shape.dims[0].value else: num_elements = None if dlist is None: dlist = empty_tensor_list( element_dtype=t.dtype, element_shape=gen_list_ops.tensor_list_element_shape( op.outputs[0], shape_type=dtypes.int32)) tensor_grad = gen_list_ops.tensor_list_stack( dlist, element_shape=array_ops.slice(array_ops.shape(t), [1], [-1]), element_dtype=t.dtype, num_elements=num_elements) shape_grad = None return tensor_grad, shape_grad @ops.RegisterGradient("TensorListGetItem") def _TensorListGetItemGrad(op, ditem): """Gradient for TensorListGetItem.""" list_size = gen_list_ops.tensor_list_length(op.inputs[0]) list_grad = gen_list_ops.tensor_list_set_item( gen_list_ops.tensor_list_reserve( gen_list_ops.tensor_list_element_shape(op.inputs[0], shape_type=dtypes.int32), list_size, element_dtype=ditem.dtype), index=op.inputs[1], item=ditem) index_grad = None element_shape_grad = None return list_grad, index_grad, element_shape_grad @ops.RegisterGradient("TensorListSetItem") def _TensorListSetItemGrad(op, dlist): """Gradient function for TensorListSetItem.""" _, index, item = op.inputs list_grad = gen_list_ops.tensor_list_set_item( dlist, index=index, item=array_ops.zeros_like(item)) index_grad = None element_grad = tensor_list_get_item( dlist, index, element_shape=array_ops.shape(item), element_dtype=item.dtype) return list_grad, index_grad, element_grad @ops.RegisterGradient("TensorListResize") def _TensorListResizeGrad(op, dlist): input_list, _ = op.inputs input_list_size = gen_list_ops.tensor_list_length(input_list) return gen_list_ops.tensor_list_resize(dlist, input_list_size), None @ops.RegisterGradient("TensorListGather") def _TensorListGatherGrad(op, dtensor): """Gradient function for TensorListGather.""" input_list, indices, _ = op.inputs element_shape = gen_list_ops.tensor_list_element_shape( input_list, shape_type=dtypes.int32) num_elements = gen_list_ops.tensor_list_length(input_list) dlist = tensor_list_reserve(element_shape, num_elements, dtensor.dtype) dlist = tensor_list_scatter( tensor=dtensor, indices=indices, input_handle=dlist) return dlist, None, None @ops.RegisterGradient("TensorListScatter") @ops.RegisterGradient("TensorListScatterV2") def _TensorListScatterGrad(op, dlist): """Gradient function for TensorListScatter.""" tensor = op.inputs[0] indices = op.inputs[1] dtensor = gen_list_ops.tensor_list_gather( dlist, indices, element_shape=array_ops.slice(array_ops.shape(tensor), [1], [-1]), element_dtype=tensor.dtype) if op.type == "TensorListScatterV2": return dtensor, None, None, None else: return dtensor, None, None @ops.RegisterGradient("TensorListScatterIntoExistingList") def _TensorListScatterIntoExistingListGrad(op, dlist): """Gradient function for TensorListScatterIntoExistingList.""" _, tensor, indices = op.inputs dtensor = gen_list_ops.tensor_list_gather( dlist, indices, element_shape=array_ops.slice(array_ops.shape(tensor), [1], [-1]), element_dtype=tensor.dtype) zeros = array_ops.zeros_like(tensor) dlist = tensor_list_scatter(zeros, indices, indices, input_handle=dlist) return dlist, dtensor, None def _build_element_shape(shape): """Converts shape to a format understood by list_ops for element_shape. If `shape` is already a `Tensor` it is returned as-is. We do not perform a type check here. If shape is None or a TensorShape with unknown rank, -1 is returned. If shape is a scalar, an int32 tensor with empty list is returned. Note we do directly return an empty list since ops.convert_to_tensor would conver it to a float32 which is not a valid type for element_shape. If shape is a sequence of dims, None's in the list are replaced with -1. We do not check the dtype of the other dims. Args: shape: Could be None, Tensor, TensorShape or a list of dims (each dim could be a None, scalar or Tensor). Returns: A None-free shape that can be converted to a tensor. """ if isinstance(shape, ops.Tensor): return shape if isinstance(shape, tensor_shape.TensorShape): # `TensorShape.as_list` requires rank to be known. shape = shape.as_list() if shape else None # Shape is unknown. if shape is None: return -1 # Shape is numpy array or a scalar. if isinstance(shape, (np.ndarray, np.generic)) or not shape: return ops.convert_to_tensor(shape, dtype=dtypes.int32) # Shape is a sequence of dimensions. Convert None dims to -1. def convert(val): if val is None: return -1 if isinstance(val, ops.Tensor): return val if isinstance(val, tensor_shape.Dimension): return val.value if val.value is not None else -1 return val return [convert(d) for d in shape]
{ "content_hash": "19466454f1249a77cde4a9c48d489efe", "timestamp": "", "source": "github", "line_count": 399, "max_line_length": 81, "avg_line_length": 35.478696741854634, "alnum_prop": 0.6876236224922294, "repo_name": "freedomtan/tensorflow", "id": "f4da26ccb949cd83a6630879140779d51c64bd4e", "size": "14845", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "tensorflow/python/ops/list_ops.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "32479" }, { "name": "Batchfile", "bytes": "38366" }, { "name": "C", "bytes": "1035837" }, { "name": "C#", "bytes": "13395" }, { "name": "C++", "bytes": "99324075" }, { "name": "CMake", "bytes": "107781" }, { "name": "Dockerfile", "bytes": "283435" }, { "name": "Go", "bytes": "2013128" }, { "name": "HTML", "bytes": "4686483" }, { "name": "Java", "bytes": "928595" }, { "name": "Jupyter Notebook", "bytes": "981916" }, { "name": "LLVM", "bytes": "6536" }, { "name": "MLIR", "bytes": "4489624" }, { "name": "Makefile", "bytes": "97500" }, { "name": "NASL", "bytes": "8048" }, { "name": "Objective-C", "bytes": "141623" }, { "name": "Objective-C++", "bytes": "360423" }, { "name": "PHP", "bytes": "20570" }, { "name": "Pawn", "bytes": "32277" }, { "name": "Perl", "bytes": "7536" }, { "name": "Python", "bytes": "42762396" }, { "name": "RobotFramework", "bytes": "2661" }, { "name": "Roff", "bytes": "2515" }, { "name": "Ruby", "bytes": "6723" }, { "name": "Shell", "bytes": "647623" }, { "name": "Smarty", "bytes": "52687" }, { "name": "Starlark", "bytes": "4632847" }, { "name": "Swift", "bytes": "56924" }, { "name": "Vim Snippet", "bytes": "58" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8"> <title>SoundManager2.as</title> <style type="text/css"> /** * http://jashkenas.github.com/docco/resources/docco.css */ /*--------------------- Layout and Typography ----------------------------*/ body { font-family: 'Palatino Linotype', 'Book Antiqua', Palatino, FreeSerif, serif; font-size: 15px; line-height: 22px; color: #252519; margin: 0; padding: 0; } a { color: #261a3b; } a:visited { color: #261a3b; } p { margin: 0 0 15px 0; } h1, h2, h3, h4, h5, h6 { margin: 0px 0 15px 0; } h1 { margin-top: 40px; } #container { position: relative; } #background { position: fixed; top: 0; left: 525px; right: 0; bottom: 0; background: #f5f5ff; border-left: 1px solid #e5e5ee; z-index: -1; } #jump_to, #jump_page { background: white; -webkit-box-shadow: 0 0 25px #777; -moz-box-shadow: 0 0 25px #777; -webkit-border-bottom-left-radius: 5px; -moz-border-radius-bottomleft: 5px; font: 10px Arial; text-transform: uppercase; cursor: pointer; text-align: right; } #jump_to, #jump_wrapper { position: fixed; right: 0; top: 0; padding: 5px 10px; } #jump_wrapper { padding: 0; display: none; } #jump_to:hover #jump_wrapper { display: block; } #jump_page { padding: 5px 0 3px; margin: 0 0 25px 25px; } #jump_page .source { display: block; padding: 5px 10px; text-decoration: none; border-top: 1px solid #eee; } #jump_page .source:hover { background: #f5f5ff; } #jump_page .source:first-child { } table td { border: 0; outline: 0; } td.docs, th.docs { max-width: 450px; min-width: 450px; min-height: 5px; padding: 10px 25px 1px 50px; overflow-x: hidden; vertical-align: top; text-align: left; } .docs pre { margin: 15px 0 15px; padding-left: 15px; } .docs p tt, .docs p code { background: #f8f8ff; border: 1px solid #dedede; font-size: 12px; padding: 0 0.2em; } .pilwrap { position: relative; } .pilcrow { font: 12px Arial; text-decoration: none; color: #454545; position: absolute; top: 3px; left: -20px; padding: 1px 2px; opacity: 0; -webkit-transition: opacity 0.2s linear; } td.docs:hover .pilcrow { opacity: 1; } td.code, th.code { padding: 14px 15px 16px 25px; width: 100%; vertical-align: top; background: #f5f5ff; border-left: 1px solid #e5e5ee; } pre, tt, code { font-size: 12px; line-height: 18px; font-family: Menlo, Monaco, Consolas, "Lucida Console", monospace; margin: 0; padding: 0; } /*---------------------- Syntax Highlighting -----------------------------*/ td.linenos { background-color: #f0f0f0; padding-right: 10px; } span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; } body .hll { background-color: #ffffcc } body .c { color: #408080; font-style: italic } /* Comment */ body .err { border: 1px solid #FF0000 } /* Error */ body .k { color: #954121 } /* Keyword */ body .o { color: #666666 } /* Operator */ body .cm { color: #408080; font-style: italic } /* Comment.Multiline */ body .cp { color: #BC7A00 } /* Comment.Preproc */ body .c1 { color: #408080; font-style: italic } /* Comment.Single */ body .cs { color: #408080; font-style: italic } /* Comment.Special */ body .gd { color: #A00000 } /* Generic.Deleted */ body .ge { font-style: italic } /* Generic.Emph */ body .gr { color: #FF0000 } /* Generic.Error */ body .gh { color: #000080; font-weight: bold } /* Generic.Heading */ body .gi { color: #00A000 } /* Generic.Inserted */ body .go { color: #808080 } /* Generic.Output */ body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */ body .gs { font-weight: bold } /* Generic.Strong */ body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */ body .gt { color: #0040D0 } /* Generic.Traceback */ body .kc { color: #954121 } /* Keyword.Constant */ body .kd { color: #954121; font-weight: bold } /* Keyword.Declaration */ body .kn { color: #954121; font-weight: bold } /* Keyword.Namespace */ body .kp { color: #954121 } /* Keyword.Pseudo */ body .kr { color: #954121; font-weight: bold } /* Keyword.Reserved */ body .kt { color: #B00040 } /* Keyword.Type */ body .m { color: #666666 } /* Literal.Number */ body .s { color: #219161 } /* Literal.String */ body .na { color: #7D9029 } /* Name.Attribute */ body .nb { color: #954121 } /* Name.Builtin */ body .nc { color: #0000FF; font-weight: bold } /* Name.Class */ body .no { color: #880000 } /* Name.Constant */ body .nd { color: #AA22FF } /* Name.Decorator */ body .ni { color: #999999; font-weight: bold } /* Name.Entity */ body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */ body .nf { color: #0000FF } /* Name.Function */ body .nl { color: #A0A000 } /* Name.Label */ body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */ body .nt { color: #954121; font-weight: bold } /* Name.Tag */ body .nv { color: #19469D } /* Name.Variable */ body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */ body .w { color: #bbbbbb } /* Text.Whitespace */ body .mf { color: #666666 } /* Literal.Number.Float */ body .mh { color: #666666 } /* Literal.Number.Hex */ body .mi { color: #666666 } /* Literal.Number.Integer */ body .mo { color: #666666 } /* Literal.Number.Oct */ body .sb { color: #219161 } /* Literal.String.Backtick */ body .sc { color: #219161 } /* Literal.String.Char */ body .sd { color: #219161; font-style: italic } /* Literal.String.Doc */ body .s2 { color: #219161 } /* Literal.String.Double */ body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */ body .sh { color: #219161 } /* Literal.String.Heredoc */ body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */ body .sx { color: #954121 } /* Literal.String.Other */ body .sr { color: #BB6688 } /* Literal.String.Regex */ body .s1 { color: #219161 } /* Literal.String.Single */ body .ss { color: #19469D } /* Literal.String.Symbol */ body .bp { color: #954121 } /* Name.Builtin.Pseudo */ body .vc { color: #19469D } /* Name.Variable.Class */ body .vg { color: #19469D } /* Name.Variable.Global */ body .vi { color: #19469D } /* Name.Variable.Instance */ body .il { color: #666666 } /* Literal.Number.Integer.Long */ </style> </head> <body> <div id='container'> <div id="background"></div> <div id="jump_to"> Jump To &hellip; <div id="jump_wrapper"> <div id="jump_page"> <a class="source" href="../demo/360-player/script/360player.html">360player.js</a> <a class="source" href="../demo/flashblock/flashblock.html">flashblock.css</a> <a class="source" href="../demo/mp3-player-button/script/mp3-player-button.html">mp3-player-button.js</a> <a class="source" href="../demo/mpc/script/mpc.html">mpc.js</a> <a class="source" href="../demo/page-player/script/page-player.html">page-player.js</a> <a class="source" href="../demo/play-mp3-links/script/inlineplayer.html">inlineplayer.js</a> <a class="source" href="../script/soundmanager2.html">soundmanager2.js</a> <a class="source" href="SoundManager2.html">SoundManager2.as</a> <a class="source" href="SoundManager2_AS3.html">SoundManager2_AS3.as</a> <a class="source" href="SoundManager2_SMSound_AS3.html">SoundManager2_SMSound_AS3.as</a> </div> </div> </div> <table cellspacing=0 cellpadding=0> <thead> <tr> <th class=docs><h1>SoundManager2.as</h1></th> <th class=code></th> </tr> </thead> <tbody> <tr id='section-SoundManager_2:_Javascript_Sound_for_the_Web'> <td class=docs> <div class="pilwrap"> <a class="pilcrow" href="#section-SoundManager_2:_Javascript_Sound_for_the_Web">&#182;</a> </div> <h2>SoundManager 2: Javascript Sound for the Web</h2> <p>http://schillmania.com/projects/soundmanager2/</p> <p>Copyright &copy; 2007, Scott Schiller. All rights reserved. Code licensed under the BSD License: http://www.schillmania.com/projects/soundmanager2/license.txt</p> <p>Flash 8 / ActionScript 2 version</p> <p>Compiling AS to Flash 8 SWF using MTASC (free compiler &ndash; http://www.mtasc.org/): mtasc -swf soundmanager2.swf -main -header 16:16:30 SoundManager2.as -version 8</p> <p>ActionScript Sound class reference (Macromedia), documentation download: http://livedocs.macromedia.com/flash/8/ Previously-live URL: http://livedocs.macromedia.com/flash/8/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&amp;file=00002668.html</p> <p>*** NOTE ON LOCAL FILE SYSTEM ACCESS ***</p> <p>Flash security allows local OR network access, but not both unless explicitly whitelisted/allowed by the flash player&rsquo;s security settings.</p> <p>To enable in-flash messaging for troubleshooting, pass debug=1 in FlashVars (within object/embed code) SM2 will do this by default when soundManager.debugFlash = true.</p> </td> <td class=code> <div class='highlight'><pre><span class="k">import</span> <span class="nn">flash.external.ExternalInterface</span><span class="o">;</span> <span class="c1">// woo</span> <span class="kd">class</span> <span class="n">SoundManager2</span> <span class="o">{</span> <span class="kd">static</span> <span class="kd">var</span> <span class="n">app</span><span class="p">:</span> <span class="kt">SoundManager2</span><span class="o">;</span> <span class="kd">function </span><span class="nf">SoundManager2</span><span class="o">()</span> <span class="o">{</span> <span class="n">var</span> <span class="n">version</span> <span class="o">=</span> <span class="s2">&quot;V2.97a.20111220&quot;</span><span class="o">;</span> <span class="n">var</span> <span class="n">version_as</span> <span class="o">=</span> <span class="s2">&quot;(AS2/Flash 8)&quot;</span><span class="o">;</span></pre></div> </td> </tr> <tr id='section-2'> <td class=docs> <div class="pilwrap"> <a class="pilcrow" href="#section-2">&#182;</a> </div> <p>Cross-domain security options HTML on foo.com loading .swf hosted on bar.com? Define your &ldquo;HTML domain&rdquo; here to allow JS+Flash communication to work. // allow<em>xdomain</em>scripting = true; // xdomain = &ldquo;foo.com&rdquo;; For all domains (possible security risk?), use xdomain = &ldquo;<em>&rdquo;; which ends up as System.security.allowDomain(&ldquo;</em>&rdquo;); When loading from HTTPS, use System.security.allowInsecureDomain(); See &ldquo;allowDomain (security.allowDomain method)&rdquo; in Flash 8/AS2 liveDocs documentation (AS2 reference &ndash;&gt; classes &ndash;&gt; security) download from http://livedocs.macromedia.com/flash/8/ Related AS3 documentation: http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/system/Security.html#allowDomain%28%29</p> </td> <td class=code> <div class='highlight'><pre> <span class="n">var</span> <span class="n">allow_xdomain_scripting</span> <span class="o">=</span> <span class="kc">false</span><span class="o">;</span> <span class="n">var</span> <span class="n">xdomain</span> <span class="o">=</span> <span class="s2">&quot;*&quot;</span><span class="o">;</span> <span class="k">if</span> <span class="o">(</span><span class="n">allow_xdomain_scripting</span> <span class="o">&amp;&amp;</span> <span class="n">xdomain</span><span class="o">)</span> <span class="o">{</span> <span class="n">System</span><span class="o">.</span><span class="na">security</span><span class="o">.</span><span class="na">allowDomain</span><span class="o">(</span><span class="n">xdomain</span><span class="o">);</span> <span class="n">version_as</span> <span class="o">+=</span> <span class="s1">&#39; - cross-domain enabled&#39;</span><span class="o">;</span> <span class="o">}</span></pre></div> </td> </tr> <tr id='section-3'> <td class=docs> <div class="pilwrap"> <a class="pilcrow" href="#section-3">&#182;</a> </div> <p>externalInterface references (for Javascript callbacks)</p> </td> <td class=code> <div class='highlight'><pre> <span class="n">var</span> <span class="n">baseJSController</span> <span class="o">=</span> <span class="s2">&quot;soundManager&quot;</span><span class="o">;</span> <span class="n">var</span> <span class="n">baseJSObject</span> <span class="o">=</span> <span class="n">baseJSController</span> <span class="o">+</span> <span class="s2">&quot;.sounds&quot;</span><span class="o">;</span></pre></div> </td> </tr> <tr id='section-4'> <td class=docs> <div class="pilwrap"> <a class="pilcrow" href="#section-4">&#182;</a> </div> <p>internal objects</p> </td> <td class=code> <div class='highlight'><pre> <span class="n">var</span> <span class="n">sounds</span> <span class="o">=</span> <span class="o">[];</span> <span class="c1">// indexed string array</span> <span class="n">var</span> <span class="n">soundObjects</span> <span class="o">=</span> <span class="o">[];</span> <span class="c1">// associative Sound() object array</span> <span class="n">var</span> <span class="n">timer</span> <span class="o">=</span> <span class="kc">null</span><span class="o">;</span> <span class="n">var</span> <span class="n">pollingEnabled</span> <span class="o">=</span> <span class="kc">false</span><span class="o">;</span> <span class="c1">// polling (timer) flag - disabled by default, enabled by JS-&gt;Flash call</span> <span class="n">var</span> <span class="n">debugEnabled</span> <span class="o">=</span> <span class="kc">true</span><span class="o">;</span> <span class="c1">// Flash debug output enabled by default, disabled by JS call</span> <span class="n">var</span> <span class="n">flashDebugEnabled</span> <span class="o">=</span> <span class="kc">false</span><span class="o">;</span> <span class="c1">// debug output to flash movie, off by default</span> <span class="n">var</span> <span class="n">didSandboxMessage</span> <span class="o">=</span> <span class="kc">false</span><span class="o">;</span> <span class="n">var</span> <span class="n">caughtFatal</span> <span class="o">=</span> <span class="kc">false</span><span class="o">;</span></pre></div> </td> </tr> <tr id='section-5'> <td class=docs> <div class="pilwrap"> <a class="pilcrow" href="#section-5">&#182;</a> </div> <p>for flash text output, debugging etc.</p> </td> <td class=code> <div class='highlight'><pre> <span class="n">var</span> <span class="n">_messages</span> <span class="o">=</span> <span class="o">[];</span> <span class="n">var</span> <span class="n">_messageObj</span> <span class="o">=</span> <span class="kc">null</span><span class="o">;</span> <span class="n">flashDebugEnabled</span> <span class="o">=</span> <span class="o">(</span><span class="n">_root</span><span class="o">.</span><span class="na">debug</span> <span class="o">==</span> <span class="mi">1</span><span class="o">);</span></pre></div> </td> </tr> <tr id='section-6'> <td class=docs> <div class="pilwrap"> <a class="pilcrow" href="#section-6">&#182;</a> </div> <p>display stuffs</p> </td> <td class=code> <div class='highlight'><pre> <span class="n">Stage</span><span class="o">.</span><span class="na">scaleMode</span> <span class="o">=</span> <span class="s1">&#39;noScale&#39;</span><span class="o">;</span> <span class="n">Stage</span><span class="o">.</span><span class="na">align</span> <span class="o">=</span> <span class="s1">&#39;TL&#39;</span><span class="o">;</span></pre></div> </td> </tr> <tr id='section-7'> <td class=docs> <div class="pilwrap"> <a class="pilcrow" href="#section-7">&#182;</a> </div> <p>context menu item with version info</p> </td> <td class=code> <div class='highlight'><pre> <span class="n">var</span> <span class="n">doNothing</span> <span class="o">=</span> <span class="kd">function</span><span class="o">()</span> <span class="o">{}</span> <span class="kd">var</span> <span class="n">sm2Menu</span><span class="p">:</span><span class="kt">ContextMenu</span> <span class="o">=</span> <span class="k">new</span> <span class="kt">ContextMenu</span><span class="o">();</span> <span class="kd">var</span> <span class="n">sm2MenuItem</span><span class="p">:</span><span class="kt">ContextMenuItem</span> <span class="o">=</span> <span class="k">new</span> <span class="kt">ContextMenuItem</span><span class="o">(</span><span class="s1">&#39;SoundManager &#39;</span> <span class="o">+</span> <span class="n">version</span> <span class="o">+</span> <span class="s1">&#39; &#39;</span> <span class="o">+</span> <span class="n">version_as</span><span class="o">,</span> <span class="n">doNothing</span><span class="o">);</span> <span class="n">sm2MenuItem</span><span class="o">.</span><span class="na">enabled</span> <span class="o">=</span> <span class="kc">false</span><span class="o">;</span> <span class="n">sm2Menu</span><span class="o">.</span><span class="na">customItems</span><span class="o">.</span><span class="na">push</span><span class="o">(</span><span class="n">sm2MenuItem</span><span class="o">);</span> <span class="n">_root</span><span class="o">.</span><span class="na">menu</span> <span class="o">=</span> <span class="n">sm2Menu</span><span class="o">;</span> <span class="n">var</span> <span class="n">writeDebug</span> <span class="o">=</span> <span class="kd">function</span><span class="o">(</span><span class="n">s</span><span class="o">)</span> <span class="o">{</span></pre></div> </td> </tr> <tr id='section-8'> <td class=docs> <div class="pilwrap"> <a class="pilcrow" href="#section-8">&#182;</a> </div> <p><d></p> </td> <td class=code> <div class='highlight'><pre> <span class="k">if</span> <span class="o">(!</span><span class="n">debugEnabled</span><span class="o">)</span> <span class="k">return</span> <span class="kc">false</span><span class="o">;</span> <span class="n">ExternalInterface</span><span class="o">.</span><span class="na">call</span><span class="o">(</span><span class="n">baseJSController</span> <span class="o">+</span> <span class="s2">&quot;[&#39;_writeDebug&#39;]&quot;</span><span class="o">,</span> <span class="s2">&quot;(Flash): &quot;</span> <span class="o">+</span> <span class="n">s</span><span class="o">);</span></pre></div> </td> </tr> <tr id='section-9'> <td class=docs> <div class="pilwrap"> <a class="pilcrow" href="#section-9">&#182;</a> </div> <p></d></p> </td> <td class=code> <div class='highlight'><pre> <span class="o">}</span> <span class="n">var</span> <span class="n">flashDebug</span> <span class="o">=</span> <span class="kd">function</span><span class="o">(</span><span class="n">messageText</span><span class="o">)</span> <span class="o">{</span></pre></div> </td> </tr> <tr id='section-10'> <td class=docs> <div class="pilwrap"> <a class="pilcrow" href="#section-10">&#182;</a> </div> <p><d></p> </td> <td class=code> <div class='highlight'><pre> <span class="n">_messages</span><span class="o">.</span><span class="na">push</span><span class="o">(</span><span class="n">messageText</span><span class="o">);</span> <span class="k">if</span> <span class="o">(!</span><span class="n">flashDebugEnabled</span><span class="o">)</span> <span class="o">{</span> <span class="k">return</span> <span class="kc">false</span><span class="o">;</span> <span class="o">}</span> <span class="n">var</span> <span class="n">sans</span> <span class="o">=</span> <span class="k">new</span> <span class="kt">TextFormat</span><span class="o">();</span> <span class="n">sans</span><span class="o">.</span><span class="na">size</span> <span class="o">=</span> <span class="mi">12</span><span class="o">;</span> <span class="n">sans</span><span class="o">.</span><span class="na">font</span> <span class="o">=</span> <span class="s2">&quot;Arial&quot;</span><span class="o">;</span></pre></div> </td> </tr> <tr id='section-11'> <td class=docs> <div class="pilwrap"> <a class="pilcrow" href="#section-11">&#182;</a> </div> <p>320x240 if no stage dimensions (happens in IE, apparently 0 before stage resize event fires.)</p> </td> <td class=code> <div class='highlight'><pre> <span class="n">var</span> <span class="n">w</span> <span class="o">=</span> <span class="n">Stage</span><span class="o">.</span><span class="na">width</span><span class="o">?</span><span class="n">Stage</span><span class="o">.</span><span class="na">width</span><span class="o">:</span><span class="mi">320</span><span class="o">;</span> <span class="n">var</span> <span class="n">h</span> <span class="o">=</span> <span class="n">Stage</span><span class="o">.</span><span class="na">height</span><span class="o">?</span><span class="n">Stage</span><span class="o">.</span><span class="na">height</span><span class="o">:</span><span class="mi">240</span><span class="o">;</span> <span class="k">if</span> <span class="o">(!</span><span class="n">_messageObj</span><span class="o">)</span> <span class="o">{</span> <span class="n">_messageObj</span> <span class="o">=</span> <span class="n">_root</span><span class="o">.</span><span class="na">createTextField</span><span class="o">(</span><span class="s2">&quot;_messageObj&quot;</span><span class="o">,</span> <span class="mi">0</span><span class="o">,</span> <span class="mi">0</span><span class="o">,</span> <span class="mi">0</span><span class="o">,</span> <span class="n">w</span><span class="o">,</span> <span class="n">h</span><span class="o">);</span> <span class="n">_messageObj</span><span class="o">.</span><span class="na">x</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">_messageObj</span><span class="o">.</span><span class="na">y</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">_messageObj</span><span class="o">.</span><span class="na">multiline</span> <span class="o">=</span> <span class="kc">true</span><span class="o">;</span> <span class="n">_messageObj</span><span class="o">.</span><span class="na">html</span> <span class="o">=</span> <span class="kc">true</span><span class="o">;</span> <span class="n">_messageObj</span><span class="o">.</span><span class="na">wordWrap</span> <span class="o">=</span> <span class="kc">true</span><span class="o">;</span> <span class="n">_messageObj</span><span class="o">.</span><span class="na">align</span> <span class="o">=</span> <span class="s1">&#39;left&#39;</span><span class="o">;</span> <span class="n">_messageObj</span><span class="o">.</span><span class="na">autoSize</span> <span class="o">=</span> <span class="kc">false</span><span class="o">;</span> <span class="o">}</span> <span class="n">_messageObj</span><span class="o">.</span><span class="na">htmlText</span> <span class="o">=</span> <span class="n">_messages</span><span class="o">.</span><span class="na">join</span><span class="o">(</span><span class="s1">&#39;\n&#39;</span><span class="o">);</span> <span class="n">_messageObj</span><span class="o">.</span><span class="na">setTextFormat</span><span class="o">(</span><span class="n">sans</span><span class="o">);</span> <span class="n">_messageObj</span><span class="o">.</span><span class="na">width</span> <span class="o">=</span> <span class="n">w</span><span class="o">;</span> <span class="n">_messageObj</span><span class="o">.</span><span class="na">height</span> <span class="o">=</span> <span class="n">h</span><span class="o">;</span></pre></div> </td> </tr> <tr id='section-12'> <td class=docs> <div class="pilwrap"> <a class="pilcrow" href="#section-12">&#182;</a> </div> <p></d></p> </td> <td class=code> <div class='highlight'><pre> <span class="o">}</span> <span class="n">var</span> <span class="n">_externalInterfaceTest</span> <span class="o">=</span> <span class="kd">function</span><span class="o">(</span><span class="n">isFirstCall</span><span class="o">)</span> <span class="o">{</span> <span class="n">var</span> <span class="n">sandboxType</span> <span class="o">=</span> <span class="n">System</span><span class="o">.</span><span class="na">security</span><span class="o">[</span><span class="s1">&#39;sandboxType&#39;</span><span class="o">];</span> <span class="k">try</span> <span class="o">{</span> <span class="k">if</span> <span class="o">(</span><span class="n">isFirstCall</span><span class="o">)</span> <span class="o">{</span> <span class="n">flashDebug</span><span class="o">(</span><span class="s1">&#39;Testing Flash -&amp;gt; JS...&#39;</span><span class="o">)</span> <span class="k">if</span> <span class="o">(!</span><span class="n">didSandboxMessage</span> <span class="o">&amp;&amp;</span> <span class="n">sandboxType</span> <span class="o">!=</span> <span class="s1">&#39;remote&#39;</span> <span class="o">&amp;&amp;</span> <span class="n">sandboxType</span> <span class="o">!=</span> <span class="s1">&#39;localTrusted&#39;</span><span class="o">)</span> <span class="o">{</span> <span class="n">didSandboxMessage</span> <span class="o">=</span> <span class="kc">true</span><span class="o">;</span> <span class="n">flashDebug</span><span class="o">(</span><span class="s1">&#39;&lt;br&gt;&lt;b&gt;Fatal: Security sandbox error: Got &quot;&#39;</span> <span class="o">+</span> <span class="n">sandboxType</span> <span class="o">+</span> <span class="s1">&#39;&quot;, expected &quot;remote&quot; or &quot;localTrusted&quot;.&lt;br&gt;Additional security permissions need to be granted.&lt;br&gt;See &lt;a href=&quot;http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html&quot;&gt;flash security settings panel&lt;/a&gt; for non-HTTP, eg. file:// use.&lt;/b&gt;&lt;br&gt;http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html&lt;br&gt;&lt;br&gt;You may also be able to right-click this movie and choose from the menu: &lt;br&gt;&quot;Global Settings&quot; -&gt; &quot;Advanced&quot; tab -&gt; &quot;Trusted Location Settings&quot;&lt;br&gt;&#39;</span><span class="o">);</span> <span class="o">}</span> <span class="n">var</span> <span class="n">d</span> <span class="o">=</span> <span class="k">new</span> <span class="kt">Date</span><span class="o">();</span> <span class="n">ExternalInterface</span><span class="o">.</span><span class="na">call</span><span class="o">(</span><span class="n">baseJSController</span> <span class="o">+</span> <span class="s2">&quot;._externalInterfaceOK&quot;</span><span class="o">,</span> <span class="n">d</span><span class="o">.</span><span class="na">getTime</span><span class="o">(),</span> <span class="n">version</span><span class="o">);</span> <span class="k">if</span> <span class="o">(!</span><span class="n">didSandboxMessage</span><span class="o">)</span> <span class="o">{</span> <span class="n">flashDebug</span><span class="o">(</span><span class="s1">&#39;Flash -&amp;gt; JS OK&#39;</span><span class="o">);</span> <span class="o">}</span> <span class="o">}</span> <span class="k">else</span> <span class="o">{</span> <span class="n">writeDebug</span><span class="o">(</span><span class="s1">&#39;SM2 SWF &#39;</span> <span class="o">+</span> <span class="n">version</span> <span class="o">+</span> <span class="s1">&#39; &#39;</span> <span class="o">+</span> <span class="n">version_as</span><span class="o">);</span> <span class="n">flashDebug</span><span class="o">(</span><span class="s1">&#39;JS -&amp;gt; Flash OK&#39;</span><span class="o">);</span> <span class="n">writeDebug</span><span class="o">(</span><span class="s1">&#39;JS to/from Flash OK&#39;</span><span class="o">);</span> <span class="n">ExternalInterface</span><span class="o">.</span><span class="na">call</span><span class="o">(</span><span class="n">baseJSController</span> <span class="o">+</span> <span class="s2">&quot;._setSandboxType&quot;</span><span class="o">,</span> <span class="n">sandboxType</span><span class="o">);</span> <span class="o">}</span> <span class="o">}</span> <span class="k">catch</span><span class="o">(</span><span class="n">e</span><span class="o">)</span> <span class="o">{</span> <span class="n">flashDebug</span><span class="o">(</span><span class="n">e</span><span class="o">.</span><span class="na">toString</span><span class="o">());</span> <span class="k">if</span> <span class="o">(!</span><span class="n">caughtFatal</span><span class="o">)</span> <span class="o">{</span> <span class="n">caughtFatal</span> <span class="o">=</span> <span class="kc">true</span><span class="o">;</span> <span class="o">}</span> <span class="k">return</span> <span class="kc">false</span><span class="o">;</span> <span class="o">}</span> <span class="k">return</span> <span class="kc">true</span><span class="o">;</span> <span class="c1">// to verify that a call from JS to here, works. (eg. JS receives &quot;true&quot;, thus OK.)</span> <span class="o">}</span> <span class="n">var</span> <span class="n">_disableDebug</span> <span class="o">=</span> <span class="kd">function</span><span class="o">()</span> <span class="o">{</span></pre></div> </td> </tr> <tr id='section-13'> <td class=docs> <div class="pilwrap"> <a class="pilcrow" href="#section-13">&#182;</a> </div> <p>prevent future debug calls from Flash going to client (maybe improve performance)</p> </td> <td class=code> <div class='highlight'><pre> <span class="n">writeDebug</span><span class="o">(</span><span class="s1">&#39;_disableDebug()&#39;</span><span class="o">);</span> <span class="n">debugEnabled</span> <span class="o">=</span> <span class="kc">false</span><span class="o">;</span> <span class="o">}</span> <span class="n">var</span> <span class="n">checkProgress</span> <span class="o">=</span> <span class="kd">function</span><span class="o">()</span> <span class="o">{</span> <span class="n">var</span> <span class="n">bL</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">var</span> <span class="n">bT</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">var</span> <span class="n">nD</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">var</span> <span class="n">nP</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">var</span> <span class="n">oSound</span> <span class="o">=</span> <span class="kc">null</span><span class="o">;</span> <span class="k">for</span> <span class="o">(</span><span class="n">var</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="o">,</span> <span class="n">j</span> <span class="o">=</span> <span class="n">sounds</span><span class="o">.</span><span class="na">length</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">j</span><span class="o">;</span> <span class="n">i</span><span class="o">++)</span> <span class="o">{</span> <span class="n">oSound</span> <span class="o">=</span> <span class="n">soundObjects</span><span class="o">[</span><span class="n">sounds</span><span class="o">[</span><span class="n">i</span><span class="o">]];</span> <span class="n">bL</span> <span class="o">=</span> <span class="n">oSound</span><span class="o">.</span><span class="na">getBytesLoaded</span><span class="o">();</span> <span class="n">bT</span> <span class="o">=</span> <span class="n">oSound</span><span class="o">.</span><span class="na">getBytesTotal</span><span class="o">();</span> <span class="n">nD</span> <span class="o">=</span> <span class="n">oSound</span><span class="o">.</span><span class="na">duration</span> <span class="o">||</span> <span class="mi">0</span><span class="o">;</span> <span class="c1">// can sometimes be null with short MP3s? Wack.</span> <span class="n">nP</span> <span class="o">=</span> <span class="n">oSound</span><span class="o">.</span><span class="na">position</span><span class="o">;</span> <span class="k">if</span> <span class="o">(</span><span class="n">bL</span> <span class="o">&amp;&amp;</span> <span class="n">bT</span> <span class="o">&amp;&amp;</span> <span class="n">bL</span> <span class="o">!=</span> <span class="n">oSound</span><span class="o">.</span><span class="na">lastValues</span><span class="o">.</span><span class="na">bytes</span><span class="o">)</span> <span class="o">{</span> <span class="n">oSound</span><span class="o">.</span><span class="na">lastValues</span><span class="o">.</span><span class="na">bytes</span> <span class="o">=</span> <span class="n">bL</span><span class="o">;</span> <span class="n">ExternalInterface</span><span class="o">.</span><span class="na">call</span><span class="o">(</span><span class="n">baseJSObject</span> <span class="o">+</span> <span class="s2">&quot;[&#39;&quot;</span> <span class="o">+</span> <span class="n">oSound</span><span class="o">.</span><span class="na">sID</span> <span class="o">+</span> <span class="s2">&quot;&#39;]._whileloading&quot;</span><span class="o">,</span> <span class="n">bL</span><span class="o">,</span> <span class="n">bT</span><span class="o">,</span> <span class="n">nD</span><span class="o">);</span> <span class="o">}</span> <span class="k">if</span> <span class="o">(</span><span class="k">typeof</span> <span class="n">nP</span> <span class="o">!=</span> <span class="s1">&#39;undefined&#39;</span> <span class="o">&amp;&amp;</span> <span class="n">nP</span> <span class="o">!=</span> <span class="n">oSound</span><span class="o">.</span><span class="na">lastValues</span><span class="o">.</span><span class="na">position</span><span class="o">)</span> <span class="o">{</span> <span class="n">oSound</span><span class="o">.</span><span class="na">lastValues</span><span class="o">.</span><span class="na">position</span> <span class="o">=</span> <span class="n">nP</span><span class="o">;</span> <span class="n">ExternalInterface</span><span class="o">.</span><span class="na">call</span><span class="o">(</span><span class="n">baseJSObject</span> <span class="o">+</span> <span class="s2">&quot;[&#39;&quot;</span> <span class="o">+</span> <span class="n">oSound</span><span class="o">.</span><span class="na">sID</span> <span class="o">+</span> <span class="s2">&quot;&#39;]._whileplaying&quot;</span><span class="o">,</span> <span class="n">nP</span><span class="o">);</span></pre></div> </td> </tr> <tr id='section-14'> <td class=docs> <div class="pilwrap"> <a class="pilcrow" href="#section-14">&#182;</a> </div> <p>if position changed, check for near-end</p> </td> <td class=code> <div class='highlight'><pre> <span class="o">}</span> <span class="o">}</span> <span class="o">}</span> <span class="n">var</span> <span class="n">onLoad</span> <span class="o">=</span> <span class="kd">function</span><span class="o">(</span><span class="n">bSuccess</span><span class="o">)</span> <span class="o">{</span> <span class="n">checkProgress</span><span class="o">();</span> <span class="c1">// ensure progress stats are up-to-date</span></pre></div> </td> </tr> <tr id='section-15'> <td class=docs> <div class="pilwrap"> <a class="pilcrow" href="#section-15">&#182;</a> </div> <p>force duration update (doesn&rsquo;t seem to be always accurate)</p> </td> <td class=code> <div class='highlight'><pre> <span class="n">ExternalInterface</span><span class="o">.</span><span class="na">call</span><span class="o">(</span><span class="n">baseJSObject</span> <span class="o">+</span> <span class="s2">&quot;[&#39;&quot;</span> <span class="o">+</span> <span class="k">this</span><span class="o">.</span><span class="na">sID</span> <span class="o">+</span> <span class="s2">&quot;&#39;]._whileloading&quot;</span><span class="o">,</span> <span class="k">this</span><span class="o">.</span><span class="na">getBytesLoaded</span><span class="o">(),</span> <span class="k">this</span><span class="o">.</span><span class="na">getBytesTotal</span><span class="o">(),</span> <span class="k">this</span><span class="o">.</span><span class="na">duration</span><span class="o">);</span> <span class="n">ExternalInterface</span><span class="o">.</span><span class="na">call</span><span class="o">(</span><span class="n">baseJSObject</span> <span class="o">+</span> <span class="s2">&quot;[&#39;&quot;</span> <span class="o">+</span> <span class="k">this</span><span class="o">.</span><span class="na">sID</span> <span class="o">+</span> <span class="s2">&quot;&#39;]._onload&quot;</span><span class="o">,</span> <span class="k">this</span><span class="o">.</span><span class="na">duration</span> <span class="o">&gt;</span> <span class="mi">0</span> <span class="o">?</span> <span class="mi">1</span> <span class="o">:</span> <span class="mi">0</span><span class="o">);</span> <span class="c1">// bSuccess doesn&#39;t always seem to work, so check MP3 duration instead.</span> <span class="o">}</span> <span class="n">var</span> <span class="n">onID3</span> <span class="o">=</span> <span class="kd">function</span><span class="o">()</span> <span class="o">{</span></pre></div> </td> </tr> <tr id='section-&amp;mdash;&amp;ndash;_NOTE:_BUGGY?_&amp;mdash;&amp;ndash;'> <td class=docs> <div class="pilwrap"> <a class="pilcrow" href="#section-&amp;mdash;&amp;ndash;_NOTE:_BUGGY?_&amp;mdash;&amp;ndash;">&#182;</a> </div> <h2>&mdash;&ndash; NOTE: BUGGY? &mdash;&ndash;</h2> <p>TODO: Investigate holes in ID3 parsing &ndash; for some reason, Album will be populated with Date if empty and date is provided. (?) ID3V1 seem to parse OK, but &ldquo;holes&rdquo; / blanks in ID3V2 data seem to get messed up (eg. missing album gets filled with date.) iTunes issues: onID3 was not called with a test MP3 encoded with iTunes 7.01, and what appeared to be valid ID3V2 data. May be related to thumbnails for album art included in MP3 file by iTunes. See http://mabblog.com/blog/?p=33</p> </td> <td class=code> <div class='highlight'><pre> <span class="n">var</span> <span class="n">id3Data</span> <span class="o">=</span> <span class="o">[];</span> <span class="n">var</span> <span class="n">id3Props</span> <span class="o">=</span> <span class="o">[];</span> <span class="k">for</span> <span class="o">(</span><span class="n">var</span> <span class="n">prop</span> <span class="k">in</span> <span class="k">this</span><span class="o">.</span><span class="na">id3</span><span class="o">)</span> <span class="o">{</span> <span class="n">id3Props</span><span class="o">.</span><span class="na">push</span><span class="o">(</span><span class="n">prop</span><span class="o">);</span> <span class="n">id3Data</span><span class="o">.</span><span class="na">push</span><span class="o">(</span><span class="k">this</span><span class="o">.</span><span class="na">id3</span><span class="o">[</span><span class="n">prop</span><span class="o">]);</span></pre></div> </td> </tr> <tr id='section-17'> <td class=docs> <div class="pilwrap"> <a class="pilcrow" href="#section-17">&#182;</a> </div> <p>writeDebug(&lsquo;id3[&rsquo;+prop+&lsquo;]: &rsquo;+this.id3[prop]);</p> </td> <td class=code> <div class='highlight'><pre> <span class="o">}</span> <span class="n">ExternalInterface</span><span class="o">.</span><span class="na">call</span><span class="o">(</span><span class="n">baseJSObject</span> <span class="o">+</span> <span class="s2">&quot;[&#39;&quot;</span> <span class="o">+</span> <span class="k">this</span><span class="o">.</span><span class="na">sID</span> <span class="o">+</span> <span class="s2">&quot;&#39;]._onid3&quot;</span><span class="o">,</span> <span class="n">id3Props</span><span class="o">,</span> <span class="n">id3Data</span><span class="o">);</span></pre></div> </td> </tr> <tr id='section-18'> <td class=docs> <div class="pilwrap"> <a class="pilcrow" href="#section-18">&#182;</a> </div> <p>unhook own event handler, prevent second call (can fire twice as data is received &ndash; ID3V2 at beginning, ID3V1 at end.) Therefore if ID3V2 data is received, ID3V1 is ignored.</p> </td> <td class=code> <div class='highlight'><pre> <span class="n">soundObjects</span><span class="o">[</span><span class="k">this</span><span class="o">.</span><span class="na">sID</span><span class="o">].</span><span class="n">onID3</span> <span class="o">=</span> <span class="kc">null</span><span class="o">;</span> <span class="o">}</span> <span class="n">var</span> <span class="n">registerOnComplete</span> <span class="o">=</span> <span class="kd">function</span><span class="o">(</span><span class="n">sID</span><span class="o">)</span> <span class="o">{</span> <span class="n">soundObjects</span><span class="o">[</span><span class="n">sID</span><span class="o">].</span><span class="n">onSoundComplete</span> <span class="o">=</span> <span class="kd">function</span><span class="o">()</span> <span class="o">{</span> <span class="n">checkProgress</span><span class="o">();</span> <span class="n">ExternalInterface</span><span class="o">.</span><span class="na">call</span><span class="o">(</span><span class="n">baseJSObject</span> <span class="o">+</span> <span class="s2">&quot;[&#39;&quot;</span> <span class="o">+</span> <span class="n">sID</span> <span class="o">+</span> <span class="s2">&quot;&#39;]._onfinish&quot;</span><span class="o">);</span> <span class="o">}</span> <span class="o">}</span> <span class="n">var</span> <span class="n">_setPosition</span> <span class="o">=</span> <span class="kd">function</span><span class="o">(</span><span class="n">sID</span><span class="o">,</span> <span class="n">nSecOffset</span><span class="o">,</span> <span class="n">isPaused</span><span class="o">)</span> <span class="o">{</span> <span class="n">var</span> <span class="n">s</span> <span class="o">=</span> <span class="n">soundObjects</span><span class="o">[</span><span class="n">sID</span><span class="o">];</span></pre></div> </td> </tr> <tr id='section-19'> <td class=docs> <div class="pilwrap"> <a class="pilcrow" href="#section-19">&#182;</a> </div> <p>writeDebug(&lsquo;_setPosition()&rsquo;);</p> </td> <td class=code> <div class='highlight'><pre> <span class="n">s</span><span class="o">.</span><span class="na">lastValues</span><span class="o">.</span><span class="na">position</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="na">position</span><span class="o">;</span> <span class="k">if</span> <span class="o">(</span><span class="n">s</span><span class="o">.</span><span class="na">lastValues</span><span class="o">.</span><span class="na">loops</span> <span class="o">&gt;</span> <span class="mi">1</span> <span class="o">&amp;&amp;</span> <span class="n">nSecOffset</span> <span class="o">!=</span> <span class="mi">0</span><span class="o">)</span> <span class="o">{</span> <span class="n">writeDebug</span><span class="o">(</span><span class="s1">&#39;Warning: Looping functionality being disabled due to Flash limitation.&#39;</span><span class="o">);</span> <span class="n">s</span><span class="o">.</span><span class="na">lastValues</span><span class="o">.</span><span class="na">loops</span> <span class="o">=</span> <span class="mi">1</span><span class="o">;</span> <span class="o">}</span> <span class="n">s</span><span class="o">.</span><span class="na">start</span><span class="o">(</span><span class="n">nSecOffset</span><span class="o">,</span> <span class="n">s</span><span class="o">.</span><span class="na">lastValues</span><span class="o">.</span><span class="na">nLoops</span> <span class="o">||</span> <span class="mi">1</span><span class="o">);</span> <span class="c1">// start playing at new position</span> <span class="k">if</span> <span class="o">(</span><span class="n">isPaused</span><span class="o">)</span> <span class="o">{</span> <span class="n">s</span><span class="o">.</span><span class="na">stop</span><span class="o">();</span> <span class="o">}</span> <span class="o">}</span> <span class="n">var</span> <span class="n">_load</span> <span class="o">=</span> <span class="kd">function</span><span class="o">(</span><span class="n">sID</span><span class="o">,</span> <span class="n">sURL</span><span class="o">,</span> <span class="n">bStream</span><span class="o">,</span> <span class="n">bAutoPlay</span><span class="o">,</span> <span class="n">bCheckPolicyFile</span><span class="o">)</span> <span class="o">{</span></pre></div> </td> </tr> <tr id='section-20'> <td class=docs> <div class="pilwrap"> <a class="pilcrow" href="#section-20">&#182;</a> </div> <p>writeDebug(&lsquo;_load(): &rsquo;+sID+&lsquo;, &rsquo;+sURL+&lsquo;, &rsquo;+bStream+&lsquo;, &rsquo;+bAutoPlay);</p> </td> <td class=code> <div class='highlight'><pre> <span class="k">if</span> <span class="o">(</span><span class="k">typeof</span> <span class="n">bAutoPlay</span> <span class="o">==</span> <span class="s1">&#39;undefined&#39;</span><span class="o">)</span> <span class="o">{</span> <span class="n">bAutoPlay</span> <span class="o">=</span> <span class="kc">false</span><span class="o">;</span> <span class="o">}</span> <span class="k">if</span> <span class="o">(</span><span class="k">typeof</span> <span class="n">bStream</span> <span class="o">==</span> <span class="s1">&#39;undefined&#39;</span><span class="o">)</span> <span class="o">{</span> <span class="n">bStream</span> <span class="o">=</span> <span class="kc">true</span><span class="o">;</span> <span class="o">}</span> <span class="k">if</span> <span class="o">(</span><span class="k">typeof</span> <span class="n">bCheckPolicyFile</span> <span class="o">==</span> <span class="s1">&#39;undefined&#39;</span><span class="o">)</span> <span class="o">{</span> <span class="n">bCheckPolicyFile</span> <span class="o">=</span> <span class="kc">false</span><span class="o">;</span> <span class="o">}</span></pre></div> </td> </tr> <tr id='section-21'> <td class=docs> <div class="pilwrap"> <a class="pilcrow" href="#section-21">&#182;</a> </div> <p>writeDebug(&lsquo;bStream: &rsquo;+bStream); writeDebug(&lsquo;bAutoPlay: &rsquo;+bAutoPlay); checkProgress();</p> </td> <td class=code> <div class='highlight'><pre> <span class="n">var</span> <span class="n">s</span> <span class="o">=</span> <span class="n">soundObjects</span><span class="o">[</span><span class="n">sID</span><span class="o">];</span> <span class="n">s</span><span class="o">.</span><span class="na">onID3</span> <span class="o">=</span> <span class="n">onID3</span><span class="o">;</span> <span class="n">s</span><span class="o">.</span><span class="na">onLoad</span> <span class="o">=</span> <span class="n">onLoad</span><span class="o">;</span> <span class="n">s</span><span class="o">.</span><span class="na">loaded</span> <span class="o">=</span> <span class="kc">true</span><span class="o">;</span> <span class="n">s</span><span class="o">.</span><span class="na">checkPolicyFile</span> <span class="o">=</span> <span class="n">bCheckPolicyFile</span><span class="o">;</span> <span class="n">s</span><span class="o">.</span><span class="na">loadSound</span><span class="o">(</span><span class="n">sURL</span><span class="o">,</span> <span class="n">bStream</span><span class="o">);</span> <span class="k">if</span> <span class="o">(</span><span class="n">bAutoPlay</span> <span class="o">!=</span> <span class="kc">true</span><span class="o">)</span> <span class="o">{</span> <span class="n">s</span><span class="o">.</span><span class="na">stop</span><span class="o">();</span> <span class="c1">// prevent default auto-play behaviour</span> <span class="o">}</span> <span class="k">else</span> <span class="o">{</span> <span class="n">writeDebug</span><span class="o">(</span><span class="s1">&#39;auto-play allowed&#39;</span><span class="o">);</span> <span class="o">}</span> <span class="n">registerOnComplete</span><span class="o">(</span><span class="n">sID</span><span class="o">);</span> <span class="o">}</span> <span class="n">var</span> <span class="n">_unload</span> <span class="o">=</span> <span class="kd">function</span><span class="o">(</span><span class="n">sID</span><span class="o">,</span> <span class="n">sURL</span><span class="o">)</span> <span class="o">{</span></pre></div> </td> </tr> <tr id='section-22'> <td class=docs> <div class="pilwrap"> <a class="pilcrow" href="#section-22">&#182;</a> </div> <p>effectively &ldquo;stop&rdquo; loading by loading a tiny MP3</p> </td> <td class=code> <div class='highlight'><pre> <span class="n">var</span> <span class="n">s</span> <span class="o">=</span> <span class="n">soundObjects</span><span class="o">[</span><span class="n">sID</span><span class="o">];</span> <span class="n">s</span><span class="o">.</span><span class="na">onID3</span> <span class="o">=</span> <span class="kc">null</span><span class="o">;</span> <span class="n">s</span><span class="o">.</span><span class="na">onLoad</span> <span class="o">=</span> <span class="kc">null</span><span class="o">;</span> <span class="n">s</span><span class="o">.</span><span class="na">loaded</span> <span class="o">=</span> <span class="kc">false</span><span class="o">;</span></pre></div> </td> </tr> <tr id='section-23'> <td class=docs> <div class="pilwrap"> <a class="pilcrow" href="#section-23">&#182;</a> </div> <p>ensure position is reset, if unload fails</p> </td> <td class=code> <div class='highlight'><pre> <span class="n">s</span><span class="o">.</span><span class="na">start</span><span class="o">(</span><span class="mi">0</span><span class="o">,</span><span class="mi">1</span><span class="o">);</span> <span class="n">s</span><span class="o">.</span><span class="na">stop</span><span class="o">();</span> <span class="n">s</span><span class="o">.</span><span class="na">loadSound</span><span class="o">(</span><span class="n">sURL</span><span class="o">,</span> <span class="kc">true</span><span class="o">);</span> <span class="n">s</span><span class="o">.</span><span class="na">stop</span><span class="o">();</span> <span class="c1">// prevent auto-play</span> <span class="o">}</span> <span class="n">var</span> <span class="n">_createSound</span> <span class="o">=</span> <span class="kd">function</span><span class="o">(</span><span class="n">sID</span><span class="o">,</span> <span class="n">loops</span><span class="o">,</span> <span class="n">checkPolicyFile</span><span class="o">)</span> <span class="o">{</span> <span class="n">var</span> <span class="n">s</span> <span class="o">=</span> <span class="k">new</span> <span class="kt">Sound</span><span class="o">();</span> <span class="k">if</span> <span class="o">(!</span><span class="n">soundObjects</span><span class="o">[</span><span class="n">sID</span><span class="o">])</span> <span class="o">{</span> <span class="n">sounds</span><span class="o">.</span><span class="na">push</span><span class="o">(</span><span class="n">sID</span><span class="o">);</span> <span class="o">}</span> <span class="n">soundObjects</span><span class="o">[</span><span class="n">sID</span><span class="o">]</span> <span class="o">=</span> <span class="n">s</span><span class="o">;</span> <span class="n">s</span><span class="o">.</span><span class="na">setVolume</span><span class="o">(</span><span class="mi">100</span><span class="o">);</span> <span class="n">s</span><span class="o">.</span><span class="na">sID</span> <span class="o">=</span> <span class="n">sID</span><span class="o">;</span> <span class="n">s</span><span class="o">.</span><span class="na">paused</span> <span class="o">=</span> <span class="kc">false</span><span class="o">;</span> <span class="n">s</span><span class="o">.</span><span class="na">loaded</span> <span class="o">=</span> <span class="kc">false</span><span class="o">;</span> <span class="n">s</span><span class="o">.</span><span class="na">checkPolicyFile</span> <span class="o">=</span> <span class="n">checkPolicyFile</span><span class="o">;</span> <span class="n">s</span><span class="o">.</span><span class="na">lastValues</span> <span class="o">=</span> <span class="o">{</span> <span class="n">bytes</span><span class="o">:</span> <span class="mi">0</span><span class="o">,</span> <span class="n">position</span><span class="o">:</span> <span class="mi">0</span><span class="o">,</span> <span class="n">nLoops</span><span class="o">:</span> <span class="n">loops</span><span class="o">||</span><span class="mi">1</span> <span class="o">};</span> <span class="o">}</span> <span class="n">var</span> <span class="n">_destroySound</span> <span class="o">=</span> <span class="kd">function</span><span class="o">(</span><span class="n">sID</span><span class="o">)</span> <span class="o">{</span></pre></div> </td> </tr> <tr id='section-24'> <td class=docs> <div class="pilwrap"> <a class="pilcrow" href="#section-24">&#182;</a> </div> <p>for the power of garbage collection! .. er, Greyskull!</p> </td> <td class=code> <div class='highlight'><pre> <span class="n">var</span> <span class="n">s</span> <span class="o">=</span> <span class="o">(</span><span class="n">soundObjects</span><span class="o">[</span><span class="n">sID</span><span class="o">]</span> <span class="o">||</span> <span class="kc">null</span><span class="o">);</span> <span class="k">if</span> <span class="o">(!</span><span class="n">s</span><span class="o">)</span> <span class="o">{</span> <span class="k">return</span> <span class="kc">false</span><span class="o">;</span> <span class="o">}</span> <span class="k">for</span> <span class="o">(</span><span class="n">var</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">sounds</span><span class="o">.</span><span class="na">length</span><span class="o">;</span> <span class="n">i</span><span class="o">++)</span> <span class="o">{</span> <span class="k">if</span> <span class="o">(</span><span class="n">sounds</span><span class="o">[</span><span class="n">i</span><span class="o">]</span> <span class="o">==</span> <span class="n">sID</span><span class="o">)</span> <span class="o">{</span> <span class="n">sounds</span><span class="o">.</span><span class="na">splice</span><span class="o">(</span><span class="n">i</span><span class="o">,</span> <span class="mi">1</span><span class="o">);</span> <span class="k">break</span><span class="o">;</span> <span class="o">}</span> <span class="o">}</span> <span class="n">s</span> <span class="o">=</span> <span class="kc">null</span><span class="o">;</span> <span class="n">delete</span> <span class="n">soundObjects</span><span class="o">[</span><span class="n">sID</span><span class="o">];</span> <span class="o">}</span> <span class="n">var</span> <span class="n">_stop</span> <span class="o">=</span> <span class="kd">function</span><span class="o">(</span><span class="n">sID</span><span class="o">,</span> <span class="n">bStopAll</span><span class="o">)</span> <span class="o">{</span></pre></div> </td> </tr> <tr id='section-25'> <td class=docs> <div class="pilwrap"> <a class="pilcrow" href="#section-25">&#182;</a> </div> <p>stop this particular instance (or &ldquo;all&rdquo;, based on parameter)</p> </td> <td class=code> <div class='highlight'><pre> <span class="k">if</span> <span class="o">(</span><span class="n">bStopAll</span><span class="o">)</span> <span class="o">{</span> <span class="n">_root</span><span class="o">.</span><span class="na">stop</span><span class="o">();</span> <span class="o">}</span> <span class="k">else</span> <span class="o">{</span> <span class="n">soundObjects</span><span class="o">[</span><span class="n">sID</span><span class="o">].</span><span class="n">stop</span><span class="o">();</span> <span class="n">soundObjects</span><span class="o">[</span><span class="n">sID</span><span class="o">].</span><span class="n">paused</span> <span class="o">=</span> <span class="kc">false</span><span class="o">;</span> <span class="o">}</span> <span class="o">}</span> <span class="n">var</span> <span class="n">_start</span> <span class="o">=</span> <span class="kd">function</span><span class="o">(</span><span class="n">sID</span><span class="o">,</span> <span class="n">nLoops</span><span class="o">,</span> <span class="n">nMsecOffset</span><span class="o">)</span> <span class="o">{</span></pre></div> </td> </tr> <tr id='section-26'> <td class=docs> <div class="pilwrap"> <a class="pilcrow" href="#section-26">&#182;</a> </div> <p>writeDebug(&lsquo;_start: &rsquo; + sID + &lsquo;, loops: &rsquo; + nLoops + &lsquo;, nMsecOffset: &rsquo; + nMsecOffset);</p> </td> <td class=code> <div class='highlight'><pre> <span class="n">registerOnComplete</span><span class="o">();</span> <span class="n">var</span> <span class="n">s</span> <span class="o">=</span> <span class="n">soundObjects</span><span class="o">[</span><span class="n">sID</span><span class="o">];</span> <span class="n">s</span><span class="o">.</span><span class="na">lastValues</span><span class="o">.</span><span class="na">paused</span> <span class="o">=</span> <span class="kc">false</span><span class="o">;</span> <span class="c1">// reset pause if applicable</span> <span class="n">s</span><span class="o">.</span><span class="na">lastValues</span><span class="o">.</span><span class="na">nLoops</span> <span class="o">=</span> <span class="o">(</span><span class="n">nLoops</span> <span class="o">||</span> <span class="mi">1</span><span class="o">);</span> <span class="n">s</span><span class="o">.</span><span class="na">start</span><span class="o">(</span><span class="n">nMsecOffset</span><span class="o">,</span> <span class="n">nLoops</span><span class="o">);</span> <span class="o">}</span> <span class="n">var</span> <span class="n">_pause</span> <span class="o">=</span> <span class="kd">function</span><span class="o">(</span><span class="n">sID</span><span class="o">)</span> <span class="o">{</span></pre></div> </td> </tr> <tr id='section-27'> <td class=docs> <div class="pilwrap"> <a class="pilcrow" href="#section-27">&#182;</a> </div> <p>writeDebug(&lsquo;_pause()&rsquo;);</p> </td> <td class=code> <div class='highlight'><pre> <span class="n">var</span> <span class="n">s</span> <span class="o">=</span> <span class="n">soundObjects</span><span class="o">[</span><span class="n">sID</span><span class="o">];</span> <span class="k">if</span> <span class="o">(!</span><span class="n">s</span><span class="o">.</span><span class="na">paused</span><span class="o">)</span> <span class="o">{</span></pre></div> </td> </tr> <tr id='section-28'> <td class=docs> <div class="pilwrap"> <a class="pilcrow" href="#section-28">&#182;</a> </div> <p>reference current position, stop sound</p> </td> <td class=code> <div class='highlight'><pre> <span class="n">s</span><span class="o">.</span><span class="na">paused</span> <span class="o">=</span> <span class="kc">true</span><span class="o">;</span> <span class="n">s</span><span class="o">.</span><span class="na">lastValues</span><span class="o">.</span><span class="na">position</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="na">position</span><span class="o">;</span></pre></div> </td> </tr> <tr id='section-29'> <td class=docs> <div class="pilwrap"> <a class="pilcrow" href="#section-29">&#182;</a> </div> <p>writeDebug(&lsquo;_pause(): position: &rsquo;+s.lastValues.position);</p> </td> <td class=code> <div class='highlight'><pre> <span class="n">s</span><span class="o">.</span><span class="na">stop</span><span class="o">();</span> <span class="o">}</span> <span class="k">else</span> <span class="o">{</span></pre></div> </td> </tr> <tr id='section-30'> <td class=docs> <div class="pilwrap"> <a class="pilcrow" href="#section-30">&#182;</a> </div> <p>resume playing from last position writeDebug(&lsquo;resuming &ndash; playing at &rsquo;+s.lastValues.position+&lsquo;, &rsquo;+s.lastValues.nLoops+&lsquo; times&rsquo;);</p> </td> <td class=code> <div class='highlight'><pre> <span class="n">s</span><span class="o">.</span><span class="na">paused</span> <span class="o">=</span> <span class="kc">false</span><span class="o">;</span> <span class="n">s</span><span class="o">.</span><span class="na">start</span><span class="o">(</span><span class="n">s</span><span class="o">.</span><span class="na">lastValues</span><span class="o">.</span><span class="na">position</span> <span class="o">/</span> <span class="mi">1000</span><span class="o">,</span> <span class="n">s</span><span class="o">.</span><span class="na">lastValues</span><span class="o">.</span><span class="na">nLoops</span><span class="o">);</span> <span class="o">}</span> <span class="o">}</span> <span class="n">var</span> <span class="n">_setPan</span> <span class="o">=</span> <span class="kd">function</span><span class="o">(</span><span class="n">sID</span><span class="o">,</span> <span class="n">nPan</span><span class="o">)</span> <span class="o">{</span> <span class="n">soundObjects</span><span class="o">[</span><span class="n">sID</span><span class="o">].</span><span class="n">setPan</span><span class="o">(</span><span class="n">nPan</span><span class="o">);</span> <span class="o">}</span> <span class="n">var</span> <span class="n">_setVolume</span> <span class="o">=</span> <span class="kd">function</span><span class="o">(</span><span class="n">sID</span><span class="o">,</span> <span class="n">nVol</span><span class="o">)</span> <span class="o">{</span> <span class="n">soundObjects</span><span class="o">[</span><span class="n">sID</span><span class="o">].</span><span class="n">setVolume</span><span class="o">(</span><span class="n">nVol</span><span class="o">);</span> <span class="o">}</span> <span class="n">var</span> <span class="n">_setPolling</span> <span class="o">=</span> <span class="kd">function</span><span class="o">(</span><span class="n">bPolling</span><span class="o">,</span> <span class="n">timerInterval</span><span class="o">)</span> <span class="o">{</span> <span class="k">if</span> <span class="o">(</span><span class="k">typeof</span> <span class="n">timerInterval</span> <span class="o">===</span> <span class="s1">&#39;undefined&#39;</span><span class="o">)</span> <span class="o">{</span> <span class="n">timerInterval</span> <span class="o">=</span> <span class="mi">50</span><span class="o">;</span> <span class="o">}</span> <span class="n">pollingEnabled</span> <span class="o">=</span> <span class="n">bPolling</span><span class="o">;</span> <span class="k">if</span> <span class="o">(</span><span class="n">timer</span> <span class="o">==</span> <span class="kc">null</span> <span class="o">&amp;&amp;</span> <span class="n">pollingEnabled</span><span class="o">)</span> <span class="o">{</span> <span class="n">writeDebug</span><span class="o">(</span><span class="s1">&#39;Enabling polling, &#39;</span> <span class="o">+</span> <span class="n">timerInterval</span> <span class="o">+</span> <span class="s1">&#39; ms interval&#39;</span><span class="o">);</span> <span class="n">timer</span> <span class="o">=</span> <span class="nf">setInterval</span><span class="o">(</span><span class="n">checkProgress</span><span class="o">,</span> <span class="n">timerInterval</span><span class="o">);</span> <span class="o">}</span> <span class="k">else</span> <span class="k">if</span> <span class="o">(</span><span class="n">timer</span> <span class="o">&amp;&amp;</span> <span class="o">!</span><span class="n">pollingEnabled</span><span class="o">)</span> <span class="o">{</span> <span class="n">writeDebug</span><span class="o">(</span><span class="s1">&#39;Disabling polling&#39;</span><span class="o">);</span> <span class="nf">clearInterval</span><span class="o">(</span><span class="n">timer</span><span class="o">);</span> <span class="n">timer</span> <span class="o">=</span> <span class="kc">null</span><span class="o">;</span> <span class="o">}</span> <span class="o">}</span> <span class="n">var</span> <span class="n">_init</span> <span class="o">=</span> <span class="kd">function</span><span class="o">()</span> <span class="o">{</span></pre></div> </td> </tr> <tr id='section-31'> <td class=docs> <div class="pilwrap"> <a class="pilcrow" href="#section-31">&#182;</a> </div> <p>OK now stuff should be available</p> </td> <td class=code> <div class='highlight'><pre> <span class="k">try</span> <span class="o">{</span> <span class="n">flashDebug</span><span class="o">(</span><span class="s1">&#39;Adding ExternalInterface callbacks...&#39;</span><span class="o">);</span> <span class="n">ExternalInterface</span><span class="o">.</span><span class="na">addCallback</span><span class="o">(</span><span class="s1">&#39;_load&#39;</span><span class="o">,</span> <span class="k">this</span><span class="o">,</span> <span class="n">_load</span><span class="o">);</span> <span class="n">ExternalInterface</span><span class="o">.</span><span class="na">addCallback</span><span class="o">(</span><span class="s1">&#39;_unload&#39;</span><span class="o">,</span> <span class="k">this</span><span class="o">,</span> <span class="n">_unload</span><span class="o">);</span> <span class="n">ExternalInterface</span><span class="o">.</span><span class="na">addCallback</span><span class="o">(</span><span class="s1">&#39;_stop&#39;</span><span class="o">,</span> <span class="k">this</span><span class="o">,</span> <span class="n">_stop</span><span class="o">);</span> <span class="n">ExternalInterface</span><span class="o">.</span><span class="na">addCallback</span><span class="o">(</span><span class="s1">&#39;_start&#39;</span><span class="o">,</span> <span class="k">this</span><span class="o">,</span> <span class="n">_start</span><span class="o">);</span> <span class="n">ExternalInterface</span><span class="o">.</span><span class="na">addCallback</span><span class="o">(</span><span class="s1">&#39;_pause&#39;</span><span class="o">,</span> <span class="k">this</span><span class="o">,</span> <span class="n">_pause</span><span class="o">);</span> <span class="n">ExternalInterface</span><span class="o">.</span><span class="na">addCallback</span><span class="o">(</span><span class="s1">&#39;_setPosition&#39;</span><span class="o">,</span> <span class="k">this</span><span class="o">,</span> <span class="n">_setPosition</span><span class="o">);</span> <span class="n">ExternalInterface</span><span class="o">.</span><span class="na">addCallback</span><span class="o">(</span><span class="s1">&#39;_setPan&#39;</span><span class="o">,</span> <span class="k">this</span><span class="o">,</span> <span class="n">_setPan</span><span class="o">);</span> <span class="n">ExternalInterface</span><span class="o">.</span><span class="na">addCallback</span><span class="o">(</span><span class="s1">&#39;_setVolume&#39;</span><span class="o">,</span> <span class="k">this</span><span class="o">,</span> <span class="n">_setVolume</span><span class="o">);</span> <span class="n">ExternalInterface</span><span class="o">.</span><span class="na">addCallback</span><span class="o">(</span><span class="s1">&#39;_setPolling&#39;</span><span class="o">,</span> <span class="k">this</span><span class="o">,</span> <span class="n">_setPolling</span><span class="o">);</span> <span class="n">ExternalInterface</span><span class="o">.</span><span class="na">addCallback</span><span class="o">(</span><span class="s1">&#39;_externalInterfaceTest&#39;</span><span class="o">,</span> <span class="k">this</span><span class="o">,</span> <span class="n">_externalInterfaceTest</span><span class="o">);</span> <span class="n">ExternalInterface</span><span class="o">.</span><span class="na">addCallback</span><span class="o">(</span><span class="s1">&#39;_disableDebug&#39;</span><span class="o">,</span> <span class="k">this</span><span class="o">,</span> <span class="n">_disableDebug</span><span class="o">);</span> <span class="n">ExternalInterface</span><span class="o">.</span><span class="na">addCallback</span><span class="o">(</span><span class="s1">&#39;_createSound&#39;</span><span class="o">,</span> <span class="k">this</span><span class="o">,</span> <span class="n">_createSound</span><span class="o">);</span> <span class="n">ExternalInterface</span><span class="o">.</span><span class="na">addCallback</span><span class="o">(</span><span class="s1">&#39;_destroySound&#39;</span><span class="o">,</span> <span class="k">this</span><span class="o">,</span> <span class="n">_destroySound</span><span class="o">);</span> <span class="o">}</span> <span class="k">catch</span><span class="o">(</span><span class="n">e</span><span class="o">)</span> <span class="o">{</span> <span class="n">flashDebug</span><span class="o">(</span><span class="s1">&#39;Fatal: ExternalInterface error: &#39;</span> <span class="o">+</span> <span class="n">e</span><span class="o">.</span><span class="na">toString</span><span class="o">());</span> <span class="o">}</span></pre></div> </td> </tr> <tr id='section-32'> <td class=docs> <div class="pilwrap"> <a class="pilcrow" href="#section-32">&#182;</a> </div> <p>try to talk to JS, do init etc.</p> </td> <td class=code> <div class='highlight'><pre> <span class="n">_externalInterfaceTest</span><span class="o">(</span><span class="kc">true</span><span class="o">);</span></pre></div> </td> </tr> <tr id='section-33'> <td class=docs> <div class="pilwrap"> <a class="pilcrow" href="#section-33">&#182;</a> </div> <p>flashDebug(&lsquo;Init OK&rsquo;);</p> </td> <td class=code> <div class='highlight'><pre> <span class="o">}</span> <span class="n">flashDebug</span><span class="o">(</span><span class="s1">&#39;SM2 SWF &#39;</span> <span class="o">+</span> <span class="n">version</span> <span class="o">+</span> <span class="s1">&#39; &#39;</span> <span class="o">+</span> <span class="n">version_as</span><span class="o">);</span> <span class="k">if</span> <span class="o">(</span><span class="n">ExternalInterface</span><span class="o">.</span><span class="na">available</span><span class="o">)</span> <span class="o">{</span> <span class="n">flashDebug</span><span class="o">(</span><span class="s1">&#39;ExternalInterface available&#39;</span><span class="o">);</span> <span class="n">_init</span><span class="o">();</span> <span class="o">}</span> <span class="k">else</span> <span class="o">{</span></pre></div> </td> </tr> <tr id='section-34'> <td class=docs> <div class="pilwrap"> <a class="pilcrow" href="#section-34">&#182;</a> </div> <p>d'oh! &ndash; may be from a corrupt install, ancient (pre-Netscape 6?) browser etc.</p> </td> <td class=code> <div class='highlight'><pre> <span class="n">flashDebug</span><span class="o">(</span><span class="s1">&#39;Fatal: ExternalInterface (Flash &amp;lt;-&amp;gt; JS) not available&#39;</span><span class="o">);</span> <span class="o">}</span> <span class="o">}</span> <span class="c1">// SoundManager2()</span></pre></div> </td> </tr> <tr id='section-35'> <td class=docs> <div class="pilwrap"> <a class="pilcrow" href="#section-35">&#182;</a> </div> <p>entry point</p> </td> <td class=code> <div class='highlight'><pre> <span class="kd">static</span> <span class="kd">function </span><span class="nf">main</span><span class="o">(</span><span class="err">mc</span><span class="o">)</span> <span class="o">{</span> <span class="n">app</span> <span class="o">=</span> <span class="k">new</span> <span class="kt">SoundManager2</span><span class="o">();</span> <span class="o">}</span> <span class="o">}</span></pre></div> </td> </tr> </table> </div> </body>
{ "content_hash": "7fc24176ef503a7c98e68fd6f1e8d077", "timestamp": "", "source": "github", "line_count": 946, "max_line_length": 961, "avg_line_length": 80.73044397463002, "alnum_prop": 0.5893074596378206, "repo_name": "LeoDutra/SoundManager2", "id": "d4d702fc4a204c93baf99cf29225ffc7002b4983", "size": "76371", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "doc/generated/src/SoundManager2.html", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
//===--- CFG.cpp - Classes for representing and building CFGs----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the CFG and CFGBuilder classes for representing and // building Control-Flow Graphs (CFGs) from ASTs. // //===----------------------------------------------------------------------===// #include "clang/Analysis/CFG.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Attr.h" #include "clang/AST/CharUnits.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/PrettyPrinter.h" #include "clang/AST/StmtVisitor.h" #include "clang/Basic/Builtins.h" #include "llvm/ADT/DenseMap.h" #include <memory> #include "llvm/ADT/SmallPtrSet.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/Format.h" #include "llvm/Support/GraphWriter.h" #include "llvm/Support/SaveAndRestore.h" using namespace clang; namespace { static SourceLocation GetEndLoc(Decl *D) { if (VarDecl *VD = dyn_cast<VarDecl>(D)) if (Expr *Ex = VD->getInit()) return Ex->getSourceRange().getEnd(); return D->getLocation(); } class CFGBuilder; /// The CFG builder uses a recursive algorithm to build the CFG. When /// we process an expression, sometimes we know that we must add the /// subexpressions as block-level expressions. For example: /// /// exp1 || exp2 /// /// When processing the '||' expression, we know that exp1 and exp2 /// need to be added as block-level expressions, even though they /// might not normally need to be. AddStmtChoice records this /// contextual information. If AddStmtChoice is 'NotAlwaysAdd', then /// the builder has an option not to add a subexpression as a /// block-level expression. /// class AddStmtChoice { public: enum Kind { NotAlwaysAdd = 0, AlwaysAdd = 1 }; AddStmtChoice(Kind a_kind = NotAlwaysAdd) : kind(a_kind) {} bool alwaysAdd(CFGBuilder &builder, const Stmt *stmt) const; /// Return a copy of this object, except with the 'always-add' bit /// set as specified. AddStmtChoice withAlwaysAdd(bool alwaysAdd) const { return AddStmtChoice(alwaysAdd ? AlwaysAdd : NotAlwaysAdd); } private: Kind kind; }; /// LocalScope - Node in tree of local scopes created for C++ implicit /// destructor calls generation. It contains list of automatic variables /// declared in the scope and link to position in previous scope this scope /// began in. /// /// The process of creating local scopes is as follows: /// - Init CFGBuilder::ScopePos with invalid position (equivalent for null), /// - Before processing statements in scope (e.g. CompoundStmt) create /// LocalScope object using CFGBuilder::ScopePos as link to previous scope /// and set CFGBuilder::ScopePos to the end of new scope, /// - On every occurrence of VarDecl increase CFGBuilder::ScopePos if it points /// at this VarDecl, /// - For every normal (without jump) end of scope add to CFGBlock destructors /// for objects in the current scope, /// - For every jump add to CFGBlock destructors for objects /// between CFGBuilder::ScopePos and local scope position saved for jump /// target. Thanks to C++ restrictions on goto jumps we can be sure that /// jump target position will be on the path to root from CFGBuilder::ScopePos /// (adding any variable that doesn't need constructor to be called to /// LocalScope can break this assumption), /// class LocalScope { public: typedef BumpVector<VarDecl*> AutomaticVarsTy; /// const_iterator - Iterates local scope backwards and jumps to previous /// scope on reaching the beginning of currently iterated scope. class const_iterator { const LocalScope* Scope; /// VarIter is guaranteed to be greater then 0 for every valid iterator. /// Invalid iterator (with null Scope) has VarIter equal to 0. unsigned VarIter; public: /// Create invalid iterator. Dereferencing invalid iterator is not allowed. /// Incrementing invalid iterator is allowed and will result in invalid /// iterator. const_iterator() : Scope(nullptr), VarIter(0) {} /// Create valid iterator. In case when S.Prev is an invalid iterator and /// I is equal to 0, this will create invalid iterator. const_iterator(const LocalScope& S, unsigned I) : Scope(&S), VarIter(I) { // Iterator to "end" of scope is not allowed. Handle it by going up // in scopes tree possibly up to invalid iterator in the root. if (VarIter == 0 && Scope) *this = Scope->Prev; } VarDecl *const* operator->() const { assert (Scope && "Dereferencing invalid iterator is not allowed"); assert (VarIter != 0 && "Iterator has invalid value of VarIter member"); return &Scope->Vars[VarIter - 1]; } VarDecl *operator*() const { return *this->operator->(); } const_iterator &operator++() { if (!Scope) return *this; assert (VarIter != 0 && "Iterator has invalid value of VarIter member"); --VarIter; if (VarIter == 0) *this = Scope->Prev; return *this; } const_iterator operator++(int) { const_iterator P = *this; ++*this; return P; } bool operator==(const const_iterator &rhs) const { return Scope == rhs.Scope && VarIter == rhs.VarIter; } bool operator!=(const const_iterator &rhs) const { return !(*this == rhs); } LLVM_EXPLICIT operator bool() const { return *this != const_iterator(); } int distance(const_iterator L); }; friend class const_iterator; private: BumpVectorContext ctx; /// Automatic variables in order of declaration. AutomaticVarsTy Vars; /// Iterator to variable in previous scope that was declared just before /// begin of this scope. const_iterator Prev; public: /// Constructs empty scope linked to previous scope in specified place. LocalScope(BumpVectorContext &ctx, const_iterator P) : ctx(ctx), Vars(ctx, 4), Prev(P) {} /// Begin of scope in direction of CFG building (backwards). const_iterator begin() const { return const_iterator(*this, Vars.size()); } void addVar(VarDecl *VD) { Vars.push_back(VD, ctx); } }; /// distance - Calculates distance from this to L. L must be reachable from this /// (with use of ++ operator). Cost of calculating the distance is linear w.r.t. /// number of scopes between this and L. int LocalScope::const_iterator::distance(LocalScope::const_iterator L) { int D = 0; const_iterator F = *this; while (F.Scope != L.Scope) { assert (F != const_iterator() && "L iterator is not reachable from F iterator."); D += F.VarIter; F = F.Scope->Prev; } D += F.VarIter - L.VarIter; return D; } /// BlockScopePosPair - Structure for specifying position in CFG during its /// build process. It consists of CFGBlock that specifies position in CFG graph /// and LocalScope::const_iterator that specifies position in LocalScope graph. struct BlockScopePosPair { BlockScopePosPair() : block(nullptr) {} BlockScopePosPair(CFGBlock *b, LocalScope::const_iterator scopePos) : block(b), scopePosition(scopePos) {} CFGBlock *block; LocalScope::const_iterator scopePosition; }; /// TryResult - a class representing a variant over the values /// 'true', 'false', or 'unknown'. This is returned by tryEvaluateBool, /// and is used by the CFGBuilder to decide if a branch condition /// can be decided up front during CFG construction. class TryResult { int X; public: TryResult(bool b) : X(b ? 1 : 0) {} TryResult() : X(-1) {} bool isTrue() const { return X == 1; } bool isFalse() const { return X == 0; } bool isKnown() const { return X >= 0; } void negate() { assert(isKnown()); X ^= 0x1; } }; TryResult bothKnownTrue(TryResult R1, TryResult R2) { if (!R1.isKnown() || !R2.isKnown()) return TryResult(); return TryResult(R1.isTrue() && R2.isTrue()); } class reverse_children { llvm::SmallVector<Stmt *, 12> childrenBuf; ArrayRef<Stmt*> children; public: reverse_children(Stmt *S); typedef ArrayRef<Stmt*>::reverse_iterator iterator; iterator begin() const { return children.rbegin(); } iterator end() const { return children.rend(); } }; reverse_children::reverse_children(Stmt *S) { if (CallExpr *CE = dyn_cast<CallExpr>(S)) { children = CE->getRawSubExprs(); return; } switch (S->getStmtClass()) { // Note: Fill in this switch with more cases we want to optimize. case Stmt::InitListExprClass: { InitListExpr *IE = cast<InitListExpr>(S); children = llvm::makeArrayRef(reinterpret_cast<Stmt**>(IE->getInits()), IE->getNumInits()); return; } default: break; } // Default case for all other statements. for (Stmt::child_range I = S->children(); I; ++I) { childrenBuf.push_back(*I); } // This needs to be done *after* childrenBuf has been populated. children = childrenBuf; } /// CFGBuilder - This class implements CFG construction from an AST. /// The builder is stateful: an instance of the builder should be used to only /// construct a single CFG. /// /// Example usage: /// /// CFGBuilder builder; /// CFG* cfg = builder.BuildAST(stmt1); /// /// CFG construction is done via a recursive walk of an AST. We actually parse /// the AST in reverse order so that the successor of a basic block is /// constructed prior to its predecessor. This allows us to nicely capture /// implicit fall-throughs without extra basic blocks. /// class CFGBuilder { typedef BlockScopePosPair JumpTarget; typedef BlockScopePosPair JumpSource; ASTContext *Context; std::unique_ptr<CFG> cfg; CFGBlock *Block; CFGBlock *Succ; JumpTarget ContinueJumpTarget; JumpTarget BreakJumpTarget; CFGBlock *SwitchTerminatedBlock; CFGBlock *DefaultCaseBlock; CFGBlock *TryTerminatedBlock; // Current position in local scope. LocalScope::const_iterator ScopePos; // LabelMap records the mapping from Label expressions to their jump targets. typedef llvm::DenseMap<LabelDecl*, JumpTarget> LabelMapTy; LabelMapTy LabelMap; // A list of blocks that end with a "goto" that must be backpatched to their // resolved targets upon completion of CFG construction. typedef std::vector<JumpSource> BackpatchBlocksTy; BackpatchBlocksTy BackpatchBlocks; // A list of labels whose address has been taken (for indirect gotos). typedef llvm::SmallPtrSet<LabelDecl*, 5> LabelSetTy; LabelSetTy AddressTakenLabels; bool badCFG; const CFG::BuildOptions &BuildOpts; // State to track for building switch statements. bool switchExclusivelyCovered; Expr::EvalResult *switchCond; CFG::BuildOptions::ForcedBlkExprs::value_type *cachedEntry; const Stmt *lastLookup; // Caches boolean evaluations of expressions to avoid multiple re-evaluations // during construction of branches for chained logical operators. typedef llvm::DenseMap<Expr *, TryResult> CachedBoolEvalsTy; CachedBoolEvalsTy CachedBoolEvals; public: explicit CFGBuilder(ASTContext *astContext, const CFG::BuildOptions &buildOpts) : Context(astContext), cfg(new CFG()), // crew a new CFG Block(nullptr), Succ(nullptr), SwitchTerminatedBlock(nullptr), DefaultCaseBlock(nullptr), TryTerminatedBlock(nullptr), badCFG(false), BuildOpts(buildOpts), switchExclusivelyCovered(false), switchCond(nullptr), cachedEntry(nullptr), lastLookup(nullptr) {} // buildCFG - Used by external clients to construct the CFG. std::unique_ptr<CFG> buildCFG(const Decl *D, Stmt *Statement); bool alwaysAdd(const Stmt *stmt); private: // Visitors to walk an AST and construct the CFG. CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc); CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc); CFGBlock *VisitBreakStmt(BreakStmt *B); CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc); CFGBlock *VisitCaseStmt(CaseStmt *C); CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc); CFGBlock *VisitCompoundStmt(CompoundStmt *C); CFGBlock *VisitConditionalOperator(AbstractConditionalOperator *C, AddStmtChoice asc); CFGBlock *VisitContinueStmt(ContinueStmt *C); CFGBlock *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E, AddStmtChoice asc); CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S); CFGBlock *VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc); CFGBlock *VisitCXXNewExpr(CXXNewExpr *DE, AddStmtChoice asc); CFGBlock *VisitCXXDeleteExpr(CXXDeleteExpr *DE, AddStmtChoice asc); CFGBlock *VisitCXXForRangeStmt(CXXForRangeStmt *S); CFGBlock *VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E, AddStmtChoice asc); CFGBlock *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C, AddStmtChoice asc); CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T); CFGBlock *VisitCXXTryStmt(CXXTryStmt *S); CFGBlock *VisitDeclStmt(DeclStmt *DS); CFGBlock *VisitDeclSubExpr(DeclStmt *DS); CFGBlock *VisitDefaultStmt(DefaultStmt *D); CFGBlock *VisitDoStmt(DoStmt *D); CFGBlock *VisitExprWithCleanups(ExprWithCleanups *E, AddStmtChoice asc); CFGBlock *VisitForStmt(ForStmt *F); CFGBlock *VisitGotoStmt(GotoStmt *G); CFGBlock *VisitIfStmt(IfStmt *I); CFGBlock *VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc); CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I); CFGBlock *VisitLabelStmt(LabelStmt *L); CFGBlock *VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc); CFGBlock *VisitLogicalOperator(BinaryOperator *B); std::pair<CFGBlock *, CFGBlock *> VisitLogicalOperator(BinaryOperator *B, Stmt *Term, CFGBlock *TrueBlock, CFGBlock *FalseBlock); CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc); CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S); CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S); CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S); CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S); CFGBlock *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S); CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S); CFGBlock *VisitPseudoObjectExpr(PseudoObjectExpr *E); CFGBlock *VisitReturnStmt(ReturnStmt *R); CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc); CFGBlock *VisitSwitchStmt(SwitchStmt *S); CFGBlock *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E, AddStmtChoice asc); CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc); CFGBlock *VisitWhileStmt(WhileStmt *W); CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd); CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc); CFGBlock *VisitChildren(Stmt *S); CFGBlock *VisitNoRecurse(Expr *E, AddStmtChoice asc); /// When creating the CFG for temporary destructors, we want to mirror the /// branch structure of the corresponding constructor calls. /// Thus, while visiting a statement for temporary destructors, we keep a /// context to keep track of the following information: /// - whether a subexpression is executed unconditionally /// - if a subexpression is executed conditionally, the first /// CXXBindTemporaryExpr we encounter in that subexpression (which /// corresponds to the last temporary destructor we have to call for this /// subexpression) and the CFG block at that point (which will become the /// successor block when inserting the decision point). /// /// That way, we can build the branch structure for temporary destructors as /// follows: /// 1. If a subexpression is executed unconditionally, we add the temporary /// destructor calls to the current block. /// 2. If a subexpression is executed conditionally, when we encounter a /// CXXBindTemporaryExpr: /// a) If it is the first temporary destructor call in the subexpression, /// we remember the CXXBindTemporaryExpr and the current block in the /// TempDtorContext; we start a new block, and insert the temporary /// destructor call. /// b) Otherwise, add the temporary destructor call to the current block. /// 3. When we finished visiting a conditionally executed subexpression, /// and we found at least one temporary constructor during the visitation /// (2.a has executed), we insert a decision block that uses the /// CXXBindTemporaryExpr as terminator, and branches to the current block /// if the CXXBindTemporaryExpr was marked executed, and otherwise /// branches to the stored successor. struct TempDtorContext { TempDtorContext() : IsConditional(false), KnownExecuted(true), Succ(nullptr), TerminatorExpr(nullptr) {} TempDtorContext(TryResult KnownExecuted) : IsConditional(true), KnownExecuted(KnownExecuted), Succ(nullptr), TerminatorExpr(nullptr) {} /// Returns whether we need to start a new branch for a temporary destructor /// call. This is the case when the the temporary destructor is /// conditionally executed, and it is the first one we encounter while /// visiting a subexpression - other temporary destructors at the same level /// will be added to the same block and are executed under the same /// condition. bool needsTempDtorBranch() const { return IsConditional && !TerminatorExpr; } /// Remember the successor S of a temporary destructor decision branch for /// the corresponding CXXBindTemporaryExpr E. void setDecisionPoint(CFGBlock *S, CXXBindTemporaryExpr *E) { Succ = S; TerminatorExpr = E; } const bool IsConditional; const TryResult KnownExecuted; CFGBlock *Succ; CXXBindTemporaryExpr *TerminatorExpr; }; // Visitors to walk an AST and generate destructors of temporaries in // full expression. CFGBlock *VisitForTemporaryDtors(Stmt *E, bool BindToTemporary, TempDtorContext &Context); CFGBlock *VisitChildrenForTemporaryDtors(Stmt *E, TempDtorContext &Context); CFGBlock *VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E, TempDtorContext &Context); CFGBlock *VisitCXXBindTemporaryExprForTemporaryDtors( CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context); CFGBlock *VisitConditionalOperatorForTemporaryDtors( AbstractConditionalOperator *E, bool BindToTemporary, TempDtorContext &Context); void InsertTempDtorDecisionBlock(const TempDtorContext &Context, CFGBlock *FalseSucc = nullptr); // NYS == Not Yet Supported CFGBlock *NYS() { badCFG = true; return Block; } void autoCreateBlock() { if (!Block) Block = createBlock(); } CFGBlock *createBlock(bool add_successor = true); CFGBlock *createNoReturnBlock(); CFGBlock *addStmt(Stmt *S) { return Visit(S, AddStmtChoice::AlwaysAdd); } CFGBlock *addInitializer(CXXCtorInitializer *I); void addAutomaticObjDtors(LocalScope::const_iterator B, LocalScope::const_iterator E, Stmt *S); void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD); // Local scopes creation. LocalScope* createOrReuseLocalScope(LocalScope* Scope); void addLocalScopeForStmt(Stmt *S); LocalScope* addLocalScopeForDeclStmt(DeclStmt *DS, LocalScope* Scope = nullptr); LocalScope* addLocalScopeForVarDecl(VarDecl *VD, LocalScope* Scope = nullptr); void addLocalScopeAndDtors(Stmt *S); // Interface to CFGBlock - adding CFGElements. void appendStmt(CFGBlock *B, const Stmt *S) { if (alwaysAdd(S) && cachedEntry) cachedEntry->second = B; // All block-level expressions should have already been IgnoreParens()ed. assert(!isa<Expr>(S) || cast<Expr>(S)->IgnoreParens() == S); B->appendStmt(const_cast<Stmt*>(S), cfg->getBumpVectorContext()); } void appendInitializer(CFGBlock *B, CXXCtorInitializer *I) { B->appendInitializer(I, cfg->getBumpVectorContext()); } void appendNewAllocator(CFGBlock *B, CXXNewExpr *NE) { B->appendNewAllocator(NE, cfg->getBumpVectorContext()); } void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) { B->appendBaseDtor(BS, cfg->getBumpVectorContext()); } void appendMemberDtor(CFGBlock *B, FieldDecl *FD) { B->appendMemberDtor(FD, cfg->getBumpVectorContext()); } void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) { B->appendTemporaryDtor(E, cfg->getBumpVectorContext()); } void appendAutomaticObjDtor(CFGBlock *B, VarDecl *VD, Stmt *S) { B->appendAutomaticObjDtor(VD, S, cfg->getBumpVectorContext()); } void appendDeleteDtor(CFGBlock *B, CXXRecordDecl *RD, CXXDeleteExpr *DE) { B->appendDeleteDtor(RD, DE, cfg->getBumpVectorContext()); } void prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk, LocalScope::const_iterator B, LocalScope::const_iterator E); void addSuccessor(CFGBlock *B, CFGBlock *S, bool IsReachable = true) { B->addSuccessor(CFGBlock::AdjacentBlock(S, IsReachable), cfg->getBumpVectorContext()); } /// Add a reachable successor to a block, with the alternate variant that is /// unreachable. void addSuccessor(CFGBlock *B, CFGBlock *ReachableBlock, CFGBlock *AltBlock) { B->addSuccessor(CFGBlock::AdjacentBlock(ReachableBlock, AltBlock), cfg->getBumpVectorContext()); } /// \brief Find a relational comparison with an expression evaluating to a /// boolean and a constant other than 0 and 1. /// e.g. if ((x < y) == 10) TryResult checkIncorrectRelationalOperator(const BinaryOperator *B) { const Expr *LHSExpr = B->getLHS()->IgnoreParens(); const Expr *RHSExpr = B->getRHS()->IgnoreParens(); const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr); const Expr *BoolExpr = RHSExpr; bool IntFirst = true; if (!IntLiteral) { IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr); BoolExpr = LHSExpr; IntFirst = false; } if (!IntLiteral || !BoolExpr->isKnownToHaveBooleanValue()) return TryResult(); llvm::APInt IntValue = IntLiteral->getValue(); if ((IntValue == 1) || (IntValue == 0)) return TryResult(); bool IntLarger = IntLiteral->getType()->isUnsignedIntegerType() || !IntValue.isNegative(); BinaryOperatorKind Bok = B->getOpcode(); if (Bok == BO_GT || Bok == BO_GE) { // Always true for 10 > bool and bool > -1 // Always false for -1 > bool and bool > 10 return TryResult(IntFirst == IntLarger); } else { // Always true for -1 < bool and bool < 10 // Always false for 10 < bool and bool < -1 return TryResult(IntFirst != IntLarger); } } /// Find an incorrect equality comparison. Either with an expression /// evaluating to a boolean and a constant other than 0 and 1. /// e.g. if (!x == 10) or a bitwise and/or operation that always evaluates to /// true/false e.q. (x & 8) == 4. TryResult checkIncorrectEqualityOperator(const BinaryOperator *B) { const Expr *LHSExpr = B->getLHS()->IgnoreParens(); const Expr *RHSExpr = B->getRHS()->IgnoreParens(); const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr); const Expr *BoolExpr = RHSExpr; if (!IntLiteral) { IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr); BoolExpr = LHSExpr; } if (!IntLiteral) return TryResult(); const BinaryOperator *BitOp = dyn_cast<BinaryOperator>(BoolExpr); if (BitOp && (BitOp->getOpcode() == BO_And || BitOp->getOpcode() == BO_Or)) { const Expr *LHSExpr2 = BitOp->getLHS()->IgnoreParens(); const Expr *RHSExpr2 = BitOp->getRHS()->IgnoreParens(); const IntegerLiteral *IntLiteral2 = dyn_cast<IntegerLiteral>(LHSExpr2); if (!IntLiteral2) IntLiteral2 = dyn_cast<IntegerLiteral>(RHSExpr2); if (!IntLiteral2) return TryResult(); llvm::APInt L1 = IntLiteral->getValue(); llvm::APInt L2 = IntLiteral2->getValue(); if ((BitOp->getOpcode() == BO_And && (L2 & L1) != L1) || (BitOp->getOpcode() == BO_Or && (L2 | L1) != L1)) { if (BuildOpts.Observer) BuildOpts.Observer->compareBitwiseEquality(B, B->getOpcode() != BO_EQ); TryResult(B->getOpcode() != BO_EQ); } } else if (BoolExpr->isKnownToHaveBooleanValue()) { llvm::APInt IntValue = IntLiteral->getValue(); if ((IntValue == 1) || (IntValue == 0)) { return TryResult(); } return TryResult(B->getOpcode() != BO_EQ); } return TryResult(); } TryResult analyzeLogicOperatorCondition(BinaryOperatorKind Relation, const llvm::APSInt &Value1, const llvm::APSInt &Value2) { assert(Value1.isSigned() == Value2.isSigned()); switch (Relation) { default: return TryResult(); case BO_EQ: return TryResult(Value1 == Value2); case BO_NE: return TryResult(Value1 != Value2); case BO_LT: return TryResult(Value1 < Value2); case BO_LE: return TryResult(Value1 <= Value2); case BO_GT: return TryResult(Value1 > Value2); case BO_GE: return TryResult(Value1 >= Value2); } } /// \brief Find a pair of comparison expressions with or without parentheses /// with a shared variable and constants and a logical operator between them /// that always evaluates to either true or false. /// e.g. if (x != 3 || x != 4) TryResult checkIncorrectLogicOperator(const BinaryOperator *B) { assert(B->isLogicalOp()); const BinaryOperator *LHS = dyn_cast<BinaryOperator>(B->getLHS()->IgnoreParens()); const BinaryOperator *RHS = dyn_cast<BinaryOperator>(B->getRHS()->IgnoreParens()); if (!LHS || !RHS) return TryResult(); if (!LHS->isComparisonOp() || !RHS->isComparisonOp()) return TryResult(); BinaryOperatorKind BO1 = LHS->getOpcode(); const DeclRefExpr *Decl1 = dyn_cast<DeclRefExpr>(LHS->getLHS()->IgnoreParenImpCasts()); const IntegerLiteral *Literal1 = dyn_cast<IntegerLiteral>(LHS->getRHS()->IgnoreParens()); if (!Decl1 && !Literal1) { if (BO1 == BO_GT) BO1 = BO_LT; else if (BO1 == BO_GE) BO1 = BO_LE; else if (BO1 == BO_LT) BO1 = BO_GT; else if (BO1 == BO_LE) BO1 = BO_GE; Decl1 = dyn_cast<DeclRefExpr>(LHS->getRHS()->IgnoreParenImpCasts()); Literal1 = dyn_cast<IntegerLiteral>(LHS->getLHS()->IgnoreParens()); } if (!Decl1 || !Literal1) return TryResult(); BinaryOperatorKind BO2 = RHS->getOpcode(); const DeclRefExpr *Decl2 = dyn_cast<DeclRefExpr>(RHS->getLHS()->IgnoreParenImpCasts()); const IntegerLiteral *Literal2 = dyn_cast<IntegerLiteral>(RHS->getRHS()->IgnoreParens()); if (!Decl2 && !Literal2) { if (BO2 == BO_GT) BO2 = BO_LT; else if (BO2 == BO_GE) BO2 = BO_LE; else if (BO2 == BO_LT) BO2 = BO_GT; else if (BO2 == BO_LE) BO2 = BO_GE; Decl2 = dyn_cast<DeclRefExpr>(RHS->getRHS()->IgnoreParenImpCasts()); Literal2 = dyn_cast<IntegerLiteral>(RHS->getLHS()->IgnoreParens()); } if (!Decl2 || !Literal2) return TryResult(); // Check that it is the same variable on both sides. if (Decl1->getDecl() != Decl2->getDecl()) return TryResult(); llvm::APSInt L1, L2; if (!Literal1->EvaluateAsInt(L1, *Context) || !Literal2->EvaluateAsInt(L2, *Context)) return TryResult(); // Can't compare signed with unsigned or with different bit width. if (L1.isSigned() != L2.isSigned() || L1.getBitWidth() != L2.getBitWidth()) return TryResult(); // Values that will be used to determine if result of logical // operator is always true/false const llvm::APSInt Values[] = { // Value less than both Value1 and Value2 llvm::APSInt::getMinValue(L1.getBitWidth(), L1.isUnsigned()), // L1 L1, // Value between Value1 and Value2 ((L1 < L2) ? L1 : L2) + llvm::APSInt(llvm::APInt(L1.getBitWidth(), 1), L1.isUnsigned()), // L2 L2, // Value greater than both Value1 and Value2 llvm::APSInt::getMaxValue(L1.getBitWidth(), L1.isUnsigned()), }; // Check whether expression is always true/false by evaluating the following // * variable x is less than the smallest literal. // * variable x is equal to the smallest literal. // * Variable x is between smallest and largest literal. // * Variable x is equal to the largest literal. // * Variable x is greater than largest literal. bool AlwaysTrue = true, AlwaysFalse = true; for (unsigned int ValueIndex = 0; ValueIndex < sizeof(Values) / sizeof(Values[0]); ++ValueIndex) { llvm::APSInt Value = Values[ValueIndex]; TryResult Res1, Res2; Res1 = analyzeLogicOperatorCondition(BO1, Value, L1); Res2 = analyzeLogicOperatorCondition(BO2, Value, L2); if (!Res1.isKnown() || !Res2.isKnown()) return TryResult(); if (B->getOpcode() == BO_LAnd) { AlwaysTrue &= (Res1.isTrue() && Res2.isTrue()); AlwaysFalse &= !(Res1.isTrue() && Res2.isTrue()); } else { AlwaysTrue &= (Res1.isTrue() || Res2.isTrue()); AlwaysFalse &= !(Res1.isTrue() || Res2.isTrue()); } } if (AlwaysTrue || AlwaysFalse) { if (BuildOpts.Observer) BuildOpts.Observer->compareAlwaysTrue(B, AlwaysTrue); return TryResult(AlwaysTrue); } return TryResult(); } /// Try and evaluate an expression to an integer constant. bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) { if (!BuildOpts.PruneTriviallyFalseEdges) return false; return !S->isTypeDependent() && !S->isValueDependent() && S->EvaluateAsRValue(outResult, *Context); } /// tryEvaluateBool - Try and evaluate the Stmt and return 0 or 1 /// if we can evaluate to a known value, otherwise return -1. TryResult tryEvaluateBool(Expr *S) { if (!BuildOpts.PruneTriviallyFalseEdges || S->isTypeDependent() || S->isValueDependent()) return TryResult(); if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(S)) { if (Bop->isLogicalOp()) { // Check the cache first. CachedBoolEvalsTy::iterator I = CachedBoolEvals.find(S); if (I != CachedBoolEvals.end()) return I->second; // already in map; // Retrieve result at first, or the map might be updated. TryResult Result = evaluateAsBooleanConditionNoCache(S); CachedBoolEvals[S] = Result; // update or insert return Result; } else { switch (Bop->getOpcode()) { default: break; // For 'x & 0' and 'x * 0', we can determine that // the value is always false. case BO_Mul: case BO_And: { // If either operand is zero, we know the value // must be false. llvm::APSInt IntVal; if (Bop->getLHS()->EvaluateAsInt(IntVal, *Context)) { if (IntVal.getBoolValue() == false) { return TryResult(false); } } if (Bop->getRHS()->EvaluateAsInt(IntVal, *Context)) { if (IntVal.getBoolValue() == false) { return TryResult(false); } } } break; } } } return evaluateAsBooleanConditionNoCache(S); } /// \brief Evaluate as boolean \param E without using the cache. TryResult evaluateAsBooleanConditionNoCache(Expr *E) { if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(E)) { if (Bop->isLogicalOp()) { TryResult LHS = tryEvaluateBool(Bop->getLHS()); if (LHS.isKnown()) { // We were able to evaluate the LHS, see if we can get away with not // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 if (LHS.isTrue() == (Bop->getOpcode() == BO_LOr)) return LHS.isTrue(); TryResult RHS = tryEvaluateBool(Bop->getRHS()); if (RHS.isKnown()) { if (Bop->getOpcode() == BO_LOr) return LHS.isTrue() || RHS.isTrue(); else return LHS.isTrue() && RHS.isTrue(); } } else { TryResult RHS = tryEvaluateBool(Bop->getRHS()); if (RHS.isKnown()) { // We can't evaluate the LHS; however, sometimes the result // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. if (RHS.isTrue() == (Bop->getOpcode() == BO_LOr)) return RHS.isTrue(); } else { TryResult BopRes = checkIncorrectLogicOperator(Bop); if (BopRes.isKnown()) return BopRes.isTrue(); } } return TryResult(); } else if (Bop->isEqualityOp()) { TryResult BopRes = checkIncorrectEqualityOperator(Bop); if (BopRes.isKnown()) return BopRes.isTrue(); } else if (Bop->isRelationalOp()) { TryResult BopRes = checkIncorrectRelationalOperator(Bop); if (BopRes.isKnown()) return BopRes.isTrue(); } } bool Result; if (E->EvaluateAsBooleanCondition(Result, *Context)) return Result; return TryResult(); } }; inline bool AddStmtChoice::alwaysAdd(CFGBuilder &builder, const Stmt *stmt) const { return builder.alwaysAdd(stmt) || kind == AlwaysAdd; } bool CFGBuilder::alwaysAdd(const Stmt *stmt) { bool shouldAdd = BuildOpts.alwaysAdd(stmt); if (!BuildOpts.forcedBlkExprs) return shouldAdd; if (lastLookup == stmt) { if (cachedEntry) { assert(cachedEntry->first == stmt); return true; } return shouldAdd; } lastLookup = stmt; // Perform the lookup! CFG::BuildOptions::ForcedBlkExprs *fb = *BuildOpts.forcedBlkExprs; if (!fb) { // No need to update 'cachedEntry', since it will always be null. assert(!cachedEntry); return shouldAdd; } CFG::BuildOptions::ForcedBlkExprs::iterator itr = fb->find(stmt); if (itr == fb->end()) { cachedEntry = nullptr; return shouldAdd; } cachedEntry = &*itr; return true; } // FIXME: Add support for dependent-sized array types in C++? // Does it even make sense to build a CFG for an uninstantiated template? static const VariableArrayType *FindVA(const Type *t) { while (const ArrayType *vt = dyn_cast<ArrayType>(t)) { if (const VariableArrayType *vat = dyn_cast<VariableArrayType>(vt)) if (vat->getSizeExpr()) return vat; t = vt->getElementType().getTypePtr(); } return nullptr; } /// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an /// arbitrary statement. Examples include a single expression or a function /// body (compound statement). The ownership of the returned CFG is /// transferred to the caller. If CFG construction fails, this method returns /// NULL. std::unique_ptr<CFG> CFGBuilder::buildCFG(const Decl *D, Stmt *Statement) { assert(cfg.get()); if (!Statement) return nullptr; // Create an empty block that will serve as the exit block for the CFG. Since // this is the first block added to the CFG, it will be implicitly registered // as the exit block. Succ = createBlock(); assert(Succ == &cfg->getExit()); Block = nullptr; // the EXIT block is empty. Create all other blocks lazily. if (BuildOpts.AddImplicitDtors) if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(D)) addImplicitDtorsForDestructor(DD); // Visit the statements and create the CFG. CFGBlock *B = addStmt(Statement); if (badCFG) return nullptr; // For C++ constructor add initializers to CFG. if (const CXXConstructorDecl *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) { for (CXXConstructorDecl::init_const_reverse_iterator I = CD->init_rbegin(), E = CD->init_rend(); I != E; ++I) { B = addInitializer(*I); if (badCFG) return nullptr; } } if (B) Succ = B; // Backpatch the gotos whose label -> block mappings we didn't know when we // encountered them. for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(), E = BackpatchBlocks.end(); I != E; ++I ) { CFGBlock *B = I->block; const GotoStmt *G = cast<GotoStmt>(B->getTerminator()); LabelMapTy::iterator LI = LabelMap.find(G->getLabel()); // If there is no target for the goto, then we are looking at an // incomplete AST. Handle this by not registering a successor. if (LI == LabelMap.end()) continue; JumpTarget JT = LI->second; prependAutomaticObjDtorsWithTerminator(B, I->scopePosition, JT.scopePosition); addSuccessor(B, JT.block); } // Add successors to the Indirect Goto Dispatch block (if we have one). if (CFGBlock *B = cfg->getIndirectGotoBlock()) for (LabelSetTy::iterator I = AddressTakenLabels.begin(), E = AddressTakenLabels.end(); I != E; ++I ) { // Lookup the target block. LabelMapTy::iterator LI = LabelMap.find(*I); // If there is no target block that contains label, then we are looking // at an incomplete AST. Handle this by not registering a successor. if (LI == LabelMap.end()) continue; addSuccessor(B, LI->second.block); } // Create an empty entry block that has no predecessors. cfg->setEntry(createBlock()); return std::move(cfg); } /// createBlock - Used to lazily create blocks that are connected /// to the current (global) succcessor. CFGBlock *CFGBuilder::createBlock(bool add_successor) { CFGBlock *B = cfg->createBlock(); if (add_successor && Succ) addSuccessor(B, Succ); return B; } /// createNoReturnBlock - Used to create a block is a 'noreturn' point in the /// CFG. It is *not* connected to the current (global) successor, and instead /// directly tied to the exit block in order to be reachable. CFGBlock *CFGBuilder::createNoReturnBlock() { CFGBlock *B = createBlock(false); B->setHasNoReturnElement(); addSuccessor(B, &cfg->getExit(), Succ); return B; } /// addInitializer - Add C++ base or member initializer element to CFG. CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) { if (!BuildOpts.AddInitializers) return Block; bool HasTemporaries = false; // Destructors of temporaries in initialization expression should be called // after initialization finishes. Expr *Init = I->getInit(); if (Init) { HasTemporaries = isa<ExprWithCleanups>(Init); if (BuildOpts.AddTemporaryDtors && HasTemporaries) { // Generate destructors for temporaries in initialization expression. TempDtorContext Context; VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(), /*BindToTemporary=*/false, Context); } } autoCreateBlock(); appendInitializer(Block, I); if (Init) { if (HasTemporaries) { // For expression with temporaries go directly to subexpression to omit // generating destructors for the second time. return Visit(cast<ExprWithCleanups>(Init)->getSubExpr()); } return Visit(Init); } return Block; } /// \brief Retrieve the type of the temporary object whose lifetime was /// extended by a local reference with the given initializer. static QualType getReferenceInitTemporaryType(ASTContext &Context, const Expr *Init) { while (true) { // Skip parentheses. Init = Init->IgnoreParens(); // Skip through cleanups. if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init)) { Init = EWC->getSubExpr(); continue; } // Skip through the temporary-materialization expression. if (const MaterializeTemporaryExpr *MTE = dyn_cast<MaterializeTemporaryExpr>(Init)) { Init = MTE->GetTemporaryExpr(); continue; } // Skip derived-to-base and no-op casts. if (const CastExpr *CE = dyn_cast<CastExpr>(Init)) { if ((CE->getCastKind() == CK_DerivedToBase || CE->getCastKind() == CK_UncheckedDerivedToBase || CE->getCastKind() == CK_NoOp) && Init->getType()->isRecordType()) { Init = CE->getSubExpr(); continue; } } // Skip member accesses into rvalues. if (const MemberExpr *ME = dyn_cast<MemberExpr>(Init)) { if (!ME->isArrow() && ME->getBase()->isRValue()) { Init = ME->getBase(); continue; } } break; } return Init->getType(); } /// addAutomaticObjDtors - Add to current block automatic objects destructors /// for objects in range of local scope positions. Use S as trigger statement /// for destructors. void CFGBuilder::addAutomaticObjDtors(LocalScope::const_iterator B, LocalScope::const_iterator E, Stmt *S) { if (!BuildOpts.AddImplicitDtors) return; if (B == E) return; // We need to append the destructors in reverse order, but any one of them // may be a no-return destructor which changes the CFG. As a result, buffer // this sequence up and replay them in reverse order when appending onto the // CFGBlock(s). SmallVector<VarDecl*, 10> Decls; Decls.reserve(B.distance(E)); for (LocalScope::const_iterator I = B; I != E; ++I) Decls.push_back(*I); for (SmallVectorImpl<VarDecl*>::reverse_iterator I = Decls.rbegin(), E = Decls.rend(); I != E; ++I) { // If this destructor is marked as a no-return destructor, we need to // create a new block for the destructor which does not have as a successor // anything built thus far: control won't flow out of this block. QualType Ty = (*I)->getType(); if (Ty->isReferenceType()) { Ty = getReferenceInitTemporaryType(*Context, (*I)->getInit()); } Ty = Context->getBaseElementType(Ty); const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor(); if (Dtor->isNoReturn()) Block = createNoReturnBlock(); else autoCreateBlock(); appendAutomaticObjDtor(Block, *I, S); } } /// addImplicitDtorsForDestructor - Add implicit destructors generated for /// base and member objects in destructor. void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) { assert (BuildOpts.AddImplicitDtors && "Can be called only when dtors should be added"); const CXXRecordDecl *RD = DD->getParent(); // At the end destroy virtual base objects. for (const auto &VI : RD->vbases()) { const CXXRecordDecl *CD = VI.getType()->getAsCXXRecordDecl(); if (!CD->hasTrivialDestructor()) { autoCreateBlock(); appendBaseDtor(Block, &VI); } } // Before virtual bases destroy direct base objects. for (const auto &BI : RD->bases()) { if (!BI.isVirtual()) { const CXXRecordDecl *CD = BI.getType()->getAsCXXRecordDecl(); if (!CD->hasTrivialDestructor()) { autoCreateBlock(); appendBaseDtor(Block, &BI); } } } // First destroy member objects. for (auto *FI : RD->fields()) { // Check for constant size array. Set type to array element type. QualType QT = FI->getType(); if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) { if (AT->getSize() == 0) continue; QT = AT->getElementType(); } if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl()) if (!CD->hasTrivialDestructor()) { autoCreateBlock(); appendMemberDtor(Block, FI); } } } /// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either /// way return valid LocalScope object. LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) { if (!Scope) { llvm::BumpPtrAllocator &alloc = cfg->getAllocator(); Scope = alloc.Allocate<LocalScope>(); BumpVectorContext ctx(alloc); new (Scope) LocalScope(ctx, ScopePos); } return Scope; } /// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement /// that should create implicit scope (e.g. if/else substatements). void CFGBuilder::addLocalScopeForStmt(Stmt *S) { if (!BuildOpts.AddImplicitDtors) return; LocalScope *Scope = nullptr; // For compound statement we will be creating explicit scope. if (CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) { for (auto *BI : CS->body()) { Stmt *SI = BI->stripLabelLikeStatements(); if (DeclStmt *DS = dyn_cast<DeclStmt>(SI)) Scope = addLocalScopeForDeclStmt(DS, Scope); } return; } // For any other statement scope will be implicit and as such will be // interesting only for DeclStmt. if (DeclStmt *DS = dyn_cast<DeclStmt>(S->stripLabelLikeStatements())) addLocalScopeForDeclStmt(DS); } /// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will /// reuse Scope if not NULL. LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt *DS, LocalScope* Scope) { if (!BuildOpts.AddImplicitDtors) return Scope; for (auto *DI : DS->decls()) if (VarDecl *VD = dyn_cast<VarDecl>(DI)) Scope = addLocalScopeForVarDecl(VD, Scope); return Scope; } /// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will /// create add scope for automatic objects and temporary objects bound to /// const reference. Will reuse Scope if not NULL. LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl *VD, LocalScope* Scope) { if (!BuildOpts.AddImplicitDtors) return Scope; // Check if variable is local. switch (VD->getStorageClass()) { case SC_None: case SC_Auto: case SC_Register: break; default: return Scope; } // Check for const references bound to temporary. Set type to pointee. QualType QT = VD->getType(); if (QT.getTypePtr()->isReferenceType()) { // Attempt to determine whether this declaration lifetime-extends a // temporary. // // FIXME: This is incorrect. Non-reference declarations can lifetime-extend // temporaries, and a single declaration can extend multiple temporaries. // We should look at the storage duration on each nested // MaterializeTemporaryExpr instead. const Expr *Init = VD->getInit(); if (!Init) return Scope; if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init)) Init = EWC->getSubExpr(); if (!isa<MaterializeTemporaryExpr>(Init)) return Scope; // Lifetime-extending a temporary. QT = getReferenceInitTemporaryType(*Context, Init); } // Check for constant size array. Set type to array element type. while (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) { if (AT->getSize() == 0) return Scope; QT = AT->getElementType(); } // Check if type is a C++ class with non-trivial destructor. if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl()) if (!CD->hasTrivialDestructor()) { // Add the variable to scope Scope = createOrReuseLocalScope(Scope); Scope->addVar(VD); ScopePos = Scope->begin(); } return Scope; } /// addLocalScopeAndDtors - For given statement add local scope for it and /// add destructors that will cleanup the scope. Will reuse Scope if not NULL. void CFGBuilder::addLocalScopeAndDtors(Stmt *S) { if (!BuildOpts.AddImplicitDtors) return; LocalScope::const_iterator scopeBeginPos = ScopePos; addLocalScopeForStmt(S); addAutomaticObjDtors(ScopePos, scopeBeginPos, S); } /// prependAutomaticObjDtorsWithTerminator - Prepend destructor CFGElements for /// variables with automatic storage duration to CFGBlock's elements vector. /// Elements will be prepended to physical beginning of the vector which /// happens to be logical end. Use blocks terminator as statement that specifies /// destructors call site. /// FIXME: This mechanism for adding automatic destructors doesn't handle /// no-return destructors properly. void CFGBuilder::prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk, LocalScope::const_iterator B, LocalScope::const_iterator E) { BumpVectorContext &C = cfg->getBumpVectorContext(); CFGBlock::iterator InsertPos = Blk->beginAutomaticObjDtorsInsert(Blk->end(), B.distance(E), C); for (LocalScope::const_iterator I = B; I != E; ++I) InsertPos = Blk->insertAutomaticObjDtor(InsertPos, *I, Blk->getTerminator()); } /// Visit - Walk the subtree of a statement and add extra /// blocks for ternary operators, &&, and ||. We also process "," and /// DeclStmts (which may contain nested control-flow). CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc) { if (!S) { badCFG = true; return nullptr; } if (Expr *E = dyn_cast<Expr>(S)) S = E->IgnoreParens(); switch (S->getStmtClass()) { default: return VisitStmt(S, asc); case Stmt::AddrLabelExprClass: return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc); case Stmt::BinaryConditionalOperatorClass: return VisitConditionalOperator(cast<BinaryConditionalOperator>(S), asc); case Stmt::BinaryOperatorClass: return VisitBinaryOperator(cast<BinaryOperator>(S), asc); case Stmt::BlockExprClass: return VisitNoRecurse(cast<Expr>(S), asc); case Stmt::BreakStmtClass: return VisitBreakStmt(cast<BreakStmt>(S)); case Stmt::CallExprClass: case Stmt::CXXOperatorCallExprClass: case Stmt::CXXMemberCallExprClass: case Stmt::UserDefinedLiteralClass: return VisitCallExpr(cast<CallExpr>(S), asc); case Stmt::CaseStmtClass: return VisitCaseStmt(cast<CaseStmt>(S)); case Stmt::ChooseExprClass: return VisitChooseExpr(cast<ChooseExpr>(S), asc); case Stmt::CompoundStmtClass: return VisitCompoundStmt(cast<CompoundStmt>(S)); case Stmt::ConditionalOperatorClass: return VisitConditionalOperator(cast<ConditionalOperator>(S), asc); case Stmt::ContinueStmtClass: return VisitContinueStmt(cast<ContinueStmt>(S)); case Stmt::CXXCatchStmtClass: return VisitCXXCatchStmt(cast<CXXCatchStmt>(S)); case Stmt::ExprWithCleanupsClass: return VisitExprWithCleanups(cast<ExprWithCleanups>(S), asc); case Stmt::CXXDefaultArgExprClass: case Stmt::CXXDefaultInitExprClass: // FIXME: The expression inside a CXXDefaultArgExpr is owned by the // called function's declaration, not by the caller. If we simply add // this expression to the CFG, we could end up with the same Expr // appearing multiple times. // PR13385 / <rdar://problem/12156507> // // It's likewise possible for multiple CXXDefaultInitExprs for the same // expression to be used in the same function (through aggregate // initialization). return VisitStmt(S, asc); case Stmt::CXXBindTemporaryExprClass: return VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), asc); case Stmt::CXXConstructExprClass: return VisitCXXConstructExpr(cast<CXXConstructExpr>(S), asc); case Stmt::CXXNewExprClass: return VisitCXXNewExpr(cast<CXXNewExpr>(S), asc); case Stmt::CXXDeleteExprClass: return VisitCXXDeleteExpr(cast<CXXDeleteExpr>(S), asc); case Stmt::CXXFunctionalCastExprClass: return VisitCXXFunctionalCastExpr(cast<CXXFunctionalCastExpr>(S), asc); case Stmt::CXXTemporaryObjectExprClass: return VisitCXXTemporaryObjectExpr(cast<CXXTemporaryObjectExpr>(S), asc); case Stmt::CXXThrowExprClass: return VisitCXXThrowExpr(cast<CXXThrowExpr>(S)); case Stmt::CXXTryStmtClass: return VisitCXXTryStmt(cast<CXXTryStmt>(S)); case Stmt::CXXForRangeStmtClass: return VisitCXXForRangeStmt(cast<CXXForRangeStmt>(S)); case Stmt::DeclStmtClass: return VisitDeclStmt(cast<DeclStmt>(S)); case Stmt::DefaultStmtClass: return VisitDefaultStmt(cast<DefaultStmt>(S)); case Stmt::DoStmtClass: return VisitDoStmt(cast<DoStmt>(S)); case Stmt::ForStmtClass: return VisitForStmt(cast<ForStmt>(S)); case Stmt::GotoStmtClass: return VisitGotoStmt(cast<GotoStmt>(S)); case Stmt::IfStmtClass: return VisitIfStmt(cast<IfStmt>(S)); case Stmt::ImplicitCastExprClass: return VisitImplicitCastExpr(cast<ImplicitCastExpr>(S), asc); case Stmt::IndirectGotoStmtClass: return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S)); case Stmt::LabelStmtClass: return VisitLabelStmt(cast<LabelStmt>(S)); case Stmt::LambdaExprClass: return VisitLambdaExpr(cast<LambdaExpr>(S), asc); case Stmt::MemberExprClass: return VisitMemberExpr(cast<MemberExpr>(S), asc); case Stmt::NullStmtClass: return Block; case Stmt::ObjCAtCatchStmtClass: return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S)); case Stmt::ObjCAutoreleasePoolStmtClass: return VisitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(S)); case Stmt::ObjCAtSynchronizedStmtClass: return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S)); case Stmt::ObjCAtThrowStmtClass: return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S)); case Stmt::ObjCAtTryStmtClass: return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S)); case Stmt::ObjCForCollectionStmtClass: return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S)); case Stmt::OpaqueValueExprClass: return Block; case Stmt::PseudoObjectExprClass: return VisitPseudoObjectExpr(cast<PseudoObjectExpr>(S)); case Stmt::ReturnStmtClass: return VisitReturnStmt(cast<ReturnStmt>(S)); case Stmt::UnaryExprOrTypeTraitExprClass: return VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S), asc); case Stmt::StmtExprClass: return VisitStmtExpr(cast<StmtExpr>(S), asc); case Stmt::SwitchStmtClass: return VisitSwitchStmt(cast<SwitchStmt>(S)); case Stmt::UnaryOperatorClass: return VisitUnaryOperator(cast<UnaryOperator>(S), asc); case Stmt::WhileStmtClass: return VisitWhileStmt(cast<WhileStmt>(S)); } } CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) { if (asc.alwaysAdd(*this, S)) { autoCreateBlock(); appendStmt(Block, S); } return VisitChildren(S); } /// VisitChildren - Visit the children of a Stmt. CFGBlock *CFGBuilder::VisitChildren(Stmt *S) { CFGBlock *B = Block; // Visit the children in their reverse order so that they appear in // left-to-right (natural) order in the CFG. reverse_children RChildren(S); for (reverse_children::iterator I = RChildren.begin(), E = RChildren.end(); I != E; ++I) { if (Stmt *Child = *I) if (CFGBlock *R = Visit(Child)) B = R; } return B; } CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc) { AddressTakenLabels.insert(A->getLabel()); if (asc.alwaysAdd(*this, A)) { autoCreateBlock(); appendStmt(Block, A); } return Block; } CFGBlock *CFGBuilder::VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc) { if (asc.alwaysAdd(*this, U)) { autoCreateBlock(); appendStmt(Block, U); } return Visit(U->getSubExpr(), AddStmtChoice()); } CFGBlock *CFGBuilder::VisitLogicalOperator(BinaryOperator *B) { CFGBlock *ConfluenceBlock = Block ? Block : createBlock(); appendStmt(ConfluenceBlock, B); if (badCFG) return nullptr; return VisitLogicalOperator(B, nullptr, ConfluenceBlock, ConfluenceBlock).first; } std::pair<CFGBlock*, CFGBlock*> CFGBuilder::VisitLogicalOperator(BinaryOperator *B, Stmt *Term, CFGBlock *TrueBlock, CFGBlock *FalseBlock) { // Introspect the RHS. If it is a nested logical operation, we recursively // build the CFG using this function. Otherwise, resort to default // CFG construction behavior. Expr *RHS = B->getRHS()->IgnoreParens(); CFGBlock *RHSBlock, *ExitBlock; do { if (BinaryOperator *B_RHS = dyn_cast<BinaryOperator>(RHS)) if (B_RHS->isLogicalOp()) { std::tie(RHSBlock, ExitBlock) = VisitLogicalOperator(B_RHS, Term, TrueBlock, FalseBlock); break; } // The RHS is not a nested logical operation. Don't push the terminator // down further, but instead visit RHS and construct the respective // pieces of the CFG, and link up the RHSBlock with the terminator // we have been provided. ExitBlock = RHSBlock = createBlock(false); if (!Term) { assert(TrueBlock == FalseBlock); addSuccessor(RHSBlock, TrueBlock); } else { RHSBlock->setTerminator(Term); TryResult KnownVal = tryEvaluateBool(RHS); if (!KnownVal.isKnown()) KnownVal = tryEvaluateBool(B); addSuccessor(RHSBlock, TrueBlock, !KnownVal.isFalse()); addSuccessor(RHSBlock, FalseBlock, !KnownVal.isTrue()); } Block = RHSBlock; RHSBlock = addStmt(RHS); } while (false); if (badCFG) return std::make_pair(nullptr, nullptr); // Generate the blocks for evaluating the LHS. Expr *LHS = B->getLHS()->IgnoreParens(); if (BinaryOperator *B_LHS = dyn_cast<BinaryOperator>(LHS)) if (B_LHS->isLogicalOp()) { if (B->getOpcode() == BO_LOr) FalseBlock = RHSBlock; else TrueBlock = RHSBlock; // For the LHS, treat 'B' as the terminator that we want to sink // into the nested branch. The RHS always gets the top-most // terminator. return VisitLogicalOperator(B_LHS, B, TrueBlock, FalseBlock); } // Create the block evaluating the LHS. // This contains the '&&' or '||' as the terminator. CFGBlock *LHSBlock = createBlock(false); LHSBlock->setTerminator(B); Block = LHSBlock; CFGBlock *EntryLHSBlock = addStmt(LHS); if (badCFG) return std::make_pair(nullptr, nullptr); // See if this is a known constant. TryResult KnownVal = tryEvaluateBool(LHS); // Now link the LHSBlock with RHSBlock. if (B->getOpcode() == BO_LOr) { addSuccessor(LHSBlock, TrueBlock, !KnownVal.isFalse()); addSuccessor(LHSBlock, RHSBlock, !KnownVal.isTrue()); } else { assert(B->getOpcode() == BO_LAnd); addSuccessor(LHSBlock, RHSBlock, !KnownVal.isFalse()); addSuccessor(LHSBlock, FalseBlock, !KnownVal.isTrue()); } return std::make_pair(EntryLHSBlock, ExitBlock); } CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc) { // && or || if (B->isLogicalOp()) return VisitLogicalOperator(B); if (B->getOpcode() == BO_Comma) { // , autoCreateBlock(); appendStmt(Block, B); addStmt(B->getRHS()); return addStmt(B->getLHS()); } if (B->isAssignmentOp()) { if (asc.alwaysAdd(*this, B)) { autoCreateBlock(); appendStmt(Block, B); } Visit(B->getLHS()); return Visit(B->getRHS()); } if (asc.alwaysAdd(*this, B)) { autoCreateBlock(); appendStmt(Block, B); } CFGBlock *RBlock = Visit(B->getRHS()); CFGBlock *LBlock = Visit(B->getLHS()); // If visiting RHS causes us to finish 'Block', e.g. the RHS is a StmtExpr // containing a DoStmt, and the LHS doesn't create a new block, then we should // return RBlock. Otherwise we'll incorrectly return NULL. return (LBlock ? LBlock : RBlock); } CFGBlock *CFGBuilder::VisitNoRecurse(Expr *E, AddStmtChoice asc) { if (asc.alwaysAdd(*this, E)) { autoCreateBlock(); appendStmt(Block, E); } return Block; } CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) { // "break" is a control-flow statement. Thus we stop processing the current // block. if (badCFG) return nullptr; // Now create a new block that ends with the break statement. Block = createBlock(false); Block->setTerminator(B); // If there is no target for the break, then we are looking at an incomplete // AST. This means that the CFG cannot be constructed. if (BreakJumpTarget.block) { addAutomaticObjDtors(ScopePos, BreakJumpTarget.scopePosition, B); addSuccessor(Block, BreakJumpTarget.block); } else badCFG = true; return Block; } static bool CanThrow(Expr *E, ASTContext &Ctx) { QualType Ty = E->getType(); if (Ty->isFunctionPointerType()) Ty = Ty->getAs<PointerType>()->getPointeeType(); else if (Ty->isBlockPointerType()) Ty = Ty->getAs<BlockPointerType>()->getPointeeType(); const FunctionType *FT = Ty->getAs<FunctionType>(); if (FT) { if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) if (!isUnresolvedExceptionSpec(Proto->getExceptionSpecType()) && Proto->isNothrow(Ctx)) return false; } return true; } CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) { // Compute the callee type. QualType calleeType = C->getCallee()->getType(); if (calleeType == Context->BoundMemberTy) { QualType boundType = Expr::findBoundMemberType(C->getCallee()); // We should only get a null bound type if processing a dependent // CFG. Recover by assuming nothing. if (!boundType.isNull()) calleeType = boundType; } // If this is a call to a no-return function, this stops the block here. bool NoReturn = getFunctionExtInfo(*calleeType).getNoReturn(); bool AddEHEdge = false; // Languages without exceptions are assumed to not throw. if (Context->getLangOpts().Exceptions) { if (BuildOpts.AddEHEdges) AddEHEdge = true; } // If this is a call to a builtin function, it might not actually evaluate // its arguments. Don't add them to the CFG if this is the case. bool OmitArguments = false; if (FunctionDecl *FD = C->getDirectCallee()) { if (FD->isNoReturn()) NoReturn = true; if (FD->hasAttr<NoThrowAttr>()) AddEHEdge = false; if (FD->getBuiltinID() == Builtin::BI__builtin_object_size) OmitArguments = true; } if (!CanThrow(C->getCallee(), *Context)) AddEHEdge = false; if (OmitArguments) { assert(!NoReturn && "noreturn calls with unevaluated args not implemented"); assert(!AddEHEdge && "EH calls with unevaluated args not implemented"); autoCreateBlock(); appendStmt(Block, C); return Visit(C->getCallee()); } if (!NoReturn && !AddEHEdge) { return VisitStmt(C, asc.withAlwaysAdd(true)); } if (Block) { Succ = Block; if (badCFG) return nullptr; } if (NoReturn) Block = createNoReturnBlock(); else Block = createBlock(); appendStmt(Block, C); if (AddEHEdge) { // Add exceptional edges. if (TryTerminatedBlock) addSuccessor(Block, TryTerminatedBlock); else addSuccessor(Block, &cfg->getExit()); } return VisitChildren(C); } CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc) { CFGBlock *ConfluenceBlock = Block ? Block : createBlock(); appendStmt(ConfluenceBlock, C); if (badCFG) return nullptr; AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true); Succ = ConfluenceBlock; Block = nullptr; CFGBlock *LHSBlock = Visit(C->getLHS(), alwaysAdd); if (badCFG) return nullptr; Succ = ConfluenceBlock; Block = nullptr; CFGBlock *RHSBlock = Visit(C->getRHS(), alwaysAdd); if (badCFG) return nullptr; Block = createBlock(false); // See if this is a known constant. const TryResult& KnownVal = tryEvaluateBool(C->getCond()); addSuccessor(Block, KnownVal.isFalse() ? nullptr : LHSBlock); addSuccessor(Block, KnownVal.isTrue() ? nullptr : RHSBlock); Block->setTerminator(C); return addStmt(C->getCond()); } CFGBlock *CFGBuilder::VisitCompoundStmt(CompoundStmt *C) { addLocalScopeAndDtors(C); CFGBlock *LastBlock = Block; for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend(); I != E; ++I ) { // If we hit a segment of code just containing ';' (NullStmts), we can // get a null block back. In such cases, just use the LastBlock if (CFGBlock *newBlock = addStmt(*I)) LastBlock = newBlock; if (badCFG) return nullptr; } return LastBlock; } CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C, AddStmtChoice asc) { const BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(C); const OpaqueValueExpr *opaqueValue = (BCO ? BCO->getOpaqueValue() : nullptr); // Create the confluence block that will "merge" the results of the ternary // expression. CFGBlock *ConfluenceBlock = Block ? Block : createBlock(); appendStmt(ConfluenceBlock, C); if (badCFG) return nullptr; AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true); // Create a block for the LHS expression if there is an LHS expression. A // GCC extension allows LHS to be NULL, causing the condition to be the // value that is returned instead. // e.g: x ?: y is shorthand for: x ? x : y; Succ = ConfluenceBlock; Block = nullptr; CFGBlock *LHSBlock = nullptr; const Expr *trueExpr = C->getTrueExpr(); if (trueExpr != opaqueValue) { LHSBlock = Visit(C->getTrueExpr(), alwaysAdd); if (badCFG) return nullptr; Block = nullptr; } else LHSBlock = ConfluenceBlock; // Create the block for the RHS expression. Succ = ConfluenceBlock; CFGBlock *RHSBlock = Visit(C->getFalseExpr(), alwaysAdd); if (badCFG) return nullptr; // If the condition is a logical '&&' or '||', build a more accurate CFG. if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(C->getCond()->IgnoreParens())) if (Cond->isLogicalOp()) return VisitLogicalOperator(Cond, C, LHSBlock, RHSBlock).first; // Create the block that will contain the condition. Block = createBlock(false); // See if this is a known constant. const TryResult& KnownVal = tryEvaluateBool(C->getCond()); addSuccessor(Block, LHSBlock, !KnownVal.isFalse()); addSuccessor(Block, RHSBlock, !KnownVal.isTrue()); Block->setTerminator(C); Expr *condExpr = C->getCond(); if (opaqueValue) { // Run the condition expression if it's not trivially expressed in // terms of the opaque value (or if there is no opaque value). if (condExpr != opaqueValue) addStmt(condExpr); // Before that, run the common subexpression if there was one. // At least one of this or the above will be run. return addStmt(BCO->getCommon()); } return addStmt(condExpr); } CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) { // Check if the Decl is for an __label__. If so, elide it from the // CFG entirely. if (isa<LabelDecl>(*DS->decl_begin())) return Block; // This case also handles static_asserts. if (DS->isSingleDecl()) return VisitDeclSubExpr(DS); CFGBlock *B = nullptr; // Build an individual DeclStmt for each decl. for (DeclStmt::reverse_decl_iterator I = DS->decl_rbegin(), E = DS->decl_rend(); I != E; ++I) { // Get the alignment of the new DeclStmt, padding out to >=8 bytes. unsigned A = llvm::AlignOf<DeclStmt>::Alignment < 8 ? 8 : llvm::AlignOf<DeclStmt>::Alignment; // Allocate the DeclStmt using the BumpPtrAllocator. It will get // automatically freed with the CFG. DeclGroupRef DG(*I); Decl *D = *I; void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A); DeclStmt *DSNew = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D)); cfg->addSyntheticDeclStmt(DSNew, DS); // Append the fake DeclStmt to block. B = VisitDeclSubExpr(DSNew); } return B; } /// VisitDeclSubExpr - Utility method to add block-level expressions for /// DeclStmts and initializers in them. CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) { assert(DS->isSingleDecl() && "Can handle single declarations only."); VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl()); if (!VD) { // Of everything that can be declared in a DeclStmt, only VarDecls impact // runtime semantics. return Block; } bool HasTemporaries = false; // Guard static initializers under a branch. CFGBlock *blockAfterStaticInit = nullptr; if (BuildOpts.AddStaticInitBranches && VD->isStaticLocal()) { // For static variables, we need to create a branch to track // whether or not they are initialized. if (Block) { Succ = Block; Block = nullptr; if (badCFG) return nullptr; } blockAfterStaticInit = Succ; } // Destructors of temporaries in initialization expression should be called // after initialization finishes. Expr *Init = VD->getInit(); if (Init) { HasTemporaries = isa<ExprWithCleanups>(Init); if (BuildOpts.AddTemporaryDtors && HasTemporaries) { // Generate destructors for temporaries in initialization expression. TempDtorContext Context; VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(), /*BindToTemporary=*/false, Context); } } autoCreateBlock(); appendStmt(Block, DS); // Keep track of the last non-null block, as 'Block' can be nulled out // if the initializer expression is something like a 'while' in a // statement-expression. CFGBlock *LastBlock = Block; if (Init) { if (HasTemporaries) { // For expression with temporaries go directly to subexpression to omit // generating destructors for the second time. ExprWithCleanups *EC = cast<ExprWithCleanups>(Init); if (CFGBlock *newBlock = Visit(EC->getSubExpr())) LastBlock = newBlock; } else { if (CFGBlock *newBlock = Visit(Init)) LastBlock = newBlock; } } // If the type of VD is a VLA, then we must process its size expressions. for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr()); VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr())) { if (CFGBlock *newBlock = addStmt(VA->getSizeExpr())) LastBlock = newBlock; } // Remove variable from local scope. if (ScopePos && VD == *ScopePos) ++ScopePos; CFGBlock *B = LastBlock; if (blockAfterStaticInit) { Succ = B; Block = createBlock(false); Block->setTerminator(DS); addSuccessor(Block, blockAfterStaticInit); addSuccessor(Block, B); B = Block; } return B; } CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) { // We may see an if statement in the middle of a basic block, or it may be the // first statement we are processing. In either case, we create a new basic // block. First, we create the blocks for the then...else statements, and // then we create the block containing the if statement. If we were in the // middle of a block, we stop processing that block. That block is then the // implicit successor for the "then" and "else" clauses. // Save local scope position because in case of condition variable ScopePos // won't be restored when traversing AST. SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); // Create local scope for possible condition variable. // Store scope position. Add implicit destructor. if (VarDecl *VD = I->getConditionVariable()) { LocalScope::const_iterator BeginScopePos = ScopePos; addLocalScopeForVarDecl(VD); addAutomaticObjDtors(ScopePos, BeginScopePos, I); } // The block we were processing is now finished. Make it the successor // block. if (Block) { Succ = Block; if (badCFG) return nullptr; } // Process the false branch. CFGBlock *ElseBlock = Succ; if (Stmt *Else = I->getElse()) { SaveAndRestore<CFGBlock*> sv(Succ); // NULL out Block so that the recursive call to Visit will // create a new basic block. Block = nullptr; // If branch is not a compound statement create implicit scope // and add destructors. if (!isa<CompoundStmt>(Else)) addLocalScopeAndDtors(Else); ElseBlock = addStmt(Else); if (!ElseBlock) // Can occur when the Else body has all NullStmts. ElseBlock = sv.get(); else if (Block) { if (badCFG) return nullptr; } } // Process the true branch. CFGBlock *ThenBlock; { Stmt *Then = I->getThen(); assert(Then); SaveAndRestore<CFGBlock*> sv(Succ); Block = nullptr; // If branch is not a compound statement create implicit scope // and add destructors. if (!isa<CompoundStmt>(Then)) addLocalScopeAndDtors(Then); ThenBlock = addStmt(Then); if (!ThenBlock) { // We can reach here if the "then" body has all NullStmts. // Create an empty block so we can distinguish between true and false // branches in path-sensitive analyses. ThenBlock = createBlock(false); addSuccessor(ThenBlock, sv.get()); } else if (Block) { if (badCFG) return nullptr; } } // Specially handle "if (expr1 || ...)" and "if (expr1 && ...)" by // having these handle the actual control-flow jump. Note that // if we introduce a condition variable, e.g. "if (int x = exp1 || exp2)" // we resort to the old control-flow behavior. This special handling // removes infeasible paths from the control-flow graph by having the // control-flow transfer of '&&' or '||' go directly into the then/else // blocks directly. if (!I->getConditionVariable()) if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(I->getCond()->IgnoreParens())) if (Cond->isLogicalOp()) return VisitLogicalOperator(Cond, I, ThenBlock, ElseBlock).first; // Now create a new block containing the if statement. Block = createBlock(false); // Set the terminator of the new block to the If statement. Block->setTerminator(I); // See if this is a known constant. const TryResult &KnownVal = tryEvaluateBool(I->getCond()); // Add the successors. If we know that specific branches are // unreachable, inform addSuccessor() of that knowledge. addSuccessor(Block, ThenBlock, /* isReachable = */ !KnownVal.isFalse()); addSuccessor(Block, ElseBlock, /* isReachable = */ !KnownVal.isTrue()); // Add the condition as the last statement in the new block. This may create // new blocks as the condition may contain control-flow. Any newly created // blocks will be pointed to be "Block". CFGBlock *LastBlock = addStmt(I->getCond()); // Finally, if the IfStmt contains a condition variable, add it and its // initializer to the CFG. if (const DeclStmt* DS = I->getConditionVariableDeclStmt()) { autoCreateBlock(); LastBlock = addStmt(const_cast<DeclStmt *>(DS)); } return LastBlock; } CFGBlock *CFGBuilder::VisitReturnStmt(ReturnStmt *R) { // If we were in the middle of a block we stop processing that block. // // NOTE: If a "return" appears in the middle of a block, this means that the // code afterwards is DEAD (unreachable). We still keep a basic block // for that code; a simple "mark-and-sweep" from the entry block will be // able to report such dead blocks. // Create the new block. Block = createBlock(false); addAutomaticObjDtors(ScopePos, LocalScope::const_iterator(), R); // If the one of the destructors does not return, we already have the Exit // block as a successor. if (!Block->hasNoReturnElement()) addSuccessor(Block, &cfg->getExit()); // Add the return statement to the block. This may create new blocks if R // contains control-flow (short-circuit operations). return VisitStmt(R, AddStmtChoice::AlwaysAdd); } CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) { // Get the block of the labeled statement. Add it to our map. addStmt(L->getSubStmt()); CFGBlock *LabelBlock = Block; if (!LabelBlock) // This can happen when the body is empty, i.e. LabelBlock = createBlock(); // scopes that only contains NullStmts. assert(LabelMap.find(L->getDecl()) == LabelMap.end() && "label already in map"); LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos); // Labels partition blocks, so this is the end of the basic block we were // processing (L is the block's label). Because this is label (and we have // already processed the substatement) there is no extra control-flow to worry // about. LabelBlock->setLabel(L); if (badCFG) return nullptr; // We set Block to NULL to allow lazy creation of a new block (if necessary); Block = nullptr; // This block is now the implicit successor of other blocks. Succ = LabelBlock; return LabelBlock; } CFGBlock *CFGBuilder::VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc) { CFGBlock *LastBlock = VisitNoRecurse(E, asc); for (LambdaExpr::capture_init_iterator it = E->capture_init_begin(), et = E->capture_init_end(); it != et; ++it) { if (Expr *Init = *it) { CFGBlock *Tmp = Visit(Init); if (Tmp) LastBlock = Tmp; } } return LastBlock; } CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) { // Goto is a control-flow statement. Thus we stop processing the current // block and create a new one. Block = createBlock(false); Block->setTerminator(G); // If we already know the mapping to the label block add the successor now. LabelMapTy::iterator I = LabelMap.find(G->getLabel()); if (I == LabelMap.end()) // We will need to backpatch this block later. BackpatchBlocks.push_back(JumpSource(Block, ScopePos)); else { JumpTarget JT = I->second; addAutomaticObjDtors(ScopePos, JT.scopePosition, G); addSuccessor(Block, JT.block); } return Block; } CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) { CFGBlock *LoopSuccessor = nullptr; // Save local scope position because in case of condition variable ScopePos // won't be restored when traversing AST. SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); // Create local scope for init statement and possible condition variable. // Add destructor for init statement and condition variable. // Store scope position for continue statement. if (Stmt *Init = F->getInit()) addLocalScopeForStmt(Init); LocalScope::const_iterator LoopBeginScopePos = ScopePos; if (VarDecl *VD = F->getConditionVariable()) addLocalScopeForVarDecl(VD); LocalScope::const_iterator ContinueScopePos = ScopePos; addAutomaticObjDtors(ScopePos, save_scope_pos.get(), F); // "for" is a control-flow statement. Thus we stop processing the current // block. if (Block) { if (badCFG) return nullptr; LoopSuccessor = Block; } else LoopSuccessor = Succ; // Save the current value for the break targets. // All breaks should go to the code following the loop. SaveAndRestore<JumpTarget> save_break(BreakJumpTarget); BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr; // Now create the loop body. { assert(F->getBody()); // Save the current values for Block, Succ, continue and break targets. SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget); // Create an empty block to represent the transition block for looping back // to the head of the loop. If we have increment code, it will // go in this block as well. Block = Succ = TransitionBlock = createBlock(false); TransitionBlock->setLoopTarget(F); if (Stmt *I = F->getInc()) { // Generate increment code in its own basic block. This is the target of // continue statements. Succ = addStmt(I); } // Finish up the increment (or empty) block if it hasn't been already. if (Block) { assert(Block == Succ); if (badCFG) return nullptr; Block = nullptr; } // The starting block for the loop increment is the block that should // represent the 'loop target' for looping back to the start of the loop. ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos); ContinueJumpTarget.block->setLoopTarget(F); // Loop body should end with destructor of Condition variable (if any). addAutomaticObjDtors(ScopePos, LoopBeginScopePos, F); // If body is not a compound statement create implicit scope // and add destructors. if (!isa<CompoundStmt>(F->getBody())) addLocalScopeAndDtors(F->getBody()); // Now populate the body block, and in the process create new blocks as we // walk the body of the loop. BodyBlock = addStmt(F->getBody()); if (!BodyBlock) { // In the case of "for (...;...;...);" we can have a null BodyBlock. // Use the continue jump target as the proxy for the body. BodyBlock = ContinueJumpTarget.block; } else if (badCFG) return nullptr; } // Because of short-circuit evaluation, the condition of the loop can span // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that // evaluate the condition. CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr; do { Expr *C = F->getCond(); // Specially handle logical operators, which have a slightly // more optimal CFG representation. if (BinaryOperator *Cond = dyn_cast_or_null<BinaryOperator>(C ? C->IgnoreParens() : nullptr)) if (Cond->isLogicalOp()) { std::tie(EntryConditionBlock, ExitConditionBlock) = VisitLogicalOperator(Cond, F, BodyBlock, LoopSuccessor); break; } // The default case when not handling logical operators. EntryConditionBlock = ExitConditionBlock = createBlock(false); ExitConditionBlock->setTerminator(F); // See if this is a known constant. TryResult KnownVal(true); if (C) { // Now add the actual condition to the condition block. // Because the condition itself may contain control-flow, new blocks may // be created. Thus we update "Succ" after adding the condition. Block = ExitConditionBlock; EntryConditionBlock = addStmt(C); // If this block contains a condition variable, add both the condition // variable and initializer to the CFG. if (VarDecl *VD = F->getConditionVariable()) { if (Expr *Init = VD->getInit()) { autoCreateBlock(); appendStmt(Block, F->getConditionVariableDeclStmt()); EntryConditionBlock = addStmt(Init); assert(Block == EntryConditionBlock); } } if (Block && badCFG) return nullptr; KnownVal = tryEvaluateBool(C); } // Add the loop body entry as a successor to the condition. addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock); // Link up the condition block with the code that follows the loop. (the // false branch). addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor); } while (false); // Link up the loop-back block to the entry condition block. addSuccessor(TransitionBlock, EntryConditionBlock); // The condition block is the implicit successor for any code above the loop. Succ = EntryConditionBlock; // If the loop contains initialization, create a new block for those // statements. This block can also contain statements that precede the loop. if (Stmt *I = F->getInit()) { Block = createBlock(); return addStmt(I); } // There is no loop initialization. We are thus basically a while loop. // NULL out Block to force lazy block construction. Block = nullptr; Succ = EntryConditionBlock; return EntryConditionBlock; } CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) { if (asc.alwaysAdd(*this, M)) { autoCreateBlock(); appendStmt(Block, M); } return Visit(M->getBase()); } CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) { // Objective-C fast enumeration 'for' statements: // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC // // for ( Type newVariable in collection_expression ) { statements } // // becomes: // // prologue: // 1. collection_expression // T. jump to loop_entry // loop_entry: // 1. side-effects of element expression // 1. ObjCForCollectionStmt [performs binding to newVariable] // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil] // TB: // statements // T. jump to loop_entry // FB: // what comes after // // and // // Type existingItem; // for ( existingItem in expression ) { statements } // // becomes: // // the same with newVariable replaced with existingItem; the binding works // the same except that for one ObjCForCollectionStmt::getElement() returns // a DeclStmt and the other returns a DeclRefExpr. // CFGBlock *LoopSuccessor = nullptr; if (Block) { if (badCFG) return nullptr; LoopSuccessor = Block; Block = nullptr; } else LoopSuccessor = Succ; // Build the condition blocks. CFGBlock *ExitConditionBlock = createBlock(false); // Set the terminator for the "exit" condition block. ExitConditionBlock->setTerminator(S); // The last statement in the block should be the ObjCForCollectionStmt, which // performs the actual binding to 'element' and determines if there are any // more items in the collection. appendStmt(ExitConditionBlock, S); Block = ExitConditionBlock; // Walk the 'element' expression to see if there are any side-effects. We // generate new blocks as necessary. We DON'T add the statement by default to // the CFG unless it contains control-flow. CFGBlock *EntryConditionBlock = Visit(S->getElement(), AddStmtChoice::NotAlwaysAdd); if (Block) { if (badCFG) return nullptr; Block = nullptr; } // The condition block is the implicit successor for the loop body as well as // any code above the loop. Succ = EntryConditionBlock; // Now create the true branch. { // Save the current values for Succ, continue and break targets. SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget), save_break(BreakJumpTarget); // Add an intermediate block between the BodyBlock and the // EntryConditionBlock to represent the "loop back" transition, for looping // back to the head of the loop. CFGBlock *LoopBackBlock = nullptr; Succ = LoopBackBlock = createBlock(); LoopBackBlock->setLoopTarget(S); BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); ContinueJumpTarget = JumpTarget(Succ, ScopePos); CFGBlock *BodyBlock = addStmt(S->getBody()); if (!BodyBlock) BodyBlock = ContinueJumpTarget.block; // can happen for "for (X in Y) ;" else if (Block) { if (badCFG) return nullptr; } // This new body block is a successor to our "exit" condition block. addSuccessor(ExitConditionBlock, BodyBlock); } // Link up the condition block with the code that follows the loop. // (the false branch). addSuccessor(ExitConditionBlock, LoopSuccessor); // Now create a prologue block to contain the collection expression. Block = createBlock(); return addStmt(S->getCollection()); } CFGBlock *CFGBuilder::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) { // Inline the body. return addStmt(S->getSubStmt()); // TODO: consider adding cleanups for the end of @autoreleasepool scope. } CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) { // FIXME: Add locking 'primitives' to CFG for @synchronized. // Inline the body. CFGBlock *SyncBlock = addStmt(S->getSynchBody()); // The sync body starts its own basic block. This makes it a little easier // for diagnostic clients. if (SyncBlock) { if (badCFG) return nullptr; Block = nullptr; Succ = SyncBlock; } // Add the @synchronized to the CFG. autoCreateBlock(); appendStmt(Block, S); // Inline the sync expression. return addStmt(S->getSynchExpr()); } CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *S) { // FIXME return NYS(); } CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) { autoCreateBlock(); // Add the PseudoObject as the last thing. appendStmt(Block, E); CFGBlock *lastBlock = Block; // Before that, evaluate all of the semantics in order. In // CFG-land, that means appending them in reverse order. for (unsigned i = E->getNumSemanticExprs(); i != 0; ) { Expr *Semantic = E->getSemanticExpr(--i); // If the semantic is an opaque value, we're being asked to bind // it to its source expression. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic)) Semantic = OVE->getSourceExpr(); if (CFGBlock *B = Visit(Semantic)) lastBlock = B; } return lastBlock; } CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) { CFGBlock *LoopSuccessor = nullptr; // Save local scope position because in case of condition variable ScopePos // won't be restored when traversing AST. SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); // Create local scope for possible condition variable. // Store scope position for continue statement. LocalScope::const_iterator LoopBeginScopePos = ScopePos; if (VarDecl *VD = W->getConditionVariable()) { addLocalScopeForVarDecl(VD); addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W); } // "while" is a control-flow statement. Thus we stop processing the current // block. if (Block) { if (badCFG) return nullptr; LoopSuccessor = Block; Block = nullptr; } else { LoopSuccessor = Succ; } CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr; // Process the loop body. { assert(W->getBody()); // Save the current values for Block, Succ, continue and break targets. SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget), save_break(BreakJumpTarget); // Create an empty block to represent the transition block for looping back // to the head of the loop. Succ = TransitionBlock = createBlock(false); TransitionBlock->setLoopTarget(W); ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos); // All breaks should go to the code following the loop. BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); // Loop body should end with destructor of Condition variable (if any). addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W); // If body is not a compound statement create implicit scope // and add destructors. if (!isa<CompoundStmt>(W->getBody())) addLocalScopeAndDtors(W->getBody()); // Create the body. The returned block is the entry to the loop body. BodyBlock = addStmt(W->getBody()); if (!BodyBlock) BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;" else if (Block && badCFG) return nullptr; } // Because of short-circuit evaluation, the condition of the loop can span // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that // evaluate the condition. CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr; do { Expr *C = W->getCond(); // Specially handle logical operators, which have a slightly // more optimal CFG representation. if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(C->IgnoreParens())) if (Cond->isLogicalOp()) { std::tie(EntryConditionBlock, ExitConditionBlock) = VisitLogicalOperator(Cond, W, BodyBlock, LoopSuccessor); break; } // The default case when not handling logical operators. ExitConditionBlock = createBlock(false); ExitConditionBlock->setTerminator(W); // Now add the actual condition to the condition block. // Because the condition itself may contain control-flow, new blocks may // be created. Thus we update "Succ" after adding the condition. Block = ExitConditionBlock; Block = EntryConditionBlock = addStmt(C); // If this block contains a condition variable, add both the condition // variable and initializer to the CFG. if (VarDecl *VD = W->getConditionVariable()) { if (Expr *Init = VD->getInit()) { autoCreateBlock(); appendStmt(Block, W->getConditionVariableDeclStmt()); EntryConditionBlock = addStmt(Init); assert(Block == EntryConditionBlock); } } if (Block && badCFG) return nullptr; // See if this is a known constant. const TryResult& KnownVal = tryEvaluateBool(C); // Add the loop body entry as a successor to the condition. addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock); // Link up the condition block with the code that follows the loop. (the // false branch). addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor); } while(false); // Link up the loop-back block to the entry condition block. addSuccessor(TransitionBlock, EntryConditionBlock); // There can be no more statements in the condition block since we loop back // to this block. NULL out Block to force lazy creation of another block. Block = nullptr; // Return the condition block, which is the dominating block for the loop. Succ = EntryConditionBlock; return EntryConditionBlock; } CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) { // FIXME: For now we pretend that @catch and the code it contains does not // exit. return Block; } CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) { // FIXME: This isn't complete. We basically treat @throw like a return // statement. // If we were in the middle of a block we stop processing that block. if (badCFG) return nullptr; // Create the new block. Block = createBlock(false); // The Exit block is the only successor. addSuccessor(Block, &cfg->getExit()); // Add the statement to the block. This may create new blocks if S contains // control-flow (short-circuit operations). return VisitStmt(S, AddStmtChoice::AlwaysAdd); } CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) { // If we were in the middle of a block we stop processing that block. if (badCFG) return nullptr; // Create the new block. Block = createBlock(false); if (TryTerminatedBlock) // The current try statement is the only successor. addSuccessor(Block, TryTerminatedBlock); else // otherwise the Exit block is the only successor. addSuccessor(Block, &cfg->getExit()); // Add the statement to the block. This may create new blocks if S contains // control-flow (short-circuit operations). return VisitStmt(T, AddStmtChoice::AlwaysAdd); } CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) { CFGBlock *LoopSuccessor = nullptr; // "do...while" is a control-flow statement. Thus we stop processing the // current block. if (Block) { if (badCFG) return nullptr; LoopSuccessor = Block; } else LoopSuccessor = Succ; // Because of short-circuit evaluation, the condition of the loop can span // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that // evaluate the condition. CFGBlock *ExitConditionBlock = createBlock(false); CFGBlock *EntryConditionBlock = ExitConditionBlock; // Set the terminator for the "exit" condition block. ExitConditionBlock->setTerminator(D); // Now add the actual condition to the condition block. Because the condition // itself may contain control-flow, new blocks may be created. if (Stmt *C = D->getCond()) { Block = ExitConditionBlock; EntryConditionBlock = addStmt(C); if (Block) { if (badCFG) return nullptr; } } // The condition block is the implicit successor for the loop body. Succ = EntryConditionBlock; // See if this is a known constant. const TryResult &KnownVal = tryEvaluateBool(D->getCond()); // Process the loop body. CFGBlock *BodyBlock = nullptr; { assert(D->getBody()); // Save the current values for Block, Succ, and continue and break targets SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget), save_break(BreakJumpTarget); // All continues within this loop should go to the condition block ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos); // All breaks should go to the code following the loop. BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); // NULL out Block to force lazy instantiation of blocks for the body. Block = nullptr; // If body is not a compound statement create implicit scope // and add destructors. if (!isa<CompoundStmt>(D->getBody())) addLocalScopeAndDtors(D->getBody()); // Create the body. The returned block is the entry to the loop body. BodyBlock = addStmt(D->getBody()); if (!BodyBlock) BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)" else if (Block) { if (badCFG) return nullptr; } if (!KnownVal.isFalse()) { // Add an intermediate block between the BodyBlock and the // ExitConditionBlock to represent the "loop back" transition. Create an // empty block to represent the transition block for looping back to the // head of the loop. // FIXME: Can we do this more efficiently without adding another block? Block = nullptr; Succ = BodyBlock; CFGBlock *LoopBackBlock = createBlock(); LoopBackBlock->setLoopTarget(D); // Add the loop body entry as a successor to the condition. addSuccessor(ExitConditionBlock, LoopBackBlock); } else addSuccessor(ExitConditionBlock, nullptr); } // Link up the condition block with the code that follows the loop. // (the false branch). addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor); // There can be no more statements in the body block(s) since we loop back to // the body. NULL out Block to force lazy creation of another block. Block = nullptr; // Return the loop body, which is the dominating block for the loop. Succ = BodyBlock; return BodyBlock; } CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) { // "continue" is a control-flow statement. Thus we stop processing the // current block. if (badCFG) return nullptr; // Now create a new block that ends with the continue statement. Block = createBlock(false); Block->setTerminator(C); // If there is no target for the continue, then we are looking at an // incomplete AST. This means the CFG cannot be constructed. if (ContinueJumpTarget.block) { addAutomaticObjDtors(ScopePos, ContinueJumpTarget.scopePosition, C); addSuccessor(Block, ContinueJumpTarget.block); } else badCFG = true; return Block; } CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E, AddStmtChoice asc) { if (asc.alwaysAdd(*this, E)) { autoCreateBlock(); appendStmt(Block, E); } // VLA types have expressions that must be evaluated. CFGBlock *lastBlock = Block; if (E->isArgumentType()) { for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr()); VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr())) lastBlock = addStmt(VA->getSizeExpr()); } return lastBlock; } /// VisitStmtExpr - Utility method to handle (nested) statement /// expressions (a GCC extension). CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) { if (asc.alwaysAdd(*this, SE)) { autoCreateBlock(); appendStmt(Block, SE); } return VisitCompoundStmt(SE->getSubStmt()); } CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) { // "switch" is a control-flow statement. Thus we stop processing the current // block. CFGBlock *SwitchSuccessor = nullptr; // Save local scope position because in case of condition variable ScopePos // won't be restored when traversing AST. SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); // Create local scope for possible condition variable. // Store scope position. Add implicit destructor. if (VarDecl *VD = Terminator->getConditionVariable()) { LocalScope::const_iterator SwitchBeginScopePos = ScopePos; addLocalScopeForVarDecl(VD); addAutomaticObjDtors(ScopePos, SwitchBeginScopePos, Terminator); } if (Block) { if (badCFG) return nullptr; SwitchSuccessor = Block; } else SwitchSuccessor = Succ; // Save the current "switch" context. SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock), save_default(DefaultCaseBlock); SaveAndRestore<JumpTarget> save_break(BreakJumpTarget); // Set the "default" case to be the block after the switch statement. If the // switch statement contains a "default:", this value will be overwritten with // the block for that code. DefaultCaseBlock = SwitchSuccessor; // Create a new block that will contain the switch statement. SwitchTerminatedBlock = createBlock(false); // Now process the switch body. The code after the switch is the implicit // successor. Succ = SwitchSuccessor; BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos); // When visiting the body, the case statements should automatically get linked // up to the switch. We also don't keep a pointer to the body, since all // control-flow from the switch goes to case/default statements. assert(Terminator->getBody() && "switch must contain a non-NULL body"); Block = nullptr; // For pruning unreachable case statements, save the current state // for tracking the condition value. SaveAndRestore<bool> save_switchExclusivelyCovered(switchExclusivelyCovered, false); // Determine if the switch condition can be explicitly evaluated. assert(Terminator->getCond() && "switch condition must be non-NULL"); Expr::EvalResult result; bool b = tryEvaluate(Terminator->getCond(), result); SaveAndRestore<Expr::EvalResult*> save_switchCond(switchCond, b ? &result : nullptr); // If body is not a compound statement create implicit scope // and add destructors. if (!isa<CompoundStmt>(Terminator->getBody())) addLocalScopeAndDtors(Terminator->getBody()); addStmt(Terminator->getBody()); if (Block) { if (badCFG) return nullptr; } // If we have no "default:" case, the default transition is to the code // following the switch body. Moreover, take into account if all the // cases of a switch are covered (e.g., switching on an enum value). // // Note: We add a successor to a switch that is considered covered yet has no // case statements if the enumeration has no enumerators. bool SwitchAlwaysHasSuccessor = false; SwitchAlwaysHasSuccessor |= switchExclusivelyCovered; SwitchAlwaysHasSuccessor |= Terminator->isAllEnumCasesCovered() && Terminator->getSwitchCaseList(); addSuccessor(SwitchTerminatedBlock, DefaultCaseBlock, !SwitchAlwaysHasSuccessor); // Add the terminator and condition in the switch block. SwitchTerminatedBlock->setTerminator(Terminator); Block = SwitchTerminatedBlock; CFGBlock *LastBlock = addStmt(Terminator->getCond()); // Finally, if the SwitchStmt contains a condition variable, add both the // SwitchStmt and the condition variable initialization to the CFG. if (VarDecl *VD = Terminator->getConditionVariable()) { if (Expr *Init = VD->getInit()) { autoCreateBlock(); appendStmt(Block, Terminator->getConditionVariableDeclStmt()); LastBlock = addStmt(Init); } } return LastBlock; } static bool shouldAddCase(bool &switchExclusivelyCovered, const Expr::EvalResult *switchCond, const CaseStmt *CS, ASTContext &Ctx) { if (!switchCond) return true; bool addCase = false; if (!switchExclusivelyCovered) { if (switchCond->Val.isInt()) { // Evaluate the LHS of the case value. const llvm::APSInt &lhsInt = CS->getLHS()->EvaluateKnownConstInt(Ctx); const llvm::APSInt &condInt = switchCond->Val.getInt(); if (condInt == lhsInt) { addCase = true; switchExclusivelyCovered = true; } else if (condInt < lhsInt) { if (const Expr *RHS = CS->getRHS()) { // Evaluate the RHS of the case value. const llvm::APSInt &V2 = RHS->EvaluateKnownConstInt(Ctx); if (V2 <= condInt) { addCase = true; switchExclusivelyCovered = true; } } } } else addCase = true; } return addCase; } CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) { // CaseStmts are essentially labels, so they are the first statement in a // block. CFGBlock *TopBlock = nullptr, *LastBlock = nullptr; if (Stmt *Sub = CS->getSubStmt()) { // For deeply nested chains of CaseStmts, instead of doing a recursion // (which can blow out the stack), manually unroll and create blocks // along the way. while (isa<CaseStmt>(Sub)) { CFGBlock *currentBlock = createBlock(false); currentBlock->setLabel(CS); if (TopBlock) addSuccessor(LastBlock, currentBlock); else TopBlock = currentBlock; addSuccessor(SwitchTerminatedBlock, shouldAddCase(switchExclusivelyCovered, switchCond, CS, *Context) ? currentBlock : nullptr); LastBlock = currentBlock; CS = cast<CaseStmt>(Sub); Sub = CS->getSubStmt(); } addStmt(Sub); } CFGBlock *CaseBlock = Block; if (!CaseBlock) CaseBlock = createBlock(); // Cases statements partition blocks, so this is the top of the basic block we // were processing (the "case XXX:" is the label). CaseBlock->setLabel(CS); if (badCFG) return nullptr; // Add this block to the list of successors for the block with the switch // statement. assert(SwitchTerminatedBlock); addSuccessor(SwitchTerminatedBlock, CaseBlock, shouldAddCase(switchExclusivelyCovered, switchCond, CS, *Context)); // We set Block to NULL to allow lazy creation of a new block (if necessary) Block = nullptr; if (TopBlock) { addSuccessor(LastBlock, CaseBlock); Succ = TopBlock; } else { // This block is now the implicit successor of other blocks. Succ = CaseBlock; } return Succ; } CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) { if (Terminator->getSubStmt()) addStmt(Terminator->getSubStmt()); DefaultCaseBlock = Block; if (!DefaultCaseBlock) DefaultCaseBlock = createBlock(); // Default statements partition blocks, so this is the top of the basic block // we were processing (the "default:" is the label). DefaultCaseBlock->setLabel(Terminator); if (badCFG) return nullptr; // Unlike case statements, we don't add the default block to the successors // for the switch statement immediately. This is done when we finish // processing the switch statement. This allows for the default case // (including a fall-through to the code after the switch statement) to always // be the last successor of a switch-terminated block. // We set Block to NULL to allow lazy creation of a new block (if necessary) Block = nullptr; // This block is now the implicit successor of other blocks. Succ = DefaultCaseBlock; return DefaultCaseBlock; } CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) { // "try"/"catch" is a control-flow statement. Thus we stop processing the // current block. CFGBlock *TrySuccessor = nullptr; if (Block) { if (badCFG) return nullptr; TrySuccessor = Block; } else TrySuccessor = Succ; CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock; // Create a new block that will contain the try statement. CFGBlock *NewTryTerminatedBlock = createBlock(false); // Add the terminator in the try block. NewTryTerminatedBlock->setTerminator(Terminator); bool HasCatchAll = false; for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) { // The code after the try is the implicit successor. Succ = TrySuccessor; CXXCatchStmt *CS = Terminator->getHandler(h); if (CS->getExceptionDecl() == nullptr) { HasCatchAll = true; } Block = nullptr; CFGBlock *CatchBlock = VisitCXXCatchStmt(CS); if (!CatchBlock) return nullptr; // Add this block to the list of successors for the block with the try // statement. addSuccessor(NewTryTerminatedBlock, CatchBlock); } if (!HasCatchAll) { if (PrevTryTerminatedBlock) addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock); else addSuccessor(NewTryTerminatedBlock, &cfg->getExit()); } // The code after the try is the implicit successor. Succ = TrySuccessor; // Save the current "try" context. SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock, NewTryTerminatedBlock); cfg->addTryDispatchBlock(TryTerminatedBlock); assert(Terminator->getTryBlock() && "try must contain a non-NULL body"); Block = nullptr; return addStmt(Terminator->getTryBlock()); } CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) { // CXXCatchStmt are treated like labels, so they are the first statement in a // block. // Save local scope position because in case of exception variable ScopePos // won't be restored when traversing AST. SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); // Create local scope for possible exception variable. // Store scope position. Add implicit destructor. if (VarDecl *VD = CS->getExceptionDecl()) { LocalScope::const_iterator BeginScopePos = ScopePos; addLocalScopeForVarDecl(VD); addAutomaticObjDtors(ScopePos, BeginScopePos, CS); } if (CS->getHandlerBlock()) addStmt(CS->getHandlerBlock()); CFGBlock *CatchBlock = Block; if (!CatchBlock) CatchBlock = createBlock(); // CXXCatchStmt is more than just a label. They have semantic meaning // as well, as they implicitly "initialize" the catch variable. Add // it to the CFG as a CFGElement so that the control-flow of these // semantics gets captured. appendStmt(CatchBlock, CS); // Also add the CXXCatchStmt as a label, to mirror handling of regular // labels. CatchBlock->setLabel(CS); // Bail out if the CFG is bad. if (badCFG) return nullptr; // We set Block to NULL to allow lazy creation of a new block (if necessary) Block = nullptr; return CatchBlock; } CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) { // C++0x for-range statements are specified as [stmt.ranged]: // // { // auto && __range = range-init; // for ( auto __begin = begin-expr, // __end = end-expr; // __begin != __end; // ++__begin ) { // for-range-declaration = *__begin; // statement // } // } // Save local scope position before the addition of the implicit variables. SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); // Create local scopes and destructors for range, begin and end variables. if (Stmt *Range = S->getRangeStmt()) addLocalScopeForStmt(Range); if (Stmt *BeginEnd = S->getBeginEndStmt()) addLocalScopeForStmt(BeginEnd); addAutomaticObjDtors(ScopePos, save_scope_pos.get(), S); LocalScope::const_iterator ContinueScopePos = ScopePos; // "for" is a control-flow statement. Thus we stop processing the current // block. CFGBlock *LoopSuccessor = nullptr; if (Block) { if (badCFG) return nullptr; LoopSuccessor = Block; } else LoopSuccessor = Succ; // Save the current value for the break targets. // All breaks should go to the code following the loop. SaveAndRestore<JumpTarget> save_break(BreakJumpTarget); BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); // The block for the __begin != __end expression. CFGBlock *ConditionBlock = createBlock(false); ConditionBlock->setTerminator(S); // Now add the actual condition to the condition block. if (Expr *C = S->getCond()) { Block = ConditionBlock; CFGBlock *BeginConditionBlock = addStmt(C); if (badCFG) return nullptr; assert(BeginConditionBlock == ConditionBlock && "condition block in for-range was unexpectedly complex"); (void)BeginConditionBlock; } // The condition block is the implicit successor for the loop body as well as // any code above the loop. Succ = ConditionBlock; // See if this is a known constant. TryResult KnownVal(true); if (S->getCond()) KnownVal = tryEvaluateBool(S->getCond()); // Now create the loop body. { assert(S->getBody()); // Save the current values for Block, Succ, and continue targets. SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget); // Generate increment code in its own basic block. This is the target of // continue statements. Block = nullptr; Succ = addStmt(S->getInc()); ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos); // The starting block for the loop increment is the block that should // represent the 'loop target' for looping back to the start of the loop. ContinueJumpTarget.block->setLoopTarget(S); // Finish up the increment block and prepare to start the loop body. assert(Block); if (badCFG) return nullptr; Block = nullptr; // Add implicit scope and dtors for loop variable. addLocalScopeAndDtors(S->getLoopVarStmt()); // Populate a new block to contain the loop body and loop variable. addStmt(S->getBody()); if (badCFG) return nullptr; CFGBlock *LoopVarStmtBlock = addStmt(S->getLoopVarStmt()); if (badCFG) return nullptr; // This new body block is a successor to our condition block. addSuccessor(ConditionBlock, KnownVal.isFalse() ? nullptr : LoopVarStmtBlock); } // Link up the condition block with the code that follows the loop (the // false branch). addSuccessor(ConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor); // Add the initialization statements. Block = createBlock(); addStmt(S->getBeginEndStmt()); return addStmt(S->getRangeStmt()); } CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E, AddStmtChoice asc) { if (BuildOpts.AddTemporaryDtors) { // If adding implicit destructors visit the full expression for adding // destructors of temporaries. TempDtorContext Context; VisitForTemporaryDtors(E->getSubExpr(), false, Context); // Full expression has to be added as CFGStmt so it will be sequenced // before destructors of it's temporaries. asc = asc.withAlwaysAdd(true); } return Visit(E->getSubExpr(), asc); } CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E, AddStmtChoice asc) { if (asc.alwaysAdd(*this, E)) { autoCreateBlock(); appendStmt(Block, E); // We do not want to propagate the AlwaysAdd property. asc = asc.withAlwaysAdd(false); } return Visit(E->getSubExpr(), asc); } CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc) { autoCreateBlock(); appendStmt(Block, C); return VisitChildren(C); } CFGBlock *CFGBuilder::VisitCXXNewExpr(CXXNewExpr *NE, AddStmtChoice asc) { autoCreateBlock(); appendStmt(Block, NE); if (NE->getInitializer()) Block = Visit(NE->getInitializer()); if (BuildOpts.AddCXXNewAllocator) appendNewAllocator(Block, NE); if (NE->isArray()) Block = Visit(NE->getArraySize()); for (CXXNewExpr::arg_iterator I = NE->placement_arg_begin(), E = NE->placement_arg_end(); I != E; ++I) Block = Visit(*I); return Block; } CFGBlock *CFGBuilder::VisitCXXDeleteExpr(CXXDeleteExpr *DE, AddStmtChoice asc) { autoCreateBlock(); appendStmt(Block, DE); QualType DTy = DE->getDestroyedType(); DTy = DTy.getNonReferenceType(); CXXRecordDecl *RD = Context->getBaseElementType(DTy)->getAsCXXRecordDecl(); if (RD) { if (RD->isCompleteDefinition() && !RD->hasTrivialDestructor()) appendDeleteDtor(Block, RD, DE); } return VisitChildren(DE); } CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E, AddStmtChoice asc) { if (asc.alwaysAdd(*this, E)) { autoCreateBlock(); appendStmt(Block, E); // We do not want to propagate the AlwaysAdd property. asc = asc.withAlwaysAdd(false); } return Visit(E->getSubExpr(), asc); } CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C, AddStmtChoice asc) { autoCreateBlock(); appendStmt(Block, C); return VisitChildren(C); } CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc) { if (asc.alwaysAdd(*this, E)) { autoCreateBlock(); appendStmt(Block, E); } return Visit(E->getSubExpr(), AddStmtChoice()); } CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) { // Lazily create the indirect-goto dispatch block if there isn't one already. CFGBlock *IBlock = cfg->getIndirectGotoBlock(); if (!IBlock) { IBlock = createBlock(false); cfg->setIndirectGotoBlock(IBlock); } // IndirectGoto is a control-flow statement. Thus we stop processing the // current block and create a new one. if (badCFG) return nullptr; Block = createBlock(false); Block->setTerminator(I); addSuccessor(Block, IBlock); return addStmt(I->getTarget()); } CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool BindToTemporary, TempDtorContext &Context) { assert(BuildOpts.AddImplicitDtors && BuildOpts.AddTemporaryDtors); tryAgain: if (!E) { badCFG = true; return nullptr; } switch (E->getStmtClass()) { default: return VisitChildrenForTemporaryDtors(E, Context); case Stmt::BinaryOperatorClass: return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E), Context); case Stmt::CXXBindTemporaryExprClass: return VisitCXXBindTemporaryExprForTemporaryDtors( cast<CXXBindTemporaryExpr>(E), BindToTemporary, Context); case Stmt::BinaryConditionalOperatorClass: case Stmt::ConditionalOperatorClass: return VisitConditionalOperatorForTemporaryDtors( cast<AbstractConditionalOperator>(E), BindToTemporary, Context); case Stmt::ImplicitCastExprClass: // For implicit cast we want BindToTemporary to be passed further. E = cast<CastExpr>(E)->getSubExpr(); goto tryAgain; case Stmt::CXXFunctionalCastExprClass: // For functional cast we want BindToTemporary to be passed further. E = cast<CXXFunctionalCastExpr>(E)->getSubExpr(); goto tryAgain; case Stmt::ParenExprClass: E = cast<ParenExpr>(E)->getSubExpr(); goto tryAgain; case Stmt::MaterializeTemporaryExprClass: { const MaterializeTemporaryExpr* MTE = cast<MaterializeTemporaryExpr>(E); BindToTemporary = (MTE->getStorageDuration() != SD_FullExpression); SmallVector<const Expr *, 2> CommaLHSs; SmallVector<SubobjectAdjustment, 2> Adjustments; // Find the expression whose lifetime needs to be extended. E = const_cast<Expr *>( cast<MaterializeTemporaryExpr>(E) ->GetTemporaryExpr() ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments)); // Visit the skipped comma operator left-hand sides for other temporaries. for (const Expr *CommaLHS : CommaLHSs) { VisitForTemporaryDtors(const_cast<Expr *>(CommaLHS), /*BindToTemporary=*/false, Context); } goto tryAgain; } case Stmt::BlockExprClass: // Don't recurse into blocks; their subexpressions don't get evaluated // here. return Block; case Stmt::LambdaExprClass: { // For lambda expressions, only recurse into the capture initializers, // and not the body. auto *LE = cast<LambdaExpr>(E); CFGBlock *B = Block; for (Expr *Init : LE->capture_inits()) { if (CFGBlock *R = VisitForTemporaryDtors( Init, /*BindToTemporary=*/false, Context)) B = R; } return B; } case Stmt::CXXDefaultArgExprClass: E = cast<CXXDefaultArgExpr>(E)->getExpr(); goto tryAgain; case Stmt::CXXDefaultInitExprClass: E = cast<CXXDefaultInitExpr>(E)->getExpr(); goto tryAgain; } } CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E, TempDtorContext &Context) { if (isa<LambdaExpr>(E)) { // Do not visit the children of lambdas; they have their own CFGs. return Block; } // When visiting children for destructors we want to visit them in reverse // order that they will appear in the CFG. Because the CFG is built // bottom-up, this means we visit them in their natural order, which // reverses them in the CFG. CFGBlock *B = Block; for (Stmt::child_range I = E->children(); I; ++I) { if (Stmt *Child = *I) if (CFGBlock *R = VisitForTemporaryDtors(Child, false, Context)) B = R; } return B; } CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors( BinaryOperator *E, TempDtorContext &Context) { if (E->isLogicalOp()) { VisitForTemporaryDtors(E->getLHS(), false, Context); TryResult RHSExecuted = tryEvaluateBool(E->getLHS()); if (RHSExecuted.isKnown() && E->getOpcode() == BO_LOr) RHSExecuted.negate(); // We do not know at CFG-construction time whether the right-hand-side was // executed, thus we add a branch node that depends on the temporary // constructor call. TempDtorContext RHSContext( bothKnownTrue(Context.KnownExecuted, RHSExecuted)); VisitForTemporaryDtors(E->getRHS(), false, RHSContext); InsertTempDtorDecisionBlock(RHSContext); return Block; } if (E->isAssignmentOp()) { // For assignment operator (=) LHS expression is visited // before RHS expression. For destructors visit them in reverse order. CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context); CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context); return LHSBlock ? LHSBlock : RHSBlock; } // For any other binary operator RHS expression is visited before // LHS expression (order of children). For destructors visit them in reverse // order. CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context); CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context); return RHSBlock ? RHSBlock : LHSBlock; } CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors( CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context) { // First add destructors for temporaries in subexpression. CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr(), false, Context); if (!BindToTemporary) { // If lifetime of temporary is not prolonged (by assigning to constant // reference) add destructor for it. const CXXDestructorDecl *Dtor = E->getTemporary()->getDestructor(); if (Dtor->isNoReturn()) { // If the destructor is marked as a no-return destructor, we need to // create a new block for the destructor which does not have as a // successor anything built thus far. Control won't flow out of this // block. if (B) Succ = B; Block = createNoReturnBlock(); } else if (Context.needsTempDtorBranch()) { // If we need to introduce a branch, we add a new block that we will hook // up to a decision block later. if (B) Succ = B; Block = createBlock(); } else { autoCreateBlock(); } if (Context.needsTempDtorBranch()) { Context.setDecisionPoint(Succ, E); } appendTemporaryDtor(Block, E); B = Block; } return B; } void CFGBuilder::InsertTempDtorDecisionBlock(const TempDtorContext &Context, CFGBlock *FalseSucc) { if (!Context.TerminatorExpr) { // If no temporary was found, we do not need to insert a decision point. return; } assert(Context.TerminatorExpr); CFGBlock *Decision = createBlock(false); Decision->setTerminator(CFGTerminator(Context.TerminatorExpr, true)); addSuccessor(Decision, Block, !Context.KnownExecuted.isFalse()); addSuccessor(Decision, FalseSucc ? FalseSucc : Context.Succ, !Context.KnownExecuted.isTrue()); Block = Decision; } CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors( AbstractConditionalOperator *E, bool BindToTemporary, TempDtorContext &Context) { VisitForTemporaryDtors(E->getCond(), false, Context); CFGBlock *ConditionBlock = Block; CFGBlock *ConditionSucc = Succ; TryResult ConditionVal = tryEvaluateBool(E->getCond()); TryResult NegatedVal = ConditionVal; if (NegatedVal.isKnown()) NegatedVal.negate(); TempDtorContext TrueContext( bothKnownTrue(Context.KnownExecuted, ConditionVal)); VisitForTemporaryDtors(E->getTrueExpr(), BindToTemporary, TrueContext); CFGBlock *TrueBlock = Block; Block = ConditionBlock; Succ = ConditionSucc; TempDtorContext FalseContext( bothKnownTrue(Context.KnownExecuted, NegatedVal)); VisitForTemporaryDtors(E->getFalseExpr(), BindToTemporary, FalseContext); if (TrueContext.TerminatorExpr && FalseContext.TerminatorExpr) { InsertTempDtorDecisionBlock(FalseContext, TrueBlock); } else if (TrueContext.TerminatorExpr) { Block = TrueBlock; InsertTempDtorDecisionBlock(TrueContext); } else { InsertTempDtorDecisionBlock(FalseContext); } return Block; } } // end anonymous namespace /// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has /// no successors or predecessors. If this is the first block created in the /// CFG, it is automatically set to be the Entry and Exit of the CFG. CFGBlock *CFG::createBlock() { bool first_block = begin() == end(); // Create the block. CFGBlock *Mem = getAllocator().Allocate<CFGBlock>(); new (Mem) CFGBlock(NumBlockIDs++, BlkBVC, this); Blocks.push_back(Mem, BlkBVC); // If this is the first block, set it as the Entry and Exit. if (first_block) Entry = Exit = &back(); // Return the block. return &back(); } /// buildCFG - Constructs a CFG from an AST. std::unique_ptr<CFG> CFG::buildCFG(const Decl *D, Stmt *Statement, ASTContext *C, const BuildOptions &BO) { CFGBuilder Builder(C, BO); return Builder.buildCFG(D, Statement); } const CXXDestructorDecl * CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const { switch (getKind()) { case CFGElement::Statement: case CFGElement::Initializer: case CFGElement::NewAllocator: llvm_unreachable("getDestructorDecl should only be used with " "ImplicitDtors"); case CFGElement::AutomaticObjectDtor: { const VarDecl *var = castAs<CFGAutomaticObjDtor>().getVarDecl(); QualType ty = var->getType(); ty = ty.getNonReferenceType(); while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) { ty = arrayType->getElementType(); } const RecordType *recordType = ty->getAs<RecordType>(); const CXXRecordDecl *classDecl = cast<CXXRecordDecl>(recordType->getDecl()); return classDecl->getDestructor(); } case CFGElement::DeleteDtor: { const CXXDeleteExpr *DE = castAs<CFGDeleteDtor>().getDeleteExpr(); QualType DTy = DE->getDestroyedType(); DTy = DTy.getNonReferenceType(); const CXXRecordDecl *classDecl = astContext.getBaseElementType(DTy)->getAsCXXRecordDecl(); return classDecl->getDestructor(); } case CFGElement::TemporaryDtor: { const CXXBindTemporaryExpr *bindExpr = castAs<CFGTemporaryDtor>().getBindTemporaryExpr(); const CXXTemporary *temp = bindExpr->getTemporary(); return temp->getDestructor(); } case CFGElement::BaseDtor: case CFGElement::MemberDtor: // Not yet supported. return nullptr; } llvm_unreachable("getKind() returned bogus value"); } bool CFGImplicitDtor::isNoReturn(ASTContext &astContext) const { if (const CXXDestructorDecl *DD = getDestructorDecl(astContext)) return DD->isNoReturn(); return false; } //===----------------------------------------------------------------------===// // CFGBlock operations. //===----------------------------------------------------------------------===// CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, bool IsReachable) : ReachableBlock(IsReachable ? B : nullptr), UnreachableBlock(!IsReachable ? B : nullptr, B && IsReachable ? AB_Normal : AB_Unreachable) {} CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock) : ReachableBlock(B), UnreachableBlock(B == AlternateBlock ? nullptr : AlternateBlock, B == AlternateBlock ? AB_Alternate : AB_Normal) {} void CFGBlock::addSuccessor(AdjacentBlock Succ, BumpVectorContext &C) { if (CFGBlock *B = Succ.getReachableBlock()) B->Preds.push_back(AdjacentBlock(this, Succ.isReachable()), C); if (CFGBlock *UnreachableB = Succ.getPossiblyUnreachableBlock()) UnreachableB->Preds.push_back(AdjacentBlock(this, false), C); Succs.push_back(Succ, C); } bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F, const CFGBlock *From, const CFGBlock *To) { if (F.IgnoreNullPredecessors && !From) return true; if (To && From && F.IgnoreDefaultsWithCoveredEnums) { // If the 'To' has no label or is labeled but the label isn't a // CaseStmt then filter this edge. if (const SwitchStmt *S = dyn_cast_or_null<SwitchStmt>(From->getTerminator().getStmt())) { if (S->isAllEnumCasesCovered()) { const Stmt *L = To->getLabel(); if (!L || !isa<CaseStmt>(L)) return true; } } } return false; } //===----------------------------------------------------------------------===// // CFG pretty printing //===----------------------------------------------------------------------===// namespace { class StmtPrinterHelper : public PrinterHelper { typedef llvm::DenseMap<const Stmt*,std::pair<unsigned,unsigned> > StmtMapTy; typedef llvm::DenseMap<const Decl*,std::pair<unsigned,unsigned> > DeclMapTy; StmtMapTy StmtMap; DeclMapTy DeclMap; signed currentBlock; unsigned currStmt; const LangOptions &LangOpts; public: StmtPrinterHelper(const CFG* cfg, const LangOptions &LO) : currentBlock(0), currStmt(0), LangOpts(LO) { for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) { unsigned j = 1; for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ; BI != BEnd; ++BI, ++j ) { if (Optional<CFGStmt> SE = BI->getAs<CFGStmt>()) { const Stmt *stmt= SE->getStmt(); std::pair<unsigned, unsigned> P((*I)->getBlockID(), j); StmtMap[stmt] = P; switch (stmt->getStmtClass()) { case Stmt::DeclStmtClass: DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P; break; case Stmt::IfStmtClass: { const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable(); if (var) DeclMap[var] = P; break; } case Stmt::ForStmtClass: { const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable(); if (var) DeclMap[var] = P; break; } case Stmt::WhileStmtClass: { const VarDecl *var = cast<WhileStmt>(stmt)->getConditionVariable(); if (var) DeclMap[var] = P; break; } case Stmt::SwitchStmtClass: { const VarDecl *var = cast<SwitchStmt>(stmt)->getConditionVariable(); if (var) DeclMap[var] = P; break; } case Stmt::CXXCatchStmtClass: { const VarDecl *var = cast<CXXCatchStmt>(stmt)->getExceptionDecl(); if (var) DeclMap[var] = P; break; } default: break; } } } } } virtual ~StmtPrinterHelper() {} const LangOptions &getLangOpts() const { return LangOpts; } void setBlockID(signed i) { currentBlock = i; } void setStmtID(unsigned i) { currStmt = i; } bool handledStmt(Stmt *S, raw_ostream &OS) override { StmtMapTy::iterator I = StmtMap.find(S); if (I == StmtMap.end()) return false; if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock && I->second.second == currStmt) { return false; } OS << "[B" << I->second.first << "." << I->second.second << "]"; return true; } bool handleDecl(const Decl *D, raw_ostream &OS) { DeclMapTy::iterator I = DeclMap.find(D); if (I == DeclMap.end()) return false; if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock && I->second.second == currStmt) { return false; } OS << "[B" << I->second.first << "." << I->second.second << "]"; return true; } }; } // end anonymous namespace namespace { class CFGBlockTerminatorPrint : public StmtVisitor<CFGBlockTerminatorPrint,void> { raw_ostream &OS; StmtPrinterHelper* Helper; PrintingPolicy Policy; public: CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper, const PrintingPolicy &Policy) : OS(os), Helper(helper), Policy(Policy) { this->Policy.IncludeNewlines = false; } void VisitIfStmt(IfStmt *I) { OS << "if "; if (Stmt *C = I->getCond()) C->printPretty(OS, Helper, Policy); } // Default case. void VisitStmt(Stmt *Terminator) { Terminator->printPretty(OS, Helper, Policy); } void VisitDeclStmt(DeclStmt *DS) { VarDecl *VD = cast<VarDecl>(DS->getSingleDecl()); OS << "static init " << VD->getName(); } void VisitForStmt(ForStmt *F) { OS << "for (" ; if (F->getInit()) OS << "..."; OS << "; "; if (Stmt *C = F->getCond()) C->printPretty(OS, Helper, Policy); OS << "; "; if (F->getInc()) OS << "..."; OS << ")"; } void VisitWhileStmt(WhileStmt *W) { OS << "while " ; if (Stmt *C = W->getCond()) C->printPretty(OS, Helper, Policy); } void VisitDoStmt(DoStmt *D) { OS << "do ... while "; if (Stmt *C = D->getCond()) C->printPretty(OS, Helper, Policy); } void VisitSwitchStmt(SwitchStmt *Terminator) { OS << "switch "; Terminator->getCond()->printPretty(OS, Helper, Policy); } void VisitCXXTryStmt(CXXTryStmt *CS) { OS << "try ..."; } void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) { if (Stmt *Cond = C->getCond()) Cond->printPretty(OS, Helper, Policy); OS << " ? ... : ..."; } void VisitChooseExpr(ChooseExpr *C) { OS << "__builtin_choose_expr( "; if (Stmt *Cond = C->getCond()) Cond->printPretty(OS, Helper, Policy); OS << " )"; } void VisitIndirectGotoStmt(IndirectGotoStmt *I) { OS << "goto *"; if (Stmt *T = I->getTarget()) T->printPretty(OS, Helper, Policy); } void VisitBinaryOperator(BinaryOperator* B) { if (!B->isLogicalOp()) { VisitExpr(B); return; } if (B->getLHS()) B->getLHS()->printPretty(OS, Helper, Policy); switch (B->getOpcode()) { case BO_LOr: OS << " || ..."; return; case BO_LAnd: OS << " && ..."; return; default: llvm_unreachable("Invalid logical operator."); } } void VisitExpr(Expr *E) { E->printPretty(OS, Helper, Policy); } public: void print(CFGTerminator T) { if (T.isTemporaryDtorsBranch()) OS << "(Temp Dtor) "; Visit(T.getStmt()); } }; } // end anonymous namespace static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper, const CFGElement &E) { if (Optional<CFGStmt> CS = E.getAs<CFGStmt>()) { const Stmt *S = CS->getStmt(); assert(S != nullptr && "Expecting non-null Stmt"); // special printing for statement-expressions. if (const StmtExpr *SE = dyn_cast<StmtExpr>(S)) { const CompoundStmt *Sub = SE->getSubStmt(); if (Sub->children()) { OS << "({ ... ; "; Helper.handledStmt(*SE->getSubStmt()->body_rbegin(),OS); OS << " })\n"; return; } } // special printing for comma expressions. if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) { if (B->getOpcode() == BO_Comma) { OS << "... , "; Helper.handledStmt(B->getRHS(),OS); OS << '\n'; return; } } S->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts())); if (isa<CXXOperatorCallExpr>(S)) { OS << " (OperatorCall)"; } else if (isa<CXXBindTemporaryExpr>(S)) { OS << " (BindTemporary)"; } else if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(S)) { OS << " (CXXConstructExpr, " << CCE->getType().getAsString() << ")"; } else if (const CastExpr *CE = dyn_cast<CastExpr>(S)) { OS << " (" << CE->getStmtClassName() << ", " << CE->getCastKindName() << ", " << CE->getType().getAsString() << ")"; } // Expressions need a newline. if (isa<Expr>(S)) OS << '\n'; } else if (Optional<CFGInitializer> IE = E.getAs<CFGInitializer>()) { const CXXCtorInitializer *I = IE->getInitializer(); if (I->isBaseInitializer()) OS << I->getBaseClass()->getAsCXXRecordDecl()->getName(); else if (I->isDelegatingInitializer()) OS << I->getTypeSourceInfo()->getType()->getAsCXXRecordDecl()->getName(); else OS << I->getAnyMember()->getName(); OS << "("; if (Expr *IE = I->getInit()) IE->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts())); OS << ")"; if (I->isBaseInitializer()) OS << " (Base initializer)\n"; else if (I->isDelegatingInitializer()) OS << " (Delegating initializer)\n"; else OS << " (Member initializer)\n"; } else if (Optional<CFGAutomaticObjDtor> DE = E.getAs<CFGAutomaticObjDtor>()) { const VarDecl *VD = DE->getVarDecl(); Helper.handleDecl(VD, OS); const Type* T = VD->getType().getTypePtr(); if (const ReferenceType* RT = T->getAs<ReferenceType>()) T = RT->getPointeeType().getTypePtr(); T = T->getBaseElementTypeUnsafe(); OS << ".~" << T->getAsCXXRecordDecl()->getName().str() << "()"; OS << " (Implicit destructor)\n"; } else if (Optional<CFGNewAllocator> NE = E.getAs<CFGNewAllocator>()) { OS << "CFGNewAllocator("; if (const CXXNewExpr *AllocExpr = NE->getAllocatorExpr()) AllocExpr->getType().print(OS, PrintingPolicy(Helper.getLangOpts())); OS << ")\n"; } else if (Optional<CFGDeleteDtor> DE = E.getAs<CFGDeleteDtor>()) { const CXXRecordDecl *RD = DE->getCXXRecordDecl(); if (!RD) return; CXXDeleteExpr *DelExpr = const_cast<CXXDeleteExpr*>(DE->getDeleteExpr()); Helper.handledStmt(cast<Stmt>(DelExpr->getArgument()), OS); OS << "->~" << RD->getName().str() << "()"; OS << " (Implicit destructor)\n"; } else if (Optional<CFGBaseDtor> BE = E.getAs<CFGBaseDtor>()) { const CXXBaseSpecifier *BS = BE->getBaseSpecifier(); OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()"; OS << " (Base object destructor)\n"; } else if (Optional<CFGMemberDtor> ME = E.getAs<CFGMemberDtor>()) { const FieldDecl *FD = ME->getFieldDecl(); const Type *T = FD->getType()->getBaseElementTypeUnsafe(); OS << "this->" << FD->getName(); OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()"; OS << " (Member object destructor)\n"; } else if (Optional<CFGTemporaryDtor> TE = E.getAs<CFGTemporaryDtor>()) { const CXXBindTemporaryExpr *BT = TE->getBindTemporaryExpr(); OS << "~"; BT->getType().print(OS, PrintingPolicy(Helper.getLangOpts())); OS << "() (Temporary object destructor)\n"; } } static void print_block(raw_ostream &OS, const CFG* cfg, const CFGBlock &B, StmtPrinterHelper &Helper, bool print_edges, bool ShowColors) { Helper.setBlockID(B.getBlockID()); // Print the header. if (ShowColors) OS.changeColor(raw_ostream::YELLOW, true); OS << "\n [B" << B.getBlockID(); if (&B == &cfg->getEntry()) OS << " (ENTRY)]\n"; else if (&B == &cfg->getExit()) OS << " (EXIT)]\n"; else if (&B == cfg->getIndirectGotoBlock()) OS << " (INDIRECT GOTO DISPATCH)]\n"; else if (B.hasNoReturnElement()) OS << " (NORETURN)]\n"; else OS << "]\n"; if (ShowColors) OS.resetColor(); // Print the label of this block. if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) { if (print_edges) OS << " "; if (LabelStmt *L = dyn_cast<LabelStmt>(Label)) OS << L->getName(); else if (CaseStmt *C = dyn_cast<CaseStmt>(Label)) { OS << "case "; if (C->getLHS()) C->getLHS()->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts())); if (C->getRHS()) { OS << " ... "; C->getRHS()->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts())); } } else if (isa<DefaultStmt>(Label)) OS << "default"; else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) { OS << "catch ("; if (CS->getExceptionDecl()) CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper.getLangOpts()), 0); else OS << "..."; OS << ")"; } else llvm_unreachable("Invalid label statement in CFGBlock."); OS << ":\n"; } // Iterate through the statements in the block and print them. unsigned j = 1; for (CFGBlock::const_iterator I = B.begin(), E = B.end() ; I != E ; ++I, ++j ) { // Print the statement # in the basic block and the statement itself. if (print_edges) OS << " "; OS << llvm::format("%3d", j) << ": "; Helper.setStmtID(j); print_elem(OS, Helper, *I); } // Print the terminator of this block. if (B.getTerminator()) { if (ShowColors) OS.changeColor(raw_ostream::GREEN); OS << " T: "; Helper.setBlockID(-1); PrintingPolicy PP(Helper.getLangOpts()); CFGBlockTerminatorPrint TPrinter(OS, &Helper, PP); TPrinter.print(B.getTerminator()); OS << '\n'; if (ShowColors) OS.resetColor(); } if (print_edges) { // Print the predecessors of this block. if (!B.pred_empty()) { const raw_ostream::Colors Color = raw_ostream::BLUE; if (ShowColors) OS.changeColor(Color); OS << " Preds " ; if (ShowColors) OS.resetColor(); OS << '(' << B.pred_size() << "):"; unsigned i = 0; if (ShowColors) OS.changeColor(Color); for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end(); I != E; ++I, ++i) { if (i % 10 == 8) OS << "\n "; CFGBlock *B = *I; bool Reachable = true; if (!B) { Reachable = false; B = I->getPossiblyUnreachableBlock(); } OS << " B" << B->getBlockID(); if (!Reachable) OS << "(Unreachable)"; } if (ShowColors) OS.resetColor(); OS << '\n'; } // Print the successors of this block. if (!B.succ_empty()) { const raw_ostream::Colors Color = raw_ostream::MAGENTA; if (ShowColors) OS.changeColor(Color); OS << " Succs "; if (ShowColors) OS.resetColor(); OS << '(' << B.succ_size() << "):"; unsigned i = 0; if (ShowColors) OS.changeColor(Color); for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end(); I != E; ++I, ++i) { if (i % 10 == 8) OS << "\n "; CFGBlock *B = *I; bool Reachable = true; if (!B) { Reachable = false; B = I->getPossiblyUnreachableBlock(); } if (B) { OS << " B" << B->getBlockID(); if (!Reachable) OS << "(Unreachable)"; } else { OS << " NULL"; } } if (ShowColors) OS.resetColor(); OS << '\n'; } } } /// dump - A simple pretty printer of a CFG that outputs to stderr. void CFG::dump(const LangOptions &LO, bool ShowColors) const { print(llvm::errs(), LO, ShowColors); } /// print - A simple pretty printer of a CFG that outputs to an ostream. void CFG::print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const { StmtPrinterHelper Helper(this, LO); // Print the entry block. print_block(OS, this, getEntry(), Helper, true, ShowColors); // Iterate through the CFGBlocks and print them one by one. for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) { // Skip the entry block, because we already printed it. if (&(**I) == &getEntry() || &(**I) == &getExit()) continue; print_block(OS, this, **I, Helper, true, ShowColors); } // Print the exit block. print_block(OS, this, getExit(), Helper, true, ShowColors); OS << '\n'; OS.flush(); } /// dump - A simply pretty printer of a CFGBlock that outputs to stderr. void CFGBlock::dump(const CFG* cfg, const LangOptions &LO, bool ShowColors) const { print(llvm::errs(), cfg, LO, ShowColors); } void CFGBlock::dump() const { dump(getParent(), LangOptions(), false); } /// print - A simple pretty printer of a CFGBlock that outputs to an ostream. /// Generally this will only be called from CFG::print. void CFGBlock::print(raw_ostream &OS, const CFG* cfg, const LangOptions &LO, bool ShowColors) const { StmtPrinterHelper Helper(cfg, LO); print_block(OS, cfg, *this, Helper, true, ShowColors); OS << '\n'; } /// printTerminator - A simple pretty printer of the terminator of a CFGBlock. void CFGBlock::printTerminator(raw_ostream &OS, const LangOptions &LO) const { CFGBlockTerminatorPrint TPrinter(OS, nullptr, PrintingPolicy(LO)); TPrinter.print(getTerminator()); } Stmt *CFGBlock::getTerminatorCondition(bool StripParens) { Stmt *Terminator = this->Terminator; if (!Terminator) return nullptr; Expr *E = nullptr; switch (Terminator->getStmtClass()) { default: break; case Stmt::CXXForRangeStmtClass: E = cast<CXXForRangeStmt>(Terminator)->getCond(); break; case Stmt::ForStmtClass: E = cast<ForStmt>(Terminator)->getCond(); break; case Stmt::WhileStmtClass: E = cast<WhileStmt>(Terminator)->getCond(); break; case Stmt::DoStmtClass: E = cast<DoStmt>(Terminator)->getCond(); break; case Stmt::IfStmtClass: E = cast<IfStmt>(Terminator)->getCond(); break; case Stmt::ChooseExprClass: E = cast<ChooseExpr>(Terminator)->getCond(); break; case Stmt::IndirectGotoStmtClass: E = cast<IndirectGotoStmt>(Terminator)->getTarget(); break; case Stmt::SwitchStmtClass: E = cast<SwitchStmt>(Terminator)->getCond(); break; case Stmt::BinaryConditionalOperatorClass: E = cast<BinaryConditionalOperator>(Terminator)->getCond(); break; case Stmt::ConditionalOperatorClass: E = cast<ConditionalOperator>(Terminator)->getCond(); break; case Stmt::BinaryOperatorClass: // '&&' and '||' E = cast<BinaryOperator>(Terminator)->getLHS(); break; case Stmt::ObjCForCollectionStmtClass: return Terminator; } if (!StripParens) return E; return E ? E->IgnoreParens() : nullptr; } //===----------------------------------------------------------------------===// // CFG Graphviz Visualization //===----------------------------------------------------------------------===// #ifndef NDEBUG static StmtPrinterHelper* GraphHelper; #endif void CFG::viewCFG(const LangOptions &LO) const { #ifndef NDEBUG StmtPrinterHelper H(this, LO); GraphHelper = &H; llvm::ViewGraph(this,"CFG"); GraphHelper = nullptr; #endif } namespace llvm { template<> struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits { DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {} static std::string getNodeLabel(const CFGBlock *Node, const CFG* Graph) { #ifndef NDEBUG std::string OutSStr; llvm::raw_string_ostream Out(OutSStr); print_block(Out,Graph, *Node, *GraphHelper, false, false); std::string& OutStr = Out.str(); if (OutStr[0] == '\n') OutStr.erase(OutStr.begin()); // Process string output to make it nicer... for (unsigned i = 0; i != OutStr.length(); ++i) if (OutStr[i] == '\n') { // Left justify OutStr[i] = '\\'; OutStr.insert(OutStr.begin()+i+1, 'l'); } return OutStr; #else return ""; #endif } }; } // end namespace llvm
{ "content_hash": "0cf4fc441712524bbfacb7830a5df846", "timestamp": "", "source": "github", "line_count": 4572, "max_line_length": 82, "avg_line_length": 33.14020122484689, "alnum_prop": 0.6536032260406422, "repo_name": "Fairly/opencor", "id": "3836195aeaba4fe0608916dab63a248fe1ed8f66", "size": "151517", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/plugins/thirdParty/LLVM/tools/clang/lib/Analysis/CFG.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "1617" }, { "name": "Batchfile", "bytes": "5129" }, { "name": "C", "bytes": "9283641" }, { "name": "C++", "bytes": "127655731" }, { "name": "CMake", "bytes": "216018" }, { "name": "HTML", "bytes": "9294" }, { "name": "NSIS", "bytes": "4599" }, { "name": "Objective-C", "bytes": "282234" }, { "name": "PHP", "bytes": "317578" }, { "name": "Shell", "bytes": "2879" }, { "name": "SourcePawn", "bytes": "1544" }, { "name": "Visual Basic", "bytes": "332" }, { "name": "XSLT", "bytes": "58213" } ], "symlink_target": "" }
package org.drools.core.common; import org.drools.core.impl.InternalKnowledgeBase; import org.drools.core.reteoo.SegmentMemory; import org.kie.internal.runtime.StatefulKnowledgeSession; import java.util.HashSet; import java.util.Set; import java.util.concurrent.atomic.AtomicReferenceArray; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * A concurrent implementation for the node memories interface */ public class ConcurrentNodeMemories implements NodeMemories { private AtomicReferenceArray<Memory> memories; private Lock lock; private InternalKnowledgeBase kBase; public ConcurrentNodeMemories( InternalKnowledgeBase kBase ) { this.kBase = kBase; this.memories = new AtomicReferenceArray<Memory>( this.kBase.getNodeCount() ); this.lock = new ReentrantLock(); } public void clearNodeMemory( MemoryFactory node ) { this.memories.set( node.getId(), null ); } public void clear() { this.memories = new AtomicReferenceArray<Memory>( this.kBase.getNodeCount() ); } public void resetAllMemories(StatefulKnowledgeSession session) { InternalKnowledgeBase kBase = (InternalKnowledgeBase)session.getKieBase(); Set<SegmentMemory> smems = new HashSet<SegmentMemory>(); for (int i = 0; i < memories.length(); i++) { Memory memory = memories.get(i); if (memory != null) { if (memory.getSegmentMemory() != null) { smems.add(memory.getSegmentMemory()); } memory.reset(); } } for (SegmentMemory smem : smems) { smem.reset(kBase.getSegmentPrototype(smem)); if ( smem.isSegmentLinked() ) { smem.notifyRuleLinkSegment((InternalWorkingMemory)session); } } } /** * The implementation tries to delay locking as much as possible, by running * some potentialy unsafe opperations out of the critical session. In case it * fails the checks, it will move into the critical sessions and re-check everything * before effectively doing any change on data structures. */ public Memory getNodeMemory(MemoryFactory node, InternalWorkingMemory wm) { if( node.getId() >= this.memories.length() ) { resize( node ); } Memory memory = this.memories.get( node.getId() ); if( memory == null ) { memory = createNodeMemory( node, wm ); } return memory; } /** * Checks if a memory does not exists for the given node and * creates it. */ private Memory createNodeMemory( MemoryFactory node, InternalWorkingMemory wm ) { try { this.lock.lock(); // need to try again in a synchronized code block to make sure // it was not created yet Memory memory = this.memories.get( node.getId() ); if( memory == null ) { memory = node.createMemory( this.kBase.getConfiguration(), wm ); if( !this.memories.compareAndSet( node.getId(), null, memory ) ) { memory = this.memories.get( node.getId() ); } } return memory; } finally { this.lock.unlock(); } } /** * @param node */ private void resize( MemoryFactory node ) { try { this.lock.lock(); if( node.getId() >= this.memories.length() ) { // adding some buffer for new nodes, so that we reduce array copies int size = Math.max( this.kBase.getNodeCount(), node.getId() + 32 ); AtomicReferenceArray<Memory> newMem = new AtomicReferenceArray<Memory>( size ); for ( int i = 0; i < this.memories.length(); i++ ) { newMem.set( i, this.memories.get( i ) ); } this.memories = newMem; } } finally { this.lock.unlock(); } } public void setKnowledgeBaseReference( InternalKnowledgeBase kBase ) { this.kBase = kBase; } public Memory peekNodeMemory(int nodeId) { return this.memories.get( nodeId ); } public int length() { return this.memories.length(); } }
{ "content_hash": "c747a073235405e13bc56260393e32d5", "timestamp": "", "source": "github", "line_count": 141, "max_line_length": 95, "avg_line_length": 32.01418439716312, "alnum_prop": 0.5777580859548073, "repo_name": "TonnyFeng/drools", "id": "14bd9c8d20048a296dd26d924e3bb8ee85ef6b8f", "size": "5107", "binary": false, "copies": "13", "ref": "refs/heads/master", "path": "drools-core/src/main/java/org/drools/core/common/ConcurrentNodeMemories.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2554" }, { "name": "CSS", "bytes": "1412" }, { "name": "GAP", "bytes": "197125" }, { "name": "HTML", "bytes": "10808" }, { "name": "Java", "bytes": "27263264" }, { "name": "Protocol Buffer", "bytes": "13819" }, { "name": "Python", "bytes": "4529" }, { "name": "Ruby", "bytes": "491" }, { "name": "Shell", "bytes": "1120" }, { "name": "Standard ML", "bytes": "82260" }, { "name": "XSLT", "bytes": "24302" } ], "symlink_target": "" }
module Moe module Sequence module Locksmith module ModuleFunctions def itemize(owner_id, payload, sequence_id, timestamp, uid) { "hash" => owner_id, "range" => "#{sequence_id}.#{timestamp}.#{uid}", "payload" => MultiJson.dump(payload) } end def key(owner_id, sequence_id, timestamp, uid) { "hash" => owner_id, "range" => "#{sequence_id}.#{timestamp}.#{uid}" } end end extend ModuleFunctions end end end
{ "content_hash": "910b71031b8ba3e02c6d56a4eaa0397b", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 67, "avg_line_length": 23.08, "alnum_prop": 0.48873483535528595, "repo_name": "Geezeo/moe", "id": "167400c4a20ff88e57e72bf2a88181472a114d0e", "size": "577", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "lib/moe/sequence/locksmith.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "27037" } ], "symlink_target": "" }
> Compile a folder of SVG files into variables in a JavaScript file, ready for injection into HTML. This plugin creates an SVG icon system by creating a JavaScript file for injecting inline SVG into HTML. For a detailed description on how JavaScript SVG injection works - see this article [here](http://www.pencilscoop.com/2014/04/injecting-svg-with-javascript/) ## Getting Started This plugin requires Grunt `~0.4.1` If you haven't used [Grunt](http://gruntjs.com/) before, be sure to check out the [Getting Started](http://gruntjs.com/getting-started) guide, as it explains how to create a [Gruntfile](http://gruntjs.com/sample-gruntfile) as well as install and use Grunt plugins. Once you're familiar with that process, you may install this plugin with this command: ```shell npm install grunt-svginject --save-dev ``` One the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript: ```js grunt.loadNpmTasks('grunt-svginject'); ``` ### Overview In your project's Gruntfile, add a section named `svginject` to the data object passed into `grunt.initConfig()`. ```js grunt.initConfig({ svginject: { all : { options: {}, files: { //output : input], } } } }) ``` ### Usage Examples #### Default Options ```js grunt.initConfig({ svginject: { all : { options: {}, files: { 'dest/SVGinject.js': ['svgs/*.svg'], } } } }) ``` #### An example Using the above config, let’s go through an example. Say the folder “svgs” contains 3 .SVG files - icon1.svg, icon2.svg and icon3.svg. Those SVG files contain something this: ```html <svg><circle fill="#EC008C" cx="46.921" cy="57.107" r="31.759"/></svg> ``` SVGinject will then create a single JavaScript file at “dest/SVGinject.js” with the following (including the comments and in this spaced format): ```js document.addEventListener('DOMContentLoaded', function(){ // // SVG icon 1 var SVGicon1 = document.querySelectorAll('.svg-icon1'); for (i = 0; i < SVGicon1.length; ++i) { SVGicon1[i].innerHTML = '<svg><circle fill="#EC008C" cx="46.921" cy="57.107" r="31.759"/></svg>'; } // // SVG icon 2 var SVGicon2 = document.querySelectorAll('.svg-icon2'); for (i = 0; i < SVGicon2.length; ++i) { SVGicon2[i].innerHTML = '<svg><circle fill="#EC008C" cx="46.921" cy="57.107" r="31.759"/></svg>'; } // SVG icon 3 var SVGicon3 = document.querySelectorAll('.svg-icon3'); for (i = 0; i < SVGicon3.length; ++i) { SVGicon3[i].innerHTML = '<svg><circle fill="#EC008C" cx="46.921" cy="57.107" r="31.759"/></svg>'; } }); ``` To include those SVGs in HTML, all you would do is this: ```html <span class="svg-icon1"></span> <span class="svg-icon2"></span> <span class="svg-icon3"></span> ``` Inline SVG markup will then be appended to those elements. So if the script is included in that document, the above would result in this: ```html <span class="svg-icon1"><svg><circle fill="#EC008C" cx="46.921" cy="57.107" r="31.759"/></svg></span> <span class="svg-icon2"><svg><circle fill="#EC008C" cx="46.921" cy="57.107" r="31.759"/></svg></span> <span class="svg-icon3"><svg><circle fill="#EC008C" cx="46.921" cy="57.107" r="31.759"/></svg></span> ``` Note that it supports multiple classes so the below would also work : ```html <span class="svg-icon1"></span> <span class="svg-icon1"></span> <span class="svg-icon1"></span> ``` ### Usage Notes The plugin will automatically minify all SVGs. This is handled when building the injection functions, so origional SVG files remain unchanged. It will also replace any single-quotation <code> ' ' </code> marks with double-quotation marks <code>" "</code>. This is because they are placed inside single quote marks in the JavaScript out. Again this handled when the injection function is built - origional SVG files will remain unchanged. The class names are named by the file-name with the prefix <code>svg-</code>. So a source-file named "icon1.svg" will be inserted into any class named <code>svg-icon1</code>. ## Contributing In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [Grunt](http://gruntjs.com/). ## Release History ### v0.0.2 - Minor Improvements - Added function to auto-minify of SVG files. - Added function to auto-replace quote marks of SVG files. - Inject compiles result for injection.
{ "content_hash": "6cb289c484f340a1f4580b0648104d38", "timestamp": "", "source": "github", "line_count": 133, "max_line_length": 351, "avg_line_length": 33.36842105263158, "alnum_prop": 0.6946822893195133, "repo_name": "fmnguyen/coffee-vis", "id": "e06f46961535da48348b5763728455a055ec8875", "size": "4467", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "node_modules/grunt-svginject/README.md", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "63816" }, { "name": "HTML", "bytes": "7317" }, { "name": "JavaScript", "bytes": "5287" } ], "symlink_target": "" }
package org.apache.flink.runtime.io.network.partition; import org.apache.flink.runtime.io.network.buffer.Buffer; import org.apache.flink.util.IOUtils; import org.apache.flink.shaded.netty4.io.netty.util.internal.PlatformDependent; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import static org.apache.flink.util.Preconditions.checkArgument; import static org.apache.flink.util.Preconditions.checkNotNull; import static org.apache.flink.util.Preconditions.checkState; /** * An implementation of {@link BoundedData} that writes directly into a File Channel * and maps the file into memory after writing. Readers simply access the memory mapped * data. All readers access the same memory, which is mapped in a read-only manner. * * <p>Similarly as the {@link MemoryMappedBoundedData}, this implementation needs to work around * the fact that the memory mapped regions cannot exceed 2GB in Java. While the implementation writes * to the a single file, the result may be multiple memory mapped buffers. * * <h2>Important!</h2> * * <p>This class performs absolutely no synchronization and relies on single threaded access * or externally synchronized access. Concurrent access around disposal may cause * segmentation faults! */ final class FileChannelMemoryMappedBoundedData implements BoundedData { /** The file channel backing the memory mapped file. */ private final FileChannel fileChannel; /** The reusable array with header buffer and data buffer, to use gathering writes on the * file channel ({@link java.nio.channels.GatheringByteChannel#write(ByteBuffer[])}). */ private final ByteBuffer[] headerAndBufferArray; /** All memory mapped regions. */ private final ArrayList<ByteBuffer> memoryMappedRegions; /** The path of the memory mapped file. */ private final Path filePath; /** The position in the file channel. Cached for efficiency, because an actual position * lookup in the channel involves various locks and checks. */ private long pos; /** The position where the current memory mapped region must end. */ private long endOfCurrentRegion; /** The position where the current memory mapped started. */ private long startOfCurrentRegion; /** The maximum size of each mapped region. */ private final long maxRegionSize; FileChannelMemoryMappedBoundedData( Path filePath, FileChannel fileChannel, int maxSizePerMappedRegion) { this.filePath = filePath; this.fileChannel = fileChannel; this.headerAndBufferArray = BufferReaderWriterUtil.allocatedWriteBufferArray(); this.memoryMappedRegions = new ArrayList<>(4); this.maxRegionSize = maxSizePerMappedRegion; this.endOfCurrentRegion = maxSizePerMappedRegion; } @Override public void writeBuffer(Buffer buffer) throws IOException { if (tryWriteBuffer(buffer)) { return; } mapRegionAndStartNext(); if (!tryWriteBuffer(buffer)) { throwTooLargeBuffer(buffer); } } private boolean tryWriteBuffer(Buffer buffer) throws IOException { final long spaceLeft = endOfCurrentRegion - pos; final long bytesWritten = BufferReaderWriterUtil.writeToByteChannelIfBelowSize( fileChannel, buffer, headerAndBufferArray, spaceLeft); if (bytesWritten >= 0) { pos += bytesWritten; return true; } else { return false; } } @Override public BoundedData.Reader createReader() { checkState(!fileChannel.isOpen()); final List<ByteBuffer> buffers = memoryMappedRegions.stream() .map((bb) -> bb.duplicate().order(ByteOrder.nativeOrder())) .collect(Collectors.toList()); return new MemoryMappedBoundedData.BufferSlicer(buffers); } /** * Finishes the current region and prevents further writes. * After calling this method, further calls to {@link #writeBuffer(Buffer)} will fail. */ @Override public void finishWrite() throws IOException { mapRegionAndStartNext(); fileChannel.close(); } /** * Closes the file and unmaps all memory mapped regions. * After calling this method, access to any ByteBuffer obtained from this instance * will cause a segmentation fault. */ public void close() throws IOException { IOUtils.closeQuietly(fileChannel); for (ByteBuffer bb : memoryMappedRegions) { PlatformDependent.freeDirectBuffer(bb); } memoryMappedRegions.clear(); // To make this compatible with all versions of Windows, we must wait with // deleting the file until it is unmapped. // See also https://stackoverflow.com/questions/11099295/file-flag-delete-on-close-and-memory-mapped-files/51649618#51649618 Files.delete(filePath); } @Override public long getSize() { return pos; } private void mapRegionAndStartNext() throws IOException { final ByteBuffer region = fileChannel.map(MapMode.READ_ONLY, startOfCurrentRegion, pos - startOfCurrentRegion); region.order(ByteOrder.nativeOrder()); memoryMappedRegions.add(region); startOfCurrentRegion = pos; endOfCurrentRegion = startOfCurrentRegion + maxRegionSize; } private void throwTooLargeBuffer(Buffer buffer) throws IOException { throw new IOException(String.format( "The buffer (%d bytes) is larger than the maximum size of a memory buffer (%d bytes)", buffer.getSize(), maxRegionSize)); } // ------------------------------------------------------------------------ // Factories // ------------------------------------------------------------------------ /** * Creates new FileChannelMemoryMappedBoundedData, creating a memory mapped file at the given path. */ public static FileChannelMemoryMappedBoundedData create(Path memMappedFilePath) throws IOException { return createWithRegionSize(memMappedFilePath, Integer.MAX_VALUE); } /** * Creates new FileChannelMemoryMappedBoundedData, creating a memory mapped file at the given path. * Each mapped region (= ByteBuffer) will be of the given size. */ public static FileChannelMemoryMappedBoundedData createWithRegionSize(Path memMappedFilePath, int regionSize) throws IOException { checkNotNull(memMappedFilePath, "memMappedFilePath"); checkArgument(regionSize > 0, "regions size most be > 0"); final FileChannel fileChannel = FileChannel.open(memMappedFilePath, StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW); return new FileChannelMemoryMappedBoundedData(memMappedFilePath, fileChannel, regionSize); } }
{ "content_hash": "a4c510d222a94aad432a50d46cae25fd", "timestamp": "", "source": "github", "line_count": 194, "max_line_length": 131, "avg_line_length": 34.170103092783506, "alnum_prop": 0.7518479408658922, "repo_name": "shaoxuan-wang/flink", "id": "4a71fcdd1ac3ca7ddbc7aef990db80c4c64b08be", "size": "7434", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/FileChannelMemoryMappedBoundedData.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "4588" }, { "name": "CSS", "bytes": "57936" }, { "name": "Clojure", "bytes": "90539" }, { "name": "Dockerfile", "bytes": "10807" }, { "name": "FreeMarker", "bytes": "11851" }, { "name": "HTML", "bytes": "224454" }, { "name": "Java", "bytes": "46844396" }, { "name": "JavaScript", "bytes": "1829" }, { "name": "Makefile", "bytes": "5134" }, { "name": "Python", "bytes": "733285" }, { "name": "Scala", "bytes": "12596192" }, { "name": "Shell", "bytes": "461101" }, { "name": "TypeScript", "bytes": "243702" } ], "symlink_target": "" }
// // breakout.c // // Chashmeet Singh // // CS 50 // // standard libraries #define _XOPEN_SOURCE #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> // Stanford Portable Library #include "spl/gevents.h" #include "spl/gobjects.h" #include "spl/gwindow.h" // height and width of game's window in pixels #define HEIGHT 600 #define WIDTH 400 // number of rows of bricks #define ROWS 5 // number of columns of bricks #define COLS 10 // radius of ball in pixels #define RADIUS 10 // lives #define LIVES 3 // prototypes void initBricks(GWindow window); GOval initBall(GWindow window); GRect initPaddle(GWindow window); GLabel initScoreboard(GWindow window); void updateScoreboard(GWindow window, GLabel label, int points); GObject detectCollision(GWindow window, GOval ball); double velocityX; double velocityY; int main(void) { // instantiate window GWindow window = newGWindow(WIDTH, HEIGHT); // instantiate bricks initBricks(window); // instantiate ball, centered in middle of window GOval ball = initBall(window); // instantiate paddle, centered at bottom of window GRect paddle = initPaddle(window); // instantiate scoreboard, centered in middle of window, just above ball GLabel label = initScoreboard(window); // number of bricks initially int bricks = COLS * ROWS; // number of lives initially int lives = LIVES; // number of points initially int points = 0; // wait for click before starting waitForClick(); velocityX = 1.0; velocityY = 2.5; // keep playing until game over while (lives > 0 && bricks > 0) { // Scoreboard updateScoreboard(window, label, points); // move ball move(ball, velocityX, velocityY); pause(10); // check for mouse event. GEvent event = getNextEvent(MOUSE_EVENT); // Lock the paddle X to the cursor. if (event != NULL) { // if the event was movement if (getEventType(event) == MOUSE_MOVED) { // ensure paddle follows top cursor double x = getX(event) - getWidth(paddle) / 2; double y = 500; setLocation(paddle, x, y); } } GObject object = detectCollision(window, ball); if (object != NULL) { // If the ball hits the paddle. if (object == paddle) { velocityY = -velocityY; } // If the ball hits a block. Remove block, add a point, decrement count and bounce. else if (strcmp(getType(object), "GRect") == 0) { removeGWindow(window, object); velocityY = -velocityY; points++; bricks--; } } // If the ball hits the right wall. if (getX(ball) + getWidth(ball) >= getWidth(window)) { velocityX = -velocityX; } // If the ball hits the left wall. if (getX(ball) <= 0) { velocityX = -velocityX; } // If the ball hits the top wall. if (getY(ball) <= 0) { velocityY = -velocityY; } // Remove a life. Start over. if (getY(ball) + getHeight(ball) >= getHeight(window)) { lives--; //move ball to start setLocation(ball, 190, 200); //move paddle to start setLocation(paddle, 160, 500); waitForClick(); } } // You Lose Label Message for kicks. if (bricks > 0) { GLabel game_over = newGLabel("YOU LOSE!"); setFont(game_over, "SansSerif-70"); setColor(game_over, "RED"); add(window, game_over); setLocation(game_over, 15, 300); } else { GLabel game_over = newGLabel("YOU WIN!"); setFont(game_over, "SansSerif-70"); setColor(game_over, "GREEN"); add(window, game_over); setLocation(game_over, 15, 300); } // wait for click before exiting waitForClick(); // game over closeGWindow(window); return 0; } /** * Initializes window with a grid of bricks. */ void initBricks(GWindow window) { // initial starting Y position of the bricks. int brick_y = 50; // the space between each line. int row_space = 20; // 5 rows of bricks. for (int i = 0; i < ROWS; i++) { // initial starting X pos. int brick_x = 2; //10 bricks per row. for (int j = 0; j < COLS; j++) { GRect brick = newGRect(brick_x + 5, brick_y, 35, 10); // Setting colors based on row. Not elegant. if (i == 0) { setColor(brick, "RED"); } if (i == 1) { setColor(brick, "ORANGE"); } if (i == 2) { setColor(brick, "YELLOW"); } if (i == 3) { setColor(brick, "GREEN"); } if (i == 4) { setColor(brick, "BLUE"); } setFilled(brick, true); add(window, brick); brick_x = brick_x + 39; } brick_y = brick_y + 15; } } /** * Instantiates ball in center of window. Returns ball. */ GOval initBall(GWindow window) { GOval ball = newGOval(200 - 10, 200, 20, 20); setColor(ball, "BLACK"); setFilled(ball, true); add(window, ball); return ball; } /** * Instantiates paddle in bottom-middle of window. */ GRect initPaddle(GWindow window) { GRect paddle = newGRect(200 - 35, 500, 70, 10); // purple color setColor(paddle, "BLUE"); setFilled(paddle, true); add(window, paddle); return paddle; } /** * Instantiates, configures, and returns label for scoreboard. */ GLabel initScoreboard(GWindow window) { GLabel label = newGLabel(" "); setFont(label, "SansSerif-50"); setColor(label, "C0C0C0"); add(window, label); setLocation(label, 185, 300); return label; } /** * Updates scoreboard's label, keeping it centered in window. */ void updateScoreboard(GWindow window, GLabel label, int points) { // update label char s[12]; sprintf(s, "%i", points); setLabel(label, s); // center label in window double x = (getWidth(window) - getWidth(label)) / 2; double y = (getHeight(window) - getHeight(label)) / 2; setLocation(label, x, y); } /** * Detects whether ball has collided with some object in window * by checking the four corners of its bounding box (which are * outside the ball's GOval, and so the ball can't collide with * itself). Returns object if so, else NULL. */ GObject detectCollision(GWindow window, GOval ball) { // ball's location double x = getX(ball); double y = getY(ball); // for checking for collisions GObject object; // check for collision at ball's top-left corner object = getGObjectAt(window, x, y); if (object != NULL) { return object; } // check for collision at ball's top-right corner object = getGObjectAt(window, x + 2 * RADIUS, y); if (object != NULL) { return object; } // check for collision at ball's bottom-left corner object = getGObjectAt(window, x, y + 2 * RADIUS); if (object != NULL) { return object; } // check for collision at ball's bottom-right corner object = getGObjectAt(window, x + 2 * RADIUS, y + 2 * RADIUS); if (object != NULL) { return object; } // no collision return NULL; }
{ "content_hash": "3527bcb61f3379363c7c004adcb79d45", "timestamp": "", "source": "github", "line_count": 337, "max_line_length": 95, "avg_line_length": 23.617210682492583, "alnum_prop": 0.5446664153788164, "repo_name": "chashmeetsingh/CS-50-Breakout.c", "id": "b89dc0e382279853f048c58bc8b1f7a270f31242", "size": "7959", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "breakout.c", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "7959" } ], "symlink_target": "" }
import copy import mock import six from heat.common import exception from heat.common import grouputils from heat.common import template_format from heat.engine import resource from heat.engine.resources.openstack.heat import instance_group as instgrp from heat.engine import rsrc_defn from heat.engine import scheduler from heat.engine import stack as parser from heat.tests.autoscaling import inline_templates from heat.tests import common from heat.tests import utils class TestInstanceGroup(common.HeatTestCase): def setUp(self): super(TestInstanceGroup, self).setUp() t = template_format.parse(inline_templates.as_template) self.stack = utils.parse_stack(t, params=inline_templates.as_params) self.defn = rsrc_defn.ResourceDefinition( 'asg', 'OS::Heat::InstanceGroup', {'Size': 2, 'AvailabilityZones': ['zoneb'], 'LaunchConfigurationName': 'config'}) self.instance_group = instgrp.InstanceGroup('asg', self.defn, self.stack) def test_child_template(self): self.instance_group._create_template = mock.Mock(return_value='tpl') self.assertEqual('tpl', self.instance_group.child_template()) self.instance_group._create_template.assert_called_once_with(2) def test_child_params(self): expected = {'parameters': {}, 'resource_registry': { 'OS::Heat::ScaledResource': 'AWS::EC2::Instance'}} self.assertEqual(expected, self.instance_group.child_params()) def test_tags_default(self): expected = [{'Value': u'asg', 'Key': 'metering.groupname'}] self.assertEqual(expected, self.instance_group._tags()) def test_tags_with_extra(self): self.instance_group.properties.data['Tags'] = [ {'Key': 'fee', 'Value': 'foo'}] expected = [{'Key': 'fee', 'Value': 'foo'}, {'Value': u'asg', 'Key': 'metering.groupname'}] self.assertEqual(expected, self.instance_group._tags()) def test_tags_with_metering(self): self.instance_group.properties.data['Tags'] = [ {'Key': 'metering.fee', 'Value': 'foo'}] expected = [{'Key': 'metering.fee', 'Value': 'foo'}] self.assertEqual(expected, self.instance_group._tags()) def test_validate_launch_conf(self): props = self.instance_group.properties.data props['LaunchConfigurationName'] = 'urg_i_cant_spell' creator = scheduler.TaskRunner(self.instance_group.create) error = self.assertRaises(exception.ResourceFailure, creator) self.assertIn('(urg_i_cant_spell) reference can not be found.', six.text_type(error)) def test_validate_launch_conf_no_ref(self): props = self.instance_group.properties.data props['LaunchConfigurationName'] = 'JobServerConfig' creator = scheduler.TaskRunner(self.instance_group.create) error = self.assertRaises(exception.ResourceFailure, creator) self.assertIn('(JobServerConfig) reference can not be', six.text_type(error)) def test_handle_create(self): self.instance_group.create_with_template = mock.Mock(return_value=None) self.instance_group.validate_launchconfig = mock.Mock( return_value=None) self.instance_group._create_template = mock.Mock(return_value='{}') self.instance_group.handle_create() self.instance_group.validate_launchconfig.assert_called_once_with() self.instance_group._create_template.assert_called_once_with(2) self.instance_group.create_with_template.assert_called_once_with('{}') def test_update_in_failed(self): self.instance_group.state_set('CREATE', 'FAILED') # to update the failed instance_group self.instance_group.resize = mock.Mock(return_value=None) self.instance_group.handle_update(self.defn, None, None) self.instance_group.resize.assert_called_once_with(2) def test_handle_delete(self): self.instance_group.delete_nested = mock.Mock(return_value=None) self.instance_group.handle_delete() self.instance_group.delete_nested.assert_called_once_with() def test_handle_update_size(self): self.instance_group._try_rolling_update = mock.Mock(return_value=None) self.instance_group.resize = mock.Mock(return_value=None) props = {'Size': 5} defn = rsrc_defn.ResourceDefinition( 'nopayload', 'AWS::AutoScaling::AutoScalingGroup', props) self.instance_group.handle_update(defn, None, props) self.instance_group.resize.assert_called_once_with(5) def test_attributes(self): mock_members = self.patchobject(grouputils, 'get_members') instances = [] for ip_ex in six.moves.range(1, 4): inst = mock.Mock() inst.FnGetAtt.return_value = '2.1.3.%d' % ip_ex instances.append(inst) mock_members.return_value = instances res = self.instance_group._resolve_attribute('InstanceList') self.assertEqual('2.1.3.1,2.1.3.2,2.1.3.3', res) class TestLaunchConfig(common.HeatTestCase): def create_resource(self, t, stack, resource_name): # subsequent resources may need to reference previous created resources # use the stack's resource objects instead of instantiating new ones rsrc = stack[resource_name] self.assertIsNone(rsrc.validate()) scheduler.TaskRunner(rsrc.create)() self.assertEqual((rsrc.CREATE, rsrc.COMPLETE), rsrc.state) return rsrc def test_update_metadata_replace(self): """Updating the config's metadata causes a config replacement.""" lc_template = ''' { "AWSTemplateFormatVersion" : "2010-09-09", "Resources": { "JobServerConfig" : { "Type" : "AWS::AutoScaling::LaunchConfiguration", "Metadata": {"foo": "bar"}, "Properties": { "ImageId" : "foo", "InstanceType" : "m1.large", "KeyName" : "test", } } } } ''' self.stub_ImageConstraint_validate() self.stub_FlavorConstraint_validate() self.stub_KeypairConstraint_validate() t = template_format.parse(lc_template) stack = utils.parse_stack(t) rsrc = self.create_resource(t, stack, 'JobServerConfig') props = copy.copy(rsrc.properties.data) metadata = copy.copy(rsrc.metadata_get()) update_snippet = rsrc_defn.ResourceDefinition(rsrc.name, rsrc.type(), props, metadata) # Change nothing in the first update scheduler.TaskRunner(rsrc.update, update_snippet)() self.assertEqual('bar', metadata['foo']) metadata['foo'] = 'wibble' update_snippet = rsrc_defn.ResourceDefinition(rsrc.name, rsrc.type(), props, metadata) # Changing metadata in the second update triggers UpdateReplace updater = scheduler.TaskRunner(rsrc.update, update_snippet) self.assertRaises(resource.UpdateReplace, updater) class LoadbalancerReloadTest(common.HeatTestCase): def test_Instances(self): t = template_format.parse(inline_templates.as_template) stack = utils.parse_stack(t) lb = stack['ElasticLoadBalancer'] lb.update = mock.Mock(return_value=None) defn = rsrc_defn.ResourceDefinition( 'asg', 'OS::Heat::InstanceGroup', {'Size': 2, 'AvailabilityZones': ['zoneb'], "LaunchConfigurationName": "LaunchConfig", "LoadBalancerNames": ["ElasticLoadBalancer"]}) group = instgrp.InstanceGroup('asg', defn, stack) mock_members = self.patchobject(grouputils, 'get_member_refids') mock_members.return_value = ['aaaa', 'bbb'] expected = rsrc_defn.ResourceDefinition( 'ElasticLoadBalancer', 'AWS::ElasticLoadBalancing::LoadBalancer', {'Instances': ['aaaa', 'bbb'], 'Listeners': [{'InstancePort': u'80', 'LoadBalancerPort': u'80', 'Protocol': 'HTTP'}], 'AvailabilityZones': ['nova']}, metadata={}, deletion_policy='Delete' ) group._lb_reload() mock_members.assert_called_once_with(group, exclude=[]) lb.update.assert_called_once_with(expected) def test_members(self): t = template_format.parse(inline_templates.as_template) t['Resources']['ElasticLoadBalancer'] = { 'Type': 'OS::Neutron::LoadBalancer', 'Properties': { 'protocol_port': 8080, } } stack = utils.parse_stack(t) lb = stack['ElasticLoadBalancer'] lb.update = mock.Mock(return_value=None) defn = rsrc_defn.ResourceDefinition( 'asg', 'OS::Heat::InstanceGroup', {'Size': 2, 'AvailabilityZones': ['zoneb'], "LaunchConfigurationName": "LaunchConfig", "LoadBalancerNames": ["ElasticLoadBalancer"]}) group = instgrp.InstanceGroup('asg', defn, stack) mock_members = self.patchobject(grouputils, 'get_member_refids') mock_members.return_value = ['aaaa', 'bbb'] expected = rsrc_defn.ResourceDefinition( 'ElasticLoadBalancer', 'OS::Neutron::LoadBalancer', {'protocol_port': 8080, 'members': ['aaaa', 'bbb']}, metadata={}, deletion_policy='Delete') group._lb_reload() mock_members.assert_called_once_with(group, exclude=[]) lb.update.assert_called_once_with(expected) def test_lb_reload_invalid_resource(self): t = template_format.parse(inline_templates.as_template) t['Resources']['ElasticLoadBalancer'] = { 'Type': 'AWS::EC2::Volume', 'Properties': { 'AvailabilityZone': 'nova' } } stack = utils.parse_stack(t) lb = stack['ElasticLoadBalancer'] lb.update = mock.Mock(return_value=None) defn = rsrc_defn.ResourceDefinition( 'asg', 'OS::Heat::InstanceGroup', {'Size': 2, 'AvailabilityZones': ['zoneb'], "LaunchConfigurationName": "LaunchConfig", "LoadBalancerNames": ["ElasticLoadBalancer"]}) group = instgrp.InstanceGroup('asg', defn, stack) mock_members = self.patchobject(grouputils, 'get_member_refids') mock_members.return_value = ['aaaa', 'bbb'] error = self.assertRaises(exception.Error, group._lb_reload) self.assertEqual( "Unsupported resource 'ElasticLoadBalancer' in " "LoadBalancerNames", six.text_type(error)) def test_lb_reload_static_resolve(self): t = template_format.parse(inline_templates.as_template) properties = t['Resources']['ElasticLoadBalancer']['Properties'] properties['AvailabilityZones'] = {'Fn::GetAZs': ''} self.patchobject(parser.Stack, 'get_availability_zones', return_value=['abc', 'xyz']) mock_members = self.patchobject(grouputils, 'get_member_refids') mock_members.return_value = ['aaaabbbbcccc'] # Check that the Fn::GetAZs is correctly resolved expected = {u'Properties': {'Instances': ['aaaabbbbcccc'], u'Listeners': [{u'InstancePort': u'80', u'LoadBalancerPort': u'80', u'Protocol': u'HTTP'}], u'AvailabilityZones': ['abc', 'xyz']}, u'DeletionPolicy': 'Delete', u'Metadata': {}} stack = utils.parse_stack(t, params=inline_templates.as_params) lb = stack['ElasticLoadBalancer'] lb.state_set(lb.CREATE, lb.COMPLETE) lb.handle_update = mock.Mock(return_value=None) group = stack['WebServerGroup'] group._lb_reload() lb.handle_update.assert_called_once_with( mock.ANY, expected, {'Instances': ['aaaabbbbcccc']}) class ReplaceTest(common.HeatTestCase): scenarios = [ ('1', dict(min_in_service=0, batch_size=1, updates=2)), ('2', dict(min_in_service=0, batch_size=2, updates=1)), ('3', dict(min_in_service=3, batch_size=1, updates=3)), ('4', dict(min_in_service=3, batch_size=2, updates=2))] def setUp(self): super(ReplaceTest, self).setUp() t = template_format.parse(inline_templates.as_template) self.stack = utils.parse_stack(t, params=inline_templates.as_params) lc = self.create_launch_config(t, self.stack) lcid = lc.FnGetRefId() self.defn = rsrc_defn.ResourceDefinition( 'asg', 'OS::Heat::InstanceGroup', {'Size': 2, 'AvailabilityZones': ['zoneb'], 'LaunchConfigurationName': lcid}) self.group = instgrp.InstanceGroup('asg', self.defn, self.stack) self.group._lb_reload = mock.Mock() self.group.update_with_template = mock.Mock() self.group.check_update_complete = mock.Mock() self.group._nested = self.get_fake_nested_stack() def create_launch_config(self, t, stack): self.stub_ImageConstraint_validate() self.stub_FlavorConstraint_validate() self.stub_SnapshotConstraint_validate() rsrc = stack['LaunchConfig'] self.assertIsNone(rsrc.validate()) scheduler.TaskRunner(rsrc.create)() self.assertEqual((rsrc.CREATE, rsrc.COMPLETE), rsrc.state) return rsrc def get_fake_nested_stack(self): nested_t = ''' heat_template_version: 2013-05-23 description: AutoScaling Test resources: one: type: ResourceWithPropsAndAttrs properties: Foo: hello two: type: ResourceWithPropsAndAttrs properties: Foo: fee ''' return utils.parse_stack(template_format.parse(nested_t)) def test_rolling_updates(self): self.group._replace(self.min_in_service, self.batch_size, 0) self.assertEqual(self.updates, len(self.group.update_with_template.call_args_list)) self.assertEqual(self.updates + 1, len(self.group._lb_reload.call_args_list))
{ "content_hash": "cbfc985384c417185a2ebbdf2c60bca6", "timestamp": "", "source": "github", "line_count": 367, "max_line_length": 79, "avg_line_length": 40.76021798365122, "alnum_prop": 0.5896116050538137, "repo_name": "rh-s/heat", "id": "81099ad931e79bc6d1fe2fc80cc7be1e39f6f0c0", "size": "15534", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "heat/tests/test_instance_group.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "6288599" }, { "name": "Shell", "bytes": "32845" } ], "symlink_target": "" }
@interface ViewController : UIViewController @end
{ "content_hash": "de8a030ea21198f7282dd45f22b7236c", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 44, "avg_line_length": 10.6, "alnum_prop": 0.7924528301886793, "repo_name": "LeeJunhui/iPadLearning-QQZone", "id": "6d4a9fe93440b4c1d8404e9d018b255b90945bb0", "size": "213", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "QQZoneHD/QQZoneHD/ViewController.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "4201" } ], "symlink_target": "" }
require 'spec_helper' describe ThinkingSphinx::Search do before :each do ThinkingSphinx::Configuration.instance.hunspell.reset end describe '#suggestion' do it "should return a spelling suggestion, if there is one" do search = ThinkingSphinx::Search.new('wodrs incorret on purpose') expect(search.suggestion).to eq('words incorrect on purpose') end it "should be actual query if there is no suggestion" do search = ThinkingSphinx::Search.new('words all correct here') expect(search.suggestion).to eq('words all correct here') end end describe '#suggestion?' do it "should return true if there is a spelling suggestion" do search = ThinkingSphinx::Search.new('wodrs incorret on purpose') expect(search.suggestion?).to be_truthy end it "should return false if there is no spelling suggestion" do search = ThinkingSphinx::Search.new('words all correct here') expect(search.suggestion?).to be_falsey end it "should return false if there are conditions and no spelling suggestion" do search = ThinkingSphinx::Search.new('words', :conditions => {:all => 'here'} ) expect(search.suggestion?).to be_falsey end end describe '#redo_with_suggestion' do before :each do @config = ThinkingSphinx::Configuration.instance @client = Riddle::Client.new allow(@config).to receive_messages(:client => @client) allow(@client).to receive_messages(:query => {:matches => [], :total_found => 0, :total => 0}) end it "should repeat the query with the spelling suggestion" do expect(@client).to receive(:query) do |query, index, comment| expect(query).to eq('words incorrect on purpose') end search = ThinkingSphinx::Search.new('wodrs incorret on purpose') search.redo_with_suggestion search.first end it "should redo the query if it's already been populated" do expect(@client).to receive(:query).twice search = ThinkingSphinx::Search.new('wodrs incorret on purpose') search.first search.redo_with_suggestion search.first end end end
{ "content_hash": "5e66ad6247f60e9ee762fa19ea5ed4af", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 100, "avg_line_length": 32.985074626865675, "alnum_prop": 0.6665158371040724, "repo_name": "josephglanville/thinking-sphinx-hunspell", "id": "8ecccc8a8fa1e8c1c8b86ad9c3ad662f4a01ea21", "size": "2210", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/thinking_sphinx/hunspell_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "11327" } ], "symlink_target": "" }
using UnityEngine; using System.Collections; using UnityEngine.SceneManagement; public class HubGui : MonoBehaviour { public GUISkin Skin; private Vector2 scrollPos = new Vector2(); private string demoDescription = "<color=orange>PUN Demo Hub</color>\n\nSelect a demo to learn more about it.\n\nYou should open individual scenes in the Editor to dissect how they work.\n\nLook out for Console output. Especially in Editor (double click logs to jump to their origin in source)."; private struct DemoBtn { public string Text; public string Link; } private DemoBtn demoBtn; private DemoBtn webLink; GUIStyle m_Headline; void Start() { if (PhotonNetwork.connected || PhotonNetwork.connecting) { PhotonNetwork.Disconnect(); } m_Headline = new GUIStyle(this.Skin.label); m_Headline.padding = new RectOffset(3, 0, 0, 0); } void OnGUI() { GUI.skin = this.Skin; GUILayout.Space(10); GUILayout.BeginHorizontal(); GUILayout.Space(10); scrollPos = GUILayout.BeginScrollView(scrollPos, GUILayout.Width(320)); GUILayout.Label("Basics", m_Headline); if (GUILayout.Button("Demo Boxes", GUILayout.Width(280))) { demoDescription = "<color=orange>Demo Boxes</color>\n\nUses ConnectAndJoinRandom script.\n(joins a random room or creates one)\n\nInstantiates simple prefabs.\nSynchronizes positions without smoothing.\nShows that RPCs target a specific object."; demoBtn = new DemoBtn() { Text = "Start", Link = "DemoBoxes-Scene" }; } if (GUILayout.Button("Demo Worker", GUILayout.Width(280))) { demoDescription = "<color=orange>Demo Worker</color>\n\nJoins the default lobby and shows existing rooms.\nLets you create or join a room.\nInstantiates an animated character.\nSynchronizes position and animation state of character with smoothing.\nImplements simple in-room Chat via RPC calls."; demoBtn = new DemoBtn() { Text = "Start", Link = "DemoWorker-Scene" }; } if (GUILayout.Button("Movement Smoothing", GUILayout.Width(280))) { demoDescription = "<color=orange>Movement Smoothing</color>\n\nUses ConnectAndJoinRandom script.\nShows several basic ways to synchronize positions between controlling client and remote ones.\nThe TransformView is a good default to use."; demoBtn = new DemoBtn() { Text = "Start", Link = "DemoSynchronization-Scene" }; } if (GUILayout.Button("Basic Tutorial", GUILayout.Width(280))) { demoDescription = "<color=orange>Basic tutorial</color>\n\n" + "All custom code for connection, player and scene management.\n" + "Auto synchronization of room levels.\n" + "Uses PhotonAnimatoView for Animator synch.\n" + "New Unity UI all around, for Menus and player health HUD.\n" + "Full step by step tutorial available online."; demoBtn = new DemoBtn() { Text = "Start", Link = "PunBasics-Launcher" }; } GUILayout.Label("Advanced", m_Headline); if (GUILayout.Button("Ownership Transfer", GUILayout.Width(280))) { demoDescription = "<color=orange>Ownership Transfer</color>\n\nShows how to transfer the ownership of a PhotonView.\nThe owner will send position updates of the GameObject.\nTransfer can be edited per PhotonView and set to Fixed (no transfer), Request (owner has to agree) or Takeover (owner can't object)."; this.demoBtn = new DemoBtn() { Text = "Start", Link = "DemoChangeOwner-Scene" }; this.webLink = new DemoBtn(); } if (GUILayout.Button("Pickup, Teams, Scores", GUILayout.Width(280))) { demoDescription = "<color=orange>Pickup, Teams, Scores</color>\n\nUses ConnectAndJoinRandom script.\nImplements item pickup with RPCs.\nUses Custom Properties for Teams.\nCounts score per player and team.\nUses PhotonPlayer extension methods for easy Custom Property access."; this.demoBtn = new DemoBtn() { Text = "Start", Link = "DemoPickup-Scene" }; this.webLink = new DemoBtn(); } GUILayout.Label("Feature Demos", m_Headline); if (GUILayout.Button("Chat", GUILayout.Width(280))) { demoDescription = "<color=orange>Chat</color>\n\nUses the Chat API (now part of PUN).\nSimple UI.\nYou can enter any User ID.\nAutomatically subscribes some channels.\nAllows simple commands via text.\n\nRequires configuration of Chat App ID in scene."; this.demoBtn = new DemoBtn() { Text = "Start", Link = "DemoChat-Scene" }; this.webLink = new DemoBtn(); } if (GUILayout.Button("RPG Movement", GUILayout.Width(280))) { demoDescription = "<color=orange>RPG Movement</color>\n\nDemonstrates how to use the PhotonTransformView component to synchronize position updates smoothly using inter- and extrapolation.\n\nThis demo also shows how to setup a Mecanim Animator to update animations automatically based on received position updates (without sending explicit animation updates)."; this.demoBtn = new DemoBtn() { Text = "Start", Link = "DemoRPGMovement-Scene" }; this.webLink = new DemoBtn(); } if (GUILayout.Button("Mecanim Animations", GUILayout.Width(280))) { demoDescription = "<color=orange>Mecanim Animations</color>\n\nThis demo shows how to use the PhotonAnimatorView component to easily synchronize Mecanim animations.\n\nIt also demonstrates another feature of the PhotonTransformView component which gives you more control how position updates are inter-/extrapolated by telling the component how fast the object moves and turns using SetSynchronizedValues()."; this.demoBtn = new DemoBtn() { Text = "Start", Link = "DemoMecanim-Scene" }; this.webLink = new DemoBtn(); } if (GUILayout.Button("2D Game", GUILayout.Width(280))) { demoDescription = "<color=orange>2D Game Demo</color>\n\nSynchronizes animations, positions and physics in a 2D scene."; this.demoBtn = new DemoBtn() { Text = "Start", Link = "Demo2DJumpAndRunWithPhysics-Scene" }; this.webLink = new DemoBtn(); } if (GUILayout.Button("Friends & Authentication", GUILayout.Width(280))) { demoDescription = "<color=orange>Friends & Authentication</color>\n\nShows connect with or without (server-side) authentication.\n\nAuthentication requires minor server-side setup (in Dashboard).\n\nOnce connected, you can find (made up) friends.\nJoin a room just to see how that gets visible in friends list."; this.demoBtn = new DemoBtn() { Text = "Start", Link = "DemoFriends-Scene" }; this.webLink = new DemoBtn(); } if (GUILayout.Button("Turn Based Game", GUILayout.Width(280))) { demoDescription = "<color=orange>'Rock Paper Scissor' Turn Based Game</color>\n\nDemonstrate TurnBased Game Mechanics using PUN.\n\nIt makes use of the TurnBasedManager Utility Script"; this.demoBtn = new DemoBtn() { Text = "Start", Link = "DemoRPS-Scene" }; this.webLink = new DemoBtn(); } GUILayout.Label("Tutorial", m_Headline); if (GUILayout.Button("Marco Polo Tutorial", GUILayout.Width(280))) { demoDescription = "<color=orange>Marco Polo Tutorial</color>\n\nFinal result you could get when you do the Marco Polo Tutorial.\nSlightly modified to be more compatible with this package."; this.demoBtn = new DemoBtn() { Text = "Start", Link = "MarcoPolo-Scene" }; this.webLink = new DemoBtn() { Text = "Open Tutorial (www)", Link = "http://tinyurl.com/nmylf44" }; } GUILayout.EndScrollView(); GUILayout.BeginVertical(GUILayout.Width(Screen.width - 345)); GUILayout.Label(demoDescription); GUILayout.Space(10); if (!string.IsNullOrEmpty(this.demoBtn.Text)) { if (GUILayout.Button(this.demoBtn.Text)) { SceneManager.LoadScene(this.demoBtn.Link); } } if (!string.IsNullOrEmpty(this.webLink.Text)) { if (GUILayout.Button(this.webLink.Text)) { Application.OpenURL(this.webLink.Link); } } GUILayout.EndVertical(); GUILayout.EndHorizontal(); } }
{ "content_hash": "ef46db4dda2b2710524afbbec642314a", "timestamp": "", "source": "github", "line_count": 156, "max_line_length": 421, "avg_line_length": 55.30769230769231, "alnum_prop": 0.6497450162262401, "repo_name": "googlearchive/tango-examples-unity", "id": "35de11b8464907387b292d9c7613bf1745766cea", "size": "8630", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "TangoWithMultiplayer/Assets/Photon Unity Networking/Demos/DemoHub/HubGui.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "5858349" }, { "name": "GLSL", "bytes": "3996" }, { "name": "HLSL", "bytes": "20068" }, { "name": "Java", "bytes": "21381" }, { "name": "Mask", "bytes": "305" }, { "name": "Objective-C", "bytes": "1433" }, { "name": "Objective-C++", "bytes": "2960" }, { "name": "ShaderLab", "bytes": "145277" }, { "name": "Shell", "bytes": "360" } ], "symlink_target": "" }
import React from 'react'; import { Jumbotron, Button, ButtonToolbar } from 'react-bootstrap' import { LinkContainer } from 'react-router-bootstrap'; class Home extends React.Component { render() { return( <Jumbotron> <h1>This is a Movie Vote Widget...?</h1> <p>express.js + MySQL(MariaDB) + React.js + Ice Americano... react is very difficult.. but interesting..</p> <p>in fact.. my first react app...</p> <ButtonToolbar> <LinkContainer to="/votes"> <Button bsStyle="primary" bsSize="lg"> 영화 목록 보러가기 </Button> </LinkContainer> <LinkContainer to="/vote_results"> <Button bsStyle="primary" bsSize="lg"> 투표 결과 보러가기 </Button> </LinkContainer> </ButtonToolbar> </Jumbotron> ); } } export default Home;
{ "content_hash": "d0a8e042b13b5776c3be47be66c4c171", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 112, "avg_line_length": 27.275862068965516, "alnum_prop": 0.6308470290771175, "repo_name": "uyu423/vote_widget", "id": "269bffdd3401f2d6921fbf126ecd9ade25439cca", "size": "823", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/containers/Home.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "9009" }, { "name": "JavaScript", "bytes": "48080" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="generator" content="Docutils 0.8.1: http://docutils.sourceforge.net/" /> <title>libtorrent manual</title> <meta name="author" content="Arvid Norberg, arvid&#64;rasterbar.com" /> <link rel="stylesheet" type="text/css" href="../../css/base.css" /> <link rel="stylesheet" type="text/css" href="../../css/rst.css" /> <script type="text/javascript"> /* <![CDATA[ */ (function() { var s = document.createElement('script'), t = document.getElementsByTagName('script')[0]; s.type = 'text/javascript'; s.async = true; s.src = 'http://api.flattr.com/js/0.6/load.js?mode=auto'; t.parentNode.insertBefore(s, t); })(); /* ]]> */ </script> <link rel="stylesheet" href="style.css" type="text/css" /> <style type="text/css"> /* Hides from IE-mac \*/ * html pre { height: 1%; } /* End hide from IE-mac */ </style> </head> <body> <div class="document" id="libtorrent-manual"> <div id="container"> <div id="headerNav"> <ul> <li class="first"><a href="/">Home</a></li> <li><a href="../../products.html">Products</a></li> <li><a href="../../contact.html">Contact</a></li> </ul> </div> <div id="header"> <h1><span>Rasterbar Software</span></h1> <h2><span>Software developement and consulting</span></h2> </div> <div id="main"> <h1 class="title">libtorrent manual</h1> <table class="docinfo" frame="void" rules="none"> <col class="docinfo-name" /> <col class="docinfo-content" /> <tbody valign="top"> <tr><th class="docinfo-name">Author:</th> <td>Arvid Norberg, <a class="last reference external" href="mailto:arvid&#64;rasterbar.com">arvid&#64;rasterbar.com</a></td></tr> <tr><th class="docinfo-name">Version:</th> <td>1.0.0</td></tr> </tbody> </table> <div class="contents topic" id="table-of-contents"> <p class="topic-title first">Table of contents</p> <ul class="simple"> <li><a class="reference internal" href="#introduction" id="id2">introduction</a></li> <li><a class="reference internal" href="#features" id="id3">features</a><ul> <li><a class="reference internal" href="#extensions" id="id4">extensions</a></li> <li><a class="reference internal" href="#disk-management" id="id5">disk management</a></li> <li><a class="reference internal" href="#network" id="id6">network</a></li> </ul> </li> <li><a class="reference internal" href="#highlighted-features" id="id7">highlighted features</a><ul> <li><a class="reference internal" href="#disk-caching" id="id8">disk caching</a></li> <li><a class="reference internal" href="#high-performance-disk-subsystem" id="id9">high performance disk subsystem</a></li> <li><a class="reference internal" href="#network-buffers" id="id10">network buffers</a></li> <li><a class="reference internal" href="#piece-picker" id="id11">piece picker</a></li> <li><a class="reference internal" href="#share-mode" id="id12">share mode</a></li> <li><a class="reference internal" href="#merkle-hash-tree-torrents" id="id13">merkle hash tree torrents</a></li> <li><a class="reference internal" href="#customizable-file-storage" id="id14">customizable file storage</a></li> <li><a class="reference internal" href="#easy-to-use-api" id="id15">easy to use API</a></li> </ul> </li> <li><a class="reference internal" href="#portability" id="id16">portability</a></li> </ul> </div> <div class="section" id="introduction"> <h1>introduction</h1> <p>libtorrent is a feature complete C++ bittorrent implementation focusing on efficiency and scalability. It runs on embedded devices as well as desktops. It boasts a well documented library interface that is easy to use. It comes with a simple bittorrent client demonstrating the use of the library.</p> </div> <div class="section" id="features"> <h1>features</h1> <p>libtorrent is under active development. It is an ongoing project. Its current state supports and includes the following features:</p> <div class="section" id="extensions"> <h2>extensions</h2> <ul class="simple"> <li>plugin interface for implementing custom bittorrent extensions without having to modify libtorrent</li> <li>supports trackerless torrents (using the Mainline kademlia DHT protocol) with some <a class="reference external" href="dht_extensions.html">DHT extensions</a>. <a class="reference external" href="http://bittorrent.org/beps/bep_0005.html">BEP 5</a>.</li> <li>supports the bittorrent <a class="reference external" href="extension_protocol.html">extension protocol</a>. See <a class="reference external" href="manual.html#extensions">extensions</a>. <a class="reference external" href="http://bittorrent.org/beps/bep_0010.html">BEP 10</a>.</li> <li>supports the uTorrent metadata transfer protocol <a class="reference external" href="http://bittorrent.org/beps/bep_0009.html">BEP 9</a> (i.e. magnet links).</li> <li>supports the uTorrent peer exchange protocol (PEX).</li> <li>supports local peer discovery (multicasts for peers on the same local network)</li> <li>multitracker extension support (supports both strict <a class="reference external" href="http://bittorrent.org/beps/bep_0012.html">BEP 12</a> and the uTorrent interpretation).</li> <li>tracker scrapes</li> <li>supports lt_trackers extension, to exchange trackers between peers</li> <li><a class="reference external" href="manual.html#http-seeding">HTTP seeding</a>, as specified in <a class="reference external" href="http://bittorrent.org/beps/bep_0017.html">BEP 17</a> and <a class="reference external" href="http://bittorrent.org/beps/bep_0019.html">BEP 19</a>.</li> <li>supports the udp-tracker protocol. (<a class="reference external" href="http://bittorrent.org/beps/bep_0015.html">BEP 15</a>).</li> <li>supports the <tt class="docutils literal">no_peer_id=1</tt> extension that will ease the load off trackers.</li> <li>supports the <tt class="docutils literal">compact=1</tt> tracker parameter.</li> <li>super seeding/initial seeding (<a class="reference external" href="http://bittorrent.org/beps/bep_0016.html">BEP 16</a>).</li> <li>private torrents (<a class="reference external" href="http://bittorrent.org/beps/bep_0027.html">BEP 27</a>).</li> <li>upload-only extension (<a class="reference external" href="http://bittorrent.org/beps/bep_0021.html">BEP 21</a>).</li> <li>support for IPv6, including <a class="reference external" href="http://bittorrent.org/beps/bep_0007.html">BEP 7</a> and <a class="reference external" href="http://bittorrent.org/beps/bep_0024.html">BEP 24</a>.</li> <li>support for merkle hash tree torrents. This makes the size of torrent files scale well with the size of the content.</li> <li>share-mode. This is a special mode torrents can be put in to optimize share ratio rather than downloading the torrent.</li> </ul> </div> <div class="section" id="disk-management"> <h2>disk management</h2> <ul class="simple"> <li>uses a separate disk I/O thread to not have the disk ever block on network or client interaction. (see <a class="reference external" href="manual.html#threads">threads</a>).</li> <li>supports files &gt; 2 gigabytes.</li> <li>fast resume support, a way to get rid of the costly piece check at the start of a resumed torrent. Saves the storage state, piece_picker state as well as all local peers in a separate fast-resume file.</li> <li>has an adjustable read and write disk cache for improved disk throughput.</li> <li>queues torrents for file check, instead of checking all of them in parallel.</li> <li>does not have any requirements on the piece order in a torrent that it resumes. This means it can resume a torrent downloaded by any client.</li> <li>seed mode, where the files on disk are assumed to be complete, and each piece's hash is verified the first time it is requested.</li> </ul> </div> <div class="section" id="network"> <h2>network</h2> <ul class="simple"> <li>a high quality uTP implementation (<a class="reference external" href="http://bittorrent.org/beps/bep_0029.html">BEP 29</a>). A transport protocol with delay based congestion control. See separate <a class="reference external" href="utp.html">article</a>.</li> <li>adjusts the length of the request queue depending on download rate.</li> <li>serves multiple torrents on a single port and in a single thread</li> <li>piece picking on block-level (as opposed to piece-level). This means it can download parts of the same piece from different peers. It will also prefer to download whole pieces from single peers if the download speed is high enough from that particular peer.</li> <li>supports http proxies and basic proxy authentication</li> <li>supports gzipped tracker-responses</li> <li>can limit the upload and download bandwidth usage and the maximum number of unchoked peers</li> <li>possibility to limit the number of connections.</li> <li>delays have messages if there's no other outgoing traffic to the peer, and doesn't send have messages to peers that already has the piece. This saves bandwidth.</li> <li>selective downloading. The ability to select which parts of a torrent you want to download.</li> <li>ip filter to disallow ip addresses and ip ranges from connecting and being connected.</li> <li>NAT-PMP and UPnP support (automatic port mapping on routers that supports it)</li> <li>implements automatic upload slots, to optimize download rate without spreading upload capacity too thin. The number of upload slots is adjusted based on the peers' download capacity to work even for connections that are orders of magnitude faster than others.</li> </ul> </div> </div> <div class="section" id="highlighted-features"> <h1>highlighted features</h1> <div class="section" id="disk-caching"> <h2>disk caching</h2> <p>All disk I/O in libtorrent is done asynchronously to the network thread, by the disk io thread. When a block is read, the disk io thread reads all subsequent blocks from that piece into the read cache, assuming that the peer requesting the block will also request more blocks from the same piece. This decreases the number of syscalls for reading data. It also decreases delay from seeking.</p> <p>Similarly, for write requests, blocks are cached and flushed to disk once one full piece is complete or the piece is the least recently updated one when more cache space is needed. The cache dynamically allocates space between the write and read cache. The write cache is strictly prioritized over the read cache.</p> <p>The cache blocks that are in used, are locked into physical memory to avoid it being paged out to disk. Allowing the disk cache to be paged out to disk means that it would become extremely inefficient to flush it, since it would have to be read back into physical memory only to be flushed back out to disk again.</p> <p>In order to conserve memory, and system calls, iovec file operations are used to flush multiple cache blocks in a single call.</p> <p>On low-memory systems, the disk cache can be disabled altogether or set to smaller limit, to save memory.</p> <p>The disk caching algorithm is configurable between 'LRU' and 'largest contiguous'. The largest contiguous algorithm is the default and flushes the largest contiguous block of buffers, instead of flushing all blocks belonging to the piece which was written to least recently.</p> <p>For version 0.15 a lot of work went into optimizing the cache algorithm, trying to increase the cache hit rate and utilization. The graph to the left shows the memory utilization in 0.14. This cache is a straight forward, fairly naive, implementation. Every block read will also read all subsequent blocks in that piece into the cache. Whenever we need more space, the entire oldest piece is evicted from the cache. Caching writes always takes presedence over the read cache. Whenever a piece is fully downloaded, it is flushed to disk.</p> <img alt="disk_buffer_before_optimization.png" src="disk_buffer_before_optimization.png" style="width: 49%;" /> <img alt="disk_buffer.png" src="disk_buffer.png" style="width: 49%;" /> <p>The left graph shows the problem of evicting entire pieces at a time, and waiting until an entire piece is downloaded until flushing it. These graphs were generated for a torrent with fairly large pieces. This means that granularity was poor in 0.14, since it only dealt with entire pieces. In 0.15, the granularity problem has been fixed by evicting one block at a time from the read cache. This maximizes the read cache utilization. The write cache is also flushed when a sufficient number of contiguous blocks have been downloaded for a piece, which is not tied to the piece size anymore. This way the cache scales a lot better with piece sizes.</p> <p>The graph to the right shows the same download but with the new optimized disk cache algorithm. It clearly shows an increased utilization, which means higher read hit rates or smaller caches with maintained hit rate.</p> </div> <div class="section" id="high-performance-disk-subsystem"> <h2>high performance disk subsystem</h2> <p>In some circumstances, the disk cache may not suffice to provide maximum performance. One such example is high performance seeding, to a large number of peers, over a fast up-link. In such a case, the amount of RAM may simply not be enough to cache disk reads. When there's not enough RAM to cache disk reads, the disk throughput would typically degrade to perform as poorly as with no cache at all, with the majority of the time spent waiting for the disk head to seek.</p> <p>To solve this problem, libtorrent sorts read requests by their physical offset on the disk. They are processed by having the disk read head sweep back and forth over the drive.</p> <p>This makes libtorrent very suitable for large scale, high-throughput seeding.</p> <img alt="disk_access_no_elevator.png" src="disk_access_no_elevator.png" style="width: 49%;" /> <img alt="disk_access_elevator.png" src="disk_access_elevator.png" style="width: 49%;" /> <p>These plots illustrates the physical disk offset for reads over time. The left plot is of a run where disk operation re-ordering is turned off and the righ is when it's turned on. The right one has a relatively smooth sine wave shape whereas the left one is more random and involves much longer seeks back and forth over the disk.</p> <p>True physical disk offset queries are only supported on newer linux kernels, Mac OS X and Windows 2000 and up.</p> </div> <div class="section" id="network-buffers"> <h2>network buffers</h2> <p>On CPUs with small L2 caches, copying memory can be expensive operations. It is important to keep copying to a minimum on such machines. This mostly applies to embedded systems.</p> <p>In order to minimize the number of times received data is copied, the receive buffer for payload data is received directly into a page aligned disk buffer. If the connection is encrypted, the buffer is decrypted in-place. The buffer is then moved into the disk cache without being copied. Once all the blocks for a piece have been received, or the cache needs to be flushed, all the blocks are passed directly to <tt class="docutils literal">writev()</tt> to flush them in a single syscall. This means a single copy into user space memory, and a single copy back into kernel memory, as illustrated by this figure:</p> <img alt="write_disk_buffers.png" src="write_disk_buffers.png" style="width: 100%;" /> <p>When seeding and uploading in general, unnecessary copying is avoided by caching blocks in aligned buffers, that are copied once into the peer's send buffer. The peer's send buffer is not guaranteed to be aligned, even though it is most of the time. The send buffer is then encrypted with the peer specific key and chained onto the <tt class="docutils literal">iovec</tt> for sending. This means there is one user space copy in order to allow unaligned peer requests and peer-specific encryption. This is illustrated by the following figure:</p> <img alt="read_disk_buffers.png" src="read_disk_buffers.png" style="width: 100%;" /> </div> <div class="section" id="piece-picker"> <h2>piece picker</h2> <p>The piece picker is a central component in a bittorrent implementation. The piece picker in libtorrent is optimized for quickly finding the rarest pieces. It keeps a list of all available pieces sorted by rarity, and pieces with the same rarity, shuffled. The rarest first mode is the dominant piece picker mode. Other modes are supported as well, and used by peers in specific situations.</p> <p>The piece picker allows to combine the availability of a piece with a priority. Together they determine the sort order of the piece list. Pieces with priority 0 will never be picked, which is used for the selective download feature.</p> <p>In order to have as few partially finished pieces as possible, peers have an affinity towards picking blocks from the same pieces as other peers in the same speed category. The speed category is a coarse categorization of peers based on their download rate. This makes slow peers pick blocks from the same piece, and fast peers pick from the same piece, and hence decreasing the likelihood of slow peers blocking the completion of pieces.</p> <p>The piece picker can also be set to download pieces in sequential order.</p> </div> <div class="section" id="share-mode"> <h2>share mode</h2> <p>The share mode feature in libtorrent is intended for users who are only interested in helping out swarms, not downloading the torrents.</p> <p>It works by predicting the demand for pieces, and only download pieces if there is enough demand. New pieces will only be downloaded once the share ratio has hit a certain target.</p> <p>This feature is especially useful when combined with RSS, so that a client can be set up to provide additional bandwidth to an entire feed.</p> </div> <div class="section" id="merkle-hash-tree-torrents"> <h2>merkle hash tree torrents</h2> <p>Merkle hash tree torrents is an extension that lets a torrent file only contain the root hash of the hash tree forming the piece hashes. The main benefit of this feature is that regardless of how many pieces there is in a torrent, the .torrent file will always be the same size. It will only grow with the number of files (since it still has to contain the file names).</p> <p>With regular torrents, clients have to request multiple blocks for pieces, typically from different peers, before the data can be verified against the piece hash. The larger the pieces are, the longer it will take to download a complete piece and verify it. Before the piece is verified, it cannot be shared with the swarm, which means the larger piece sizes, the slower turnaround data has when it is downloaded by peers. Since on average the data has to sit around, waiting, in client buffers before it has been verified and can be uploaded again.</p> <p>Another problem with large piece sizes is that it is harder for a client to pinpoint the malicious or buggy peer when a piece fails, and it will take longer to re-download it and take more tries before the piece succeeds the larger the pieces are.</p> <p>The piece size in regular torrents is a tradeoff between the size of the .torrent file itself and the piece size. Often, for files that are 4 GB, the piece size is 2 or 4 MB, just to avoid making the .torrent file too big.</p> <p>Merkle torrents solves these problems by removing the tradeoff between .torrent size and piece size. With merkle torrents, the piece size can be the minimum block size (16 kB), which lets peers verify every block of data received from peers, immediately. This gives a minimum turnaround time and completely removes the problem of identifying malicious peers.</p> <img alt="merkle_tree.png" src="merkle_tree.png" /> <p>The root hash is built by hashing all the piece hashes pair-wise, until they all collapse down to the root.</p> <img alt="storage.png" class="align-right" src="storage.png" /> </div> <div class="section" id="customizable-file-storage"> <h2>customizable file storage</h2> <p>libtorrent's storage implementation is customizable. That means a special purpose bittorrent client can replace the default way to store files on disk.</p> <p>When implementing a bittorrent cache, it doesn't matter how the data is stored on disk, as long as it can be retrieved and seeded. In that case a new storage class can be implemented (inheriting from the <tt class="docutils literal">storage_interface</tt> class) that avoids the unnecessary step of mapping slots to files and offsets. The storage can ignore the file boundaries and just store the entire torrent in a single file (which will end up being all the files concatenated). The main advantage of this, other than a slight cpu performance gain, is that all file operations would be page (and sector) aligned. This enables efficient unbuffered I/O, and can potentially lead to more efficient read caching (using the built in disk cache rather than relying on the operating system's disk cache).</p> <p>The storage interface supports operating systems where you can ask for sparse regions (such as Windows and Solaris). The advantage of this is that when checking files, the regions that are known to be sparse can be skipped, which can reduce the time to check a torrent significantly.</p> </div> <div class="section" id="easy-to-use-api"> <h2>easy to use API</h2> <p>One of the design goals of the libtorrent API is to make common operations simple, but still have it possible to do complicated and advanced operations. This is best illustrated by example code to implement a simple bittorrent client:</p> <pre class="literal-block"> #include &lt;iostream&gt; #include &quot;libtorrent/session.hpp&quot; // usage a.out [torrent-file] int main(int argc, char* argv[]) try { using namespace libtorrent; session s; s.listen_on(std::make_pair(6881, 6889)); add_torrent_params p; p.save_path = &quot;./&quot;; p.ti = new torrent_info(argv[1]); s.add_torrent(p); // wait for the user to end char a; std::cin.unsetf(std::ios_base::skipws); std::cin &gt;&gt; a; return 0; } catch (std::exception&amp; e) { std::cerr &lt;&lt; ec.what() &lt;&lt; std::endl; return 1; } </pre> <p>This client doesn't give the user any status information or progress about the torrent, but it is fully functional.</p> <p>libtorrent also comes with python bindings for easy access for python developers.</p> </div> </div> <div class="section" id="portability"> <h1>portability</h1> <p>libtorrent runs on most major operating systems, including Windows, MacOS X, Linux, BSD and Solaris. It uses Boost.Thread, Boost.Filesystem, Boost.Date_time and various other boost libraries as well as <a class="reference external" href="http://www.zlib.org">zlib</a> (shipped) and <a class="reference external" href="http://asio.sf.net">asio</a> (shipped). At least version 1.34.1 of boost is required.</p> <p>libtorrent uses asio, hence it will take full advantage of high performance network APIs on the most popular platforms. I/O completion ports on windows, epoll on linux and kqueue on MacOS X and BSD.</p> <p>libtorrent has been successfully compiled and tested on:</p> <ul class="simple"> <li>Windows 2000, XP and Vista vc7.1, vc8</li> <li>Linux x86 GCC 3.3, GCC 3.4.2, 4.x</li> <li>Linux PPC GCC 4.1.1</li> <li>MacOS X (darwin), (Apple's) GCC 3.3, (Apple's) GCC 4.0</li> <li>SunOS 5.8 GCC 3.1 and Sunpro</li> <li>Cygwin GCC 3.3.3</li> </ul> <p>Fails on:</p> <ul class="simple"> <li>GCC 2.95.4</li> <li>msvc6</li> </ul> </div> </div> <div id="footer"> <span>Copyright &copy; 2005 Rasterbar Software.</span> </div> </div> <script src="http://www.google-analytics.com/urchin.js" type="text/javascript"> </script> <script type="text/javascript"> _uacct = "UA-1599045-1"; urchinTracker(); </script> </div> </body> </html>
{ "content_hash": "26b6d476bc825a601b8f74fa1d51f0a9", "timestamp": "", "source": "github", "line_count": 404, "max_line_length": 287, "avg_line_length": 59.51732673267327, "alnum_prop": 0.745643584944895, "repo_name": "ABuus/libtorrent", "id": "d9b033068fe5c6563d1f5a8ff52dd03af9430509", "size": "24045", "binary": false, "copies": "18", "ref": "refs/heads/master", "path": "docs/features.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "340258" }, { "name": "C++", "bytes": "3657650" }, { "name": "JavaScript", "bytes": "1785" }, { "name": "Perl", "bytes": "18750" }, { "name": "Python", "bytes": "79813" }, { "name": "Shell", "bytes": "7185" } ], "symlink_target": "" }
import React from 'react'; import { SubmitField } from 'uniforms-semantic'; import createContext from './_createContext'; import mount from './_mount'; test('<SubmitField> - renders', () => { const element = <SubmitField />; const wrapper = mount(element, createContext()); expect(wrapper).toHaveLength(1); }); test('<SubmitField> - renders disabled if error', () => { const element = <SubmitField />; const wrapper = mount(element, createContext(undefined, { error: {} })); expect(wrapper).toHaveLength(1); expect(wrapper.find('input').prop('disabled')).toBe(true); }); test('<SubmitField> - renders enabled if error and enabled', () => { const element = <SubmitField disabled={false} />; const wrapper = mount(element, createContext(undefined, { error: {} })); expect(wrapper).toHaveLength(1); expect(wrapper.find('input').prop('disabled')).toBe(false); }); test('<SubmitField> - renders a wrapper with correct value', () => { const element = <SubmitField value="Example" />; const wrapper = mount(element, createContext()); expect(wrapper).toHaveLength(1); expect(wrapper.find('input').prop('value')).toBe('Example'); });
{ "content_hash": "96533da8078a790f3801275b05a97651", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 74, "avg_line_length": 32.333333333333336, "alnum_prop": 0.6769759450171822, "repo_name": "vazco/uniforms", "id": "c70b979413e2fc1e4ecdf258405fc887fe6f89f6", "size": "1164", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/uniforms-semantic/__tests__/SubmitField.tsx", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "15485" }, { "name": "HTML", "bytes": "1580" }, { "name": "JavaScript", "bytes": "6477" }, { "name": "Shell", "bytes": "69" }, { "name": "TypeScript", "bytes": "1396635" } ], "symlink_target": "" }
package com.uplink.mowitnow.core.parser; import com.uplink.mowitnow.core.context.Paire; import com.uplink.mowitnow.core.domain.Area; import com.uplink.mowitnow.core.domain.Instruction; import com.uplink.mowitnow.core.domain.LawnMower; import org.assertj.core.util.Lists; import org.junit.Before; import org.junit.Test; import java.util.Arrays; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.*; public class MowItNowParserTest { MowItNowParser parser ; List<String> inputDataList; @Before public void setup(){ inputDataList = Lists.newArrayList("5 5" ,"1 2 N" ,"GAGAGAGAA","3 3 E","AADAADADDA"); parser = new MowItNowParser(inputDataList); } @Test public void testGetArea() throws Exception { assertThat(parser.getArea()).isEqualsToByComparingFields(new Area(5,5)); } @Test public void testGetListLawnMowerWithShortInstruction() throws Exception { inputDataList = Lists.newArrayList("5 5" ,"1 1 N" ,"A"); parser = new MowItNowParser(inputDataList); List<Paire<List<Instruction>, LawnMower>> listLawnMowerWithInstruction = parser.getListLawnMowerWithInstruction(); assertThat(listLawnMowerWithInstruction).hasSize(1); assertThat(listLawnMowerWithInstruction.get(0).getLeftElement()).containsSequence(Instruction.A); } @Test public void testGetListLawnMowerWithLongInstruction() throws Exception { List<Paire<List<Instruction>, LawnMower>> listLawnMowerWithInstruction = parser.getListLawnMowerWithInstruction(); assertThat(listLawnMowerWithInstruction).hasSize(2); assertThat(listLawnMowerWithInstruction.get(0).getLeftElement()).containsSequence(Instruction.G, Instruction.A, Instruction.G, Instruction.A, Instruction.G, Instruction.A, Instruction.G, Instruction.A, Instruction.A); assertThat(listLawnMowerWithInstruction.get(1).getLeftElement()).containsSequence(Instruction.A , Instruction.A, Instruction.D, Instruction.A, Instruction.A, Instruction.D, Instruction.A, Instruction.D, Instruction.D, Instruction.A); } }
{ "content_hash": "af8fc7db0b040530b270f3e43c9be1ce", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 165, "avg_line_length": 37.016949152542374, "alnum_prop": 0.739010989010989, "repo_name": "oraclewalid/MowItNow", "id": "b9785abc2fbc22bbec0b81b54193f844485268b8", "size": "2184", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/com/uplink/mowitnow/core/parser/MowItNowParserTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "30590" } ], "symlink_target": "" }
<?php $additionalNamespaces = $additionalModulePaths = $moduleDependencies = null; $rootPath = realpath(dirname(__DIR__)); $testsPath = "$rootPath/tests"; if (is_readable($testsPath . '/TestConfiguration.php')) { require_once $testsPath . '/TestConfiguration.php'; } else { require_once $testsPath . '/TestConfiguration.php.dist'; } $path = array( ZF2_PATH, get_include_path(), ); set_include_path(implode(PATH_SEPARATOR, $path)); require_once 'Zend/Loader/AutoloaderFactory.php'; require_once 'Zend/Loader/StandardAutoloader.php'; use Zend\Loader\AutoloaderFactory; use Zend\Loader\StandardAutoloader; // setup autoloader AutoloaderFactory::factory( array( 'Zend\Loader\StandardAutoloader' => array( StandardAutoloader::AUTOREGISTER_ZF => true, StandardAutoloader::ACT_AS_FALLBACK => false, StandardAutoloader::LOAD_NS => $additionalNamespaces, ) ) ); // The module name is obtained using directory name or constant $moduleName = pathinfo($rootPath, PATHINFO_BASENAME); if (defined('MODULE_NAME')) { $moduleName = MODULE_NAME; } // A locator will be set to this class if available $moduleTestCaseClassname = '\\'.$moduleName.'Test\\Framework\\TestCase'; // This module's path plus additionally defined paths are used $modulePaths $modulePaths = array(dirname($rootPath)); if (isset($additionalModulePaths)) { $modulePaths = array_merge($modulePaths, $additionalModulePaths); } // Load this module and defined dependencies $modules = array($moduleName); if (isset($moduleDependencies)) { $modules = array_merge($modules, $moduleDependencies); } $listenerOptions = new Zend\ModuleManager\Listener\ListenerOptions(array('module_paths' => $modulePaths)); $defaultListeners = new Zend\ModuleManager\Listener\DefaultListenerAggregate($listenerOptions); $sharedEvents = new Zend\EventManager\SharedEventManager(); $moduleManager = new \Zend\ModuleManager\ModuleManager($modules); $moduleManager->getEventManager()->setSharedManager($sharedEvents); $moduleManager->getEventManager()->attachAggregate($defaultListeners); $moduleManager->loadModules(); if (method_exists($moduleTestCaseClassname, 'setLocator')) { $config = $defaultListeners->getConfigListener()->getMergedConfig(); $di = new \Zend\Di\Di; $di->instanceManager()->addTypePreference('Zend\Di\LocatorInterface', $di); if (isset($config['di'])) { $diConfig = new \Zend\Di\Config($config['di']); $diConfig->configure($di); } $routerDiConfig = new \Zend\Di\Config( array( 'definition' => array( 'class' => array( 'Zend\Mvc\Router\RouteStackInterface' => array( 'instantiator' => array( 'Zend\Mvc\Router\Http\TreeRouteStack', 'factory' ), ), ), ), ) ); $routerDiConfig->configure($di); call_user_func_array($moduleTestCaseClassname.'::setLocator', array($di)); } // When this is in global scope, PHPUnit catches exception: // Exception: Zend\Stdlib\PriorityQueue::serialize() must return a string or NULL unset($moduleManager, $sharedEvents);
{ "content_hash": "ba95f0f7258ec25ae808df1a2e8b425c", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 106, "avg_line_length": 33.69, "alnum_prop": 0.6500445235975066, "repo_name": "webIntegral/wi-restful", "id": "4756e5949c4ce7897c58a1d0c8d92f325e1c6a4b", "size": "3679", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "module/CPIps/tests/bootstrap.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "711" }, { "name": "CSS", "bytes": "1042" }, { "name": "HTML", "bytes": "14839" }, { "name": "PHP", "bytes": "75217" } ], "symlink_target": "" }
<!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_101) on Sat Aug 20 05:41:48 EDT 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Uses of Class org.apache.solr.search.join.ScoreJoinQParserPlugin (Solr 6.2.0 API)</title> <meta name="date" content="2016-08-20"> <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 org.apache.solr.search.join.ScoreJoinQParserPlugin (Solr 6.2.0 API)"; } } 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="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/solr/search/join/ScoreJoinQParserPlugin.html" title="class in org.apache.solr.search.join">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</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?org/apache/solr/search/join/class-use/ScoreJoinQParserPlugin.html" target="_top">Frames</a></li> <li><a href="ScoreJoinQParserPlugin.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 org.apache.solr.search.join.ScoreJoinQParserPlugin" class="title">Uses of Class<br>org.apache.solr.search.join.ScoreJoinQParserPlugin</h2> </div> <div class="classUseContainer">No usage of org.apache.solr.search.join.ScoreJoinQParserPlugin</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="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/solr/search/join/ScoreJoinQParserPlugin.html" title="class in org.apache.solr.search.join">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</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?org/apache/solr/search/join/class-use/ScoreJoinQParserPlugin.html" target="_top">Frames</a></li> <li><a href="ScoreJoinQParserPlugin.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 ======= --> <p class="legalCopy"><small> <i>Copyright &copy; 2000-2016 Apache Software Foundation. All Rights Reserved.</i> <script src='../../../../../../prettify.js' type='text/javascript'></script> <script type='text/javascript'> (function(){ var oldonload = window.onload; if (typeof oldonload != 'function') { window.onload = prettyPrint; } else { window.onload = function() { oldonload(); prettyPrint(); } } })(); </script> </small></p> </body> </html>
{ "content_hash": "da77001703fc35745c915368a973f44a", "timestamp": "", "source": "github", "line_count": 140, "max_line_length": 163, "avg_line_length": 37.00714285714286, "alnum_prop": 0.5981470758540822, "repo_name": "berkeleybop/bbop-manager-golr", "id": "1f4cb760685016022bd0c5910eb6a1a5a77976a9", "size": "5181", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "solr/docs/solr-core/org/apache/solr/search/join/class-use/ScoreJoinQParserPlugin.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "AMPL", "bytes": "291" }, { "name": "Batchfile", "bytes": "59559" }, { "name": "CSS", "bytes": "454655" }, { "name": "HTML", "bytes": "74053220" }, { "name": "JavaScript", "bytes": "1565460" }, { "name": "Python", "bytes": "3829" }, { "name": "Shell", "bytes": "90362" }, { "name": "Web Ontology Language", "bytes": "1998135" }, { "name": "XSLT", "bytes": "124838" } ], "symlink_target": "" }
import { User } from '../auth/user'; import { Transaction } from '../core/transaction'; import { OnlineState, TargetId } from '../core/types'; import { LocalStore } from '../local/local_store'; import { QueryData } from '../local/query_data'; import { Datastore } from './datastore'; import { RemoteSyncer } from './remote_syncer'; import { AsyncQueue } from '../util/async_queue'; /** * RemoteStore - An interface to remotely stored data, basically providing a * wrapper around the Datastore that is more reliable for the rest of the * system. * * RemoteStore is responsible for maintaining the connection to the server. * - maintaining a list of active listens. * - reconnecting when the connection is dropped. * - resuming all the active listens on reconnect. * * RemoteStore handles all incoming events from the Datastore. * - listening to the watch stream and repackaging the events as RemoteEvents * - notifying SyncEngine of any changes to the active listens. * * RemoteStore takes writes from other components and handles them reliably. * - pulling pending mutations from LocalStore and sending them to Datastore. * - retrying mutations that failed because of network problems. * - acking mutations to the SyncEngine once they are accepted or rejected. */ export declare class RemoteStore { /** * The local store, used to fill the write pipeline with outbound * mutations and resolve existence filter mismatches. */ private localStore; /** The client-side proxy for interacting with the backend. */ private datastore; private pendingWrites; private lastBatchSeen; /** * A mapping of watched targets that the client cares about tracking and the * user has explicitly called a 'listen' for this target. * * These targets may or may not have been sent to or acknowledged by the * server. On re-establishing the listen stream, these targets should be sent * to the server. The targets removed with unlistens are removed eagerly * without waiting for confirmation from the listen stream. */ private listenTargets; /** * A mapping of targetId to pending acks needed. * * If a targetId is present in this map, then we're waiting for watch to * acknowledge a removal or addition of the target. If a target is not in this * mapping, and it's in the listenTargets map, then we consider the target to * be active. * * We increment the count here every time we issue a request over the stream * to watch or unwatch. We then decrement the count every time we get a target * added or target removed message from the server. Once the count is equal to * 0 we know that the client and server are in the same state (once this state * is reached the targetId is removed from the map to free the memory). */ private pendingTargetResponses; private accumulatedWatchChanges; private watchStream; private writeStream; private onlineStateTracker; constructor( /** * The local store, used to fill the write pipeline with outbound * mutations and resolve existence filter mismatches. */ localStore: LocalStore, /** The client-side proxy for interacting with the backend. */ datastore: Datastore, asyncQueue: AsyncQueue, onlineStateHandler: (onlineState: OnlineState) => void); /** SyncEngine to notify of watch and write events. */ syncEngine: RemoteSyncer; /** * Starts up the remote store, creating streams, restoring state from * LocalStore, etc. */ start(): Promise<void>; private isNetworkEnabled(); /** Re-enables the network. Idempotent. */ enableNetwork(): Promise<void>; /** * Temporarily disables the network. The network can be re-enabled using * enableNetwork(). */ disableNetwork(): Promise<void>; /** * Disables the network, if it is currently enabled. */ private disableNetworkInternal(); shutdown(): Promise<void>; /** Starts new listen for the given query. Uses resume token if provided */ listen(queryData: QueryData): void; /** Removes the listen from server */ unlisten(targetId: TargetId): void; /** * We need to increment the the expected number of pending responses we're due * from watch so we wait for the ack to process any messages from this target. */ private sendWatchRequest(queryData); /** * We need to increment the expected number of pending responses we're due * from watch so we wait for the removal on the server before we process any * messages from this target. */ private sendUnwatchRequest(targetId); /** * Increment the mapping of how many acks are needed from watch before we can * consider the server to be 'in-sync' with the client's active targets. */ private recordPendingTargetRequest(targetId); private startWatchStream(); /** * Returns whether the watch stream should be started because it's necessary * and has not yet been started. */ private shouldStartWatchStream(); private cleanUpWatchStreamState(); private onWatchStreamOpen(); private onWatchStreamClose(error); private onWatchStreamChange(watchChange, snapshotVersion); /** * Takes a batch of changes from the Datastore, repackages them as a * RemoteEvent, and passes that on to the listener, which is typically the * SyncEngine. */ private handleWatchChangeBatch(snapshotVersion, changes); /** Handles an error on a target */ private handleTargetError(watchChange); cleanUpWriteStreamState(): void; /** * Notifies that there are new mutations to process in the queue. This is * typically called by SyncEngine after it has sent mutations to LocalStore. */ fillWritePipeline(): Promise<void>; /** * Returns true if the backend can accept additional write requests. * * When sending mutations to the write stream (e.g. in fillWritePipeline), * call this method first to check if more mutations can be sent. * * Currently the only thing that can prevent the backend from accepting * write requests is if there are too many requests already outstanding. As * writes complete the backend will be able to accept more. */ canWriteMutations(): boolean; outstandingWrites(): number; /** * Given mutations to commit, actually commits them to the Datastore. Note * that this does *not* return a Promise specifically because the AsyncQueue * should not block operations for this. */ private commit(batch); private shouldStartWriteStream(); private startWriteStream(); private onWriteStreamOpen(); private onWriteHandshakeComplete(); private onMutationResult(commitVersion, results); private onWriteStreamClose(error?); private handleHandshakeError(error); private handleWriteError(error); createTransaction(): Transaction; handleUserChange(user: User): Promise<void>; }
{ "content_hash": "b63383bcf03fe33dba78ae48d7364e9e", "timestamp": "", "source": "github", "line_count": 168, "max_line_length": 110, "avg_line_length": 42.36309523809524, "alnum_prop": 0.6990304903751581, "repo_name": "SpatialMap/SpatialMapDev", "id": "424b10370a943e4c5679916152f576d981349ed2", "size": "7710", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "node_modules/@firebase/firestore/dist/src/remote/remote_store.d.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "32148" }, { "name": "HTML", "bytes": "14793" }, { "name": "JavaScript", "bytes": "186767" } ], "symlink_target": "" }
class EncodingProfileDocument < ActiveFedora::NokogiriDatastream set_terminology do |t| t.root(:path=>"encodingProfile", #:xmlns => 'avalon/encoding', :namespace_prefix=>nil) # The quality is a quick way to determine which stream to provide # on the fly # # Expected values are 'low', 'medium', and 'high' t.quality(path: 'quality') # MIME type is provided to the player so it can serve the right context # to the user t.mime_type(path: 'mime_type') # Both audio and video have a bitrate and codec but video also adds # additional information about resolution and framerate since it is # visual. # # An audio profile should always be present but video depends if the # content is visual as well. t.audio(path: 'audio') { t.audio_bitrate(path: 'bitrate') t.audio_codec(path: 'codec') } t.video(path: 'video') { t.video_bitrate(path: 'bitrate') t.video_codec(path: 'codec') t.resolution { t.video_width(path: 'width') t.video_height(path: 'height') } t.frame_rate(path: 'framerate') } end def self.xml_template builder = Nokogiri::XML::Builder.new do |xml| xml.encodingProfile { xml.quality xml.mime_type xml.audio { xml.bitrate xml.codec } } end return builder.doc end end
{ "content_hash": "14e2ee9cc3cc594cac451ad46086cc74", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 75, "avg_line_length": 26.703703703703702, "alnum_prop": 0.5991678224687933, "repo_name": "tessafallon/dhf", "id": "96867981dd60049f2b8b1275165fcc3e601b30b7", "size": "2123", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "avalon/branches/comments-refactor/app/models/encoding_profile_document.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1337412" }, { "name": "CoffeeScript", "bytes": "260022" }, { "name": "JavaScript", "bytes": "3289902" }, { "name": "Ruby", "bytes": "10896953" }, { "name": "Shell", "bytes": "3367" } ], "symlink_target": "" }
#ifndef BOOST_CONTAINERS_DETAIL_VERSION_TYPE_HPP #define BOOST_CONTAINERS_DETAIL_VERSION_TYPE_HPP #include "config_begin.hpp" #include INCLUDE_BOOST_CONTAINER_DETAIL_MPL_HPP #include INCLUDE_BOOST_CONTAINER_DETAIL_TYPE_TRAITS_HPP namespace boost{ namespace container { namespace containers_detail { //using namespace boost; template <class T, unsigned V> struct version_type : public containers_detail::integral_constant<unsigned, V> { typedef T type; version_type(const version_type<T, 0>&); }; namespace impl{ template <class T, bool = containers_detail::is_convertible<version_type<T, 0>, typename T::version>::value> struct extract_version { static const unsigned value = 1; }; template <class T> struct extract_version<T, true> { static const unsigned value = T::version::value; }; template <class T> struct has_version { private: struct two {char _[2];}; template <class U> static two test(...); template <class U> static char test(const typename U::version*); public: static const bool value = sizeof(test<T>(0)) == 1; void dummy(){} }; template <class T, bool = has_version<T>::value> struct version { static const unsigned value = 1; }; template <class T> struct version<T, true> { static const unsigned value = extract_version<T>::value; }; } //namespace impl template <class T> struct version : public containers_detail::integral_constant<unsigned, impl::version<T>::value> { }; } //namespace containers_detail { } //namespace container { } //namespace boost{ #endif //#define BOOST_CONTAINERS_DETAIL_VERSION_TYPE_HPP
{ "content_hash": "4c455fa065f2271b152a86a2166da97d", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 99, "avg_line_length": 21.67948717948718, "alnum_prop": 0.6729745712596097, "repo_name": "pennwin2013/netsvr", "id": "fdaa688b5cf36527d2ad872f40bb30aea7d457ae", "size": "2279", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "include/boost/interprocess/containers/container/detail/version_type.hpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "67355" }, { "name": "C++", "bytes": "52439988" }, { "name": "Python", "bytes": "2525" } ], "symlink_target": "" }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation; namespace Test.Isolated.Root { [Cmdlet("Test", "RootCommand")] public class TestRootCommand : PSCmdlet { [Parameter(Mandatory = true)] public Red Param { get; set; } protected override void ProcessRecord() { WriteObject(Param.Name); } } public class Red { public string Name { get; } public Red(string name) { Name = name; } } public class Yellow { public string Id { get; } public Yellow(string id) { Id = id; } } }
{ "content_hash": "2578d5d4bf37d5f0dc4d6c207ac99885", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 47, "avg_line_length": 18.358974358974358, "alnum_prop": 0.5321229050279329, "repo_name": "TravisEz13/PowerShell", "id": "74aa40006f253a683eb753efa3c8268be77d3d8f", "size": "718", "binary": false, "copies": "4", "ref": "refs/heads/travisez13-main", "path": "test/tools/TestAlc/root/RootCommand.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "24" }, { "name": "C#", "bytes": "30828572" }, { "name": "Dockerfile", "bytes": "6464" }, { "name": "HTML", "bytes": "18060" }, { "name": "JavaScript", "bytes": "8738" }, { "name": "PowerShell", "bytes": "4998299" }, { "name": "Rich Text Format", "bytes": "40664" }, { "name": "Roff", "bytes": "214981" }, { "name": "Shell", "bytes": "57904" }, { "name": "XSLT", "bytes": "14397" } ], "symlink_target": "" }
<!-- Description: Agrave Expect: feed['title'] == 'testing \xc0 entity' --> <feed xmlns="http://www.w3.org/2005/Atom"> <title>testing &Agrave; entity</title> </feed>
{ "content_hash": "8e8129b19856f9ed2cdfb3b35e8c53fb", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 51, "avg_line_length": 24.428571428571427, "alnum_prop": 0.6432748538011696, "repo_name": "simplepie/simplepie-ng", "id": "7e4d27e681a39abb9b1e6b648842a3d5d6ff251c", "size": "171", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/Integration/feeds/entities/upper_Agrave.xml", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "22404" }, { "name": "Makefile", "bytes": "8026" }, { "name": "PHP", "bytes": "505427" }, { "name": "Python", "bytes": "10399" }, { "name": "Roff", "bytes": "2170" }, { "name": "Shell", "bytes": "271" }, { "name": "XSLT", "bytes": "734" } ], "symlink_target": "" }
<!DOCTYPE html> <html class="no-js"> <head lang="en-us"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,user-scalable=no,initial-scale=1,maximum-scale=1"> <meta http-equiv="X-UA-Compatible" content="IE=10" /> <title>Aggregates - Uchiwa Documentation</title> <meta name="generator" content="Hugo 0.30.2" /> <meta name="description" content="A simple dashboard for the Sensu monitoring framework"> <link rel="canonical" href="https://docs.uchiwa.io/reference/aggregates/"> <meta name="author" content="Simon Plourde"> <meta property="og:url" content="https://docs.uchiwa.io/reference/aggregates/"> <meta property="og:title" content="Uchiwa Documentation"> <meta name="apple-mobile-web-app-title" content="Uchiwa Documentation"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"> <link rel="shortcut icon" type="image/x-icon" href="https://docs.uchiwa.io/images/favicon.ico"> <link rel="icon" type="image/x-icon" href="https://docs.uchiwa.io/images/favicon.ico"> <style> @font-face { font-family: 'Icon'; src: url('https://docs.uchiwa.io/fonts/icon.eot?52m981'); src: url('https://docs.uchiwa.io/fonts/icon.eot?#iefix52m981') format('embedded-opentype'), url('https://docs.uchiwa.io/fonts/icon.woff?52m981') format('woff'), url('https://docs.uchiwa.io/fonts/icon.ttf?52m981') format('truetype'), url('https://docs.uchiwa.io/fonts/icon.svg?52m981#icon') format('svg'); font-weight: normal; font-style: normal; } </style> <link rel="stylesheet" href="https://docs.uchiwa.io/stylesheets/application.css"> <link rel="stylesheet" href="https://docs.uchiwa.io/stylesheets/temporary.css"> <link rel="stylesheet" href="https://docs.uchiwa.io/stylesheets/palettes.css"> <link rel="stylesheet" href="https://docs.uchiwa.io/stylesheets/highlight/highlight.css"> <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Roboto:400,700|Roboto&#43;Mono"> <style> body, input { font-family: 'Roboto', Helvetica, Arial, sans-serif; } pre, code { font-family: 'Roboto Mono', 'Courier New', 'Courier', monospace; } </style> <script src="https://docs.uchiwa.io/javascripts/modernizr.js"></script> </head> <body class="palette-primary-light-blue palette-accent-light-blue"> <div class="backdrop"> <div class="backdrop-paper"></div> </div> <input class="toggle" type="checkbox" id="toggle-drawer"> <input class="toggle" type="checkbox" id="toggle-search"> <label class="toggle-button overlay" for="toggle-drawer"></label> <header class="header"> <nav aria-label="Header"> <div class="bar default"> <div class="button button-menu" role="button" aria-label="Menu"> <label class="toggle-button icon icon-menu" for="toggle-drawer"> <span></span> </label> </div> <div class="stretch"> <div class="title"> Aggregates </div> </div> <div class="button button-twitter" role="button" aria-label="Twitter"> <a href="https://twitter.com/uchiwaio" title="@uchiwaio on Twitter" target="_blank" class="toggle-button icon icon-twitter"></a> </div> <div class="button button-github" role="button" aria-label="GitHub"> <a href="https://github.com/palourde" title="@palourde on GitHub" target="_blank" class="toggle-button icon icon-github"></a> </div> </div> <div class="bar search"> <div class="button button-close" role="button" aria-label="Close"> <label class="toggle-button icon icon-back" for="toggle-search"></label> </div> <div class="stretch"> <div class="field"> <input class="query" type="text" placeholder="Search" autocapitalize="off" autocorrect="off" autocomplete="off" spellcheck> </div> </div> <div class="button button-reset" role="button" aria-label="Search"> <button class="toggle-button icon icon-close" id="reset-search"></button> </div> </div> </nav> </header> <main class="main"> <div class="drawer"> <nav aria-label="Navigation"> <a href="https://github.com/sensu/uchiwa" class="project"> <div class="banner"> <div class="name"> <strong>Uchiwa Documentation <span class="version">1.1.0</span></strong> <br> sensu/uchiwa </div> </div> </a> <div class="scrollable"> <div class="wrapper"> <ul class="repo"> <li class="repo-download"> <a href="https://uchiwa.io/#/download" title="Download" data-action="download"> <i class="icon icon-download"></i> Download </a> </li> <li class="repo-stars"> <a href="https://github.com/sensu/uchiwa/stargazers" target="_blank" title="Stargazers" data-action="star"> <i class="icon icon-star"></i> Stars <span class="count">&ndash;</span> </a> </li> </ul> <hr> <div class="toc"> <ul> <li> <a title="Home" href="https://docs.uchiwa.io/"> Home </a> </li> <li> <span class="section">Getting Started</span> <ul> <a title="Basic Concepts" href="https://docs.uchiwa.io/getting-started/basic-concepts/"> Basic Concepts </a> <a title="Installation" href="https://docs.uchiwa.io/getting-started/installation/"> Installation </a> <a title="Configuration" href="https://docs.uchiwa.io/getting-started/configuration/"> Configuration </a> </ul> </li> <li> <span class="section">Guides</span> <ul> <a title="High Availability" href="https://docs.uchiwa.io/guides/high-availability/"> High Availability </a> <a title="Search Queries" href="https://docs.uchiwa.io/guides/search-queries/"> Search Queries </a> <a title="Security" href="https://docs.uchiwa.io/guides/security/"> Security </a> <a title="Troubleshooting" href="https://docs.uchiwa.io/guides/troubleshooting/"> Troubleshooting </a> </ul> </li> <li> <span class="section">Reference</span> <ul> <a class="current" title="Aggregates" href="https://docs.uchiwa.io/reference/aggregates/"> Aggregates </a> <ul id="scrollspy"> </ul> <a title="Checks" href="https://docs.uchiwa.io/reference/checks/"> Checks </a> <a title="Clients" href="https://docs.uchiwa.io/reference/clients/"> Clients </a> <a title="Events" href="https://docs.uchiwa.io/reference/events/"> Events </a> <a title="Silencing" href="https://docs.uchiwa.io/reference/silencing/"> Silencing </a> </ul> </li> <li> <span class="section">API</span> <ul> <a title="Authentication" href="https://docs.uchiwa.io/api/authentication/"> Authentication </a> <a title="Health API" href="https://docs.uchiwa.io/api/health/"> Health API </a> </ul> </li> <li> <a title="Contributing" href="https://docs.uchiwa.io/contributing"> Contributing </a> </li> </ul> <hr> <span class="section">The author</span> <ul> <li> <a href="https://twitter.com/uchiwaio" target="_blank" title="@uchiwaio on Twitter"> @uchiwaio on Twitter </a> </li> <li> <a href="https://github.com/palourde" target="_blank" title="@palourde on GitHub"> @palourde on GitHub </a> </li> <li> <a href="mailto:[email protected]" title="Email of [email protected]"> Contact via email </a> </li> </ul> </div> </div> </div> </nav> </div> <article class="article"> <div class="wrapper"> <h1>Aggregates </h1> <p>To understand aggregates in Sensu, please refer yourself to the <a href="https://sensuapp.org/docs/latest/reference/aggregates.html">Sensu documentation</a>.</p> <h2 id="list-all-aggregates">List All Aggregates</h2> <p>To view all aggregates, head over to the <em>aggregates view</em>.</p> <h2 id="view-an-aggregate">View An Aggregate</h2> <p>To see the detail of a specific aggregate, click on it from the <em>aggregates view</em>. From there, you can see the <strong>check</strong> and <strong>client members</strong>, in addition to the <strong>results</strong> of every check members.</p> <h2 id="delete-an-aggregate">Delete An Aggregate</h2> <p>It&rsquo;s currently impossible to delete an aggregate from Uchiwa, but we would love to have you <a href="https://docs.uchiwa.io/contributing/">contribute</a> to Uchiwa by implementing this feature!</p> <aside class="copyright" role="note"> &copy; 2018 Released under the MIT license &ndash; Documentation built with <a href="https://www.gohugo.io" target="_blank">Hugo</a> using the <a href="http://github.com/digitalcraftsman/hugo-material-docs" target="_blank">Material</a> theme. </aside> <footer class="footer"> <nav class="pagination" aria-label="Footer"> <div class="previous"> <a href="https://docs.uchiwa.io/guides/troubleshooting/" title="Troubleshooting"> <span class="direction"> Previous </span> <div class="page"> <div class="button button-previous" role="button" aria-label="Previous"> <i class="icon icon-back"></i> </div> <div class="stretch"> <div class="title"> Troubleshooting </div> </div> </div> </a> </div> <div class="next"> <a href="https://docs.uchiwa.io/reference/checks/" title="Checks"> <span class="direction"> Next </span> <div class="page"> <div class="stretch"> <div class="title"> Checks </div> </div> <div class="button button-next" role="button" aria-label="Next"> <i class="icon icon-forward"></i> </div> </div> </a> </div> </nav> </footer> </div> </article> <div class="results" role="status" aria-live="polite"> <div class="scrollable"> <div class="wrapper"> <div class="meta"></div> <div class="list"></div> </div> </div> </div> </main> <script> var base_url = 'https:\/\/docs.uchiwa.io\/'; var repo_id = 'sensu\/uchiwa'; </script> <script src="https://docs.uchiwa.io/javascripts/application.js"></script> <script> /* Add headers to scrollspy */ var headers = document.getElementsByTagName("h2"); var scrollspy = document.getElementById('scrollspy'); if(scrollspy) { if(headers.length > 0) { for(var i = 0; i < headers.length; i++) { var li = document.createElement("li"); li.setAttribute("class", "anchor"); var a = document.createElement("a"); a.setAttribute("href", "#" + headers[i].id); a.setAttribute("title", headers[i].innerHTML); a.innerHTML = headers[i].innerHTML; li.appendChild(a) scrollspy.appendChild(li); } } else { scrollspy.parentElement.removeChild(scrollspy) } /* Add permanent link next to the headers */ var headers = document.querySelectorAll("h1, h2, h3, h4, h5, h6"); for(var i = 0; i < headers.length; i++) { var a = document.createElement("a"); a.setAttribute("class", "headerlink"); a.setAttribute("href", "#" + headers[i].id); a.setAttribute("title", "Permanent link") a.innerHTML = "#"; headers[i].appendChild(a); } } </script> <script> (function(i,s,o,g,r,a,m){ i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q|| []).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g; m.parentNode.insertBefore(a,m) })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga'); ga('create', 'UA-56100759-3', 'auto'); ga('set', 'anonymizeIp', true); ga('send', 'pageview'); var buttons = document.querySelectorAll('a'); Array.prototype.map.call(buttons, function(item) { if (item.host != document.location.host) { item.addEventListener('click', function() { var action = item.getAttribute('data-action') || 'follow'; ga('send', 'event', 'outbound', action, item.href); }); } }); var query = document.querySelector('.query'); query.addEventListener('blur', function() { if (this.value) { var path = document.location.pathname; ga('send', 'pageview', path + '?q=' + this.value); } }); </script> <script src="//gohugo.io/js/highlight.pack.js"></script> <script>hljs.initHighlightingOnLoad();</script> </body> </html>
{ "content_hash": "4180b8ed1620da2ee9f9a9da35e5a7f0", "timestamp": "", "source": "github", "line_count": 665, "max_line_length": 135, "avg_line_length": 21.090225563909776, "alnum_prop": 0.5564349376114082, "repo_name": "palourde/uchiwa-docs", "id": "66494dc9594f0522d12b0a13f5e63e85dbce3539", "size": "14025", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/reference/aggregates/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1426" }, { "name": "HTML", "bytes": "18439" } ], "symlink_target": "" }
package ceylon.interop.java.internal; import ceylon.language.Array; import ceylon.language.AssertionError; import ceylon.language.SharedAnnotation$annotation$; import com.redhat.ceylon.compiler.java.language.IntArray; import com.redhat.ceylon.compiler.java.metadata.Ceylon; import com.redhat.ceylon.compiler.java.metadata.Ignore; import com.redhat.ceylon.compiler.java.metadata.Method; import com.redhat.ceylon.compiler.java.metadata.Name; import com.redhat.ceylon.compiler.java.metadata.TypeInfo; @Ceylon(major = 7) @Method @SharedAnnotation$annotation$ public final class javaIntArray_ { @Ignore private javaIntArray_() {} /** * Cast a Ceylon <code>Array&lt;Character&gt;</code> or * <code>Array&lt;java.lang.Integer&gt;</code> to a Java * <code>IntArray</code>, that is, to <code>int[]</code>, * preserving the identity of the given array. * * @see IntArray */ public static int[] javaIntArray(@SuppressWarnings("rawtypes") @Name("array") @TypeInfo("ceylon.language::Array<ceylon.language::Character>|ceylon.language::Array<java.lang::Integer>") Object array){ @SuppressWarnings("rawtypes") Object a = ((Array) array).toArray(); if(a instanceof int[]){ return (int[]) a; } throw new AssertionError("Invalid source array type: "+a); } }
{ "content_hash": "e1180a0ab2ab553819c7ce15f49b674b", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 111, "avg_line_length": 32.80952380952381, "alnum_prop": 0.690856313497823, "repo_name": "jvasileff/ceylon-sdk", "id": "9e46c4d75d68b45de26b79e807ed56c2118a19d0", "size": "1378", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "source/ceylon/interop/java/internal/javaIntArray_.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "3083" }, { "name": "Ceylon", "bytes": "1691439" }, { "name": "Java", "bytes": "26965" }, { "name": "Shell", "bytes": "549" } ], "symlink_target": "" }
#include "netip/ip_manager.hh" static IP_Manager s_manager; IP_Manager & IP_Manager::manager () { return s_manager; } /* * Use IP_Manager::manager() to get the global instance */ IP_Manager::IP_Manager () : EL(0), timer(this), ping_interval(1), ping_next(0), last_port(0xC000), host(IP_Address_DefaultHost), gateway(IP_Address_DefaultGateway), netmask(IP_Address_DefaultNetmask), ticker(0) { for (int i = 0; i < IP_Buffer_Extras; i++) { add_to_spares (buffers + i); } timer.start (*this, ping_interval); // we'll adjust this later } IP_Connection * IP_Manager::connection_for_port (const ns16_t & port) { Chain<IP_Connection>::iterator I = chain_connection.begin (); while (*I) { if ((*I)->listening (port)) { break; } ++I; } return *I; } u16_t IP_Manager::available_port () { while (true) { if (!connection_for_port (last_port)) { break; } if (last_port == 0xFFFF) { last_port = 0xC000; } else { ++last_port; } } return last_port; } bool IP_Manager::channel_add (IP_Channel * channel) { if (channel) { IP_Channel * C = chain_channel.chain_first (); if (C) { if (C->number () == 15) { return false; } channel->set_number (C->number () + 1); } else { channel->set_number (1); // first channel is #1; reserve 0 for ourself } chain_channel.chain_prepend (channel); } return true; } IP_Channel * IP_Manager::channel (u8_t number) { Chain<IP_Channel>::iterator I = chain_channel.begin (); while (*I) { if ((*I)->number () == number) { break; } ++I; } return *I; } void IP_Manager::connection_handover (IP_Buffer * buffer) { bool bHandedOver = false; Chain<IP_Connection>::iterator I = chain_connection.begin (); while (*I) { if ((*I)->accept (buffer)) { bHandedOver = true; break; } ++I; } if (!bHandedOver) { add_to_spares (buffer); } } bool IP_Manager::queue (IP_Buffer *& buffer) { bool bQueued = false; if (buffer) { IP_Buffer * pending = buffer; IP_Buffer * spare = get_from_spares (); if (buffer == spare) { DEBUG_PRINT ("$^$"); // help! } if (spare) { buffer = spare; chain_buffers_pending.chain_push (pending, true /* FIFO */); bQueued = true; } } return bQueued; } void IP_Manager::broadcast (IP_Buffer * buffer) { // DEBUG_PRINT("IP_Manager::broadcast\n"); u8_t channel_origin = buffer->channel (); bool bEndOfLine = true; Chain<IP_Channel>::iterator I = chain_channel.begin (); while (*I) { if ((*I)->number () != channel_origin) { // don't send it backwards (*I)->send (buffer); bEndOfLine = false; } ++I; } if (bEndOfLine) { add_to_spares (buffer); } } void IP_Manager::forward (IP_Buffer * buffer) { // DEBUG_PRINT("IP_Manager::forward\n"); u8_t channel_number; IP_Channel * ch = 0; switch (channel_for_destination (channel_number, buffer->ip().destination ())) { case ri_Destination_Self: // that's us! chain_buffers_pending.chain_push (buffer, true /* FIFO */); break; case ri_Destination_Local: // route through local network to final destination case ri_Gateway_Local: // route through local network to gateway ch = channel (channel_number); if (ch) { ch->send (buffer); } else { add_to_spares (buffer); } break; case ri_Broadcast_Local: broadcast (buffer); break; case ri_Gateway_Self: // we're the gateway - route to external network // TODO: route to external network case ri_InvalidAddress: // reserved network address, or channel not registered add_to_spares (buffer); break; } } IP_Manager::RoutingInfo IP_Manager::channel_for_destination (u8_t & channel, const IP_Address & destination) const { u8_t id; RoutingInfo ri; if (is_local_network (destination)) { id = destination.local_network_id (); if (id == host.local_network_id ()) { channel = 0; return ri_Destination_Self; } if (id == 255 /* reserved for broadcasts */) { return ri_Broadcast_Local; } ri = ri_Destination_Local; } else { id = gateway.local_network_id (); if (id == host.local_network_id ()) { channel = 0; return ri_Gateway_Self; } ri = ri_Gateway_Local; } if ((id == 0 /* reserved as a network identifier */) || (id == 255 /* reserved for broadcasts */)) { return ri_InvalidAddress; } if ((--id) & 1) { id >>= 1; channel = channel_register[id] & 0x0F; } else { id >>= 1; channel = channel_register[id] >> 4; } if (!channel) { return ri_InvalidAddress; } return ri; } void IP_Manager::register_source (u8_t channel, const IP_Address & source) { if (channel > 0x0F) { // allowed a maximum of 15 external channels; and 0 = self return; } if (!is_local_network (source)) { return; } u8_t id = source.local_network_id (); if ((id == 0 /* reserved as a network identifier */) || (id == 255 /* reserved for broadcasts */)) { return; } if ((--id) & 1) { id >>= 1; channel_register[id] &= 0xF0; channel_register[id] |= channel; } else { id >>= 1; channel_register[id] &= 0x0F; channel_register[id] |= (channel << 4); } } void IP_Manager::tick () { /* Update I/O channels */ Chain<IP_Channel>::iterator C = chain_channel.begin (); while (*C) { (*C)->update (); ++C; } switch (ticker) { // try to balance processor load to allow the timers to function properly case 0: { /* Update IP connections */ Chain<IP_Connection>::iterator I = chain_connection.begin (); while (*I) { (*I)->update (); ++I; } } ++ticker; break; case 1: // Handle next pending buffer, if any { IP_Buffer * pending = chain_buffers_pending.chain_pop (); if (pending) { // DEBUG_PRINT("IP_Manager::tick: pending\n"); switch (pending->sniff ()) { case IP_Buffer::hs_Okay: // DEBUG_PRINT("IP_Manager::tick: pending: Okay\n"); register_source (pending->channel (), pending->ip().source ()); if (pending->ip().destination () == host) { // it's for us connection_handover (pending); // hand over to appropriate connection } else { // forward it forward (pending); } break; case IP_Buffer::hs_EchoRequest: // DEBUG_PRINT("IP_Manager::tick: Echo Request\n"); register_source (pending->channel (), pending->ip().source ()); // pending->print (); if (pending->ip().destination () == host) { // it's for us; we don't respond to broadcast pings pending->ping_to_pong (); forward (pending); } else { // forward it if (chain_buffers_pending.chain_first () && !chain_buffers_spare.chain_first ()) { // if other pending (not possible if total spares == 1), but no spares, then drop it add_to_spares (pending); // more important to have spare buffers than ping packets (trying to avoid storms) } else { forward (pending); } } break; case IP_Buffer::hs_EchoReply: DEBUG_PRINT("IP_Manager::tick: Echo Reply\n"); // pending->print (); register_source (pending->channel (), pending->ip().source ()); if (pending->ip().destination () == host) { // it's for us if (EL) { u32_t round_trip; u16_t seq_no; pending->pong (round_trip, seq_no); // get the values EL->pong (pending->ip().source (), round_trip, seq_no); // pass them on } add_to_spares (pending); } else { // forward it forward (pending); } break; case IP_Buffer::hs_Protocol_Unsupported: DEBUG_PRINT("IP_Manager::tick: Protocol Unsupported\n"); register_source (pending->channel (), pending->ip().source ()); if (pending->ip().destination () == host) { // it's for us - but we can't use it add_to_spares (pending); } else { // forward it forward (pending); } break; /* Unable to handle this packet; don't handle or even forward it */ case IP_Buffer::hs_FrameError: case IP_Buffer::hs_IPv4: case IP_Buffer::hs_IPv4_FrameError: case IP_Buffer::hs_IPv4_PacketTooShort: case IP_Buffer::hs_IPv4_Checksum: case IP_Buffer::hs_IPv6: case IP_Buffer::hs_IPv6_FrameError: case IP_Buffer::hs_IPv6_PacketTooShort: case IP_Buffer::hs_Protocol_PacketTooShort: case IP_Buffer::hs_Protocol_FrameError: case IP_Buffer::hs_Protocol_Checksum: pending->print (); DEBUG_PRINT("IP_Manager::tick: Bad Packet\n"); add_to_spares (pending); break; } } } ++ticker; break; case 2: default: { // TODO: Handle next pending task, if any } ticker = 0; break; } } void IP_Manager::every_millisecond () { // ... } void IP_Manager::every_second () { // ... } bool IP_Manager::timeout () { // DEBUG_PRINT ("IP_Manager::timeout\n"); if (ping_interval == 1) { ping_interval = 1000 + 4 * (u16_t) host.local_network_id (); // set interval between 1 & 2 seconds timer.start (*this, ping_interval); } else { IP_Address B = host; B.set_local_network_id (255); // broadcast address for local network ping (B, ping_seq_no ()); } return true; // keep running } void IP_Manager::ping (const IP_Address & address, u16_t seq_no) { DEBUG_PRINT ("IP_Manager::ping\n"); IP_Buffer * spare = get_from_spares (); if (!spare) { DEBUG_PRINT ("IP_Manager::ping: no spare\n"); return; // can't do anything right now } spare->channel (0); spare->ping (address, seq_no); // spare->print (); forward (spare); }
{ "content_hash": "f85082d6cbadd30b38c2ef5785d2f226", "timestamp": "", "source": "github", "line_count": 404, "max_line_length": 172, "avg_line_length": 23.97029702970297, "alnum_prop": 0.5900454357703429, "repo_name": "FJFranklin/wifi-py-rpi-car-controller", "id": "268574f7f27ae95f8b17cf336106fe3b9124b097", "size": "11149", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "NetIP/ip_manager.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "26318" }, { "name": "C++", "bytes": "382308" }, { "name": "CSS", "bytes": "2234" }, { "name": "HTML", "bytes": "16732" }, { "name": "Hack", "bytes": "10142" }, { "name": "JavaScript", "bytes": "122246" }, { "name": "MATLAB", "bytes": "42930" }, { "name": "Makefile", "bytes": "2149" }, { "name": "Python", "bytes": "465172" }, { "name": "Shell", "bytes": "1864" } ], "symlink_target": "" }
export default class ZoteroCitationsView { private element: HTMLElement constructor(serializedState) { // Create root element this.element = document.createElement('div') this.element.classList.add('zotero-citations') // Create message element const message = document.createElement('div') message.textContent = 'The ZoteroCitations package is Alive! It\'s ALIVE!' message.classList.add('message') this.element.appendChild(message) } // Returns an object that can be retrieved when package is activated protected serialize() { console.log('nothing to do') } // Tear down any state and detach protected destroy() { this.element.remove() } protected getElement() { return this.element } }
{ "content_hash": "43de3d3d8f6d0e2ac50884ceee837764", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 78, "avg_line_length": 25.3, "alnum_prop": 0.7048748353096179, "repo_name": "ZotPlus/zotero-citations", "id": "2cdf0d83183ce526c2e6fd202b2e731ecabcb2a8", "size": "789", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/zotero-citations-view.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "6780" } ], "symlink_target": "" }
package org.apache.lens.cube.metadata; import java.util.*; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.hive.metastore.api.FieldSchema; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.ql.metadata.Table; public class DerivedCube extends AbstractCubeTable implements CubeInterface { private static final List<FieldSchema> COLUMNS = new ArrayList<FieldSchema>(); static { COLUMNS.add(new FieldSchema("dummy", "string", "dummy column")); } private final Cube parent; private final Set<String> measures = new HashSet<String>(); private final Set<String> dimensions = new HashSet<String>(); public DerivedCube(String name, Set<String> measures, Set<String> dimensions, Cube parent) { this(name, measures, dimensions, new HashMap<String, String>(), 0L, parent); } public DerivedCube(String name, Set<String> measures, Set<String> dimensions, Map<String, String> properties, double weight, Cube parent) { super(name, COLUMNS, properties, weight); for (String msr : measures) { this.measures.add(msr.toLowerCase()); } for (String dim : dimensions) { this.dimensions.add(dim.toLowerCase()); } this.parent = parent; addProperties(); } public DerivedCube(Table tbl, Cube parent) { super(tbl); this.measures.addAll(getMeasures(getName(), getProperties())); this.dimensions.addAll(getDimensions(getName(), getProperties())); this.parent = parent; } private Set<CubeMeasure> cachedMeasures = new HashSet<CubeMeasure>(); private Set<CubeDimAttribute> cachedDims = new HashSet<CubeDimAttribute>(); public Set<CubeMeasure> getMeasures() { synchronized (measures) { if (cachedMeasures.isEmpty()) { for (String msr : measures) { cachedMeasures.add(parent.getMeasureByName(msr)); } } } return cachedMeasures; } public Set<CubeDimAttribute> getDimAttributes() { synchronized (dimensions) { if (cachedDims.isEmpty()) { for (String dim : dimensions) { cachedDims.add(parent.getDimAttributeByName(dim)); } } } return cachedDims; } @Override public CubeTableType getTableType() { return CubeTableType.CUBE; } @Override public Set<String> getStorages() { return null; } @Override public void addProperties() { super.addProperties(); getProperties().put(MetastoreUtil.getCubeMeasureListKey(getName()), StringUtils.join(measures, ",").toLowerCase()); getProperties().put(MetastoreUtil.getCubeDimensionListKey(getName()), StringUtils.join(dimensions, ",").toLowerCase()); getProperties().put(MetastoreUtil.getParentCubeNameKey(getName()), parent.getName().toLowerCase()); getProperties().put(MetastoreUtil.getParentCubeNameKey(getName()), parent.getName().toLowerCase()); } public static Set<String> getMeasures(String name, Map<String, String> props) { Set<String> measures = new HashSet<String>(); String measureStr = props.get(MetastoreUtil.getCubeMeasureListKey(name)); measures.addAll(Arrays.asList(StringUtils.split(measureStr, ','))); return measures; } public Set<String> getTimedDimensions() { String str = getProperties().get(MetastoreUtil.getCubeTimedDimensionListKey(getName())); if (str != null) { Set<String> timedDimensions = new HashSet<String>(); timedDimensions.addAll(Arrays.asList(StringUtils.split(str, ','))); return timedDimensions; } else { return parent.getTimedDimensions(); } } public static Set<String> getDimensions(String name, Map<String, String> props) { Set<String> dimensions = new HashSet<String>(); String dimStr = props.get(MetastoreUtil.getCubeDimensionListKey(name)); dimensions.addAll(Arrays.asList(StringUtils.split(dimStr, ','))); return dimensions; } public Cube getParent() { return parent; } @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(Object obj) { if (!super.equals(obj)) { return false; } DerivedCube other = (DerivedCube) obj; if (!this.getParent().equals(other.getParent())) { return false; } if (this.getMeasureNames() == null) { if (other.getMeasureNames() != null) { return false; } } else if (!this.getMeasureNames().equals(other.getMeasureNames())) { return false; } if (this.getDimAttributeNames() == null) { if (other.getDimAttributeNames() != null) { return false; } } else if (!this.getDimAttributeNames().equals(other.getDimAttributeNames())) { return false; } return true; } public CubeDimAttribute getDimAttributeByName(String dimension) { if (dimensions.contains(dimension.toLowerCase())) { return parent.getDimAttributeByName(dimension); } return null; } public CubeMeasure getMeasureByName(String measure) { if (measures.contains(measure.toLowerCase())) { return parent.getMeasureByName(measure); } return null; } public CubeColumn getColumnByName(String column) { CubeColumn cubeCol = (CubeColumn) getMeasureByName(column); if (cubeCol == null) { cubeCol = (CubeColumn) getDimAttributeByName(column); } return cubeCol; } /** * Add a new measure * * @param measure * @throws HiveException */ public void addMeasure(String measure) throws HiveException { measures.add(measure.toLowerCase()); getProperties().put(MetastoreUtil.getCubeMeasureListKey(getName()), StringUtils.join(measures, ",").toLowerCase()); } /** * Add a new dimension * * @param dimension * @throws HiveException */ public void addDimension(String dimension) throws HiveException { dimensions.add(dimension.toLowerCase()); getProperties().put(MetastoreUtil.getCubeDimensionListKey(getName()), StringUtils.join(dimensions, ",").toLowerCase()); } /** * Remove the dimension with name specified * * @param dimName */ public void removeDimension(String dimName) { dimensions.remove(dimName.toLowerCase()); getProperties().put(MetastoreUtil.getCubeDimensionListKey(getName()), StringUtils.join(dimensions, ",").toLowerCase()); } /** * Remove the measure with name specified * * @param msrName */ public void removeMeasure(String msrName) { measures.remove(msrName.toLowerCase()); getProperties().put(MetastoreUtil.getCubeMeasureListKey(getName()), StringUtils.join(measures, ",").toLowerCase()); } @Override public boolean isDerivedCube() { return true; } @Override public Set<String> getMeasureNames() { return measures; } @Override public Set<String> getDimAttributeNames() { Set<String> dimNames = new HashSet<String>(); for (CubeDimAttribute f : getDimAttributes()) { MetastoreUtil.addColumnNames(f, dimNames); } return dimNames; } @Override public boolean allFieldsQueriable() { return true; } @Override public Set<ExprColumn> getExpressions() { return null; } @Override public ExprColumn getExpressionByName(String exprName) { return null; } @Override public Set<String> getAllFieldNames() { Set<String> fieldNames = new HashSet<String>(); fieldNames.addAll(getMeasureNames()); fieldNames.addAll(getDimAttributeNames()); fieldNames.addAll(getTimedDimensions()); return fieldNames; } @Override public Set<String> getExpressionNames() { // TODO Auto-generated method stub return null; } @Override public Set<JoinChain> getJoinChains() { // TODO Auto-generated method stub return null; } @Override public JoinChain getChainByName(String chainName) { // TODO Auto-generated method stub return null; } @Override public Set<String> getJoinChainNames() { // TODO Auto-generated method stub return null; } }
{ "content_hash": "d7cb0c7891e1d9736389748d3deba9ab", "timestamp": "", "source": "github", "line_count": 285, "max_line_length": 119, "avg_line_length": 28.014035087719297, "alnum_prop": 0.6842434869739479, "repo_name": "adeelmahmood/lens", "id": "e7012f7fab56cb2067c1c6a36cd566fb4dc0cae9", "size": "8792", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "lens-cube/src/main/java/org/apache/lens/cube/metadata/DerivedCube.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "10377" }, { "name": "Java", "bytes": "4422819" }, { "name": "JavaScript", "bytes": "282078" }, { "name": "Shell", "bytes": "14016" } ], "symlink_target": "" }
package org.apache.hadoop.yarn.server.nodemanager.containermanager.logaggregation; import org.apache.commons.io.FileUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileContext; import org.apache.hadoop.fs.Path; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationAccessType; import org.apache.hadoop.yarn.api.records.LogAggregationContext; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.event.Dispatcher; import org.apache.hadoop.yarn.event.Event; import org.apache.hadoop.yarn.event.EventHandler; import org.apache.hadoop.yarn.logaggregation.AggregatedLogFormat.LogKey; import org.apache.hadoop.yarn.logaggregation.AggregatedLogFormat.LogValue; import org.apache.hadoop.yarn.logaggregation.AggregatedLogFormat.LogWriter; import org.apache.hadoop.yarn.server.api.ContainerLogContext; import org.apache.hadoop.yarn.server.api.ContainerType; import org.apache.hadoop.yarn.server.nodemanager.Context; import org.apache.hadoop.yarn.server.nodemanager.DeletionService; import org.apache.hadoop.yarn.server.nodemanager.LocalDirsHandlerService; import org.apache.hadoop.yarn.server.nodemanager.NodeManager; import org.apache.hadoop.yarn.server.nodemanager.recovery.NMNullStateStoreService; import org.apache.hadoop.yarn.server.nodemanager.security.NMContainerTokenSecretManager; import org.apache.hadoop.yarn.server.nodemanager.security.NMTokenSecretManagerInNM; import org.apache.hadoop.yarn.server.security.ApplicationACLsManager; import org.apache.hadoop.yarn.util.ConverterUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Matchers; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; /** * Unit tests of AppLogAggregatorImpl class. */ public class TestAppLogAggregatorImpl { private static final File LOCAL_LOG_DIR = new File("target", TestAppLogAggregatorImpl.class.getName() + "-localLogDir"); private static final File REMOTE_LOG_FILE = new File("target", TestAppLogAggregatorImpl.class.getName() + "-remoteLogFile"); @Before public void setUp() throws IOException { if(LOCAL_LOG_DIR.exists()) { FileUtils.cleanDirectory(LOCAL_LOG_DIR); } if(REMOTE_LOG_FILE.exists()) { FileUtils.cleanDirectory(REMOTE_LOG_FILE); } } @After public void cleanUp() throws IOException { FileUtils.deleteDirectory(LOCAL_LOG_DIR); FileUtils.deleteQuietly(REMOTE_LOG_FILE); } @Test public void testAggregatorWithRetentionPolicyDisabledShouldUploadAllFiles() throws Exception { final ApplicationId applicationId = ApplicationId.newInstance(System.currentTimeMillis(), 0); final ApplicationAttemptId attemptId = ApplicationAttemptId.newInstance(applicationId, 0); final ContainerId containerId = ContainerId.newContainerId(attemptId, 0); // create artificial log files final File appLogDir = new File(LOCAL_LOG_DIR, applicationId.toString()); final File containerLogDir = new File(appLogDir, containerId.toString()); containerLogDir.mkdirs(); final Set<File> logFiles = createContainerLogFiles(containerLogDir, 3); final long logRetentionSecs = 10000; final long recoveredLogInitedTime = -1; verifyLogAggregationWithExpectedFiles2DeleteAndUpload( applicationId, containerId, logRetentionSecs, recoveredLogInitedTime, logFiles, logFiles); } @Test public void testAggregatorWhenNoFileOlderThanRetentionPolicyShouldUploadAll() throws IOException { final ApplicationId applicationId = ApplicationId.newInstance(System.currentTimeMillis(), 0); final ApplicationAttemptId attemptId = ApplicationAttemptId.newInstance(applicationId, 0); final ContainerId containerId = ContainerId.newContainerId(attemptId, 0); // create artificial log files final File appLogDir = new File(LOCAL_LOG_DIR, applicationId.toString()); final File containerLogDir = new File(appLogDir, containerId.toString()); containerLogDir.mkdirs(); final Set<File> logFiles = createContainerLogFiles(containerLogDir, 3); // set log retention period to 1 week. final long logRententionSec = 7 * 24 * 60 * 60; final long recoveredLogInitedTimeMillis = System.currentTimeMillis() - 60*60; verifyLogAggregationWithExpectedFiles2DeleteAndUpload(applicationId, containerId, logRententionSec, recoveredLogInitedTimeMillis, logFiles, logFiles); } @Test public void testAggregatorWhenAllFilesOlderThanRetentionShouldUploadNone() throws IOException { final ApplicationId applicationId = ApplicationId.newInstance(System.currentTimeMillis(), 0); final ApplicationAttemptId attemptId = ApplicationAttemptId.newInstance(applicationId, 0); final ContainerId containerId = ContainerId.newContainerId(attemptId, 0); // create artificial log files final File appLogDir = new File(LOCAL_LOG_DIR, applicationId.toString()); final File containerLogDir = new File(appLogDir, containerId.toString()); containerLogDir.mkdirs(); final Set<File> logFiles = createContainerLogFiles(containerLogDir, 3); final long week = 7 * 24 * 60 * 60; final long recoveredLogInitedTimeMillis = System.currentTimeMillis() - 2 * week * 1000; verifyLogAggregationWithExpectedFiles2DeleteAndUpload( applicationId, containerId, week, recoveredLogInitedTimeMillis, logFiles, new HashSet<File>()); } /** * Create the given number of log files under the container log directory. * @param containerLogDir the directory to create container log files * @param numOfFiles the number of log files to create * @return the set of log files created */ private static Set<File> createContainerLogFiles(File containerLogDir, int numOfFiles) throws IOException { assert(numOfFiles >= 0); assert(containerLogDir.exists()); Set<File> containerLogFiles = new HashSet<>(); for(int i = 0; i < numOfFiles; i++) { final File logFile = new File(containerLogDir, "logfile" + i); logFile.createNewFile(); containerLogFiles.add(logFile); } return containerLogFiles; } /** * Verify if the application log aggregator, configured with given log * retention period and the recovered log initialization time of * the application, uploads and deletes the set of log files as expected. * @param appId application id * @param containerId container id * @param logRetentionSecs log retention period * @param recoveredLogInitedTimeMillis recovered log initialization time * @param expectedFilesToDelete the set of files expected to be deleted * @param expectedFilesToUpload the set of files expected to be uploaded. */ public void verifyLogAggregationWithExpectedFiles2DeleteAndUpload( ApplicationId appId, ContainerId containerId, long logRetentionSecs, long recoveredLogInitedTimeMillis, Set<File> expectedFilesToDelete, Set<File> expectedFilesToUpload) throws IOException { final Set<String> filesExpected2Delete = new HashSet<>(); for(File file: expectedFilesToDelete) { filesExpected2Delete.add(file.getAbsolutePath()); } final Set<String> filesExpected2Upload = new HashSet<>(); for(File file: expectedFilesToUpload) { filesExpected2Upload.add(file.getAbsolutePath()); } // deletion service with verification to check files to delete DeletionService deletionServiceWithExpectedFiles = createDeletionServiceWithExpectedFile2Delete(filesExpected2Delete); final YarnConfiguration config = new YarnConfiguration(); config.setLong( YarnConfiguration.LOG_AGGREGATION_RETAIN_SECONDS, logRetentionSecs); final AppLogAggregatorInTest appLogAggregator = createAppLogAggregator(appId, LOCAL_LOG_DIR.getAbsolutePath(), config, recoveredLogInitedTimeMillis, deletionServiceWithExpectedFiles); appLogAggregator.startContainerLogAggregation( new ContainerLogContext(containerId, ContainerType.TASK, 0)); // set app finished flag first appLogAggregator.finishLogAggregation(); appLogAggregator.run(); // verify uploaded files ArgumentCaptor<LogValue> logValCaptor = ArgumentCaptor.forClass(LogValue.class); verify(appLogAggregator.logWriter).append(any(LogKey.class), logValCaptor.capture()); Set<String> filesUploaded = new HashSet<>(); LogValue logValue = logValCaptor.getValue(); for(File file: logValue.getPendingLogFilesToUploadForThisContainer()) { filesUploaded.add(file.getAbsolutePath()); } verifyFilesUploaded(filesUploaded , filesExpected2Upload); } private static void verifyFilesUploaded(Set<String> filesUploaded, Set<String> filesExpected) { final String errMsgPrefix = "The set of files uploaded are not the same " + "as expected"; if(filesUploaded.size() != filesExpected.size()) { fail(errMsgPrefix + ": actual size: " + filesUploaded.size() + " vs " + "expected size: " + filesExpected.size()); } for(String file: filesExpected) { if(!filesUploaded.contains(file)) { fail(errMsgPrefix + ": expecting " + file); } } } private static AppLogAggregatorInTest createAppLogAggregator( ApplicationId applicationId, String rootLogDir, YarnConfiguration config, long recoveredLogInitedTimeMillis, DeletionService deletionServiceWithFilesToExpect) throws IOException { final Dispatcher dispatcher = createNullDispatcher(); final NodeId nodeId = NodeId.newInstance("localhost", 0); final String userId = "AppLogAggregatorTest"; final UserGroupInformation ugi = UserGroupInformation.createRemoteUser(userId); final LocalDirsHandlerService dirsService = createLocalDirsHandlerService(config, rootLogDir); final DeletionService deletionService = deletionServiceWithFilesToExpect; final LogAggregationContext logAggregationContext = null; final Map<ApplicationAccessType, String> appAcls = new HashMap<>(); final Context context = createContext(config); final FileContext fakeLfs = mock(FileContext.class); final Path remoteLogDirForApp = new Path(REMOTE_LOG_FILE.getAbsolutePath()); return new AppLogAggregatorInTest(dispatcher, deletionService, config, applicationId, ugi, nodeId, dirsService, remoteLogDirForApp, appAcls, logAggregationContext, context, fakeLfs, recoveredLogInitedTimeMillis); } /** * Create a deletionService that verifies the paths of container log files * passed to the delete method of DeletionService by AppLogAggregatorImpl. * This approach is taken due to lack of support of varargs captor in the * current mockito version 1.8.5 (The support is added in 1.10.x). **/ private static DeletionService createDeletionServiceWithExpectedFile2Delete( final Set<String> expectedPathsForDeletion) { DeletionService deletionServiceWithExpectedFiles = mock(DeletionService .class); // verify paths passed to first invocation of delete method against // expected paths doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocationOnMock) throws Throwable { Set<String> paths = new HashSet<>(); Object[] args = invocationOnMock.getArguments(); for(int i = 2; i < args.length; i++) { Path path = (Path) args[i]; paths.add(path.toUri().getRawPath()); } verifyFilesToDelete(expectedPathsForDeletion, paths); return null; } }).doNothing().when(deletionServiceWithExpectedFiles).delete( any(String.class), any(Path.class), Matchers.<Path>anyVararg()); return deletionServiceWithExpectedFiles; } private static void verifyFilesToDelete(Set<String> files2ToDelete, Set<String> filesExpected) { final String errMsgPrefix = "The set of paths for deletion are not the " + "same as expected"; if(files2ToDelete.size() != filesExpected.size()) { fail(errMsgPrefix + ": actual size: " + files2ToDelete.size() + " vs " + "expected size: " + filesExpected.size()); } for(String file: filesExpected) { if(!files2ToDelete.contains(file)) { fail(errMsgPrefix + ": expecting " + file); } } } private static Dispatcher createNullDispatcher() { return new Dispatcher() { @Override public EventHandler<Event> getEventHandler() { return new EventHandler<Event>() { @Override public void handle(Event event) { // do nothing } }; } @Override public void register(Class<? extends Enum> eventType, EventHandler handler) { // do nothing } }; } private static LocalDirsHandlerService createLocalDirsHandlerService( YarnConfiguration conf, final String rootLogDir) { LocalDirsHandlerService dirsHandlerService = new LocalDirsHandlerService() { @Override public List<String> getLogDirsForRead() { return new ArrayList<String>() { { add(rootLogDir); } }; } @Override public List<String> getLogDirsForCleanup() { return new ArrayList<String>() { { add(rootLogDir); } }; } }; dirsHandlerService.init(conf); // appLogAggregator only calls LocalDirsHandlerServer for local directories // so it is ok to not start the service. return dirsHandlerService; } private static Context createContext(YarnConfiguration conf) { return new NodeManager.NMContext( new NMContainerTokenSecretManager(conf), new NMTokenSecretManagerInNM(), null, new ApplicationACLsManager(conf), new NMNullStateStoreService(), false, conf); } private static final class AppLogAggregatorInTest extends AppLogAggregatorImpl { final DeletionService deletionService; final ApplicationId applicationId; final LogWriter logWriter; final ArgumentCaptor<LogValue> logValue; public AppLogAggregatorInTest(Dispatcher dispatcher, DeletionService deletionService, Configuration conf, ApplicationId appId, UserGroupInformation ugi, NodeId nodeId, LocalDirsHandlerService dirsHandler, Path remoteNodeLogFileForApp, Map<ApplicationAccessType, String> appAcls, LogAggregationContext logAggregationContext, Context context, FileContext lfs, long recoveredLogInitedTime) throws IOException { super(dispatcher, deletionService, conf, appId, ugi, nodeId, dirsHandler, remoteNodeLogFileForApp, appAcls, logAggregationContext, context, lfs, -1, recoveredLogInitedTime); this.applicationId = appId; this.deletionService = deletionService; this.logWriter = getSpiedLogWriter(conf, ugi, remoteNodeLogFileForApp); this.logValue = ArgumentCaptor.forClass(LogValue.class); } @Override protected LogWriter createLogWriter() { return this.logWriter; } private LogWriter getSpiedLogWriter(Configuration conf, UserGroupInformation ugi, Path remoteAppLogFile) throws IOException { return spy(new LogWriter(conf, remoteAppLogFile, ugi)); } } }
{ "content_hash": "5c06b11ddb2aabc2cdfe15e985a756a2", "timestamp": "", "source": "github", "line_count": 418, "max_line_length": 88, "avg_line_length": 38.84688995215311, "alnum_prop": 0.731001354846656, "repo_name": "WIgor/hadoop", "id": "17d527a7a5df7ba890715f56b47590bcf86d0899", "size": "17044", "binary": false, "copies": "1", "ref": "refs/heads/trunk", "path": "hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/logaggregation/TestAppLogAggregatorImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "68758" }, { "name": "C", "bytes": "1406803" }, { "name": "C++", "bytes": "1816626" }, { "name": "CMake", "bytes": "54617" }, { "name": "CSS", "bytes": "58838" }, { "name": "HTML", "bytes": "207277" }, { "name": "Java", "bytes": "65993734" }, { "name": "JavaScript", "bytes": "628725" }, { "name": "Protocol Buffer", "bytes": "272379" }, { "name": "Python", "bytes": "23553" }, { "name": "Shell", "bytes": "388794" }, { "name": "TLA", "bytes": "14993" }, { "name": "TeX", "bytes": "19322" }, { "name": "XSLT", "bytes": "16894" } ], "symlink_target": "" }
/* * Do not modify this file. This file is generated from the config-2014-11-12.normal.json service model. */ using System; using System.IO; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using Amazon.ConfigService; using Amazon.ConfigService.Model; using Amazon.ConfigService.Model.Internal.MarshallTransformations; using Amazon.Runtime.Internal.Transform; using ServiceClientGenerator; using AWSSDK_DotNet35.UnitTests.TestTools; namespace AWSSDK_DotNet35.UnitTests.Marshalling { [TestClass] public class ConfigServiceMarshallingTests { static readonly ServiceModel service_model = Utils.LoadServiceModel("config-2014-11-12.normal.json", "config.customizations.json"); [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("ConfigService")] public void DeleteConfigRuleMarshallTest() { var request = InstantiateClassGenerator.Execute<DeleteConfigRuleRequest>(); var marshaller = new DeleteConfigRuleRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DeleteConfigRuleRequest>(request,jsonRequest); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("ConfigService")] public void DeleteDeliveryChannelMarshallTest() { var request = InstantiateClassGenerator.Execute<DeleteDeliveryChannelRequest>(); var marshaller = new DeleteDeliveryChannelRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DeleteDeliveryChannelRequest>(request,jsonRequest); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("ConfigService")] public void DeliverConfigSnapshotMarshallTest() { var request = InstantiateClassGenerator.Execute<DeliverConfigSnapshotRequest>(); var marshaller = new DeliverConfigSnapshotRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DeliverConfigSnapshotRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DeliverConfigSnapshot").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DeliverConfigSnapshotResponseUnmarshaller.Instance.Unmarshall(context) as DeliverConfigSnapshotResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("ConfigService")] public void DescribeComplianceByConfigRuleMarshallTest() { var request = InstantiateClassGenerator.Execute<DescribeComplianceByConfigRuleRequest>(); var marshaller = new DescribeComplianceByConfigRuleRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DescribeComplianceByConfigRuleRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeComplianceByConfigRule").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DescribeComplianceByConfigRuleResponseUnmarshaller.Instance.Unmarshall(context) as DescribeComplianceByConfigRuleResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("ConfigService")] public void DescribeComplianceByResourceMarshallTest() { var request = InstantiateClassGenerator.Execute<DescribeComplianceByResourceRequest>(); var marshaller = new DescribeComplianceByResourceRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DescribeComplianceByResourceRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeComplianceByResource").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DescribeComplianceByResourceResponseUnmarshaller.Instance.Unmarshall(context) as DescribeComplianceByResourceResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("ConfigService")] public void DescribeConfigRuleEvaluationStatusMarshallTest() { var request = InstantiateClassGenerator.Execute<DescribeConfigRuleEvaluationStatusRequest>(); var marshaller = new DescribeConfigRuleEvaluationStatusRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DescribeConfigRuleEvaluationStatusRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeConfigRuleEvaluationStatus").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DescribeConfigRuleEvaluationStatusResponseUnmarshaller.Instance.Unmarshall(context) as DescribeConfigRuleEvaluationStatusResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("ConfigService")] public void DescribeConfigRulesMarshallTest() { var request = InstantiateClassGenerator.Execute<DescribeConfigRulesRequest>(); var marshaller = new DescribeConfigRulesRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DescribeConfigRulesRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeConfigRules").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DescribeConfigRulesResponseUnmarshaller.Instance.Unmarshall(context) as DescribeConfigRulesResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("ConfigService")] public void DescribeConfigurationRecordersMarshallTest() { var request = InstantiateClassGenerator.Execute<DescribeConfigurationRecordersRequest>(); var marshaller = new DescribeConfigurationRecordersRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DescribeConfigurationRecordersRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeConfigurationRecorders").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DescribeConfigurationRecordersResponseUnmarshaller.Instance.Unmarshall(context) as DescribeConfigurationRecordersResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("ConfigService")] public void DescribeConfigurationRecorderStatusMarshallTest() { var request = InstantiateClassGenerator.Execute<DescribeConfigurationRecorderStatusRequest>(); var marshaller = new DescribeConfigurationRecorderStatusRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DescribeConfigurationRecorderStatusRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeConfigurationRecorderStatus").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DescribeConfigurationRecorderStatusResponseUnmarshaller.Instance.Unmarshall(context) as DescribeConfigurationRecorderStatusResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("ConfigService")] public void DescribeDeliveryChannelsMarshallTest() { var request = InstantiateClassGenerator.Execute<DescribeDeliveryChannelsRequest>(); var marshaller = new DescribeDeliveryChannelsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DescribeDeliveryChannelsRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeDeliveryChannels").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DescribeDeliveryChannelsResponseUnmarshaller.Instance.Unmarshall(context) as DescribeDeliveryChannelsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("ConfigService")] public void DescribeDeliveryChannelStatusMarshallTest() { var request = InstantiateClassGenerator.Execute<DescribeDeliveryChannelStatusRequest>(); var marshaller = new DescribeDeliveryChannelStatusRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DescribeDeliveryChannelStatusRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeDeliveryChannelStatus").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DescribeDeliveryChannelStatusResponseUnmarshaller.Instance.Unmarshall(context) as DescribeDeliveryChannelStatusResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("ConfigService")] public void GetComplianceDetailsByConfigRuleMarshallTest() { var request = InstantiateClassGenerator.Execute<GetComplianceDetailsByConfigRuleRequest>(); var marshaller = new GetComplianceDetailsByConfigRuleRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<GetComplianceDetailsByConfigRuleRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("GetComplianceDetailsByConfigRule").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = GetComplianceDetailsByConfigRuleResponseUnmarshaller.Instance.Unmarshall(context) as GetComplianceDetailsByConfigRuleResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("ConfigService")] public void GetComplianceDetailsByResourceMarshallTest() { var request = InstantiateClassGenerator.Execute<GetComplianceDetailsByResourceRequest>(); var marshaller = new GetComplianceDetailsByResourceRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<GetComplianceDetailsByResourceRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("GetComplianceDetailsByResource").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = GetComplianceDetailsByResourceResponseUnmarshaller.Instance.Unmarshall(context) as GetComplianceDetailsByResourceResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("ConfigService")] public void GetComplianceSummaryByConfigRuleMarshallTest() { var request = InstantiateClassGenerator.Execute<GetComplianceSummaryByConfigRuleRequest>(); var marshaller = new GetComplianceSummaryByConfigRuleRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("GetComplianceSummaryByConfigRule").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = GetComplianceSummaryByConfigRuleResponseUnmarshaller.Instance.Unmarshall(context) as GetComplianceSummaryByConfigRuleResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("ConfigService")] public void GetComplianceSummaryByResourceTypeMarshallTest() { var request = InstantiateClassGenerator.Execute<GetComplianceSummaryByResourceTypeRequest>(); var marshaller = new GetComplianceSummaryByResourceTypeRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<GetComplianceSummaryByResourceTypeRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("GetComplianceSummaryByResourceType").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = GetComplianceSummaryByResourceTypeResponseUnmarshaller.Instance.Unmarshall(context) as GetComplianceSummaryByResourceTypeResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("ConfigService")] public void GetResourceConfigHistoryMarshallTest() { var request = InstantiateClassGenerator.Execute<GetResourceConfigHistoryRequest>(); var marshaller = new GetResourceConfigHistoryRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<GetResourceConfigHistoryRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("GetResourceConfigHistory").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = GetResourceConfigHistoryResponseUnmarshaller.Instance.Unmarshall(context) as GetResourceConfigHistoryResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("ConfigService")] public void ListDiscoveredResourcesMarshallTest() { var request = InstantiateClassGenerator.Execute<ListDiscoveredResourcesRequest>(); var marshaller = new ListDiscoveredResourcesRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<ListDiscoveredResourcesRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ListDiscoveredResources").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = ListDiscoveredResourcesResponseUnmarshaller.Instance.Unmarshall(context) as ListDiscoveredResourcesResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("ConfigService")] public void PutConfigRuleMarshallTest() { var request = InstantiateClassGenerator.Execute<PutConfigRuleRequest>(); var marshaller = new PutConfigRuleRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<PutConfigRuleRequest>(request,jsonRequest); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("ConfigService")] public void PutConfigurationRecorderMarshallTest() { var request = InstantiateClassGenerator.Execute<PutConfigurationRecorderRequest>(); var marshaller = new PutConfigurationRecorderRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<PutConfigurationRecorderRequest>(request,jsonRequest); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("ConfigService")] public void PutDeliveryChannelMarshallTest() { var request = InstantiateClassGenerator.Execute<PutDeliveryChannelRequest>(); var marshaller = new PutDeliveryChannelRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<PutDeliveryChannelRequest>(request,jsonRequest); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("ConfigService")] public void PutEvaluationsMarshallTest() { var request = InstantiateClassGenerator.Execute<PutEvaluationsRequest>(); var marshaller = new PutEvaluationsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<PutEvaluationsRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("PutEvaluations").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = PutEvaluationsResponseUnmarshaller.Instance.Unmarshall(context) as PutEvaluationsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("ConfigService")] public void StartConfigurationRecorderMarshallTest() { var request = InstantiateClassGenerator.Execute<StartConfigurationRecorderRequest>(); var marshaller = new StartConfigurationRecorderRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<StartConfigurationRecorderRequest>(request,jsonRequest); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("ConfigService")] public void StopConfigurationRecorderMarshallTest() { var request = InstantiateClassGenerator.Execute<StopConfigurationRecorderRequest>(); var marshaller = new StopConfigurationRecorderRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<StopConfigurationRecorderRequest>(request,jsonRequest); } } }
{ "content_hash": "fcbad8677be4889c5884e70c92f135e4", "timestamp": "", "source": "github", "line_count": 602, "max_line_length": 166, "avg_line_length": 49.81893687707641, "alnum_prop": 0.6570637858024074, "repo_name": "rafd123/aws-sdk-net", "id": "29896ce8590ba0895ecba181f160689eec9b35a5", "size": "30578", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sdk/test/UnitTests/Generated/Marshalling/ConfigServiceMarshallingTests.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "85386370" }, { "name": "CSS", "bytes": "18119" }, { "name": "HTML", "bytes": "24352" }, { "name": "JavaScript", "bytes": "6576" }, { "name": "PowerShell", "bytes": "12753" }, { "name": "XSLT", "bytes": "7010" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name Caladenia dilatata var. stricta ### Remarks null
{ "content_hash": "71ce099342c548ca97cac9a22e0b749f", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 12.384615384615385, "alnum_prop": 0.7204968944099379, "repo_name": "mdoering/backbone", "id": "2eb368e61a720a049037aa524a45987fa4d368cc", "size": "224", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Caladenia/Caladenia stricta/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package com.amazonaws.services.directory.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.directory.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * DirectoryVpcSettings JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DirectoryVpcSettingsJsonUnmarshaller implements Unmarshaller<DirectoryVpcSettings, JsonUnmarshallerContext> { public DirectoryVpcSettings unmarshall(JsonUnmarshallerContext context) throws Exception { DirectoryVpcSettings directoryVpcSettings = new DirectoryVpcSettings(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("VpcId", targetDepth)) { context.nextToken(); directoryVpcSettings.setVpcId(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("SubnetIds", targetDepth)) { context.nextToken(); directoryVpcSettings.setSubnetIds(new ListUnmarshaller<String>(context.getUnmarshaller(String.class)) .unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return directoryVpcSettings; } private static DirectoryVpcSettingsJsonUnmarshaller instance; public static DirectoryVpcSettingsJsonUnmarshaller getInstance() { if (instance == null) instance = new DirectoryVpcSettingsJsonUnmarshaller(); return instance; } }
{ "content_hash": "850dd462822dc22ad3075cc93054b8f4", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 136, "avg_line_length": 36.391304347826086, "alnum_prop": 0.643568299482278, "repo_name": "aws/aws-sdk-java", "id": "b6b0ca2717b138250759875aa7b7d11052457f03", "size": "3091", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-directory/src/main/java/com/amazonaws/services/directory/model/transform/DirectoryVpcSettingsJsonUnmarshaller.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package org.opencds.cqf.cql.engine.elm.execution; import javax.xml.namespace.QName; import org.opencds.cqf.cql.engine.exception.InvalidOperatorArgument; import org.opencds.cqf.cql.engine.execution.Context; import org.opencds.cqf.cql.engine.runtime.Date; import org.opencds.cqf.cql.engine.runtime.DateTime; import org.opencds.cqf.cql.engine.runtime.Quantity; import org.opencds.cqf.cql.engine.runtime.Time; import org.opencds.cqf.cql.engine.runtime.Value; /* maximum<T>() T The maximum operator returns the maximum representable value for the given type. The maximum operator is defined for the Integer, Long, Decimal, DateTime, and Time types. For Integer, maximum returns the maximum signed 32-bit integer, 231 - 1. For Long, maximum returns the maximum signed 64-bit Long, 263 - 1. For Decimal, maximum returns the maximum representable decimal value, (1037 – 1) / 108 (9999999999999999999999999999.99999999). For DateTime, maximum returns the maximum representable date/time value, DateTime(9999, 12, 31, 23, 59, 59, 999). For Time, maximum returns the maximum representable time value, Time(23, 59, 59, 999). For any other type, attempting to invoke maximum results in an error. */ public class MaxValueEvaluator extends org.cqframework.cql.elm.execution.MaxValue { public static Object maxValue(String type) { if (type == null) { return null; } if (type.endsWith("Integer")) { return Value.MAX_INT; } if (type.endsWith("Long")) { return Value.MAX_LONG; } if (type.endsWith("Decimal")) { return Value.MAX_DECIMAL; } if (type.endsWith("Date")) { return new Date(9999, 12, 31); } if (type.endsWith("DateTime")) { return new DateTime(null, 9999, 12, 31, 23, 59, 59, 999); } if (type.endsWith("Time")) { return new Time(23, 59, 59, 999); } // NOTE: Quantity max is not standard if (type.endsWith("Quantity")) { return new Quantity().withValue(Value.MAX_DECIMAL).withUnit("1"); } throw new InvalidOperatorArgument(String.format("The Maximum operator is not implemented for type %s", type)); } @Override protected Object internalEvaluate(Context context) { QName valueType = context.fixupQName(this.getValueType()); String type = valueType.getLocalPart(); return maxValue(type); } }
{ "content_hash": "6fa089eafead9166573ab57cad6d5b3b", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 127, "avg_line_length": 38.06153846153846, "alnum_prop": 0.6721907841552143, "repo_name": "DBCG/cql_engine", "id": "2cb88f1b6f5341b7afea48dd64e9b1d8f41bf8f5", "size": "2476", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "engine/src/main/java/org/opencds/cqf/cql/engine/elm/execution/MaxValueEvaluator.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "382" }, { "name": "Java", "bytes": "1777463" }, { "name": "Shell", "bytes": "2259" } ], "symlink_target": "" }
package com.ceridwen.lcf.server.openapi;
{ "content_hash": "f9bb4212c764c76b0e367483d478a8d6", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 40, "avg_line_length": 21, "alnum_prop": 0.8095238095238095, "repo_name": "ceridwen-com/lcfserver", "id": "c84a4d8e9e8dca4ae3c0de21f38e4d279654434e", "size": "643", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "lcfserver-webservice/src/main/java/com/ceridwen/lcf/server/openapi/package-info.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "17439" }, { "name": "Java", "bytes": "202419" }, { "name": "Smalltalk", "bytes": "4806" } ], "symlink_target": "" }
![Mollie](https://www.mollie.com/files/Mollie-Logo-Style-Small.png) # Let op # Deze module wordt niet meer onderhouden, ook kan er geen ondersteuning meer worden geboden indien de module niet juist werkt. Onze excuses voor het ongemak. # Installatie # **Let op:** voor de installatie van deze module is FTP-toegang tot je webserver benodigd. Heb je hier geen ervaring mee? Laat de installatie van deze module dan over aan je websitebouwer of serverbeheerder. + Download op de [osCommerce Releases](https://github.com/mollie/OsCommerce/releases)-pagina de nieuwste release. + Kopieër de inhoud van de gedownloade map `catalog` naar de bestaande osCommerce-installatie op je server. + Ga naar uw osCommerce AdminPanel (Beheerpagina). + Ga in het menu naar _Modules_ en selecteer _Payments_. + Klik rechtsbovenin op de knop _Install module_. Indien correct geïnstalleerd, verschijnen in dit overzicht onze betaalmethodes onder de naam _Mollie_. + Klik op _Install module_ bij elke betaalmethode die u wenst te gebruiken. + Vul je _Mollie API key_ in en bewaar de instellingen. Je vindt de API key in Mollie Beheer onder [Websiteprofielen](https://www.mollie.com/beheer/account/profielen/). De instellingen worden automatisch toegepast op alle Mollie-betaalmethodes. # Over Mollie # Via [Mollie](https://www.mollie.com/) is gemakkelijk wereldwijd online betaalmethodes aan te sluiten zonder de gebruikelijke technische en administratieve rompslomp. Mollie geeft op ieder moment toegang tot je transactieoverzichten en andere statistieken. [Mollie](https://www.mollie.com/) is gestart door developers en verwerkt voor meer dan 20.000 websites de online betalingen. # Ondersteunde betaalmethodes # ### iDEAL ### Met [iDEAL](https://www.mollie.com/nl/betaaldiensten/ideal/) kun je vertrouwd, veilig en gemakkelijk uw online aankopen afrekenen. iDEAL is het systeem dat direct is gekoppelt aan je internetbankieren. ### Creditcard ### [Creditcard](https://www.mollie.com/nl/betaaldiensten/creditcard/) is vrijwel de bekendste methode voor het ontvangen van betalingen met wereldwijde dekking. Doordat we onder andere de bekende merken Mastercard en Visa ondersteunen, zorgt dit direct voor veel potentiële kopers. ### Mister Cash ### [Mister Cash](https://www.mollie.com/nl/betaaldiensten/mistercash/) maakt gebruik van een fysieke kaart die gekoppeld is aan tegoed op een Belgische bankrekening. Betalingen via Mister Cash zijn gegarandeerd en lijkt daarmee sterk op iDEAL in Nederland. Daarom is het uitermate geschikt voor uw webwinkel. ### Overboekingen ### [Overboekingen](https://www.mollie.com/nl/betaaldiensten/overboeking/) binnen de SEPA zone ontvangen via Mollie. Hiermee kun je betalingen ontvangen van zowel particulieren als zakelijke klanten in meer dan 35 Europese landen. ### PayPal ### [PayPal](https://www.mollie.com/nl/betaaldiensten/paypal/) is wereldwijd een zeer populaire betaalmethode. In enkele klikken kun je betalingen ontvangen via een bankoverschrijving, creditcard of het PayPal-saldo. ### Bitcoin ### [Bitcoin](https://www.mollie.com/nl/betaaldiensten/bitcoin/) is een vorm van elektronisch geld. De bitcoin-euro wisselkoers wordt vastgesteld op het moment van de transactie waardoor het bedrag en de uitbetaling zijn gegarandeerd. ### paysafecard ### [paysafecard](https://www.mollie.com/nl/betaaldiensten/paysafecard/) is de populairste prepaidcard voor online betalingen die veel door ouders voor hun kinderen wordt gekocht. # Veelgestelde vragen # ### Ik kan Mollie niet kiezen bij het afrekenen! ### Als je de _Live API key_ gebruikt, en iDEAL is nog niet voor je account geactiveerd, kan de module geen betaalmethode vinden om de bestelling mee af te ronden. De module is dan niet zichtbaar. Je kunt de _test API key_ gebruiken totdat iDEAL voor je account actief is. Het is ook mogelijk dat het bedrag van de bestelling to hoog of te laag is voor de beschikbare betaalmethodes. Het is bijvoorbeeld niet mogelijk om betalingen hoger dan € 50.000 af te rekenen met iDEAL. Als iDEAL geactiveerd is voor uw account en het bedrag klopt ook, controleer dan of de relevante betaalmethodes ingeschakeld staan bij het websiteprofiel in uw Mollie Beheer. ### Moet ik ook een redirect URL of webhook instellen? ### Het is niet nodig een redirect URL of webhook in te stellen. Dat doet de module zelf automatisch bij elke order. # Licentie # [BSD (Berkeley Software Distribution) License](http://www.opensource.org/licenses/bsd-license.php). Copyright © 2015, Mollie B.V. # Ondersteuning # Contact: [www.mollie.com/nl/about](https://www.mollie.com/nl/about) — [email protected] — +31 20-612 88 55 + [Meer informatie over iDEAL via Mollie](https://www.mollie.com/ideal/) + [Meer informatie over Creditcard via Mollie](https://www.mollie.com/creditcard/) + [Meer informatie over Mister Cash via Mollie](https://www.mollie.com/mistercash/) + [Meer informatie over Overboeking via Mollie](https://www.mollie.com/banktransfer/) + [Meer informatie over PayPal via Mollie](https://www.mollie.com/paypal/) + [Meer informatie over paysafecard via Mollie](https://www.mollie.com/paysafecard/)
{ "content_hash": "7e0c1906286c8a94fbd61a819af7df12", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 218, "avg_line_length": 60.35294117647059, "alnum_prop": 0.7840155945419103, "repo_name": "mollie/osCommerce", "id": "ea458c23a6c0b773d593acf307a94193b43fc81d", "size": "5140", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33261", "license": "bsd-2-clause", "language": [ { "name": "PHP", "bytes": "51704" }, { "name": "Shell", "bytes": "96" } ], "symlink_target": "" }
require 'spec_helper' describe MetaTags::ViewHelper, 'displaying charset' do subject { ActionView::Base.new } it 'should not display charset if blank' do expect(subject.display_meta_tags).to eq('') expect(subject.display_meta_tags(charset: '')).to eq('') end it 'should display charset' do subject.display_meta_tags(charset: 'UTF-8').tap do |meta| expect(meta).to eq('<meta charset="UTF-8" />') end end end
{ "content_hash": "58a4e6901611045251feb28484ac85db", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 61, "avg_line_length": 27.625, "alnum_prop": 0.6742081447963801, "repo_name": "JuanitoFatas/meta-tags", "id": "2daae54a8204598241dfd632faa5f7748bb2c582", "size": "442", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "spec/view_helper/charset_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "75613" } ], "symlink_target": "" }
cask :v1 => 'air-connect' do version :latest sha256 :no_check url 'http://downloads.avatron.com/AirConnectInstaller.zip' name 'Air Connect' appcast 'https://avatron.com/updates/software/airconnect_mac/appcast.xml', :sha256 => 'af9bc6dc41bc632995c4e49b958a5623bc091ac0fe1fb337fbc9a571cfc1e85b' homepage 'https://avatron.com/get-air-connect/' license :gratis app 'Air Connect.app' end
{ "content_hash": "205ddee6339815e9379d64cc533321a1", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 87, "avg_line_length": 31.615384615384617, "alnum_prop": 0.7396593673965937, "repo_name": "wizonesolutions/homebrew-cask", "id": "d0a206dad606b19b9cea447053e436589d707c6a", "size": "411", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "Casks/air-connect.rb", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Ruby", "bytes": "1647627" }, { "name": "Shell", "bytes": "57683" } ], "symlink_target": "" }
/*jslint browser: true, devel: true, node: true, ass: true, nomen: true, unparam: true, indent: 4 */ /** * @license * Copyright (c) 2015 The ExpandJS authors. All rights reserved. * This code may only be used under the BSD style license found at https://expandjs.github.io/LICENSE.txt * The complete set of authors may be found at https://expandjs.github.io/AUTHORS.txt * The complete set of contributors may be found at https://expandjs.github.io/CONTRIBUTORS.txt */ (function () { "use strict"; var CustomError = require('../error/CustomError'); /** * Creates a custom error with the `InvalidError` type and a predefined message. * * ```js * console.log(new InvalidError('myVar')); * // => InvalidError{message: 'myVar is not valid', stack: '...'} * ``` * * @function InvalidError * @param {string} key The key to be used in the message * @constructor */ module.exports = function InvalidError(key) { CustomError.call(this, 'InvalidError', key, 'is not valid'); }; }());
{ "content_hash": "dfb9670f134d280b06675d40c3eb1407", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 105, "avg_line_length": 34.41935483870968, "alnum_prop": 0.6438612933458294, "repo_name": "Klaudit/expandjs", "id": "443fa160930dbf9bebd66e8731428d908ae940a2", "size": "1067", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "lib/error/InvalidError.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "731" }, { "name": "JavaScript", "bytes": "1436686" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "e4f83aea5c43a5c10b5ed2992bb7a3ed", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "04c6f712dbf135f9d7baf011f73a88d1e22a21cc", "size": "178", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Erodiophyllum/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
require 'spec_helper_acceptance' describe 'with file recursive purge' do basedir = default.tmpdir('concat') context 'should still create concat file' do pp = <<-EOS file { '#{basedir}/bar': ensure => directory, purge => true, recurse => true, } concat { "foobar": ensure => 'present', path => '#{basedir}/bar/foobar', } concat::fragment { 'foo': target => 'foobar', content => 'foo', } EOS it 'applies the manifest twice with no stderr' do apply_manifest(pp, catch_failures: true) apply_manifest(pp, catch_changes: true) end describe file("#{basedir}/bar/foobar") do it { is_expected.to be_file } its(:content) do is_expected.to match 'foo' end end end end
{ "content_hash": "02324420d3b2922ddfe99ab25ceda2fe", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 53, "avg_line_length": 22.916666666666668, "alnum_prop": 0.5587878787878788, "repo_name": "integratedfordevelopers/integrated-puphpet", "id": "6e84da97e84ef60a2c9d8920b7c5e1a5bddd6bf1", "size": "825", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "puppet/modules/concat/spec/acceptance/concurrency_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "64673" }, { "name": "Groovy", "bytes": "646" }, { "name": "HTML", "bytes": "674135" }, { "name": "JavaScript", "bytes": "26394" }, { "name": "Makefile", "bytes": "649" }, { "name": "Nix", "bytes": "7317" }, { "name": "PLSQL", "bytes": "2279" }, { "name": "Pascal", "bytes": "31969" }, { "name": "Puppet", "bytes": "1588760" }, { "name": "Ruby", "bytes": "4412876" }, { "name": "Shell", "bytes": "236292" }, { "name": "Vim script", "bytes": "10274" } ], "symlink_target": "" }
package com.amazonaws.ant.cloudformation; import org.apache.tools.ant.BuildException; import com.amazonaws.ant.AWSAntTask; import com.amazonaws.services.cloudformation.AmazonCloudFormationClient; import com.amazonaws.services.cloudformation.model.DescribeStacksRequest; public class WaitForStackToReachStateTask extends AWSAntTask { private static final String FAILED = "FAILED"; private String stackName; private String status; /** * Set the name of this stack. Required. * * @param stackName * The stack name */ public void setStackName(String stackName) { this.stackName = stackName; } /** * Set the status to wait for this stack to reach. Should not contain * "FAILED" * * @param status * The status to wait for this stack to reach. */ public void setStatus(String status) { this.status = status; } /** * Waits for the specified stack to reach the specified status. Returns true * if it does, returns false if it reaches a status with "FAILED", or if 30 * minutes pass without reaching the desired status. */ private void checkParams() { boolean areMissingParams = false; StringBuilder errors = new StringBuilder(""); if (stackName == null) { areMissingParams = true; errors.append("Missing parameter: stackName is required \n"); } if (status == null) { areMissingParams = true; errors.append("Missing parameter: stackName is required \n"); } if (areMissingParams) { throw new BuildException(errors.toString()); } } public void execute() { checkParams(); AmazonCloudFormationClient client = getOrCreateClient(AmazonCloudFormationClient.class); if (!waitForCloudFormationStackToReachStatus(client, stackName, status)) { throw new BuildException("The stack update or creation failed"); } } public static boolean waitForCloudFormationStackToReachStatus( AmazonCloudFormationClient client, String stackName, String status) { int count = 0; while (true) { if (count++ == 100) { System.out .println(stackName + " never reached state " + status); return false; } try { Thread.sleep(1000 * 30); } catch (InterruptedException e) { System.out.println(e.getMessage()); return false; } String stackStatus = client .describeStacks( new DescribeStacksRequest() .withStackName(stackName)).getStacks() .get(0).getStackStatus(); if (stackStatus.equals(status)) { return true; } else if (stackStatus.contains(FAILED)) { System.out.println("The process failed with status " + stackStatus); return false; } System.out.println(stackName + " is in status " + stackStatus); } } }
{ "content_hash": "6f6f8945715298c579c7fe76a9071f8d", "timestamp": "", "source": "github", "line_count": 98, "max_line_length": 96, "avg_line_length": 32.98979591836735, "alnum_prop": 0.5842870399010207, "repo_name": "awslabs/aws-ant-tasks", "id": "39fc0bcd88bda04e2c71180a1d156bebd6c7be8a", "size": "3812", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/com/amazonaws/ant/cloudformation/WaitForStackToReachStateTask.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "258846" } ], "symlink_target": "" }