Dataset Preview
Duplicate
The full dataset viewer is not available (click to read why). Only showing a preview of the rows.
The dataset generation failed
Error code:   DatasetGenerationError
Exception:    TypeError
Message:      Couldn't cast array of type
struct<content_hash: string, timestamp: string, source: string, line_count: int64, max_line_length: int64, avg_line_length: double, alnum_prop: double, repo_name: string, id: string, size: string, binary: bool, copies: string, ref: string, path: string, mode: string, license: string, language: list<item: struct<name: string, bytes: string>>, symlink_target: string>
to
{'content_hash': Value(dtype='string', id=None), 'timestamp': Value(dtype='string', id=None), 'source': Value(dtype='string', id=None), 'line_count': Value(dtype='int64', id=None), 'max_line_length': Value(dtype='int64', id=None), 'avg_line_length': Value(dtype='float64', id=None), 'alnum_prop': Value(dtype='float64', id=None), 'repo_name': Value(dtype='string', id=None), 'id': Value(dtype='string', id=None), 'size': Value(dtype='string', id=None), 'binary': Value(dtype='bool', id=None), 'copies': Value(dtype='string', id=None), 'ref': Value(dtype='string', id=None), 'path': Value(dtype='string', id=None), 'mode': Value(dtype='string', id=None), 'license': Value(dtype='string', id=None), 'language': [{'name': Value(dtype='string', id=None), 'bytes': Value(dtype='string', id=None)}]}
Traceback:    Traceback (most recent call last):
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 2011, in _prepare_split_single
                  writer.write_table(table)
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/arrow_writer.py", line 585, in write_table
                  pa_table = table_cast(pa_table, self._schema)
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2302, in table_cast
                  return cast_table_to_schema(table, schema)
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2261, in cast_table_to_schema
                  arrays = [cast_array_to_feature(table[name], feature) for name, feature in features.items()]
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2261, in <listcomp>
                  arrays = [cast_array_to_feature(table[name], feature) for name, feature in features.items()]
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 1802, in wrapper
                  return pa.chunked_array([func(chunk, *args, **kwargs) for chunk in array.chunks])
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 1802, in <listcomp>
                  return pa.chunked_array([func(chunk, *args, **kwargs) for chunk in array.chunks])
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2122, in cast_array_to_feature
                  raise TypeError(f"Couldn't cast array of type\n{_short_str(array.type)}\nto\n{_short_str(feature)}")
              TypeError: Couldn't cast array of type
              struct<content_hash: string, timestamp: string, source: string, line_count: int64, max_line_length: int64, avg_line_length: double, alnum_prop: double, repo_name: string, id: string, size: string, binary: bool, copies: string, ref: string, path: string, mode: string, license: string, language: list<item: struct<name: string, bytes: string>>, symlink_target: string>
              to
              {'content_hash': Value(dtype='string', id=None), 'timestamp': Value(dtype='string', id=None), 'source': Value(dtype='string', id=None), 'line_count': Value(dtype='int64', id=None), 'max_line_length': Value(dtype='int64', id=None), 'avg_line_length': Value(dtype='float64', id=None), 'alnum_prop': Value(dtype='float64', id=None), 'repo_name': Value(dtype='string', id=None), 'id': Value(dtype='string', id=None), 'size': Value(dtype='string', id=None), 'binary': Value(dtype='bool', id=None), 'copies': Value(dtype='string', id=None), 'ref': Value(dtype='string', id=None), 'path': Value(dtype='string', id=None), 'mode': Value(dtype='string', id=None), 'license': Value(dtype='string', id=None), 'language': [{'name': Value(dtype='string', id=None), 'bytes': Value(dtype='string', id=None)}]}
              
              The above exception was the direct cause of the following exception:
              
              Traceback (most recent call last):
                File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1529, in compute_config_parquet_and_info_response
                  parquet_operations = convert_to_parquet(builder)
                File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1154, in convert_to_parquet
                  builder.download_and_prepare(
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1027, in download_and_prepare
                  self._download_and_prepare(
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1122, in _download_and_prepare
                  self._prepare_split(split_generator, **prepare_split_kwargs)
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1882, in _prepare_split
                  for job_id, done, content in self._prepare_split_single(
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 2038, in _prepare_split_single
                  raise DatasetGenerationError("An error occurred while generating the dataset") from e
              datasets.exceptions.DatasetGenerationError: An error occurred while generating the dataset

Need help to make the dataset viewer work? Make sure to review how to configure the dataset viewer, and open a discussion for direct support.

text
string
meta
dict
%TestCase Class defining interface for test cases % The TestCase class defines an individual test case. % % Normally a test writer will create their own test class that is a subclass % of TestCase. Each instance of the TestCase subclass that gets created will % be associated with a single test method. % % If a test fixture is needed, override the setUp() and tearDown() methods. % % TestSuite(subclass_name), where subclass_name is the name of a TestCase % subclass, creates a test suite containing one TestCase instance per test % method contained in the subclass. % % A simpler test-writing alternative to use subfunction-based M-file tests. % See the MATLAB xUnit documentation. % % TestCase methods: % TestCase - Constructor % run - Execute the test case % % TestCase properties: % Location - Location of M-file containing the test case % Name - Name of test case % % See also TestComponent, TestSuite % Steven L. Eddins % Copyright 2008-2010 The MathWorks, Inc. classdef TestCase < TestComponent properties MethodName end methods function self = TestCase(testMethod) %TestCase Constructor % TestCase(methodName) constructs a TestCase object using the % specified testMethod (a string). self.MethodName = testMethod; self.Name = testMethod; self.Location = which(class(self)); end function did_pass = run(self, monitor) %run Execute the test case % test_case.run(monitor) calls the TestCase object's setUp() % method, then the test method, then the tearDown() method. % observer is a TestRunObserver object. The testStarted(), % testFailure(), testError(), and testFinished() methods of % observer are called at the appropriate times. monitor is a % TestRunMonitor object. Typically it is either a TestRunLogger % subclass or a CommandWindowTestRunDisplay subclass. % % test_case.run() automatically uses a % CommandWindowTestRunDisplay object in order to print test % suite execution information to the Command Window. if nargin < 2 monitor = CommandWindowTestRunDisplay(); end did_pass = true; monitor.testComponentStarted(self); try self.setUp(); f = str2func(self.MethodName); try % Call the test method. f(self); catch failureException monitor.testCaseFailure(self, failureException); did_pass = false; end self.tearDown(); catch errorException monitor.testCaseError(self, errorException); did_pass = false; end monitor.testComponentFinished(self, did_pass); end function num = numTestCases(self) num = 1; end function print(self, numLeadingBlanks) if nargin < 2 numLeadingBlanks = 0; end fprintf('%s%s\n', blanks(numLeadingBlanks), self.Name); end end end
{ "content_hash": "720a7a1a6058b6c895b25b2330dc2593", "timestamp": "", "source": "github", "line_count": 103, "max_line_length": 79, "avg_line_length": 34.22330097087379, "alnum_prop": 0.5665248226950355, "repo_name": "wittawatj/k2abc", "id": "8b09ff87598e9677e563880849b163ea9c8e6b52", "size": "3525", "binary": false, "copies": "18", "ref": "refs/heads/master", "path": "code/thirdpartycode/xunit/TestCase.m", "mode": "33261", "license": "mit", "language": [ { "name": "Matlab", "bytes": "321491" } ] }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>tlc: 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.13.0 / tlc - 20181116</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> tlc <small> 20181116 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-04-05 07:15:45 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-04-05 07:15:45 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 4 Virtual package relying on a GMP lib system installation coq 8.13.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.3 A library manager for OCaml zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; synopsis: &quot;A general-purpose alternative to Coq&#39;s standard library&quot; maintainer: &quot;francois.pottier@inria.fr&quot; authors: [ &quot;Arthur Charguéraud &lt;arthur.chargueraud@inria.fr&gt;&quot; ] homepage: &quot;https://github.com/charguer/tlc&quot; dev-repo: &quot;git+https://github.com/charguer/tlc.git&quot; bug-reports: &quot;https://github.com/charguer/tlc/issues&quot; license: &quot;CeCILL-B&quot; build: [ [make &quot;-j%{jobs}%&quot;] ] install: [ [make &quot;install&quot;] ] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.6&quot; &amp; &lt; &quot;8.11&quot;} ] url { src: &quot;https://github.com/charguer/tlc/archive/20181116.tar.gz&quot; checksum: &quot;md5=fb787df96d77da6ca63c760a5e34ca89&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-tlc.20181116 coq.8.13.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.13.0). The following dependencies couldn&#39;t be met: - coq-tlc -&gt; coq &lt; 8.11 -&gt; ocaml &lt; 4.10 base of this switch (use `--unlock-base&#39; to force) No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-tlc.20181116</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": "a88d49539a1b72d99476cd7a28bc7034", "timestamp": "", "source": "github", "line_count": 164, "max_line_length": 159, "avg_line_length": 39.609756097560975, "alnum_prop": 0.5281711822660099, "repo_name": "coq-bench/coq-bench.github.io", "id": "69c4fe71d76397f90f891834165b31578bfa14c4", "size": "6522", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.10.2-2.0.6/released/8.13.0/tlc/20181116.html", "mode": "33188", "license": "mit", "language": [] }
#ifndef FUSION_TUPLE_FORWARD_14122014_0051 #define FUSION_TUPLE_FORWARD_14122014_0051 #include <boost/config.hpp> #include <boost/fusion/support/config.hpp> #include <boost/fusion/container/vector/detail/config.hpp> #if !defined(BOOST_FUSION_HAS_VARIADIC_VECTOR) \ || (defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES)) # if defined(BOOST_FUSION_HAS_VARIADIC_TUPLE) # undef BOOST_FUSION_HAS_VARIADIC_TUPLE # endif #else # if !defined(BOOST_FUSION_HAS_VARIADIC_TUPLE) # define BOOST_FUSION_HAS_VARIADIC_TUPLE # endif #endif /////////////////////////////////////////////////////////////////////////////// // With no variadics, we will use the C++03 version /////////////////////////////////////////////////////////////////////////////// #if !defined(BOOST_FUSION_HAS_VARIADIC_TUPLE) # include <boost/fusion/tuple/detail/tuple_fwd.hpp> #else /////////////////////////////////////////////////////////////////////////////// // C++11 interface /////////////////////////////////////////////////////////////////////////////// namespace boost { namespace fusion { template <typename ...T> struct tuple; }} #endif #endif
{ "content_hash": "1dfe564460a7670abd979490165d37d2", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 79, "avg_line_length": 31.31578947368421, "alnum_prop": 0.5176470588235295, "repo_name": "alex-friedl/crossplatform-push-notifications-example", "id": "b8d930150cb46b6c8b947abfeec9ba4a0e238cbc", "size": "1555", "binary": false, "copies": "12", "ref": "refs/heads/master", "path": "app/third-party/boost_1_63_0/boost/fusion/tuple/tuple_fwd.hpp", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "2072" }, { "name": "JavaScript", "bytes": "8507" }, { "name": "Objective-C", "bytes": "6603" }, { "name": "Python", "bytes": "1766" }, { "name": "Ruby", "bytes": "2510" } ] }
package org.vertexium.cypher.executionPlan; import org.vertexium.cypher.VertexiumCypherQueryContext; import org.vertexium.cypher.VertexiumCypherResult; public class MatchExecutionStep extends ExecutionStepWithChildren { public MatchExecutionStep(PatternPartExecutionStep[] childSteps, WhereExecutionStep whereStep) { super(toChildSteps(childSteps, whereStep)); } private static ExecutionStep[] toChildSteps(PatternPartExecutionStep[] childSteps, WhereExecutionStep whereStep) { int length = childSteps.length + (whereStep == null ? 0 : 1); ExecutionStep[] results = new ExecutionStep[length]; System.arraycopy(childSteps, 0, results, 0, childSteps.length); if (whereStep != null) { results[results.length - 1] = whereStep; } return results; } @Override public VertexiumCypherResult execute(VertexiumCypherQueryContext ctx, VertexiumCypherResult source) { return super.execute(ctx, source); } @Override public String toString() { return String.format("%s", super.toString()); } }
{ "content_hash": "9745d753a91f0be05ec79a1945680b63", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 118, "avg_line_length": 36.93333333333333, "alnum_prop": 0.7138989169675091, "repo_name": "visallo/vertexium", "id": "1812939b437952d46165d645719b90da0cc24ded", "size": "1108", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "cypher/src/main/java/org/vertexium/cypher/executionPlan/MatchExecutionStep.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "31058" }, { "name": "Dockerfile", "bytes": "448" }, { "name": "Gherkin", "bytes": "747158" }, { "name": "Java", "bytes": "4006071" }, { "name": "Shell", "bytes": "346" }, { "name": "XSLT", "bytes": "726" } ] }
import * as React from 'react'; import { Route } from 'react-router-dom'; import App from 'src/web/App'; import Home from 'src/web/pages/Home'; import NewProfile from 'src/web/pages/NewProfile'; import Profile from 'src/web/pages/Profile'; export default ( <App> <Route path="/" exact component={Home} /> <Route path="/new-profile" component={NewProfile} /> <Route path="/profiles/:profileId" component={Profile} /> </App> );
{ "content_hash": "3ff26675eca467be79a586cff7707308", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 61, "avg_line_length": 29.6, "alnum_prop": 0.6846846846846847, "repo_name": "bsidelinger912/rounder", "id": "411f0be9b1594cce0d9ad032ae6464f11a0219d8", "size": "444", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/web/routes.tsx", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "35677" }, { "name": "HTML", "bytes": "48745" }, { "name": "JavaScript", "bytes": "40981" }, { "name": "TypeScript", "bytes": "60017" } ] }
package src import ( "encoding/json" "strings" ) // FlatFileListRequest struct client for FlatFileList Request type FlatFileListRequest struct { client *Client HTTPRequest *HTTPRequest } // FlatFileListRequestOptions struct - options for request type FlatFileListRequestOptions struct { MediaType []MediaType Limit *uint32 Offset *uint32 Fields []string PreviewSize *PreviewSize PreviewCrop *bool } // Request get request func (req *FlatFileListRequest) Request() *HTTPRequest { return req.HTTPRequest } // NewFlatFileListRequest create new FlatFileList Request func (c *Client) NewFlatFileListRequest(options ...FlatFileListRequestOptions) *FlatFileListRequest { var parameters = make(map[string]interface{}) if len(options) > 0 { opt := options[0] if opt.Limit != nil { parameters["limit"] = *opt.Limit } if opt.Offset != nil { parameters["offset"] = *opt.Offset } if opt.Fields != nil { parameters["fields"] = strings.Join(opt.Fields, ",") } if opt.PreviewSize != nil { parameters["preview_size"] = opt.PreviewSize.String() } if opt.PreviewCrop != nil { parameters["preview_crop"] = *opt.PreviewCrop } if opt.MediaType != nil { var strMediaTypes = make([]string, len(opt.MediaType)) for i, t := range opt.MediaType { strMediaTypes[i] = t.String() } parameters["media_type"] = strings.Join(strMediaTypes, ",") } } return &FlatFileListRequest{ client: c, HTTPRequest: createGetRequest(c, "/resources/files", parameters), } } // Exec run FlatFileList Request func (req *FlatFileListRequest) Exec() (*FilesResourceListResponse, error) { data, err := req.Request().run(req.client) if err != nil { return nil, err } var info FilesResourceListResponse err = json.Unmarshal(data, &info) if err != nil { return nil, err } if cap(info.Items) == 0 { info.Items = []ResourceInfoResponse{} } return &info, nil }
{ "content_hash": "57322e0bb108e0dc770d5453bd89c54a", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 101, "avg_line_length": 24.73076923076923, "alnum_prop": 0.6925868325557284, "repo_name": "kynikos/rclone", "id": "ce047fa3e4f7b5269f0cb9959a1627686ad7b6ee", "size": "1929", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "yandex/api/flat_file_list_request.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "1006944" }, { "name": "HTML", "bytes": "224067" }, { "name": "Makefile", "bytes": "3756" }, { "name": "Python", "bytes": "3571" }, { "name": "Roff", "bytes": "193217" }, { "name": "Shell", "bytes": "2305" } ] }
<?php namespace R2Ecommerce\Entity\Repository; class ProductCart extends EntityRepository { }
{ "content_hash": "1f88532a9a69ba271acbfa75497101d8", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 44, "avg_line_length": 15.833333333333334, "alnum_prop": 0.8210526315789474, "repo_name": "mediaforce/ecomart", "id": "e5fe60ad95e2b58252dd6f953b13e79259b59218", "size": "95", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "module/R2Ecommerce/src/R2Ecommerce/Entity/Repository/ProductCart.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "748" }, { "name": "Batchfile", "bytes": "107" }, { "name": "CSS", "bytes": "474774" }, { "name": "HTML", "bytes": "829682" }, { "name": "JavaScript", "bytes": "3961488" }, { "name": "PHP", "bytes": "592669" }, { "name": "Ruby", "bytes": "941" } ] }
SYNONYM #### According to Index Fungorum #### Published in null #### Original name Phellodon excentrici-mexicana R.E. Baird ### Remarks null
{ "content_hash": "24570b2825f3185600c3c6400410f0bc", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 40, "avg_line_length": 11.076923076923077, "alnum_prop": 0.7152777777777778, "repo_name": "mdoering/backbone", "id": "832b4d69c86eb4cb7f7bf628a3675f68e1631ef4", "size": "208", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Basidiomycota/Agaricomycetes/Thelephorales/Bankeraceae/Phellodon/Phellodon excentri-mexicanus/ Syn. Phellodon excentrici-mexicana/README.md", "mode": "33188", "license": "apache-2.0", "language": [] }
<?php namespace FL\GmailBundle\Model\Collection; use FL\GmailBundle\Model\GmailUserInterface; /** * Abstraction of a Google Apps Domain: * It consists of a string, for the account's domain * and a list of GmailUsers. * * This class is not meant to be persisted. */ class GmailDomain { /** * @var \SplObjectStorage */ private $gmailUsers; /** * @var string */ private $domain; /** * LabelCollection constructor. * * @param string */ public function __construct(string $domain) { $this->domain = $domain; $this->gmailUsers = new \SplObjectStorage(); } /** * @param GmailUserInterface $user * * @return GmailDomain */ public function addGmailUser(GmailUserInterface $user): self { $this->gmailUsers->attach($user); return $this; } /** * @param GmailUserInterface $user * * @return GmailDomain */ public function removeGmailUser(GmailUserInterface $user): self { $this->gmailUsers->detach($user); return $this; } /** * @return \SplObjectStorage */ public function getGmailUsers(): \SplObjectStorage { return $this->gmailUsers; } /** * @param string $userId * * @return GmailUserInterface|null */ public function findGmailUserById(string $userId) { foreach ($this->gmailUsers as $user) { /** @var GmailUserInterface $user */ if ($user->getUserId() === $userId) { return $user; } } return; } /** * @param string $primaryEmailAddress * * @return GmailUserInterface|null */ public function findGmailUserByPrimaryEmail(string $primaryEmailAddress) { /** @var GmailUserInterface $user */ foreach ($this->gmailUsers as $user) { if ($user->getPrimaryEmailAddress() === $primaryEmailAddress) { return $user; } } return; } /** * @param string $emailAliasAddress * * @return GmailUserInterface|null */ public function findGmailUserByEmailAlias(string $emailAliasAddress) { /** @var GmailUserInterface $user */ foreach ($this->gmailUsers as $user) { foreach ($user->getEmailAliases() as $emailAlias) { if ($emailAlias === $emailAliasAddress) { return $user; } } } return; } /** * @param string $primaryOrAliasAddress * * @return GmailUserInterface|null */ public function findGmailUserByEmail(string $primaryOrAliasAddress) { /** @var GmailUserInterface $user */ foreach ($this->gmailUsers as $user) { foreach ($user->getAllEmailAddresses() as $emailAddress) { if ($emailAddress === $primaryOrAliasAddress) { return $user; } } } return; } /** * @return string */ public function getDomain(): string { return $this->domain; } }
{ "content_hash": "9885dcbdb71abcfa8cb989067c235b87", "timestamp": "", "source": "github", "line_count": 148, "max_line_length": 76, "avg_line_length": 21.64864864864865, "alnum_prop": 0.5424469413233458, "repo_name": "fourlabsldn/GmailBundle", "id": "b59e50bdb715412ed57dc807c28b7193479a7eec", "size": "3204", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Model/Collection/GmailDomain.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "96134" } ] }
package com.dli.repositories; import com.dli.entities.Demo; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import java.util.Date; import java.util.List; @Mapper public interface CollectRepo { void addCollection(@Param("userid") int userid, @Param("item_type")String item_type, @Param("item_id")int item_id); void cancelCollection(@Param("userid") int userid, @Param("item_type")String item_type, @Param("item_id")int item_id); int countCollection( @Param("itemtype") String itemtype ,@Param("itemid") int itemid, @Param("userid")int userid); int countAllCollection(@Param("itemtype") String itemtype ,@Param("itemid") int itemid ); }
{ "content_hash": "3935a4ce3a2bf268686fcb8598c28c67", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 124, "avg_line_length": 30.956521739130434, "alnum_prop": 0.7247191011235955, "repo_name": "smile-org/smile", "id": "ef0f948a75d283be6f440a18caa388d1d2e3452f", "size": "712", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "backend/src/main/java/com/dli/repositories/CollectRepo.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "138760" }, { "name": "HTML", "bytes": "480345" }, { "name": "Java", "bytes": "590298" }, { "name": "JavaScript", "bytes": "123729" }, { "name": "Vue", "bytes": "999535" } ] }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_29) on Mon Nov 26 17:21:38 MSK 2012 --> <TITLE> org.apache.poi.poifs.storage (POI API Documentation) </TITLE> <META NAME="date" CONTENT="2012-11-26"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> </HEAD> <BODY BGCOLOR="white"> <FONT size="+1" CLASS="FrameTitleFont"> <A HREF="../../../../../org/apache/poi/poifs/storage/package-summary.html" target="classFrame">org.apache.poi.poifs.storage</A></FONT> <TABLE BORDER="0" WIDTH="100%" SUMMARY=""> <TR> <TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont"> Interfaces</FONT>&nbsp; <FONT CLASS="FrameItemFont"> <BR> <A HREF="BlockList.html" title="interface in org.apache.poi.poifs.storage" target="classFrame"><I>BlockList</I></A> <BR> <A HREF="BlockWritable.html" title="interface in org.apache.poi.poifs.storage" target="classFrame"><I>BlockWritable</I></A> <BR> <A HREF="HeaderBlockConstants.html" title="interface in org.apache.poi.poifs.storage" target="classFrame"><I>HeaderBlockConstants</I></A> <BR> <A HREF="ListManagedBlock.html" title="interface in org.apache.poi.poifs.storage" target="classFrame"><I>ListManagedBlock</I></A></FONT></TD> </TR> </TABLE> <TABLE BORDER="0" WIDTH="100%" SUMMARY=""> <TR> <TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont"> Classes</FONT>&nbsp; <FONT CLASS="FrameItemFont"> <BR> <A HREF="BATBlock.html" title="class in org.apache.poi.poifs.storage" target="classFrame">BATBlock</A> <BR> <A HREF="BATBlock.BATBlockAndIndex.html" title="class in org.apache.poi.poifs.storage" target="classFrame">BATBlock.BATBlockAndIndex</A> <BR> <A HREF="BlockAllocationTableReader.html" title="class in org.apache.poi.poifs.storage" target="classFrame">BlockAllocationTableReader</A> <BR> <A HREF="BlockAllocationTableWriter.html" title="class in org.apache.poi.poifs.storage" target="classFrame">BlockAllocationTableWriter</A> <BR> <A HREF="DataInputBlock.html" title="class in org.apache.poi.poifs.storage" target="classFrame">DataInputBlock</A> <BR> <A HREF="DocumentBlock.html" title="class in org.apache.poi.poifs.storage" target="classFrame">DocumentBlock</A> <BR> <A HREF="HeaderBlock.html" title="class in org.apache.poi.poifs.storage" target="classFrame">HeaderBlock</A> <BR> <A HREF="HeaderBlockWriter.html" title="class in org.apache.poi.poifs.storage" target="classFrame">HeaderBlockWriter</A> <BR> <A HREF="PropertyBlock.html" title="class in org.apache.poi.poifs.storage" target="classFrame">PropertyBlock</A> <BR> <A HREF="RawDataBlock.html" title="class in org.apache.poi.poifs.storage" target="classFrame">RawDataBlock</A> <BR> <A HREF="RawDataBlockList.html" title="class in org.apache.poi.poifs.storage" target="classFrame">RawDataBlockList</A> <BR> <A HREF="SmallBlockTableReader.html" title="class in org.apache.poi.poifs.storage" target="classFrame">SmallBlockTableReader</A> <BR> <A HREF="SmallBlockTableWriter.html" title="class in org.apache.poi.poifs.storage" target="classFrame">SmallBlockTableWriter</A> <BR> <A HREF="SmallDocumentBlock.html" title="class in org.apache.poi.poifs.storage" target="classFrame">SmallDocumentBlock</A> <BR> <A HREF="SmallDocumentBlockList.html" title="class in org.apache.poi.poifs.storage" target="classFrame">SmallDocumentBlockList</A></FONT></TD> </TR> </TABLE> </BODY> </HTML>
{ "content_hash": "a39cde5523d399de58cfa71f42844a70", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 142, "avg_line_length": 45.63636363636363, "alnum_prop": 0.721969265793967, "repo_name": "HRKN2245/CameraSunmoku", "id": "7a62c358dcf6d8d2f7c6c68cfebcac4ac1720168", "size": "3514", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ExtractSample/poi-3.9/docs/apidocs/org/apache/poi/poifs/storage/package-frame.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "16091" }, { "name": "Java", "bytes": "126912" } ] }
package club.zhcs.hammer.chain; import java.util.ArrayList; import java.util.List; import org.apache.shiro.authz.aop.AuthorizingAnnotationMethodInterceptor; import org.nutz.integration.shiro.NutShiroProcessor; import org.nutz.lang.ContinueLoop; import org.nutz.lang.Each; import org.nutz.lang.ExitLoop; import org.nutz.lang.Lang; import org.nutz.lang.LoopException; import org.nutz.log.Log; import org.nutz.log.Logs; import org.nutz.mvc.ActionChain; import org.nutz.mvc.ActionInfo; import org.nutz.mvc.NutConfig; import org.nutz.mvc.Processor; import org.nutz.mvc.impl.NutActionChain; import org.nutz.mvc.impl.processor.ActionFiltersProcessor; import club.zhcs.hammer.ext.shiro.anno.ThunderRequiresPermissions; import club.zhcs.hammer.ext.shiro.anno.ThunderRequiresRoles; import club.zhcs.hammer.ext.shiro.aop.ThunderPermissionAnnotationMethodInterceptor; import club.zhcs.hammer.ext.shiro.aop.ThunderRoleAnnotationMethodInterceptor; import club.zhcs.titans.nutz.chain.KerboresActionChainMaker; import club.zhcs.titans.nutz.processor.CSRFProtectPostProcessor; import club.zhcs.titans.nutz.processor.CSRFProtectPreProcessor; import club.zhcs.titans.nutz.processor.KerboresFailProcessor; import club.zhcs.titans.nutz.processor.XSSProtectProcessor; public class ThunderChainMaker extends KerboresActionChainMaker { private Log log = Logs.get(); @Override public ActionChain eval(final NutConfig config, final ActionInfo ai) { List<Processor> list = normalList(); List<AuthorizingAnnotationMethodInterceptor> interceptors = new ArrayList<AuthorizingAnnotationMethodInterceptor>(); interceptors.add(new ThunderPermissionAnnotationMethodInterceptor()); interceptors.add(new ThunderRoleAnnotationMethodInterceptor()); addBefore(list, ActionFiltersProcessor.class, new NutShiroProcessor(interceptors, ThunderRequiresPermissions.class, ThunderRequiresRoles.class)); addBefore(list, ActionFiltersProcessor.class, new XSSProtectProcessor()); addBefore(list, ActionFiltersProcessor.class, new CSRFProtectPreProcessor()); addBefore(list, ActionFiltersProcessor.class, new CSRFProtectPostProcessor()); Processor error = new KerboresFailProcessor(); Lang.each(list, new Each<Processor>() { @Override public void invoke(int paramInt1, Processor processor, int paramInt2) throws ExitLoop, ContinueLoop, LoopException { try { processor.init(config, ai); } catch (Throwable e) { log.error(e); } } }); try { error.init(config, ai); } catch (Throwable e) { e.printStackTrace(); } return new NutActionChain(list, error, ai); } }
{ "content_hash": "9273f19891c4018159a22bd9e3070fdf", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 147, "avg_line_length": 38, "alnum_prop": 0.781578947368421, "repo_name": "ZHCS-CLUB/Hammer", "id": "a3c3bb6b834e2c2535d2a0085ecdc57bcb20d2d7", "size": "2896", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Hammer-rest/src/main/java/club/zhcs/hammer/chain/ThunderChainMaker.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "8198" }, { "name": "HTML", "bytes": "508" }, { "name": "Java", "bytes": "109431" }, { "name": "JavaScript", "bytes": "28516" }, { "name": "Vue", "bytes": "139149" } ] }
import fnmatch import imp import logging import modulefinder import optparse import os import sys import zipfile from telemetry import benchmark from telemetry.core import command_line from telemetry.core import discover from telemetry.util import bootstrap from telemetry.util import cloud_storage from telemetry.util import path from telemetry.util import path_set DEPS_FILE = 'bootstrap_deps' def FindBootstrapDependencies(base_dir): deps_file = os.path.join(base_dir, DEPS_FILE) if not os.path.exists(deps_file): return [] deps_paths = bootstrap.ListAllDepsPaths(deps_file) return set(os.path.realpath(os.path.join( path.GetChromiumSrcDir(), os.pardir, deps_path)) for deps_path in deps_paths) def FindPythonDependencies(module_path): logging.info('Finding Python dependencies of %s' % module_path) # Load the module to inherit its sys.path modifications. imp.load_source( os.path.splitext(os.path.basename(module_path))[0], module_path) # Analyze the module for its imports. finder = modulefinder.ModuleFinder() finder.run_script(module_path) # Filter for only imports in Chromium. for module in finder.modules.itervalues(): # If it's an __init__.py, module.__path__ gives the package's folder. module_path = module.__path__[0] if module.__path__ else module.__file__ if not module_path: continue module_path = os.path.realpath(module_path) if not path.IsSubpath(module_path, path.GetChromiumSrcDir()): continue yield module_path def FindPageSetDependencies(base_dir): logging.info('Finding page sets in %s' % base_dir) # Add base_dir to path so our imports relative to base_dir will work. sys.path.append(base_dir) tests = discover.DiscoverClasses(base_dir, base_dir, benchmark.Benchmark, index_by_class_name=True) for test_class in tests.itervalues(): test_obj = test_class() # Ensure the test's default options are set if needed. parser = optparse.OptionParser() test_obj.AddCommandLineArgs(parser, None) options = optparse.Values() for k, v in parser.get_default_values().__dict__.iteritems(): options.ensure_value(k, v) # Page set paths are relative to their runner script, not relative to us. path.GetBaseDir = lambda: base_dir # TODO: Loading the page set will automatically download its Cloud Storage # deps. This is really expensive, and we don't want to do this by default. page_set = test_obj.CreatePageSet(options) # Add all of its serving_dirs as dependencies. for serving_dir in page_set.serving_dirs: yield serving_dir def FindExcludedFiles(files, options): # Define some filters for files. def IsHidden(path_string): for pathname_component in path_string.split(os.sep): if pathname_component.startswith('.'): return True return False def IsPyc(path_string): return os.path.splitext(path_string)[1] == '.pyc' def IsInCloudStorage(path_string): return os.path.exists(path_string + '.sha1') def MatchesExcludeOptions(path_string): for pattern in options.exclude: if (fnmatch.fnmatch(path_string, pattern) or fnmatch.fnmatch(os.path.basename(path_string), pattern)): return True return False # Collect filters we're going to use to exclude files. exclude_conditions = [ IsHidden, IsPyc, IsInCloudStorage, MatchesExcludeOptions, ] # Check all the files against the filters. for file_path in files: if any(condition(file_path) for condition in exclude_conditions): yield file_path def FindDependencies(target_paths, options): # Verify arguments. for target_path in target_paths: if not os.path.exists(target_path): raise ValueError('Path does not exist: %s' % target_path) dependencies = path_set.PathSet() # Including __init__.py will include Telemetry and its dependencies. # If the user doesn't pass any arguments, we just have Telemetry. dependencies |= FindPythonDependencies(os.path.realpath( os.path.join(path.GetTelemetryDir(), 'telemetry', '__init__.py'))) dependencies |= FindBootstrapDependencies(path.GetTelemetryDir()) # Add dependencies. for target_path in target_paths: base_dir = os.path.dirname(os.path.realpath(target_path)) dependencies.add(base_dir) dependencies |= FindBootstrapDependencies(base_dir) dependencies |= FindPythonDependencies(target_path) if options.include_page_set_data: dependencies |= FindPageSetDependencies(base_dir) # Remove excluded files. dependencies -= FindExcludedFiles(set(dependencies), options) return dependencies def ZipDependencies(target_paths, dependencies, options): base_dir = os.path.dirname(os.path.realpath(path.GetChromiumSrcDir())) with zipfile.ZipFile(options.zip, 'w', zipfile.ZIP_DEFLATED) as zip_file: # Add dependencies to archive. for dependency_path in dependencies: path_in_archive = os.path.join( 'telemetry', os.path.relpath(dependency_path, base_dir)) zip_file.write(dependency_path, path_in_archive) # Add symlinks to executable paths, for ease of use. for target_path in target_paths: link_info = zipfile.ZipInfo( os.path.join('telemetry', os.path.basename(target_path))) link_info.create_system = 3 # Unix attributes. # 010 is regular file, 0111 is the permission bits rwxrwxrwx. link_info.external_attr = 0100777 << 16 # Octal. relative_path = os.path.relpath(target_path, base_dir) link_script = ( '#!/usr/bin/env python\n\n' 'import os\n' 'import sys\n\n\n' 'script = os.path.join(os.path.dirname(__file__), \'%s\')\n' 'os.execv(sys.executable, [sys.executable, script] + sys.argv[1:])' % relative_path) zip_file.writestr(link_info, link_script) # Add gsutil to the archive, if it's available. The gsutil in # depot_tools is modified to allow authentication using prodaccess. # TODO: If there's a gsutil in telemetry/third_party/, bootstrap_deps # will include it. Then there will be two copies of gsutil at the same # location in the archive. This can be confusing for users. gsutil_path = os.path.realpath(cloud_storage.FindGsutil()) if cloud_storage.SupportsProdaccess(gsutil_path): gsutil_base_dir = os.path.join(os.path.dirname(gsutil_path), os.pardir) gsutil_dependencies = path_set.PathSet() gsutil_dependencies.add(os.path.dirname(gsutil_path)) # Also add modules from depot_tools that are needed by gsutil. gsutil_dependencies.add(os.path.join(gsutil_base_dir, 'boto')) gsutil_dependencies.add(os.path.join(gsutil_base_dir, 'fancy_urllib')) gsutil_dependencies.add(os.path.join(gsutil_base_dir, 'retry_decorator')) gsutil_dependencies -= FindExcludedFiles( set(gsutil_dependencies), options) # Also add upload.py to the archive from depot_tools, if it is available. # This allows us to post patches without requiring a full depot_tools # install. There's no real point in including upload.py if we do not # also have gsutil, which is why this is inside the gsutil block. gsutil_dependencies.add(os.path.join(gsutil_base_dir, 'upload.py')) for dependency_path in gsutil_dependencies: path_in_archive = os.path.join( 'telemetry', os.path.relpath(path.GetTelemetryDir(), base_dir), 'third_party', os.path.relpath(dependency_path, gsutil_base_dir)) zip_file.write(dependency_path, path_in_archive) class FindDependenciesCommand(command_line.OptparseCommand): """Prints all dependencies""" @classmethod def AddCommandLineArgs(cls, parser, _): parser.add_option( '-v', '--verbose', action='count', dest='verbosity', help='Increase verbosity level (repeat as needed).') parser.add_option( '-p', '--include-page-set-data', action='store_true', default=False, help='Scan tests for page set data and include them.') parser.add_option( '-e', '--exclude', action='append', default=[], help='Exclude paths matching EXCLUDE. Can be used multiple times.') parser.add_option( '-z', '--zip', help='Store files in a zip archive at ZIP.') @classmethod def ProcessCommandLineArgs(cls, parser, args, _): if args.verbosity >= 2: logging.getLogger().setLevel(logging.DEBUG) elif args.verbosity: logging.getLogger().setLevel(logging.INFO) else: logging.getLogger().setLevel(logging.WARNING) def Run(self, args): target_paths = args.positional_args dependencies = FindDependencies(target_paths, args) if args.zip: ZipDependencies(target_paths, dependencies, args) print 'Zip archive written to %s.' % args.zip else: print '\n'.join(sorted(dependencies)) return 0
{ "content_hash": "200e778ee3e0001de3d3ef98bc121e87", "timestamp": "", "source": "github", "line_count": 244, "max_line_length": 79, "avg_line_length": 36.618852459016395, "alnum_prop": 0.6930050363738108, "repo_name": "mou4e/zirconium", "id": "b3dffb1eb8e82ed658aad9f5693274598a6875f5", "size": "9098", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "tools/telemetry/telemetry/util/find_dependencies.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "AppleScript", "bytes": "6973" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "23829" }, { "name": "C", "bytes": "4115478" }, { "name": "C++", "bytes": "233013312" }, { "name": "CSS", "bytes": "931463" }, { "name": "Emacs Lisp", "bytes": "988" }, { "name": "HTML", "bytes": "28131619" }, { "name": "Java", "bytes": "9810569" }, { "name": "JavaScript", "bytes": "19670133" }, { "name": "Makefile", "bytes": "68017" }, { "name": "Objective-C", "bytes": "1475873" }, { "name": "Objective-C++", "bytes": "8640851" }, { "name": "PHP", "bytes": "97817" }, { "name": "PLpgSQL", "bytes": "171186" }, { "name": "Perl", "bytes": "63937" }, { "name": "Protocol Buffer", "bytes": "456460" }, { "name": "Python", "bytes": "7958623" }, { "name": "Shell", "bytes": "477153" }, { "name": "Standard ML", "bytes": "4965" }, { "name": "XSLT", "bytes": "418" }, { "name": "nesC", "bytes": "18347" } ] }
CREATE TABLE conquest_warrior_transformation ( transformed_warrior_rank_id INTEGER NOT NULL, is_automatic BIT NOT NULL, required_link INTEGER, completed_episode_id INTEGER, current_episode_id INTEGER, distant_warrior_id INTEGER, female_warlord_count INTEGER, pokemon_count INTEGER, collection_type_id INTEGER, warrior_count INTEGER, CONSTRAINT pk_conquest_warrior_transformation_transformed_warrior_rank_id PRIMARY KEY (transformed_warrior_rank_id), CONSTRAINT fk_conquest_warrior_transformation_conquest_warrior_ranks FOREIGN KEY(transformed_warrior_rank_id) REFERENCES conquest_warrior_ranks (id), CONSTRAINT ck_conquest_warrior_transformation_is_automatic CHECK (is_automatic IN (0, 1)), CONSTRAINT fk_conquest_warrior_transformation_conquest_episodes FOREIGN KEY(completed_episode_id) REFERENCES conquest_episodes (id), FOREIGN KEY(current_episode_id) REFERENCES conquest_episodes (id), CONSTRAINT fk_conquest_warrior_transformation_conquest_warriors FOREIGN KEY(distant_warrior_id) REFERENCES conquest_warriors (id), CONSTRAINT fk_conquest_warrior_transformation_pkmn_types FOREIGN KEY(collection_type_id) REFERENCES pkmn_types (id) );
{ "content_hash": "0d24c4c359ef484578a9b6e632d29ceb", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 151, "avg_line_length": 61.78947368421053, "alnum_prop": 0.807495741056218, "repo_name": "RichiePhoebix/SSDT.Pokedex", "id": "840423cf8e8bbddf670054599d0346c87e3cf8d6", "size": "1176", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SSDT.Pokedex/SSDT.Pokedex/dbo/Tables/conquest_warrior_transformation.sql", "mode": "33188", "license": "mit", "language": [] }
Countries and states in json.
{ "content_hash": "a5b159639cc3c7e52b3dab95443b7d2b", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 29, "avg_line_length": 30, "alnum_prop": 0.8, "repo_name": "orestisioakeimidis/countries-states-json", "id": "d585108bdd93746e402122a6fa1ddb19974fc35f", "size": "57", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "TypeScript", "bytes": "13696" } ] }
/** * @file * @brief Definitions for the IP router. * @details no cache routing. * * @date 16.11.09 * @author Nikolay Korotky */ #ifndef NET_L3_ROUTE_H_ #define NET_L3_ROUTE_H_ #include <stdint.h> #include <net/skbuff.h> #include <net/l3/ipv4/ip.h> #include <stddef.h> #include <net/netdevice.h> struct net_device; /** * Routing table entry. */ typedef struct rt_entry { struct net_device *dev; in_addr_t rt_dst; uint32_t rt_flags; in_addr_t rt_mask; in_addr_t rt_gateway; } rt_entry_t; /**< Flags */ #define RTF_UP 0x0001 /* route usable */ #define RTF_GATEWAY 0x0002 /* destination is a gateway */ #if 0 #define RTF_HOST 0x0004 /* host entry (net otherwise) */ #define RTF_REINSTATE 0x0008 /* reinstate route after tmout */ #define RTF_DYNAMIC 0x0010 /* created dyn. (by redirect) */ #define RTF_MODIFIED 0x0020 /* modified dyn. (by redirect) */ #define RTF_MTU 0x0040 /* specific MTU for this route */ #define RTF_MSS RTF_MTU /* Compatibility :-( */ #define RTF_WINDOW 0x0080 /* per route window clamping */ #define RTF_IRTT 0x0100 /* Initial round trip time */ #define RTF_REJECT 0x0200 /* Reject route */ #endif /** * Add new route to table. * @param dev Iface * @param dst Destination network * @param mask Genmask * @param gw Gateway */ extern int rt_add_route(struct net_device *dev, in_addr_t dst, in_addr_t mask, in_addr_t gw, int flags); /** * Remove route from table. * @param dev Iface * @param dst Destination network * @param mask Genmask * @param gw Gateway */ extern int rt_del_route(struct net_device *dev, in_addr_t dst, in_addr_t mask, in_addr_t gw); /** * Rebuild sk_buff according to appropriated route. * @param skbuff * @param route - take this route as best match. Or NULL to define it */ extern int ip_route(sk_buff_t *skb, struct net_device *wanna_dev, struct rt_entry *suggested_route); /** * Get IP address of the next machine after routing * After this new_addr will be equal to source_addr or to gateway for this IP * @param ip address * @param pointer to result * @return error code */ extern int rt_fib_route_ip(in_addr_t source_addr, in_addr_t *new_addr); /** * Get IP address of local interface from which packet would be sent * After this new_addr will be equal to interface address * @param ip address * @param pointer to result * @return error code */ extern int rt_fib_source_ip(in_addr_t dst, struct net_device *dev, in_addr_t *out_src); extern int rt_fib_out_dev(in_addr_t dst, const struct sock *sk, struct net_device **out_dev); /** * @param dst - ip address of destination * @param out_dev - device, from witch data will be send to dst. * @return pointer to best match entity for dst * @retval NULL if entity not found */ extern struct rt_entry* rt_fib_get_best(in_addr_t dst, struct net_device *out_dev); /** * Get first element from route from table. * @return pointer to first entity * @retval NULL if entity not found */ extern struct rt_entry * rt_fib_get_first(void); /** * Get next element from route from table uses * pointer to previous entry * Use this function after rt_fib_get_first * @param entry pointer to previous element * @return pointer to next entity * @retval NULL if entity more not found */ extern struct rt_entry * rt_fib_get_next(struct rt_entry *entry); #endif /* NET_L3_ROUTE_H_ */
{ "content_hash": "a5133c8b81697ca54459c48bdeb05df4", "timestamp": "", "source": "github", "line_count": 122, "max_line_length": 83, "avg_line_length": 29.30327868852459, "alnum_prop": 0.6489510489510489, "repo_name": "gzoom13/embox", "id": "be5bf3eca08768f9d8714bc4b5772c2034c97b2d", "size": "3575", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "src/include/net/l3/route.h", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Assembly", "bytes": "113262" }, { "name": "Awk", "bytes": "763" }, { "name": "Batchfile", "bytes": "1242" }, { "name": "C", "bytes": "5430329" }, { "name": "C++", "bytes": "280450" }, { "name": "CSS", "bytes": "1546" }, { "name": "HTML", "bytes": "39637" }, { "name": "JavaScript", "bytes": "9102" }, { "name": "Lua", "bytes": "22656" }, { "name": "Makefile", "bytes": "560893" }, { "name": "Objective-C", "bytes": "16125" }, { "name": "PAWN", "bytes": "824" }, { "name": "PHP", "bytes": "2977" }, { "name": "POV-Ray SDL", "bytes": "5104" }, { "name": "Protocol Buffer", "bytes": "208" }, { "name": "Python", "bytes": "2563" }, { "name": "Shell", "bytes": "39714" } ] }
$( document ).ready(function() { console.log( "ready!" ); // handle input of new job $( "#new-website-form" ).submit(function(e) { e.preventDefault(); var website = $("input:first").val(); // clear input field $("input:first").val(''); // check for type of input var regex = 'http://*'; var regex1 = 'https://*'; if (website.match(regex1)) { website = website.slice(8); } else if (website.match(regex)) { website = website.slice(7); } var regex2 = 'www.*' if (!website.match(regex2)) { website = 'www.'+website; } // make http request $.ajax({ type: "POST", url: 'http://localhost:3000/newWebsite', data: {url: website}, success: function (jobId) { $("#job-id").html("The Job ID for " + website + " is " + jobId + "."); }, error: function (error) { console.log('error in clientside post request to newWebsite endpoint', error); } }); }); // Handle input of id to get results of job $( "#website-status" ).submit(function (e) { e.preventDefault(); var jobId = $("#status-input").val(); // clear input field $("#status-input").val(''); // check for type of input if (!isNaN(jobId) && jobId !== '') { // make http request $.ajax({ type: "GET", url: 'http://localhost:3000/checkWebsite/'+jobId, success: function (results) { var message = ''; if (results.position === null) { message = "No such job has been entered." } else if (results.position >= 0) { message = "The website has not yet been archived! It is " + results.position + " away from being processed. Hang tight."; } else { message = "The results for job #"+ results.id +" and website " + results.url + " is: " + results.content; } $('#website-status-results') .html(message); }, error: function (error) { console.log('error in clientside get request to checkWebsite endpoint', error); } }); } else { alert('Input must be a number!') } }); });
{ "content_hash": "eb339ca50dc7bf05a236f315d08e2ca6", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 131, "avg_line_length": 28.985915492957748, "alnum_prop": 0.56511175898931, "repo_name": "CodeLizards/Jobs-Queue", "id": "8ae638044c114788c6067f3988efc52b94a59a12", "size": "2058", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "client/requests.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "152" }, { "name": "HTML", "bytes": "1048" }, { "name": "JavaScript", "bytes": "8116" } ] }
/** * Created by jianhao on 2017/2/3. */ package sia import org.apache.spark.sql.SparkSession import scala.io.Source object Day06App { def main(args: Array[String]): Unit = { val spark = SparkSession.builder() .appName("GitHub push counter") .master("local[*]") .getOrCreate() val homeDir = System.getenv("HOME") val inputPath = homeDir + "/Desktop/SMACK/learning-spark/Day6SecondApp/github-archive/2015-03-01-0.json" val githubLog = spark.read.json(inputPath) val pushes = githubLog.filter("type ='PushEvent'") //filter欄位type為PushEvent的資料 val grouped = pushes.groupBy("actor.login").count() val ordered = grouped.orderBy(grouped("count").desc) ordered.show(5) val empPath = homeDir + "/Desktop/SMACK/learning-spark/Day6SecondApp/ghEmployees.txt" val employees = Set() ++ ( //用++將yield line.trim產生的集合物件放入空的Set中 for { line <- Source.fromFile(empPath).getLines() } yield line.trim ) //輸入一個字串,若有出現在employees中則回傳True,否則就回傳False val isEmp: String => Boolean = { //String => Boolean: 代表的是這個變數的型態 name => employees.contains(name) } val isEmployee = spark.udf.register("isEmpUdf", isEmp) //SparkSQL User Define Fuction(UDF)註冊成UDF import spark.implicits._ //匯入implicits函數 val filtered = ordered.filter(isEmployee($"login")) //接著就能透過UDF比對order中的資料了,ordered RDD透過filter方式呼叫isEmployee進行過慮 filtered.show(5) } }
{ "content_hash": "e0bcef554402142e88955a9bb146035d", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 121, "avg_line_length": 25.06896551724138, "alnum_prop": 0.6774415405777167, "repo_name": "cocoaswifty/learning-spark", "id": "b13744b9359176a2619d61b1cfd9f9d9ec95165f", "size": "1622", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Day6SecondApp/scalaDemo.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Scala", "bytes": "20770" } ] }
// Copyright 2015 Patrick Putnam // // 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. #ifndef POPCOUNT_HPP_ #define POPCOUNT_HPP_ /* // Popcount algorithm found on Hamming Weight wiki page: // http://en.wikipedia.org/wiki/Hamming_weight // (date 1/1/2015) // const unsigned long long M1 = 0x5555555555555555; //binary: 0101... const unsigned long long M2 = 0x3333333333333333; //binary: 00110011.. const unsigned long long M4 = 0x0f0f0f0f0f0f0f0f; //binary: 4 zeros, 4 ones ... const unsigned long long M8 = 0x00ff00ff00ff00ff; //binary: 8 zeros, 8 ones ... const unsigned long long M16 = 0x0000ffff0000ffff; //binary: 16 zeros, 16 ones ... const unsigned long long M32 = 0x00000000ffffffff; //binary: 32 zeros, 32 ones const unsigned long long HFF = 0xffffffffffffffff; //binary: all ones const unsigned long long H01 = 0x0101010101010101; //the sum of 256 to the power of 0,1,2,3... inline unsigned int popcount( unsigned int x ) { x -=((x >> 1) & (unsigned int) M1); x = (x & (unsigned int) M2) + ((x >> 2) & (unsigned int) M2); x = (x + (x >> 4)) & (unsigned int) M4; return (x * (unsigned int) H01) >> 24; } inline unsigned long long popcount( unsigned long long x ) { x -= (x >> 1) & M1; x = (x & M2) + ((x >> 2) & M2); x = (x + (x >> 4) ) & M4; return ( x * H01) >> 56; }*/ template < unsigned int WordWidth > struct popcount_constants; /** * Byte Lookup Table Based popcount * Allocates 1K (256 * 4 bytes) of memory * * (6/11/15) * Clever macro construction found at: * http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetTable * */ template < > struct popcount_constants< 1 > { static const unsigned int lookup[ 256 ]; template < class T > static unsigned int eval( T x ) { return lookup[ (unsigned char) x ]; } }; template < > struct popcount_constants< 2 > { template < class T > static unsigned int eval( T t ) { return eval( (unsigned short) t ); } static unsigned int eval( unsigned short x ) { typedef popcount_constants< 1 > base_type; return (base_type::lookup[ x & 0x00FF ] + base_type::lookup[x >> 8]); } }; template < > struct popcount_constants< 4 > { static const unsigned int M1 = 0x55555555; //binary: 0101... static const unsigned int M2 = 0x33333333; //binary: 00110011.. static const unsigned int M4 = 0x0f0f0f0f; //binary: 4 zeros, 4 ones ... static const unsigned int M8 = 0x00ff00ff; //binary: 8 zeros, 8 ones ... static const unsigned int M16 = 0x0000ffff; //binary: 16 zeros, 16 ones ... static const unsigned int HFF = 0xffffffff; //binary: all ones static const unsigned int H01 = 0x01010101; //the sum of 256 to the power of 0,1,2,3... static const unsigned long long DSHIFT = 24; template < class T > static unsigned int eval( T x ) { return eval( (unsigned int) x ); } static unsigned int eval( unsigned int x ) { x -=((x >> 1) & M1); x = (x & M2) + ((x >> 2) & M2); x = (x + (x >> 4)) & M4; return (x * H01) >> DSHIFT; } }; template < > struct popcount_constants< 8 > { static const unsigned long long M1 = 0x5555555555555555; //binary: 0101... static const unsigned long long M2 = 0x3333333333333333; //binary: 00110011.. static const unsigned long long M4 = 0x0f0f0f0f0f0f0f0f; //binary: 4 zeros, 4 ones ... static const unsigned long long M8 = 0x00ff00ff00ff00ff; //binary: 8 zeros, 8 ones ... static const unsigned long long M16 = 0x0000ffff0000ffff; //binary: 16 zeros, 16 ones ... static const unsigned long long M32 = 0x00000000ffffffff; //binary: 32 zeros, 32 ones static const unsigned long long HFF = 0xffffffffffffffff; //binary: all ones static const unsigned long long H01 = 0x0101010101010101; //the sum of 256 to the power of 0,1,2,3... static const unsigned long long DSHIFT = 56; template < class T > static unsigned int eval( T t ) { return eval( (unsigned long long) t ); } static unsigned int eval( unsigned long long x ) { x -= (x >> 1) & M1; x = (x & M2) + ((x >> 2) & M2); x = (x + (x >> 4) ) & M4; return ( x * H01) >> DSHIFT; } }; template < class T > unsigned int popcount( T x ) { typedef popcount_constants< sizeof(T) > base_type; return base_type::eval( x ); } #endif // POPCOUNT_HPP_
{ "content_hash": "8b1608765a3d6123e0376a9a62096f09", "timestamp": "", "source": "github", "line_count": 135, "max_line_length": 105, "avg_line_length": 36.592592592592595, "alnum_prop": 0.6368421052631579, "repo_name": "putnampp/clotho", "id": "fa4ab6d07b9d3fcc712e2108f4d7725714f7f2f1", "size": "4940", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "include/clotho/utility/popcount.hpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2235" }, { "name": "C++", "bytes": "1925404" }, { "name": "CMake", "bytes": "30518" }, { "name": "Cuda", "bytes": "65398" }, { "name": "Makefile", "bytes": "331" }, { "name": "Python", "bytes": "8217" } ] }
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using DynamicMVC.ApplicationMetadataLibrary.Interfaces; using DynamicMVC.Shared.Interfaces; namespace DynamicMVC.ApplicationMetadataLibrary.Strategies.ApplicationMetadataProviderValidators { public class TypesAreNotEmpty : IApplicationMetadataProviderValidator { public IEnumerable<ValidationResult> Validate(IApplicationMetadataProvider applicationMetadataProvider) { var validationResults = new List<ValidationResult>(); if (!applicationMetadataProvider.MetadataAssemblyTypes.Any()) validationResults.Add(new ValidationResult("Metadata assembly must contain at least one type.")); if (!applicationMetadataProvider.EntityAssemblyTypes.Any()) validationResults.Add(new ValidationResult("Entity assembly must contain at least one type.")); if (!applicationMetadataProvider.MvcAssemblyTypes.Any()) validationResults.Add(new ValidationResult("Mvc assembly must contain at least one type.")); return validationResults; } } }
{ "content_hash": "4fcfd67040da36cbab0192f31044fe5c", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 113, "avg_line_length": 48.541666666666664, "alnum_prop": 0.7459227467811159, "repo_name": "PrecisionWebTechnologies/DynamicMVC", "id": "39e75a3bfbf95d831964d259c85a2c85cd7387f2", "size": "1165", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "DynamicMVC.ApplicationMetadataLibrary/Strategies/ApplicationMetadataProviderValidators/TypesAreNotEmpty.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "104" }, { "name": "C#", "bytes": "596776" }, { "name": "CSS", "bytes": "64024" }, { "name": "HTML", "bytes": "5127" }, { "name": "JavaScript", "bytes": "203177" } ] }
declare namespace java { namespace lang { namespace management { interface CompilationMXBean extends java.lang.management.PlatformManagedObject { getName(): java.lang.String isCompilationTimeMonitoringSupported(): boolean getTotalCompilationTime(): number } } } }
{ "content_hash": "603aa6573959010cc6daf9e69378193a", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 86, "avg_line_length": 24.153846153846153, "alnum_prop": 0.6910828025477707, "repo_name": "wizawu/1c", "id": "0656dfdd5665891da1f94336fa88a1c2b9f71b00", "size": "314", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "@types/jdk/java.lang.management.CompilationMXBean.d.ts", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "4841" }, { "name": "JavaScript", "bytes": "419" }, { "name": "Makefile", "bytes": "846" }, { "name": "Shell", "bytes": "841" }, { "name": "TypeScript", "bytes": "67719" } ] }
namespace g{ namespace Uno{ namespace Graphics{ // public enum PolygonWinding :234 uEnumType* PolygonWinding_typeof(); }}} // ::g::Uno::Graphics
{ "content_hash": "7c5ed16ecc8e70d8c61778ad03c5d075", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 35, "avg_line_length": 18.375, "alnum_prop": 0.7278911564625851, "repo_name": "blyk/BlackCode-Fuse", "id": "97e84f948e648b56022b249cce55389442a67c05", "size": "357", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "BrowserShare/.build/Simulator/Android/include/Uno.Graphics.PolygonWinding.h", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "31111" }, { "name": "C", "bytes": "22885804" }, { "name": "C++", "bytes": "197750292" }, { "name": "Java", "bytes": "951083" }, { "name": "JavaScript", "bytes": "578555" }, { "name": "Logos", "bytes": "48297" }, { "name": "Makefile", "bytes": "6592573" }, { "name": "Shell", "bytes": "19985" } ] }
package com.simplegeo.android.service; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.http.client.ClientProtocolException; import org.json.JSONArray; import org.json.JSONException; import android.content.Intent; import android.location.Location; import android.os.IBinder; import android.test.ServiceTestCase; import com.simplegeo.android.TestEnvironment; import com.simplegeo.client.SimpleGeoClient; import com.simplegeo.client.http.exceptions.APIException; import com.simplegeo.client.model.DefaultRecord; import com.simplegeo.client.model.Region; import com.simplegeo.client.types.Point; import com.simplegeo.client.utilities.ModelHelper; public class LocationServiceTest extends ServiceTestCase<LocationService> { String layer = null; public LocationServiceTest() { super(LocationService.class); } public void setUp() throws Exception { SimpleGeoClient client = SimpleGeoClient.getInstance(); client.getHttpClient().setToken(TestEnvironment.getKey(), TestEnvironment.getSecret()); client.setFutureTask(false); layer = TestEnvironment.getLayer(); super.setUp(); } public void testStartable() { Intent startIntent = new Intent(); startIntent.setClass(getContext(), LocationService.class); startService(startIntent); assertNotNull(getService()); } public void testBindable() { Intent startIntent = new Intent(); startIntent.setClass(getContext(), LocationService.class); IBinder service = bindService(startIntent); assertNotNull(service); } public void testTrackRecords() throws ClientProtocolException, IOException { Intent startIntent = new Intent(); startIntent.setClass(getContext(), LocationService.class); startService(startIntent); LocationService locationService = getService(); DefaultRecord record = ModelHelper.getRandomDefaultRecord(); record.setLayer(layer); locationService.trackedRecords.add(record); Location location = new Location(""); location.setLatitude(10.0); location.setLongitude(10.0); locationService.onLocationChanged(location); ModelHelper.waitForWrite(); record = (DefaultRecord)SimpleGeoClient.getInstance().retrieve(record); assertEquals(record.getLatitude(), location.getLatitude()); assertEquals(record.getLongitude(), location.getLongitude()); SimpleGeoClient.getInstance().delete(record); ModelHelper.waitForWrite(); } public void testTrackedCachedRecords() throws ClientProtocolException, IOException { Intent startIntent = new Intent(); startIntent.setClass(getContext(), LocationService.class); startService(startIntent); LocationService locationService = getService(); locationService.updateCommitLog(mContext.getCacheDir().getAbsolutePath(), mContext.getPackageName()); locationService.cacheUpdates = true; DefaultRecord record = ModelHelper.getRandomDefaultRecord(); record.setLayer(layer); locationService.trackedRecords.add(record); Location location = new Location(""); location.setLatitude(10.0); location.setLongitude(10.0); locationService.onLocationChanged(location); ModelHelper.waitForWrite(); try { record = (DefaultRecord)SimpleGeoClient.getInstance().retrieve(record); fail(); } catch(APIException e) { assertEquals(e.statusCode, 404); } locationService.replayCommitLog(); ModelHelper.waitForWrite(); record = (DefaultRecord)SimpleGeoClient.getInstance().retrieve(record); assertEquals(record.getLatitude(), location.getLatitude()); assertEquals(record.getLongitude(), location.getLongitude()); SimpleGeoClient.getInstance().delete(record); ModelHelper.waitForWrite(); } public void testLocationChange() { Intent startIntent = new Intent(); startIntent.setClass(getContext(), LocationService.class); startService(startIntent); LocationService locationService = getService(); final Location newLocation = new Location(""); LocationHandler locationHandler = new LocationHandler() { @Override public void onLocationChanged(Location fromLocation, Location toLocation) { newLocation.setLatitude(toLocation.getLatitude()); newLocation.setLongitude(toLocation.getLongitude()); } }; locationService.addHandler(locationHandler); Location location = new Location(""); location.setLatitude(10.0); location.setLongitude(10.0); locationService.onLocationChanged(location); assertEquals(newLocation.getLatitude(), location.getLatitude()); assertEquals(newLocation.getLongitude(), location.getLongitude()); } public void testRegionUpdates() throws ClientProtocolException, IOException, JSONException { Intent startIntent = new Intent(); startIntent.setClass(getContext(), LocationService.class); startService(startIntent); LocationService locationService = getService(); Map<Point, JSONArray> stages = getStages(); final List<Region> enteredRegions = new ArrayList<Region>(); final List<Region> exitedRegions = new ArrayList<Region>(); LocationHandler locationHandler = new LocationHandler() { @Override public void onRegionsEntered(List<Region> regions, Location fromLocation, Location toLocation) { enteredRegions.addAll(regions); } @Override public void onRegionsExited(List<Region> regions, Location fromLocation, Location toLocation) { exitedRegions.addAll(regions); } }; locationService.addHandler(locationHandler); for(Point point : stages.keySet()) { enteredRegions.clear(); exitedRegions.clear(); List<Region> previousRegionSet = locationService.getRegions(); Location location = new Location(""); location.setLatitude(point.getLatitude()); location.setLongitude(point.getLongitude()); locationService.onLocationChanged(location); List<Region> currentRegionSet = Region.getRegions(stages.get(point)); List<Region> difference = Region.difference(previousRegionSet, currentRegionSet); assertRegionsEqual(difference, exitedRegions); difference.clear(); for(Region region : currentRegionSet) if(!region.contained(previousRegionSet)) difference.add(region); assertRegionsEqual(difference, enteredRegions); } } public Map<Point, JSONArray> getStages() throws ClientProtocolException, IOException { List<Point> points = new ArrayList<Point>(); points.add(new Point(34.052659, -118.388672)); points.add(new Point(34.052659, -118.388672)); points.add(new Point(34.082522, -118.38672)); points.add(new Point(39.96028, -105.292969)); SimpleGeoClient client = SimpleGeoClient.getInstance(); Map<Point, JSONArray> stages = new HashMap<Point, JSONArray>(); for(Point point : points) stages.put(point, (JSONArray)client.contains(point.getLatitude(), point.getLongitude())); return stages; } private void assertRegionsEqual(List<Region> regionSetOne, List<Region> regionSetTwo) { if(regionSetOne == null && regionSetTwo == null) assertEquals(regionSetOne, regionSetTwo); else { assertNotNull(regionSetOne); assertNotNull(regionSetTwo); assertEquals(regionSetOne.size(), regionSetTwo.size()); for(int i = 0; i < regionSetOne.size(); i++) assertTrue(regionSetOne.get(i).equals(regionSetTwo.get(i))); } } }
{ "content_hash": "e124eea5c18effe35f2a94fe92df0e9c", "timestamp": "", "source": "github", "line_count": 215, "max_line_length": 106, "avg_line_length": 36.51627906976744, "alnum_prop": 0.7034772640427971, "repo_name": "simplegeo/simplegeo-android-client", "id": "93b87385bef3a32843cc0ff0d8fd02d0f9368bba", "size": "9415", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/src/com/simplegeo/android/service/LocationServiceTest.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "37082" } ] }
require_relative '../spec_helper' describe 'Pool canonical behaviour' do context 'untyped pools' do context 'push_any' do before(:each) do @p1 = Pool.new name: 'p1', initial_value: 2, mode: :push_any @p2 = Pool.new name: 'p2' @e = Edge.new name: 'e', from: @p1, to: @p2 @p1.attach_edge!(@e) @p2.attach_edge!(@e) end it 'pushes one' do @p1.trigger! expect(@p1.resource_count).to eq 1 # because it's just received the resource, it'll be blocked expect(@p2.instant_resource_count).to eq 1 end end context 'pull_any' do before(:each) do @p1 = Pool.new name: 'p1', mode: :pull_any @p2 = Pool.new name: 'p2', initial_value: 2 @e = Edge.new name: 'e', from: @p2, to: @p1 @p1.attach_edge!(@e) @p2.attach_edge!(@e) end it 'pulls one' do @p1.trigger! expect(@p2.resource_count).to eq 1 # # because it's just received the resource, it'll be blocked expect(@p1.instant_resource_count).to eq 1 end end context 'push_all' do end context 'pull_all' do end end end
{ "content_hash": "f23681e7327f8c0a5c780d76eca3d9a9", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 69, "avg_line_length": 17.720588235294116, "alnum_prop": 0.5435684647302904, "repo_name": "queirozfcom/rachinations", "id": "a8501426236eedc242ddd40da382e7807696556d", "size": "1205", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "testing/spec/canon/pool_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "147659" } ] }
std::unique_ptr<wchar_t[]> char2wchar ( char* orig ); std::unique_ptr<wchar_t[]> char2wchar ( const char* orig ); void char2wchar ( char* orig, wchar_t* dest, int destLength ); std::unique_ptr<char[]> wchar2char ( wchar_t* orig ); std::unique_ptr<char[]> wchar2char ( const wchar_t* orig ); void wchar2char ( wchar_t* orig, char* dest, int destLength ); std::wstring string2wstring ( std::string& orig ); std::string wstring2string ( std::wstring& orig ); void trimwhitespace ( char* str ); void copyTrimmed ( char** dest, char* src ); void makeSlug(char *str); std::unique_ptr<char[]> str_base64_encode ( char* raw ); std::unique_ptr<char[]> str_base64_decode ( char* enc ); std::unique_ptr<char[]> make_unique_str ( int size );
{ "content_hash": "93d12b530ab6c4a41386822485dcc465", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 62, "avg_line_length": 38.63157894736842, "alnum_prop": 0.6866485013623979, "repo_name": "ajoabraham/odbc-driver", "id": "5b3460e0d994b0e17645edbd91300a4a6bd9b478", "size": "793", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Common/StringUtils.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ada", "bytes": "89080" }, { "name": "Assembly", "bytes": "138199" }, { "name": "Batchfile", "bytes": "190" }, { "name": "C", "bytes": "1168253" }, { "name": "C#", "bytes": "60476" }, { "name": "C++", "bytes": "3536429" }, { "name": "CLIPS", "bytes": "5291" }, { "name": "CMake", "bytes": "25458" }, { "name": "CSS", "bytes": "1415" }, { "name": "DIGITAL Command Language", "bytes": "27303" }, { "name": "Groff", "bytes": "7559" }, { "name": "HTML", "bytes": "37981" }, { "name": "JavaScript", "bytes": "6113" }, { "name": "Makefile", "bytes": "32540" }, { "name": "Module Management System", "bytes": "1545" }, { "name": "Objective-C", "bytes": "25644" }, { "name": "Pascal", "bytes": "70297" }, { "name": "Perl", "bytes": "3895" }, { "name": "PowerShell", "bytes": "880" }, { "name": "SAS", "bytes": "1847" }, { "name": "Shell", "bytes": "1373" } ] }
/** * Module dependencies. */ var http = require('http'), querystring = require('querystring'); /** * Constants. */ var API_HOST = 'www.google.com', API_END_POINT = '/recaptcha/api/verify', SCRIPT_SRC = API_HOST + '/recaptcha/api/challenge', NOSCRIPT_SRC = API_HOST + '/recaptcha/api/noscript'; /** * Initialize Recaptcha with given `public_key`, `private_key` and optionally * `data`. * * The `data` argument should have the following keys and values: * * remoteip: The IP of the client who submitted the form. * challenge: The value of `recaptcha_challenge_field` from the Recaptcha * form. * response: The value of `recaptcha_response_field` from the Recaptcha * form. * * @param {String} public_key Your Recaptcha public key. * @param {String} private_key Your Recaptcha private key. * @param {Object} data The Recaptcha data to be verified. See above for * format. (optional) * @param {Boolean} secure Flag for using https connections to load client-facing things. (optional) * @api public */ var Recaptcha = exports.Recaptcha = function Recaptcha(public_key, private_key, data, secure) { this.public_key = public_key; this.private_key = private_key; if (typeof(data) == 'boolean'){ this.data = undefined; this.is_secure = data; } else { this.data = data; this.is_secure = secure; } return this; } /** * Render the Recaptcha fields as HTML. * * If there was an error during `verify` and the selected Recaptcha theme * supports it, it will be displayed. * * @api public */ Recaptcha.prototype.toHTML = function() { var query_string = 'k=' + this.public_key; if (this.error_code) { query_string += '&error=' + this.error_code; } var script_src = (this.is_secure ? "https://" : "http://") + SCRIPT_SRC + '?' + query_string; var noscript_src = (this.is_secure ? "https://" : "http://") + NOSCRIPT_SRC + '?' + query_string; return '<script type="text/javascript" src="' + script_src + '"></script>' + '<noscript><iframe src="' + noscript_src + '" height="300" width="500" ' + 'frameborder="0"></iframe><br><textarea name="recaptcha_challenge_field" ' + 'rows="3" cols="40"></textarea><input type="hidden" ' + 'name="recaptcha_response_field" value="manual_challenge"></noscript>'; }; /** * Verify the Recaptcha response. * * Example usage: * * var recaptcha = new Recaptcha('PUBLIC_KEY', 'PRIVATE_KEY', data); * recaptcha.verify(function(success, error_code) { * if (success) { * // data was valid. Continue onward. * } * else { * // data was invalid, redisplay the form using * // recaptcha.toHTML(). * } * }); * * @param {Function} callback * @api public */ Recaptcha.prototype.verify = function(callback) { var self = this; // See if we can declare this invalid without even contacting Recaptcha. if (typeof(this.data) === 'undefined') { this.error_code = 'verify-params-incorrect'; return callback(false, 'verify-params-incorrect'); } if (!('remoteip' in this.data && 'challenge' in this.data && 'response' in this.data)) { this.error_code = 'verify-params-incorrect'; return callback(false, 'verify-params-incorrect'); } if (this.data.response === '') { this.error_code = 'incorrect-captcha-sol'; return callback(false, 'incorrect-captcha-sol'); } // Add the private_key to the request. this.data['privatekey'] = this.private_key; var data_qs = querystring.stringify(this.data); var recaptcha = http.createClient(80, API_HOST); var request = recaptcha.request('POST', API_END_POINT, { host: API_HOST, 'Content-Length': data_qs.length, 'Content-Type': 'application/x-www-form-urlencoded' }); request.on('response', function(response) { var body = ''; response.on('data', function(chunk) { body += chunk; }); response.on('end', function() { var success, error_code; parts = body.split('\n'); success = parts[0]; error_code = parts[1]; if (success !== 'true') { self.error_code = error_code; } return callback(success === 'true', error_code); }); }); request.write(data_qs, 'utf8'); request.end(); };
{ "content_hash": "f30430da3219a500618f8629aa71e211", "timestamp": "", "source": "github", "line_count": 149, "max_line_length": 101, "avg_line_length": 30.93288590604027, "alnum_prop": 0.5836407029724452, "repo_name": "iskanderIt/ExpensesReport", "id": "944cca0789567e270ba3d4ae78978b2b620d0edc", "size": "4715", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "node_modules/recaptcha/lib/recaptcha.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "329565" }, { "name": "HTML", "bytes": "189092" }, { "name": "JavaScript", "bytes": "771441" }, { "name": "Makefile", "bytes": "234" } ] }
<!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_112) on Thu Jul 06 10:54:05 MST 2017 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Interface org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer.node.ContextConsumer (Public javadocs 2017.7.0 API)</title> <meta name="date" content="2017-07-06"> <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 Interface org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer.node.ContextConsumer (Public javadocs 2017.7.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/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/node/ContextConsumer.html" title="interface in org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer.node">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">WildFly Swarm API, 2017.7.0</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../../../../index.html?org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/node/class-use/ContextConsumer.html" target="_top">Frames</a></li> <li><a href="ContextConsumer.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 Interface org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer.node.ContextConsumer" class="title">Uses of Interface<br>org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer.node.ContextConsumer</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/node/ContextConsumer.html" title="interface in org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer.node">ContextConsumer</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer">org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer.node">org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer.node</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/node/ContextConsumer.html" title="interface in org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer.node">ContextConsumer</a> in <a href="../../../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/package-summary.html">org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/package-summary.html">org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer</a> with parameters of type <a href="../../../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/node/ContextConsumer.html" title="interface in org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer.node">ContextConsumer</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/Node.html" title="type parameter in Node">T</a></code></td> <td class="colLast"><span class="typeNameLabel">Node.</span><code><span class="memberNameLink"><a href="../../../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/Node.html#context-java.lang.String-org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer.node.ContextConsumer-">context</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;childKey, <a href="../../../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/node/ContextConsumer.html" title="interface in org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer.node">ContextConsumer</a>&nbsp;consumer)</code> <div class="block">Create and configure a Context object to the list of subresources</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer.node"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/node/ContextConsumer.html" title="interface in org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer.node">ContextConsumer</a> in <a href="../../../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/node/package-summary.html">org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer.node</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/node/package-summary.html">org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer.node</a> that return <a href="../../../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/node/ContextConsumer.html" title="interface in org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer.node">ContextConsumer</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>default <a href="../../../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/node/ContextConsumer.html" title="interface in org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer.node">ContextConsumer</a>&lt;<a href="../../../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/node/ContextConsumer.html" title="type parameter in ContextConsumer">T</a>&gt;</code></td> <td class="colLast"><span class="typeNameLabel">ContextConsumer.</span><code><span class="memberNameLink"><a href="../../../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/node/ContextConsumer.html#andThen-org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer.node.ContextConsumer-">andThen</a></span>(<a href="../../../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/node/ContextConsumer.html" title="interface in org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer.node">ContextConsumer</a>&lt;<a href="../../../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/node/ContextConsumer.html" title="type parameter in ContextConsumer">T</a>&gt;&nbsp;after)</code>&nbsp;</td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/node/package-summary.html">org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer.node</a> with parameters of type <a href="../../../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/node/ContextConsumer.html" title="interface in org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer.node">ContextConsumer</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>default <a href="../../../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/node/ContextConsumer.html" title="interface in org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer.node">ContextConsumer</a>&lt;<a href="../../../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/node/ContextConsumer.html" title="type parameter in ContextConsumer">T</a>&gt;</code></td> <td class="colLast"><span class="typeNameLabel">ContextConsumer.</span><code><span class="memberNameLink"><a href="../../../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/node/ContextConsumer.html#andThen-org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer.node.ContextConsumer-">andThen</a></span>(<a href="../../../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/node/ContextConsumer.html" title="interface in org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer.node">ContextConsumer</a>&lt;<a href="../../../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/node/ContextConsumer.html" title="type parameter in ContextConsumer">T</a>&gt;&nbsp;after)</code>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </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><a href="../../../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/node/ContextConsumer.html" title="interface in org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer.node">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">WildFly Swarm API, 2017.7.0</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../../../../index.html?org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/node/class-use/ContextConsumer.html" target="_top">Frames</a></li> <li><a href="ContextConsumer.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 &#169; 2017 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p> </body> </html>
{ "content_hash": "2cbe6eb174978fc69b3759d8684b7d4d", "timestamp": "", "source": "github", "line_count": 206, "max_line_length": 828, "avg_line_length": 69.20873786407768, "alnum_prop": 0.6758083748334152, "repo_name": "wildfly-swarm/wildfly-swarm-javadocs", "id": "baf5287f03fa877b3371bc05c2bcd05559dd2bc6", "size": "14257", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "2017.7.0/apidocs/org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/node/class-use/ContextConsumer.html", "mode": "33188", "license": "apache-2.0", "language": [] }
package stroom.widget.dropdowntree.client.view; import stroom.svg.client.SvgImages; import stroom.widget.util.client.MouseUtil; import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyDownEvent; import com.google.gwt.event.dom.client.MouseDownEvent; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.SimplePanel; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; import com.gwtplatform.mvp.client.ViewWithUiHandlers; public class DropDownViewImpl extends ViewWithUiHandlers<DropDownUiHandlers> implements DropDownView { private final Widget widget; @UiField FlowPanel container; @UiField Label label; @UiField SimplePanel button; @Inject public DropDownViewImpl(final Binder binder) { widget = binder.createAndBindUi(this); widget.addDomHandler(event -> { if (MouseUtil.isPrimary(event)) { showPopup(event.getNativeEvent()); } }, MouseDownEvent.getType()); widget.addDomHandler(event -> { if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { showPopup(event.getNativeEvent()); } }, KeyDownEvent.getType()); widget.getElement().setTabIndex(0); button.getElement().setInnerHTML(SvgImages.MONO_ELLIPSES); } @Override public Widget asWidget() { return widget; } @Override public void focus() { widget.getElement().focus(); } @Override public void setText(final String text) { label.setText(text); label.setTitle(text); } private void showPopup(final NativeEvent e) { e.stopPropagation(); if (getUiHandlers() != null) { getUiHandlers().showPopup(); } } public interface Binder extends UiBinder<Widget, DropDownViewImpl> { } }
{ "content_hash": "b864890ec3350aa520a966b79257f213", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 76, "avg_line_length": 27.93421052631579, "alnum_prop": 0.6745171926519077, "repo_name": "gchq/stroom", "id": "094e18866ae36f3d0ee4603abf43e7019edc9e69", "size": "2721", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "stroom-core-client-widget/src/main/java/stroom/widget/dropdowntree/client/view/DropDownViewImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "272243" }, { "name": "Dockerfile", "bytes": "21009" }, { "name": "HTML", "bytes": "14114" }, { "name": "Java", "bytes": "22782925" }, { "name": "JavaScript", "bytes": "14516557" }, { "name": "Makefile", "bytes": "661" }, { "name": "Python", "bytes": "3176" }, { "name": "SCSS", "bytes": "158667" }, { "name": "Shell", "bytes": "166531" }, { "name": "TypeScript", "bytes": "2009517" }, { "name": "XSLT", "bytes": "174226" } ] }
//== RegionStore.cpp - Field-sensitive store model --------------*- 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 a basic region store model. In this model, we do have field // sensitivity. But we assume nothing about the heap shape. So recursive data // structures are largely ignored. Basically we do 1-limiting analysis. // Parameter pointers are assumed with no aliasing. Pointee objects of // parameters are created lazily. // //===----------------------------------------------------------------------===// #include "clang/AST/Attr.h" #include "clang/AST/CharUnits.h" #include "clang/Analysis/Analyses/LiveVariables.h" #include "clang/Analysis/AnalysisContext.h" #include "clang/Basic/TargetInfo.h" #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h" #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h" #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h" #include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h" #include "llvm/ADT/ImmutableMap.h" #include "llvm/ADT/Optional.h" #include "llvm/Support/raw_ostream.h" #include <utility> using namespace clang; using namespace ento; //===----------------------------------------------------------------------===// // Representation of binding keys. //===----------------------------------------------------------------------===// namespace { class BindingKey { public: enum Kind { Default = 0x0, Direct = 0x1 }; private: enum { Symbolic = 0x2 }; llvm::PointerIntPair<const MemRegion *, 2> P; uint64_t Data; /// Create a key for a binding to region \p r, which has a symbolic offset /// from region \p Base. explicit BindingKey(const SubRegion *r, const SubRegion *Base, Kind k) : P(r, k | Symbolic), Data(reinterpret_cast<uintptr_t>(Base)) { assert(r && Base && "Must have known regions."); assert(getConcreteOffsetRegion() == Base && "Failed to store base region"); } /// Create a key for a binding at \p offset from base region \p r. explicit BindingKey(const MemRegion *r, uint64_t offset, Kind k) : P(r, k), Data(offset) { assert(r && "Must have known regions."); assert(getOffset() == offset && "Failed to store offset"); assert((r == r->getBaseRegion() || isa<ObjCIvarRegion>(r)) && "Not a base"); } public: bool isDirect() const { return P.getInt() & Direct; } bool hasSymbolicOffset() const { return P.getInt() & Symbolic; } const MemRegion *getRegion() const { return P.getPointer(); } uint64_t getOffset() const { assert(!hasSymbolicOffset()); return Data; } const SubRegion *getConcreteOffsetRegion() const { assert(hasSymbolicOffset()); return reinterpret_cast<const SubRegion *>(static_cast<uintptr_t>(Data)); } const MemRegion *getBaseRegion() const { if (hasSymbolicOffset()) return getConcreteOffsetRegion()->getBaseRegion(); return getRegion()->getBaseRegion(); } void Profile(llvm::FoldingSetNodeID& ID) const { ID.AddPointer(P.getOpaqueValue()); ID.AddInteger(Data); } static BindingKey Make(const MemRegion *R, Kind k); bool operator<(const BindingKey &X) const { if (P.getOpaqueValue() < X.P.getOpaqueValue()) return true; if (P.getOpaqueValue() > X.P.getOpaqueValue()) return false; return Data < X.Data; } bool operator==(const BindingKey &X) const { return P.getOpaqueValue() == X.P.getOpaqueValue() && Data == X.Data; } void dump() const; }; } // end anonymous namespace BindingKey BindingKey::Make(const MemRegion *R, Kind k) { const RegionOffset &RO = R->getAsOffset(); if (RO.hasSymbolicOffset()) return BindingKey(cast<SubRegion>(R), cast<SubRegion>(RO.getRegion()), k); return BindingKey(RO.getRegion(), RO.getOffset(), k); } namespace llvm { static inline raw_ostream &operator<<(raw_ostream &os, BindingKey K) { os << '(' << K.getRegion(); if (!K.hasSymbolicOffset()) os << ',' << K.getOffset(); os << ',' << (K.isDirect() ? "direct" : "default") << ')'; return os; } template <typename T> struct isPodLike; template <> struct isPodLike<BindingKey> { static const bool value = true; }; } // end llvm namespace LLVM_DUMP_METHOD void BindingKey::dump() const { llvm::errs() << *this; } //===----------------------------------------------------------------------===// // Actual Store type. //===----------------------------------------------------------------------===// typedef llvm::ImmutableMap<BindingKey, SVal> ClusterBindings; typedef llvm::ImmutableMapRef<BindingKey, SVal> ClusterBindingsRef; typedef std::pair<BindingKey, SVal> BindingPair; typedef llvm::ImmutableMap<const MemRegion *, ClusterBindings> RegionBindings; namespace { class RegionBindingsRef : public llvm::ImmutableMapRef<const MemRegion *, ClusterBindings> { ClusterBindings::Factory *CBFactory; public: typedef llvm::ImmutableMapRef<const MemRegion *, ClusterBindings> ParentTy; RegionBindingsRef(ClusterBindings::Factory &CBFactory, const RegionBindings::TreeTy *T, RegionBindings::TreeTy::Factory *F) : llvm::ImmutableMapRef<const MemRegion *, ClusterBindings>(T, F), CBFactory(&CBFactory) {} RegionBindingsRef(const ParentTy &P, ClusterBindings::Factory &CBFactory) : llvm::ImmutableMapRef<const MemRegion *, ClusterBindings>(P), CBFactory(&CBFactory) {} RegionBindingsRef add(key_type_ref K, data_type_ref D) const { return RegionBindingsRef(static_cast<const ParentTy *>(this)->add(K, D), *CBFactory); } RegionBindingsRef remove(key_type_ref K) const { return RegionBindingsRef(static_cast<const ParentTy *>(this)->remove(K), *CBFactory); } RegionBindingsRef addBinding(BindingKey K, SVal V) const; RegionBindingsRef addBinding(const MemRegion *R, BindingKey::Kind k, SVal V) const; const SVal *lookup(BindingKey K) const; const SVal *lookup(const MemRegion *R, BindingKey::Kind k) const; using llvm::ImmutableMapRef<const MemRegion *, ClusterBindings>::lookup; RegionBindingsRef removeBinding(BindingKey K); RegionBindingsRef removeBinding(const MemRegion *R, BindingKey::Kind k); RegionBindingsRef removeBinding(const MemRegion *R) { return removeBinding(R, BindingKey::Direct). removeBinding(R, BindingKey::Default); } Optional<SVal> getDirectBinding(const MemRegion *R) const; /// getDefaultBinding - Returns an SVal* representing an optional default /// binding associated with a region and its subregions. Optional<SVal> getDefaultBinding(const MemRegion *R) const; /// Return the internal tree as a Store. Store asStore() const { return asImmutableMap().getRootWithoutRetain(); } void dump(raw_ostream &OS, const char *nl) const { for (iterator I = begin(), E = end(); I != E; ++I) { const ClusterBindings &Cluster = I.getData(); for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end(); CI != CE; ++CI) { OS << ' ' << CI.getKey() << " : " << CI.getData() << nl; } OS << nl; } } LLVM_DUMP_METHOD void dump() const { dump(llvm::errs(), "\n"); } }; } // end anonymous namespace typedef const RegionBindingsRef& RegionBindingsConstRef; Optional<SVal> RegionBindingsRef::getDirectBinding(const MemRegion *R) const { return Optional<SVal>::create(lookup(R, BindingKey::Direct)); } Optional<SVal> RegionBindingsRef::getDefaultBinding(const MemRegion *R) const { if (R->isBoundable()) if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) if (TR->getValueType()->isUnionType()) return UnknownVal(); return Optional<SVal>::create(lookup(R, BindingKey::Default)); } RegionBindingsRef RegionBindingsRef::addBinding(BindingKey K, SVal V) const { const MemRegion *Base = K.getBaseRegion(); const ClusterBindings *ExistingCluster = lookup(Base); ClusterBindings Cluster = (ExistingCluster ? *ExistingCluster : CBFactory->getEmptyMap()); ClusterBindings NewCluster = CBFactory->add(Cluster, K, V); return add(Base, NewCluster); } RegionBindingsRef RegionBindingsRef::addBinding(const MemRegion *R, BindingKey::Kind k, SVal V) const { return addBinding(BindingKey::Make(R, k), V); } const SVal *RegionBindingsRef::lookup(BindingKey K) const { const ClusterBindings *Cluster = lookup(K.getBaseRegion()); if (!Cluster) return nullptr; return Cluster->lookup(K); } const SVal *RegionBindingsRef::lookup(const MemRegion *R, BindingKey::Kind k) const { return lookup(BindingKey::Make(R, k)); } RegionBindingsRef RegionBindingsRef::removeBinding(BindingKey K) { const MemRegion *Base = K.getBaseRegion(); const ClusterBindings *Cluster = lookup(Base); if (!Cluster) return *this; ClusterBindings NewCluster = CBFactory->remove(*Cluster, K); if (NewCluster.isEmpty()) return remove(Base); return add(Base, NewCluster); } RegionBindingsRef RegionBindingsRef::removeBinding(const MemRegion *R, BindingKey::Kind k){ return removeBinding(BindingKey::Make(R, k)); } //===----------------------------------------------------------------------===// // Fine-grained control of RegionStoreManager. //===----------------------------------------------------------------------===// namespace { struct minimal_features_tag {}; struct maximal_features_tag {}; class RegionStoreFeatures { bool SupportsFields; public: RegionStoreFeatures(minimal_features_tag) : SupportsFields(false) {} RegionStoreFeatures(maximal_features_tag) : SupportsFields(true) {} void enableFields(bool t) { SupportsFields = t; } bool supportsFields() const { return SupportsFields; } }; } //===----------------------------------------------------------------------===// // Main RegionStore logic. //===----------------------------------------------------------------------===// namespace { class invalidateRegionsWorker; class RegionStoreManager : public StoreManager { public: const RegionStoreFeatures Features; RegionBindings::Factory RBFactory; mutable ClusterBindings::Factory CBFactory; typedef std::vector<SVal> SValListTy; private: typedef llvm::DenseMap<const LazyCompoundValData *, SValListTy> LazyBindingsMapTy; LazyBindingsMapTy LazyBindingsMap; /// The largest number of fields a struct can have and still be /// considered "small". /// /// This is currently used to decide whether or not it is worth "forcing" a /// LazyCompoundVal on bind. /// /// This is controlled by 'region-store-small-struct-limit' option. /// To disable all small-struct-dependent behavior, set the option to "0". unsigned SmallStructLimit; /// \brief A helper used to populate the work list with the given set of /// regions. void populateWorkList(invalidateRegionsWorker &W, ArrayRef<SVal> Values, InvalidatedRegions *TopLevelRegions); public: RegionStoreManager(ProgramStateManager& mgr, const RegionStoreFeatures &f) : StoreManager(mgr), Features(f), RBFactory(mgr.getAllocator()), CBFactory(mgr.getAllocator()), SmallStructLimit(0) { if (SubEngine *Eng = StateMgr.getOwningEngine()) { AnalyzerOptions &Options = Eng->getAnalysisManager().options; SmallStructLimit = Options.getOptionAsInteger("region-store-small-struct-limit", 2); } } /// setImplicitDefaultValue - Set the default binding for the provided /// MemRegion to the value implicitly defined for compound literals when /// the value is not specified. RegionBindingsRef setImplicitDefaultValue(RegionBindingsConstRef B, const MemRegion *R, QualType T); /// ArrayToPointer - Emulates the "decay" of an array to a pointer /// type. 'Array' represents the lvalue of the array being decayed /// to a pointer, and the returned SVal represents the decayed /// version of that lvalue (i.e., a pointer to the first element of /// the array). This is called by ExprEngine when evaluating /// casts from arrays to pointers. SVal ArrayToPointer(Loc Array, QualType ElementTy) override; StoreRef getInitialStore(const LocationContext *InitLoc) override { return StoreRef(RBFactory.getEmptyMap().getRootWithoutRetain(), *this); } //===-------------------------------------------------------------------===// // Binding values to regions. //===-------------------------------------------------------------------===// RegionBindingsRef invalidateGlobalRegion(MemRegion::Kind K, const Expr *Ex, unsigned Count, const LocationContext *LCtx, RegionBindingsRef B, InvalidatedRegions *Invalidated); StoreRef invalidateRegions(Store store, ArrayRef<SVal> Values, const Expr *E, unsigned Count, const LocationContext *LCtx, const CallEvent *Call, InvalidatedSymbols &IS, RegionAndSymbolInvalidationTraits &ITraits, InvalidatedRegions *Invalidated, InvalidatedRegions *InvalidatedTopLevel) override; bool scanReachableSymbols(Store S, const MemRegion *R, ScanReachableSymbols &Callbacks) override; RegionBindingsRef removeSubRegionBindings(RegionBindingsConstRef B, const SubRegion *R); public: // Part of public interface to class. StoreRef Bind(Store store, Loc LV, SVal V) override { return StoreRef(bind(getRegionBindings(store), LV, V).asStore(), *this); } RegionBindingsRef bind(RegionBindingsConstRef B, Loc LV, SVal V); // BindDefault is only used to initialize a region with a default value. StoreRef BindDefault(Store store, const MemRegion *R, SVal V) override { RegionBindingsRef B = getRegionBindings(store); assert(!B.lookup(R, BindingKey::Direct)); BindingKey Key = BindingKey::Make(R, BindingKey::Default); if (B.lookup(Key)) { const SubRegion *SR = cast<SubRegion>(R); assert(SR->getAsOffset().getOffset() == SR->getSuperRegion()->getAsOffset().getOffset() && "A default value must come from a super-region"); B = removeSubRegionBindings(B, SR); } else { B = B.addBinding(Key, V); } return StoreRef(B.asImmutableMap().getRootWithoutRetain(), *this); } /// Attempt to extract the fields of \p LCV and bind them to the struct region /// \p R. /// /// This path is used when it seems advantageous to "force" loading the values /// within a LazyCompoundVal to bind memberwise to the struct region, rather /// than using a Default binding at the base of the entire region. This is a /// heuristic attempting to avoid building long chains of LazyCompoundVals. /// /// \returns The updated store bindings, or \c None if binding non-lazily /// would be too expensive. Optional<RegionBindingsRef> tryBindSmallStruct(RegionBindingsConstRef B, const TypedValueRegion *R, const RecordDecl *RD, nonloc::LazyCompoundVal LCV); /// BindStruct - Bind a compound value to a structure. RegionBindingsRef bindStruct(RegionBindingsConstRef B, const TypedValueRegion* R, SVal V); /// BindVector - Bind a compound value to a vector. RegionBindingsRef bindVector(RegionBindingsConstRef B, const TypedValueRegion* R, SVal V); RegionBindingsRef bindArray(RegionBindingsConstRef B, const TypedValueRegion* R, SVal V); /// Clears out all bindings in the given region and assigns a new value /// as a Default binding. RegionBindingsRef bindAggregate(RegionBindingsConstRef B, const TypedRegion *R, SVal DefaultVal); /// \brief Create a new store with the specified binding removed. /// \param ST the original store, that is the basis for the new store. /// \param L the location whose binding should be removed. StoreRef killBinding(Store ST, Loc L) override; void incrementReferenceCount(Store store) override { getRegionBindings(store).manualRetain(); } /// If the StoreManager supports it, decrement the reference count of /// the specified Store object. If the reference count hits 0, the memory /// associated with the object is recycled. void decrementReferenceCount(Store store) override { getRegionBindings(store).manualRelease(); } bool includedInBindings(Store store, const MemRegion *region) const override; /// \brief Return the value bound to specified location in a given state. /// /// The high level logic for this method is this: /// getBinding (L) /// if L has binding /// return L's binding /// else if L is in killset /// return unknown /// else /// if L is on stack or heap /// return undefined /// else /// return symbolic SVal getBinding(Store S, Loc L, QualType T) override { return getBinding(getRegionBindings(S), L, T); } SVal getBinding(RegionBindingsConstRef B, Loc L, QualType T = QualType()); SVal getBindingForElement(RegionBindingsConstRef B, const ElementRegion *R); SVal getBindingForField(RegionBindingsConstRef B, const FieldRegion *R); SVal getBindingForObjCIvar(RegionBindingsConstRef B, const ObjCIvarRegion *R); SVal getBindingForVar(RegionBindingsConstRef B, const VarRegion *R); SVal getBindingForLazySymbol(const TypedValueRegion *R); SVal getBindingForFieldOrElementCommon(RegionBindingsConstRef B, const TypedValueRegion *R, QualType Ty); SVal getLazyBinding(const SubRegion *LazyBindingRegion, RegionBindingsRef LazyBinding); /// Get bindings for the values in a struct and return a CompoundVal, used /// when doing struct copy: /// struct s x, y; /// x = y; /// y's value is retrieved by this method. SVal getBindingForStruct(RegionBindingsConstRef B, const TypedValueRegion *R); SVal getBindingForArray(RegionBindingsConstRef B, const TypedValueRegion *R); NonLoc createLazyBinding(RegionBindingsConstRef B, const TypedValueRegion *R); /// Used to lazily generate derived symbols for bindings that are defined /// implicitly by default bindings in a super region. /// /// Note that callers may need to specially handle LazyCompoundVals, which /// are returned as is in case the caller needs to treat them differently. Optional<SVal> getBindingForDerivedDefaultValue(RegionBindingsConstRef B, const MemRegion *superR, const TypedValueRegion *R, QualType Ty); /// Get the state and region whose binding this region \p R corresponds to. /// /// If there is no lazy binding for \p R, the returned value will have a null /// \c second. Note that a null pointer can represents a valid Store. std::pair<Store, const SubRegion *> findLazyBinding(RegionBindingsConstRef B, const SubRegion *R, const SubRegion *originalRegion); /// Returns the cached set of interesting SVals contained within a lazy /// binding. /// /// The precise value of "interesting" is determined for the purposes of /// RegionStore's internal analysis. It must always contain all regions and /// symbols, but may omit constants and other kinds of SVal. const SValListTy &getInterestingValues(nonloc::LazyCompoundVal LCV); //===------------------------------------------------------------------===// // State pruning. //===------------------------------------------------------------------===// /// removeDeadBindings - Scans the RegionStore of 'state' for dead values. /// It returns a new Store with these values removed. StoreRef removeDeadBindings(Store store, const StackFrameContext *LCtx, SymbolReaper& SymReaper) override; //===------------------------------------------------------------------===// // Region "extents". //===------------------------------------------------------------------===// // FIXME: This method will soon be eliminated; see the note in Store.h. DefinedOrUnknownSVal getSizeInElements(ProgramStateRef state, const MemRegion* R, QualType EleTy) override; //===------------------------------------------------------------------===// // Utility methods. //===------------------------------------------------------------------===// RegionBindingsRef getRegionBindings(Store store) const { return RegionBindingsRef(CBFactory, static_cast<const RegionBindings::TreeTy*>(store), RBFactory.getTreeFactory()); } void print(Store store, raw_ostream &Out, const char* nl, const char *sep) override; void iterBindings(Store store, BindingsHandler& f) override { RegionBindingsRef B = getRegionBindings(store); for (RegionBindingsRef::iterator I = B.begin(), E = B.end(); I != E; ++I) { const ClusterBindings &Cluster = I.getData(); for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end(); CI != CE; ++CI) { const BindingKey &K = CI.getKey(); if (!K.isDirect()) continue; if (const SubRegion *R = dyn_cast<SubRegion>(K.getRegion())) { // FIXME: Possibly incorporate the offset? if (!f.HandleBinding(*this, store, R, CI.getData())) return; } } } } }; } // end anonymous namespace //===----------------------------------------------------------------------===// // RegionStore creation. //===----------------------------------------------------------------------===// std::unique_ptr<StoreManager> ento::CreateRegionStoreManager(ProgramStateManager &StMgr) { RegionStoreFeatures F = maximal_features_tag(); return llvm::make_unique<RegionStoreManager>(StMgr, F); } std::unique_ptr<StoreManager> ento::CreateFieldsOnlyRegionStoreManager(ProgramStateManager &StMgr) { RegionStoreFeatures F = minimal_features_tag(); F.enableFields(true); return llvm::make_unique<RegionStoreManager>(StMgr, F); } //===----------------------------------------------------------------------===// // Region Cluster analysis. //===----------------------------------------------------------------------===// namespace { /// Used to determine which global regions are automatically included in the /// initial worklist of a ClusterAnalysis. enum GlobalsFilterKind { /// Don't include any global regions. GFK_None, /// Only include system globals. GFK_SystemOnly, /// Include all global regions. GFK_All }; template <typename DERIVED> class ClusterAnalysis { protected: typedef llvm::DenseMap<const MemRegion *, const ClusterBindings *> ClusterMap; typedef const MemRegion * WorkListElement; typedef SmallVector<WorkListElement, 10> WorkList; llvm::SmallPtrSet<const ClusterBindings *, 16> Visited; WorkList WL; RegionStoreManager &RM; ASTContext &Ctx; SValBuilder &svalBuilder; RegionBindingsRef B; protected: const ClusterBindings *getCluster(const MemRegion *R) { return B.lookup(R); } /// Returns true if all clusters in the given memspace should be initially /// included in the cluster analysis. Subclasses may provide their /// own implementation. bool includeEntireMemorySpace(const MemRegion *Base) { return false; } public: ClusterAnalysis(RegionStoreManager &rm, ProgramStateManager &StateMgr, RegionBindingsRef b) : RM(rm), Ctx(StateMgr.getContext()), svalBuilder(StateMgr.getSValBuilder()), B(std::move(b)) {} RegionBindingsRef getRegionBindings() const { return B; } bool isVisited(const MemRegion *R) { return Visited.count(getCluster(R)); } void GenerateClusters() { // Scan the entire set of bindings and record the region clusters. for (RegionBindingsRef::iterator RI = B.begin(), RE = B.end(); RI != RE; ++RI){ const MemRegion *Base = RI.getKey(); const ClusterBindings &Cluster = RI.getData(); assert(!Cluster.isEmpty() && "Empty clusters should be removed"); static_cast<DERIVED*>(this)->VisitAddedToCluster(Base, Cluster); // If the base's memspace should be entirely invalidated, add the cluster // to the workspace up front. if (static_cast<DERIVED*>(this)->includeEntireMemorySpace(Base)) AddToWorkList(WorkListElement(Base), &Cluster); } } bool AddToWorkList(WorkListElement E, const ClusterBindings *C) { if (C && !Visited.insert(C).second) return false; WL.push_back(E); return true; } bool AddToWorkList(const MemRegion *R) { return static_cast<DERIVED*>(this)->AddToWorkList(R); } void RunWorkList() { while (!WL.empty()) { WorkListElement E = WL.pop_back_val(); const MemRegion *BaseR = E; static_cast<DERIVED*>(this)->VisitCluster(BaseR, getCluster(BaseR)); } } void VisitAddedToCluster(const MemRegion *baseR, const ClusterBindings &C) {} void VisitCluster(const MemRegion *baseR, const ClusterBindings *C) {} void VisitCluster(const MemRegion *BaseR, const ClusterBindings *C, bool Flag) { static_cast<DERIVED*>(this)->VisitCluster(BaseR, C); } }; } //===----------------------------------------------------------------------===// // Binding invalidation. //===----------------------------------------------------------------------===// bool RegionStoreManager::scanReachableSymbols(Store S, const MemRegion *R, ScanReachableSymbols &Callbacks) { assert(R == R->getBaseRegion() && "Should only be called for base regions"); RegionBindingsRef B = getRegionBindings(S); const ClusterBindings *Cluster = B.lookup(R); if (!Cluster) return true; for (ClusterBindings::iterator RI = Cluster->begin(), RE = Cluster->end(); RI != RE; ++RI) { if (!Callbacks.scan(RI.getData())) return false; } return true; } static inline bool isUnionField(const FieldRegion *FR) { return FR->getDecl()->getParent()->isUnion(); } typedef SmallVector<const FieldDecl *, 8> FieldVector; static void getSymbolicOffsetFields(BindingKey K, FieldVector &Fields) { assert(K.hasSymbolicOffset() && "Not implemented for concrete offset keys"); const MemRegion *Base = K.getConcreteOffsetRegion(); const MemRegion *R = K.getRegion(); while (R != Base) { if (const FieldRegion *FR = dyn_cast<FieldRegion>(R)) if (!isUnionField(FR)) Fields.push_back(FR->getDecl()); R = cast<SubRegion>(R)->getSuperRegion(); } } static bool isCompatibleWithFields(BindingKey K, const FieldVector &Fields) { assert(K.hasSymbolicOffset() && "Not implemented for concrete offset keys"); if (Fields.empty()) return true; FieldVector FieldsInBindingKey; getSymbolicOffsetFields(K, FieldsInBindingKey); ptrdiff_t Delta = FieldsInBindingKey.size() - Fields.size(); if (Delta >= 0) return std::equal(FieldsInBindingKey.begin() + Delta, FieldsInBindingKey.end(), Fields.begin()); else return std::equal(FieldsInBindingKey.begin(), FieldsInBindingKey.end(), Fields.begin() - Delta); } /// Collects all bindings in \p Cluster that may refer to bindings within /// \p Top. /// /// Each binding is a pair whose \c first is the key (a BindingKey) and whose /// \c second is the value (an SVal). /// /// The \p IncludeAllDefaultBindings parameter specifies whether to include /// default bindings that may extend beyond \p Top itself, e.g. if \p Top is /// an aggregate within a larger aggregate with a default binding. static void collectSubRegionBindings(SmallVectorImpl<BindingPair> &Bindings, SValBuilder &SVB, const ClusterBindings &Cluster, const SubRegion *Top, BindingKey TopKey, bool IncludeAllDefaultBindings) { FieldVector FieldsInSymbolicSubregions; if (TopKey.hasSymbolicOffset()) { getSymbolicOffsetFields(TopKey, FieldsInSymbolicSubregions); Top = cast<SubRegion>(TopKey.getConcreteOffsetRegion()); TopKey = BindingKey::Make(Top, BindingKey::Default); } // Find the length (in bits) of the region being invalidated. uint64_t Length = UINT64_MAX; SVal Extent = Top->getExtent(SVB); if (Optional<nonloc::ConcreteInt> ExtentCI = Extent.getAs<nonloc::ConcreteInt>()) { const llvm::APSInt &ExtentInt = ExtentCI->getValue(); assert(ExtentInt.isNonNegative() || ExtentInt.isUnsigned()); // Extents are in bytes but region offsets are in bits. Be careful! Length = ExtentInt.getLimitedValue() * SVB.getContext().getCharWidth(); } else if (const FieldRegion *FR = dyn_cast<FieldRegion>(Top)) { if (FR->getDecl()->isBitField()) Length = FR->getDecl()->getBitWidthValue(SVB.getContext()); } for (ClusterBindings::iterator I = Cluster.begin(), E = Cluster.end(); I != E; ++I) { BindingKey NextKey = I.getKey(); if (NextKey.getRegion() == TopKey.getRegion()) { // FIXME: This doesn't catch the case where we're really invalidating a // region with a symbolic offset. Example: // R: points[i].y // Next: points[0].x if (NextKey.getOffset() > TopKey.getOffset() && NextKey.getOffset() - TopKey.getOffset() < Length) { // Case 1: The next binding is inside the region we're invalidating. // Include it. Bindings.push_back(*I); } else if (NextKey.getOffset() == TopKey.getOffset()) { // Case 2: The next binding is at the same offset as the region we're // invalidating. In this case, we need to leave default bindings alone, // since they may be providing a default value for a regions beyond what // we're invalidating. // FIXME: This is probably incorrect; consider invalidating an outer // struct whose first field is bound to a LazyCompoundVal. if (IncludeAllDefaultBindings || NextKey.isDirect()) Bindings.push_back(*I); } } else if (NextKey.hasSymbolicOffset()) { const MemRegion *Base = NextKey.getConcreteOffsetRegion(); if (Top->isSubRegionOf(Base)) { // Case 3: The next key is symbolic and we just changed something within // its concrete region. We don't know if the binding is still valid, so // we'll be conservative and include it. if (IncludeAllDefaultBindings || NextKey.isDirect()) if (isCompatibleWithFields(NextKey, FieldsInSymbolicSubregions)) Bindings.push_back(*I); } else if (const SubRegion *BaseSR = dyn_cast<SubRegion>(Base)) { // Case 4: The next key is symbolic, but we changed a known // super-region. In this case the binding is certainly included. if (Top == Base || BaseSR->isSubRegionOf(Top)) if (isCompatibleWithFields(NextKey, FieldsInSymbolicSubregions)) Bindings.push_back(*I); } } } } static void collectSubRegionBindings(SmallVectorImpl<BindingPair> &Bindings, SValBuilder &SVB, const ClusterBindings &Cluster, const SubRegion *Top, bool IncludeAllDefaultBindings) { collectSubRegionBindings(Bindings, SVB, Cluster, Top, BindingKey::Make(Top, BindingKey::Default), IncludeAllDefaultBindings); } RegionBindingsRef RegionStoreManager::removeSubRegionBindings(RegionBindingsConstRef B, const SubRegion *Top) { BindingKey TopKey = BindingKey::Make(Top, BindingKey::Default); const MemRegion *ClusterHead = TopKey.getBaseRegion(); if (Top == ClusterHead) { // We can remove an entire cluster's bindings all in one go. return B.remove(Top); } const ClusterBindings *Cluster = B.lookup(ClusterHead); if (!Cluster) { // If we're invalidating a region with a symbolic offset, we need to make // sure we don't treat the base region as uninitialized anymore. if (TopKey.hasSymbolicOffset()) { const SubRegion *Concrete = TopKey.getConcreteOffsetRegion(); return B.addBinding(Concrete, BindingKey::Default, UnknownVal()); } return B; } SmallVector<BindingPair, 32> Bindings; collectSubRegionBindings(Bindings, svalBuilder, *Cluster, Top, TopKey, /*IncludeAllDefaultBindings=*/false); ClusterBindingsRef Result(*Cluster, CBFactory); for (SmallVectorImpl<BindingPair>::const_iterator I = Bindings.begin(), E = Bindings.end(); I != E; ++I) Result = Result.remove(I->first); // If we're invalidating a region with a symbolic offset, we need to make sure // we don't treat the base region as uninitialized anymore. // FIXME: This isn't very precise; see the example in // collectSubRegionBindings. if (TopKey.hasSymbolicOffset()) { const SubRegion *Concrete = TopKey.getConcreteOffsetRegion(); Result = Result.add(BindingKey::Make(Concrete, BindingKey::Default), UnknownVal()); } if (Result.isEmpty()) return B.remove(ClusterHead); return B.add(ClusterHead, Result.asImmutableMap()); } namespace { class invalidateRegionsWorker : public ClusterAnalysis<invalidateRegionsWorker> { const Expr *Ex; unsigned Count; const LocationContext *LCtx; InvalidatedSymbols &IS; RegionAndSymbolInvalidationTraits &ITraits; StoreManager::InvalidatedRegions *Regions; GlobalsFilterKind GlobalsFilter; public: invalidateRegionsWorker(RegionStoreManager &rm, ProgramStateManager &stateMgr, RegionBindingsRef b, const Expr *ex, unsigned count, const LocationContext *lctx, InvalidatedSymbols &is, RegionAndSymbolInvalidationTraits &ITraitsIn, StoreManager::InvalidatedRegions *r, GlobalsFilterKind GFK) : ClusterAnalysis<invalidateRegionsWorker>(rm, stateMgr, b), Ex(ex), Count(count), LCtx(lctx), IS(is), ITraits(ITraitsIn), Regions(r), GlobalsFilter(GFK) {} void VisitCluster(const MemRegion *baseR, const ClusterBindings *C); void VisitBinding(SVal V); using ClusterAnalysis::AddToWorkList; bool AddToWorkList(const MemRegion *R); /// Returns true if all clusters in the memory space for \p Base should be /// be invalidated. bool includeEntireMemorySpace(const MemRegion *Base); /// Returns true if the memory space of the given region is one of the global /// regions specially included at the start of invalidation. bool isInitiallyIncludedGlobalRegion(const MemRegion *R); }; } bool invalidateRegionsWorker::AddToWorkList(const MemRegion *R) { bool doNotInvalidateSuperRegion = ITraits.hasTrait( R, RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion); const MemRegion *BaseR = doNotInvalidateSuperRegion ? R : R->getBaseRegion(); return AddToWorkList(WorkListElement(BaseR), getCluster(BaseR)); } void invalidateRegionsWorker::VisitBinding(SVal V) { // A symbol? Mark it touched by the invalidation. if (SymbolRef Sym = V.getAsSymbol()) IS.insert(Sym); if (const MemRegion *R = V.getAsRegion()) { AddToWorkList(R); return; } // Is it a LazyCompoundVal? All references get invalidated as well. if (Optional<nonloc::LazyCompoundVal> LCS = V.getAs<nonloc::LazyCompoundVal>()) { const RegionStoreManager::SValListTy &Vals = RM.getInterestingValues(*LCS); for (RegionStoreManager::SValListTy::const_iterator I = Vals.begin(), E = Vals.end(); I != E; ++I) VisitBinding(*I); return; } } void invalidateRegionsWorker::VisitCluster(const MemRegion *baseR, const ClusterBindings *C) { bool PreserveRegionsContents = ITraits.hasTrait(baseR, RegionAndSymbolInvalidationTraits::TK_PreserveContents); if (C) { for (ClusterBindings::iterator I = C->begin(), E = C->end(); I != E; ++I) VisitBinding(I.getData()); // Invalidate regions contents. if (!PreserveRegionsContents) B = B.remove(baseR); } // BlockDataRegion? If so, invalidate captured variables that are passed // by reference. if (const BlockDataRegion *BR = dyn_cast<BlockDataRegion>(baseR)) { for (BlockDataRegion::referenced_vars_iterator BI = BR->referenced_vars_begin(), BE = BR->referenced_vars_end() ; BI != BE; ++BI) { const VarRegion *VR = BI.getCapturedRegion(); const VarDecl *VD = VR->getDecl(); if (VD->hasAttr<BlocksAttr>() || !VD->hasLocalStorage()) { AddToWorkList(VR); } else if (Loc::isLocType(VR->getValueType())) { // Map the current bindings to a Store to retrieve the value // of the binding. If that binding itself is a region, we should // invalidate that region. This is because a block may capture // a pointer value, but the thing pointed by that pointer may // get invalidated. SVal V = RM.getBinding(B, loc::MemRegionVal(VR)); if (Optional<Loc> L = V.getAs<Loc>()) { if (const MemRegion *LR = L->getAsRegion()) AddToWorkList(LR); } } } return; } // Symbolic region? if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(baseR)) IS.insert(SR->getSymbol()); // Nothing else should be done in the case when we preserve regions context. if (PreserveRegionsContents) return; // Otherwise, we have a normal data region. Record that we touched the region. if (Regions) Regions->push_back(baseR); if (isa<AllocaRegion>(baseR) || isa<SymbolicRegion>(baseR)) { // Invalidate the region by setting its default value to // conjured symbol. The type of the symbol is irrelevant. DefinedOrUnknownSVal V = svalBuilder.conjureSymbolVal(baseR, Ex, LCtx, Ctx.IntTy, Count); B = B.addBinding(baseR, BindingKey::Default, V); return; } if (!baseR->isBoundable()) return; const TypedValueRegion *TR = cast<TypedValueRegion>(baseR); QualType T = TR->getValueType(); if (isInitiallyIncludedGlobalRegion(baseR)) { // If the region is a global and we are invalidating all globals, // erasing the entry is good enough. This causes all globals to be lazily // symbolicated from the same base symbol. return; } if (T->isStructureOrClassType()) { // Invalidate the region by setting its default value to // conjured symbol. The type of the symbol is irrelevant. DefinedOrUnknownSVal V = svalBuilder.conjureSymbolVal(baseR, Ex, LCtx, Ctx.IntTy, Count); B = B.addBinding(baseR, BindingKey::Default, V); return; } if (const ArrayType *AT = Ctx.getAsArrayType(T)) { bool doNotInvalidateSuperRegion = ITraits.hasTrait( baseR, RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion); if (doNotInvalidateSuperRegion) { // We are not doing blank invalidation of the whole array region so we // have to manually invalidate each elements. Optional<uint64_t> NumElements; // Compute lower and upper offsets for region within array. if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) NumElements = CAT->getSize().getZExtValue(); if (!NumElements) // We are not dealing with a constant size array goto conjure_default; QualType ElementTy = AT->getElementType(); uint64_t ElemSize = Ctx.getTypeSize(ElementTy); const RegionOffset &RO = baseR->getAsOffset(); const MemRegion *SuperR = baseR->getBaseRegion(); if (RO.hasSymbolicOffset()) { // If base region has a symbolic offset, // we revert to invalidating the super region. if (SuperR) AddToWorkList(SuperR); goto conjure_default; } uint64_t LowerOffset = RO.getOffset(); uint64_t UpperOffset = LowerOffset + *NumElements * ElemSize; bool UpperOverflow = UpperOffset < LowerOffset; // Invalidate regions which are within array boundaries, // or have a symbolic offset. if (!SuperR) goto conjure_default; const ClusterBindings *C = B.lookup(SuperR); if (!C) goto conjure_default; for (ClusterBindings::iterator I = C->begin(), E = C->end(); I != E; ++I) { const BindingKey &BK = I.getKey(); Optional<uint64_t> ROffset = BK.hasSymbolicOffset() ? Optional<uint64_t>() : BK.getOffset(); // Check offset is not symbolic and within array's boundaries. // Handles arrays of 0 elements and of 0-sized elements as well. if (!ROffset || ((*ROffset >= LowerOffset && *ROffset < UpperOffset) || (UpperOverflow && (*ROffset >= LowerOffset || *ROffset < UpperOffset)) || (LowerOffset == UpperOffset && *ROffset == LowerOffset))) { B = B.removeBinding(I.getKey()); // Bound symbolic regions need to be invalidated for dead symbol // detection. SVal V = I.getData(); const MemRegion *R = V.getAsRegion(); if (R && isa<SymbolicRegion>(R)) VisitBinding(V); } } } conjure_default: // Set the default value of the array to conjured symbol. DefinedOrUnknownSVal V = svalBuilder.conjureSymbolVal(baseR, Ex, LCtx, AT->getElementType(), Count); B = B.addBinding(baseR, BindingKey::Default, V); return; } DefinedOrUnknownSVal V = svalBuilder.conjureSymbolVal(baseR, Ex, LCtx, T,Count); assert(SymbolManager::canSymbolicate(T) || V.isUnknown()); B = B.addBinding(baseR, BindingKey::Direct, V); } bool invalidateRegionsWorker::isInitiallyIncludedGlobalRegion( const MemRegion *R) { switch (GlobalsFilter) { case GFK_None: return false; case GFK_SystemOnly: return isa<GlobalSystemSpaceRegion>(R->getMemorySpace()); case GFK_All: return isa<NonStaticGlobalSpaceRegion>(R->getMemorySpace()); } llvm_unreachable("unknown globals filter"); } bool invalidateRegionsWorker::includeEntireMemorySpace(const MemRegion *Base) { if (isInitiallyIncludedGlobalRegion(Base)) return true; const MemSpaceRegion *MemSpace = Base->getMemorySpace(); return ITraits.hasTrait(MemSpace, RegionAndSymbolInvalidationTraits::TK_EntireMemSpace); } RegionBindingsRef RegionStoreManager::invalidateGlobalRegion(MemRegion::Kind K, const Expr *Ex, unsigned Count, const LocationContext *LCtx, RegionBindingsRef B, InvalidatedRegions *Invalidated) { // Bind the globals memory space to a new symbol that we will use to derive // the bindings for all globals. const GlobalsSpaceRegion *GS = MRMgr.getGlobalsRegion(K); SVal V = svalBuilder.conjureSymbolVal(/* SymbolTag = */ (const void*) GS, Ex, LCtx, /* type does not matter */ Ctx.IntTy, Count); B = B.removeBinding(GS) .addBinding(BindingKey::Make(GS, BindingKey::Default), V); // Even if there are no bindings in the global scope, we still need to // record that we touched it. if (Invalidated) Invalidated->push_back(GS); return B; } void RegionStoreManager::populateWorkList(invalidateRegionsWorker &W, ArrayRef<SVal> Values, InvalidatedRegions *TopLevelRegions) { for (ArrayRef<SVal>::iterator I = Values.begin(), E = Values.end(); I != E; ++I) { SVal V = *I; if (Optional<nonloc::LazyCompoundVal> LCS = V.getAs<nonloc::LazyCompoundVal>()) { const SValListTy &Vals = getInterestingValues(*LCS); for (SValListTy::const_iterator I = Vals.begin(), E = Vals.end(); I != E; ++I) { // Note: the last argument is false here because these are // non-top-level regions. if (const MemRegion *R = (*I).getAsRegion()) W.AddToWorkList(R); } continue; } if (const MemRegion *R = V.getAsRegion()) { if (TopLevelRegions) TopLevelRegions->push_back(R); W.AddToWorkList(R); continue; } } } StoreRef RegionStoreManager::invalidateRegions(Store store, ArrayRef<SVal> Values, const Expr *Ex, unsigned Count, const LocationContext *LCtx, const CallEvent *Call, InvalidatedSymbols &IS, RegionAndSymbolInvalidationTraits &ITraits, InvalidatedRegions *TopLevelRegions, InvalidatedRegions *Invalidated) { GlobalsFilterKind GlobalsFilter; if (Call) { if (Call->isInSystemHeader()) GlobalsFilter = GFK_SystemOnly; else GlobalsFilter = GFK_All; } else { GlobalsFilter = GFK_None; } RegionBindingsRef B = getRegionBindings(store); invalidateRegionsWorker W(*this, StateMgr, B, Ex, Count, LCtx, IS, ITraits, Invalidated, GlobalsFilter); // Scan the bindings and generate the clusters. W.GenerateClusters(); // Add the regions to the worklist. populateWorkList(W, Values, TopLevelRegions); W.RunWorkList(); // Return the new bindings. B = W.getRegionBindings(); // For calls, determine which global regions should be invalidated and // invalidate them. (Note that function-static and immutable globals are never // invalidated by this.) // TODO: This could possibly be more precise with modules. switch (GlobalsFilter) { case GFK_All: B = invalidateGlobalRegion(MemRegion::GlobalInternalSpaceRegionKind, Ex, Count, LCtx, B, Invalidated); // FALLTHROUGH case GFK_SystemOnly: B = invalidateGlobalRegion(MemRegion::GlobalSystemSpaceRegionKind, Ex, Count, LCtx, B, Invalidated); // FALLTHROUGH case GFK_None: break; } return StoreRef(B.asStore(), *this); } //===----------------------------------------------------------------------===// // Extents for regions. //===----------------------------------------------------------------------===// DefinedOrUnknownSVal RegionStoreManager::getSizeInElements(ProgramStateRef state, const MemRegion *R, QualType EleTy) { SVal Size = cast<SubRegion>(R)->getExtent(svalBuilder); const llvm::APSInt *SizeInt = svalBuilder.getKnownValue(state, Size); if (!SizeInt) return UnknownVal(); CharUnits RegionSize = CharUnits::fromQuantity(SizeInt->getSExtValue()); if (Ctx.getAsVariableArrayType(EleTy)) { // FIXME: We need to track extra state to properly record the size // of VLAs. Returning UnknownVal here, however, is a stop-gap so that // we don't have a divide-by-zero below. return UnknownVal(); } CharUnits EleSize = Ctx.getTypeSizeInChars(EleTy); // If a variable is reinterpreted as a type that doesn't fit into a larger // type evenly, round it down. // This is a signed value, since it's used in arithmetic with signed indices. return svalBuilder.makeIntVal(RegionSize / EleSize, false); } //===----------------------------------------------------------------------===// // Location and region casting. //===----------------------------------------------------------------------===// /// ArrayToPointer - Emulates the "decay" of an array to a pointer /// type. 'Array' represents the lvalue of the array being decayed /// to a pointer, and the returned SVal represents the decayed /// version of that lvalue (i.e., a pointer to the first element of /// the array). This is called by ExprEngine when evaluating casts /// from arrays to pointers. SVal RegionStoreManager::ArrayToPointer(Loc Array, QualType T) { if (!Array.getAs<loc::MemRegionVal>()) return UnknownVal(); const MemRegion* R = Array.castAs<loc::MemRegionVal>().getRegion(); NonLoc ZeroIdx = svalBuilder.makeZeroArrayIndex(); return loc::MemRegionVal(MRMgr.getElementRegion(T, ZeroIdx, R, Ctx)); } //===----------------------------------------------------------------------===// // Loading values from regions. //===----------------------------------------------------------------------===// SVal RegionStoreManager::getBinding(RegionBindingsConstRef B, Loc L, QualType T) { assert(!L.getAs<UnknownVal>() && "location unknown"); assert(!L.getAs<UndefinedVal>() && "location undefined"); // For access to concrete addresses, return UnknownVal. Checks // for null dereferences (and similar errors) are done by checkers, not // the Store. // FIXME: We can consider lazily symbolicating such memory, but we really // should defer this when we can reason easily about symbolicating arrays // of bytes. if (L.getAs<loc::ConcreteInt>()) { return UnknownVal(); } if (!L.getAs<loc::MemRegionVal>()) { return UnknownVal(); } const MemRegion *MR = L.castAs<loc::MemRegionVal>().getRegion(); if (isa<BlockDataRegion>(MR)) { return UnknownVal(); } if (isa<AllocaRegion>(MR) || isa<SymbolicRegion>(MR) || isa<CodeTextRegion>(MR)) { if (T.isNull()) { if (const TypedRegion *TR = dyn_cast<TypedRegion>(MR)) T = TR->getLocationType(); else { const SymbolicRegion *SR = cast<SymbolicRegion>(MR); T = SR->getSymbol()->getType(); } } MR = GetElementZeroRegion(MR, T); } // FIXME: Perhaps this method should just take a 'const MemRegion*' argument // instead of 'Loc', and have the other Loc cases handled at a higher level. const TypedValueRegion *R = cast<TypedValueRegion>(MR); QualType RTy = R->getValueType(); // FIXME: we do not yet model the parts of a complex type, so treat the // whole thing as "unknown". if (RTy->isAnyComplexType()) return UnknownVal(); // FIXME: We should eventually handle funny addressing. e.g.: // // int x = ...; // int *p = &x; // char *q = (char*) p; // char c = *q; // returns the first byte of 'x'. // // Such funny addressing will occur due to layering of regions. if (RTy->isStructureOrClassType()) return getBindingForStruct(B, R); // FIXME: Handle unions. if (RTy->isUnionType()) return createLazyBinding(B, R); if (RTy->isArrayType()) { if (RTy->isConstantArrayType()) return getBindingForArray(B, R); else return UnknownVal(); } // FIXME: handle Vector types. if (RTy->isVectorType()) return UnknownVal(); if (const FieldRegion* FR = dyn_cast<FieldRegion>(R)) return CastRetrievedVal(getBindingForField(B, FR), FR, T, false); if (const ElementRegion* ER = dyn_cast<ElementRegion>(R)) { // FIXME: Here we actually perform an implicit conversion from the loaded // value to the element type. Eventually we want to compose these values // more intelligently. For example, an 'element' can encompass multiple // bound regions (e.g., several bound bytes), or could be a subset of // a larger value. return CastRetrievedVal(getBindingForElement(B, ER), ER, T, false); } if (const ObjCIvarRegion *IVR = dyn_cast<ObjCIvarRegion>(R)) { // FIXME: Here we actually perform an implicit conversion from the loaded // value to the ivar type. What we should model is stores to ivars // that blow past the extent of the ivar. If the address of the ivar is // reinterpretted, it is possible we stored a different value that could // fit within the ivar. Either we need to cast these when storing them // or reinterpret them lazily (as we do here). return CastRetrievedVal(getBindingForObjCIvar(B, IVR), IVR, T, false); } if (const VarRegion *VR = dyn_cast<VarRegion>(R)) { // FIXME: Here we actually perform an implicit conversion from the loaded // value to the variable type. What we should model is stores to variables // that blow past the extent of the variable. If the address of the // variable is reinterpretted, it is possible we stored a different value // that could fit within the variable. Either we need to cast these when // storing them or reinterpret them lazily (as we do here). return CastRetrievedVal(getBindingForVar(B, VR), VR, T, false); } const SVal *V = B.lookup(R, BindingKey::Direct); // Check if the region has a binding. if (V) return *V; // The location does not have a bound value. This means that it has // the value it had upon its creation and/or entry to the analyzed // function/method. These are either symbolic values or 'undefined'. if (R->hasStackNonParametersStorage()) { // All stack variables are considered to have undefined values // upon creation. All heap allocated blocks are considered to // have undefined values as well unless they are explicitly bound // to specific values. return UndefinedVal(); } // All other values are symbolic. return svalBuilder.getRegionValueSymbolVal(R); } static QualType getUnderlyingType(const SubRegion *R) { QualType RegionTy; if (const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(R)) RegionTy = TVR->getValueType(); if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R)) RegionTy = SR->getSymbol()->getType(); return RegionTy; } /// Checks to see if store \p B has a lazy binding for region \p R. /// /// If \p AllowSubregionBindings is \c false, a lazy binding will be rejected /// if there are additional bindings within \p R. /// /// Note that unlike RegionStoreManager::findLazyBinding, this will not search /// for lazy bindings for super-regions of \p R. static Optional<nonloc::LazyCompoundVal> getExistingLazyBinding(SValBuilder &SVB, RegionBindingsConstRef B, const SubRegion *R, bool AllowSubregionBindings) { Optional<SVal> V = B.getDefaultBinding(R); if (!V) return None; Optional<nonloc::LazyCompoundVal> LCV = V->getAs<nonloc::LazyCompoundVal>(); if (!LCV) return None; // If the LCV is for a subregion, the types might not match, and we shouldn't // reuse the binding. QualType RegionTy = getUnderlyingType(R); if (!RegionTy.isNull() && !RegionTy->isVoidPointerType()) { QualType SourceRegionTy = LCV->getRegion()->getValueType(); if (!SVB.getContext().hasSameUnqualifiedType(RegionTy, SourceRegionTy)) return None; } if (!AllowSubregionBindings) { // If there are any other bindings within this region, we shouldn't reuse // the top-level binding. SmallVector<BindingPair, 16> Bindings; collectSubRegionBindings(Bindings, SVB, *B.lookup(R->getBaseRegion()), R, /*IncludeAllDefaultBindings=*/true); if (Bindings.size() > 1) return None; } return *LCV; } std::pair<Store, const SubRegion *> RegionStoreManager::findLazyBinding(RegionBindingsConstRef B, const SubRegion *R, const SubRegion *originalRegion) { if (originalRegion != R) { if (Optional<nonloc::LazyCompoundVal> V = getExistingLazyBinding(svalBuilder, B, R, true)) return std::make_pair(V->getStore(), V->getRegion()); } typedef std::pair<Store, const SubRegion *> StoreRegionPair; StoreRegionPair Result = StoreRegionPair(); if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) { Result = findLazyBinding(B, cast<SubRegion>(ER->getSuperRegion()), originalRegion); if (Result.second) Result.second = MRMgr.getElementRegionWithSuper(ER, Result.second); } else if (const FieldRegion *FR = dyn_cast<FieldRegion>(R)) { Result = findLazyBinding(B, cast<SubRegion>(FR->getSuperRegion()), originalRegion); if (Result.second) Result.second = MRMgr.getFieldRegionWithSuper(FR, Result.second); } else if (const CXXBaseObjectRegion *BaseReg = dyn_cast<CXXBaseObjectRegion>(R)) { // C++ base object region is another kind of region that we should blast // through to look for lazy compound value. It is like a field region. Result = findLazyBinding(B, cast<SubRegion>(BaseReg->getSuperRegion()), originalRegion); if (Result.second) Result.second = MRMgr.getCXXBaseObjectRegionWithSuper(BaseReg, Result.second); } return Result; } SVal RegionStoreManager::getBindingForElement(RegionBindingsConstRef B, const ElementRegion* R) { // We do not currently model bindings of the CompoundLiteralregion. if (isa<CompoundLiteralRegion>(R->getBaseRegion())) return UnknownVal(); // Check if the region has a binding. if (const Optional<SVal> &V = B.getDirectBinding(R)) return *V; const MemRegion* superR = R->getSuperRegion(); // Check if the region is an element region of a string literal. if (const StringRegion *StrR=dyn_cast<StringRegion>(superR)) { // FIXME: Handle loads from strings where the literal is treated as // an integer, e.g., *((unsigned int*)"hello") QualType T = Ctx.getAsArrayType(StrR->getValueType())->getElementType(); if (!Ctx.hasSameUnqualifiedType(T, R->getElementType())) return UnknownVal(); const StringLiteral *Str = StrR->getStringLiteral(); SVal Idx = R->getIndex(); if (Optional<nonloc::ConcreteInt> CI = Idx.getAs<nonloc::ConcreteInt>()) { int64_t i = CI->getValue().getSExtValue(); // Abort on string underrun. This can be possible by arbitrary // clients of getBindingForElement(). if (i < 0) return UndefinedVal(); int64_t length = Str->getLength(); // Technically, only i == length is guaranteed to be null. // However, such overflows should be caught before reaching this point; // the only time such an access would be made is if a string literal was // used to initialize a larger array. char c = (i >= length) ? '\0' : Str->getCodeUnit(i); return svalBuilder.makeIntVal(c, T); } } // Check for loads from a code text region. For such loads, just give up. if (isa<CodeTextRegion>(superR)) return UnknownVal(); // Handle the case where we are indexing into a larger scalar object. // For example, this handles: // int x = ... // char *y = &x; // return *y; // FIXME: This is a hack, and doesn't do anything really intelligent yet. const RegionRawOffset &O = R->getAsArrayOffset(); // If we cannot reason about the offset, return an unknown value. if (!O.getRegion()) return UnknownVal(); if (const TypedValueRegion *baseR = dyn_cast_or_null<TypedValueRegion>(O.getRegion())) { QualType baseT = baseR->getValueType(); if (baseT->isScalarType()) { QualType elemT = R->getElementType(); if (elemT->isScalarType()) { if (Ctx.getTypeSizeInChars(baseT) >= Ctx.getTypeSizeInChars(elemT)) { if (const Optional<SVal> &V = B.getDirectBinding(superR)) { if (SymbolRef parentSym = V->getAsSymbol()) return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R); if (V->isUnknownOrUndef()) return *V; // Other cases: give up. We are indexing into a larger object // that has some value, but we don't know how to handle that yet. return UnknownVal(); } } } } } return getBindingForFieldOrElementCommon(B, R, R->getElementType()); } SVal RegionStoreManager::getBindingForField(RegionBindingsConstRef B, const FieldRegion* R) { // Check if the region has a binding. if (const Optional<SVal> &V = B.getDirectBinding(R)) return *V; QualType Ty = R->getValueType(); return getBindingForFieldOrElementCommon(B, R, Ty); } Optional<SVal> RegionStoreManager::getBindingForDerivedDefaultValue(RegionBindingsConstRef B, const MemRegion *superR, const TypedValueRegion *R, QualType Ty) { if (const Optional<SVal> &D = B.getDefaultBinding(superR)) { const SVal &val = D.getValue(); if (SymbolRef parentSym = val.getAsSymbol()) return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R); if (val.isZeroConstant()) return svalBuilder.makeZeroVal(Ty); if (val.isUnknownOrUndef()) return val; // Lazy bindings are usually handled through getExistingLazyBinding(). // We should unify these two code paths at some point. if (val.getAs<nonloc::LazyCompoundVal>() || val.getAs<nonloc::CompoundVal>()) return val; llvm_unreachable("Unknown default value"); } return None; } SVal RegionStoreManager::getLazyBinding(const SubRegion *LazyBindingRegion, RegionBindingsRef LazyBinding) { SVal Result; if (const ElementRegion *ER = dyn_cast<ElementRegion>(LazyBindingRegion)) Result = getBindingForElement(LazyBinding, ER); else Result = getBindingForField(LazyBinding, cast<FieldRegion>(LazyBindingRegion)); // FIXME: This is a hack to deal with RegionStore's inability to distinguish a // default value for /part/ of an aggregate from a default value for the // /entire/ aggregate. The most common case of this is when struct Outer // has as its first member a struct Inner, which is copied in from a stack // variable. In this case, even if the Outer's default value is symbolic, 0, // or unknown, it gets overridden by the Inner's default value of undefined. // // This is a general problem -- if the Inner is zero-initialized, the Outer // will now look zero-initialized. The proper way to solve this is with a // new version of RegionStore that tracks the extent of a binding as well // as the offset. // // This hack only takes care of the undefined case because that can very // quickly result in a warning. if (Result.isUndef()) Result = UnknownVal(); return Result; } SVal RegionStoreManager::getBindingForFieldOrElementCommon(RegionBindingsConstRef B, const TypedValueRegion *R, QualType Ty) { // At this point we have already checked in either getBindingForElement or // getBindingForField if 'R' has a direct binding. // Lazy binding? Store lazyBindingStore = nullptr; const SubRegion *lazyBindingRegion = nullptr; std::tie(lazyBindingStore, lazyBindingRegion) = findLazyBinding(B, R, R); if (lazyBindingRegion) return getLazyBinding(lazyBindingRegion, getRegionBindings(lazyBindingStore)); // Record whether or not we see a symbolic index. That can completely // be out of scope of our lookup. bool hasSymbolicIndex = false; // FIXME: This is a hack to deal with RegionStore's inability to distinguish a // default value for /part/ of an aggregate from a default value for the // /entire/ aggregate. The most common case of this is when struct Outer // has as its first member a struct Inner, which is copied in from a stack // variable. In this case, even if the Outer's default value is symbolic, 0, // or unknown, it gets overridden by the Inner's default value of undefined. // // This is a general problem -- if the Inner is zero-initialized, the Outer // will now look zero-initialized. The proper way to solve this is with a // new version of RegionStore that tracks the extent of a binding as well // as the offset. // // This hack only takes care of the undefined case because that can very // quickly result in a warning. bool hasPartialLazyBinding = false; const SubRegion *SR = dyn_cast<SubRegion>(R); while (SR) { const MemRegion *Base = SR->getSuperRegion(); if (Optional<SVal> D = getBindingForDerivedDefaultValue(B, Base, R, Ty)) { if (D->getAs<nonloc::LazyCompoundVal>()) { hasPartialLazyBinding = true; break; } return *D; } if (const ElementRegion *ER = dyn_cast<ElementRegion>(Base)) { NonLoc index = ER->getIndex(); if (!index.isConstant()) hasSymbolicIndex = true; } // If our super region is a field or element itself, walk up the region // hierarchy to see if there is a default value installed in an ancestor. SR = dyn_cast<SubRegion>(Base); } if (R->hasStackNonParametersStorage()) { if (isa<ElementRegion>(R)) { // Currently we don't reason specially about Clang-style vectors. Check // if superR is a vector and if so return Unknown. if (const TypedValueRegion *typedSuperR = dyn_cast<TypedValueRegion>(R->getSuperRegion())) { if (typedSuperR->getValueType()->isVectorType()) return UnknownVal(); } } // FIXME: We also need to take ElementRegions with symbolic indexes into // account. This case handles both directly accessing an ElementRegion // with a symbolic offset, but also fields within an element with // a symbolic offset. if (hasSymbolicIndex) return UnknownVal(); if (!hasPartialLazyBinding) return UndefinedVal(); } // All other values are symbolic. return svalBuilder.getRegionValueSymbolVal(R); } SVal RegionStoreManager::getBindingForObjCIvar(RegionBindingsConstRef B, const ObjCIvarRegion* R) { // Check if the region has a binding. if (const Optional<SVal> &V = B.getDirectBinding(R)) return *V; const MemRegion *superR = R->getSuperRegion(); // Check if the super region has a default binding. if (const Optional<SVal> &V = B.getDefaultBinding(superR)) { if (SymbolRef parentSym = V->getAsSymbol()) return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R); // Other cases: give up. return UnknownVal(); } return getBindingForLazySymbol(R); } SVal RegionStoreManager::getBindingForVar(RegionBindingsConstRef B, const VarRegion *R) { // Check if the region has a binding. if (const Optional<SVal> &V = B.getDirectBinding(R)) return *V; // Lazily derive a value for the VarRegion. const VarDecl *VD = R->getDecl(); const MemSpaceRegion *MS = R->getMemorySpace(); // Arguments are always symbolic. if (isa<StackArgumentsSpaceRegion>(MS)) return svalBuilder.getRegionValueSymbolVal(R); // Is 'VD' declared constant? If so, retrieve the constant value. if (VD->getType().isConstQualified()) if (const Expr *Init = VD->getInit()) if (Optional<SVal> V = svalBuilder.getConstantVal(Init)) return *V; // This must come after the check for constants because closure-captured // constant variables may appear in UnknownSpaceRegion. if (isa<UnknownSpaceRegion>(MS)) return svalBuilder.getRegionValueSymbolVal(R); if (isa<GlobalsSpaceRegion>(MS)) { QualType T = VD->getType(); // Function-scoped static variables are default-initialized to 0; if they // have an initializer, it would have been processed by now. // FIXME: This is only true when we're starting analysis from main(). // We're losing a lot of coverage here. if (isa<StaticGlobalSpaceRegion>(MS)) return svalBuilder.makeZeroVal(T); if (Optional<SVal> V = getBindingForDerivedDefaultValue(B, MS, R, T)) { assert(!V->getAs<nonloc::LazyCompoundVal>()); return V.getValue(); } return svalBuilder.getRegionValueSymbolVal(R); } return UndefinedVal(); } SVal RegionStoreManager::getBindingForLazySymbol(const TypedValueRegion *R) { // All other values are symbolic. return svalBuilder.getRegionValueSymbolVal(R); } const RegionStoreManager::SValListTy & RegionStoreManager::getInterestingValues(nonloc::LazyCompoundVal LCV) { // First, check the cache. LazyBindingsMapTy::iterator I = LazyBindingsMap.find(LCV.getCVData()); if (I != LazyBindingsMap.end()) return I->second; // If we don't have a list of values cached, start constructing it. SValListTy List; const SubRegion *LazyR = LCV.getRegion(); RegionBindingsRef B = getRegionBindings(LCV.getStore()); // If this region had /no/ bindings at the time, there are no interesting // values to return. const ClusterBindings *Cluster = B.lookup(LazyR->getBaseRegion()); if (!Cluster) return (LazyBindingsMap[LCV.getCVData()] = std::move(List)); SmallVector<BindingPair, 32> Bindings; collectSubRegionBindings(Bindings, svalBuilder, *Cluster, LazyR, /*IncludeAllDefaultBindings=*/true); for (SmallVectorImpl<BindingPair>::const_iterator I = Bindings.begin(), E = Bindings.end(); I != E; ++I) { SVal V = I->second; if (V.isUnknownOrUndef() || V.isConstant()) continue; if (Optional<nonloc::LazyCompoundVal> InnerLCV = V.getAs<nonloc::LazyCompoundVal>()) { const SValListTy &InnerList = getInterestingValues(*InnerLCV); List.insert(List.end(), InnerList.begin(), InnerList.end()); continue; } List.push_back(V); } return (LazyBindingsMap[LCV.getCVData()] = std::move(List)); } NonLoc RegionStoreManager::createLazyBinding(RegionBindingsConstRef B, const TypedValueRegion *R) { if (Optional<nonloc::LazyCompoundVal> V = getExistingLazyBinding(svalBuilder, B, R, false)) return *V; return svalBuilder.makeLazyCompoundVal(StoreRef(B.asStore(), *this), R); } static bool isRecordEmpty(const RecordDecl *RD) { if (!RD->field_empty()) return false; if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) return CRD->getNumBases() == 0; return true; } SVal RegionStoreManager::getBindingForStruct(RegionBindingsConstRef B, const TypedValueRegion *R) { const RecordDecl *RD = R->getValueType()->castAs<RecordType>()->getDecl(); if (!RD->getDefinition() || isRecordEmpty(RD)) return UnknownVal(); return createLazyBinding(B, R); } SVal RegionStoreManager::getBindingForArray(RegionBindingsConstRef B, const TypedValueRegion *R) { assert(Ctx.getAsConstantArrayType(R->getValueType()) && "Only constant array types can have compound bindings."); return createLazyBinding(B, R); } bool RegionStoreManager::includedInBindings(Store store, const MemRegion *region) const { RegionBindingsRef B = getRegionBindings(store); region = region->getBaseRegion(); // Quick path: if the base is the head of a cluster, the region is live. if (B.lookup(region)) return true; // Slow path: if the region is the VALUE of any binding, it is live. for (RegionBindingsRef::iterator RI = B.begin(), RE = B.end(); RI != RE; ++RI) { const ClusterBindings &Cluster = RI.getData(); for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end(); CI != CE; ++CI) { const SVal &D = CI.getData(); if (const MemRegion *R = D.getAsRegion()) if (R->getBaseRegion() == region) return true; } } return false; } //===----------------------------------------------------------------------===// // Binding values to regions. //===----------------------------------------------------------------------===// StoreRef RegionStoreManager::killBinding(Store ST, Loc L) { if (Optional<loc::MemRegionVal> LV = L.getAs<loc::MemRegionVal>()) if (const MemRegion* R = LV->getRegion()) return StoreRef(getRegionBindings(ST).removeBinding(R) .asImmutableMap() .getRootWithoutRetain(), *this); return StoreRef(ST, *this); } RegionBindingsRef RegionStoreManager::bind(RegionBindingsConstRef B, Loc L, SVal V) { if (L.getAs<loc::ConcreteInt>()) return B; // If we get here, the location should be a region. const MemRegion *R = L.castAs<loc::MemRegionVal>().getRegion(); // Check if the region is a struct region. if (const TypedValueRegion* TR = dyn_cast<TypedValueRegion>(R)) { QualType Ty = TR->getValueType(); if (Ty->isArrayType()) return bindArray(B, TR, V); if (Ty->isStructureOrClassType()) return bindStruct(B, TR, V); if (Ty->isVectorType()) return bindVector(B, TR, V); if (Ty->isUnionType()) return bindAggregate(B, TR, V); } if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R)) { // Binding directly to a symbolic region should be treated as binding // to element 0. QualType T = SR->getSymbol()->getType(); if (T->isAnyPointerType() || T->isReferenceType()) T = T->getPointeeType(); R = GetElementZeroRegion(SR, T); } // Clear out bindings that may overlap with this binding. RegionBindingsRef NewB = removeSubRegionBindings(B, cast<SubRegion>(R)); return NewB.addBinding(BindingKey::Make(R, BindingKey::Direct), V); } RegionBindingsRef RegionStoreManager::setImplicitDefaultValue(RegionBindingsConstRef B, const MemRegion *R, QualType T) { SVal V; if (Loc::isLocType(T)) V = svalBuilder.makeNull(); else if (T->isIntegralOrEnumerationType()) V = svalBuilder.makeZeroVal(T); else if (T->isStructureOrClassType() || T->isArrayType()) { // Set the default value to a zero constant when it is a structure // or array. The type doesn't really matter. V = svalBuilder.makeZeroVal(Ctx.IntTy); } else { // We can't represent values of this type, but we still need to set a value // to record that the region has been initialized. // If this assertion ever fires, a new case should be added above -- we // should know how to default-initialize any value we can symbolicate. assert(!SymbolManager::canSymbolicate(T) && "This type is representable"); V = UnknownVal(); } return B.addBinding(R, BindingKey::Default, V); } RegionBindingsRef RegionStoreManager::bindArray(RegionBindingsConstRef B, const TypedValueRegion* R, SVal Init) { const ArrayType *AT =cast<ArrayType>(Ctx.getCanonicalType(R->getValueType())); QualType ElementTy = AT->getElementType(); Optional<uint64_t> Size; if (const ConstantArrayType* CAT = dyn_cast<ConstantArrayType>(AT)) Size = CAT->getSize().getZExtValue(); // Check if the init expr is a string literal. if (Optional<loc::MemRegionVal> MRV = Init.getAs<loc::MemRegionVal>()) { const StringRegion *S = cast<StringRegion>(MRV->getRegion()); // Treat the string as a lazy compound value. StoreRef store(B.asStore(), *this); nonloc::LazyCompoundVal LCV = svalBuilder.makeLazyCompoundVal(store, S) .castAs<nonloc::LazyCompoundVal>(); return bindAggregate(B, R, LCV); } // Handle lazy compound values. if (Init.getAs<nonloc::LazyCompoundVal>()) return bindAggregate(B, R, Init); if (Init.isUnknown()) return bindAggregate(B, R, UnknownVal()); // Remaining case: explicit compound values. const nonloc::CompoundVal& CV = Init.castAs<nonloc::CompoundVal>(); nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end(); uint64_t i = 0; RegionBindingsRef NewB(B); for (; Size.hasValue() ? i < Size.getValue() : true ; ++i, ++VI) { // The init list might be shorter than the array length. if (VI == VE) break; const NonLoc &Idx = svalBuilder.makeArrayIndex(i); const ElementRegion *ER = MRMgr.getElementRegion(ElementTy, Idx, R, Ctx); if (ElementTy->isStructureOrClassType()) NewB = bindStruct(NewB, ER, *VI); else if (ElementTy->isArrayType()) NewB = bindArray(NewB, ER, *VI); else NewB = bind(NewB, loc::MemRegionVal(ER), *VI); } // If the init list is shorter than the array length, set the // array default value. if (Size.hasValue() && i < Size.getValue()) NewB = setImplicitDefaultValue(NewB, R, ElementTy); return NewB; } RegionBindingsRef RegionStoreManager::bindVector(RegionBindingsConstRef B, const TypedValueRegion* R, SVal V) { QualType T = R->getValueType(); assert(T->isVectorType()); const VectorType *VT = T->getAs<VectorType>(); // Use getAs for typedefs. // Handle lazy compound values and symbolic values. if (V.getAs<nonloc::LazyCompoundVal>() || V.getAs<nonloc::SymbolVal>()) return bindAggregate(B, R, V); // We may get non-CompoundVal accidentally due to imprecise cast logic or // that we are binding symbolic struct value. Kill the field values, and if // the value is symbolic go and bind it as a "default" binding. if (!V.getAs<nonloc::CompoundVal>()) { return bindAggregate(B, R, UnknownVal()); } QualType ElemType = VT->getElementType(); nonloc::CompoundVal CV = V.castAs<nonloc::CompoundVal>(); nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end(); unsigned index = 0, numElements = VT->getNumElements(); RegionBindingsRef NewB(B); for ( ; index != numElements ; ++index) { if (VI == VE) break; NonLoc Idx = svalBuilder.makeArrayIndex(index); const ElementRegion *ER = MRMgr.getElementRegion(ElemType, Idx, R, Ctx); if (ElemType->isArrayType()) NewB = bindArray(NewB, ER, *VI); else if (ElemType->isStructureOrClassType()) NewB = bindStruct(NewB, ER, *VI); else NewB = bind(NewB, loc::MemRegionVal(ER), *VI); } return NewB; } Optional<RegionBindingsRef> RegionStoreManager::tryBindSmallStruct(RegionBindingsConstRef B, const TypedValueRegion *R, const RecordDecl *RD, nonloc::LazyCompoundVal LCV) { FieldVector Fields; if (const CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(RD)) if (Class->getNumBases() != 0 || Class->getNumVBases() != 0) return None; for (const auto *FD : RD->fields()) { if (FD->isUnnamedBitfield()) continue; // If there are too many fields, or if any of the fields are aggregates, // just use the LCV as a default binding. if (Fields.size() == SmallStructLimit) return None; QualType Ty = FD->getType(); if (!(Ty->isScalarType() || Ty->isReferenceType())) return None; Fields.push_back(FD); } RegionBindingsRef NewB = B; for (FieldVector::iterator I = Fields.begin(), E = Fields.end(); I != E; ++I){ const FieldRegion *SourceFR = MRMgr.getFieldRegion(*I, LCV.getRegion()); SVal V = getBindingForField(getRegionBindings(LCV.getStore()), SourceFR); const FieldRegion *DestFR = MRMgr.getFieldRegion(*I, R); NewB = bind(NewB, loc::MemRegionVal(DestFR), V); } return NewB; } RegionBindingsRef RegionStoreManager::bindStruct(RegionBindingsConstRef B, const TypedValueRegion* R, SVal V) { if (!Features.supportsFields()) return B; QualType T = R->getValueType(); assert(T->isStructureOrClassType()); const RecordType* RT = T->getAs<RecordType>(); const RecordDecl *RD = RT->getDecl(); if (!RD->isCompleteDefinition()) return B; // Handle lazy compound values and symbolic values. if (Optional<nonloc::LazyCompoundVal> LCV = V.getAs<nonloc::LazyCompoundVal>()) { if (Optional<RegionBindingsRef> NewB = tryBindSmallStruct(B, R, RD, *LCV)) return *NewB; return bindAggregate(B, R, V); } if (V.getAs<nonloc::SymbolVal>()) return bindAggregate(B, R, V); // We may get non-CompoundVal accidentally due to imprecise cast logic or // that we are binding symbolic struct value. Kill the field values, and if // the value is symbolic go and bind it as a "default" binding. if (V.isUnknown() || !V.getAs<nonloc::CompoundVal>()) return bindAggregate(B, R, UnknownVal()); const nonloc::CompoundVal& CV = V.castAs<nonloc::CompoundVal>(); nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end(); RecordDecl::field_iterator FI, FE; RegionBindingsRef NewB(B); for (FI = RD->field_begin(), FE = RD->field_end(); FI != FE; ++FI) { if (VI == VE) break; // Skip any unnamed bitfields to stay in sync with the initializers. if (FI->isUnnamedBitfield()) continue; QualType FTy = FI->getType(); const FieldRegion* FR = MRMgr.getFieldRegion(*FI, R); if (FTy->isArrayType()) NewB = bindArray(NewB, FR, *VI); else if (FTy->isStructureOrClassType()) NewB = bindStruct(NewB, FR, *VI); else NewB = bind(NewB, loc::MemRegionVal(FR), *VI); ++VI; } // There may be fewer values in the initialize list than the fields of struct. if (FI != FE) { NewB = NewB.addBinding(R, BindingKey::Default, svalBuilder.makeIntVal(0, false)); } return NewB; } RegionBindingsRef RegionStoreManager::bindAggregate(RegionBindingsConstRef B, const TypedRegion *R, SVal Val) { // Remove the old bindings, using 'R' as the root of all regions // we will invalidate. Then add the new binding. return removeSubRegionBindings(B, R).addBinding(R, BindingKey::Default, Val); } //===----------------------------------------------------------------------===// // State pruning. //===----------------------------------------------------------------------===// namespace { class removeDeadBindingsWorker : public ClusterAnalysis<removeDeadBindingsWorker> { SmallVector<const SymbolicRegion*, 12> Postponed; SymbolReaper &SymReaper; const StackFrameContext *CurrentLCtx; public: removeDeadBindingsWorker(RegionStoreManager &rm, ProgramStateManager &stateMgr, RegionBindingsRef b, SymbolReaper &symReaper, const StackFrameContext *LCtx) : ClusterAnalysis<removeDeadBindingsWorker>(rm, stateMgr, b), SymReaper(symReaper), CurrentLCtx(LCtx) {} // Called by ClusterAnalysis. void VisitAddedToCluster(const MemRegion *baseR, const ClusterBindings &C); void VisitCluster(const MemRegion *baseR, const ClusterBindings *C); using ClusterAnalysis<removeDeadBindingsWorker>::VisitCluster; using ClusterAnalysis::AddToWorkList; bool AddToWorkList(const MemRegion *R); bool UpdatePostponed(); void VisitBinding(SVal V); }; } bool removeDeadBindingsWorker::AddToWorkList(const MemRegion *R) { const MemRegion *BaseR = R->getBaseRegion(); return AddToWorkList(WorkListElement(BaseR), getCluster(BaseR)); } void removeDeadBindingsWorker::VisitAddedToCluster(const MemRegion *baseR, const ClusterBindings &C) { if (const VarRegion *VR = dyn_cast<VarRegion>(baseR)) { if (SymReaper.isLive(VR)) AddToWorkList(baseR, &C); return; } if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(baseR)) { if (SymReaper.isLive(SR->getSymbol())) AddToWorkList(SR, &C); else Postponed.push_back(SR); return; } if (isa<NonStaticGlobalSpaceRegion>(baseR)) { AddToWorkList(baseR, &C); return; } // CXXThisRegion in the current or parent location context is live. if (const CXXThisRegion *TR = dyn_cast<CXXThisRegion>(baseR)) { const StackArgumentsSpaceRegion *StackReg = cast<StackArgumentsSpaceRegion>(TR->getSuperRegion()); const StackFrameContext *RegCtx = StackReg->getStackFrame(); if (CurrentLCtx && (RegCtx == CurrentLCtx || RegCtx->isParentOf(CurrentLCtx))) AddToWorkList(TR, &C); } } void removeDeadBindingsWorker::VisitCluster(const MemRegion *baseR, const ClusterBindings *C) { if (!C) return; // Mark the symbol for any SymbolicRegion with live bindings as live itself. // This means we should continue to track that symbol. if (const SymbolicRegion *SymR = dyn_cast<SymbolicRegion>(baseR)) SymReaper.markLive(SymR->getSymbol()); for (ClusterBindings::iterator I = C->begin(), E = C->end(); I != E; ++I) { // Element index of a binding key is live. SymReaper.markElementIndicesLive(I.getKey().getRegion()); VisitBinding(I.getData()); } } void removeDeadBindingsWorker::VisitBinding(SVal V) { // Is it a LazyCompoundVal? All referenced regions are live as well. if (Optional<nonloc::LazyCompoundVal> LCS = V.getAs<nonloc::LazyCompoundVal>()) { const RegionStoreManager::SValListTy &Vals = RM.getInterestingValues(*LCS); for (RegionStoreManager::SValListTy::const_iterator I = Vals.begin(), E = Vals.end(); I != E; ++I) VisitBinding(*I); return; } // If V is a region, then add it to the worklist. if (const MemRegion *R = V.getAsRegion()) { AddToWorkList(R); SymReaper.markLive(R); // All regions captured by a block are also live. if (const BlockDataRegion *BR = dyn_cast<BlockDataRegion>(R)) { BlockDataRegion::referenced_vars_iterator I = BR->referenced_vars_begin(), E = BR->referenced_vars_end(); for ( ; I != E; ++I) AddToWorkList(I.getCapturedRegion()); } } // Update the set of live symbols. for (SymExpr::symbol_iterator SI = V.symbol_begin(), SE = V.symbol_end(); SI!=SE; ++SI) SymReaper.markLive(*SI); } bool removeDeadBindingsWorker::UpdatePostponed() { // See if any postponed SymbolicRegions are actually live now, after // having done a scan. bool changed = false; for (SmallVectorImpl<const SymbolicRegion*>::iterator I = Postponed.begin(), E = Postponed.end() ; I != E ; ++I) { if (const SymbolicRegion *SR = *I) { if (SymReaper.isLive(SR->getSymbol())) { changed |= AddToWorkList(SR); *I = nullptr; } } } return changed; } StoreRef RegionStoreManager::removeDeadBindings(Store store, const StackFrameContext *LCtx, SymbolReaper& SymReaper) { RegionBindingsRef B = getRegionBindings(store); removeDeadBindingsWorker W(*this, StateMgr, B, SymReaper, LCtx); W.GenerateClusters(); // Enqueue the region roots onto the worklist. for (SymbolReaper::region_iterator I = SymReaper.region_begin(), E = SymReaper.region_end(); I != E; ++I) { W.AddToWorkList(*I); } do W.RunWorkList(); while (W.UpdatePostponed()); // We have now scanned the store, marking reachable regions and symbols // as live. We now remove all the regions that are dead from the store // as well as update DSymbols with the set symbols that are now dead. for (RegionBindingsRef::iterator I = B.begin(), E = B.end(); I != E; ++I) { const MemRegion *Base = I.getKey(); // If the cluster has been visited, we know the region has been marked. if (W.isVisited(Base)) continue; // Remove the dead entry. B = B.remove(Base); if (const SymbolicRegion *SymR = dyn_cast<SymbolicRegion>(Base)) SymReaper.maybeDead(SymR->getSymbol()); // Mark all non-live symbols that this binding references as dead. const ClusterBindings &Cluster = I.getData(); for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end(); CI != CE; ++CI) { SVal X = CI.getData(); SymExpr::symbol_iterator SI = X.symbol_begin(), SE = X.symbol_end(); for (; SI != SE; ++SI) SymReaper.maybeDead(*SI); } } return StoreRef(B.asStore(), *this); } //===----------------------------------------------------------------------===// // Utility methods. //===----------------------------------------------------------------------===// void RegionStoreManager::print(Store store, raw_ostream &OS, const char* nl, const char *sep) { RegionBindingsRef B = getRegionBindings(store); OS << "Store (direct and default bindings), " << B.asStore() << " :" << nl; B.dump(OS, nl); }
{ "content_hash": "4eb4632b6730a95ee4bbcaea48a92c6a", "timestamp": "", "source": "github", "line_count": 2470, "max_line_length": 85, "avg_line_length": 36.75546558704453, "alnum_prop": 0.6288965258960633, "repo_name": "ensemblr/llvm-project-boilerplate", "id": "934cc5cd3ac466716c120f93ae9e3a5185871c79", "size": "90786", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "include/llvm/tools/clang/lib/StaticAnalyzer/Core/RegionStore.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "32" }, { "name": "AppleScript", "bytes": "1429" }, { "name": "Assembly", "bytes": "15649629" }, { "name": "Awk", "bytes": "1747037" }, { "name": "Batchfile", "bytes": "34481" }, { "name": "Brainfuck", "bytes": "284" }, { "name": "C", "bytes": "85584624" }, { "name": "C#", "bytes": "20737" }, { "name": "C++", "bytes": "168418524" }, { "name": "CMake", "bytes": "1174816" }, { "name": "CSS", "bytes": "49900" }, { "name": "Cuda", "bytes": "414703" }, { "name": "Emacs Lisp", "bytes": "110018" }, { "name": "Forth", "bytes": "1490" }, { "name": "Fortran", "bytes": "356707" }, { "name": "GAP", "bytes": "6167" }, { "name": "Go", "bytes": "132137" }, { "name": "HTML", "bytes": "1751124" }, { "name": "JavaScript", "bytes": "141512" }, { "name": "LLVM", "bytes": "62219250" }, { "name": "Limbo", "bytes": "7437" }, { "name": "Logos", "bytes": "1572537943" }, { "name": "Lua", "bytes": "86606" }, { "name": "M", "bytes": "2008" }, { "name": "M4", "bytes": "109560" }, { "name": "Makefile", "bytes": "616437" }, { "name": "Mathematica", "bytes": "7845" }, { "name": "Matlab", "bytes": "53817" }, { "name": "Mercury", "bytes": "1194" }, { "name": "Mirah", "bytes": "1079943" }, { "name": "OCaml", "bytes": "407143" }, { "name": "Objective-C", "bytes": "5910944" }, { "name": "Objective-C++", "bytes": "1720450" }, { "name": "OpenEdge ABL", "bytes": "690534" }, { "name": "PHP", "bytes": "15986" }, { "name": "POV-Ray SDL", "bytes": "19471" }, { "name": "Perl", "bytes": "591927" }, { "name": "PostScript", "bytes": "845774" }, { "name": "Protocol Buffer", "bytes": "20013" }, { "name": "Python", "bytes": "1895427" }, { "name": "QMake", "bytes": "15580" }, { "name": "RenderScript", "bytes": "741" }, { "name": "Roff", "bytes": "94555" }, { "name": "Rust", "bytes": "200" }, { "name": "Scheme", "bytes": "2654" }, { "name": "Shell", "bytes": "1144090" }, { "name": "Smalltalk", "bytes": "144607" }, { "name": "SourcePawn", "bytes": "1544" }, { "name": "Standard ML", "bytes": "2841" }, { "name": "Tcl", "bytes": "8285" }, { "name": "TeX", "bytes": "320484" }, { "name": "Vim script", "bytes": "17239" }, { "name": "Yacc", "bytes": "163484" } ] }
End of preview.

No dataset card yet

Downloads last month
5