text
stringlengths
4
5.48M
meta
stringlengths
14
6.54k
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>stalmarck: 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.1 / stalmarck - 8.6.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> stalmarck <small> 8.6.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-05-02 22:22:55 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-05-02 22:22:55 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.1 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.07.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.07.1 Official release 4.07.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.3 A library manager for OCaml zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;[email protected]&quot; homepage: &quot;https://github.com/coq-community/stalmarck&quot; license: &quot;LGPL 2.1&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Stalmarck&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.6&quot; &amp; &lt; &quot;8.7~&quot;} ] tags: [ &quot;keyword: boolean formula&quot; &quot;keyword: tautology checker&quot; &quot;category: Computer Science/Decision Procedures and Certified Algorithms/Decision procedures&quot; &quot;category: Miscellaneous/Extracted Programs/Decision procedures&quot; &quot;date: 2000&quot; ] authors: [ &quot;Pierre Letouzey&quot; &quot;Laurent Théry&quot; ] bug-reports: &quot;https://github.com/coq-community/stalmarck/issues&quot; dev-repo: &quot;git+https://github.com/coq-community/stalmarck.git&quot; synopsis: &quot;Proof of Stalmarck&#39;s algorithm&quot; description: &quot;&quot;&quot; A two-level approach to prove tautology using Stalmarck&#39;s algorithm.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-community/stalmarck/archive/v8.6.0.tar.gz&quot; checksum: &quot;md5=5d5b5316fd65d219d53014f465dfa340&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-stalmarck.8.6.0 coq.8.13.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.13.1). The following dependencies couldn&#39;t be met: - coq-stalmarck -&gt; coq &lt; 8.7~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-stalmarck.8.6.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{'content_hash': 'b935021b67970a8c24eb49d301ce0e62', 'timestamp': '', 'source': 'github', 'line_count': 164, 'max_line_length': 287, 'avg_line_length': 42.86585365853659, 'alnum_prop': 0.5477951635846373, 'repo_name': 'coq-bench/coq-bench.github.io', 'id': 'db52d37fbab8b74df0346bb1653cee1dd4fe0135', 'size': '7056', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'clean/Linux-x86_64-4.07.1-2.0.6/released/8.13.1/stalmarck/8.6.0.html', 'mode': '33188', 'license': 'mit', 'language': []}
<?php namespace Polymath\Conversions\Temperature\Test; use PHPUnit_Framework_TestCase; class Temperature extends PHPUnit_Framework_TestCase { /** * @dataProvider getTestCelsius2FahrenheitData **/ public function testCelsius2Fahrenheit($temp, $expected) { $temperature = new \Polymath\Conversions\Temperature\Temperature(); $result = $temperature->Celsius2Fahrenheit($temp); $this->assertEquals($result, $expected, 'Convert degrees Celsius to degrees Fahrenheit'); } public function getTestCelsius2FahrenheitData() { return array( array(0, 32.0), array(1, 33.8), array(3, 37.4), array(100, 212.0) ); } /** * @dataProvider getTestFahrenheit2CelsiusData **/ public function testFahrenheit2Celsius($temp, $expected) { $temperature = new \Polymath\Conversions\Temperature\Temperature(); $result = $temperature->Fahrenheit2Celsius($temp); $this->assertEquals($result, $expected, 'Convert degrees Fahrenheit to degress Celsius'); } public function getTestFahrenheit2CelsiusData() { return array( array(32, 0.0), array(72, 22.222222222222), array(212, 100.0) ); } }
{'content_hash': '2a3f47af45a93a550d559cd783abc64d', 'timestamp': '', 'source': 'github', 'line_count': 47, 'max_line_length': 98, 'avg_line_length': 27.80851063829787, 'alnum_prop': 0.6235654169854629, 'repo_name': 'sanderblue/polymath', 'id': '808ba917b17b22b1fbb90786ec62b0c6bfc4a874', 'size': '1307', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tests/Polymath/Test/Conversions/Temperature/TemperatureTest.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '82056'}]}
<ul class="project"> <li class="project-info"> <span class="project-year">{{ vm.project.startYear + ' - ' + vm.project.endYear }}</span> <img ng-src="{{ vm.customizations.logos.institute.src }}" ng-if="vm.showIITLogo()" class="icon-iit"/> </li> <li class="project-metadata"> <div> <scientilla-project-type-badge type="vm.project.type"></scientilla-project-type-badge> <scientilla-research-item-authors research-item="vm.project" collapsed="vm.collapsed" type="preview" ></scientilla-research-item-authors> </div> <ul ng-if="vm.project.labels" class="project-labels" > <li ng-repeat="l in vm.project.labels"> <badge label="l"></badge> </li> </ul> <h2 class="project-title has-action" ng-click="vm.openDetails()" ng-bind-html='vm.project | title' ></h2> <!-- Only for industrial projects --> <ng-container ng-if="vm.project.typeKey === vm.projectTypeIndustrial"> <ng-container ng-if="vm.project.payment"> <strong>Payment:</strong> {{ vm.project.payment }} <span class="project-payment" ng-class="vm.project.payment"></span><br> </ng-container> <ng-container ng-if="vm.project.status"> <strong>Status:</strong> {{ vm.project.status }} <span class="project-status" ng-class="vm.project.status"></span><br> </ng-container> </ng-container> <!-- Only for competitive projects --> <ng-container ng-if="vm.project.typeKey === vm.projectTypeCompetitive"> <ng-container ng-if="vm.project.acronym"> <strong>Acronym:</strong> {{ vm.project.acronym }}<br> </ng-container> <ng-container ng-if="vm.project.role"> <strong>IIT role:</strong> {{ vm.project.role }}<br> </ng-container> <ng-container ng-if="vm.project.status"> <strong>Status:</strong> {{ vm.project.status }} <span class="project-status" ng-class="vm.project.status"></span><br> </ng-container> </ng-container> <ul class="project-actions"> <li ng-if="vm.project.verified.length" class="project-verified" uib-tooltip-html="vm.getVerifiedNamesHTML()" tooltip-class="text-left"> <i class="fas fa-check"></i> {{ vm.project.verified.length }} </li> <li ng-if="vm.isPrivacyToShow()" class="project-privacy-actions"> <i ng-click="vm.changePrivacy()" ng-if="vm.isPublic()" class="fas fa-globe-africa has-action" uib-tooltip-html="'The project is visible to everyone, click to change it'"></i> <i ng-click="vm.changePrivacy()" ng-if="!vm.isPublic()" class="fas fa-lock has-action" uib-tooltip-html="'The project is visible only to scientilla users, click to change it'"></i> </li> <li ng-if="vm.isFavoriteToShow()" class="project-favorite-actions"> <i ng-click="vm.changeFavorite()" ng-if="vm.isFavorite()" class="fas fa-star has-action" uib-tooltip-html="'This project is one of your favorite'"></i> <i ng-click="vm.changeFavorite()" ng-if="!vm.isFavorite()" class="far fa-star has-action" uib-tooltip-html="'Click here to make it favorite'"></i> </li> </ul> </li> </ul>
{'content_hash': 'c23e5d4e778778d595508be034df3266', 'timestamp': '', 'source': 'github', 'line_count': 99, 'max_line_length': 112, 'avg_line_length': 40.484848484848484, 'alnum_prop': 0.49550898203592814, 'repo_name': 'scientilla/scientilla', 'id': '4ed953cb5bb766f4720764b10ff0b5dabdf386f8', 'size': '4008', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'assets/js/app/projects/scientilla-project.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '434'}, {'name': 'CSS', 'bytes': '306886'}, {'name': 'Dockerfile', 'bytes': '959'}, {'name': 'EJS', 'bytes': '106296'}, {'name': 'HTML', 'bytes': '629792'}, {'name': 'JavaScript', 'bytes': '2089203'}, {'name': 'Pug', 'bytes': '115'}, {'name': 'SCSS', 'bytes': '218462'}, {'name': 'Shell', 'bytes': '1289'}]}
<?php namespace Tapestry\Entities\Filesystem; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Console\Output\OutputInterface; class FileWriter extends FileAction implements FilesystemInterface { /** * @param Filesystem $filesystem * @param OutputInterface $output * * @return void */ public function __invoke(Filesystem $filesystem, OutputInterface $output) { $outputPath = $this->file->getCompiledPermalink(); $output->writeln('[+] Writing File ['.$this->file->getUid().'] to path ['.$outputPath.']'); $filesystem->dumpFile($this->destinationPath.DIRECTORY_SEPARATOR.$outputPath, $this->file->getContent()); } }
{'content_hash': '2df8d7310769f832d632ea114ae2fd59', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 113, 'avg_line_length': 32.04545454545455, 'alnum_prop': 0.6836879432624113, 'repo_name': 'tapestry-cloud/tapestry', 'id': '3ec4dc82586d0c7732d0b01ce838b8b779ddced1', 'size': '705', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/Entities/Filesystem/FileWriter.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '38'}, {'name': 'CSS', 'bytes': '299'}, {'name': 'HTML', 'bytes': '12944'}, {'name': 'Hack', 'bytes': '12'}, {'name': 'JavaScript', 'bytes': '953'}, {'name': 'PHP', 'bytes': '303653'}, {'name': 'Shell', 'bytes': '1786'}]}
function fileTest2Js() { return "File: test2.js"; }
{'content_hash': '3852bd0dabbff8099b497c36f2915637', 'timestamp': '', 'source': 'github', 'line_count': 3, 'max_line_length': 26, 'avg_line_length': 18.0, 'alnum_prop': 0.6666666666666666, 'repo_name': 'intervalia/gulp-component-assembler', 'id': '4d50ea689fc09a9950863382bc5942f3f75b27e5', 'size': '54', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'sampleAssembly/src/test2.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '1427'}, {'name': 'JavaScript', 'bytes': '126689'}]}
package org.jboss.modules.filter; /** * Filter used to determine whether a path should be included or excluded from imports and exports. * * @author John Bailey */ public interface PathFilter { /** * Determine whether a path should be accepted. The given name is a path separated * by "{@code /}" characters. * * @param path the path to check * @return true if the path should be accepted, false if not */ boolean accept(String path); /** * Calculate a unique hash code for this path filter. Equal path filters must yield identical hash codes. * * @return the hash code */ int hashCode(); /** * Determine whether this filter is equal to another. Filters must implement meaningful (non-identity) equality * semantics. * * @param other the other object * @return {@code true} if this filter is the same */ boolean equals(Object other); }
{'content_hash': '42a1748f94d2d92010489d6392ea9c8c', 'timestamp': '', 'source': 'github', 'line_count': 36, 'max_line_length': 116, 'avg_line_length': 26.444444444444443, 'alnum_prop': 0.6470588235294118, 'repo_name': 'Sanne/jboss-modules', 'id': 'e7f0e36225e9c621ef22f4dd387b460bcf7145e2', 'size': '1658', 'binary': False, 'copies': '11', 'ref': 'refs/heads/master', 'path': 'src/main/java/org/jboss/modules/filter/PathFilter.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '1160118'}]}
module AvatarExpectations def resource_file(name) File.expand_path("../../fixtures/#{name}", __FILE__) end def assert_image_equality(actual_image_blob, expected_image_name, hamming_distance = 2) actual_image_path = resource_file('temp_generated_image.png') expected_image_path = resource_file("#{expected_image_name}.png") File.open(actual_image_path, 'wb') do |f| f.write actual_image_blob end actual_image = Phashion::Image.new(actual_image_path) expected_image = Phashion::Image.new(expected_image_path) result = actual_image.duplicate?(expected_image, threshold: hamming_distance) unless result puts "Hamming distance between two images: #{actual_image.distance_from(expected_image)}. Required at least #{hamming_distance}." end expect(result).to be true File.delete(actual_image_path) end def assert_image_format(image, format) temp_file = Tempfile.new('avatarly') File.open(temp_file, 'wb') do |f| f.write image end expect(FastImage.type(temp_file)).to eql(format) end end
{'content_hash': '10953ad5c5a309013ad606668e7e5f00', 'timestamp': '', 'source': 'github', 'line_count': 36, 'max_line_length': 135, 'avg_line_length': 30.055555555555557, 'alnum_prop': 0.6903881700554528, 'repo_name': 'ArturT/avatarly', 'id': '08b269e7331d7be520d72bdb689c64597dce8fd8', 'size': '1082', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'spec/support/avatar_expectations.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '9262'}]}
START_ATF_NAMESPACE namespace Register { class _DELPOST_DB_BASERegister : public IRegister { public: void Register() override { auto& hook_core = CATFCore::get_instance(); for (auto& r : Detail::_DELPOST_DB_BASE_functions) hook_core.reg_wrapper(r.pBind, r); } }; }; // end namespace Register END_ATF_NAMESPACE
{'content_hash': 'a70dff3a1997cc125ecbcfb5f5bfb595', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 70, 'avg_line_length': 31.4, 'alnum_prop': 0.4840764331210191, 'repo_name': 'goodwinxp/Yorozuya', 'id': '36f5a280efeba94f817a3f0248c5cb96885f5c1e', 'size': '691', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'library/ATF/_DELPOST_DB_BASERegister.hpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '207291'}, {'name': 'C++', 'bytes': '21670817'}]}
namespace Labo.TwitterMiner.Services { using Labo.TwitterMiner.Entity; public interface ITwitterCrawlHistoryService { TwitterCrawlHistory GetLastCrawlStatistics(string query); void InsertIntoCrawlHistory(long startTweetID, long endTweetID, string hashTag); } }
{'content_hash': '1974735d64d794b50a7656f30dca27da', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 88, 'avg_line_length': 26.727272727272727, 'alnum_prop': 0.7585034013605442, 'repo_name': 'LaboFoundation/Labo.TwitterMiner', 'id': '515516eb6d9100ef1a46853a082cc6b7a98ec5f1', 'size': '294', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Labo.TwitterMiner/Services/ITwitterCrawlHistoryService.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '104308'}]}
import unittest2 try: # pylint: disable=unused-import import gcloud.pubsub._gax # pylint: enable=unused-import except ImportError: # pragma: NO COVER _HAVE_GAX = False else: _HAVE_GAX = True class _Base(object): PROJECT = 'PROJECT' PROJECT_PATH = 'projects/%s' % (PROJECT,) FILTER = 'logName:syslog AND severity>=ERROR' def _makeOne(self, *args, **kw): return self._getTargetClass()(*args, **kw) @unittest2.skipUnless(_HAVE_GAX, 'No gax-python') class Test_LoggingAPI(_Base, unittest2.TestCase): LOG_NAME = 'log_name' def _getTargetClass(self): from gcloud.logging._gax import _LoggingAPI return _LoggingAPI def test_ctor(self): gax_api = _GAXLoggingAPI() api = self._makeOne(gax_api) self.assertTrue(api._gax_api is gax_api) def test_list_entries_no_paging(self): from google.gax import INITIAL_PAGE from gcloud.logging import DESCENDING from gcloud._testing import _GAXPageIterator TOKEN = 'TOKEN' TEXT = 'TEXT' response = _GAXPageIterator( [_LogEntryPB(self.LOG_NAME, text_payload=TEXT)], TOKEN) gax_api = _GAXLoggingAPI(_list_log_entries_response=response) api = self._makeOne(gax_api) entries, next_token = api.list_entries( [self.PROJECT], self.FILTER, DESCENDING) self.assertEqual(len(entries), 1) entry = entries[0] self.assertIsInstance(entry, dict) self.assertEqual(entry['logName'], self.LOG_NAME) self.assertEqual(entry['resource'], {'type': 'global'}) self.assertEqual(entry['textPayload'], TEXT) self.assertEqual(next_token, TOKEN) projects, filter_, order_by, page_size, options = ( gax_api._list_log_entries_called_with) self.assertEqual(projects, [self.PROJECT]) self.assertEqual(filter_, self.FILTER) self.assertEqual(order_by, DESCENDING) self.assertEqual(page_size, 0) self.assertTrue(options.page_token is INITIAL_PAGE) def test_list_entries_with_paging(self): from gcloud._testing import _GAXPageIterator SIZE = 23 TOKEN = 'TOKEN' NEW_TOKEN = 'NEW_TOKEN' PAYLOAD = {'message': 'MESSAGE', 'weather': 'sunny'} response = _GAXPageIterator( [_LogEntryPB(self.LOG_NAME, json_payload=PAYLOAD)], NEW_TOKEN) gax_api = _GAXLoggingAPI(_list_log_entries_response=response) api = self._makeOne(gax_api) entries, next_token = api.list_entries( [self.PROJECT], page_size=SIZE, page_token=TOKEN) self.assertEqual(len(entries), 1) entry = entries[0] self.assertIsInstance(entry, dict) self.assertEqual(entry['logName'], self.LOG_NAME) self.assertEqual(entry['resource'], {'type': 'global'}) self.assertEqual(entry['jsonPayload'], PAYLOAD) self.assertEqual(next_token, NEW_TOKEN) projects, filter_, order_by, page_size, options = ( gax_api._list_log_entries_called_with) self.assertEqual(projects, [self.PROJECT]) self.assertEqual(filter_, '') self.assertEqual(order_by, '') self.assertEqual(page_size, SIZE) self.assertEqual(options.page_token, TOKEN) def test_list_entries_with_extra_properties(self): from datetime import datetime from gcloud._testing import _GAXPageIterator from gcloud._helpers import UTC from gcloud._helpers import _datetime_to_rfc3339 from gcloud._helpers import _datetime_to_pb_timestamp NOW = datetime.utcnow().replace(tzinfo=UTC) SIZE = 23 TOKEN = 'TOKEN' NEW_TOKEN = 'NEW_TOKEN' PAYLOAD = {'message': 'MESSAGE', 'weather': 'sunny'} SEVERITY = 'WARNING' LABELS = { 'foo': 'bar', } IID = 'IID' request = _HTTPRequestPB() operation = _LogEntryOperationPB() EXTRAS = { 'severity': SEVERITY, 'labels': LABELS, 'insert_id': IID, 'http_request': request, 'operation': operation, } ENTRY = _LogEntryPB(self.LOG_NAME, proto_payload=PAYLOAD, **EXTRAS) ENTRY.resource.labels['foo'] = 'bar' ENTRY.timestamp = _datetime_to_pb_timestamp(NOW) response = _GAXPageIterator([ENTRY], NEW_TOKEN) gax_api = _GAXLoggingAPI(_list_log_entries_response=response) api = self._makeOne(gax_api) entries, next_token = api.list_entries( [self.PROJECT], page_size=SIZE, page_token=TOKEN) self.assertEqual(len(entries), 1) entry = entries[0] self.assertIsInstance(entry, dict) self.assertEqual(entry['logName'], self.LOG_NAME) self.assertEqual(entry['resource'], {'type': 'global', 'labels': {'foo': 'bar'}}) self.assertEqual(entry['protoPayload'], PAYLOAD) self.assertEqual(entry['severity'], SEVERITY) self.assertEqual(entry['labels'], LABELS) self.assertEqual(entry['insertId'], IID) self.assertEqual(entry['timestamp'], _datetime_to_rfc3339(NOW)) EXPECTED_REQUEST = { 'request_method': request.request_method, 'request_url': request.request_url, 'status': request.status, 'request_size': request.request_size, 'response_size': request.response_size, 'referer': request.referer, 'user_agent': request.user_agent, 'remote_ip': request.remote_ip, 'cache_hit': request.cache_hit, } self.assertEqual(entry['httpRequest'], EXPECTED_REQUEST) EXPECTED_OPERATION = { 'producer': operation.producer, 'id': operation.id, 'first': operation.first, 'last': operation.last, } self.assertEqual(entry['operation'], EXPECTED_OPERATION) self.assertEqual(next_token, NEW_TOKEN) projects, filter_, order_by, page_size, options = ( gax_api._list_log_entries_called_with) self.assertEqual(projects, [self.PROJECT]) self.assertEqual(filter_, '') self.assertEqual(order_by, '') self.assertEqual(page_size, SIZE) self.assertEqual(options.page_token, TOKEN) def test_write_entries_single(self): from google.logging.v2.log_entry_pb2 import LogEntry TEXT = 'TEXT' LOG_PATH = 'projects/%s/logs/%s' % (self.PROJECT, self.LOG_NAME) ENTRY = { 'logName': LOG_PATH, 'resource': {'type': 'global'}, 'textPayload': TEXT, } gax_api = _GAXLoggingAPI() api = self._makeOne(gax_api) api.write_entries([ENTRY]) entries, log_name, resource, labels, partial_success, options = ( gax_api._write_log_entries_called_with) self.assertEqual(len(entries), 1) entry = entries[0] self.assertTrue(isinstance(entry, LogEntry)) self.assertEqual(entry.log_name, LOG_PATH) self.assertEqual(entry.resource.type, 'global') self.assertEqual(entry.labels, {}) self.assertEqual(entry.text_payload, TEXT) self.assertEqual(log_name, None) self.assertEqual(resource, None) self.assertEqual(labels, None) self.assertEqual(partial_success, False) self.assertEqual(options, None) def test_write_entries_w_extra_properties(self): # pylint: disable=too-many-statements from datetime import datetime from google.logging.type.log_severity_pb2 import WARNING from google.logging.v2.log_entry_pb2 import LogEntry from gcloud._helpers import UTC, _pb_timestamp_to_datetime NOW = datetime.utcnow().replace(tzinfo=UTC) TEXT = 'TEXT' LOG_PATH = 'projects/%s/logs/%s' % (self.PROJECT, self.LOG_NAME) SEVERITY = 'WARNING' LABELS = { 'foo': 'bar', } IID = 'IID' REQUEST_METHOD = 'GET' REQUEST_URL = 'http://example.com/requested' STATUS = 200 REQUEST_SIZE = 256 RESPONSE_SIZE = 1024 REFERRER_URL = 'http://example.com/referer' USER_AGENT = 'Agent/1.0' REMOTE_IP = '1.2.3.4' REQUEST = { 'requestMethod': REQUEST_METHOD, 'requestUrl': REQUEST_URL, 'status': STATUS, 'requestSize': REQUEST_SIZE, 'responseSize': RESPONSE_SIZE, 'referer': REFERRER_URL, 'userAgent': USER_AGENT, 'remoteIp': REMOTE_IP, 'cacheHit': False, } PRODUCER = 'PRODUCER' OPID = 'OPID' OPERATION = { 'producer': PRODUCER, 'id': OPID, 'first': False, 'last': True, } ENTRY = { 'logName': LOG_PATH, 'resource': {'type': 'global'}, 'textPayload': TEXT, 'severity': SEVERITY, 'labels': LABELS, 'insertId': IID, 'timestamp': NOW, 'httpRequest': REQUEST, 'operation': OPERATION, } gax_api = _GAXLoggingAPI() api = self._makeOne(gax_api) api.write_entries([ENTRY]) entries, log_name, resource, labels, partial_success, options = ( gax_api._write_log_entries_called_with) self.assertEqual(len(entries), 1) entry = entries[0] self.assertTrue(isinstance(entry, LogEntry)) self.assertEqual(entry.log_name, LOG_PATH) self.assertEqual(entry.resource.type, 'global') self.assertEqual(entry.text_payload, TEXT) self.assertEqual(entry.severity, WARNING) self.assertEqual(entry.labels, LABELS) self.assertEqual(entry.insert_id, IID) stamp = _pb_timestamp_to_datetime(entry.timestamp) self.assertEqual(stamp, NOW) request = entry.http_request self.assertEqual(request.request_method, REQUEST_METHOD) self.assertEqual(request.request_url, REQUEST_URL) self.assertEqual(request.status, STATUS) self.assertEqual(request.request_size, REQUEST_SIZE) self.assertEqual(request.response_size, RESPONSE_SIZE) self.assertEqual(request.referer, REFERRER_URL) self.assertEqual(request.user_agent, USER_AGENT) self.assertEqual(request.remote_ip, REMOTE_IP) self.assertEqual(request.cache_hit, False) operation = entry.operation self.assertEqual(operation.producer, PRODUCER) self.assertEqual(operation.id, OPID) self.assertFalse(operation.first) self.assertTrue(operation.last) self.assertEqual(log_name, None) self.assertEqual(resource, None) self.assertEqual(labels, None) self.assertEqual(partial_success, False) self.assertEqual(options, None) # pylint: enable=too-many-statements def test_write_entries_multiple(self): # pylint: disable=too-many-statements import datetime from google.logging.type.log_severity_pb2 import WARNING from google.logging.v2.log_entry_pb2 import LogEntry from google.protobuf.any_pb2 import Any from google.protobuf.struct_pb2 import Struct from gcloud._helpers import _datetime_to_rfc3339, UTC TEXT = 'TEXT' NOW = datetime.datetime.utcnow().replace(tzinfo=UTC) TIMESTAMP_TYPE_URL = 'type.googleapis.com/google.protobuf.Timestamp' JSON = {'payload': 'PAYLOAD', 'type': 'json'} PROTO = { '@type': TIMESTAMP_TYPE_URL, 'value': _datetime_to_rfc3339(NOW), } PRODUCER = 'PRODUCER' OPID = 'OPID' URL = 'http://example.com/' ENTRIES = [ {'textPayload': TEXT, 'severity': WARNING}, {'jsonPayload': JSON, 'operation': {'producer': PRODUCER, 'id': OPID}}, {'protoPayload': PROTO, 'httpRequest': {'requestUrl': URL}}, ] LOG_PATH = 'projects/%s/logs/%s' % (self.PROJECT, self.LOG_NAME) RESOURCE = { 'type': 'global', } LABELS = { 'foo': 'bar', } gax_api = _GAXLoggingAPI() api = self._makeOne(gax_api) api.write_entries(ENTRIES, LOG_PATH, RESOURCE, LABELS) entries, log_name, resource, labels, partial_success, options = ( gax_api._write_log_entries_called_with) self.assertEqual(len(entries), len(ENTRIES)) entry = entries[0] self.assertTrue(isinstance(entry, LogEntry)) self.assertEqual(entry.log_name, '') self.assertEqual(entry.resource.type, '') self.assertEqual(entry.labels, {}) self.assertEqual(entry.text_payload, TEXT) self.assertEqual(entry.severity, WARNING) entry = entries[1] self.assertTrue(isinstance(entry, LogEntry)) self.assertEqual(entry.log_name, '') self.assertEqual(entry.resource.type, '') self.assertEqual(entry.labels, {}) json_struct = entry.json_payload self.assertTrue(isinstance(json_struct, Struct)) self.assertEqual(json_struct.fields['payload'].string_value, JSON['payload']) operation = entry.operation self.assertEqual(operation.producer, PRODUCER) self.assertEqual(operation.id, OPID) entry = entries[2] self.assertTrue(isinstance(entry, LogEntry)) self.assertEqual(entry.log_name, '') self.assertEqual(entry.resource.type, '') self.assertEqual(entry.labels, {}) proto = entry.proto_payload self.assertTrue(isinstance(proto, Any)) self.assertEqual(proto.type_url, TIMESTAMP_TYPE_URL) request = entry.http_request self.assertEqual(request.request_url, URL) self.assertEqual(log_name, LOG_PATH) self.assertEqual(resource, RESOURCE) self.assertEqual(labels, LABELS) self.assertEqual(partial_success, False) self.assertEqual(options, None) # pylint: enable=too-many-statements def test_logger_delete(self): LOG_PATH = 'projects/%s/logs/%s' % (self.PROJECT, self.LOG_NAME) gax_api = _GAXLoggingAPI() api = self._makeOne(gax_api) api.logger_delete(self.PROJECT, self.LOG_NAME) log_name, options = gax_api._delete_log_called_with self.assertEqual(log_name, LOG_PATH) self.assertEqual(options, None) @unittest2.skipUnless(_HAVE_GAX, 'No gax-python') class Test_SinksAPI(_Base, unittest2.TestCase): SINK_NAME = 'sink_name' SINK_PATH = 'projects/%s/sinks/%s' % (_Base.PROJECT, SINK_NAME) DESTINATION_URI = 'faux.googleapis.com/destination' def _getTargetClass(self): from gcloud.logging._gax import _SinksAPI return _SinksAPI def test_ctor(self): gax_api = _GAXSinksAPI() api = self._makeOne(gax_api) self.assertTrue(api._gax_api is gax_api) def test_list_sinks_no_paging(self): from google.gax import INITIAL_PAGE from gcloud._testing import _GAXPageIterator TOKEN = 'TOKEN' SINKS = [{ 'name': self.SINK_PATH, 'filter': self.FILTER, 'destination': self.DESTINATION_URI, }] response = _GAXPageIterator( [_LogSinkPB(self.SINK_PATH, self.DESTINATION_URI, self.FILTER)], TOKEN) gax_api = _GAXSinksAPI(_list_sinks_response=response) api = self._makeOne(gax_api) sinks, token = api.list_sinks(self.PROJECT) self.assertEqual(sinks, SINKS) self.assertEqual(token, TOKEN) project, page_size, options = gax_api._list_sinks_called_with self.assertEqual(project, self.PROJECT) self.assertEqual(page_size, 0) self.assertEqual(options.page_token, INITIAL_PAGE) def test_list_sinks_w_paging(self): from gcloud._testing import _GAXPageIterator TOKEN = 'TOKEN' PAGE_SIZE = 42 SINKS = [{ 'name': self.SINK_PATH, 'filter': self.FILTER, 'destination': self.DESTINATION_URI, }] response = _GAXPageIterator( [_LogSinkPB(self.SINK_PATH, self.DESTINATION_URI, self.FILTER)], None) gax_api = _GAXSinksAPI(_list_sinks_response=response) api = self._makeOne(gax_api) sinks, token = api.list_sinks( self.PROJECT, page_size=PAGE_SIZE, page_token=TOKEN) self.assertEqual(sinks, SINKS) self.assertEqual(token, None) project, page_size, options = gax_api._list_sinks_called_with self.assertEqual(project, self.PROJECT) self.assertEqual(page_size, PAGE_SIZE) self.assertEqual(options.page_token, TOKEN) def test_sink_create_error(self): from google.gax.errors import GaxError gax_api = _GAXSinksAPI(_random_gax_error=True) api = self._makeOne(gax_api) with self.assertRaises(GaxError): api.sink_create( self.PROJECT, self.SINK_NAME, self.FILTER, self.DESTINATION_URI) def test_sink_create_conflict(self): from gcloud.exceptions import Conflict gax_api = _GAXSinksAPI(_create_sink_conflict=True) api = self._makeOne(gax_api) with self.assertRaises(Conflict): api.sink_create( self.PROJECT, self.SINK_NAME, self.FILTER, self.DESTINATION_URI) def test_sink_create_ok(self): from google.logging.v2.logging_config_pb2 import LogSink gax_api = _GAXSinksAPI() api = self._makeOne(gax_api) api.sink_create( self.PROJECT, self.SINK_NAME, self.FILTER, self.DESTINATION_URI) parent, sink, options = ( gax_api._create_sink_called_with) self.assertEqual(parent, self.PROJECT_PATH) self.assertTrue(isinstance(sink, LogSink)) self.assertEqual(sink.name, self.SINK_NAME) self.assertEqual(sink.filter, self.FILTER) self.assertEqual(sink.destination, self.DESTINATION_URI) self.assertEqual(options, None) def test_sink_get_error(self): from gcloud.exceptions import NotFound gax_api = _GAXSinksAPI() api = self._makeOne(gax_api) with self.assertRaises(NotFound): api.sink_get(self.PROJECT, self.SINK_NAME) def test_sink_get_miss(self): from google.gax.errors import GaxError gax_api = _GAXSinksAPI(_random_gax_error=True) api = self._makeOne(gax_api) with self.assertRaises(GaxError): api.sink_get(self.PROJECT, self.SINK_NAME) def test_sink_get_hit(self): RESPONSE = { 'name': self.SINK_PATH, 'filter': self.FILTER, 'destination': self.DESTINATION_URI, } sink_pb = _LogSinkPB( self.SINK_PATH, self.DESTINATION_URI, self.FILTER) gax_api = _GAXSinksAPI(_get_sink_response=sink_pb) api = self._makeOne(gax_api) response = api.sink_get(self.PROJECT, self.SINK_NAME) self.assertEqual(response, RESPONSE) sink_name, options = gax_api._get_sink_called_with self.assertEqual(sink_name, self.SINK_PATH) self.assertEqual(options, None) def test_sink_update_error(self): from google.gax.errors import GaxError gax_api = _GAXSinksAPI(_random_gax_error=True) api = self._makeOne(gax_api) with self.assertRaises(GaxError): api.sink_update( self.PROJECT, self.SINK_NAME, self.FILTER, self.DESTINATION_URI) def test_sink_update_miss(self): from gcloud.exceptions import NotFound gax_api = _GAXSinksAPI() api = self._makeOne(gax_api) with self.assertRaises(NotFound): api.sink_update( self.PROJECT, self.SINK_NAME, self.FILTER, self.DESTINATION_URI) def test_sink_update_hit(self): from google.logging.v2.logging_config_pb2 import LogSink response = _LogSinkPB( self.SINK_NAME, self.FILTER, self.DESTINATION_URI) gax_api = _GAXSinksAPI(_update_sink_response=response) api = self._makeOne(gax_api) api.sink_update( self.PROJECT, self.SINK_NAME, self.FILTER, self.DESTINATION_URI) sink_name, sink, options = ( gax_api._update_sink_called_with) self.assertEqual(sink_name, self.SINK_PATH) self.assertTrue(isinstance(sink, LogSink)) self.assertEqual(sink.name, self.SINK_PATH) self.assertEqual(sink.filter, self.FILTER) self.assertEqual(sink.destination, self.DESTINATION_URI) self.assertEqual(options, None) def test_sink_delete_error(self): from google.gax.errors import GaxError gax_api = _GAXSinksAPI(_random_gax_error=True) api = self._makeOne(gax_api) with self.assertRaises(GaxError): api.sink_delete(self.PROJECT, self.SINK_NAME) def test_sink_delete_miss(self): from gcloud.exceptions import NotFound gax_api = _GAXSinksAPI(_sink_not_found=True) api = self._makeOne(gax_api) with self.assertRaises(NotFound): api.sink_delete(self.PROJECT, self.SINK_NAME) def test_sink_delete_hit(self): gax_api = _GAXSinksAPI() api = self._makeOne(gax_api) api.sink_delete(self.PROJECT, self.SINK_NAME) sink_name, options = gax_api._delete_sink_called_with self.assertEqual(sink_name, self.SINK_PATH) self.assertEqual(options, None) @unittest2.skipUnless(_HAVE_GAX, 'No gax-python') class Test_MetricsAPI(_Base, unittest2.TestCase): METRIC_NAME = 'metric_name' METRIC_PATH = 'projects/%s/metrics/%s' % (_Base.PROJECT, METRIC_NAME) DESCRIPTION = 'Description' def _getTargetClass(self): from gcloud.logging._gax import _MetricsAPI return _MetricsAPI def test_ctor(self): gax_api = _GAXMetricsAPI() api = self._makeOne(gax_api) self.assertTrue(api._gax_api is gax_api) def test_list_metrics_no_paging(self): from google.gax import INITIAL_PAGE from gcloud._testing import _GAXPageIterator TOKEN = 'TOKEN' METRICS = [{ 'name': self.METRIC_PATH, 'filter': self.FILTER, 'description': self.DESCRIPTION, }] response = _GAXPageIterator( [_LogMetricPB(self.METRIC_PATH, self.DESCRIPTION, self.FILTER)], TOKEN) gax_api = _GAXMetricsAPI(_list_log_metrics_response=response) api = self._makeOne(gax_api) metrics, token = api.list_metrics(self.PROJECT) self.assertEqual(metrics, METRICS) self.assertEqual(token, TOKEN) project, page_size, options = gax_api._list_log_metrics_called_with self.assertEqual(project, self.PROJECT) self.assertEqual(page_size, 0) self.assertEqual(options.page_token, INITIAL_PAGE) def test_list_metrics_w_paging(self): from gcloud._testing import _GAXPageIterator TOKEN = 'TOKEN' PAGE_SIZE = 42 METRICS = [{ 'name': self.METRIC_PATH, 'filter': self.FILTER, 'description': self.DESCRIPTION, }] response = _GAXPageIterator( [_LogMetricPB(self.METRIC_PATH, self.DESCRIPTION, self.FILTER)], None) gax_api = _GAXMetricsAPI(_list_log_metrics_response=response) api = self._makeOne(gax_api) metrics, token = api.list_metrics( self.PROJECT, page_size=PAGE_SIZE, page_token=TOKEN) self.assertEqual(metrics, METRICS) self.assertEqual(token, None) project, page_size, options = gax_api._list_log_metrics_called_with self.assertEqual(project, self.PROJECT) self.assertEqual(page_size, PAGE_SIZE) self.assertEqual(options.page_token, TOKEN) def test_metric_create_error(self): from google.gax.errors import GaxError gax_api = _GAXMetricsAPI(_random_gax_error=True) api = self._makeOne(gax_api) with self.assertRaises(GaxError): api.metric_create( self.PROJECT, self.METRIC_NAME, self.FILTER, self.DESCRIPTION) def test_metric_create_conflict(self): from gcloud.exceptions import Conflict gax_api = _GAXMetricsAPI(_create_log_metric_conflict=True) api = self._makeOne(gax_api) with self.assertRaises(Conflict): api.metric_create( self.PROJECT, self.METRIC_NAME, self.FILTER, self.DESCRIPTION) def test_metric_create_ok(self): from google.logging.v2.logging_metrics_pb2 import LogMetric gax_api = _GAXMetricsAPI() api = self._makeOne(gax_api) api.metric_create( self.PROJECT, self.METRIC_NAME, self.FILTER, self.DESCRIPTION) parent, metric, options = ( gax_api._create_log_metric_called_with) self.assertEqual(parent, self.PROJECT_PATH) self.assertTrue(isinstance(metric, LogMetric)) self.assertEqual(metric.name, self.METRIC_NAME) self.assertEqual(metric.filter, self.FILTER) self.assertEqual(metric.description, self.DESCRIPTION) self.assertEqual(options, None) def test_metric_get_error(self): from gcloud.exceptions import NotFound gax_api = _GAXMetricsAPI() api = self._makeOne(gax_api) with self.assertRaises(NotFound): api.metric_get(self.PROJECT, self.METRIC_NAME) def test_metric_get_miss(self): from google.gax.errors import GaxError gax_api = _GAXMetricsAPI(_random_gax_error=True) api = self._makeOne(gax_api) with self.assertRaises(GaxError): api.metric_get(self.PROJECT, self.METRIC_NAME) def test_metric_get_hit(self): RESPONSE = { 'name': self.METRIC_PATH, 'filter': self.FILTER, 'description': self.DESCRIPTION, } metric_pb = _LogMetricPB( self.METRIC_PATH, self.DESCRIPTION, self.FILTER) gax_api = _GAXMetricsAPI(_get_log_metric_response=metric_pb) api = self._makeOne(gax_api) response = api.metric_get(self.PROJECT, self.METRIC_NAME) self.assertEqual(response, RESPONSE) metric_name, options = gax_api._get_log_metric_called_with self.assertEqual(metric_name, self.METRIC_PATH) self.assertEqual(options, None) def test_metric_update_error(self): from google.gax.errors import GaxError gax_api = _GAXMetricsAPI(_random_gax_error=True) api = self._makeOne(gax_api) with self.assertRaises(GaxError): api.metric_update( self.PROJECT, self.METRIC_NAME, self.FILTER, self.DESCRIPTION) def test_metric_update_miss(self): from gcloud.exceptions import NotFound gax_api = _GAXMetricsAPI() api = self._makeOne(gax_api) with self.assertRaises(NotFound): api.metric_update( self.PROJECT, self.METRIC_NAME, self.FILTER, self.DESCRIPTION) def test_metric_update_hit(self): from google.logging.v2.logging_metrics_pb2 import LogMetric response = _LogMetricPB( self.METRIC_NAME, self.FILTER, self.DESCRIPTION) gax_api = _GAXMetricsAPI(_update_log_metric_response=response) api = self._makeOne(gax_api) api.metric_update( self.PROJECT, self.METRIC_NAME, self.FILTER, self.DESCRIPTION) metric_name, metric, options = ( gax_api._update_log_metric_called_with) self.assertEqual(metric_name, self.METRIC_PATH) self.assertTrue(isinstance(metric, LogMetric)) self.assertEqual(metric.name, self.METRIC_PATH) self.assertEqual(metric.filter, self.FILTER) self.assertEqual(metric.description, self.DESCRIPTION) self.assertEqual(options, None) def test_metric_delete_error(self): from google.gax.errors import GaxError gax_api = _GAXMetricsAPI(_random_gax_error=True) api = self._makeOne(gax_api) with self.assertRaises(GaxError): api.metric_delete(self.PROJECT, self.METRIC_NAME) def test_metric_delete_miss(self): from gcloud.exceptions import NotFound gax_api = _GAXMetricsAPI(_log_metric_not_found=True) api = self._makeOne(gax_api) with self.assertRaises(NotFound): api.metric_delete(self.PROJECT, self.METRIC_NAME) def test_metric_delete_hit(self): gax_api = _GAXMetricsAPI() api = self._makeOne(gax_api) api.metric_delete(self.PROJECT, self.METRIC_NAME) metric_name, options = gax_api._delete_log_metric_called_with self.assertEqual(metric_name, self.METRIC_PATH) self.assertEqual(options, None) class _GAXBaseAPI(object): _random_gax_error = False def __init__(self, **kw): self.__dict__.update(kw) def _make_grpc_error(self, status_code): from grpc.framework.interfaces.face.face import AbortionError class _DummyException(AbortionError): code = status_code def __init__(self): pass return _DummyException() def _make_grpc_not_found(self): from grpc.beta.interfaces import StatusCode return self._make_grpc_error(StatusCode.NOT_FOUND) def _make_grpc_failed_precondition(self): from grpc.beta.interfaces import StatusCode return self._make_grpc_error(StatusCode.FAILED_PRECONDITION) class _GAXLoggingAPI(_GAXBaseAPI): def list_log_entries( self, projects, filter_, order_by, page_size, options): self._list_log_entries_called_with = ( projects, filter_, order_by, page_size, options) return self._list_log_entries_response def write_log_entries(self, entries, log_name, resource, labels, partial_success, options): self._write_log_entries_called_with = ( entries, log_name, resource, labels, partial_success, options) def delete_log(self, log_name, options): self._delete_log_called_with = log_name, options class _GAXSinksAPI(_GAXBaseAPI): _create_sink_conflict = False _sink_not_found = False def list_sinks(self, parent, page_size, options): self._list_sinks_called_with = parent, page_size, options return self._list_sinks_response def create_sink(self, parent, sink, options): from google.gax.errors import GaxError self._create_sink_called_with = parent, sink, options if self._random_gax_error: raise GaxError('error') if self._create_sink_conflict: raise GaxError('conflict', self._make_grpc_failed_precondition()) def get_sink(self, sink_name, options): from google.gax.errors import GaxError self._get_sink_called_with = sink_name, options if self._random_gax_error: raise GaxError('error') try: return self._get_sink_response except AttributeError: raise GaxError('notfound', self._make_grpc_not_found()) def update_sink(self, sink_name, sink, options=None): from google.gax.errors import GaxError self._update_sink_called_with = sink_name, sink, options if self._random_gax_error: raise GaxError('error') try: return self._update_sink_response except AttributeError: raise GaxError('notfound', self._make_grpc_not_found()) def delete_sink(self, sink_name, options=None): from google.gax.errors import GaxError self._delete_sink_called_with = sink_name, options if self._random_gax_error: raise GaxError('error') if self._sink_not_found: raise GaxError('notfound', self._make_grpc_not_found()) class _GAXMetricsAPI(_GAXBaseAPI): _create_log_metric_conflict = False _log_metric_not_found = False def list_log_metrics(self, parent, page_size, options): self._list_log_metrics_called_with = parent, page_size, options return self._list_log_metrics_response def create_log_metric(self, parent, metric, options): from google.gax.errors import GaxError self._create_log_metric_called_with = parent, metric, options if self._random_gax_error: raise GaxError('error') if self._create_log_metric_conflict: raise GaxError('conflict', self._make_grpc_failed_precondition()) def get_log_metric(self, metric_name, options): from google.gax.errors import GaxError self._get_log_metric_called_with = metric_name, options if self._random_gax_error: raise GaxError('error') try: return self._get_log_metric_response except AttributeError: raise GaxError('notfound', self._make_grpc_not_found()) def update_log_metric(self, metric_name, metric, options=None): from google.gax.errors import GaxError self._update_log_metric_called_with = metric_name, metric, options if self._random_gax_error: raise GaxError('error') try: return self._update_log_metric_response except AttributeError: raise GaxError('notfound', self._make_grpc_not_found()) def delete_log_metric(self, metric_name, options=None): from google.gax.errors import GaxError self._delete_log_metric_called_with = metric_name, options if self._random_gax_error: raise GaxError('error') if self._log_metric_not_found: raise GaxError('notfound', self._make_grpc_not_found()) class _HTTPRequestPB(object): request_url = 'http://example.com/requested' request_method = 'GET' status = 200 referer = 'http://example.com/referer' user_agent = 'AGENT' cache_hit = False request_size = 256 response_size = 1024 remote_ip = '1.2.3.4' class _LogEntryOperationPB(object): producer = 'PRODUCER' first = last = False id = 'OPID' class _ResourcePB(object): def __init__(self, type_='global', **labels): self.type = type_ self.labels = labels class _LogEntryPB(object): severity = 'DEFAULT' http_request = operation = insert_id = None text_payload = json_payload = proto_payload = None def __init__(self, log_name, **kw): self.log_name = log_name self.resource = _ResourcePB() self.timestamp = self._make_timestamp() self.labels = kw.pop('labels', {}) self.__dict__.update(kw) @staticmethod def _make_timestamp(): from datetime import datetime from gcloud._helpers import UTC from gcloud._helpers import _datetime_to_pb_timestamp NOW = datetime.utcnow().replace(tzinfo=UTC) return _datetime_to_pb_timestamp(NOW) class _LogSinkPB(object): def __init__(self, name, destination, filter_): self.name = name self.destination = destination self.filter = filter_ class _LogMetricPB(object): def __init__(self, name, description, filter_): self.name = name self.description = description self.filter = filter_
{'content_hash': 'dd6a85d4ff0d52a2751724a8c391367b', 'timestamp': '', 'source': 'github', 'line_count': 998, 'max_line_length': 77, 'avg_line_length': 35.70741482965932, 'alnum_prop': 0.6137894264227186, 'repo_name': 'ininex/geofire-python', 'id': '3174771d5989d4760532cf824d791c79b3cc03f6', 'size': '36233', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'resource/lib/python2.7/site-packages/gcloud/logging/test__gax.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '5939'}, {'name': 'CSS', 'bytes': '6231'}, {'name': 'JavaScript', 'bytes': '6187'}, {'name': 'Protocol Buffer', 'bytes': '158375'}, {'name': 'Python', 'bytes': '13368780'}, {'name': 'Shell', 'bytes': '5031'}]}
using System; using System.Collections.Generic; namespace Twitchie2.Messages { internal class MessageArgumentDictionary { private readonly Dictionary<string, object> collection; public MessageArgumentDictionary(string[] args) { collection = new(); foreach (var arg in args) { var split = arg.Split('='); collection.Add(split[0], split[1]); } } internal T GetValue<T>(string key) where T : IEquatable<T> { if (!collection.TryGetValue(key, out var value)) return default; return MessageArgumentConverter.ConvertValue<T>(value); } public List<TwitchBadge> PopBadges() { var list = new List<TwitchBadge>(); var badges = GetValue<string>("badges"); //<badge>/<version>,<badge>/<version> if (!string.IsNullOrWhiteSpace(badges)) { foreach (var badge in badges.Split(',')) { var split = badge.Split('/'); list.Add(new(split[0], split[1])); } } return list; } } }
{'content_hash': '12367dad6ee0fdead41aa10782008cae', 'timestamp': '', 'source': 'github', 'line_count': 47, 'max_line_length': 60, 'avg_line_length': 20.425531914893618, 'alnum_prop': 0.6510416666666666, 'repo_name': 'JokkeeZ/Twitchie', 'id': 'c262e9e60052b8efc99b4378999e20c4dbe56b33', 'size': '962', 'binary': False, 'copies': '1', 'ref': 'refs/heads/Twitchie2', 'path': 'Messages/MessageArgumentDictionary.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '25926'}]}
Recordings of conferences & forums. Medical data learning notes. Skill training notes. ...
{'content_hash': 'f13342bfc7f037da28752075419e2e89', 'timestamp': '', 'source': 'github', 'line_count': 5, 'max_line_length': 35, 'avg_line_length': 19.4, 'alnum_prop': 0.7319587628865979, 'repo_name': 'BevalZ/forums', 'id': 'bf608fe237bae0c23aa3d743a265453db8c98387', 'size': '109', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33261', 'license': 'mit', 'language': []}
.class public final Lcom/google/android/gms/internal/pi; .super Lcom/google/android/gms/internal/ks; # interfaces .implements Lo/uS; # annotations .annotation system Ldalvik/annotation/MemberClasses; value = { Lcom/google/android/gms/internal/pi$h;, Lcom/google/android/gms/internal/pi$g;, Lcom/google/android/gms/internal/pi$f;, Lcom/google/android/gms/internal/pi$d;, Lcom/google/android/gms/internal/pi$c;, Lcom/google/android/gms/internal/pi$b;, Lcom/google/android/gms/internal/pi$a;, Lcom/google/android/gms/internal/pi$if; } .end annotation # static fields .field public static final CREATOR:Lo/qf; .field private static final ᴵ:Ljava/util/HashMap; .annotation system Ldalvik/annotation/Signature; value = { "Ljava/util/HashMap<Ljava/lang/String;Lcom/google/android/gms/internal/kr$a<**>;>;" } .end annotation .end field # instance fields .field public ʹ:Ljava/lang/String; .field public ʻ:Ljava/lang/String; .field public ʼ:I .field public ʽ:Lcom/google/android/gms/internal/pi$b; .field public ʾ:I .field public ʿ:Ljava/lang/String; .field public ˈ:Lcom/google/android/gms/internal/pi$c; .field public ˉ:Z .field public final ˊ:Ljava/util/Set; .annotation system Ldalvik/annotation/Signature; value = { "Ljava/util/Set<Ljava/lang/Integer;>;" } .end annotation .end field .field public final ˋ:I .field public ˌ:Ljava/lang/String; .field public ˍ:Lcom/google/android/gms/internal/pi$d; .field public ˎ:Ljava/lang/String; .field public ˏ:Lcom/google/android/gms/internal/pi$a; .field public ˑ:Ljava/lang/String; .field public ͺ:Ljava/lang/String; .field public ՙ:Ljava/lang/String; .field public י:Ljava/util/List; .annotation system Ldalvik/annotation/Signature; value = { "Ljava/util/List<Lcom/google/android/gms/internal/pi$h;>;" } .end annotation .end field .field public ـ:I .field public ٴ:Z .field public ᐝ:Ljava/lang/String; .field public ᐧ:Ljava/util/List; .annotation system Ldalvik/annotation/Signature; value = { "Ljava/util/List<Lcom/google/android/gms/internal/pi$f;>;" } .end annotation .end field .field public ᐨ:Ljava/util/List; .annotation system Ldalvik/annotation/Signature; value = { "Ljava/util/List<Lcom/google/android/gms/internal/pi$g;>;" } .end annotation .end field .field public ι:Ljava/lang/String; .field public ﹳ:I .field public ゙:I # direct methods .method static constructor <clinit>()V .locals 6 new-instance v0, Lo/qf; invoke-direct {v0}, Lo/qf;-><init>()V sput-object v0, Lcom/google/android/gms/internal/pi;->CREATOR:Lo/qf; new-instance v0, Ljava/util/HashMap; invoke-direct {v0}, Ljava/util/HashMap;-><init>()V sput-object v0, Lcom/google/android/gms/internal/pi;->ᴵ:Ljava/util/HashMap; sget-object v0, Lcom/google/android/gms/internal/pi;->ᴵ:Ljava/util/HashMap; const-string v1, "aboutMe" const-string v2, "aboutMe" const/4 v3, 0x2 invoke-static {v2, v3}, Lcom/google/android/gms/internal/kr$a;->ˏ(Ljava/lang/String;I)Lcom/google/android/gms/internal/kr$a; move-result-object v2 invoke-virtual {v0, v1, v2}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; sget-object v0, Lcom/google/android/gms/internal/pi;->ᴵ:Ljava/util/HashMap; const-string v1, "ageRange" const-string v2, "ageRange" const-class v3, Lcom/google/android/gms/internal/pi$a; const/4 v4, 0x3 invoke-static {v2, v4, v3}, Lcom/google/android/gms/internal/kr$a;->ˊ(Ljava/lang/String;ILjava/lang/Class;)Lcom/google/android/gms/internal/kr$a; move-result-object v2 invoke-virtual {v0, v1, v2}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; sget-object v0, Lcom/google/android/gms/internal/pi;->ᴵ:Ljava/util/HashMap; const-string v1, "birthday" const-string v2, "birthday" const/4 v3, 0x4 invoke-static {v2, v3}, Lcom/google/android/gms/internal/kr$a;->ˏ(Ljava/lang/String;I)Lcom/google/android/gms/internal/kr$a; move-result-object v2 invoke-virtual {v0, v1, v2}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; sget-object v0, Lcom/google/android/gms/internal/pi;->ᴵ:Ljava/util/HashMap; const-string v1, "braggingRights" const-string v2, "braggingRights" const/4 v3, 0x5 invoke-static {v2, v3}, Lcom/google/android/gms/internal/kr$a;->ˏ(Ljava/lang/String;I)Lcom/google/android/gms/internal/kr$a; move-result-object v2 invoke-virtual {v0, v1, v2}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; sget-object v0, Lcom/google/android/gms/internal/pi;->ᴵ:Ljava/util/HashMap; const-string v1, "circledByCount" const-string v2, "circledByCount" const/4 v3, 0x6 invoke-static {v2, v3}, Lcom/google/android/gms/internal/kr$a;->ˊ(Ljava/lang/String;I)Lcom/google/android/gms/internal/kr$a; move-result-object v2 invoke-virtual {v0, v1, v2}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; sget-object v0, Lcom/google/android/gms/internal/pi;->ᴵ:Ljava/util/HashMap; const-string v1, "cover" const-string v2, "cover" const-class v3, Lcom/google/android/gms/internal/pi$b; const/4 v4, 0x7 invoke-static {v2, v4, v3}, Lcom/google/android/gms/internal/kr$a;->ˊ(Ljava/lang/String;ILjava/lang/Class;)Lcom/google/android/gms/internal/kr$a; move-result-object v2 invoke-virtual {v0, v1, v2}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; sget-object v0, Lcom/google/android/gms/internal/pi;->ᴵ:Ljava/util/HashMap; const-string v1, "currentLocation" const-string v2, "currentLocation" const/16 v3, 0x8 invoke-static {v2, v3}, Lcom/google/android/gms/internal/kr$a;->ˏ(Ljava/lang/String;I)Lcom/google/android/gms/internal/kr$a; move-result-object v2 invoke-virtual {v0, v1, v2}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; sget-object v0, Lcom/google/android/gms/internal/pi;->ᴵ:Ljava/util/HashMap; const-string v1, "displayName" const-string v2, "displayName" const/16 v3, 0x9 invoke-static {v2, v3}, Lcom/google/android/gms/internal/kr$a;->ˏ(Ljava/lang/String;I)Lcom/google/android/gms/internal/kr$a; move-result-object v2 invoke-virtual {v0, v1, v2}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; sget-object v0, Lcom/google/android/gms/internal/pi;->ᴵ:Ljava/util/HashMap; const-string v1, "gender" const-string v2, "gender" new-instance v3, Lcom/google/android/gms/internal/ko; invoke-direct {v3}, Lcom/google/android/gms/internal/ko;-><init>()V const-string v4, "male" const/4 v5, 0x0 invoke-virtual {v3, v4, v5}, Lcom/google/android/gms/internal/ko;->ˊ(Ljava/lang/String;I)Lcom/google/android/gms/internal/ko; move-result-object v3 const-string v4, "female" const/4 v5, 0x1 invoke-virtual {v3, v4, v5}, Lcom/google/android/gms/internal/ko;->ˊ(Ljava/lang/String;I)Lcom/google/android/gms/internal/ko; move-result-object v3 const-string v4, "other" const/4 v5, 0x2 invoke-virtual {v3, v4, v5}, Lcom/google/android/gms/internal/ko;->ˊ(Ljava/lang/String;I)Lcom/google/android/gms/internal/ko; move-result-object v3 const/16 v4, 0xc const/4 v5, 0x0 invoke-static {v2, v4, v3, v5}, Lcom/google/android/gms/internal/kr$a;->ˊ(Ljava/lang/String;ILcom/google/android/gms/internal/kr$if;Z)Lcom/google/android/gms/internal/kr$a; move-result-object v2 invoke-virtual {v0, v1, v2}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; sget-object v0, Lcom/google/android/gms/internal/pi;->ᴵ:Ljava/util/HashMap; const-string v1, "id" const-string v2, "id" const/16 v3, 0xe invoke-static {v2, v3}, Lcom/google/android/gms/internal/kr$a;->ˏ(Ljava/lang/String;I)Lcom/google/android/gms/internal/kr$a; move-result-object v2 invoke-virtual {v0, v1, v2}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; sget-object v0, Lcom/google/android/gms/internal/pi;->ᴵ:Ljava/util/HashMap; const-string v1, "image" const-string v2, "image" const-class v3, Lcom/google/android/gms/internal/pi$c; const/16 v4, 0xf invoke-static {v2, v4, v3}, Lcom/google/android/gms/internal/kr$a;->ˊ(Ljava/lang/String;ILjava/lang/Class;)Lcom/google/android/gms/internal/kr$a; move-result-object v2 invoke-virtual {v0, v1, v2}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; sget-object v0, Lcom/google/android/gms/internal/pi;->ᴵ:Ljava/util/HashMap; const-string v1, "isPlusUser" const-string v2, "isPlusUser" const/16 v3, 0x10 invoke-static {v2, v3}, Lcom/google/android/gms/internal/kr$a;->ˎ(Ljava/lang/String;I)Lcom/google/android/gms/internal/kr$a; move-result-object v2 invoke-virtual {v0, v1, v2}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; sget-object v0, Lcom/google/android/gms/internal/pi;->ᴵ:Ljava/util/HashMap; const-string v1, "language" const-string v2, "language" const/16 v3, 0x12 invoke-static {v2, v3}, Lcom/google/android/gms/internal/kr$a;->ˏ(Ljava/lang/String;I)Lcom/google/android/gms/internal/kr$a; move-result-object v2 invoke-virtual {v0, v1, v2}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; sget-object v0, Lcom/google/android/gms/internal/pi;->ᴵ:Ljava/util/HashMap; const-string v1, "name" const-string v2, "name" const-class v3, Lcom/google/android/gms/internal/pi$d; const/16 v4, 0x13 invoke-static {v2, v4, v3}, Lcom/google/android/gms/internal/kr$a;->ˊ(Ljava/lang/String;ILjava/lang/Class;)Lcom/google/android/gms/internal/kr$a; move-result-object v2 invoke-virtual {v0, v1, v2}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; sget-object v0, Lcom/google/android/gms/internal/pi;->ᴵ:Ljava/util/HashMap; const-string v1, "nickname" const-string v2, "nickname" const/16 v3, 0x14 invoke-static {v2, v3}, Lcom/google/android/gms/internal/kr$a;->ˏ(Ljava/lang/String;I)Lcom/google/android/gms/internal/kr$a; move-result-object v2 invoke-virtual {v0, v1, v2}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; sget-object v0, Lcom/google/android/gms/internal/pi;->ᴵ:Ljava/util/HashMap; const-string v1, "objectType" const-string v2, "objectType" new-instance v3, Lcom/google/android/gms/internal/ko; invoke-direct {v3}, Lcom/google/android/gms/internal/ko;-><init>()V const-string v4, "person" const/4 v5, 0x0 invoke-virtual {v3, v4, v5}, Lcom/google/android/gms/internal/ko;->ˊ(Ljava/lang/String;I)Lcom/google/android/gms/internal/ko; move-result-object v3 const-string v4, "page" const/4 v5, 0x1 invoke-virtual {v3, v4, v5}, Lcom/google/android/gms/internal/ko;->ˊ(Ljava/lang/String;I)Lcom/google/android/gms/internal/ko; move-result-object v3 const/16 v4, 0x15 const/4 v5, 0x0 invoke-static {v2, v4, v3, v5}, Lcom/google/android/gms/internal/kr$a;->ˊ(Ljava/lang/String;ILcom/google/android/gms/internal/kr$if;Z)Lcom/google/android/gms/internal/kr$a; move-result-object v2 invoke-virtual {v0, v1, v2}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; sget-object v0, Lcom/google/android/gms/internal/pi;->ᴵ:Ljava/util/HashMap; const-string v1, "organizations" const-string v2, "organizations" const-class v3, Lcom/google/android/gms/internal/pi$f; const/16 v4, 0x16 invoke-static {v2, v4, v3}, Lcom/google/android/gms/internal/kr$a;->ˋ(Ljava/lang/String;ILjava/lang/Class;)Lcom/google/android/gms/internal/kr$a; move-result-object v2 invoke-virtual {v0, v1, v2}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; sget-object v0, Lcom/google/android/gms/internal/pi;->ᴵ:Ljava/util/HashMap; const-string v1, "placesLived" const-string v2, "placesLived" const-class v3, Lcom/google/android/gms/internal/pi$g; const/16 v4, 0x17 invoke-static {v2, v4, v3}, Lcom/google/android/gms/internal/kr$a;->ˋ(Ljava/lang/String;ILjava/lang/Class;)Lcom/google/android/gms/internal/kr$a; move-result-object v2 invoke-virtual {v0, v1, v2}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; sget-object v0, Lcom/google/android/gms/internal/pi;->ᴵ:Ljava/util/HashMap; const-string v1, "plusOneCount" const-string v2, "plusOneCount" const/16 v3, 0x18 invoke-static {v2, v3}, Lcom/google/android/gms/internal/kr$a;->ˊ(Ljava/lang/String;I)Lcom/google/android/gms/internal/kr$a; move-result-object v2 invoke-virtual {v0, v1, v2}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; sget-object v0, Lcom/google/android/gms/internal/pi;->ᴵ:Ljava/util/HashMap; const-string v1, "relationshipStatus" const-string v2, "relationshipStatus" new-instance v3, Lcom/google/android/gms/internal/ko; invoke-direct {v3}, Lcom/google/android/gms/internal/ko;-><init>()V const-string v4, "single" const/4 v5, 0x0 invoke-virtual {v3, v4, v5}, Lcom/google/android/gms/internal/ko;->ˊ(Ljava/lang/String;I)Lcom/google/android/gms/internal/ko; move-result-object v3 const-string v4, "in_a_relationship" const/4 v5, 0x1 invoke-virtual {v3, v4, v5}, Lcom/google/android/gms/internal/ko;->ˊ(Ljava/lang/String;I)Lcom/google/android/gms/internal/ko; move-result-object v3 const-string v4, "engaged" const/4 v5, 0x2 invoke-virtual {v3, v4, v5}, Lcom/google/android/gms/internal/ko;->ˊ(Ljava/lang/String;I)Lcom/google/android/gms/internal/ko; move-result-object v3 const-string v4, "married" const/4 v5, 0x3 invoke-virtual {v3, v4, v5}, Lcom/google/android/gms/internal/ko;->ˊ(Ljava/lang/String;I)Lcom/google/android/gms/internal/ko; move-result-object v3 const-string v4, "its_complicated" const/4 v5, 0x4 invoke-virtual {v3, v4, v5}, Lcom/google/android/gms/internal/ko;->ˊ(Ljava/lang/String;I)Lcom/google/android/gms/internal/ko; move-result-object v3 const-string v4, "open_relationship" const/4 v5, 0x5 invoke-virtual {v3, v4, v5}, Lcom/google/android/gms/internal/ko;->ˊ(Ljava/lang/String;I)Lcom/google/android/gms/internal/ko; move-result-object v3 const-string v4, "widowed" const/4 v5, 0x6 invoke-virtual {v3, v4, v5}, Lcom/google/android/gms/internal/ko;->ˊ(Ljava/lang/String;I)Lcom/google/android/gms/internal/ko; move-result-object v3 const-string v4, "in_domestic_partnership" const/4 v5, 0x7 invoke-virtual {v3, v4, v5}, Lcom/google/android/gms/internal/ko;->ˊ(Ljava/lang/String;I)Lcom/google/android/gms/internal/ko; move-result-object v3 const-string v4, "in_civil_union" const/16 v5, 0x8 invoke-virtual {v3, v4, v5}, Lcom/google/android/gms/internal/ko;->ˊ(Ljava/lang/String;I)Lcom/google/android/gms/internal/ko; move-result-object v3 const/16 v4, 0x19 const/4 v5, 0x0 invoke-static {v2, v4, v3, v5}, Lcom/google/android/gms/internal/kr$a;->ˊ(Ljava/lang/String;ILcom/google/android/gms/internal/kr$if;Z)Lcom/google/android/gms/internal/kr$a; move-result-object v2 invoke-virtual {v0, v1, v2}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; sget-object v0, Lcom/google/android/gms/internal/pi;->ᴵ:Ljava/util/HashMap; const-string v1, "tagline" const-string v2, "tagline" const/16 v3, 0x1a invoke-static {v2, v3}, Lcom/google/android/gms/internal/kr$a;->ˏ(Ljava/lang/String;I)Lcom/google/android/gms/internal/kr$a; move-result-object v2 invoke-virtual {v0, v1, v2}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; sget-object v0, Lcom/google/android/gms/internal/pi;->ᴵ:Ljava/util/HashMap; const-string v1, "url" const-string v2, "url" const/16 v3, 0x1b invoke-static {v2, v3}, Lcom/google/android/gms/internal/kr$a;->ˏ(Ljava/lang/String;I)Lcom/google/android/gms/internal/kr$a; move-result-object v2 invoke-virtual {v0, v1, v2}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; sget-object v0, Lcom/google/android/gms/internal/pi;->ᴵ:Ljava/util/HashMap; const-string v1, "urls" const-string v2, "urls" const-class v3, Lcom/google/android/gms/internal/pi$h; const/16 v4, 0x1c invoke-static {v2, v4, v3}, Lcom/google/android/gms/internal/kr$a;->ˋ(Ljava/lang/String;ILjava/lang/Class;)Lcom/google/android/gms/internal/kr$a; move-result-object v2 invoke-virtual {v0, v1, v2}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; sget-object v0, Lcom/google/android/gms/internal/pi;->ᴵ:Ljava/util/HashMap; const-string v1, "verified" const-string v2, "verified" const/16 v3, 0x1d invoke-static {v2, v3}, Lcom/google/android/gms/internal/kr$a;->ˎ(Ljava/lang/String;I)Lcom/google/android/gms/internal/kr$a; move-result-object v2 invoke-virtual {v0, v1, v2}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; return-void .end method .method public constructor <init>()V .locals 1 invoke-direct {p0}, Lcom/google/android/gms/internal/ks;-><init>()V const/4 v0, 0x1 iput v0, p0, Lcom/google/android/gms/internal/pi;->ˋ:I new-instance v0, Ljava/util/HashSet; invoke-direct {v0}, Ljava/util/HashSet;-><init>()V iput-object v0, p0, Lcom/google/android/gms/internal/pi;->ˊ:Ljava/util/Set; return-void .end method .method public constructor <init>(Ljava/lang/String;Ljava/lang/String;Lcom/google/android/gms/internal/pi$c;ILjava/lang/String;)V .locals 2 invoke-direct {p0}, Lcom/google/android/gms/internal/ks;-><init>()V const/4 v0, 0x1 iput v0, p0, Lcom/google/android/gms/internal/pi;->ˋ:I new-instance v0, Ljava/util/HashSet; invoke-direct {v0}, Ljava/util/HashSet;-><init>()V iput-object v0, p0, Lcom/google/android/gms/internal/pi;->ˊ:Ljava/util/Set; iput-object p1, p0, Lcom/google/android/gms/internal/pi;->ι:Ljava/lang/String; iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˊ:Ljava/util/Set; const/16 v1, 0x9 invoke-static {v1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer; move-result-object v1 invoke-interface {v0, v1}, Ljava/util/Set;->add(Ljava/lang/Object;)Z iput-object p2, p0, Lcom/google/android/gms/internal/pi;->ʿ:Ljava/lang/String; iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˊ:Ljava/util/Set; const/16 v1, 0xe invoke-static {v1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer; move-result-object v1 invoke-interface {v0, v1}, Ljava/util/Set;->add(Ljava/lang/Object;)Z iput-object p3, p0, Lcom/google/android/gms/internal/pi;->ˈ:Lcom/google/android/gms/internal/pi$c; iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˊ:Ljava/util/Set; const/16 v1, 0xf invoke-static {v1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer; move-result-object v1 invoke-interface {v0, v1}, Ljava/util/Set;->add(Ljava/lang/Object;)Z iput p4, p0, Lcom/google/android/gms/internal/pi;->ـ:I iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˊ:Ljava/util/Set; const/16 v1, 0x15 invoke-static {v1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer; move-result-object v1 invoke-interface {v0, v1}, Ljava/util/Set;->add(Ljava/lang/Object;)Z iput-object p5, p0, Lcom/google/android/gms/internal/pi;->ՙ:Ljava/lang/String; iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˊ:Ljava/util/Set; const/16 v1, 0x1b invoke-static {v1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer; move-result-object v1 invoke-interface {v0, v1}, Ljava/util/Set;->add(Ljava/lang/Object;)Z return-void .end method .method public constructor <init>(Ljava/util/Set;ILjava/lang/String;Lcom/google/android/gms/internal/pi$a;Ljava/lang/String;Ljava/lang/String;ILcom/google/android/gms/internal/pi$b;Ljava/lang/String;Ljava/lang/String;ILjava/lang/String;Lcom/google/android/gms/internal/pi$c;ZLjava/lang/String;Lcom/google/android/gms/internal/pi$d;Ljava/lang/String;ILjava/util/List;Ljava/util/List;IILjava/lang/String;Ljava/lang/String;Ljava/util/List;Z)V .locals 1 .annotation system Ldalvik/annotation/Signature; value = { "(Ljava/util/Set<Ljava/lang/Integer;>;ILjava/lang/String;Lcom/google/android/gms/internal/pi$a;Ljava/lang/String;Ljava/lang/String;ILcom/google/android/gms/internal/pi$b;Ljava/lang/String;Ljava/lang/String;ILjava/lang/String;Lcom/google/android/gms/internal/pi$c;ZLjava/lang/String;Lcom/google/android/gms/internal/pi$d;Ljava/lang/String;ILjava/util/List<Lcom/google/android/gms/internal/pi$f;>;Ljava/util/List<Lcom/google/android/gms/internal/pi$g;>;IILjava/lang/String;Ljava/lang/String;Ljava/util/List<Lcom/google/android/gms/internal/pi$h;>;Z)V" } .end annotation invoke-direct {p0}, Lcom/google/android/gms/internal/ks;-><init>()V iput-object p1, p0, Lcom/google/android/gms/internal/pi;->ˊ:Ljava/util/Set; iput p2, p0, Lcom/google/android/gms/internal/pi;->ˋ:I iput-object p3, p0, Lcom/google/android/gms/internal/pi;->ˎ:Ljava/lang/String; iput-object p4, p0, Lcom/google/android/gms/internal/pi;->ˏ:Lcom/google/android/gms/internal/pi$a; iput-object p5, p0, Lcom/google/android/gms/internal/pi;->ᐝ:Ljava/lang/String; iput-object p6, p0, Lcom/google/android/gms/internal/pi;->ʻ:Ljava/lang/String; iput p7, p0, Lcom/google/android/gms/internal/pi;->ʼ:I iput-object p8, p0, Lcom/google/android/gms/internal/pi;->ʽ:Lcom/google/android/gms/internal/pi$b; iput-object p9, p0, Lcom/google/android/gms/internal/pi;->ͺ:Ljava/lang/String; iput-object p10, p0, Lcom/google/android/gms/internal/pi;->ι:Ljava/lang/String; iput p11, p0, Lcom/google/android/gms/internal/pi;->ʾ:I iput-object p12, p0, Lcom/google/android/gms/internal/pi;->ʿ:Ljava/lang/String; iput-object p13, p0, Lcom/google/android/gms/internal/pi;->ˈ:Lcom/google/android/gms/internal/pi$c; iput-boolean p14, p0, Lcom/google/android/gms/internal/pi;->ˉ:Z move-object/from16 v0, p15 iput-object v0, p0, Lcom/google/android/gms/internal/pi;->ˌ:Ljava/lang/String; move-object/from16 v0, p16 iput-object v0, p0, Lcom/google/android/gms/internal/pi;->ˍ:Lcom/google/android/gms/internal/pi$d; move-object/from16 v0, p17 iput-object v0, p0, Lcom/google/android/gms/internal/pi;->ˑ:Ljava/lang/String; move/from16 v0, p18 iput v0, p0, Lcom/google/android/gms/internal/pi;->ـ:I move-object/from16 v0, p19 iput-object v0, p0, Lcom/google/android/gms/internal/pi;->ᐧ:Ljava/util/List; move-object/from16 v0, p20 iput-object v0, p0, Lcom/google/android/gms/internal/pi;->ᐨ:Ljava/util/List; move/from16 v0, p21 iput v0, p0, Lcom/google/android/gms/internal/pi;->ﹳ:I move/from16 v0, p22 iput v0, p0, Lcom/google/android/gms/internal/pi;->゙:I move-object/from16 v0, p23 iput-object v0, p0, Lcom/google/android/gms/internal/pi;->ʹ:Ljava/lang/String; move-object/from16 v0, p24 iput-object v0, p0, Lcom/google/android/gms/internal/pi;->ՙ:Ljava/lang/String; move-object/from16 v0, p25 iput-object v0, p0, Lcom/google/android/gms/internal/pi;->י:Ljava/util/List; move/from16 v0, p26 iput-boolean v0, p0, Lcom/google/android/gms/internal/pi;->ٴ:Z return-void .end method .method public static ˊ([B)Lcom/google/android/gms/internal/pi; .locals 4 invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel; move-result-object v2 array-length v0, p0 const/4 v1, 0x0 invoke-virtual {v2, p0, v1, v0}, Landroid/os/Parcel;->unmarshall([BII)V const/4 v0, 0x0 invoke-virtual {v2, v0}, Landroid/os/Parcel;->setDataPosition(I)V sget-object v0, Lcom/google/android/gms/internal/pi;->CREATOR:Lo/qf; invoke-virtual {v0, v2}, Lo/qf;->ˊ(Landroid/os/Parcel;)Lcom/google/android/gms/internal/pi; move-result-object v3 invoke-virtual {v2}, Landroid/os/Parcel;->recycle()V return-object v3 .end method # virtual methods .method public describeContents()I .locals 1 sget-object v0, Lcom/google/android/gms/internal/pi;->CREATOR:Lo/qf; const/4 v0, 0x0 return v0 .end method .method public equals(Ljava/lang/Object;)Z .locals 5 instance-of v0, p1, Lcom/google/android/gms/internal/pi; if-nez v0, :cond_0 const/4 v0, 0x0 return v0 :cond_0 if-ne p0, p1, :cond_1 const/4 v0, 0x1 return v0 :cond_1 move-object v0, p1 check-cast v0, Lcom/google/android/gms/internal/pi; move-object v2, v0 sget-object v0, Lcom/google/android/gms/internal/pi;->ᴵ:Ljava/util/HashMap; invoke-virtual {v0}, Ljava/util/HashMap;->values()Ljava/util/Collection; move-result-object v0 invoke-interface {v0}, Ljava/util/Collection;->iterator()Ljava/util/Iterator; move-result-object v3 :goto_0 invoke-interface {v3}, Ljava/util/Iterator;->hasNext()Z move-result v0 if-eqz v0, :cond_5 invoke-interface {v3}, Ljava/util/Iterator;->next()Ljava/lang/Object; move-result-object v0 check-cast v0, Lcom/google/android/gms/internal/kr$a; move-object v4, v0 invoke-virtual {p0, v4}, Lcom/google/android/gms/internal/pi;->ˊ(Lcom/google/android/gms/internal/kr$a;)Z move-result v0 if-eqz v0, :cond_3 invoke-virtual {v2, v4}, Lcom/google/android/gms/internal/pi;->ˊ(Lcom/google/android/gms/internal/kr$a;)Z move-result v0 if-eqz v0, :cond_2 invoke-virtual {p0, v4}, Lcom/google/android/gms/internal/pi;->ˋ(Lcom/google/android/gms/internal/kr$a;)Ljava/lang/Object; move-result-object v0 invoke-virtual {v2, v4}, Lcom/google/android/gms/internal/pi;->ˋ(Lcom/google/android/gms/internal/kr$a;)Ljava/lang/Object; move-result-object v1 invoke-virtual {v0, v1}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z move-result v0 if-nez v0, :cond_4 const/4 v0, 0x0 return v0 :cond_2 const/4 v0, 0x0 return v0 :cond_3 invoke-virtual {v2, v4}, Lcom/google/android/gms/internal/pi;->ˊ(Lcom/google/android/gms/internal/kr$a;)Z move-result v0 if-eqz v0, :cond_4 const/4 v0, 0x0 return v0 :cond_4 goto :goto_0 :cond_5 const/4 v0, 0x1 return v0 .end method .method public hashCode()I .locals 4 const/4 v1, 0x0 sget-object v0, Lcom/google/android/gms/internal/pi;->ᴵ:Ljava/util/HashMap; invoke-virtual {v0}, Ljava/util/HashMap;->values()Ljava/util/Collection; move-result-object v0 invoke-interface {v0}, Ljava/util/Collection;->iterator()Ljava/util/Iterator; move-result-object v2 :goto_0 invoke-interface {v2}, Ljava/util/Iterator;->hasNext()Z move-result v0 if-eqz v0, :cond_1 invoke-interface {v2}, Ljava/util/Iterator;->next()Ljava/lang/Object; move-result-object v0 check-cast v0, Lcom/google/android/gms/internal/kr$a; move-object v3, v0 invoke-virtual {p0, v3}, Lcom/google/android/gms/internal/pi;->ˊ(Lcom/google/android/gms/internal/kr$a;)Z move-result v0 if-eqz v0, :cond_0 invoke-virtual {v3}, Lcom/google/android/gms/internal/kr$a;->ʽ()I move-result v0 add-int/2addr v1, v0 invoke-virtual {p0, v3}, Lcom/google/android/gms/internal/pi;->ˋ(Lcom/google/android/gms/internal/kr$a;)Ljava/lang/Object; move-result-object v0 invoke-virtual {v0}, Ljava/lang/Object;->hashCode()I move-result v0 add-int/2addr v1, v0 :cond_0 goto :goto_0 :cond_1 return v1 .end method .method public writeToParcel(Landroid/os/Parcel;I)V .locals 1 sget-object v0, Lcom/google/android/gms/internal/pi;->CREATOR:Lo/qf; invoke-static {p0, p1, p2}, Lo/qf;->ˊ(Lcom/google/android/gms/internal/pi;Landroid/os/Parcel;I)V return-void .end method .method public y_()Ljava/lang/String; .locals 1 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ᐝ:Ljava/lang/String; return-object v0 .end method .method public ʳ()Z .locals 2 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˊ:Ljava/util/Set; const/16 v1, 0x14 invoke-static {v1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer; move-result-object v1 invoke-interface {v0, v1}, Ljava/util/Set;->contains(Ljava/lang/Object;)Z move-result v0 return v0 .end method .method public ʴ()I .locals 1 iget v0, p0, Lcom/google/android/gms/internal/pi;->ـ:I return v0 .end method .method public ʹ()Z .locals 2 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˊ:Ljava/util/Set; const/16 v1, 0xc invoke-static {v1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer; move-result-object v1 invoke-interface {v0, v1}, Ljava/util/Set;->contains(Ljava/lang/Object;)Z move-result v0 return v0 .end method .method public ʻ()Lo/uS$if; .locals 1 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˏ:Lcom/google/android/gms/internal/pi$a; return-object v0 .end method .method public ʼ()Z .locals 2 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˊ:Ljava/util/Set; const/4 v1, 0x3 invoke-static {v1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer; move-result-object v1 invoke-interface {v0, v1}, Ljava/util/Set;->contains(Ljava/lang/Object;)Z move-result v0 return v0 .end method .method public ʽ()Z .locals 1 const/4 v0, 0x1 return v0 .end method .method public ʾ()Z .locals 2 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˊ:Ljava/util/Set; const/4 v1, 0x4 invoke-static {v1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer; move-result-object v1 invoke-interface {v0, v1}, Ljava/util/Set;->contains(Ljava/lang/Object;)Z move-result v0 return v0 .end method .method public ʿ()Ljava/lang/String; .locals 1 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ʻ:Ljava/lang/String; return-object v0 .end method .method public ˆ()Z .locals 2 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˊ:Ljava/util/Set; const/16 v1, 0x15 invoke-static {v1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer; move-result-object v1 invoke-interface {v0, v1}, Ljava/util/Set;->contains(Ljava/lang/Object;)Z move-result v0 return v0 .end method .method public ˇ()Ljava/util/List; .locals 1 .annotation system Ldalvik/annotation/Signature; value = { "()Ljava/util/List<Lo/uS$IF;>;" } .end annotation iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ᐧ:Ljava/util/List; check-cast v0, Ljava/util/ArrayList; return-object v0 .end method .method public ˈ()Z .locals 2 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˊ:Ljava/util/Set; const/4 v1, 0x5 invoke-static {v1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer; move-result-object v1 invoke-interface {v0, v1}, Ljava/util/Set;->contains(Ljava/lang/Object;)Z move-result v0 return v0 .end method .method public ˉ()I .locals 1 iget v0, p0, Lcom/google/android/gms/internal/pi;->ʼ:I return v0 .end method .method public ˊ()Ljava/util/HashMap; .locals 1 .annotation system Ldalvik/annotation/Signature; value = { "()Ljava/util/HashMap<Ljava/lang/String;Lcom/google/android/gms/internal/kr$a<**>;>;" } .end annotation sget-object v0, Lcom/google/android/gms/internal/pi;->ᴵ:Ljava/util/HashMap; return-object v0 .end method .method protected ˊ(Lcom/google/android/gms/internal/kr$a;)Z .locals 2 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˊ:Ljava/util/Set; invoke-virtual {p1}, Lcom/google/android/gms/internal/kr$a;->ʽ()I move-result v1 invoke-static {v1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer; move-result-object v1 invoke-interface {v0, v1}, Ljava/util/Set;->contains(Ljava/lang/Object;)Z move-result v0 return v0 .end method .method protected ˋ(Lcom/google/android/gms/internal/kr$a;)Ljava/lang/Object; .locals 3 invoke-virtual {p1}, Lcom/google/android/gms/internal/kr$a;->ʽ()I move-result v0 packed-switch v0, :pswitch_data_0 goto/16 :goto_0 :pswitch_0 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˎ:Ljava/lang/String; return-object v0 :pswitch_1 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˏ:Lcom/google/android/gms/internal/pi$a; return-object v0 :pswitch_2 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ᐝ:Ljava/lang/String; return-object v0 :pswitch_3 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ʻ:Ljava/lang/String; return-object v0 :pswitch_4 iget v0, p0, Lcom/google/android/gms/internal/pi;->ʼ:I invoke-static {v0}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer; move-result-object v0 return-object v0 :pswitch_5 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ʽ:Lcom/google/android/gms/internal/pi$b; return-object v0 :pswitch_6 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ͺ:Ljava/lang/String; return-object v0 :pswitch_7 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ι:Ljava/lang/String; return-object v0 :pswitch_8 iget v0, p0, Lcom/google/android/gms/internal/pi;->ʾ:I invoke-static {v0}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer; move-result-object v0 return-object v0 :pswitch_9 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ʿ:Ljava/lang/String; return-object v0 :pswitch_a iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˈ:Lcom/google/android/gms/internal/pi$c; return-object v0 :pswitch_b iget-boolean v0, p0, Lcom/google/android/gms/internal/pi;->ˉ:Z invoke-static {v0}, Ljava/lang/Boolean;->valueOf(Z)Ljava/lang/Boolean; move-result-object v0 return-object v0 :pswitch_c iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˌ:Ljava/lang/String; return-object v0 :pswitch_d iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˍ:Lcom/google/android/gms/internal/pi$d; return-object v0 :pswitch_e iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˑ:Ljava/lang/String; return-object v0 :pswitch_f iget v0, p0, Lcom/google/android/gms/internal/pi;->ـ:I invoke-static {v0}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer; move-result-object v0 return-object v0 :pswitch_10 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ᐧ:Ljava/util/List; return-object v0 :pswitch_11 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ᐨ:Ljava/util/List; return-object v0 :pswitch_12 iget v0, p0, Lcom/google/android/gms/internal/pi;->ﹳ:I invoke-static {v0}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer; move-result-object v0 return-object v0 :pswitch_13 iget v0, p0, Lcom/google/android/gms/internal/pi;->゙:I invoke-static {v0}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer; move-result-object v0 return-object v0 :pswitch_14 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ʹ:Ljava/lang/String; return-object v0 :pswitch_15 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ՙ:Ljava/lang/String; return-object v0 :pswitch_16 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->י:Ljava/util/List; return-object v0 :pswitch_17 iget-boolean v0, p0, Lcom/google/android/gms/internal/pi;->ٴ:Z invoke-static {v0}, Ljava/lang/Boolean;->valueOf(Z)Ljava/lang/Boolean; move-result-object v0 return-object v0 :goto_0 :pswitch_18 new-instance v0, Ljava/lang/IllegalStateException; new-instance v1, Ljava/lang/StringBuilder; invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V const-string v2, "Unknown safe parcelable id=" invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v1 invoke-virtual {p1}, Lcom/google/android/gms/internal/kr$a;->ʽ()I move-result v2 invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder; move-result-object v1 invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String; move-result-object v1 invoke-direct {v0, v1}, Ljava/lang/IllegalStateException;-><init>(Ljava/lang/String;)V throw v0 :pswitch_data_0 .packed-switch 0x2 :pswitch_0 :pswitch_1 :pswitch_2 :pswitch_3 :pswitch_4 :pswitch_5 :pswitch_6 :pswitch_7 :pswitch_18 :pswitch_18 :pswitch_8 :pswitch_18 :pswitch_9 :pswitch_a :pswitch_b :pswitch_18 :pswitch_c :pswitch_d :pswitch_e :pswitch_f :pswitch_10 :pswitch_11 :pswitch_12 :pswitch_13 :pswitch_14 :pswitch_15 :pswitch_16 :pswitch_17 .end packed-switch .end method .method public ˌ()Z .locals 2 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˊ:Ljava/util/Set; const/4 v1, 0x6 invoke-static {v1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer; move-result-object v1 invoke-interface {v0, v1}, Ljava/util/Set;->contains(Ljava/lang/Object;)Z move-result v0 return v0 .end method .method public ˍ()Lo/uS$ˊ; .locals 1 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ʽ:Lcom/google/android/gms/internal/pi$b; return-object v0 .end method .method public ˏ()Ljava/lang/String; .locals 1 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˎ:Ljava/lang/String; return-object v0 .end method .method public ˑ()Z .locals 2 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˊ:Ljava/util/Set; const/4 v1, 0x7 invoke-static {v1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer; move-result-object v1 invoke-interface {v0, v1}, Ljava/util/Set;->contains(Ljava/lang/Object;)Z move-result v0 return v0 .end method .method public ˡ()Z .locals 2 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˊ:Ljava/util/Set; const/16 v1, 0x16 invoke-static {v1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer; move-result-object v1 invoke-interface {v0, v1}, Ljava/util/Set;->contains(Ljava/lang/Object;)Z move-result v0 return v0 .end method .method public ˮ()Ljava/util/List; .locals 1 .annotation system Ldalvik/annotation/Signature; value = { "()Ljava/util/List<Lo/uS$\u02cf;>;" } .end annotation iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ᐨ:Ljava/util/List; check-cast v0, Ljava/util/ArrayList; return-object v0 .end method .method public synthetic ͺ()Ljava/lang/Object; .locals 1 invoke-virtual {p0}, Lcom/google/android/gms/internal/pi;->ᒽ()Lcom/google/android/gms/internal/pi; move-result-object v0 return-object v0 .end method .method public ՙ()Ljava/lang/String; .locals 1 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ʿ:Ljava/lang/String; return-object v0 .end method .method public י()Z .locals 2 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˊ:Ljava/util/Set; const/16 v1, 0xe invoke-static {v1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer; move-result-object v1 invoke-interface {v0, v1}, Ljava/util/Set;->contains(Ljava/lang/Object;)Z move-result v0 return v0 .end method .method public ـ()Ljava/lang/String; .locals 1 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ͺ:Ljava/lang/String; return-object v0 .end method .method public ٴ()Lo/uS$ˋ; .locals 1 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˈ:Lcom/google/android/gms/internal/pi$c; return-object v0 .end method .method public ۥ()Z .locals 2 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˊ:Ljava/util/Set; const/16 v1, 0x17 invoke-static {v1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer; move-result-object v1 invoke-interface {v0, v1}, Ljava/util/Set;->contains(Ljava/lang/Object;)Z move-result v0 return v0 .end method .method public ᐝ()Z .locals 2 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˊ:Ljava/util/Set; const/4 v1, 0x2 invoke-static {v1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer; move-result-object v1 invoke-interface {v0, v1}, Ljava/util/Set;->contains(Ljava/lang/Object;)Z move-result v0 return v0 .end method .method public ᐟ()Z .locals 2 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˊ:Ljava/util/Set; const/16 v1, 0x1c invoke-static {v1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer; move-result-object v1 invoke-interface {v0, v1}, Ljava/util/Set;->contains(Ljava/lang/Object;)Z move-result v0 return v0 .end method .method public ᐠ()I .locals 1 iget v0, p0, Lcom/google/android/gms/internal/pi;->ﹳ:I return v0 .end method .method public ᐡ()Z .locals 1 iget-boolean v0, p0, Lcom/google/android/gms/internal/pi;->ٴ:Z return v0 .end method .method public ᐣ()Z .locals 2 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˊ:Ljava/util/Set; const/16 v1, 0x18 invoke-static {v1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer; move-result-object v1 invoke-interface {v0, v1}, Ljava/util/Set;->contains(Ljava/lang/Object;)Z move-result v0 return v0 .end method .method public ᐧ()Z .locals 2 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˊ:Ljava/util/Set; const/16 v1, 0x8 invoke-static {v1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer; move-result-object v1 invoke-interface {v0, v1}, Ljava/util/Set;->contains(Ljava/lang/Object;)Z move-result v0 return v0 .end method .method public ᐨ()Ljava/lang/String; .locals 1 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ι:Ljava/lang/String; return-object v0 .end method .method public ᐩ()I .locals 1 iget v0, p0, Lcom/google/android/gms/internal/pi;->゙:I return v0 .end method .method public ᐪ()Z .locals 2 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˊ:Ljava/util/Set; const/16 v1, 0x1d invoke-static {v1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer; move-result-object v1 invoke-interface {v0, v1}, Ljava/util/Set;->contains(Ljava/lang/Object;)Z move-result v0 return v0 .end method .method public ᑊ()Z .locals 2 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˊ:Ljava/util/Set; const/16 v1, 0x19 invoke-static {v1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer; move-result-object v1 invoke-interface {v0, v1}, Ljava/util/Set;->contains(Ljava/lang/Object;)Z move-result v0 return v0 .end method .method public ᒽ()Lcom/google/android/gms/internal/pi; .locals 0 return-object p0 .end method .method public ᕀ()Ljava/lang/String; .locals 1 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ʹ:Ljava/lang/String; return-object v0 .end method .method public ᴵ()Z .locals 2 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˊ:Ljava/util/Set; const/16 v1, 0xf invoke-static {v1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer; move-result-object v1 invoke-interface {v0, v1}, Ljava/util/Set;->contains(Ljava/lang/Object;)Z move-result v0 return v0 .end method .method public ᵎ()Z .locals 1 iget-boolean v0, p0, Lcom/google/android/gms/internal/pi;->ˉ:Z return v0 .end method .method public ᵔ()Z .locals 2 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˊ:Ljava/util/Set; const/16 v1, 0x10 invoke-static {v1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer; move-result-object v1 invoke-interface {v0, v1}, Ljava/util/Set;->contains(Ljava/lang/Object;)Z move-result v0 return v0 .end method .method public ᵕ()Z .locals 2 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˊ:Ljava/util/Set; const/16 v1, 0x1a invoke-static {v1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer; move-result-object v1 invoke-interface {v0, v1}, Ljava/util/Set;->contains(Ljava/lang/Object;)Z move-result v0 return v0 .end method .method public ᵢ()Ljava/lang/String; .locals 1 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˌ:Ljava/lang/String; return-object v0 .end method .method public ᵣ()Ljava/lang/String; .locals 1 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ՙ:Ljava/lang/String; return-object v0 .end method .method public ⁱ()Z .locals 2 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˊ:Ljava/util/Set; const/16 v1, 0x12 invoke-static {v1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer; move-result-object v1 invoke-interface {v0, v1}, Ljava/util/Set;->contains(Ljava/lang/Object;)Z move-result v0 return v0 .end method .method public יִ()Z .locals 2 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˊ:Ljava/util/Set; const/16 v1, 0x1b invoke-static {v1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer; move-result-object v1 invoke-interface {v0, v1}, Ljava/util/Set;->contains(Ljava/lang/Object;)Z move-result v0 return v0 .end method .method public יּ()Ljava/util/List; .locals 1 .annotation system Ldalvik/annotation/Signature; value = { "()Ljava/util/List<Lo/uS$\u141d;>;" } .end annotation iget-object v0, p0, Lcom/google/android/gms/internal/pi;->י:Ljava/util/List; check-cast v0, Ljava/util/ArrayList; return-object v0 .end method .method public ﹳ()Z .locals 2 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˊ:Ljava/util/Set; const/16 v1, 0x9 invoke-static {v1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer; move-result-object v1 invoke-interface {v0, v1}, Ljava/util/Set;->contains(Ljava/lang/Object;)Z move-result v0 return v0 .end method .method public ﹶ()Lo/uS$iF; .locals 1 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˍ:Lcom/google/android/gms/internal/pi$d; return-object v0 .end method .method public ﹺ()Z .locals 2 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˊ:Ljava/util/Set; const/16 v1, 0x13 invoke-static {v1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer; move-result-object v1 invoke-interface {v0, v1}, Ljava/util/Set;->contains(Ljava/lang/Object;)Z move-result v0 return v0 .end method .method public ー()Ljava/lang/String; .locals 1 iget-object v0, p0, Lcom/google/android/gms/internal/pi;->ˑ:Ljava/lang/String; return-object v0 .end method .method public ゙()I .locals 1 iget v0, p0, Lcom/google/android/gms/internal/pi;->ʾ:I return v0 .end method
{'content_hash': '1ad501977e2ae7d1d781b9b1f21a4f45', 'timestamp': '', 'source': 'github', 'line_count': 1933, 'max_line_length': 561, 'avg_line_length': 25.004138644593894, 'alnum_prop': 0.6828874681894358, 'repo_name': 'gelldur/jak_oni_to_robia_prezentacja', 'id': '61a3838db697f707cd6ef46b9365a25df69e363c', 'size': '48690', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Starbucks/output/smali/com/google/android/gms/internal/pi.smali', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '8427'}, {'name': 'Shell', 'bytes': '2303'}, {'name': 'Smali', 'bytes': '57557982'}]}
package japicmp.model; import japicmp.util.Optional; import javassist.bytecode.annotation.Annotation; import javassist.bytecode.annotation.MemberValue; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlTransient; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; public class JApiAnnotation implements JApiHasChangeStatus, JApiCompatibility { private final String fullyQualifiedName; private final Optional<Annotation> oldAnnotation; private final Optional<Annotation> newAnnotation; private final List<JApiAnnotationElement> elements = new LinkedList<>(); private final JApiChangeStatus changeStatus; public JApiAnnotation(String fullyQualifiedName, Optional<Annotation> oldAnnotation, Optional<Annotation> newAnnotation, JApiChangeStatus changeStatus) { this.fullyQualifiedName = fullyQualifiedName; this.oldAnnotation = oldAnnotation; this.newAnnotation = newAnnotation; computeElements(this.elements, oldAnnotation, newAnnotation); this.changeStatus = evaluateChangeStatus(changeStatus); } public String toString() { return "JApiAnnotation [fullyQualifiedName=" + fullyQualifiedName + ", oldAnnotation=" + oldAnnotation + ", newAnnotation=" + newAnnotation + ", changeStatus=" + changeStatus + ", compatibilityChanges=" + getCompatibilityChanges() + "]"; } private void computeElements(List<JApiAnnotationElement> elements, Optional<Annotation> oldAnnotationOptional, Optional<Annotation> newAnnotationOptional) { if (oldAnnotationOptional.isPresent() && newAnnotationOptional.isPresent()) { Annotation oldAnnotation = oldAnnotationOptional.get(); Annotation newAnnotation = newAnnotationOptional.get(); Map<String, Optional<MemberValue>> oldMemberValueMap = buildMemberValueMap(oldAnnotation); Map<String, Optional<MemberValue>> newMemberValueMap = buildMemberValueMap(newAnnotation); for (String memberName : oldMemberValueMap.keySet()) { Optional<MemberValue> foundOptional = newMemberValueMap.get(memberName); if (foundOptional == null) { JApiAnnotationElement jApiAnnotationElement = new JApiAnnotationElement(memberName, oldMemberValueMap.get(memberName), Optional.<MemberValue>absent(), JApiChangeStatus.REMOVED); elements.add(jApiAnnotationElement); } else { JApiAnnotationElement jApiAnnotationElement = new JApiAnnotationElement(memberName, oldMemberValueMap.get(memberName), foundOptional, JApiChangeStatus.UNCHANGED); elements.add(jApiAnnotationElement); } } for (String memberName : newMemberValueMap.keySet()) { Optional<MemberValue> foundOptional = oldMemberValueMap.get(memberName); if (foundOptional == null) { JApiAnnotationElement jApiAnnotationElement = new JApiAnnotationElement(memberName, Optional.<MemberValue>absent(), newMemberValueMap.get(memberName), JApiChangeStatus.NEW); elements.add(jApiAnnotationElement); } } } else { if (oldAnnotationOptional.isPresent()) { Annotation oldAnnotation = oldAnnotationOptional.get(); Map<String, Optional<MemberValue>> oldMemberValueMap = buildMemberValueMap(oldAnnotation); for (String memberName : oldMemberValueMap.keySet()) { JApiAnnotationElement jApiAnnotationElement = new JApiAnnotationElement(memberName, oldMemberValueMap.get(memberName), Optional.<MemberValue>absent(), JApiChangeStatus.REMOVED); elements.add(jApiAnnotationElement); } } if (newAnnotationOptional.isPresent()) { Annotation newAnnotation = newAnnotationOptional.get(); Map<String, Optional<MemberValue>> newMemberValueMap = buildMemberValueMap(newAnnotation); for (String memberName : newMemberValueMap.keySet()) { JApiAnnotationElement jApiAnnotationElement = new JApiAnnotationElement(memberName, Optional.<MemberValue>absent(), newMemberValueMap.get(memberName), JApiChangeStatus.NEW); elements.add(jApiAnnotationElement); } } } } private Map<String, Optional<MemberValue>> buildMemberValueMap(Annotation annotation) { Map<String, Optional<MemberValue>> map = new HashMap<>(); @SuppressWarnings("unchecked") Set<String> memberNames = annotation.getMemberNames(); if (memberNames != null) { for (String memberName : memberNames) { MemberValue memberValue = annotation.getMemberValue(memberName); if (memberValue == null) { map.put(memberName, Optional.<MemberValue>absent()); } else { map.put(memberName, Optional.of(memberValue)); } } } return map; } private JApiChangeStatus evaluateChangeStatus(JApiChangeStatus changeStatus) { if (changeStatus == JApiChangeStatus.UNCHANGED) { for (JApiAnnotationElement annotationElement : elements) { if (annotationElement.getChangeStatus() != JApiChangeStatus.UNCHANGED) { changeStatus = JApiChangeStatus.MODIFIED; } } } return changeStatus; } @Override @XmlAttribute(name = "changeStatus") public JApiChangeStatus getChangeStatus() { return this.changeStatus; } @XmlAttribute(name = "fullyQualifiedName") public String getFullyQualifiedName() { return fullyQualifiedName; } @XmlTransient public Optional<Annotation> getOldAnnotation() { return oldAnnotation; } @XmlTransient public Optional<Annotation> getNewAnnotation() { return newAnnotation; } @XmlElementWrapper(name = "elements") @XmlElement(name = "element") public List<JApiAnnotationElement> getElements() { return elements; } @Override @XmlAttribute public boolean isBinaryCompatible() { return true; } @Override @XmlAttribute public boolean isSourceCompatible() { return true; } @XmlElementWrapper(name = "compatibilityChanges") @XmlElement(name = "compatibilityChange") public List<JApiCompatibilityChange> getCompatibilityChanges() { return Collections.emptyList(); } }
{'content_hash': '07655c3379b49266b25c74ae631144e4', 'timestamp': '', 'source': 'github', 'line_count': 170, 'max_line_length': 157, 'avg_line_length': 35.44705882352941, 'alnum_prop': 0.7675074676402257, 'repo_name': 'siom79/japicmp', 'id': '25167abade14cb70e0521a65c7e80334b3ed0a29', 'size': '6026', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'japicmp/src/main/java/japicmp/model/JApiAnnotation.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '2663'}, {'name': 'Groovy', 'bytes': '621'}, {'name': 'Java', 'bytes': '1217765'}, {'name': 'Python', 'bytes': '1779'}, {'name': 'Shell', 'bytes': '364'}, {'name': 'XSLT', 'bytes': '34034'}]}
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Client Tests</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> {{content-for "head"}} {{content-for "test-head"}} <link rel="stylesheet" href="{{rootURL}}assets/vendor.css"> <link rel="stylesheet" href="{{rootURL}}assets/client.css"> <link rel="stylesheet" href="{{rootURL}}assets/test-support.css"> {{content-for "head-footer"}} {{content-for "test-head-footer"}} </head> <body> {{content-for "body"}} {{content-for "test-body"}} <script src="/testem.js" integrity=""></script> <script src="{{rootURL}}assets/vendor.js"></script> <script src="{{rootURL}}assets/test-support.js"></script> <script src="{{rootURL}}assets/client.js"></script> <script src="{{rootURL}}assets/tests.js"></script> {{content-for "body-footer"}} {{content-for "test-body-footer"}} </body> </html>
{'content_hash': '5904a2dd45dc6df9f41f3f0e59dbfd90', 'timestamp': '', 'source': 'github', 'line_count': 33, 'max_line_length': 72, 'avg_line_length': 31.757575757575758, 'alnum_prop': 0.6240458015267175, 'repo_name': 'davideferre/django-ember-jwt-tutorial', 'id': '080d471b1901a0d4ad5ce6d13138eecc0fa6f767', 'size': '1048', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'client/tests/index.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '5852'}, {'name': 'JavaScript', 'bytes': '17203'}, {'name': 'Python', 'bytes': '18067'}]}
normalize-package data exports a function that normalizes package metadata. This data is typically found in a package.json file, but in principle could come from any source - for example the npm registry. normalize-package-data is used by [read-package-json](https://npmjs.org/package/read-package-json) to normalize the data it reads from a package.json file. In turn, read-package-json is used by [npm](https://npmjs.org/package/npm) and various npm-related tools. ## Installation ``` npm install normalize-package-data ``` ## Usage Basic usage is really simple. You call the function that normalize-package-data exports. Let's call it `normalizeData`. ```javascript normalizeData = require('normalize-package-data') packageData = fs.readfileSync("package.json") normalizeData(packageData) // packageData is now normalized ``` Optionally, you may pass a "warning" function. It gets called whenever the normalizeData function encounters something that doesn't look right. It indicates less than perfect input data. ```javascript normalizeData = require('normalize-package-data') packageData = fs.readfileSync("package.json") warnFn = function(msg) { console.error(msg) } normalizeData(packageData, warnFn) // packageData is now normalized. Any number of warnings may have been logged. ``` If you don't provide a warning function, `normalizeData` functions silently. ### Potential exceptions If the supplied data has an invalid name or version vield, `normalizeData` will throw an error. Depending on where you call `normalizeData`, you may want to catch these errors so can pass them to a callback. ## What normalization (currently) entails * The value of `name` field gets trimmed. * The value of the `version` field gets cleaned by `semver.clean`. See [documentation for the semver module](https://github.com/isaacs/node-semver). * If `name` and/or `version` fields are missing, they are set to empty strings. * If `files` field is not an array, it will be removed. * If `bin` field is a string, then `bin` field will become an object with `name` set to the value of the `name` field, and `bin` set to the original string value. * If `man` field is a string, it will become an array with the original string as its sole member. * If `keywords` field is string, it is considered to be a list of keywords separated by one or more white-space characters. It gets converted to an array by splitting on `\s+`. * All people fields (`author`, `maintainers`, `contributors`) get converted into objects with name, email and url properties. * If `bundledDependencies` field (a typo) exists and `bundleDependencies` field does not, `bundledDependencies` will get renamed to `bundleDependencies`. * If the value of any of the dependencies fields (`dependencies`, `devDependencies`, `optionalDependencies`) is a string, it gets converted into an object with familiar `name=>value` pairs. * The values in `optionalDependencies` get added to `dependencies`. The `optionalDependencies` array is left untouched. * If `description` field does not exists, but `readme` field does, then (more or less) the first paragraph of text that's found in the readme is taken as value for `description`. * If `repository` field is a string, it will become an object with `url` set to the original string value, and `type` set to `"git"`. * If `bugs` field is a string, the value of `bugs` field is changed into an object with `url` set to the original string value. * If `bugs` field does not exist, but `repository` field points to a repository hosted on GitHub, the value of the `bugs` field gets set to an url in the form of https://github.com/[owner-name]/[repo-name]/issues . If the repository field points to a GitHub Gist repo url, the associated http url is chosen. * If `bugs` field is an object, the resulting value only has email and url properties. If email and url properties are not strings, they are ignored. If no valid values for either email or url is found, bugs field will be removed. * If `homepage` field is not a string, it will be removed. ### Rules for name field If `name` field is given, the value of the name field must be a string. The string may not: * start with a period. * contain the following characters: `/@\s+%` * contain and characters that would need to be encoded for use in urls. * resemble the word `node_modules` or `favicon.ico` (case doesn't matter). ### Rules for version field If `version` field is given, the value of the version field must be a valid *semver* string, as determined by the `semver.valid` method. See [documentation for the semver module](https://github.com/isaacs/node-semver). ## Credits This package contains code based on read-package-json written by Isaac Z. Schlueter. Used with permisson. ## License normalize-package-data is released under the [BSD 2-Clause License](http://opensource.org/licenses/MIT). Copyright (c) 2013 Meryn Stol
{'content_hash': 'c1859cdbf28ddaba0f3a39e32f6d5963', 'timestamp': '', 'source': 'github', 'line_count': 78, 'max_line_length': 307, 'avg_line_length': 62.88461538461539, 'alnum_prop': 0.7602446483180428, 'repo_name': 'fschwiet/letscodejavascript', 'id': '5712bd9ee24044e424ecebe4c3fc30f1ffe7d9d7', 'size': '5071', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'node_modules/npm/node_modules/read-package-json/node_modules/normalize-package-data/README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '36'}, {'name': 'CSS', 'bytes': '176'}, {'name': 'HTML', 'bytes': '67517'}, {'name': 'JavaScript', 'bytes': '423046'}, {'name': 'PowerShell', 'bytes': '69'}, {'name': 'Ruby', 'bytes': '625120'}, {'name': 'Shell', 'bytes': '24711'}]}
<!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 (version 1.6.0_27) on Thu Jan 23 20:13:25 EST 2014 --> <meta http-equiv="Content-Type" content="text/html" charset="utf-8"> <title>Uses of Class org.apache.lucene.queryparser.xml.builders.DuplicateFilterBuilder (Lucene 4.6.1 API)</title> <meta name="date" content="2014-01-23"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.lucene.queryparser.xml.builders.DuplicateFilterBuilder (Lucene 4.6.1 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/apache/lucene/queryparser/xml/builders/DuplicateFilterBuilder.html" title="class in org.apache.lucene.queryparser.xml.builders">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>PREV</li> <li>NEXT</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/apache/lucene/queryparser/xml/builders//class-useDuplicateFilterBuilder.html" target="_top">FRAMES</a></li> <li><a href="DuplicateFilterBuilder.html" target="_top">NO FRAMES</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.lucene.queryparser.xml.builders.DuplicateFilterBuilder" class="title">Uses of Class<br>org.apache.lucene.queryparser.xml.builders.DuplicateFilterBuilder</h2> </div> <div class="classUseContainer">No usage of org.apache.lucene.queryparser.xml.builders.DuplicateFilterBuilder</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/apache/lucene/queryparser/xml/builders/DuplicateFilterBuilder.html" title="class in org.apache.lucene.queryparser.xml.builders">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>PREV</li> <li>NEXT</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/apache/lucene/queryparser/xml/builders//class-useDuplicateFilterBuilder.html" target="_top">FRAMES</a></li> <li><a href="DuplicateFilterBuilder.html" target="_top">NO FRAMES</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> <i>Copyright &copy; 2000-2014 Apache Software Foundation. All Rights Reserved.</i> <script src='../../../../../../../prettify.js' type='text/javascript'></script> <script type='text/javascript'> (function(){ var oldonload = window.onload; if (typeof oldonload != 'function') { window.onload = prettyPrint; } else { window.onload = function() { oldonload(); prettyPrint(); } } })(); </script> </small></p> </body> </html>
{'content_hash': '64440d85d14a3a057945b410cd1062b5', 'timestamp': '', 'source': 'github', 'line_count': 131, 'max_line_length': 193, 'avg_line_length': 39.343511450381676, 'alnum_prop': 0.6055490880869228, 'repo_name': 'OrlandoLee/ForYou', 'id': 'a901e206e3b194d1224547f32fc5998f0d53ff25', 'size': '5154', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lucene/lib/lucene-4.6.1/docs/queryparser/org/apache/lucene/queryparser/xml/builders/class-use/DuplicateFilterBuilder.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '294179'}, {'name': 'Java', 'bytes': '4850924'}, {'name': 'JavaScript', 'bytes': '8728'}, {'name': 'Ruby', 'bytes': '15745'}, {'name': 'Shell', 'bytes': '368'}]}
'use strict'; var assert = require('assert'); var utils = require('../utils'); /** * Persist a value and associate it with the given key. * * @param {String} key Key to associate with the given value. * @param {*} value Value to persist. * @options {Number|Object} options Optional settings for the key-value * pair. If a Number is provided, it is set as the TTL (time to live) in ms * (milliseconds) for the key-value pair. * @property {Number} ttl TTL for the key-value pair in ms. * @callback {Function} callback * @param {Error} err Error object. * @promise * * @header KVAO.set(key, value, cb) */ module.exports = function keyValueSet(key, value, options, callback) { if (callback == undefined && typeof options === 'function') { callback = options; options = {}; } else if (typeof options === 'number') { options = {ttl: options}; } else if (!options) { options = {}; } assert(typeof key === 'string' && key, 'key must be a non-empty string'); assert(value != null, 'value must be defined and not null'); assert(typeof options === 'object', 'options must be an object'); if (options && 'ttl' in options) { assert(typeof options.ttl === 'number' && options.ttl > 0, 'options.ttl must be a positive number'); } callback = callback || utils.createPromiseCallback(); // TODO convert possible model instance in "value" to raw data via toObect() this.getConnector().set(this.modelName, key, value, options, callback); return callback.promise; };
{'content_hash': '5f61d202a12541d50c9d1b5a9bdc92a1', 'timestamp': '', 'source': 'github', 'line_count': 44, 'max_line_length': 78, 'avg_line_length': 34.56818181818182, 'alnum_prop': 0.6594345825115056, 'repo_name': 'coderReview/NTL-ISS-Food-Intake-Tracker', 'id': '15bd224b508c2e1c8be14b752c2da1ddc0805272', 'size': '1521', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'Backend Services/issfit-api/node_modules/loopback-datasource-juggler/lib/kvao/set.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '7674'}, {'name': 'CSS', 'bytes': '70936'}, {'name': 'HTML', 'bytes': '1081112'}, {'name': 'JavaScript', 'bytes': '622475'}, {'name': 'Objective-C', 'bytes': '2337557'}, {'name': 'Objective-C++', 'bytes': '10637'}, {'name': 'PLpgSQL', 'bytes': '30687'}, {'name': 'Python', 'bytes': '40699'}, {'name': 'Ruby', 'bytes': '1374'}, {'name': 'Shell', 'bytes': '6454'}]}
class StandardInterviewImporter < GenericImporter end
{'content_hash': 'ac47361084e080609e3c3fbb0d52c74c', 'timestamp': '', 'source': 'github', 'line_count': 2, 'max_line_length': 49, 'avg_line_length': 27.0, 'alnum_prop': 0.8888888888888888, 'repo_name': 'ministryofjustice/case_file_editor', 'id': 'dda97e764055fa4451cebb7cbec33dbf030d6538', 'size': '54', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/importers/standard_interview_importer.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '52179'}, {'name': 'HTML', 'bytes': '7465'}, {'name': 'JavaScript', 'bytes': '106'}, {'name': 'Ruby', 'bytes': '176660'}]}
package org.movie.tools; /** * 常量类 * @author Administrator * */ public interface Constant { public static final int DEFAULTPAGENUM=1; public static final int DEFAULTPAGESIZE=10; public static final int ZERO=0; public static final int ONE=1; public static final int LOGGED_IN=1; //登陆 public static final int NOT_LOGGED_IN=0;//未登陆 public static final int PORTALTYPE_WWW=0; public static final int PORTALTYPE_WAP=1; public static final int PORTALTYPE_CLIENT=2; }
{'content_hash': 'a4330b769ecd62b2324f56f30d158127', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 46, 'avg_line_length': 29.0, 'alnum_prop': 0.7241379310344828, 'repo_name': 'ppyang010/MovieNews', 'id': '13db9a1ac9a00c69c76df0e4cc3e68f383b87296', 'size': '509', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'movie-news-demo/movie-news-demo/src/main/java/org/movie/tools/Constant.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '251502'}, {'name': 'FreeMarker', 'bytes': '98444'}, {'name': 'Java', 'bytes': '243010'}, {'name': 'JavaScript', 'bytes': '221894'}]}
/* PROPhEcy (c) by Christian Winkel PROPhEcy is licensed under a Creative Commons Attribution 4.0 International License. You should have received a copy of the license along with this work. If not, see <http://creativecommons.org/licenses/by/4.0/>. */ package com.prophecy.network; /** * Created by Christian Winkel on 24.04.14. */ public interface INetConnection { //---------------------------------------- // Interface Functions //---------------------------------------- /** * Initializes the connection * with the specific client. * @param client The client. */ public void initialize(NetClient client); /** * Disconnects the network connection. */ public void disconnect(); } // interface INetConnection
{'content_hash': '17464241a471421a6ba97ce943628a2d', 'timestamp': '', 'source': 'github', 'line_count': 36, 'max_line_length': 64, 'avg_line_length': 21.666666666666668, 'alnum_prop': 0.6064102564102564, 'repo_name': 'Project-PROPhEcy/PROPhEcy-Framework', 'id': '58bbdffd19e31ba41e6444149ca8795faab28129', 'size': '780', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/com/prophecy/network/INetConnection.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '261482'}]}
FROM balenalib/imx8m-var-dart-ubuntu:impish-build ENV NODE_VERSION 12.22.9 ENV YARN_VERSION 1.22.4 RUN for key in \ 6A010C5166006599AA17F08146C2130DFD2497F5 \ ; do \ gpg --keyserver pgp.mit.edu --recv-keys "$key" || \ gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \ gpg --keyserver keyserver.ubuntu.com --recv-keys "$key" ; \ done \ && curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-arm64.tar.gz" \ && echo "307aa26c68600e2f73d699e58a15c59ea06928e4a348cd5a216278d9f2ee0d6c node-v$NODE_VERSION-linux-arm64.tar.gz" | sha256sum -c - \ && tar -xzf "node-v$NODE_VERSION-linux-arm64.tar.gz" -C /usr/local --strip-components=1 \ && rm "node-v$NODE_VERSION-linux-arm64.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \ && gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && mkdir -p /opt/yarn \ && tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \ && rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && npm config set unsafe-perm true -g --unsafe-perm \ && rm -rf /tmp/* CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \ && echo "Running test-stack@node" \ && chmod +x [email protected] \ && bash [email protected] \ && rm -rf [email protected] RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Ubuntu impish \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v12.22.9, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
{'content_hash': '8f9ca20864d36a3b98486cdd82c1a537', 'timestamp': '', 'source': 'github', 'line_count': 41, 'max_line_length': 694, 'avg_line_length': 66.73170731707317, 'alnum_prop': 0.7097953216374269, 'repo_name': 'resin-io-library/base-images', 'id': 'd5d8276e7b1a84c83903d7135345d80513987d5a', 'size': '2757', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'balena-base-images/node/imx8m-var-dart/ubuntu/impish/12.22.9/build/Dockerfile', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Dockerfile', 'bytes': '71234697'}, {'name': 'JavaScript', 'bytes': '13096'}, {'name': 'Shell', 'bytes': '12051936'}, {'name': 'Smarty', 'bytes': '59789'}]}
package com.thebluealliance.androidclient.database.writers; import androidx.annotation.WorkerThread; import com.google.common.collect.ImmutableList; import com.thebluealliance.androidclient.database.Database; import com.thebluealliance.androidclient.models.Event; import java.util.List; import javax.inject.Inject; public class EventListWriter extends BaseDbWriter<List<Event>> { @Inject public EventListWriter(Database db) { super(db); } @Override @WorkerThread public void write(List<Event> events, Long lastModified) { mDb.getEventsTable().add(ImmutableList.copyOf(events), lastModified); } }
{'content_hash': '8d7e4d0869b33e5647fdfd4eb84ba44d', 'timestamp': '', 'source': 'github', 'line_count': 24, 'max_line_length': 77, 'avg_line_length': 26.875, 'alnum_prop': 0.7643410852713178, 'repo_name': 'the-blue-alliance/the-blue-alliance-android', 'id': 'ac9f02586d51f9fe0a7b37d7990434b3a7f90df0', 'size': '645', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'android/src/main/java/com/thebluealliance/androidclient/database/writers/EventListWriter.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '2389864'}, {'name': 'Python', 'bytes': '25030'}, {'name': 'Shell', 'bytes': '12409'}]}
import itertools import os import os.path import sys import argparse import logging import numpy as np #experiments on sampled_small data EXPERIMENTS = ['symm', 'impl', 'impl_inv', 'trans_single', 'trans_diff'] #EXPERIMENTS = ['impl', 'trans_diff'] confs = ['0.0'] versions = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] #different random seeds EXPERIMENTS = ['{}_c{}_v{}'.format(exp, conf, version) for exp in EXPERIMENTS for conf in confs for version in versions] #EXPERIMENTS = ['exp_symm', 'exp_impl', 'exp_impl_inv', 'exp_impl_conj', 'exp_trans_single', 'exp_trans_diff'] #USER = '/home/pminervi/workspace/' USER = '/users/tdmeeste/workspace/' """ Notes: - for now: validation on training data; no hyperparam tuning """ def cartesian_product(dicts): return list(dict(zip(dicts, x)) for x in itertools.product(*dicts.values())) def summary(configuration): kvs = sorted([(k, v) for k, v in configuration.items()], key=lambda e: e[0]) return '_'.join([('%s=%s' % (k, v)) for (k, v) in kvs]) def to_cmd(c, _path=None): if _path is None: _path = USER + 'inferbeddings/' command = 'python3 {}/bin/kbp-cli.py --auc' \ ' --train {}/data/synth/sampled_small/{}_train.tsv' \ ' --valid {}/data/synth/sampled_small/{}_valid.tsv' \ ' --test {}/data/synth/sampled_small/{}_test.tsv' \ ' --clauses {}/data/synth/sampled_small/{}_clauses.pl' \ ' --nb-epochs {}' \ ' --lr {}' \ ' --nb-batches {}' \ ' --model {}' \ ' --similarity {}' \ ' --loss hinge' \ ' --margin 1' \ ' --embedding-size {}' \ ' --subsample-size {}' \ ' --adv-lr {} --adversary-epochs {}' \ ' --discriminator-epochs {} --adv-weight {} --adv-batch-size {}' \ ' --adv-pooling max' \ ''.format(_path, _path, c['tag'], _path, c['tag'], _path, c['tag'], _path, c['tag'], c['epochs'], c['lr'], c['batches'], c['model'], c['similarity'], c['embedding_size'], c['subsample_size'], c['adv_lr'], c['adv_epochs'], c['disc_epochs'], c['adv_weight'], c['adv_batch_size']) if c['adv_init_ground']: command += ' --adv-init-ground' if c['entity_space'] == 'unit-cube': command += ' --unit-cube' # ' --adv-ground-samples 100 --adv-ground-tol 0.1' \ return command def to_logfile(c, path): outfile = "%s/synth.%s.log" % (path, summary(c)) return outfile def main(argv): def formatter(prog): return argparse.HelpFormatter(prog, max_help_position=100, width=200) argparser = argparse.ArgumentParser('Generating experiments for the UCL cluster', formatter_class=formatter) argparser.add_argument('--debug', '-D', action='store_true', help='Debug flag') argparser.add_argument('--path', '-p', action='store', type=str, default=None, help='Path') args = argparser.parse_args(argv) # hyperparameters_space_transe = dict( # tag=EXPERIMENTS, # epochs=[100], # lr=[0.1], # batches=[10], # model=['TransE'], # similarity=['l1'], # embedding_size=[20], # subsample_size=[1], # adv_lr=[0.1], # adv_epochs=[0, 10], # disc_epochs=[10], # adv_weight=[0, 1], # adv_batch_size=[100], # adv_init_ground=[True] # ) hyperparameters_space_distmult_complex = dict( tag=EXPERIMENTS, epochs=[100], lr=[0.1], batches=[10], model=['DistMult', 'ComplEx'], similarity=['dot'], embedding_size=[20], subsample_size=[1], adv_lr=[0.1], adv_epochs=[10], #[0, 10] disc_epochs=[10], adv_weight=[0, 1], adv_batch_size=[100], adv_init_ground=[True], entity_space=['unit-cube', 'unit-sphere'] ) # configurations_transe = cartesian_product(hyperparameters_space_transe) # configurations_distmult_complex = cartesian_product(hyperparameters_space_distmult_complex) configurations = cartesian_product(hyperparameters_space_distmult_complex) path = USER + 'inferbeddings/logs/synth/synth_paper_iterative' if not os.path.exists(path): os.makedirs(path) # configurations = list(configurations_transe) + list(configurations_distmult_complex) np.random.shuffle(configurations) #prune configurations by hand, for combinations that aren't needed configurations_pruned = [] for c in configurations: add = True # if c['adv_weight'] == 0 and c['adv_epochs'] == 10: # add = False if add: configurations_pruned.append(c) configurations = configurations_pruned for job_id, cfg in enumerate(configurations): logfile = to_logfile(cfg, path) completed = False if os.path.isfile(logfile): with open(logfile, 'r', encoding='utf-8', errors='ignore') as f: content = f.read() completed = 'AUC-PR' in content if not completed: line = '{} > {} 2>&1'.format(to_cmd(cfg, _path=args.path), logfile) print(line) if __name__ == '__main__': logging.basicConfig(level=logging.INFO) main(sys.argv[1:])
{'content_hash': 'ac0075d7685504603d57fc357ac9ca3a', 'timestamp': '', 'source': 'github', 'line_count': 173, 'max_line_length': 120, 'avg_line_length': 31.653179190751445, 'alnum_prop': 0.547845142439737, 'repo_name': 'uclmr/inferbeddings', 'id': '7157be9f461b1b94e81b48b6cab9174b4965195f', 'size': '5524', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'scripts/synth/synth_paper_iterative.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Jupyter Notebook', 'bytes': '102860'}, {'name': 'Prolog', 'bytes': '569340'}, {'name': 'Python', 'bytes': '1319760'}, {'name': 'R', 'bytes': '769'}, {'name': 'Shell', 'bytes': '22689'}]}
import { h } from 'preact'; import { injectIntl, FormattedMessage } from 'preact-intl'; import { Field } from 'redux-form'; import renderField from '../renderField'; import emailConfirmation from './emailConfirmation'; import emailPrivacy from './emailPrivacy'; import emailPrimary from './emailPrimary'; const Emails = injectIntl(({ fields, onConfirm, onTogglePrivacy, onMakePrimary, userId, meta: { error, submitFailed }, intl }) => ( <div> <legend> <FormattedMessage id="emails" defaultMessage="Emails" /> </legend> {submitFailed && error && <span>{error}</span>} {/*console.log('userId:' + userId)*/} {fields.map((email, index) => ( <div key={index}> <div className="row"> <div className="col-sm-7 input-group"> <Field className="form-control" name={`${email}.email`} component={renderField} label="email" placeholder={intl.formatMessage({ id: 'email.placeholder', defaultMessage: '[email protected]' })} /> </div> <div className="col-sm-2 input-group"> <label className="form-check-label"> <Field className="form-check-input form-control-lg" name={`${email}.is_public`} component="input" type="checkbox" /> <FormattedMessage id="public" defaultMessage="Public" /> </label> </div> <div className="col-sm-1 input-group" onClick={() => onTogglePrivacy(userId, index)} > <Field className="form-control" name={`${email}.is_public`} component={emailPrivacy} /> </div> <div className="col-sm-1 input-group" onClick={() => onMakePrimary(userId, index)} > <Field className="form-control" name={`${email}.is_primary`} component={emailPrimary} /> </div> <div className="col-sm-1 input-group" onClick={() => onConfirm(userId, index)} > <Field className="form-control" name={`${email}.is_confirmed`} component={emailConfirmation} /> </div> <div className="col-sm-1"> <button type="button" className="btn btn-danger btn-sm" onClick={() => fields.remove(index)} > <i className="fa fa-trash" data-toggle="tooltip" data-placement="top" title={intl.formatMessage({ id: 'delete', defaultMessage: 'Delete' })} > </i> </button> </div> </div> </div> ))} <button type="button" className="btn btn-success btn-sm" onClick={() => fields.push({})}> <i className="fa fa-plus" data-toggle="tooltip" data-placement="top" title={intl.formatMessage({ id: 'add', defaultMessage: 'Add' })} > </i> </button> <label> <FormattedMessage id="addEmail" defaultMessage="Add Email" /> </label> </div> )); export default Emails;
{'content_hash': '8af429a0c75c8fb7ecd6f7322b93b04d', 'timestamp': '', 'source': 'github', 'line_count': 132, 'max_line_length': 62, 'avg_line_length': 28.992424242424242, 'alnum_prop': 0.4376796446302587, 'repo_name': 'angelsbaytech/AVnode.net', 'id': '57b45090f603c8ca3d1c7189ede1f2e23a0398a0', 'size': '3827', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/components/emails/Emails.js', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'CSS', 'bytes': '82076'}, {'name': 'HTML', 'bytes': '24471'}, {'name': 'JavaScript', 'bytes': '618265'}]}
import Ember from 'ember'; export default Ember.Route.extend({ model: function() { return this.get('userStore').find('account', null, {filter: {'kind_ne': ['service','agent']}, forceReload: true}); }, });
{'content_hash': '7109ade2648ff190202c40efb39a8070', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 118, 'avg_line_length': 30.571428571428573, 'alnum_prop': 0.6448598130841121, 'repo_name': 'nrvale0/ui', 'id': '1f2002f80930c341994b1f826cd838366f1f4e95', 'size': '214', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/admin-tab/accounts/index/route.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '148642'}, {'name': 'HTML', 'bytes': '517237'}, {'name': 'JavaScript', 'bytes': '881847'}, {'name': 'Shell', 'bytes': '11530'}, {'name': 'Standard ML', 'bytes': '1205'}]}
package com.kotcrab.vis.editor.module.editor; import com.badlogic.gdx.scenes.scene2d.ui.Table; /** * Modules implementing this interface provide UI table that is displayed on Settings window. * See {@link EditorSettingsModule} for default implementation. * @author Kotcrab */ public interface SettableModule { int PRIORITY_HIGHEST = 1000; int PRIORITY_HIGH = 750; int PRIORITY_NORMAL = 500; int PRIORITY_LOW = 250; int PRIORITY_LOWEST = 0; /** @return table that will be displayed in settings window, this method must always return same table instance */ Table getSettingsTable (); String getSettingsName (); boolean settingsChanged (); void settingsApply (); int getListPriority (); }
{'content_hash': 'b1538ffa6470ffafc5d588cb7fc905a2', 'timestamp': '', 'source': 'github', 'line_count': 29, 'max_line_length': 115, 'avg_line_length': 24.482758620689655, 'alnum_prop': 0.747887323943662, 'repo_name': 'intrigus/VisEditor', 'id': '993f2943198145f26248a7adcf84acd2996ce3f6', 'size': '1311', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'Editor/src/com/kotcrab/vis/editor/module/editor/SettableModule.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'GLSL', 'bytes': '1252'}, {'name': 'Java', 'bytes': '2479594'}]}
namespace Microsoft.Azure.Management.Internal.Network.Version2017_10_01.Models { using Newtonsoft.Json; using System.Linq; /// <summary> /// Contains SKU in an ExpressRouteCircuit. /// </summary> public partial class ExpressRouteCircuitSku { /// <summary> /// Initializes a new instance of the ExpressRouteCircuitSku class. /// </summary> public ExpressRouteCircuitSku() { CustomInit(); } /// <summary> /// Initializes a new instance of the ExpressRouteCircuitSku class. /// </summary> /// <param name="name">The name of the SKU.</param> /// <param name="tier">The tier of the SKU. Possible values are /// 'Standard' and 'Premium'. Possible values include: 'Standard', /// 'Premium'</param> /// <param name="family">The family of the SKU. Possible values are: /// 'UnlimitedData' and 'MeteredData'. Possible values include: /// 'UnlimitedData', 'MeteredData'</param> public ExpressRouteCircuitSku(string name = default(string), string tier = default(string), string family = default(string)) { Name = name; Tier = tier; Family = family; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets the name of the SKU. /// </summary> [JsonProperty(PropertyName = "name")] public string Name { get; set; } /// <summary> /// Gets or sets the tier of the SKU. Possible values are 'Standard' /// and 'Premium'. Possible values include: 'Standard', 'Premium' /// </summary> [JsonProperty(PropertyName = "tier")] public string Tier { get; set; } /// <summary> /// Gets or sets the family of the SKU. Possible values are: /// 'UnlimitedData' and 'MeteredData'. Possible values include: /// 'UnlimitedData', 'MeteredData' /// </summary> [JsonProperty(PropertyName = "family")] public string Family { get; set; } } }
{'content_hash': 'a873638b066994f3d71957871fe5fec9', 'timestamp': '', 'source': 'github', 'line_count': 64, 'max_line_length': 132, 'avg_line_length': 35.3125, 'alnum_prop': 0.5769911504424778, 'repo_name': 'naveedaz/azure-powershell', 'id': 'a944d4a18258e10b6ff706a95b3020fcfe5bb9e2', 'size': '2613', 'binary': False, 'copies': '4', 'ref': 'refs/heads/preview', 'path': 'src/Common/Commands.Common.Network/Version2017_10_01/Models/ExpressRouteCircuitSku.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '18388'}, {'name': 'C#', 'bytes': '60116091'}, {'name': 'HTML', 'bytes': '209'}, {'name': 'JavaScript', 'bytes': '4979'}, {'name': 'PHP', 'bytes': '41'}, {'name': 'PowerShell', 'bytes': '7094905'}, {'name': 'Ruby', 'bytes': '398'}, {'name': 'Shell', 'bytes': '50'}, {'name': 'Smalltalk', 'bytes': '2510'}, {'name': 'XSLT', 'bytes': '6114'}]}
"""Trivial model configuration.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from models import model class TrivialModel(model.CNNModel): """Trivial model configuration.""" def __init__(self, params=None): super(TrivialModel, self).__init__( 'trivial', 224 + 3, 32, 0.005, params=params) def add_inference(self, cnn): cnn.reshape([-1, 227 * 227 * 3]) cnn.affine(1) cnn.affine(4096) class TrivialCifar10Model(model.CNNModel): """Trivial cifar10 model configuration.""" def __init__(self, params=None): super(TrivialCifar10Model, self).__init__( 'trivial', 32, 32, 0.005, params=params) def add_inference(self, cnn): cnn.reshape([-1, 32 * 32 * 3]) cnn.affine(1) cnn.affine(4096) class TrivialSSD300Model(model.CNNModel): """Trivial SSD300 model configuration.""" def __init__(self, params=None): super(TrivialSSD300Model, self).__init__( 'trivial', 300, 32, 0.005, params=params) def add_inference(self, cnn): cnn.reshape([-1, 300 * 300 * 3]) cnn.affine(1) cnn.affine(4096) def get_input_shapes(self, subset): return [[32, 300, 300, 3], [32, 8732, 4], [32, 8732, 1], [32]] def loss_function(self, inputs, build_network_result): images, _, _, labels = inputs labels = tf.cast(labels, tf.int32) return super(TrivialSSD300Model, self).loss_function( (images, labels), build_network_result)
{'content_hash': '5f83df8a6da0a276e18728851d887b2e', 'timestamp': '', 'source': 'github', 'line_count': 56, 'max_line_length': 66, 'avg_line_length': 26.964285714285715, 'alnum_prop': 0.6496688741721854, 'repo_name': 'annarev/benchmarks', 'id': 'f9b3e62f7f62331fbd3484ddb091d8bda095f8ae', 'size': '2199', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'scripts/tf_cnn_benchmarks/models/trivial_model.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Python', 'bytes': '813002'}, {'name': 'Shell', 'bytes': '5545'}]}
namespace stx { struct Less { template<typename T, typename U> constexpr bool operator()(const T& t, const U& u) const { return t < u; } }; struct LessOrEqual { template<typename T, typename U> constexpr bool operator()(const T& t, const U& u) const { return t <= u; } }; struct Greater { template<typename T, typename U> constexpr bool operator()(const T& t, const U& u) const { return t > u; } }; struct GreaterOrEqual { template<typename T, typename U> constexpr bool operator()(const T& t, const U& u) const { return t >= u; } }; } #endif
{'content_hash': '4f965c4e753ba924ffa1ea8050f70e4b', 'timestamp': '', 'source': 'github', 'line_count': 42, 'max_line_length': 56, 'avg_line_length': 13.666666666666666, 'alnum_prop': 0.6498257839721254, 'repo_name': 'zahirtezcan/sticks', 'id': 'd62565dfecd09c514bbe1a9f7ad080cedffc0fe5', 'size': '635', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'stx/utility/Compare.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '165631'}, {'name': 'Makefile', 'bytes': '8374'}]}
#!/usr/bin/env python import boto import imp import json import os import subprocess import sys import webbrowser from distutils.spawn import find_executable from fabric.api import local, prompt, require, settings, task from fabric.state import env from glob import glob from oauth import get_document, get_credentials from time import sleep import app_config import assets import flat import render import utils from render_utils import load_graphic_config SPREADSHEET_COPY_URL_TEMPLATE = 'https://www.googleapis.com/drive/v2/files/%s/copy' SPREADSHEET_VIEW_TEMPLATE = 'https://docs.google.com/spreadsheet/ccc?key=%s#gid=1' """ Base configuration """ env.settings = None """ Environments Changing environment requires a full-stack test. An environment points to both a server and an S3 bucket. """ @task def production(): """ Run as though on production. """ env.settings = 'production' app_config.configure_targets(env.settings) @task def staging(): """ Run as though on staging. """ env.settings = 'staging' app_config.configure_targets(env.settings) """ Running the app """ @task def app(port='8000'): """ Serve app.py. """ local('gunicorn -b 0.0.0.0:%s --timeout 3600 --debug --reload app:wsgi_app' % port) """ Deployment Changes to deployment requires a full-stack test. Deployment has two primary functions: Pushing flat files to S3 and deploying code to a remote server if required. """ @task def deploy(slug): """ Deploy the latest app to S3 and, if configured, to our servers. """ require('settings', provided_by=[production, staging]) if not slug: print 'You must specify a project slug, like this: "deploy:slug"' return graphic_root = '%s/%s' % (app_config.GRAPHICS_PATH, slug) s3_root = '%s/graphics/%s' % (app_config.PROJECT_SLUG, slug) graphic_assets = '%s/assets' % graphic_root s3_assets = '%s/assets' % s3_root graphic_config = load_graphic_config(graphic_root) use_assets = getattr(graphic_config, 'USE_ASSETS', True) default_max_age = getattr(graphic_config, 'DEFAULT_MAX_AGE', None) or app_config.DEFAULT_MAX_AGE assets_max_age = getattr(graphic_config, 'ASSETS_MAX_AGE', None) or app_config.ASSETS_MAX_AGE update_copy(slug) if use_assets: assets.sync(slug) render.render(slug) flat.deploy_folder( graphic_root, s3_root, headers={ 'Cache-Control': 'max-age=%i' % default_max_age }, ignore=['%s/*' % graphic_assets] ) # Deploy parent assets flat.deploy_folder( 'www', app_config.PROJECT_SLUG, headers={ 'Cache-Control': 'max-age=%i' % default_max_age } ) if use_assets: flat.deploy_folder( graphic_assets, s3_assets, headers={ 'Cache-Control': 'max-age=%i' % assets_max_age } ) print '' print '%s URL: %s/graphics/%s/' % (env.settings.capitalize(), app_config.S3_BASE_URL, slug) def download_copy(slug): """ Downloads a Google Doc as an .xlsx file. """ graphic_path = '%s/%s' % (app_config.GRAPHICS_PATH, slug) try: graphic_config = load_graphic_config(graphic_path) except IOError: print '%s/graphic_config.py does not exist.' % slug return if not hasattr(graphic_config, 'COPY_GOOGLE_DOC_KEY') or not graphic_config.COPY_GOOGLE_DOC_KEY: print 'COPY_GOOGLE_DOC_KEY is not defined in %s/graphic_config.py.' % slug return copy_path = os.path.join(graphic_path, '%s.xlsx' % slug) get_document(graphic_config.COPY_GOOGLE_DOC_KEY, copy_path) @task def update_copy(slug=None): """ Fetches the latest Google Doc and updates local JSON. """ if slug: download_copy(slug) return slugs = os.listdir(app_config.GRAPHICS_PATH) for slug in slugs: graphic_path = '%s/%s' % (app_config.GRAPHICS_PATH, slug) if not os.path.exists('%s/graphic_config.py' % graphic_path): continue print slug download_copy(slug) """ App-specific commands """ def _add_graphic(slug, template): """ Create a graphic with `slug` from `template` """ graphic_path = '%s/%s' % (app_config.GRAPHICS_PATH, slug) if _check_slug(slug): return local('cp -r graphic_templates/_base %s' % (graphic_path)) local('cp -r graphic_templates/%s/* %s' % (template, graphic_path)) config_path = os.path.join(graphic_path, 'graphic_config.py') if os.path.isfile(config_path): print 'Creating spreadsheet...' success = copy_spreadsheet(slug) if success: download_copy(slug) else: local('rm -r graphic_path') print 'Failed to copy spreadsheet! Try again!' return else: print 'No graphic_config.py found, not creating spreadsheet' print 'Run `fab app` and visit http://127.0.0.1:8000/graphics/%s to view' % slug def _check_slug(slug): """ Does slug exist in graphics folder or production s3 bucket? """ graphic_path = '%s/%s' % (app_config.GRAPHICS_PATH, slug) if os.path.isdir(graphic_path): print 'Error: Directory already exists' return True try: bucket = utils.get_bucket(app_config.PRODUCTION_S3_BUCKET['bucket_name']) key = bucket.get_key('%s/graphics/%s/child.html' % (app_config.PROJECT_SLUG, slug)) if key: print 'Error: Slug exists on apps.npr.org' return True except boto.exception.NoAuthHandlerFound: print 'Could not authenticate, skipping Amazon S3 check' except boto.exception.S3ResponseError: print 'Could not access S3 bucket, skipping Amazon S3 check' return False @task def add_graphic(slug): """ Create a basic project. """ _add_graphic(slug, 'graphic') @task def add_bar_chart(slug): """ Create a bar chart. """ _add_graphic(slug, 'bar_chart') @task def add_column_chart(slug): """ Create a column chart. """ _add_graphic(slug, 'column_chart') @task def add_stacked_column_chart(slug): """ Create a stacked column chart. """ _add_graphic(slug, 'stacked_column_chart') @task def add_block_histogram(slug): """ Create a block histogram. """ _add_graphic(slug, 'block_histogram') @task def add_grouped_bar_chart(slug): """ Create a grouped bar chart. """ _add_graphic(slug, 'grouped_bar_chart') @task def add_stacked_bar_chart(slug): """ Create a stacked bar chart. """ _add_graphic(slug, 'stacked_bar_chart') @task def add_state_grid_map(slug): """ Create a state grid cartogram """ _add_graphic(slug, 'state_grid_map') @task def add_line_chart(slug): """ Create a line chart. """ _add_graphic(slug, 'line_chart') @task def add_dot_chart(slug): """ Create a dot chart with error bars """ _add_graphic(slug, 'dot_chart') @task def add_slopegraph(slug): """ Create a slopegraph (intended for narrow display) """ _add_graphic(slug, 'slopegraph') @task def add_map(slug): """ Create a locator map. """ _add_graphic(slug, 'locator_map') @task def add_table(slug): """ Create a data table. """ _add_graphic(slug, 'table') def _check_credentials(): """ Check credentials and spawn server and browser if not """ credentials = get_credentials() if not credentials or 'https://www.googleapis.com/auth/drive' not in credentials.config['google']['scope']: try: with open(os.devnull, 'w') as fnull: print 'Credentials were not found or permissions were not correct. Automatically opening a browser to authenticate with Google.' gunicorn = find_executable('gunicorn') process = subprocess.Popen([gunicorn, '-b', '127.0.0.1:8888', 'app:wsgi_app'], stdout=fnull, stderr=fnull) webbrowser.open_new('http://127.0.0.1:8888/oauth') print 'Waiting...' while not credentials: try: credentials = get_credentials() sleep(1) except ValueError: continue print 'Successfully authenticated!' process.terminate() except KeyboardInterrupt: print '\nCtrl-c pressed. Later, skater!' exit() def copy_spreadsheet(slug): """ Copy the COPY spreadsheet """ _check_credentials() config_path = '%s/%s/' % (app_config.GRAPHICS_PATH, slug) graphic_config = load_graphic_config(config_path) if not hasattr(graphic_config, 'COPY_GOOGLE_DOC_KEY') or not graphic_config.COPY_GOOGLE_DOC_KEY: print 'Skipping spreadsheet creation. (COPY_GOOGLE_DOC_KEY is not defined in %s/graphic_config.py.)' % slug return kwargs = { 'credentials': get_credentials(), 'url': SPREADSHEET_COPY_URL_TEMPLATE % graphic_config.COPY_GOOGLE_DOC_KEY, 'method': 'POST', 'headers': {'Content-Type': 'application/json'}, 'body': json.dumps({ 'title': '%s GRAPHIC COPY' % slug, }), } resp = app_config.authomatic.access(**kwargs) if resp.status == 200: spreadsheet_key = resp.data['id'] spreadsheet_url = SPREADSHEET_VIEW_TEMPLATE % spreadsheet_key print 'New spreadsheet created successfully!' print 'View it online at %s' % spreadsheet_url utils.replace_in_file('%s/graphic_config.py' % config_path , graphic_config.COPY_GOOGLE_DOC_KEY, spreadsheet_key) return True utils.replace_in_file(config_path, graphic_config.COPY_GOOGLE_DOC_KEY, '') print 'Error creating spreadsheet (status code %s) with message %s' % (resp.status, resp.reason) return False
{'content_hash': '212917c614b0146c9b5c48a64f966479', 'timestamp': '', 'source': 'github', 'line_count': 382, 'max_line_length': 144, 'avg_line_length': 26.17539267015707, 'alnum_prop': 0.6169616961696169, 'repo_name': 'swastvedt/dailygraphics', 'id': '8c2de6f521023a0ba7863ee34d3204f90bf78fba', 'size': '9999', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'fabfile/__init__.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '12501'}, {'name': 'HTML', 'bytes': '37659'}, {'name': 'JavaScript', 'bytes': '261258'}, {'name': 'Python', 'bytes': '56924'}]}
from abc import ABCMeta, abstractmethod, abstractproperty class Resource(object): __metaclass__ = ABCMeta # TODO: # - automate to_dict() and from_dict() based on members # - automate camelCase and snake_case conversions # - automate type conversions @classmethod def media_type(cls): return cls.MEDIA_TYPE def _dict_no_none(self, **kwargs): return { k: v for k, v in kwargs.iteritems() if v is not None } @abstractmethod def to_dict(self): pass @classmethod def from_dict(cls, resource_dict): raise NotImplementedError() def __hash__(self): return hash(frozenset(self.to_dict())) def __eq__(self, other): return isinstance(other, self.__class__) and self.to_dict() == other.to_dict() def __ne__(self, other): return self.to_dict() != other.to_dict() class ResourceList(Resource): @abstractproperty def resources(self): pass def __len__(self): return len(self.resources) def __iter__(self): return iter(self.resources) def append(self, resource): self.resources.append(resource) class PaginatedResourceList(ResourceList): def __init__(self, items=None, offset=None, limit=None, total_count=None): self.items = items or [] self.offset = offset self.limit = limit self.total_count = total_count @property def resources(self): return self.items @classmethod def items_name(cls): raise NotImplementedError("`items_name` is not implemented") @classmethod def items_class(cls): raise NotImplementedError("`items_class` is not implemented") def to_dict(self): return { self.items_name(): [ entry.to_dict() for entry in self ], "offset": self.offset, "limit": self.limit, "totalCount": self.total_count, } @classmethod def from_dict(cls, dct): return cls( [cls.items_class().from_dict(model) for model in dct[cls.items_name()]], offset=dct["offset"], limit=dct["limit"], total_count=dct["totalCount"], )
{'content_hash': 'b7f9357787c5b895f167be4aa29dee83', 'timestamp': '', 'source': 'github', 'line_count': 94, 'max_line_length': 86, 'avg_line_length': 24.319148936170212, 'alnum_prop': 0.5765529308836396, 'repo_name': 'ksweta/BeamIt-Server', 'id': 'fbc12e1d7f1c545965e7c565730bddefac21060d', 'size': '2286', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'beamit/resources/base.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '148'}, {'name': 'Python', 'bytes': '32100'}]}
<!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <title></title> <link rel="Stylesheet" href="../css/analysis.css" /> <script type="text/javascript"> function init() { if (window.location.hash) { var parentDiv, nodes, i, helpInfo, helpId, helpInfoArr, helpEnvFilter, envContent, hideEnvClass, hideNodes; helpInfo = window.location.hash.substring(1); if(helpInfo.indexOf("-")) { helpInfoArr = helpInfo.split("-"); helpId = helpInfoArr[0]; helpEnvFilter = helpInfoArr[1]; } else { helpId = helpInfo; } parentDiv = document.getElementById("topics"); nodes = parentDiv.children; hideEnvClass = (helpEnvFilter === "OnlineOnly"? "PortalOnly": "OnlineOnly"); if(document.getElementsByClassName) { hideNodes = document.getElementsByClassName(hideEnvClass); } else { hideNodes = document.querySelectorAll(hideEnvClass); } for(i=0; i < nodes.length; i++) { if(nodes[i].id !== helpId) { nodes[i].style.display ="none"; } } for(i=0; i < hideNodes.length; i++) { hideNodes[i].style.display ="none"; } } } </script> </head> <body onload="init()"> <div id="topics"> <div id="aoToolbox"> <p>De toolbox Objectanalyse omvat een aantal tools die u kunt openen en gebruiken. Deze taken zijn hieronder gerangschikt in categorie&euml;n; de categorie&euml;n zijn logische groeperingen en hebben geen enkele invloed op de manier waarop de taken worden geopend of gebruikt. </p> </div> <div id="SummarizeDataCategory" class="regularsize"> <h2>Gegevens samenvatten</h2> <hr/> <p>Deze tools berekenen totale tellingen, lengtes, gebieden en eenvoudige beschrijvende statistieken van objecten en hun attributen binnen oppervlakken of dicht bij andere objecten. <ul> <li> <b>Punten aggregeren</b> berekent statistieken over punten die binnen specifieke oppervlakken vallen. </li> <li> <b>Objecten koppelen</b> brengt attributen over van &eacute;&eacute;n laag of tabel naar een andere op basis van ruimtelijke en attribuutrelaties. </li> <li> <b>Samenvatten in de buurt van</b> berekent statistieken voor objecten en hun attributen die zich binnen een specifieke afstand bevinden. </li> <li> <b>Samenvatten in</b> berekent statistieken voor gebiedsobjecten en attributen die elkaar overlappen. </li> </ul> </p> <p> </p> </div> <div id="AggregatePointsTool" class="regularsize"> <table class="toolSummaryTable"> <thead></thead> <tbody><tr> <td><h2>Punten aggregeren</h2></td> <td> <img src="../images/GUID-60C59C66-3038-4D0E-8F6A-EC6C53FEAA02-web.png" class="titleImage" alt="Punten aggregeren"> </td> </tr></tbody> </table> <hr/> <p>Met behulp van een laag van puntobjecten en een laag van gebiedsobjecten bepaalt deze tool welke punten binnen elk gebied vallen en berekent deze de statistieken voor alle punten binnen elk gebied. Bijvoorbeeld: <ul> <li>Bereken aan de hand van bepaalde puntlocaties van criminele incidenten het aantal misdrijven per gemeente of ander administratieve regio. </li> <li>Zoek de hoogste en laagste inkomsten voor franchiselocaties per staat. </li> </ul> </p> <br/> </div> <div id="JoinFeaturesTool" class="largesize"> <table class="toolSummaryTable"> <thead></thead> <tbody><tr> <td><h2>Objecten koppelen</h2></td> <td> <img src="../images/GUID-2230E8B8-8956-475C-9C65-68A92359BB48-web.png" class="titleImage" alt="Objecten koppelen"> </td> </tr></tbody> </table> <hr/> <p>Objecten koppelen brengt attributen over van &eacute;&eacute;n laag of tabel naar een andere op basis van ruimtelijke en attribuutrelaties. Bijvoorbeeld: <ul> <li>Voeg gemeenschappelijke grens- of demografische informatie toe aan uw incidentdata. </li> <li>Identificeer de dichtstbijzijnde faciliteiten bij een bekende locatie. </li> <li>Bepaal het aantal woningen die in overstromingsgebied liggen. </li> <li>Identificeer gemeenschappelijke habitats voor verschillende soorten wilde dieren. </li> </ul> </p> <br/> </div> <div id="SummarizeNearbyTool" class="largesize"> <table class="toolSummaryTable"> <thead></thead> <tbody><tr> <td><h2>Samenvatten in de buurt van</h2></td> <td> <img src="../images/GUID-A5033D27-81B6-42E7-BA38-50D25C1CCCCA-web.png" class="titleImage" alt="Samenvatten in de buurt van"> </td> </tr></tbody> </table> <hr/> <p>Zoekt naar objecten die zich binnen een bepaalde afstand van objecten in de invoerlaag bevinden. De afstand kan worden gemeten langs rechte lijnen of gangbare wegen van een reismodus. Vervolgens kunnen statistieken worden berekend voor de objecten in de buurt. Bijvoorbeeld: <ul> <li>Bereken de totale populatie binnen vijf minuten van de locatie voor een mogelijke nieuwe winkel. </li> <li>Bereken het aantal opritten voor snelwegen binnen vijf minuten van de locatie voor een mogelijke nieuwe winkel en gebruik deze als maatstaf voor de toegankelijkheid van deze winkel. </li> </ul> </p> <br/> </div> <div id="SummarizeWithinTool" class="regularsize"> <table class="toolSummaryTable"> <thead></thead> <tbody><tr> <td><h2>Samenvatten in</h2></td> <td> <img src="../images/GUID-9B12DB3F-AA7B-41EB-87C6-D2DEC3D52DA9-web.png" class="titleImage" alt="Samenvatten in"> </td> </tr></tbody> </table> <hr/> <p>Zoekt naar gebieden (en delen van gebieden) die overlappen tussen twee lagen en berekent statistieken over de overlapping. Bijvoorbeeld: <ul> <li>Er is een kaartlaag met stroomgebieden en een laag met landgebruikgebieden per type landgebruik; bereken het totale oppervlak van het landgebruiktype voor elk stroomgebied. </li> <li>Vat de gemiddelde waarde van vrije percelen in elke stad samen op basis van een laag met percelen in een provincie en een laag met stadsgrenzen. </li> </ul> </p> <br/> </div> <div id="EnrichLocationsCategory" class="smallsize"> <h2>Data Enrichment</h2> <hr/> <p>Deze tools helpen u om de aard van gebieden te onderzoeken. Gedetailleerde demografische gegevens en statistieken worden geretourneerd voor uw gekozen gebieden. <ul> <li> <b>Laag verrijken</b> haalt informatie op over de mensen, plaatsen en bedrijven in een bepaald gebied of binnen een bepaalde reistijd of afstand van een locatie. </li> </ul> </p> </div> <div id="EnrichLayerTool" class="smallsize"> <table class="toolSummaryTable"> <thead></thead> <tbody><tr> <td><h2>Enrich Layer</h2></td> <td> <img src="../images/GUID-5B2D9742-AFD2-4054-8D05-ED6A80EDAF4D-web.png" class="titleImage" alt="Laag verrijken"> </td> </tr></tbody> </table> <hr/> <p>Haalt informatie op over de mensen, plaatsen en bedrijven in een bepaald gebied of binnen een bepaalde reistijd of afstand van een locatie. </p> <br/> </div> <div id="FindLocationsCategory" class="largesize"> <h2>Locaties zoeken</h2> <hr/> <p>Deze tools worden gebruikt om gebieden te identificeren die voldoen aan een aantal door u opgegeven criteria. Deze criteria kunnen gebaseerd zijn op attribuutquery's (bijvoorbeeld percelen die vrij zijn) en ruimtelijke query's (bijvoorbeeld binnen 1 kilometer van een rivier). De gevonden gebieden kunnen worden geselecteerd uit bestaande objecten (zoals bestaande landpercelen) of er kunnen nieuwe objecten worden gemaakt waarbij aan alle vereisten wordt voldaan. <ul> <li> <b>Beste voorzieningen kiezen</b> kiest de beste locaties voor voorzieningen door locaties toe te wijzen die vragen naar deze voorzieningen op een manier die voldoet aan een bepaald doel. </li> <li> <b>Viewshed maken</b> maakt gebieden die zichtbaar zijn op basis van locaties die u opgeeft. </li> <li> <b>Stroomgebieden maken</b> maakt stroomgebieden op basis van locaties die u opgeeft. </li> <li> <b>Nieuwe locaties afleiden</b> maakt nieuwe gebieden op basis van locaties in uw onderzoeksgebied die voldoen aan een reeks criteria. </li> <li> <b>Geschikte locaties zoeken</b> zoekt naar bestaande gebieden in een laag die voldoen aan een reeks criteria. </li> <li> <b>Gelijksoortige locaties zoeken</b> zoekt naar overeenkomende locaties onder een of meer referentielocaties op basis van de criteria die u opgeeft. </li> <li class="PortalOnly"> <b>Geocodeer locaties uit tabel</b> converteert adressen uit een tabel in co&ouml;rdinaten. </li> <li> <b>Stroomafwaarts traceren</b> bepaalt de stromingstrajecten stroomafwaarts van de locaties die u opgeeft. </li> </ul> </p> <p> </p> </div> <div id="ChooseBestFacilitiesTool" class="regularsize"> <table class="toolSummaryTable"> <thead></thead> <tbody><tr> <td><h2>Beste voorzieningen kiezen</h2></td> <td> <img src="../images/GUID-E57BEC1A-C404-436B-B389-65711FF83088-web.png" class="titleImage" alt="Beste voorzieningen kiezen"> </td> </tr></tbody> </table> <hr/> <p>Kiest de beste locaties voor voorzieningen door locaties toe te wijzen die vragen naar deze voorzieningen op een manier die voldoet aan een bepaald doel. </p> <br/> </div> <div id="CreateViewshedTool" class="smallsize"> <table class="toolSummaryTable"> <thead></thead> <tbody><tr> <td><h2>Viewshed maken</h2></td> <td> <img src="../images/GUID-491E9A75-30CC-4526-9F71-E47FD25536DE-web.png" class="titleImage" alt="Viewshed maken"> </td> </tr></tbody> </table> <hr/> <p>Maakt gebieden die zichtbaar zijn op basis van locaties die u opgeeft. </p> <br/> </div> <div id="CreateWatershedsTool" class="smallsize"> <table class="toolSummaryTable"> <thead></thead> <tbody><tr> <td><h2>Stroomgebied maken</h2></td> <td> <img src="../images/GUID-4DE64CF6-2A02-46F6-8AE4-4D9227AAB71C-web.png" class="titleImage" alt="Stroomgebied maken"> </td> </tr></tbody> </table> <hr/> <p>Maakt stroomgebieden op basis van locaties die u opgeeft. </p> <br/> </div> <div id="DeriveNewLocationsTool" class="regularsize"> <table class="toolSummaryTable"> <thead></thead> <tbody><tr> <td><h2>Nieuwe locaties afleiden</h2></td> <td> <img src="../images/GUID-4A756008-8431-4AA5-BD42-7135296560DD-web.png" class="titleImage" alt="Nieuwe locaties afleiden"> </td> </tr></tbody> </table> <hr/> <p>Maakt nieuwe objecten in uw onderzoeksgebied die voldoen aan een reeks door u opgegeven criteria. Deze criteria kunnen gebaseerd zijn op attribuutquery's (bijvoorbeeld percelen die vrij zijn) en ruimtelijke query's (bijvoorbeeld binnen anderhalve kilometer van een rivier). </p> <br/> </div> <div id="FindExistingLocationsTool" class="regularsize"> <table class="toolSummaryTable"> <thead></thead> <tbody><tr> <td><h2>Bestaande locaties zoeken</h2></td> <td> <img src="../images/GUID-FEF355B4-CF3B-48F6-9EC1-A00A1D53C81F-web.png" class="titleImage" alt="Bestaande locaties zoeken"> </td> </tr></tbody> </table> <hr/> <p>Selecteert bestaande objecten in uw onderzoeksgebied die voldoen aan een reeks door u opgegeven criteria. Deze criteria kunnen gebaseerd zijn op attribuutquery's (bijvoorbeeld percelen die vrij zijn) en ruimtelijke query's (bijvoorbeeld binnen anderhalve kilometer van een rivier). </p> <br/> </div> <div id="GeocodeLocationsfromTableTool" class="regularsize"> <table class="toolSummaryTable"> <thead></thead> <tbody><tr> <td><h2>Geocodeer locaties vanuit tabel</h2></td> <td> <img src="../images/GUID-E4194410-7BBF-4349-98C9-22781D35183E-web.png" class="titleImage" alt="Geocodeer locaties vanuit tabel"> </td> </tr></tbody> </table> <hr/> <p>Converteert adressen naar co&ouml;rdinaten. Gebruik deze tool voor adressen in een Excel-spreadsheet of een CSV-bestand. </p> <br/> </div> <div id="FindSimilarLocationsTool" class="regularsize"> <table class="toolSummaryTable"> <thead></thead> <tbody><tr> <td><h2>Gelijksoortige locaties zoeken</h2></td> <td> <img src="../images/GUID-6262A84E-9087-4E48-930E-E9B89FECC836-web.png" class="titleImage" alt="Gelijksoortige locaties zoeken"> </td> </tr></tbody> </table> <hr/> <p>Zoekt naar locaties die het meest of het minst lijken op een of meer referentielocaties op basis van de criteria die u opgeeft. </p> <br/> </div> <div id="TraceDownstreamTool" class="smallsize"> <table class="toolSummaryTable"> <thead></thead> <tbody><tr> <td><h2>Stroomafwaarts traceren</h2></td> <td> <img src="../images/GUID-1700E318-5F2D-4D4D-BF21-B12663F5D3C4-web.png" class="titleImage" alt="Stroomafwaarts traceren"> </td> </tr></tbody> </table> <hr/> <p>Bepaalt de stromingstrajecten stroomafwaarts van de locaties die u opgeeft. </p> <br/> </div> <div id="AnalyzePatternsCategory" class="regularsize"> <h2>Patronen analyseren</h2> <hr/> <p>Deze tools helpen u ruimtelijke patronen in uw gegevens te identificeren, kwantificeren en visualiseren. <ul> <li> <b>Dichtheid berekenen</b> gebruikt bekende hoeveelheden van een bepaald fenomeen en spreidt deze hoeveelheden over de kaart. </li> <li>Met <b>Hotspots zoeken</b> wordt statistisch significante clustering in het ruimtelijke patroon van uw gegevens ge&iuml;dentificeerd. </li> <li>De tool <b>Afwijkingen</b> vinden bepaalt of er sprake is van statistisch significante afwijkingen in het ruimtelijke patroon van uw data. </li> <li> <b>Punten interpoleren</b> voorspelt waarden op nieuwe locaties op basis van metingen die worden gevonden in een verzameling van punten. </li> </ul> </p> </div> <div id="CalculateDensityTool" class="regularsize"> <table class="toolSummaryTable"> <thead></thead> <tbody><tr> <td><h2>Dichtheid berekenen</h2></td> <td> <img src="../images/GUID-20E554EC-1F41-4951-99FE-B3FE71DB2E17-web.png" class="titleImage" alt="Dichtheid berekenen"> </td> </tr></tbody> </table> <hr/> <p>Dichtheidsanalyse gebruikt bekende hoeveelheden van een bepaald fenomeen en spreidt deze hoeveelheden over de kaart. U kunt deze tool bijvoorbeeld gebruik om concentraties van blikseminslagen of tornado's, de toegang tot gezondheidszorgfaciliteiten en bevolkingsdichtheden weer te geven. </p> <br/> </div> <div id="FindHotSpotsTool" class="regularsize"> <table class="toolSummaryTable"> <thead></thead> <tbody><tr> <td><h2>Hotspots zoeken</h2></td> <td> <img src="../images/GUID-D4A59131-AC88-4C7A-85BA-67861D5C1CF8-web.png" class="titleImage" alt="Hotspots zoeken"> </td> </tr></tbody> </table> <hr/> <p>Deze tool maakt een kaart die eventuele statistisch significante ruimtelijke clustering in uw gegevens weergeeft. Gebruik deze tool om onverwachte hotspots (rood) en coldspots (blauw) te zoeken van bijvoorbeeld hoge en lage huizenwaarden, de misdaaddichtheid, slachtoffers van verkeersongevallen, werkloosheid of biodiversiteit. </p> <br/> </div> <div id="FindOutliersTool" class="regularsize"> <table class="toolSummaryTable"> <thead></thead> <tbody><tr> <td><h2>Afwijkingen vinden</h2></td> <td> <img src="../images/GUID-2FD18406-6333-45B9-8220-E930C1E154B2-web.png" class="titleImage" alt="Afwijkingen vinden"> </td> </tr></tbody> </table> <hr/> <p>Deze tool maakt een kaart met alle statistisch significante clusters en ruimtelijke afwijkingen in uw data. Gebruik deze tool om objecten te identificeren die waarden hebben die aanzienlijk verschillen van de aangrenzende waarden. U kunt deze tool bijvoorbeeld gebruiken om abnormale uitgavepatronen te zoeken, bepalen waar de scherpste grenzen tussen welvaart en armoede liggen in een studiegebied of bepalen of er provincies in de Verenigde Staten zijn met ongewoon lage levensverwachting t.o.v. de aangrenzende provincies. </p> <br/> </div> <div id="InterpolatePointsTool" class="regularsize"> <table class="toolSummaryTable"> <thead></thead> <tbody><tr> <td><h2>Punten interpoleren</h2></td> <td> <img src="../images/GUID-28FC50AA-7B10-487C-949B-241EF2F8028E-web.png" class="titleImage" alt="Punten interpoleren"> </td> </tr></tbody> </table> <hr/> <p>Deze tool voorspelt waarden op nieuwe locaties op basis van metingen die worden gevonden in een verzameling van punten. De tool neemt puntgegevens met waarden op elk punt en retourneert gebieden die worden geclassificeerd op voorspelde waarden. U kunt deze tool bijvoorbeeld gebruiken om neerslagniveaus in een rioleringsgebied te voorspellen op basis van metingen die worden uitgevoerd op afzonderlijke regenmeters. </p> <br/> </div> <div id="UseProximityCategory" class="regularsize"> <h2>Nabijheid gebruiken</h2> <hr/> <p> Deze tools helpen u een van de meest gestelde vragen op het gebied van ruimtelijke analyse te beantwoorden: &quot;Wat bevindt zich in de buurt van wat?&quot; <ul> <li> <b>Beginpunten aan bestemmingen koppelen</b> meet de reistijd of afstand tussen paren van beginpunten en bestemmingen. </li> <li> <b>Buffers maken</b> maakt gebieden van gelijke afstand tot objecten. </li> <li> <b>Gebieden op basis van reistijd maken</b> zoekt naar gebieden rondom locaties die binnen een bepaald tijdsbestek kunnen worden bereikt. </li> <li> <b>Dichtstbijzijnde zoeken</b> wordt gebruikt om plaatsen te identificeren die zich het dichtst bij bekende locaties bevinden. </li> <li> <b>Routes plannen</b> bepaalt de beste manier om een wagenpark te routeren zodat ze veel stopplaatsen kunnen bezoeken. </li> </ul> </p> </div> <div id="ConnectOriginsToDestinationsTool" class="largesize"> <table class="toolSummaryTable"> <thead></thead> <tbody><tr> <td><h2>Vertrekpunten en bestemmingen met elkaar verbinden</h2></td> <td> <img src="../images/GUID-7266D30B-0250-4132-B1A5-9B59F0212FAD-web.png" class="titleImage" alt="Vertrekpunten en bestemmingen met elkaar verbinden"> </td> </tr></tbody> </table> <hr/> <p>Beginpunten aan bestemmingen koppelen meet de reistijd of afstand tussen paren van beginpunten en bestemmingen. Het hulpmiddel kan afstanden hemelsbreed, afstanden over de weg of reistijden weergeven. Met deze tool kunt u </p> <p> <ul> <li>De totale afstand berekenen die forensen tussen hun woon- en werkplaats afleggen of de tijd die dit in beslag neemt. </li> <li>Meten hoe ver klanten reizen om bij uw winkels te winkelen. Gebruik deze informatie om uw marktbereik te bepalen, met name voor gerichte reclamecampagnes of het kiezen van nieuwe winkellocaties. </li> <li>Het verwachte aantal kilometers voor uw wagenpark berekenen. Gebruik achteraf de tool Samenvatten in om de afstand per provincie of andere regio te rapporteren. </li> </ul> </p> <p>U levert de begin- en eindpunten en de tool geeft een laag terug met routes, inclusief metingen, tussen de gekoppelde beginpunten en bestemmingen. </p> <br/> </div> <div id="CreateBuffersTool" class="largesize"> <table class="toolSummaryTable"> <thead></thead> <tbody><tr> <td><h2>Buffers maken</h2></td> <td> <img src="../images/GUID-7F4A8E4D-42E3-41C1-9238-16619CE65079-web.png" class="titleImage" alt="Buffers maken"> </td> </tr></tbody> </table> <hr/> <p>Een buffer is een gebied dat een bepaalde afstand vanaf een punt-, lijn- of gebiedsobject dekt. </p> <p>Buffers worden doorgaans gebruikt om gebieden te maken die verder kunnen worden geanalyseerd met andere tools zoals Lagen bovenop plaatsen. Als de vraag bijvoorbeeld luidt &quot;Welke gebouwen bevinden zich binnen anderhalve kilometer van de school?&quot;, dan kunt u het antwoord vinden door een buffer van anderhalve kilometer rond de school te maken en boven op de buffer de laag te plaatsen die voetafdrukken van gebouwen bevat. Het eindresultaat is een laag met de gebouwen die zich binnen anderhalve kilometer van de school bevinden. </p> <br/> </div> <div id="CreateDriveTimeAreasTool" class="largesize"> <table class="toolSummaryTable"> <thead></thead> <tbody><tr> <td><h2>Gebieden op basis van reistijd maken</h2></td> <td> <img src="../images/GUID-6F629A09-768D-4C04-88A4-AB941811ADE9-web.png" class="titleImage" alt="Gebieden op basis van reistijd maken"> </td> </tr></tbody> </table> <hr/> <p>Een reistijdgebied is een gebied dat kan worden bereikt binnen een bepaalde reisduur of rijafstand. Reistijdgebieden kunnen u helpen bij het beantwoorden van vragen als: <ul> <li>Waar kan ik heen binnen een reisduur van 30 minuten vanaf hier? </li> <li>Waar kan ik heen binnen een reisduur van 30 minuten vanaf hier om 18.00 uur tijdens het spitsuur? </li> <li>Welke stadsdelen kan de brandweer binnen vijf minuten bereiken? In hoeverre zou de dekking van de reactietijd bij een brandalarm verbeteren door hier een nieuwe brandweerkazerne te bouwen? </li> <li>Welke marktgebieden worden door mijn bedrijf gedekt? Welke gebieden bevinden zich binnen 15 kilometer van mijn winkels? </li> </ul> </p> <br/> </div> <div id="FindNearestTool" class="regularsize"> <table class="toolSummaryTable"> <thead></thead> <tbody><tr> <td><h2>Dichtstbijzijnde zoeken</h2></td> <td> <img src="../images/GUID-150C2484-7459-405A-8835-B4E72CD49738-web.png" class="titleImage" alt="Dichtstbijzijnde zoeken"> </td> </tr></tbody> </table> <hr/> <p>Meet de reiskosten tussen incidenten en faciliteiten en bepaalt welke het dichtst bij elkaar liggen. Het resultaat is een laag die de beste routes toont tussen incidenten en faciliteiten en bovendien de reiskosten (tijd en afstand) van elke route weergeeft. U kunt deze tool bijvoorbeeld gebruiken om bij een ongeval het dichtstbijzijnde ziekenhuis te vinden of de dichtstbijzijnde geldautomaat ten opzichte van uw huidige locatie. </p> <br/> </div> <div id="PlanRoutesTool" class="regularsize"> <table class="toolSummaryTable"> <thead></thead> <tbody><tr> <td><h2>Routes plannen</h2></td> <td> <img src="../images/GUID-09CC6D60-3C72-42D7-968E-B0663F0B1EBB-web.png" class="titleImage" alt="Routes plannen"> </td> </tr></tbody> </table> <hr/> <p>U levert een reeks stopplaatsen en het aantal voertuigen dat beschikbaar is om de stopplaatsen te bezoeken en Routes plannen bepaalt vervolgens hoe u de stopplaatsen effici&euml;nt kunt toewijzen aan de voertuigen en het routeert de voertuigen naar de stopplaatsen. </p> <p>Gebruik deze tool om werk te plannen voor een mobiel team van inspecteurs, beoordelaars, in-home leveranciers van ondersteunende diensten, en anderen; bezorg items op externe locaties of haal ze daar op; of biedt mensen vervoersdiensten aan. </p> <br/> </div> <div id="ManageDataCategory" class="regularsize"> <h2>Data beheren</h2> <hr/> <p>Deze tools worden gebruikt zowel voor het dagelijkse beheer van geografische gegevens als voor het combineren van gegevens v&oacute;&oacute;r de analyse. <ul> <li> <b>Grenzen oplossen</b> voegt gebieden samen die een gemeenschappelijke grens en een gemeenschappelijke attribuutwaarde hebben. </li> <li> <b>Gegevens exporteren</b> maakt nieuwe gegevenssets door objecten te expoerteren van uw bestaande gegevens. </li> <li> <b>Lagen samenvoegen</b> kopieert alle objecten van twee of meer bestaande lagen naar een nieuwe laag. </li> <li> <b>Overlay-lagen</b> combineert twee of meer lagen in &eacute;&eacute;n enkele laag. Bij overlay lijkt het alsof u door een stapel kaarten kijkt en &eacute;&eacute;n kaart maakt die alle informatie bevat die in de stapel is gevonden. </li> </ul> </p> </div> <div id="DissolveBoundariesTool" class="regularsize"> <table class="toolSummaryTable"> <thead></thead> <tbody><tr> <td><h2>Grenzen oplossen</h2></td> <td> <img src="../images/GUID-7B5F69B0-3625-404F-8B52-2B562766C0BB-web.png" class="titleImage" alt="Grenzen oplossen"> </td> </tr></tbody> </table> <hr/> <p>Gebieden die elkaar overlappen of een gemeenschappelijke grens hebben, worden samengevoegd tot &eacute;&eacute;n gebied. </p> <p>U kunt bepalen welke grenzen worden samengevoegd door een veld op te geven. Als u bijvoorbeeld een laag met regio's hebt en elke regio een <i>State_Name</i>-attribuut heeft, kunt u grenzen oplossen op basis van het <i>State_Name</i>-attribuut. Aangrenzende provincies worden samengevoegd als ze dezelfde waarde hebben voor <i>State_Name</i>. Het eindresultaat is een laag met grenzen van provincies. </p> <br/> </div> <div id="ExtractDataTool" class="smallsize"> <table class="toolSummaryTable"> <thead></thead> <tbody><tr> <td><h2>Gegevens exporteren</h2></td> <td> <img src="../images/GUID-CE24332B-74C0-412F-BB94-31415A02195A-web.png" class="titleImage" alt="Gegevens exporteren"> </td> </tr></tbody> </table> <hr/> <p>Maakt een ZIP-bestand, CSV of KMZ van gegevens van uw lagen en een door u opgegeven interessegebied. </p> <p> </p> <br/> </div> <div id="MergeLayersTool" class="regularsize"> <table class="toolSummaryTable"> <thead></thead> <tbody><tr> <td><h2>Lagen samenvoegen</h2></td> <td> <img src="../images/GUID-BDDD6517-4EE7-4EEC-AE15-15DD9B709131-web.png" class="titleImage" alt="Lagen samenvoegen"> </td> </tr></tbody> </table> <hr/> <p>Kopieert objecten van twee of meer bestaande lagen naar een nieuwe kaartlaag, bijvoorbeeld: <ul> <li>Ik heb drie kaartlagen voor Engeland, Wales en Schotland en ik wil &eacute;&eacute;n kaartlaag van Groot-Brittanni&euml;. </li> <li>Ik heb 12 kaartlagen en elke laag bevat perceelinformatie voor aangrenzende buurtschappen. Ik wil ze samenvoegen tot &eacute;&eacute;n kaartlaag en ik wil alleen de attributen van de 12 invoerlagen behouden met dezelfde naam en van hetzelfde type. </li> </ul> </p> <br/> </div> <div id="OverlayLayersTool" class="largesize"> <table class="toolSummaryTable"> <thead></thead> <tbody><tr> <td><h2>Overlay lagen</h2></td> <td> <img src="../images/GUID-CE1E0E84-F3B5-446B-9FDE-4DA057F106CC-web.png" class="titleImage" alt="Overlay Layers"> </td> </tr></tbody> </table> <hr/> <p>Overlay maakt van twee of meer lagen &eacute;&eacute;n enkele laag. Bij overlay lijkt het alsof u door een stapel kaarten kijkt en &eacute;&eacute;n kaart maakt die alle informatie bevat die in de stapel is gevonden, bijvoorbeeld: <ul> <li>Welke percelen bevinden zich binnen het 100-jarige overstromingsgebied? (Binnen betekent hierbij hetzelfde als boven op.) </li> <li>Welke wegen bevinden zich binnen welke provincies? </li> <li>Welk bodemgebruik ligt boven op welk bodemtype? </li> <li>Welke bronnen bevinden zich binnen verlaten militaire basissen? </li> </ul> </p> <br/> </div> </div> </html>
{'content_hash': 'a78b9443bf544db000bb91478de25baa', 'timestamp': '', 'source': 'github', 'line_count': 633, 'max_line_length': 557, 'avg_line_length': 53.96998420221169, 'alnum_prop': 0.5610748470567574, 'repo_name': 'wanglongbiao/webapp-tools', 'id': 'e11d56d2fab082e14bb954bea110561bfc80c16e', 'size': '34163', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Highlander/ship-gis/src/main/webapp/js/arcgis_js_api/library/3.22/esri/dijit/analysis/help/nl/Analysis.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '46720'}, {'name': 'Python', 'bytes': '4289'}]}
class RecruitmentsController < ApplicationController def index @ads = Advertise.where(:on_page => "karmachari_bharti_page") @summary = Summary.new @summary_exists = Summary.all for summary_exist in @summary_exists if summary_exist.recruitment_summary != nil @summary_exist = summary_exist break end end @recruitments = Recruitment.all.order("created_at DESC").page(params[:page]).per_page(10) end def show @recruitment = Recruitment.find(params[:id]) end def new @recruitment = Recruitment.new end def edit @recruitment = Recruitment.find(params[:id]) end def create @recruitment = Recruitment.new(recruitment_params) if user_signed_in? if @recruitment.save redirect_to recruitments_path end end end def update @recruitment = Recruitment.find(params[:id]) if user_signed_in if @recruitment.update(recruitment_params) redirect_to recruitments_path end end end def destroy @recruitment = Recruitment.find(params[:id]) if @recruitment.destroy redirect_to recruitments_path end end def download_file_recruitment @document = Recruitment.find(params[:id]) send_file(@document.attachment.path, :disposition => 'attachment', :url_based_filename => false) end private def recruitment_params params.require(:recruitment).permit(:title,:description,:attachment) end end
{'content_hash': 'f622dcc635a5db6d67c38256ecd125a7', 'timestamp': '', 'source': 'github', 'line_count': 60, 'max_line_length': 91, 'avg_line_length': 23.6, 'alnum_prop': 0.701271186440678, 'repo_name': 'Nandiwalesamahj/nandi3', 'id': '62ec629b297cbd536a9a0aa4813035a8b287cd58', 'size': '1416', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/controllers/recruitments_controller.rb', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '15252'}, {'name': 'CoffeeScript', 'bytes': '5531'}, {'name': 'HTML', 'bytes': '197549'}, {'name': 'JavaScript', 'bytes': '1257'}, {'name': 'Ruby', 'bytes': '144931'}]}
var lorina = new l.lorina(); lorina.setTitle('Clipper') .setColor('#dddddd') .appendCanvas(); var map = new l.entity(); map.setSprite('terrain.png', true, true) .setPosition(0, 0); var scissors = new l.scissors(); var main = function() { lorina.blank(); scissors.mark(50, 50, 100, 50); map.draw(); scissors.cut(); lorina.draw(); }; lorina.start(main);
{'content_hash': 'ecae623989cb06fb605066a0ed20dbc3', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 40, 'avg_line_length': 17.681818181818183, 'alnum_prop': 0.6118251928020566, 'repo_name': 'jessemillar/lorina', 'id': 'b5134f7499b67af8ea1161b0a99d7a6122061c38', 'size': '389', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'demos/Scissors/game.js', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '1969'}, {'name': 'JavaScript', 'bytes': '72324'}]}
using UnityEngine; using UnityEngine.UI; [ExecuteInEditMode] public class CarParts : MonoBehaviour { /** * Collections: */ public Rigidbody2D[] TiresSteering { get; private set; } public Rigidbody2D[] TiresPowered { get; private set; } public Rigidbody2D ChassisBody { get; private set; } public Rigidbody2D CannonBody { get; private set; } public Slider HealthSlider { get; private set; } public BoxCollider2D[] BoxColliders2D { get; private set; } public SpriteRenderer[] SpriteRenderers { get; private set; } [SerializeField] private GameObject TireFrontRightGameObject; [SerializeField] private GameObject TireFrontLeftGameObject; [SerializeField] private GameObject TireRearRightGameObject; [SerializeField] private GameObject TireRearLeftGameObject; [SerializeField] private GameObject ChassisGameObject; [SerializeField] private GameObject HoodGameObject; [SerializeField] private GameObject RoofGameObject; [SerializeField] private GameObject CannonGameObject; [SpaceAttribute(8f)] [HeaderAttribute("Bullets:")] [SpaceAttribute(2f)] [SerializeField] public GameObject BulletGameObject; [SerializeField] public Transform BulletSpawnTransform; [SpaceAttribute(8f)] [HeaderAttribute("Audio:")] [SpaceAttribute(2f)] [SerializeField] public AudioSource EngineSource; [SerializeField] public AudioSource FireSource; [SerializeField] public AudioSource CollideCarSource; [SerializeField] public AudioSource CollideBulletSource; [SerializeField] public AudioSource ExplodeSource; /** * Rigidbodies 2D: */ private Rigidbody2D TireFrontRightBody; private Rigidbody2D TireFrontLeftBody; // private Rigidbody2D TireRearRightBody; // private Rigidbody2D TireRearLeftBody; /** * Box Colliders 2D: */ private BoxCollider2D TireFrontRightCollider; private BoxCollider2D TireFrontLeftCollider; private BoxCollider2D TireRearRightCollider; private BoxCollider2D TireRearLeftCollider; private BoxCollider2D ChassisCollider; /** * Sprite Renderers: */ private SpriteRenderer HoodRenderer; private SpriteRenderer RoofRenderer; private SpriteRenderer CannonRenderer; /// <summary> /// Awake is called when the script instance is being loaded. /// </summary> void Awake() { InitializeRigidbodies2D(); InitializeBoxColliders2D(); InitializeSpriteRenderers(); HealthSlider = GetComponentInChildren<Slider>(); FireSource.pitch = 1f + Random.Range(-0.2f, 0.2f); CollideCarSource.pitch = 1f + Random.Range(-0.2f, 0.2f); CollideBulletSource.pitch = 1f + Random.Range(-0.2f, 0.2f); ExplodeSource.pitch = 1f + Random.Range(-0.2f, 0.2f); InitializeCollections(); } private void InitializeRigidbodies2D() { TireFrontRightBody = TireFrontRightGameObject.GetComponent<Rigidbody2D>(); TireFrontLeftBody = TireFrontLeftGameObject.GetComponent<Rigidbody2D>(); // TireRearRightBody = TireRearRightGameObject.GetComponent<Rigidbody2D>(); // TireRearLeftBody = TireRearLeftGameObject.GetComponent<Rigidbody2D>(); ChassisBody = gameObject.GetComponent<Rigidbody2D>(); CannonBody = CannonGameObject.GetComponent<Rigidbody2D>(); } private void InitializeBoxColliders2D() { TireFrontRightCollider = TireFrontRightGameObject.GetComponent<BoxCollider2D>(); TireFrontLeftCollider = TireFrontLeftGameObject.GetComponent<BoxCollider2D>(); TireRearRightCollider = TireRearRightGameObject.GetComponent<BoxCollider2D>(); TireRearLeftCollider = TireRearLeftGameObject.GetComponent<BoxCollider2D>(); ChassisCollider = ChassisGameObject.GetComponent<BoxCollider2D>(); } private void InitializeSpriteRenderers() { HoodRenderer = HoodGameObject.GetComponent<SpriteRenderer>(); RoofRenderer = RoofGameObject.GetComponent<SpriteRenderer>(); CannonRenderer = CannonGameObject.GetComponent<SpriteRenderer>(); } private void InitializeCollections() { TiresSteering = new Rigidbody2D[] { TireFrontRightBody, TireFrontLeftBody, }; TiresPowered = new Rigidbody2D[] { TireFrontRightBody, TireFrontLeftBody, }; SpriteRenderers = new SpriteRenderer[] { HoodRenderer, RoofRenderer, CannonRenderer, }; BoxColliders2D = new BoxCollider2D[] { TireFrontRightCollider, TireFrontLeftCollider, TireRearRightCollider, TireRearLeftCollider, ChassisCollider, }; } }
{'content_hash': '6c39290eca822cbf97841802c3215e9c', 'timestamp': '', 'source': 'github', 'line_count': 142, 'max_line_length': 82, 'avg_line_length': 30.246478873239436, 'alnum_prop': 0.7809080325960419, 'repo_name': 'mysterycommand/post-rock-racing', 'id': '11f7c37583ecd4c399515c759bb315ab2ef48578', 'size': '4297', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Assets/Scripts/Car/CarParts.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '22722'}]}
<!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_13) on Wed Aug 05 08:53:15 ICT 2009 --> <META http-equiv="Content-Type" content="text/html; charset=utf8"> <TITLE> org.samples.RMI </TITLE> <META NAME="date" CONTENT="2009-08-05"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="org.samples.RMI"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../org/samples/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../org/samples/unittest/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../index.html?org/samples/RMI/package-summary.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <H2> Package org.samples.RMI </H2> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Interface Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../org/samples/RMI/RemoteInterface.html" title="interface in org.samples.RMI">RemoteInterface</A></B></TD> <TD>&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Class Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../org/samples/RMI/Client.html" title="class in org.samples.RMI">Client</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../org/samples/RMI/RemoteClass.html" title="class in org.samples.RMI">RemoteClass</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../org/samples/RMI/Server.html" title="class in org.samples.RMI">Server</A></B></TD> <TD>The Class Server.</TD> </TR> </TABLE> &nbsp; <P> <DL> </DL> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../org/samples/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../org/samples/unittest/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../index.html?org/samples/RMI/package-summary.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
{'content_hash': 'a5e49ccbb431351bd86f1b3dd39b91ca', 'timestamp': '', 'source': 'github', 'line_count': 180, 'max_line_length': 153, 'avg_line_length': 39.772222222222226, 'alnum_prop': 0.6067886576337478, 'repo_name': 'desiderantes/jgentle', 'id': '2576047a5ef89faa9b418d7f65003bc60cffe048', 'size': '7159', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'JGentleProject/doc/org/samples/RMI/package-summary.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '1420'}, {'name': 'HTML', 'bytes': '20499195'}, {'name': 'Java', 'bytes': '4562180'}, {'name': 'JavaScript', 'bytes': '108'}]}
Mincer - assets processor ========================= [![Build Status](https://travis-ci.org/js-kyle/mincer.svg?branch=master)](https://travis-ci.org/js-kyle/mincer) [![NPM version](https://img.shields.io/npm/v/mincer.svg)](https://www.npmjs.org/package/mincer) **NOTE: This project is now under limited maintenance.** JavaScript port of Sprockets (v2.10.0). It features same declarative dependency management (with exactly same language) for CSS and JavaScript and preprocessor pipeline. Mincer allows you to write assets in the languages like: CoffeeScript, LESS, Stylus and others. Moreover mincer has advanced built-in features, not available in sprockets: - sourcemaps support - macros support (nice alternative to EJS) See [Sprockets](https://github.com/sstephenson/sprockets), [Mincer API Documentation](http://js-kyle.github.io/mincer/) and [Mincer examples](https://github.com/js-kyle/mincer/tree/master/examples) for more details. Supported engines are described in [Wiki](https://github.com/js-kyle/mincer/wiki). If you wish to add new engine support - read [tutorial](https://github.com/js-kyle/mincer/wiki/How-to-create-addon). Also you can [search existing extensions](https://www.npmjs.org/browse/keyword/mincer-contrib) in npm. ## Notice on upgrade to 1.4.x If your project is using `autoprefixer` or `csswring` processors: - upgrade `csswring` to >=4.x and `autoprefixer` to >= 6.x - if you used legacy `autoprefixer-core` package, replace it with `autoprefixer` - include `postcss` >= 4.1 ## Installation Install Mincer from npm registry: $ npm install mincer ## Using Mincer from CLI To use Mincer from CLI, you will need to install it globally: $ npm install mincer -g Usage is really simple (see `mincer -h` for details): $ mincer --include assets/javascripts \ --include assets/stylesheets \ --output public/assets \ application.js application.css If you are using mincer CLI often, you would probably want to "preset" some of the options/arguments for your project. Just create `.mincerrc` file and put argument you want in it. For example: --include assets/javascripts --include assets/stylesheets --output public/assets ## Understanding the Mincer Environment You'll need an instance of the `Mincer.Environment` class to access and serve assets from your application. The `Environment` has methods for retrieving and serving assets, manipulating the load path, and registering processors. It is also used by `Mincer.Server` which can be mounted directly as `request` event handler of `http.Server` or as `connect` middleware. ### The Load Path The *load paths* is an ordered list of directories that Mincer uses to search for assets. In the simplest case, a Mincers environment's load path will consist of a single directory containing your application's asset source files. When mounted, server will serve assets from this directory as if they were static files in your public root. The power of the load path is that it lets you organize your source files into multiple directories -- even directories that live outside your application -- and combine those directories into a single virtual filesystem. That means you can easily bundle JavaScript, CSS and images into a library and import them into your application. #### Manipulating the Load Path To add a directory to your environment's load path, use the `appendPath` and `prependPath` methods. Directories at the beginning of the load path have precedence over subsequent directories. ``` javascript environment = new Mincer.Environment(); environment.appendPath('app/assets/javascripts'); environment.appendPath('lib/assets/javascripts'); environment.appendPath('vendor/assets/jquery'); ``` In general, you should append to the path by default and reserve prepending for cases where you need to override existing assets. ### Accessing Assets Once you've set up your environment's load path, you can mount the environment as a server and request assets via HTTP. You can also access assets programmatically from within your application. #### Logical Paths Assets in Mincer are always referenced by their *logical path*. The logical path is the path of the asset source file relative to its containing directory in the load path. For example, if your load path contains the directory `app/assets/javascripts`: <table> <tr> <th>Asset source file</th> <th>Logical path</th> </tr> <tr> <td>app/assets/javascripts/application.js</td> <td>application.js</td> </tr> <tr> <td>app/assets/javascripts/models/project.js</td> <td>models/project.js</td> </tr> </table> In this way, all directories in the load path are merged to create a virtual filesystem whose entries are logical paths. #### Serving Assets Over HTTP When you mount an environment, all of its assets are accessible as logical paths underneath the *mount point*. For example, if you mount your environment at `/assets` and request the URL `/assets/application.js`, Mincer will search your load path for the file named `application.js` and serve it. ``` javascript var connect = require('connect'); var Mincer = require('mincer'); var environment = new Mincer.Environment(); environment.appendPath('app/assets/javascripts'); environment.appendPath('app/assets/stylesheets'); var app = connect(); app.use('/assets', Mincer.createServer(environment)); app.use(function (req, res) { // your application here... }); ``` #### Accessing Assets Programmatically You can use the `findAsset` method to retrieve an asset from a Mincers environment. Pass it a logical path and you'll get a `BundledAsset` instance back. Call `toString` on the resulting asset to access its contents, `length` to get its length in bytes, `mtime` to query its last-modified time, and `pathname` to get its full path on the filesystem. ``` javascript var asset = environment.findAsset('application.js'); asset.toString(); // resulting contents asset.length; // length in bytes asset.mtime; // last modified time asset.pathname; // full path on the filesystem ``` ## Using Engines Asset source files can be written in another language, like Stylus or CoffeeScript, and automatically compiled to CSS or JavaScript by Mincer. Compilers for these languages are called *engines*. Engines are specified by additional extensions on the asset source filename. For example, a CSS file written in Stylus might have the name `layout.css.styl`, while a JavaScript file written in CoffeeScript might have the name `dialog.js.coffee`. ### Styling with Stylus [Stylus](http://learnboost.github.com/stylus/) is a revolutionary new language, providing an efficient, dynamic, and expressive way to generate CSS. Supporting both an indented syntax and regular CSS style. If the `stylus` Node module is available to your application, you can use Stylus to write CSS assets in Mincer. Use the extension `.css.styl`. ### Styling with LESS [LESS](http://lesscss.org/) extends CSS with dynamic behavior such as variables, mixins, operations and functions. If the `less` Node module is available to your application, you can use LESS to write CSS assets in Mincer. Use the extension `.css.less`. ### Styling with Sass [Sass](http://sass-lang.com/) is an extension of CSS3, adding nested rules, variables, mixins, selector inheritance, and more. If the `node-sass` Node module is available to your application, you can use Sass to write CSS assets in Mincer. Use the extension `.css.sass` or `.css.scss`. ### Scripting with CoffeeScript [CoffeeScript](http://jashkenas.github.com/coffee-script/) is a language that compiles to the "good parts" of JavaScript, featuring a cleaner syntax with array comprehensions, classes, and function binding. If the `coffee-script` Node module is available to your application, you can use CoffeeScript to write JavaScript assets in Mincer. Use the extension `.js.coffee`. ### JavaScript Templating with Jade Mincer supports JavaScript templates for client-side rendering of strings or markup. JavaScript templates have the special format extension `.jst` and are compiled to JavaScript functions. When loaded, a JavaScript template function can be accessed by its logical path as a property on the global `JST` object. Invoke a template function to render the template as a string. The resulting string can then be inserted into the DOM. ``` // templates/hello.jst.jade div Hello, #{ name }! ``` ``` javascript // application.js //= require templates/hello $("#hello").html(JST["templates/hello"]({ name: "Sam" })); ``` Mincer supports one template languages: [Jade][jade]. If `jade` Node module is available to your application, you can use _Jade_ templates in Mincer. Jade templates have the extension `.jst.jade`. To use compiled templates you will need to require Jade [runtime][jade-runtime] before calling renderer functions. [jade]: https://github.com/visionmedia/jade [jade-runtime]: https://github.com/visionmedia/jade/blob/master/runtime.js ### Invoking JavaScript with EJS **Note** see macros description for more convenient alternative. Mincer provides an EJS engine for preprocessing assets using embedded JavaScript code. Append `.ejs` to a CSS or JavaScript asset's filename to enable the EJS engine. You will need `ejs` Node module available to your application. **Note**: Mincer processes multiple engine extensions in order from right to left, so you can use multiple engines with a single asset. For example, to have a CoffeeScript asset that is first preprocessed with EJS, use the extension `.js.coffee.ejs`. JavaScript code embedded in an asset is evaluated in the context of a `Mincer.Context` instance for the given asset. Common uses for EJS include: - embedding another asset as a Base64-encoded `data:` URI with the `asset_data_uri` helper - inserting the URL to another asset, such as with the `asset_path` helper (you must register your own helper for this purpose, but it's dead simple). - embedding other application resources, such as a localized string database, in a JavaScript asset via JSON - embedding version constants loaded from another file ### Using helpers Mincer provides an easy way to add your own helpers for engines: ``` javascript environment.registerHelper('version', function () { var path = require('path'); return require( path.join(__dirname, '/package.json') ).version; }); ``` Now, you can call that helper with EJS like this: ``` javascript var APP = window.APP = {version: '<%= version() %>'}; ``` **NOTICE** Helpers currently work for EJS and Stylus only. So to use them with Less you will need to add EJS engine as well: ``` css // file: foobar.less.ejs .btn { background: url('<%= asset_path('bg.png') %>'); } ``` ### Macros This feature is designed as simple alternative to EJS, that does not requires additional extention and does not break language syntax. When enabled, any `'$$ expression $$'` or `"$$ expression $$"` pattern will be replaced with evaluated expression value. In expression you can write JS code and use registered helpers. Macros are off by default. You should enable those for particular extensions: ```javascript Mincer.MacroProcessor.configure(['.js', '.css']); ``` ## Managing and Bundling Dependencies You can create *asset bundles* -- ordered concatenations of asset source files -- by specifying dependencies in a special comment syntax at the top of each source file. Mincer reads these comments, called *directives*, and processes them to recursively build a dependency graph. When you request an asset with dependencies, the dependencies will be included in order at the top of the file. ### The Directive Processor Mincer runs the *directive processor* on each CSS and JavaScript source file. The directive processor scans for comment lines beginning with `=` in comment blocks at the top of the file. //= require jquery //= require jquery-ui //= require backbone //= require_tree . The first word immediately following `=` specifies the directive name. Any words following the directive name are treated as arguments. Arguments may be placed in single or double quotes if they contain spaces, similar to commands in the Unix shell. **Note**: Non-directive comment lines will be preserved in the final asset, but directive comments are stripped after processing. Mincer will not look for directives in comment blocks that occur after the first line of code. #### Supported Comment Types The directive processor understands comment blocks in three formats: /* Multi-line comment blocks (CSS, Stylus, JavaScript) *= require foo */ // Single-line comment blocks (Stylus, JavaScript) //= require foo # Single-line comment blocks (CoffeeScript) #= require foo ### Mincer Directives You can use the following directives to declare dependencies in asset source files. For directives that take a *path* argument, you may specify either a logical path or a relative path. Relative paths begin with `./` and reference files relative to the location of the current file. #### The `require` Directive ### `require` *path* inserts the contents of the asset source file specified by *path*. If the file is required multiple times, it will appear in the bundle only once. #### The `include` Directive ### `include` *path* works like `require`, but inserts the contents of the specified source file even if it has already been included or required. #### The `require_directory` Directive ### `require_directory` *path* requires all source files of the same format in the directory specified by *path*. Files are required in alphabetical order. #### The `require_tree` Directive ### `require_tree` *path* works like `require_directory`, but operates recursively to require all files in all subdirectories of the directory specified by *path*. #### The `require_self` Directive ### `require_self` tells Mincer to insert the body of the current source file before any subsequent `require` or `include` directives. #### The `depend_on` Directive ### `depend_on` *path* declares a dependency on the given *path* without including it in the bundle. This is useful when you need to expire an asset's cache in response to a change in another file. #### The `stub` Directive ### `stub` *path* allows dependency to be excluded from the asset bundle. The *path* must be a valid asset and may or may not already be part of the bundle. Once stubbed, it is blacklisted and can't be brought back by any other `require`. ## Credits Great thanks to [Sam Stephenson][sam] and [Joshua Peek][josh] for the Sprockets, the most awesome and powerfull web assets processor I ever used, and which became a great source of inspiration (and model of almost all logic behind Mincer). Special thanks to Joshua for his assistance in hacking into Sprockets sources. [sam]: https://github.com/sstephenson [josh]: https://github.com/josh ## Author [Aleksey V Zapparov][github] (follow [@zapparov][twitter] on twitter). [github]: https://github.com/ixti [twitter]: https://twitter.com/zapparov ## License Copyright (c) 2012 [Vitaly Puzrin](https://github.com/puzrin) Released under the MIT license. See [LICENSE][license] for details. [license]: https://raw.github.com/js-kyle/mincer/master/LICENSE
{'content_hash': '629e4e06c312c13cb05c9e69969b6b0d', 'timestamp': '', 'source': 'github', 'line_count': 476, 'max_line_length': 111, 'avg_line_length': 32.37394957983193, 'alnum_prop': 0.7513303049967553, 'repo_name': 'nodeca/mincer', 'id': 'b4a7e487b05c4a974e45fd0c29fc593c386b91df', 'size': '15411', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '188417'}, {'name': 'Makefile', 'bytes': '2252'}]}
#include "Array.h" /** * Allocate a new array * * @return Array * */ Array * newArray() { Array * ret = (Array *) malloc(sizeof(Array)); return_null_if(ret == NULL); ret->items = NULL; ret->last = NULL; ret->length = 0; return ret; } /** * Clone an array * * @param Array * arr * * @return Array * */ Array * Array_clone(Array * arr) { Array * ret; ArrayItem * items; return_null_if(arr == NULL); ret = newArray(); if( arr->items != NULL ) { items = arr->items; do { Array_push(ret, items->data); } while((items = items->next)); } return ret; } /** * Allocate a new array item * * @param const pointer data * * @return ArrayItem * */ ArrayItem * newArrayItem(const pointer data) { ArrayItem * ret = (ArrayItem *) malloc(sizeof(ArrayItem)); return_null_if(ret == NULL); ret->next = NULL; ret->data = data; return ret; } /** * Get the nth element from the array, null if doesn't exist * * @param Array * arr * @param int index * * NOTE: we allow negative index * * @return ArrayItem * */ ArrayItem * Array_nth(Array * arr, int index) { ArrayItem * items; return_null_if(arr == NULL); items = arr->items; // if in empty array return_null_if(items == NULL); if ( index < 0 ) { index += arr->length; } return_null_if(index >= arr->length || index < 0); while ( index-- ) { items = items->next; } return items; } /** * Push data into the array * * @param Array * arr * @param const pointer data * * @return Array * */ Array * Array_push(Array * arr, const pointer data) { return_null_if(arr == NULL); if( arr->last == NULL ) { arr->items = arr->last = newArrayItem(data); arr->length++; return arr; } // debugging purposes return_null_if(arr->last->next != NULL); arr->last->next = newArrayItem(data); arr->last = arr->last->next; arr->length++; return arr; } /** * Set the data at given index. If element doesnt exists we add elements * * @param Array * arr * @param int index * @param const pointer data * * @return pointer data */ pointer Array_set(Array * arr, int index, const pointer data) { ArrayItem * item; return_null_if(arr == NULL); item = Array_nth(arr, index); // If the element does exist if( item != NULL ) { item->data = data; return data; } // We doesn't let assignment with negative index to an unknown element if( index < 0 ) { return NULL; } // If item doesnt exist we create enough empty elements while(arr->length <= index) { Array_push(arr, NULL); } Array_push(arr, data); return data; } /** * Get data from the nth element of the array * * @param Array * arr * @param int index * * @return pointer */ pointer Array_get(Array * arr, int index) { ArrayItem * item; return_null_if(arr == NULL); item = Array_nth(arr, index); return_null_if(item == NULL); return item->data; } /** * Removes the last element of the array and returns the data in it * NOTE: You must manually free the data in the returned pointer * * @param Array * arr * * @return pointer */ pointer Array_pop(Array * arr) { ArrayItem * penultimate; pointer ret; return_null_if(arr == NULL); // trying to pop from empty array return_null_if(arr->length == 0); if ( arr->length == 1 ) { ret = ArrayItem_free(arr->items, FALSE); arr->items = NULL; arr->length = 0; return ret; } penultimate = Array_nth(arr, -2); ret = ArrayItem_free(penultimate->next, FALSE); penultimate->next = NULL; arr->length--; return ret; } /** * Removes the first element from the array and returns the data in it * * @param Array * arr * * @return pointer */ pointer Array_shift(Array * arr) { ArrayItem * first; return_null_if(arr == NULL); first = arr->items; arr->items = arr->items->next; arr->length--; return ArrayItem_free(first, FALSE); } /** * Insert an element in the first position and return the length of the new array * TODO: do not return length and return another thing (for performance) * * @param Array * arr * @param const pointer data * * @return size_t */ size_t Array_unshift(Array * arr, const pointer data) { ArrayItem * item; return_val_if(arr == NULL, 0); item = newArrayItem(data); item->next = arr->items; arr->items = item; arr->length++; return arr->length; } /** * Delete a single element from array * If with_data is true, returns the element value * else returns null * * @param Array * arr * @param int index * @param boolean with_data * * @return void */ pointer Array_delete(Array * arr, int index, boolean with_data) { ArrayItem * element; ArrayItem * prev; return_null_if(arr == NULL); element = Array_nth(arr, index); // TODO: Check for negative index to the first element, which wont work if( index == 0 || index == - ((int) arr->length) ) { arr->items = element->next; // Element was last if ( element->next == NULL ) { arr->last = NULL; } } else { prev = Array_nth(arr, index - 1); prev->next = element->next; if ( element->next == NULL ) { arr->last = prev; } } arr->length--; return ArrayItem_free(element, with_data); } /** * Removes elements from an array and returns the new length * * @param Array * arr * @param int index starting item * @param size_t elements number of elements to remove * @param boolean with_data * * @return size_t */ size_t Array_splice(Array * arr, int index, size_t elements, boolean with_data) { size_t i; ArrayItem * prev; ArrayItem * last_removed_element; return_val_if(arr == NULL, 0); // this allows negative index if( index < 0 ) { index += arr->length; } return_val_if(index >= arr->length, arr->length); return_val_if(elements + index > arr->length, arr->length); if( index == 0 ) { for(i = 0; i < elements; i++) { Array_delete(arr, 0, with_data); } arr->length -= elements; return arr->length; } prev = Array_nth(arr, index - 1); return_val_if(prev == NULL, arr->length); last_removed_element = Array_nth(arr, index + elements - 1); i = elements - 1; // want to keep the last one // TODO: optimize while(i--) { ArrayItem_free(Array_nth(arr, index + i), with_data); } prev->next = last_removed_element->next; arr->length -= elements; // If removed the last element if ( prev->next == NULL ) { arr->last = prev; } ArrayItem_free(last_removed_element, with_data); return arr->length; } /** * Concat two arrays, modifying the first one * * @param Array * arr1 * @param Array * arr2 * * @return Array * arr1 */ Array * Array_concat(Array * arr1, Array * arr2) { arr1->last->next = arr2->items; arr1->length += arr2->length; arr1->last = arr2->last; return arr1; } /** * Check if element is in array * * @param Array * arr * @param const pointer data * * @return int -1 in error, index in success * NOTE: This performs strict pointer comparison */ int Array_contains(Array * arr, const pointer data) { size_t i = 0; pointer arr_data; return_val_if(arr == NULL, -1); ARRAY_EACH_WITH_INDEX(arr, arr_data, i, if ( arr_data == data ) { return i; } ); return -1; } /** * Loop through each array element data, calling callback * * @param Array * arr * @param void (* callback)(pointer, size_t, pointer) a function that receives the data, the index and the custom data * @param pointer data */ void Array_forEach(Array * arr, void (* callback)(pointer, size_t, pointer), pointer data) { pointer arr_data; size_t i = 0; return_if(arr == NULL); ARRAY_EACH_WITH_INDEX(arr, arr_data, i, callback(arr_data, i, data); ); } /** * Loop through each array element, calling callback * * @param Array * arr * @param void (* callback)(Array *, size_t) a function that receives the data and the index */ void Array_forEachItem(Array * arr, void (* callback)(ArrayItem *, size_t)) { ArrayItem * items; size_t i = 0; return_if(arr == NULL); items = arr->items; if( items ) { do { callback(items, i++); } while((items = items->next)); } } /** * Free an element memory * * @param ArrayItem * item * @param boolean with_data * * @return pointer the data if with_data was TRUE */ pointer ArrayItem_free(ArrayItem * item, boolean with_data) { pointer data; return_null_if(item == NULL); data = item->data; if ( with_data && data != NULL ) { free(item->data); data = NULL; } free(item); return data; } /** * Remove an array with all its items * * @param Array * arr * * @return void */ void Array_destroy(Array * arr, boolean with_data) { size_t length; return_if(arr == NULL); length = arr->length; // TODO: optimize, we must free reversing the order... while(length--) { ArrayItem_free(Array_nth(arr, length), with_data); } free(arr); } /** * Sorts the array using the bubble sort algo * * @param Array * arr * @param int (* compfunc) (pointer, pointer) * * @return void */ void Array_bsort(Array * arr, int (* compfunc)(pointer, pointer)) { size_t length, i, j; ArrayItem * current_item; ArrayItem * compared_item; pointer temp_data; return_if(arr == NULL); return_if(compfunc == NULL); length = arr->length; for(i = 0; i < length; i++) { for(j = 0; j < length - i - 1; j++) { current_item = Array_nth(arr, j); compared_item = current_item->next; if( compfunc(current_item->data, compared_item->data) <= 0 ) { // Instead of swapping the whole element we just swap the data // This doesn't break arr->last, so even better temp_data = current_item->data; current_item->data = compared_item->data; compared_item->data = temp_data; } } } }
{'content_hash': '4b7e6378cda9344d9b5e8540a2ace3ee', 'timestamp': '', 'source': 'github', 'line_count': 529, 'max_line_length': 118, 'avg_line_length': 18.134215500945178, 'alnum_prop': 0.6304597102053581, 'repo_name': 'ecoal95/clib', 'id': '180660cf45846ce19780003612398929f03f07f8', 'size': '9593', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/common/Array.c', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '153946'}, {'name': 'C++', 'bytes': '6763'}, {'name': 'Makefile', 'bytes': '290'}, {'name': 'Objective-C', 'bytes': '4705'}, {'name': 'Shell', 'bytes': '148'}]}
@interface CALayer (ARAnimation) @property (nonatomic, assign) CGFloat scaleX; @property (nonatomic, assign) CGFloat scaleY; @property (nonatomic, assign) CGFloat scale; @property (nonatomic, assign) CGFloat rotationX; @property (nonatomic, assign) CGFloat rotationY; @property (nonatomic, assign) CGFloat rotation; @end
{'content_hash': 'f818a2f0d886230543ef85b3ca459e34', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 48, 'avg_line_length': 29.454545454545453, 'alnum_prop': 0.7808641975308642, 'repo_name': 'AugustRush/ARAnimation', 'id': '58c4cb06b7ca9c26be259e947ce1e1c498e6d515', 'size': '536', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Source/CALayer+ARAnimation.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Objective-C', 'bytes': '46151'}, {'name': 'Ruby', 'bytes': '632'}]}
<!DOCTYPE html><html lang="en"><head><title>lib/misc/gulp/gulp-jison</title></head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0"><meta name="groc-relative-root" content="../../../"><meta name="groc-document-path" content="lib/misc/gulp/gulp-jison.js"><meta name="groc-project-path" content="lib/misc/gulp/gulp-jison.js"><meta name="groc-github-url" content="https://github.com/sjorek/goatee-script.js"><link rel="stylesheet" type="text/css" media="all" href="../../../assets/style.css"><script type="text/javascript" src="../../../assets/behavior.js"></script><body><div id="meta"><div class="file-path"><a href="https://github.com/sjorek/goatee-script.js/blob/master/lib/misc/gulp/gulp-jison.js">lib/misc/gulp/gulp-jison.js</a></div></div><div id="document"><div class="segment"><div class="code folded"><div class="wrapper marker"><span class="c1"></span> (<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{ <span class="hljs-keyword">var</span> PLUGIN_NAME, PluginError, cli, fs, map, path, util, hasProp = {}.hasOwnProperty; fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>); path = <span class="hljs-built_in">require</span>(<span class="hljs-string">'path'</span>); map = <span class="hljs-built_in">require</span>(<span class="hljs-string">'map-stream'</span>); util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'gulp-util'</span>); PluginError = util.PluginError; cli = <span class="hljs-built_in">require</span>(<span class="hljs-string">'jison/lib/cli'</span>);</div></div></div><div class="segment"><div class="comments "><div class="wrapper"><h1 id="gulp-jison">Gulp Jison</h1> <hr></div></div><div class="code"><div class="wrapper"> PLUGIN_NAME = <span class="hljs-string">'gulp-jison'</span>; <span class="hljs-built_in">module</span>.exports = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">options</span>) </span>{ <span class="hljs-keyword">var</span> jison, lex, processFile; lex = <span class="hljs-literal">null</span>; <span class="hljs-keyword">if</span> (options.lexfile != <span class="hljs-literal">null</span>) { lex = fs.readFileSync(path.normalize(options.lexfile), <span class="hljs-string">'utf8'</span>); } processFile = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">file, options</span>) </span>{ <span class="hljs-keyword">var</span> grammar, key, name, opts, raw, ref, value; opts = {}; <span class="hljs-keyword">if</span> (options != <span class="hljs-literal">null</span>) { <span class="hljs-keyword">for</span> (key <span class="hljs-keyword">in</span> options) { <span class="hljs-keyword">if</span> (!hasProp.call(options, key)) <span class="hljs-keyword">continue</span>; value = options[key]; opts[key] = value; } } opts.file = file.path; raw = file.contents.toString(); <span class="hljs-keyword">if</span> (!opts.json) { opts.json = path.extname(opts.file) === <span class="hljs-string">'.json'</span>; } name = path.basename((ref = opts.outfile) != <span class="hljs-literal">null</span> ? ref : opts.file).replace(<span class="hljs-regexp">/\..*$/g</span>, <span class="hljs-string">''</span>); <span class="hljs-keyword">if</span> (opts.outfile == <span class="hljs-literal">null</span>) { opts.outfile = name + <span class="hljs-string">".js"</span>; } <span class="hljs-keyword">if</span> ((opts.moduleName == <span class="hljs-literal">null</span>) &amp;&amp; name) { opts.moduleName = name.replace(<span class="hljs-regexp">/-\w/g</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">match</span>) </span>{ <span class="hljs-keyword">return</span> match.charAt(<span class="hljs-number">1</span>).toUpperCase(); }); } grammar = cli.processGrammars(raw, lex, opts.json); <span class="hljs-keyword">return</span> cli.generateParserString(opts, grammar); }; jison = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">file, cb</span>) </span>{ <span class="hljs-keyword">var</span> contents; contents = processFile(file, options); <span class="hljs-keyword">if</span> (contents <span class="hljs-keyword">instanceof</span> <span class="hljs-built_in">Error</span>) { <span class="hljs-keyword">return</span> cb(contents); } file.contents = <span class="hljs-keyword">new</span> Buffer(contents); file.path = util.replaceExtension(<span class="hljs-string">'.js'</span>); <span class="hljs-keyword">return</span> callback(<span class="hljs-literal">null</span>, file); }; <span class="hljs-keyword">return</span> map(jison); }; }).call(<span class="hljs-keyword">this</span>); <span class="hljs-comment">//# sourceMappingURL=gulp-jison.js.map</span></div></div></div></div></body></html>
{'content_hash': '015b603cdf18846313b5c18f7405091c', 'timestamp': '', 'source': 'github', 'line_count': 67, 'max_line_length': 986, 'avg_line_length': 83.35820895522389, 'alnum_prop': 0.6196956132497762, 'repo_name': 'sjorek/goatee-script.js', 'id': '08e32534dcf927cf313a34e91b17fe90dae46e9f', 'size': '7169', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'doc/lib/misc/gulp/gulp-jison.js.html', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CoffeeScript', 'bytes': '145489'}, {'name': 'JavaScript', 'bytes': '124861'}]}
class AddMuesliToLecture < ActiveRecord::Migration[5.2] def change add_column :lectures, :muesli, :boolean end end
{'content_hash': 'ca15d83c5d552d2768816f97d60c5bca', 'timestamp': '', 'source': 'github', 'line_count': 5, 'max_line_length': 55, 'avg_line_length': 24.6, 'alnum_prop': 0.7398373983739838, 'repo_name': 'fosterfarrell9/mampf', 'id': '68f312fe6774d7c5aeb705d02dc0d763659dd7a6', 'size': '123', 'binary': False, 'copies': '1', 'ref': 'refs/heads/mampf-next', 'path': 'db/migrate/20190207092000_add_muesli_to_lecture.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '23598'}, {'name': 'CoffeeScript', 'bytes': '224112'}, {'name': 'Dockerfile', 'bytes': '806'}, {'name': 'HTML', 'bytes': '536434'}, {'name': 'JavaScript', 'bytes': '4185'}, {'name': 'Ruby', 'bytes': '572182'}, {'name': 'Shell', 'bytes': '830'}, {'name': 'TeX', 'bytes': '8417'}]}
'use strict'; import Render from './KeyboardRender.native'; export default function () { return Render.call(this, this.props, this.state); }
{'content_hash': '03b8913ebd808e3b4ced2095a16c6cc2', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 51, 'avg_line_length': 20.714285714285715, 'alnum_prop': 0.7172413793103448, 'repo_name': 'benoitvallon/react-native-nw-react-calculator', 'id': 'b9a23e457fbba9c532aacca1992c94983b5c2649', 'size': '145', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/common/components/KeyboardRender.ios.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1935'}, {'name': 'HTML', 'bytes': '1024'}, {'name': 'Java', 'bytes': '1151'}, {'name': 'JavaScript', 'bytes': '98745'}, {'name': 'Objective-C', 'bytes': '5035'}]}
(function() { angular.module("barbschwarz") .directive("siteHeader", [function() { return { restrict: 'A', templateUrl: "assets/js/angular/directives-template/header.html" }; // return }]) // siteHeader .directive("siteFooter", [function () { return { restrict: 'A', templateUrl: "assets/js/angular/directives-template/footer.html" }; // return }]) // siteFooter ; // angular.module })();
{'content_hash': '136662ba8ced7b98f9c227e8f0258dee', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 80, 'avg_line_length': 31.88235294117647, 'alnum_prop': 0.496309963099631, 'repo_name': 'leemtek/barb-schwarz.com', 'id': '64ea07aa6be578f0f45bbf70693da5fe952e897e', 'size': '542', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'assets/js/angular/directives.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '14'}, {'name': 'CSS', 'bytes': '841512'}, {'name': 'HTML', 'bytes': '101969'}, {'name': 'JavaScript', 'bytes': '893846'}, {'name': 'PHP', 'bytes': '593165'}]}
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System.Security.Claims; namespace Microsoft.Azure.WebJobs.Extensions.Http { internal interface IIdentityPrincipal { ClaimsIdentity ToClaimsIdentity(); } }
{'content_hash': '7a34cdd201f4bbc6644aa6b34ad634e2', 'timestamp': '', 'source': 'github', 'line_count': 12, 'max_line_length': 95, 'avg_line_length': 27.833333333333332, 'alnum_prop': 0.7485029940119761, 'repo_name': 'Azure/azure-webjobs-sdk-extensions', 'id': '4e8fac3824312bc6588d273404c547db56f08d91', 'size': '336', 'binary': False, 'copies': '1', 'ref': 'refs/heads/dev', 'path': 'src/WebJobs.Extensions.Http/IIdentityPrincipal.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '959386'}, {'name': 'PowerShell', 'bytes': '5379'}, {'name': 'Smalltalk', 'bytes': '79210'}]}
.class final Lokhttp3/RealCall; .super Ljava/lang/Object; .source "RealCall.java" # interfaces .implements Lokhttp3/Call; # annotations .annotation system Ldalvik/annotation/MemberClasses; value = { Lokhttp3/RealCall$AsyncCall; } .end annotation # instance fields .field final client:Lokhttp3/OkHttpClient; .field final eventListener:Lokhttp3/EventListener; .field private executed:Z .field final forWebSocket:Z .field final originalRequest:Lokhttp3/Request; .field final retryAndFollowUpInterceptor:Lokhttp3/internal/http/RetryAndFollowUpInterceptor; # direct methods .method constructor <init>(Lokhttp3/OkHttpClient;Lokhttp3/Request;Z)V .locals 2 .param p1, "client" # Lokhttp3/OkHttpClient; .param p2, "originalRequest" # Lokhttp3/Request; .param p3, "forWebSocket" # Z .prologue .line 45 invoke-direct {p0}, Ljava/lang/Object;-><init>()V .line 46 invoke-virtual {p1}, Lokhttp3/OkHttpClient;->eventListenerFactory()Lokhttp3/EventListener$Factory; move-result-object v0 .line 48 .local v0, "eventListenerFactory":Lokhttp3/EventListener$Factory; iput-object p1, p0, Lokhttp3/RealCall;->client:Lokhttp3/OkHttpClient; .line 49 iput-object p2, p0, Lokhttp3/RealCall;->originalRequest:Lokhttp3/Request; .line 50 iput-boolean p3, p0, Lokhttp3/RealCall;->forWebSocket:Z .line 51 new-instance v1, Lokhttp3/internal/http/RetryAndFollowUpInterceptor; invoke-direct {v1, p1, p3}, Lokhttp3/internal/http/RetryAndFollowUpInterceptor;-><init>(Lokhttp3/OkHttpClient;Z)V iput-object v1, p0, Lokhttp3/RealCall;->retryAndFollowUpInterceptor:Lokhttp3/internal/http/RetryAndFollowUpInterceptor; .line 54 invoke-interface {v0, p0}, Lokhttp3/EventListener$Factory;->create(Lokhttp3/Call;)Lokhttp3/EventListener; move-result-object v1 iput-object v1, p0, Lokhttp3/RealCall;->eventListener:Lokhttp3/EventListener; .line 55 return-void .end method .method private captureCallStackTrace()V .locals 3 .prologue .line 78 invoke-static {}, Lokhttp3/internal/platform/Platform;->get()Lokhttp3/internal/platform/Platform; move-result-object v1 const-string v2, "response.body().close()" invoke-virtual {v1, v2}, Lokhttp3/internal/platform/Platform;->getStackTraceForCloseable(Ljava/lang/String;)Ljava/lang/Object; move-result-object v0 .line 79 .local v0, "callStackTrace":Ljava/lang/Object; iget-object v1, p0, Lokhttp3/RealCall;->retryAndFollowUpInterceptor:Lokhttp3/internal/http/RetryAndFollowUpInterceptor; invoke-virtual {v1, v0}, Lokhttp3/internal/http/RetryAndFollowUpInterceptor;->setCallStackTrace(Ljava/lang/Object;)V .line 80 return-void .end method # virtual methods .method public cancel()V .locals 1 .prologue .line 92 iget-object v0, p0, Lokhttp3/RealCall;->retryAndFollowUpInterceptor:Lokhttp3/internal/http/RetryAndFollowUpInterceptor; invoke-virtual {v0}, Lokhttp3/internal/http/RetryAndFollowUpInterceptor;->cancel()V .line 93 return-void .end method .method public bridge synthetic clone()Ljava/lang/Object; .locals 1 .annotation system Ldalvik/annotation/Throws; value = { Ljava/lang/CloneNotSupportedException; } .end annotation .prologue .line 33 invoke-virtual {p0}, Lokhttp3/RealCall;->clone()Lokhttp3/RealCall; move-result-object v0 return-object v0 .end method .method public bridge synthetic clone()Lokhttp3/Call; .locals 1 .prologue .line 33 invoke-virtual {p0}, Lokhttp3/RealCall;->clone()Lokhttp3/RealCall; move-result-object v0 return-object v0 .end method .method public clone()Lokhttp3/RealCall; .locals 4 .prologue .line 105 new-instance v0, Lokhttp3/RealCall; iget-object v1, p0, Lokhttp3/RealCall;->client:Lokhttp3/OkHttpClient; iget-object v2, p0, Lokhttp3/RealCall;->originalRequest:Lokhttp3/Request; iget-boolean v3, p0, Lokhttp3/RealCall;->forWebSocket:Z invoke-direct {v0, v1, v2, v3}, Lokhttp3/RealCall;-><init>(Lokhttp3/OkHttpClient;Lokhttp3/Request;Z)V return-object v0 .end method .method public enqueue(Lokhttp3/Callback;)V .locals 2 .param p1, "responseCallback" # Lokhttp3/Callback; .prologue .line 83 monitor-enter p0 .line 84 :try_start_0 iget-boolean v0, p0, Lokhttp3/RealCall;->executed:Z if-eqz v0, :cond_0 new-instance v0, Ljava/lang/IllegalStateException; const-string v1, "Already Executed" invoke-direct {v0, v1}, Ljava/lang/IllegalStateException;-><init>(Ljava/lang/String;)V throw v0 .line 86 :catchall_0 move-exception v0 monitor-exit p0 :try_end_0 .catchall {:try_start_0 .. :try_end_0} :catchall_0 throw v0 .line 85 :cond_0 const/4 v0, 0x1 :try_start_1 iput-boolean v0, p0, Lokhttp3/RealCall;->executed:Z .line 86 monitor-exit p0 :try_end_1 .catchall {:try_start_1 .. :try_end_1} :catchall_0 .line 87 invoke-direct {p0}, Lokhttp3/RealCall;->captureCallStackTrace()V .line 88 iget-object v0, p0, Lokhttp3/RealCall;->client:Lokhttp3/OkHttpClient; invoke-virtual {v0}, Lokhttp3/OkHttpClient;->dispatcher()Lokhttp3/Dispatcher; move-result-object v0 new-instance v1, Lokhttp3/RealCall$AsyncCall; invoke-direct {v1, p0, p1}, Lokhttp3/RealCall$AsyncCall;-><init>(Lokhttp3/RealCall;Lokhttp3/Callback;)V invoke-virtual {v0, v1}, Lokhttp3/Dispatcher;->enqueue(Lokhttp3/RealCall$AsyncCall;)V .line 89 return-void .end method .method public execute()Lokhttp3/Response; .locals 3 .annotation system Ldalvik/annotation/Throws; value = { Ljava/io/IOException; } .end annotation .prologue .line 62 monitor-enter p0 .line 63 :try_start_0 iget-boolean v1, p0, Lokhttp3/RealCall;->executed:Z if-eqz v1, :cond_0 new-instance v1, Ljava/lang/IllegalStateException; const-string v2, "Already Executed" invoke-direct {v1, v2}, Ljava/lang/IllegalStateException;-><init>(Ljava/lang/String;)V throw v1 .line 65 :catchall_0 move-exception v1 monitor-exit p0 :try_end_0 .catchall {:try_start_0 .. :try_end_0} :catchall_0 throw v1 .line 64 :cond_0 const/4 v1, 0x1 :try_start_1 iput-boolean v1, p0, Lokhttp3/RealCall;->executed:Z .line 65 monitor-exit p0 :try_end_1 .catchall {:try_start_1 .. :try_end_1} :catchall_0 .line 66 invoke-direct {p0}, Lokhttp3/RealCall;->captureCallStackTrace()V .line 68 :try_start_2 iget-object v1, p0, Lokhttp3/RealCall;->client:Lokhttp3/OkHttpClient; invoke-virtual {v1}, Lokhttp3/OkHttpClient;->dispatcher()Lokhttp3/Dispatcher; move-result-object v1 invoke-virtual {v1, p0}, Lokhttp3/Dispatcher;->executed(Lokhttp3/RealCall;)V .line 69 invoke-virtual {p0}, Lokhttp3/RealCall;->getResponseWithInterceptorChain()Lokhttp3/Response; move-result-object v0 .line 70 .local v0, "result":Lokhttp3/Response; if-nez v0, :cond_1 new-instance v1, Ljava/io/IOException; const-string v2, "Canceled" invoke-direct {v1, v2}, Ljava/io/IOException;-><init>(Ljava/lang/String;)V throw v1 :try_end_2 .catchall {:try_start_2 .. :try_end_2} :catchall_1 .line 73 .end local v0 # "result":Lokhttp3/Response; :catchall_1 move-exception v1 iget-object v2, p0, Lokhttp3/RealCall;->client:Lokhttp3/OkHttpClient; invoke-virtual {v2}, Lokhttp3/OkHttpClient;->dispatcher()Lokhttp3/Dispatcher; move-result-object v2 invoke-virtual {v2, p0}, Lokhttp3/Dispatcher;->finished(Lokhttp3/RealCall;)V throw v1 .restart local v0 # "result":Lokhttp3/Response; :cond_1 iget-object v1, p0, Lokhttp3/RealCall;->client:Lokhttp3/OkHttpClient; invoke-virtual {v1}, Lokhttp3/OkHttpClient;->dispatcher()Lokhttp3/Dispatcher; move-result-object v1 invoke-virtual {v1, p0}, Lokhttp3/Dispatcher;->finished(Lokhttp3/RealCall;)V .line 71 return-object v0 .end method .method getResponseWithInterceptorChain()Lokhttp3/Response; .locals 7 .annotation system Ldalvik/annotation/Throws; value = { Ljava/io/IOException; } .end annotation .prologue const/4 v2, 0x0 .line 172 new-instance v1, Ljava/util/ArrayList; invoke-direct {v1}, Ljava/util/ArrayList;-><init>()V .line 173 .local v1, "interceptors":Ljava/util/List;, "Ljava/util/List<Lokhttp3/Interceptor;>;" iget-object v3, p0, Lokhttp3/RealCall;->client:Lokhttp3/OkHttpClient; invoke-virtual {v3}, Lokhttp3/OkHttpClient;->interceptors()Ljava/util/List; move-result-object v3 invoke-interface {v1, v3}, Ljava/util/List;->addAll(Ljava/util/Collection;)Z .line 174 iget-object v3, p0, Lokhttp3/RealCall;->retryAndFollowUpInterceptor:Lokhttp3/internal/http/RetryAndFollowUpInterceptor; invoke-interface {v1, v3}, Ljava/util/List;->add(Ljava/lang/Object;)Z .line 175 new-instance v3, Lokhttp3/internal/http/BridgeInterceptor; iget-object v4, p0, Lokhttp3/RealCall;->client:Lokhttp3/OkHttpClient; invoke-virtual {v4}, Lokhttp3/OkHttpClient;->cookieJar()Lokhttp3/CookieJar; move-result-object v4 invoke-direct {v3, v4}, Lokhttp3/internal/http/BridgeInterceptor;-><init>(Lokhttp3/CookieJar;)V invoke-interface {v1, v3}, Ljava/util/List;->add(Ljava/lang/Object;)Z .line 176 new-instance v3, Lokhttp3/internal/cache/CacheInterceptor; iget-object v4, p0, Lokhttp3/RealCall;->client:Lokhttp3/OkHttpClient; invoke-virtual {v4}, Lokhttp3/OkHttpClient;->internalCache()Lokhttp3/internal/cache/InternalCache; move-result-object v4 invoke-direct {v3, v4}, Lokhttp3/internal/cache/CacheInterceptor;-><init>(Lokhttp3/internal/cache/InternalCache;)V invoke-interface {v1, v3}, Ljava/util/List;->add(Ljava/lang/Object;)Z .line 177 new-instance v3, Lokhttp3/internal/connection/ConnectInterceptor; iget-object v4, p0, Lokhttp3/RealCall;->client:Lokhttp3/OkHttpClient; invoke-direct {v3, v4}, Lokhttp3/internal/connection/ConnectInterceptor;-><init>(Lokhttp3/OkHttpClient;)V invoke-interface {v1, v3}, Ljava/util/List;->add(Ljava/lang/Object;)Z .line 178 iget-boolean v3, p0, Lokhttp3/RealCall;->forWebSocket:Z if-nez v3, :cond_0 .line 179 iget-object v3, p0, Lokhttp3/RealCall;->client:Lokhttp3/OkHttpClient; invoke-virtual {v3}, Lokhttp3/OkHttpClient;->networkInterceptors()Ljava/util/List; move-result-object v3 invoke-interface {v1, v3}, Ljava/util/List;->addAll(Ljava/util/Collection;)Z .line 181 :cond_0 new-instance v3, Lokhttp3/internal/http/CallServerInterceptor; iget-boolean v4, p0, Lokhttp3/RealCall;->forWebSocket:Z invoke-direct {v3, v4}, Lokhttp3/internal/http/CallServerInterceptor;-><init>(Z)V invoke-interface {v1, v3}, Ljava/util/List;->add(Ljava/lang/Object;)Z .line 183 new-instance v0, Lokhttp3/internal/http/RealInterceptorChain; const/4 v5, 0x0 iget-object v6, p0, Lokhttp3/RealCall;->originalRequest:Lokhttp3/Request; move-object v3, v2 move-object v4, v2 invoke-direct/range {v0 .. v6}, Lokhttp3/internal/http/RealInterceptorChain;-><init>(Ljava/util/List;Lokhttp3/internal/connection/StreamAllocation;Lokhttp3/internal/http/HttpCodec;Lokhttp3/internal/connection/RealConnection;ILokhttp3/Request;)V .line 185 .local v0, "chain":Lokhttp3/Interceptor$Chain; iget-object v2, p0, Lokhttp3/RealCall;->originalRequest:Lokhttp3/Request; invoke-interface {v0, v2}, Lokhttp3/Interceptor$Chain;->proceed(Lokhttp3/Request;)Lokhttp3/Response; move-result-object v2 return-object v2 .end method .method public isCanceled()Z .locals 1 .prologue .line 100 iget-object v0, p0, Lokhttp3/RealCall;->retryAndFollowUpInterceptor:Lokhttp3/internal/http/RetryAndFollowUpInterceptor; invoke-virtual {v0}, Lokhttp3/internal/http/RetryAndFollowUpInterceptor;->isCanceled()Z move-result v0 return v0 .end method .method public declared-synchronized isExecuted()Z .locals 1 .prologue .line 96 monitor-enter p0 :try_start_0 iget-boolean v0, p0, Lokhttp3/RealCall;->executed:Z :try_end_0 .catchall {:try_start_0 .. :try_end_0} :catchall_0 monitor-exit p0 return v0 :catchall_0 move-exception v0 monitor-exit p0 throw v0 .end method .method redactedUrl()Ljava/lang/String; .locals 1 .prologue .line 167 iget-object v0, p0, Lokhttp3/RealCall;->originalRequest:Lokhttp3/Request; invoke-virtual {v0}, Lokhttp3/Request;->url()Lokhttp3/HttpUrl; move-result-object v0 invoke-virtual {v0}, Lokhttp3/HttpUrl;->redact()Ljava/lang/String; move-result-object v0 return-object v0 .end method .method public request()Lokhttp3/Request; .locals 1 .prologue .line 58 iget-object v0, p0, Lokhttp3/RealCall;->originalRequest:Lokhttp3/Request; return-object v0 .end method .method streamAllocation()Lokhttp3/internal/connection/StreamAllocation; .locals 1 .prologue .line 109 iget-object v0, p0, Lokhttp3/RealCall;->retryAndFollowUpInterceptor:Lokhttp3/internal/http/RetryAndFollowUpInterceptor; invoke-virtual {v0}, Lokhttp3/internal/http/RetryAndFollowUpInterceptor;->streamAllocation()Lokhttp3/internal/connection/StreamAllocation; move-result-object v0 return-object v0 .end method .method toLoggableString()Ljava/lang/String; .locals 2 .prologue .line 161 new-instance v1, Ljava/lang/StringBuilder; invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V invoke-virtual {p0}, Lokhttp3/RealCall;->isCanceled()Z move-result v0 if-eqz v0, :cond_0 const-string v0, "canceled " :goto_0 invoke-virtual {v1, v0}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v1 iget-boolean v0, p0, Lokhttp3/RealCall;->forWebSocket:Z if-eqz v0, :cond_1 .line 162 const-string v0, "web socket" :goto_1 invoke-virtual {v1, v0}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v0 const-string v1, " to " invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v0 .line 163 invoke-virtual {p0}, Lokhttp3/RealCall;->redactedUrl()Ljava/lang/String; move-result-object v1 invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v0 invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String; move-result-object v0 .line 161 return-object v0 :cond_0 const-string v0, "" goto :goto_0 .line 162 :cond_1 const-string v0, "call" goto :goto_1 .end method
{'content_hash': 'bafe94829b656c6a5fdc2d72a0770691', 'timestamp': '', 'source': 'github', 'line_count': 595, 'max_line_length': 248, 'avg_line_length': 25.34453781512605, 'alnum_prop': 0.7025862068965517, 'repo_name': 'tarsoqueiroz/NodeJS', 'id': '6ec1154b185cfd6c723a57bebdf412922caff35a', 'size': '15080', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Modules/android.JS/dist/app-debug/smali/okhttp3/RealCall.smali', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1268796'}, {'name': 'Dockerfile', 'bytes': '434'}, {'name': 'EJS', 'bytes': '665092'}, {'name': 'HTML', 'bytes': '3930157'}, {'name': 'Handlebars', 'bytes': '18028'}, {'name': 'JavaScript', 'bytes': '7009576'}, {'name': 'Pug', 'bytes': '31461'}, {'name': 'SCSS', 'bytes': '196080'}, {'name': 'Shell', 'bytes': '907'}, {'name': 'Solidity', 'bytes': '3291'}, {'name': 'Svelte', 'bytes': '9405'}, {'name': 'TypeScript', 'bytes': '304'}, {'name': 'WebAssembly', 'bytes': '89924'}]}
@implementation YDImageDownloadManager + (instancetype)sharedManager { static id instance; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ instance = [[self alloc] init]; }); return instance; } - (void)downloadImageWithUrl:(NSString *)url { ^(NSString *a){ }; } @end
{'content_hash': 'd86ea6b8812d60b73b472cbc52a6778d', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 44, 'avg_line_length': 15.952380952380953, 'alnum_prop': 0.6208955223880597, 'repo_name': 'wenbobao/CodeDemo', 'id': '205f8cd0690bcbe0ff57359d241f3fce10abb09f', 'size': '560', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'YDImageDownload/YDImageDownload/YDImageDownloadManager.m', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '138387'}, {'name': 'CSS', 'bytes': '3398'}, {'name': 'DTrace', 'bytes': '1236'}, {'name': 'HTML', 'bytes': '14823'}, {'name': 'JavaScript', 'bytes': '11044'}, {'name': 'Objective-C', 'bytes': '4887472'}, {'name': 'Objective-C++', 'bytes': '26946'}, {'name': 'Ruby', 'bytes': '5165'}, {'name': 'Shell', 'bytes': '110940'}, {'name': 'Swift', 'bytes': '208764'}]}
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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. package com.cloud.hypervisor.ovm3.objects; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import java.util.TimeZone; import org.apache.log4j.Logger; import org.apache.xmlrpc.XmlRpcException; import org.apache.xmlrpc.client.TimingOutCallback; import org.apache.xmlrpc.client.XmlRpcClient; import org.apache.xmlrpc.client.XmlRpcClientConfigImpl; import org.apache.xmlrpc.client.XmlRpcClientRequestImpl; public class Connection extends XmlRpcClient { private static final Logger LOGGER = Logger.getLogger(Connection.class); private final XmlRpcClientConfigImpl xmlClientConfig = new XmlRpcClientConfigImpl(); private XmlRpcClient xmlClient; private String hostUser = null; private String hostPass = null; private String hostIp; private String hostName; private Integer hostPort = 8899; private Boolean hostUseSsl = false; private String cert = ""; private String key = ""; /* default to 20 mins ? */ private Integer timeoutMs = 1200; private Integer timeoutS = timeoutMs * 1000; public Connection() { } public Connection(String ip, Integer port, String username, String password) { hostIp = ip; hostPort = port; hostUser = username; hostPass = password; xmlClient = setupXmlClient(); } public Connection(String ip, String username, String password) { hostIp = ip; hostUser = username; hostPass = password; xmlClient = setupXmlClient(); } private XmlRpcClient setupXmlClient() { final XmlRpcClient client = new XmlRpcClient(); URL url; try { /* TODO: should add SSL checking here! */ String prot = "http"; if (hostUseSsl) { prot = "https"; } url = new URL(prot + "://" + hostIp + ":" + hostPort.toString()); xmlClientConfig.setTimeZone(TimeZone.getTimeZone("UTC")); xmlClientConfig.setServerURL(url); /* disable, we use asyncexecute to control timeout */ xmlClientConfig.setReplyTimeout(0); /* default to 60 secs */ xmlClientConfig.setConnectionTimeout(60000); /* reply time is 5 mins */ xmlClientConfig.setReplyTimeout(60 * 15000); if (hostUser != null && hostPass != null) { LOGGER.debug("Setting username " + hostUser); xmlClientConfig.setBasicUserName(hostUser); xmlClientConfig.setBasicPassword(hostPass); } xmlClientConfig.setXmlRpcServer(null); client.setConfig(xmlClientConfig); client.setTypeFactory(new RpcTypeFactory(client)); } catch (MalformedURLException e) { LOGGER.info("Incorrect URL: ", e); } return client; } public Object call(String method, List<?> params) throws XmlRpcException { return callTimeoutInSec(method, params, this.timeoutS); } public Object call(String method, List<?> params, boolean debug) throws XmlRpcException { return callTimeoutInSec(method, params, this.timeoutS, debug); } public Object callTimeoutInSec(String method, List<?> params, int timeout, boolean debug) throws XmlRpcException { TimingOutCallback callback = new TimingOutCallback(timeout * 1000); if (debug) { LOGGER.debug("Call Ovm3 agent " + hostName + "(" + hostIp +"): " + method + " with " + params); } long startTime = System.currentTimeMillis(); try { /* returns actual xml */ XmlRpcClientRequestImpl req = new XmlRpcClientRequestImpl( xmlClient.getClientConfig(), method, params); xmlClient.executeAsync(req, callback); return callback.waitForResponse(); } catch (TimingOutCallback.TimeoutException e) { LOGGER.info("Timeout: ", e); throw new XmlRpcException(e.getMessage()); } catch (XmlRpcException e) { LOGGER.info("XML RPC Exception occured: ", e); throw e; } catch (RuntimeException e) { LOGGER.info("Runtime Exception: ", e); throw new XmlRpcException(e.getMessage()); } catch (Throwable e) { LOGGER.error("Holy crap batman!: ", e); throw new XmlRpcException(e.getMessage(), e); } finally { long endTime = System.currentTimeMillis(); /* in seconds */ float during = (endTime - startTime) / (float) 1000; LOGGER.debug("Ovm3 call " + method + " finished in " + during + " secs, on " + hostIp + ":" + hostPort); } } public Object callTimeoutInSec(String method, List<?> params, int timeout) throws XmlRpcException { return callTimeoutInSec(method, params, timeout, true); } public String getIp() { return hostIp; } public Integer getPort() { return hostPort; } public String getUserName() { return hostUser; } public void setUserName(String s) { hostUser = s; } public String getPassword() { return hostPass; } public Boolean getUseSsl() { return hostUseSsl; } public String getCert() { return cert; } public String getKey() { return key; } public String getHostName() { return hostName; } public void setHostName(String hostName) { this.hostName = hostName; } public void setIp(String agentIp) { hostIp = agentIp; } public void setPassword(String agentPassword) { hostPass = agentPassword; } }
{'content_hash': '3c0884b2500fcd69519a8d334e1897df', 'timestamp': '', 'source': 'github', 'line_count': 195, 'max_line_length': 88, 'avg_line_length': 33.85641025641026, 'alnum_prop': 0.625719478945774, 'repo_name': 'DaanHoogland/cloudstack', 'id': '711e5506f04c81938d570af8e3a1d6615ef16732', 'size': '6602', 'binary': False, 'copies': '6', 'ref': 'refs/heads/main', 'path': 'plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Connection.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '9979'}, {'name': 'C#', 'bytes': '2356211'}, {'name': 'CSS', 'bytes': '343148'}, {'name': 'Dockerfile', 'bytes': '2375'}, {'name': 'FreeMarker', 'bytes': '4887'}, {'name': 'Groovy', 'bytes': '146420'}, {'name': 'HTML', 'bytes': '153560'}, {'name': 'Java', 'bytes': '36818077'}, {'name': 'JavaScript', 'bytes': '8264908'}, {'name': 'Python', 'bytes': '12533840'}, {'name': 'Ruby', 'bytes': '22732'}, {'name': 'SCSS', 'bytes': '362625'}, {'name': 'Shell', 'bytes': '708848'}, {'name': 'XSLT', 'bytes': '57835'}]}
package streak import ( "encoding/json" "errors" "fmt" "io/ioutil" "net/http" "time" "github.com/golang/glog" ) const API_URL = "https://www.streak.com/api/v1" // Returns the time.Time value represented by the Streak timestamp timestampMs. // Streak uses milliseconds since the Unix epoch. func TimestampToTime(timestampMs int64) time.Time { seconds := timestampMs / 1000 nanoseconds := (timestampMs % 1000) * 1000000 return time.Unix(seconds, nanoseconds).UTC() } // Returns t as a Streak timestamp (milliseconds since the Unix epoch). // The result is rounded to the nearest millisecond. func TimeToTimestamp(t time.Time) int64 { ns := t.UnixNano() const MS_PER_NS = 1000000 return (ns + (MS_PER_NS / 2)) / MS_PER_NS } // Client for communicating with Streak. type Client struct { ApiKey string httpClient http.Client baseUrl string } // Returns a new Client using apiKey as the API key. func New(apiKey string) *Client { return newWithbaseUrl(apiKey, API_URL) } // For testing with a different server. func newWithbaseUrl(apiKey string, baseUrl string) *Client { if baseUrl[len(baseUrl)-1] == '/' { panic("baseUrl must not end with /: " + baseUrl) } return &Client{apiKey, http.Client{}, baseUrl} } func (c *Client) request(path string, outValue interface{}) error { if path[0] != '/' { panic("path must start with /: " + path) } // Make the request and read the response url := c.baseUrl + path request, err := http.NewRequest("GET", url, nil) if err != nil { return err } request.SetBasicAuth(c.ApiKey, "") response, err := c.httpClient.Do(request) if err != nil { return err } if response.StatusCode != http.StatusOK { errorMessage := fmt.Sprintf("Streak HTTP request failed code: %d", response.StatusCode) glog.Warning(errorMessage) return errors.New(errorMessage) } responseBytes, err := ioutil.ReadAll(response.Body) response.Body.Close() if err != nil { return err } // Parse the response // fmt.Println(string(responseBytes)) err = json.Unmarshal(responseBytes, outValue) if err != nil { glog.Warningf("Parsing response from Streak failed; raw data: %s", string(responseBytes)) return err } return err } // Represents a single Streak pipeline. See http://www.streak.com/api/#pipeline type Pipeline struct { Key string `json:"key"` Name string `json:"name"` Description string `json:"description"` LastUpdatedTimestamp int64 `json:"lastUpdatedTimestamp"` } type Box struct { Key string `json:"key"` Name string `json:"name"` LastUpdatedTimestamp int64 `json:"lastUpdatedTimestamp"` GmailThreadCount int64 `json:"gmailThreadCount"` } type Thread struct { Key string `json:"key"` Subject string `json:"subject"` LastUpdatedTimestamp int64 `json:"lastUpdatedTimestamp"` CreationTimestamp int64 `json:"creationTimestamp"` LastEmailTimestamp int64 `json:"lastEmailTimestamp"` } // Returns all pipelines. See: http://www.streak.com/api/#listallpipelines func (c *Client) GetPipelines() ([]Pipeline, error) { var pipelines []Pipeline err := c.request("/pipelines", &pipelines) return pipelines, err } func (c *Client) GetBoxes(pipeline *Pipeline) ([]Box, error) { var boxes []Box err := c.request(fmt.Sprintf("/pipelines/%s/boxes", pipeline.Key), &boxes) return boxes, err } func (c *Client) GetThreads(box *Box) ([]Thread, error) { var threads []Thread err := c.request(fmt.Sprintf("/boxes/%s/threads", box.Key), &threads) return threads, err }
{'content_hash': '885a73d8f7b06332325534fba583ac7f', 'timestamp': '', 'source': 'github', 'line_count': 133, 'max_line_length': 91, 'avg_line_length': 26.93233082706767, 'alnum_prop': 0.6878838637632607, 'repo_name': 'evanj/streak', 'id': 'ab4d30718b246364337930d8bc8af6b837d13294', 'size': '3631', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'streak.go', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Go', 'bytes': '7101'}, {'name': 'Shell', 'bytes': '176'}]}
package co.cask.cdap.api.dataset.lib; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import javax.annotation.Nonnull; /** * This class describes how a dataset is partitioned, by means of the fields of a partition key and their types. * The ordering of fields in the partitioning matters: It is the order in which partition keys are indexed in the * meta data. As a best practice, a Partitioning should name the fields in the order of how frequently they are * used in partition filters, because partition filters that contain a condition for the first field in the * Partitioning perform best. */ public class Partitioning { /** * Describes the type of a partitioning field. */ public enum FieldType { STRING { @Override public String parse(String value) { return value; } }, LONG { @Override public Long parse(String value) { return Long.parseLong(value); } }, INT { @Override public Integer parse(String value) { return Integer.parseInt(value); } }; /** * Parse a string into a value of this field type. For example, {@link FieldType#INT} delegates this * to {@link Integer#parseInt}. * @param value the string to parse */ public abstract Comparable parse(String value); } private final Map<String, FieldType> fields; /** * Private constructor to force the use of the builder. */ private Partitioning(LinkedHashMap<String, FieldType> fields) { this.fields = Collections.unmodifiableMap(new LinkedHashMap<>(fields)); } /** * @return the type of a field, or null if that field is not declared for the partitioning */ public FieldType getFieldType(String fieldName) { return fields.get(fieldName); } /** * This returns a map associating all the fields of this partitioning with their respective types. Iterators * over the key set or the entry set of this map will yield the same order in which the fields were added to * the partitioning. * * @return all fields and their types */ public Map<String, FieldType> getFields() { return fields; } /** * @return a builder for a partitioning */ public static Builder builder() { return new Builder(); } /** * A builder for partitioning objects. */ public static class Builder { private final LinkedHashMap<String, FieldType> fields = new LinkedHashMap<>(); private Builder() { } /** * Add a field with a given name and type. * * @param name the field name * @param type the type of the field * * @throws java.lang.IllegalArgumentException if the field name is null, empty, or already exists, * or if the type is null. */ public Builder addField(@Nonnull String name, @Nonnull FieldType type) { if (name == null || name.isEmpty()) { throw new IllegalArgumentException("Field name cannot be null or empty."); } if (type == null) { throw new IllegalArgumentException("Field type cannot be null."); } if (fields.containsKey(name)) { throw new IllegalArgumentException(String.format("Field '%s' already exists in partitioning.", name)); } fields.put(name, type); return this; } /** * Add field of type STRING. * * @param name the field name * * @throws java.lang.IllegalArgumentException if the field name is null, empty, or already exists. */ public Builder addStringField(String name) { return addField(name, FieldType.STRING); } /** * Add field of type INT. * * @param name the field name * * @throws java.lang.IllegalArgumentException if the field name is null, empty, or already exists. */ public Builder addIntField(String name) { return addField(name, FieldType.INT); } /** * Add field of type LONG. * * @param name the field name * * @throws java.lang.IllegalArgumentException if the field name is null, empty, or already exists. */ public Builder addLongField(String name) { return addField(name, FieldType.LONG); } /** * Create the partitioning. * * @throws java.lang.IllegalStateException if no fields have been added */ public Partitioning build() { if (fields.isEmpty()) { throw new IllegalStateException("Partitioning cannot be empty."); } return new Partitioning(fields); } } }
{'content_hash': '9d6481e01324420b5ce02e68aff46451', 'timestamp': '', 'source': 'github', 'line_count': 162, 'max_line_length': 113, 'avg_line_length': 28.19753086419753, 'alnum_prop': 0.6492994746059545, 'repo_name': 'mpouttuclarke/cdap', 'id': '675b47c7a9fba8e57f6e79d914e00cc79d4b0734', 'size': '5165', 'binary': False, 'copies': '4', 'ref': 'refs/heads/develop', 'path': 'cdap-api/src/main/java/co/cask/cdap/api/dataset/lib/Partitioning.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '13173'}, {'name': 'CSS', 'bytes': '206745'}, {'name': 'HTML', 'bytes': '436495'}, {'name': 'Java', 'bytes': '16032874'}, {'name': 'JavaScript', 'bytes': '1119446'}, {'name': 'Python', 'bytes': '90731'}, {'name': 'Scala', 'bytes': '30287'}, {'name': 'Shell', 'bytes': '177663'}]}
@interface SettingsViewController () @end @implementation SettingsViewController @synthesize tbl; - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { [super viewDidLoad]; self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"menuIcon.png"] style:UIBarButtonItemStyleBordered target:self action:@selector(showMenu)]; self.title = @"Settings"; self.tbl.backgroundView = nil; self.tbl.backgroundColor = [UIColor colorWithRed:225.0/255.0 green:225.0/255.0 blue:220.0/255.0 alpha:1.0]; } - (void) viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; self.visibleTag = SETTINGS_TAG; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (UIView *)tableView:(UITableView *)tv viewForFooterInSection:(NSInteger)section { switch (section) { case 0:{ return nil; } case 1:{ UIView* footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tbl.frame.size.width, 100)]; footerView.backgroundColor = [UIColor clearColor]; [footerView setClipsToBounds:NO]; [footerView setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin]; UILabel* cacheLabel = [[UILabel alloc] initWithFrame:CGRectMake (20, 10, footerView.frame.size.width-30, 30)]; cacheLabel.font = [UIFont fontWithName:@"HelveticaNeue" size:18.0]; [cacheLabel setBackgroundColor:[UIColor clearColor]]; [cacheLabel setShadowColor:[UIColor colorWithWhite:1 alpha:.75]]; [cacheLabel setText:@"Days to keep stories:"]; [footerView addSubview:cacheLabel]; NSArray* cacheDays = [NSArray arrayWithObjects: @"1", @"2", @"3", @"4", @"5", nil]; UISegmentedControl* cacheControl = [[UISegmentedControl alloc] initWithItems:cacheDays]; cacheControl.tintColor = [UIColor blackColor]; [cacheControl addTarget:self action:@selector(cacheSelection:) forControlEvents:UIControlEventValueChanged]; cacheControl.frame = CGRectMake(10, 44, self.tbl.frame.size.width-20, 47); [cacheControl setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin]; cacheControl.selectedSegmentIndex = [[PreferencesManager sharedPreferencesManager] storyLifetime]-1; [footerView addSubview:cacheControl]; return footerView; } } return nil; } - (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section { // hackity hackity hackity switch (section) { case 0: return 0; break; case 1: return 100; break; } return 0; } #pragma mark - UITableViewDataSource methods -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"]; UISwitch *switchview = [[UISwitch alloc] initWithFrame:CGRectZero]; [switchview setOnTintColor: [UIColor blackColor]]; cell.textLabel.font = [UIFont fontWithName:@"HelveticaNeue" size:18.0]; if(indexPath.section == 0){ switch (indexPath.row) { case 0: cell.textLabel.text = @"Hacker News"; [switchview setOn:[[PreferencesManager sharedPreferencesManager] requiresHackerNews]]; [switchview addTarget:self action:@selector(toggleRequiresHackerNews:) forControlEvents:UIControlEventValueChanged]; break; case 1: cell.textLabel.text = @"Reddit Programming"; [switchview setOn:[[PreferencesManager sharedPreferencesManager] requiresProggit]]; [switchview addTarget:self action:@selector(toggleRequiresProggit:) forControlEvents:UIControlEventValueChanged]; break; default: break; } } else { // it's 1 switch (indexPath.row) { case 0: cell.textLabel.text = @"Sounds"; [switchview setOn:[[PreferencesManager sharedPreferencesManager] requiresSound]]; [switchview addTarget:self action:@selector(toggleRequiresSound:) forControlEvents:UIControlEventValueChanged]; break; default: break; } } cell.accessoryView = switchview; return cell; } -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { switch (section) { case 0: return 2; case 1: return 1; default: return 0; } } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 2; } # pragma mark - control responders - (void) toggleRequiresHackerNews:(id)sender { [[PreferencesManager sharedPreferencesManager] setRequiresHackerNews:[sender isOn]]; [[SoundManager sharedSoundManager] playSoundWithName:@"oneClick" andExtension:@"wav"]; } - (void) toggleRequiresProggit:(id)sender { [[PreferencesManager sharedPreferencesManager] setRequiresProggit:[sender isOn]]; [[SoundManager sharedSoundManager] playSoundWithName:@"oneClick" andExtension:@"wav"]; } - (void) toggleRequiresSound:(id)sender { [[PreferencesManager sharedPreferencesManager] setRequiresSound:[sender isOn]]; [[SoundManager sharedSoundManager] playSoundWithName:@"oneClick" andExtension:@"wav"]; } - (void) cacheSelection:(id)sender { [[SoundManager sharedSoundManager] playSoundWithName:@"oneClick" andExtension:@"wav"]; [[PreferencesManager sharedPreferencesManager] setStoryLifetime:[sender selectedSegmentIndex]+1]; } @end
{'content_hash': '6a2e6afffdcdcb8c2830cef8f778aecb', 'timestamp': '', 'source': 'github', 'line_count': 162, 'max_line_length': 192, 'avg_line_length': 37.98148148148148, 'alnum_prop': 0.6660165772793759, 'repo_name': 'hodgesmr/CoderNews', 'id': 'acaf5565fbcd0ba5b7b1c009803e4562031d4be5', 'size': '7500', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'CoderNews/View Controllers/SettingsViewController.m', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Objective-C', 'bytes': '395304'}]}
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:os-core="http://www.openspaces.org/schema/core" xmlns:os-events="http://www.openspaces.org/schema/events" xmlns:context="http://www.springframework.org/schema/context" xmlns:os-remoting="http://www.openspaces.org/schema/remoting" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.openspaces.org/schema/core http://www.openspaces.org/schema/12.0/core/openspaces-core.xsd http://www.openspaces.org/schema/events http://www.openspaces.org/schema/12.0/events/openspaces-events.xsd http://www.openspaces.org/schema/remoting http://www.openspaces.org/schema/12.0/remoting/openspaces-remoting.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"> <!-- Spring property configurer which allows us to use system properties (such as user.name). --> <bean id="propertiesConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"/> <context:component-scan base-package="com.gigaspaces.app.event_processing.processor" /> <!-- Enables to configure Spring beans through annotations --> <context:annotation-config /> <!-- Enable @PostPrimary and others annotation support. --> <os-core:annotation-support /> <!-- Enables using @Polling and @Notify annotations to creating polling and notify containers --> <os-events:annotation-support /> <!-- Enables using @RemotingService and other remoting related annotations --> <os-remoting:annotation-support /> <!-- Enables the usage of @GigaSpaceContext annotation based injection. --> <os-core:giga-space-late-context/> <!-- A bean representing a space (an IJSpace implementation). Note, we do not specify here the cluster topology of the space. It is declated outside of the processing unit or within the SLA bean. --> <os-core:space id="space" url="/./myGrid" /> <os-core:space id="spaceForLocalView" url="jini://*/*/myGrid" /> <!-- Defines a distributed transaction manager. --> <os-core:distributed-tx-manager id="transactionManager"/> <!-- OpenSpaces simplified space API built on top of IJSpace/JavaSpace. --> <os-core:giga-space id="gigaSpace" space="space" tx-manager="transactionManager"/> <!-- The data processor bean --> <bean id="dataProcessor" class="com.gigaspaces.app.event_processing.processor.Processor"/> <!-- A polling event container that performs (by default) polling take operations against the space using the provided template (in our case, and the non processed data objects). Once a match is found, the data processor bean event listener is triggered using the annotation adapter. --> <!--<os-events:polling-container id="dataProcessorPollingEventContainer" giga-space="gigaSpace">--> <!--<os-events:tx-support tx-manager="transactionManager"/>--> <!--<os-core:template>--> <!--<bean class="com.gigaspaces.app.event_processing.common.Data">--> <!--<property name="processed" value="false"/>--> <!--</bean>--> <!--</os-core:template>--> <!--<os-events:listener>--> <!--<os-events:annotation-adapter>--> <!--<os-events:delegate ref="dataProcessor"/>--> <!--</os-events:annotation-adapter>--> <!--</os-events:listener>--> <!--</os-events:polling-container>--> <!--<bean id="viewSpace" class="org.openspaces.core.space.cache.LocalViewSpaceFactoryBean">--> <!--<property name="space" ref="space" />--> <!--<property name="localViews">--> <!--<list>--> <!--<bean class="com.j_spaces.core.client.view.View">--> <!--<constructor-arg index="0" value="com.gigaspaces.app.event_processing.common.Data" />--> <!--<constructor-arg index="1" value="status != EStatus.Four" />--> <!--</bean>--> <!--</list>--> <!--</property>--> <!--</bean>--> <os-core:local-view id="localViewSpace" space="spaceForLocalView"> <os-core:view-query class="com.gigaspaces.app.event_processing.common.Data" where="status != 'Four'"/> </os-core:local-view> <os-core:giga-space id="localView" space="localViewSpace"/> </beans>
{'content_hash': '82d9ad6693695ab944fb3d248f22470c', 'timestamp': '', 'source': 'github', 'line_count': 102, 'max_line_length': 135, 'avg_line_length': 45.86274509803921, 'alnum_prop': 0.6408721675929885, 'repo_name': 'GigaSpaces-POCs/payment-processing', 'id': '64d2e3706a989c33d57b928777bbe094bdcb8d98', 'size': '4678', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'processor/src/main/resources/META-INF/spring/pu.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '25398'}]}
{-# LANGUAGE OverloadedStrings, TupleSections #-} module Process where import Control.Applicative import Control.Arrow import Control.Monad ((>=>), join) import Data.ByteString (ByteString) import Data.Foldable (forM_) import Data.Function import Data.HashMap.Strict (lookup, toList) import Data.Maybe import Data.Monoid import Data.String import Data.String.Conversions import Data.Traversable (sequenceA) import Data.Text (Text) import Data.Time.Clock (UTCTime, addUTCTime) import Data.Time.Clock.POSIX (posixSecondsToUTCTime) import Data.Time.Format (formatTime) import GHC.IO.Exception (ExitCode(..)) import Network.Mail.Mime import Pipes import qualified Pipes.Prelude as P import Prelude hiding (lookup) import Systemd.Journal import System.Locale (defaultTimeLocale) import System.Process (readProcessWithExitCode) import Text.Read (readMaybe) import Options process :: (Applicative m, Monad m) => Configuration String -> GetsJournal m -> Pipe JournalFields Mail m () process options jget = P.map extractPriority >-> pCatMaybes >-> P.filter (isSevere . fst) >-> P.mapM (snd >>> mkMail options jget) -- * journal stuff extractPriority :: JournalFields -> Maybe (Priority, JournalFields) extractPriority fields = do p <- lookup "PRIORITY" fields (, fields) <$> parsePriority p parsePriority :: ByteString -> Maybe Priority parsePriority = readMaybe . cs >=> toEnumMaybe isSevere :: Priority -> Bool isSevere p = fromEnum p <= fromEnum Error type GetsJournal m = MessageSource -> UTCTime -- start time -> UTCTime -- end time -> m (Maybe String) -- | Attempt to get information about context around an entry mkContextInfo :: (Applicative m, Monad m) => Configuration a -> JournalFields -> GetsJournal m -> m (Maybe String) mkContextInfo cfg fields gj = join <$> sequenceA (gj source <$> from <*> until) where source = getMessageSource fields until = utcTime fields from = addUTCTime <$> fmap (negate . fromInteger) (contextInterval cfg) <*> until -- JOURNALCTL(1): -- -- --since=, --until= -- Start showing entries on or newer than the specified date, or on or -- older than the specified date, respectively. Date specifications -- should be of the format "2012-10-30 18:17:16". -- formatUTCTimeForJournalCtl :: UTCTime -> String formatUTCTimeForJournalCtl = formatTime defaultTimeLocale "%F %T" ioJournal :: MonadIO m => GetsJournal m ioJournal (Unit source) start end = do let args = [ "-u", source , "--since=" ++ formatUTCTimeForJournalCtl start , "--until=" ++ formatUTCTimeForJournalCtl end , "--no-pager" ] output <- liftIO $ readProcessWithExitCode "journalctl" args "" return $ case output of (ExitSuccess, stdout, _) -> Just stdout _ -> Nothing ioJournal _ _ _ = return Nothing -- * mail stuff excludeFields :: [JournalField] excludeFields = [ "COREDUMP" ] mkMail :: (Applicative m, Monad m) => Configuration String -> GetsJournal m -> JournalFields -> m Mail mkMail options jget fields = do ctx <- mkContextInfo options fields jget let cts = fromMaybe "<no context available>" ctx return (addPart [plainPart $ cs (date ++ pretty fields ++ "\n" ++ cts)] $ mailFromToSubject (addr (sender options)) (map addr mailReceivers) subject) where messageSource = getMessageSource fields mailReceivers = lookupReceivers (messageSourceName messageSource) options date = "On " <> maybe "<unknown date>" show (utcTime fields) <> ":\n\n" subject = "error message on " <> host fields <> ": " <> showMessageSource messageSource <> outcome fields addr :: String -> Address addr = Address Nothing . cs pretty :: JournalFields -> String pretty = toList >>> filter (\(k,_) -> notElem k excludeFields) >>> map (\ (key, value) -> prettyJournalField key ++ " = " ++ cs value) >>> unlines mailFromToSubject :: Address -> [Address] -> Text -> Mail mailFromToSubject from to subject = (emptyMail from){ mailTo = to, mailHeaders = [("Subject", subject)] } host :: JournalFields -> Text host = maybe "<unknown host>" cs . lookup "_HOSTNAME" utcTime :: JournalFields -> Maybe UTCTime utcTime jf = do let toSec y = y `div` 10 ^ (6::Int) msrt <- lookup "_SOURCE_REALTIME_TIMESTAMP" jf micros <- readMaybe $ cs msrt return . posixSecondsToUTCTime . fromInteger . toSec $ micros data MessageSource = Unit String | UnknownType String | UnknownSource messageSourceName :: MessageSource -> Maybe String messageSourceName (Unit name) = Just name messageSourceName (UnknownType name) = Just name messageSourceName UnknownSource = Nothing showMessageSource :: MessageSource -> Text showMessageSource (Unit name) = "systemd unit " <> cs (addQuotes name) showMessageSource (UnknownType name) = cs name showMessageSource UnknownSource = "<unknown message source>" getMessageSource :: JournalFields -> MessageSource getMessageSource fields = fromMaybe UnknownSource ((Unit . cs <$> lookup "_SYSTEMD_UNIT" fields) <|> (Unit . cs <$> lookup "UNIT" fields) <|> (UnknownType . cs <$> lookup "SYSLOG_IDENTIFIER" fields) <|> (UnknownType . cs <$> lookup "_COMM" fields)) -- | combines RESULT and MESSAGE (if they exist) outcome :: JournalFields -> Text outcome fields = cs $ case (lookup "RESULT" fields, lookup "MESSAGE" fields) of (Just result, Just message) -> ": " <> result <> ": " <> message (Just result, Nothing) -> ": " <> result (Nothing, Just message) -> ": " <> message (Nothing, Nothing) -> "" prettyJournalField :: JournalField -> String prettyJournalField = show >>> drop (length ("JournalField " :: String)) >>> read -- * utils pCatMaybes :: Monad m => Pipe (Maybe a) a m () pCatMaybes = do mx <- await forM_ mx yield pCatMaybes toEnumMaybe :: (Enum a, Bounded a) => Int -> Maybe a toEnumMaybe n | n >= minBound && n <= maxBound = Just $ toEnum n | otherwise = Nothing addQuotes :: (IsString a, Monoid a) => a -> a addQuotes t = "\"" <> t <> "\""
{'content_hash': '6b86a35aa1ba5554c8cdbcedc2c16949', 'timestamp': '', 'source': 'github', 'line_count': 198, 'max_line_length': 108, 'avg_line_length': 34.31818181818182, 'alnum_prop': 0.6100073583517293, 'repo_name': 'zalora/journal-mailer', 'id': '4ce63afbb9c0a37f4cde7fe538c0b11cae92bf1c', 'size': '6795', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Process.hs', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Haskell', 'bytes': '26174'}, {'name': 'Nix', 'bytes': '280'}]}
"""Settings for the zinnia-theme-html5 demo""" import os gettext = lambda s: s DEBUG = True TEMPLATE_DEBUG = DEBUG DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(os.path.dirname(__file__), 'demo.db')} } TIME_ZONE = 'Europe/Paris' STATIC_URL = '/static/' MEDIA_URL = '/media/' SECRET_KEY = 'jo-1rzm(%sf)3#n+fb7h945yuv3(pt63abhi12_t7e^^5q8dyw' USE_TZ = True USE_I18N = True USE_L10N = True SITE_ID = 1 LANGUAGE_CODE = 'en' LANGUAGES = ( ('en', gettext('English')), ('fr', gettext('French')), ('de', gettext('German')), ('es', gettext('Spanish')), ('it', gettext('Italian')), ('nl', gettext('Dutch')), ('sl', gettext('Slovenian')), ('bg', gettext('Bulgarian')), ('hu', gettext('Hungarian')), ('cs', gettext('Czech')), ('sk', gettext('Slovak')), ('lt', gettext('Lithuanian')), ('ru', gettext('Russian')), ('pl', gettext('Polish')), ('eu', gettext('Basque')), ('he', gettext('Hebrew')), ('ca', gettext('Catalan')), ('tr', gettext('Turkish')), ('sv', gettext('Swedish')), ('hr_HR', gettext('Croatian')), ('pt_BR', gettext('Brazilian Portuguese')), ('fi_FI', gettext('Finnish (Finland)')), ('zh_CN', gettext('Simplified Chinese')), ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.admindocs.middleware.XViewMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'zinnia_html5.middleware.DraftHTML5ValidatorCleaner', ) ROOT_URLCONF = 'demo_zinnia_html5.urls' TEMPLATE_LOADERS = ( 'app_namespace.Loader', 'django.template.loaders.app_directories.Loader' ) TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.i18n', 'django.core.context_processors.request', 'django.contrib.messages.context_processors.messages', 'zinnia.context_processors.version', ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.sitemaps', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sites', 'django.contrib.admin', 'django.contrib.admindocs', 'django.contrib.staticfiles', 'django_comments', 'mptt', 'tagging', 'zinnia_html5', 'zinnia', ) SILENCED_SYSTEM_CHECKS = ['1_6.W001']
{'content_hash': '4dd9c0c225e74d9be993e065c522f13a', 'timestamp': '', 'source': 'github', 'line_count': 99, 'max_line_length': 73, 'avg_line_length': 26.515151515151516, 'alnum_prop': 0.6384761904761905, 'repo_name': 'django-blog-zinnia/zinnia-theme-html5', 'id': 'ff0892881d68e261c75b4424bee8a90e7b973db3', 'size': '2625', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'demo_zinnia_html5/settings.py', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Python', 'bytes': '13277'}]}
import config from "../" import stylelint from "stylelint" import test from "ava" const validCss = ( ` a { top: .2em; } `) const invalidCss = ( `a { top: 0.2em; } `) test("no warnings with valid css", t => { return stylelint.lint({ code: validCss, config: config, }) .then(data => { const { errored, results } = data const { warnings } = results[0] t.notOk(errored, "no errored") t.is(warnings.length, 0, "flags no warnings") }) }) test("a warning with invalid css", t => { return stylelint.lint({ code: invalidCss, config: config, }) .then(data => { const { errored, results } = data const { warnings } = results[0] t.ok(errored, "errored") t.is(warnings.length, 1, "flags one warning") t.is(warnings[0].text, "Unexpected leading zero (number-leading-zero)", "correct warning text") }) })
{'content_hash': '38f70e2577418d560a7e29b50cf561e2', 'timestamp': '', 'source': 'github', 'line_count': 44, 'max_line_length': 99, 'avg_line_length': 19.704545454545453, 'alnum_prop': 0.6078431372549019, 'repo_name': 'cssrecipes/stylelint-config-cssrecipes', 'id': 'eea97e8aaa201fc2299e6c8db49c539849c35604', 'size': '867', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': '__tests__/index.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '3909'}]}
package at.ac.tuwien.infosys.wadl2java.codegen; import java.io.FileNotFoundException; import java.util.List; import org.junit.Test; import at.ac.tuwien.infosys.BaseTest; import at.ac.tuwien.infosys.java2wadl.WadlException; import at.ac.tuwien.infosys.java2wadl.wadl.IApplication; import at.ac.tuwien.infosys.java2wadl.wadl.IMethod; import at.ac.tuwien.infosys.java2wadl.wadl.IMethodDefinition; import at.ac.tuwien.infosys.java2wadl.wadl.IMethodReference; import at.ac.tuwien.infosys.java2wadl.wadl.IResource; import at.ac.tuwien.infosys.wadl2java.xml.ApplicationParser; public class MethodResolverTest extends BaseTest { @Test public void testResolveMethod() throws FileNotFoundException, WadlException { String xml = loadResource("at.ac.tuwien.infosys.wadl2java.codegen.MethodResolverTestCase.txt"); IApplication application = new ApplicationParser().parse(xml); List<IResource> resources = application.getResources().getResources(); assertEquals(1, resources.size()); IResource resource = resources.get(0); List<IMethod> methods = resource.getMethods(); assertEquals(1, methods.size()); IMethod method = methods.get(0); IMethodDefinition methodDefinition = (IMethodDefinition) application.getMethods().get(0); assertTrue(method instanceof IMethodReference); assertNotNull(methodDefinition); assertEquals(methodDefinition, new MethodResolver().resolve(application, method)); } @Test public void testResolveUnresolvableMethodAndFail() throws FileNotFoundException, WadlException { String xml = loadResource("at.ac.tuwien.infosys.wadl2java.codegen.MethodResolverTestCase2.txt"); IApplication application = new ApplicationParser().parse(xml); List<IResource> resources = application.getResources().getResources(); assertEquals(1, resources.size()); IResource resource = resources.get(0); List<IMethod> methods = resource.getMethods(); assertEquals(1, methods.size()); IMethod method = methods.get(0); try { new MethodResolver().resolve(application, method); fail(); } catch (WadlException e) { assertEquals(e.getMessage(), "Unable to resolve method-reference for: #HelloWorldResource_getMessage_"); } } }
{'content_hash': 'ccffe2e21108a4696669e5da2c7959ce', 'timestamp': '', 'source': 'github', 'line_count': 57, 'max_line_length': 107, 'avg_line_length': 38.19298245614035, 'alnum_prop': 0.7827285254937988, 'repo_name': 'ameingast/java2wadl', 'id': 'ed61beebf5b8718c25f32483ac6b5f67de8ee1f3', 'size': '2177', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/test/java/at/ac/tuwien/infosys/wadl2java/codegen/MethodResolverTest.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Java', 'bytes': '221058'}, {'name': 'TeX', 'bytes': '57447'}]}
/* 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. */ package org.flowable.engine.test.bpmn.deployment; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.ArrayList; import java.util.List; import org.flowable.common.engine.impl.history.HistoryLevel; import org.flowable.engine.impl.test.HistoryTestHelper; import org.flowable.engine.impl.test.PluggableFlowableTestCase; import org.flowable.engine.runtime.EventSubscription; import org.flowable.engine.runtime.ProcessInstance; import org.junit.jupiter.api.Test; /** * A test specifically written to test how events (start/boundary) are handled when deploying a new version of a process definition. * * @author Joram Barrez */ public class MessageEventsAndNewVersionDeploymentsTest extends PluggableFlowableTestCase { private static final String TEST_PROCESS_GLOBAL_BOUNDARY_MESSAGE = "org/flowable/engine/test/bpmn/deployment/MessageEventsAndNewVersionDeploymentsTest.testGlobalMessageBoundaryEvent.bpmn20.xml"; private static final String TEST_PROCESS_START_MESSAGE = "org/flowable/engine/test/bpmn/deployment/MessageEventsAndNewVersionDeploymentsTest.testStartMessageEvent.bpmn20.xml"; private static final String TEST_PROCESS_NO_EVENTS = "org/flowable/engine/test/bpmn/deployment/MessageEventsAndNewVersionDeploymentsTest.processWithoutEvents.bpmn20.xml"; private static final String TEST_PROCESS_BOTH_START_AND_BOUNDARY_MESSAGE = "org/flowable/engine/test/bpmn/deployment/MessageEventsAndNewVersionDeploymentsTest.testBothBoundaryAndStartMessage.bpmn20.xml"; private static final String TEST_PROCESS_BOTH_START_AND_BOUNDARY_MESSAGE_SAME_MESSAGE = "org/flowable/engine/test/bpmn/deployment/MessageEventsAndNewVersionDeploymentsTest.testBothBoundaryAndStartMessageSameMessage.bpmn20.xml"; /* * BOUNDARY MESSAGE EVENT */ @Test public void testMessageBoundaryEvent() { String deploymentId1 = deployBoundaryMessageTestProcess(); runtimeService.startProcessInstanceByKey("messageTest"); assertEquals(1, getAllEventSubscriptions().size()); String deploymentId2 = deployBoundaryMessageTestProcess(); runtimeService.startProcessInstanceByKey("messageTest"); assertEquals(2, getAllEventSubscriptions().size()); assertReceiveMessage("myMessage", 2); List<org.flowable.task.api.Task> tasks = taskService.createTaskQuery().list(); assertEquals(2, tasks.size()); for (org.flowable.task.api.Task task : tasks) { assertEquals("Task after message", task.getName()); } cleanup(deploymentId1, deploymentId2); } /** * Verifying that the event subscriptions do get removed when removing a deployment. */ @Test public void testBoundaryEventSubscriptionDeletedOnDeploymentDelete() { String deploymentId = deployBoundaryMessageTestProcess(); runtimeService.startProcessInstanceByKey("messageTest"); assertEquals("My Task", taskService.createTaskQuery().singleResult().getName()); String deploymentId2 = deployBoundaryMessageTestProcess(); runtimeService.startProcessInstanceByKey("messageTest"); assertEquals(2, taskService.createTaskQuery().count()); assertEquals(2, getAllEventSubscriptions().size()); repositoryService.deleteDeployment(deploymentId, true); assertEquals("My Task", taskService.createTaskQuery().singleResult().getName()); assertEquals(1, getAllEventSubscriptions().size()); repositoryService.deleteDeployment(deploymentId2, true); assertEquals(0, getAllEventSubscriptions().size()); } /** * Verifying that the event subscriptions do get removed when removing a process instance. */ @Test public void testBoundaryEventSubscriptionsDeletedOnProcessInstanceDelete() { String deploymentId1 = deployBoundaryMessageTestProcess(); runtimeService.startProcessInstanceByKey("messageTest"); assertEquals("My Task", taskService.createTaskQuery().singleResult().getName()); String deploymentId2 = deployBoundaryMessageTestProcess(); ProcessInstance processInstance2 = runtimeService.startProcessInstanceByKey("messageTest"); assertEquals(2, taskService.createTaskQuery().count()); assertEquals(2, getAllEventSubscriptions().size()); // Deleting PI of second deployment runtimeService.deleteProcessInstance(processInstance2.getId(), "testing"); assertEquals("My Task", taskService.createTaskQuery().singleResult().getName()); assertEquals(1, getAllEventSubscriptions().size()); runtimeService.messageEventReceived("myMessage", getExecutionIdsForMessageEventSubscription("myMessage").get(0)); assertEquals(0, getAllEventSubscriptions().size()); assertEquals("Task after message", taskService.createTaskQuery().singleResult().getName()); cleanup(deploymentId1, deploymentId2); } /* * START MESSAGE EVENT */ @Test public void testStartMessageEvent() { String deploymentId1 = deployStartMessageTestProcess(); assertEquals(1, getAllEventSubscriptions().size()); assertEventSubscriptionsCount(1); assertEquals(0, runtimeService.createProcessInstanceQuery().count()); runtimeService.startProcessInstanceByMessage("myStartMessage"); assertEquals(1, runtimeService.createProcessInstanceQuery().count()); String deploymentId2 = deployStartMessageTestProcess(); assertEventSubscriptionsCount(1); runtimeService.startProcessInstanceByMessage("myStartMessage"); assertEquals(2, runtimeService.createProcessInstanceQuery().count()); assertEventSubscriptionsCount(1); cleanup(deploymentId1, deploymentId2); } @Test public void testMessageStartEventSubscriptionAfterDeploymentDelete() { // Deploy two version of process definition, delete latest and check if all is good String deploymentId1 = deployStartMessageTestProcess(); List<EventSubscription> eventSubscriptions = getAllEventSubscriptions(); assertEquals(1, eventSubscriptions.size()); String deploymentId2 = deployStartMessageTestProcess(); eventSubscriptions = getAllEventSubscriptions(); assertEventSubscriptionsCount(1); repositoryService.deleteDeployment(deploymentId2, true); eventSubscriptions = getAllEventSubscriptions(); assertEquals(1, eventSubscriptions.size()); cleanup(deploymentId1); assertEquals(0, getAllEventSubscriptions().size()); // Deploy two versions of process definition, delete the first deploymentId1 = deployStartMessageTestProcess(); deploymentId2 = deployStartMessageTestProcess(); assertEquals(1, getAllEventSubscriptions().size()); repositoryService.deleteDeployment(deploymentId1, true); eventSubscriptions = getAllEventSubscriptions(); assertEquals(1, eventSubscriptions.size()); assertEquals(repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId2).singleResult().getId(), eventSubscriptions.get(0).getProcessDefinitionId()); cleanup(deploymentId2); assertEquals(0, getAllEventSubscriptions().size()); } /** * v1 -> has start message event v2 -> has no start message event v3 -> has start message event */ @Test public void testDeployIntermediateVersionWithoutMessageStartEvent() { String deploymentId1 = deployStartMessageTestProcess(); assertEquals(1, getAllEventSubscriptions().size()); assertEquals(0, runtimeService.createProcessInstanceQuery().count()); runtimeService.startProcessInstanceByMessage("myStartMessage"); assertEquals(1, runtimeService.createProcessInstanceQuery().count()); assertEventSubscriptionsCount(1); String deploymentId2 = deployProcessWithoutEvents(); assertEquals(0, getAllEventSubscriptions().size()); assertEquals(1, runtimeService.createProcessInstanceQuery().count()); assertThatThrownBy(() -> runtimeService.startProcessInstanceByMessage("myStartMessage")); assertEquals(1, runtimeService.createProcessInstanceQuery().count()); assertEventSubscriptionsCount(0); String deploymentId3 = deployStartMessageTestProcess(); assertEquals(1, getAllEventSubscriptions().size()); assertEquals(1, runtimeService.createProcessInstanceQuery().count()); runtimeService.startProcessInstanceByMessage("myStartMessage"); assertEquals(2, runtimeService.createProcessInstanceQuery().count()); assertEventSubscriptionsCount(1); List<EventSubscription> eventSubscriptions = getAllEventSubscriptions(); assertEquals(repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId3).singleResult().getId(), eventSubscriptions.get(0).getProcessDefinitionId()); cleanup(deploymentId1, deploymentId2, deploymentId3); } @Test public void testDeleteDeploymentWithStartMessageEvents1() { String deploymentId1; String deploymentId2; String deploymentId3; deploymentId1 = deployStartMessageTestProcess(); deploymentId2 = deployProcessWithoutEvents(); deploymentId3 = deployStartMessageTestProcess(); repositoryService.deleteDeployment(deploymentId3, true); assertEventSubscriptionsCount(0); // the latest is now the one without a message start cleanup(deploymentId1, deploymentId2); } @Test public void testDeleteDeploymentWithStartMessageEvents2() { String deploymentId1 = deployStartMessageTestProcess(); String deploymentId2 = deployProcessWithoutEvents(); String deploymentId3 = deployStartMessageTestProcess(); repositoryService.deleteDeployment(deploymentId2, true); assertEventSubscriptionsCount(1); // the latest is now the one with the message runtimeService.startProcessInstanceByMessage("myStartMessage"); assertEquals(repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId3).singleResult().getId(), runtimeService.createProcessInstanceQuery().singleResult().getProcessDefinitionId()); cleanup(deploymentId1, deploymentId3); } @Test public void testDeleteDeploymentWithStartMessageEvents3() { String deploymentId1 = deployStartMessageTestProcess(); String deploymentId2 = deployProcessWithoutEvents(); String deploymentId3 = deployStartMessageTestProcess(); repositoryService.deleteDeployment(deploymentId1, true); assertEventSubscriptionsCount(1); // the latest is now the one with the message runtimeService.startProcessInstanceByMessage("myStartMessage"); assertEquals(repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId3).singleResult().getId(), runtimeService.createProcessInstanceQuery().singleResult().getProcessDefinitionId()); cleanup(deploymentId2, deploymentId3); } @Test public void testDeleteDeploymentWithStartMessageEvents4() { String deploymentId1 = deployStartMessageTestProcess(); String deploymentId2 = deployProcessWithoutEvents(); String deploymentId3 = deployStartMessageTestProcess(); repositoryService.deleteDeployment(deploymentId2, true); repositoryService.deleteDeployment(deploymentId3, true); assertEventSubscriptionsCount(1); // the latest is now the one with the message start runtimeService.startProcessInstanceByMessage("myStartMessage"); assertEquals(repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId1).singleResult().getId(), runtimeService.createProcessInstanceQuery().singleResult().getProcessDefinitionId()); cleanup(deploymentId1); } @Test public void testDeleteDeploymentWithStartMessageEvents5() { String deploymentId1 = deployStartMessageTestProcess(); String deploymentId2 = deployProcessWithoutEvents(); assertEventSubscriptionsCount(0); assertThatThrownBy(() -> runtimeService.startProcessInstanceByMessage("myStartMessage")); assertEquals(0, runtimeService.createExecutionQuery().count()); repositoryService.deleteDeployment(deploymentId2, true); assertEventSubscriptionsCount(1); // the first is now the one with the signal runtimeService.startProcessInstanceByMessage("myStartMessage"); assertEquals(repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId1).singleResult().getId(), runtimeService.createProcessInstanceQuery().singleResult().getProcessDefinitionId()); cleanup(deploymentId1); } @Test public void testDeleteDeploymentWithStartMessageEvents6() { String deploymentId1 = deployStartMessageTestProcess(); String deploymentId2 = deployProcessWithoutEvents(); String deploymentId3 = deployStartMessageTestProcess(); String deploymentId4 = deployProcessWithoutEvents(); assertThatThrownBy(() -> runtimeService.startProcessInstanceByMessage("myStartMessage")); assertEquals(0, runtimeService.createExecutionQuery().count()); repositoryService.deleteDeployment(deploymentId2, true); repositoryService.deleteDeployment(deploymentId3, true); assertThatThrownBy(() -> runtimeService.startProcessInstanceByMessage("myStartMessage")); assertEquals(0, runtimeService.createExecutionQuery().count()); repositoryService.deleteDeployment(deploymentId1, true); assertThatThrownBy(() -> runtimeService.startProcessInstanceByMessage("myStartMessage")); assertEquals(0, runtimeService.createExecutionQuery().count()); cleanup(deploymentId4); } @Test public void testDeleteDeploymentWithStartMessageEvents7() { String deploymentId1 = deployStartMessageTestProcess(); String deploymentId2 = deployProcessWithoutEvents(); String deploymentId3 = deployStartMessageTestProcess(); String deploymentId4 = deployProcessWithoutEvents(); assertThatThrownBy(() -> runtimeService.startProcessInstanceByMessage("myStartMessage")); assertEquals(0, runtimeService.createExecutionQuery().count()); repositoryService.deleteDeployment(deploymentId2, true); repositoryService.deleteDeployment(deploymentId3, true); assertThatThrownBy(() -> runtimeService.startProcessInstanceByMessage("myStartMessage")); assertEquals(0, runtimeService.createExecutionQuery().count()); repositoryService.deleteDeployment(deploymentId4, true); runtimeService.startProcessInstanceByMessage("myStartMessage"); assertEquals(1, runtimeService.createProcessInstanceQuery().count()); cleanup(deploymentId1); } /* * BOTH BOUNDARY AND START MESSAGE */ @Test public void testBothBoundaryAndStartEvent() { // Deploy process with both boundary and start event String deploymentId1 = deployProcessWithBothStartAndBoundaryMessage(); assertEventSubscriptionsCount(1); assertEquals(0, runtimeService.createExecutionQuery().count()); runtimeService.startProcessInstanceByMessage("myStartMessage"); runtimeService.startProcessInstanceByMessage("myStartMessage"); assertEquals(2, runtimeService.createProcessInstanceQuery().count()); assertEquals(3, getAllEventSubscriptions().size()); // 1 for the start, 2 for the boundary // Deploy version with only a boundary signal String deploymentId2 = deployBoundaryMessageTestProcess(); assertThatThrownBy(() -> runtimeService.startProcessInstanceByMessage("myStartMessage")); assertEquals(2, runtimeService.createProcessInstanceQuery().count()); assertEventSubscriptionsCount(2); // 2 boundary events remain // Deploy version with signal start String deploymentId3 = deployStartMessageTestProcess(); runtimeService.startProcessInstanceByMessage("myStartMessage"); assertEquals(3, runtimeService.createProcessInstanceQuery().count()); assertEventSubscriptionsCount(3); // Delete last version again, making the one with the boundary the latest repositoryService.deleteDeployment(deploymentId3, true); assertThatThrownBy(() -> runtimeService.startProcessInstanceByMessage("myStartMessage")); assertEquals(2, runtimeService.createProcessInstanceQuery().count()); // -1, cause process instance of deploymentId3 is gone too assertEventSubscriptionsCount(2); // The 2 boundary remains // Test the boundary signal assertReceiveMessage("myBoundaryMessage", 2); assertEquals(2, taskService.createTaskQuery().taskName("Task after boundary message").list().size()); // Delete second version repositoryService.deleteDeployment(deploymentId2, true); runtimeService.startProcessInstanceByMessage("myStartMessage"); assertEquals(3, runtimeService.createProcessInstanceQuery().count()); // -1, cause process instance of deploymentId3 is gone too assertEventSubscriptionsCount(2); // 2 boundaries cleanup(deploymentId1); } @Test public void testBothBoundaryAndStartSameMessageId() { // Deploy process with both boundary and start event String deploymentId1 = deployProcessWithBothStartAndBoundarySameMessage(); assertEquals(1, getAllEventSubscriptions().size()); assertEventSubscriptionsCount(1); assertEquals(0, runtimeService.createExecutionQuery().count()); for (int i = 0; i < 9; i++) { // Every iteration will signal the boundary event of the previous iteration! runtimeService.startProcessInstanceByMessage("myMessage"); } if (HistoryTestHelper.isHistoryLevelAtLeast(HistoryLevel.ACTIVITY, processEngineConfiguration)) { assertEquals(9, historyService.createHistoricProcessInstanceQuery().count()); } assertEquals(10, getAllEventSubscriptions().size()); // 1 for the start, 9 for boundary // Deploy version with only a start signal. The boundary events should still react though! String deploymentId2 = deployStartMessageTestProcess(); runtimeService.startProcessInstanceByMessage("myStartMessage"); assertEquals(10, runtimeService.createProcessInstanceQuery().count()); assertEventSubscriptionsCount(10); // Remains 10: 1 one was removed, but one added for the new message assertThatThrownBy(() -> runtimeService.startProcessInstanceByMessage("myMessage")); cleanup(deploymentId1, deploymentId2); } /* * HELPERS */ private String deployBoundaryMessageTestProcess() { return deploy(TEST_PROCESS_GLOBAL_BOUNDARY_MESSAGE); } private String deployStartMessageTestProcess() { return deploy(TEST_PROCESS_START_MESSAGE); } private String deployProcessWithoutEvents() { return deploy(TEST_PROCESS_NO_EVENTS); } private String deployProcessWithBothStartAndBoundaryMessage() { return deploy(TEST_PROCESS_BOTH_START_AND_BOUNDARY_MESSAGE); } private String deployProcessWithBothStartAndBoundarySameMessage() { return deploy(TEST_PROCESS_BOTH_START_AND_BOUNDARY_MESSAGE_SAME_MESSAGE); } private String deploy(String path) { String deploymentId = repositoryService .createDeployment() .addClasspathResource(path) .deploy() .getId(); return deploymentId; } private void cleanup(String... deploymentIds) { deleteDeployments(); } private List<String> getExecutionIdsForMessageEventSubscription(final String messageName) { List<EventSubscription> eventSubscriptions = runtimeService.createEventSubscriptionQuery() .eventType("message") .eventName(messageName) .orderByCreateDate() .desc() .list(); List<String> executionIds = new ArrayList<>(); for (EventSubscription eventSubscription : eventSubscriptions) { executionIds.add(eventSubscription.getExecutionId()); } return executionIds; } private List<EventSubscription> getAllEventSubscriptions() { List<EventSubscription> eventSubscriptionEntities = runtimeService.createEventSubscriptionQuery() .orderByCreateDate() .desc() .list(); for (EventSubscription entity : eventSubscriptionEntities) { assertEquals("message", entity.getEventType()); assertNotNull(entity.getProcessDefinitionId()); } return eventSubscriptionEntities; } private void assertReceiveMessage(String messageName, int executionIdsCount) { List<String> executionIds = getExecutionIdsForMessageEventSubscription(messageName); assertEquals(executionIdsCount, executionIds.size()); for (String executionId : executionIds) { runtimeService.messageEventReceived(messageName, executionId); } } private void assertEventSubscriptionsCount(long count) { assertEquals(count, getAllEventSubscriptions().size()); } }
{'content_hash': '34054e3ed4faef49abf2b3503101e1ed', 'timestamp': '', 'source': 'github', 'line_count': 474, 'max_line_length': 231, 'avg_line_length': 46.53164556962025, 'alnum_prop': 0.7277384838592673, 'repo_name': 'lsmall/flowable-engine', 'id': 'f183cc59edc84a2365851a87da7fe9ff48ca28b0', 'size': '22056', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'modules/flowable-engine/src/test/java/org/flowable/engine/test/bpmn/deployment/MessageEventsAndNewVersionDeploymentsTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '166'}, {'name': 'CSS', 'bytes': '688913'}, {'name': 'Dockerfile', 'bytes': '6367'}, {'name': 'Groovy', 'bytes': '482'}, {'name': 'HTML', 'bytes': '1117510'}, {'name': 'Java', 'bytes': '33771201'}, {'name': 'JavaScript', 'bytes': '12402628'}, {'name': 'PLSQL', 'bytes': '109354'}, {'name': 'PLpgSQL', 'bytes': '11691'}, {'name': 'SQLPL', 'bytes': '1265'}, {'name': 'Shell', 'bytes': '19145'}]}
use std::borrow::Cow; use nom::{IResult, be_u32}; use primitives::field::{TableEntries, TableEntry, Value}; use common::shortstr; use pool::ParserPool; use NomBytes; impl<'a> NomBytes<'a> for TableEntries<'a> { type Output = TableEntries<'a>; fn nom_bytes<'b, P>(input: &'a [u8], pool: &'b mut P) -> IResult<&'a [u8], Self> where P: ParserPool { let (input, num_bytes) = try_parse!(input, be_u32); let (_, bytes) = try_parse!(input, peek!(length_bytes!(value!(num_bytes)))); #[ignore(unused_variables)] map!(input, length_value!( value!(num_bytes), terminated!( fold_many0!( tuple!( map!(shortstr, |s| Cow::Borrowed(s)), apply!(Value::nom_bytes, pool) ), pool.new_table_entries_vec(bytes), |mut entries: Vec<TableEntry<'a>>, entry: TableEntry<'a>| { entries.push(entry); entries } ), eof!() ) ), |entries| TableEntries::from_entries(entries) ) } }
{'content_hash': '5dfd8e76e62e2082ad0d1937738eedcd', 'timestamp': '', 'source': 'github', 'line_count': 40, 'max_line_length': 84, 'avg_line_length': 32.275, 'alnum_prop': 0.44229279628195195, 'repo_name': 'alreece45/amqp-rs', 'id': '6b02399fd651b1fa5713ad23180698b59241e982', 'size': '1629', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'amqp0/parser-nom/src/field/table.rs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Rust', 'bytes': '3453642'}]}
package ua.com.fielden.platform.sample.domain; import ua.com.fielden.platform.entity.AbstractEntity; import ua.com.fielden.platform.entity.annotation.CompanionObject; import ua.com.fielden.platform.entity.annotation.DescTitle; import ua.com.fielden.platform.entity.annotation.IsProperty; import ua.com.fielden.platform.entity.annotation.KeyTitle; import ua.com.fielden.platform.entity.annotation.KeyType; import ua.com.fielden.platform.entity.annotation.MapEntityTo; import ua.com.fielden.platform.entity.annotation.MapTo; import ua.com.fielden.platform.entity.annotation.Observable; import ua.com.fielden.platform.entity.annotation.Required; import ua.com.fielden.platform.entity.annotation.Title; import ua.com.fielden.platform.security.user.User; /** * Master entity object. * * @author Developers * */ @KeyType(String.class) @KeyTitle(value = "Key", desc = "Some key description") @CompanionObject(ITgSubSystem.class) @MapEntityTo @DescTitle(value = "Desc", desc = "Some desc description") public class TgSubSystem extends AbstractEntity<String> { @IsProperty @MapTo @Title("Category") private TgCategory firstCategory; @IsProperty @MapTo @Title(value = "Second Category", desc = "Desc") private TgCategory secondCategory; @IsProperty(assignBeforeSave = true) @MapTo @Title(value = "User", desc = "Desc") @Required private User user; @IsProperty(assignBeforeSave = true) @MapTo @Title(value = "Explanation", desc = "Desc") private String explanation; @Observable public TgSubSystem setExplanation(final String explanation) { this.explanation = explanation; return this; } public String getExplanation() { return explanation; } @Observable public TgSubSystem setUser(final User user) { this.user = user; return this; } public User getUser() { return user; } @Observable public TgSubSystem setSecondCategory(final TgCategory secondCategory) { this.secondCategory = secondCategory; return this; } public TgCategory getSecondCategory() { return secondCategory; } @Observable public TgSubSystem setFirstCategory(final TgCategory category) { this.firstCategory = category; return this; } public TgCategory getFirstCategory() { return firstCategory; } }
{'content_hash': '0d1ecf17435b5877014fe8efe96be0cb', 'timestamp': '', 'source': 'github', 'line_count': 90, 'max_line_length': 75, 'avg_line_length': 26.822222222222223, 'alnum_prop': 0.7125103562551781, 'repo_name': 'fieldenms/tg', 'id': 'e2d4e3b3f8db4d6a10aaaf9c5ab00493e96bd502', 'size': '2414', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'platform-pojo-bl/src/main/java/ua/com/fielden/platform/sample/domain/TgSubSystem.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '4729'}, {'name': 'CSS', 'bytes': '177044'}, {'name': 'CoffeeScript', 'bytes': '2455'}, {'name': 'HTML', 'bytes': '2236957'}, {'name': 'Java', 'bytes': '12685270'}, {'name': 'JavaScript', 'bytes': '34404107'}, {'name': 'Makefile', 'bytes': '28094'}, {'name': 'Python', 'bytes': '3798'}, {'name': 'Roff', 'bytes': '3102'}, {'name': 'Shell', 'bytes': '13899'}, {'name': 'TSQL', 'bytes': '1058'}, {'name': 'TeX', 'bytes': '1296798'}, {'name': 'XSLT', 'bytes': '6158'}]}
package com.intellij.psi.impl.search; import com.intellij.psi.PsiFile; import com.intellij.psi.impl.cache.TodoCacheManager; import com.intellij.psi.search.IndexPattern; import com.intellij.psi.search.IndexPatternProvider; import com.intellij.psi.search.searches.IndexPatternSearch; import org.jetbrains.annotations.NotNull; /** * @author yole */ public class IndexPatternSearchImpl extends IndexPatternSearch { public IndexPatternSearchImpl() { registerExecutor(new IndexPatternSearcher()); } @Override protected int getOccurrencesCountImpl(@NotNull PsiFile file, @NotNull IndexPatternProvider provider) { int count = TodoCacheManager.getInstance(file.getProject()).getTodoCount(file.getVirtualFile(), provider); if (count != -1) return count; return search(file, provider).findAll().size(); } @Override protected int getOccurrencesCountImpl(@NotNull PsiFile file, @NotNull IndexPattern pattern) { int count = TodoCacheManager.getInstance(file.getProject()).getTodoCount(file.getVirtualFile(), pattern); if (count != -1) return count; return search(file, pattern).findAll().size(); } }
{'content_hash': '67c4388bb16903de0cc5afe81c64f788', 'timestamp': '', 'source': 'github', 'line_count': 33, 'max_line_length': 110, 'avg_line_length': 34.484848484848484, 'alnum_prop': 0.7671353251318102, 'repo_name': 'ernestp/consulo', 'id': '085408ace5d8dcc0b2e0aedf5cb68a185ee04a72', 'size': '1738', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'platform/editor-ui-ex/src/com/intellij/psi/impl/search/IndexPatternSearchImpl.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '3588'}, {'name': 'C', 'bytes': '47018'}, {'name': 'C++', 'bytes': '88348'}, {'name': 'CSS', 'bytes': '12523'}, {'name': 'Groovy', 'bytes': '41575'}, {'name': 'HTML', 'bytes': '188389'}, {'name': 'Java', 'bytes': '54360143'}, {'name': 'Lex', 'bytes': '5949'}, {'name': 'Objective-C', 'bytes': '18984'}, {'name': 'Python', 'bytes': '2985'}, {'name': 'Shell', 'bytes': '8598'}, {'name': 'Thrift', 'bytes': '1228'}, {'name': 'XSLT', 'bytes': '49230'}]}
{% extends "proposals/base.html" %} {% load i18n bootstrap %} {% block content %} <h1>Proposal: {{ proposal.title }}</h1> <p><a href="{% url proposal_edit proposal.pk %}">{% trans "Edit proposal" %}</a></p> <h2>Current Speakers</h2> {% for speaker in speakers %} {% if speaker.user %} <p><b>{{ speaker.name }}</b> &mdash; {{ speaker.email }}</p> {% else %} <p>{{ speaker.email }} &mdash; pending invitation</p> {% endif %} {% endfor %} <h2>Add another speaker</h2> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset> {{ add_speaker_form|bootstrap }} <div class="form-actions"> <input class="btn btn-primary" type="submit" value="{% trans "Add speaker" %}" /> </div> </fieldset> </form> {% endblock %} {% block extra_body %} <script type="text/javascript"> $(function() { $("#id_email").focus(); }); </script> {% endblock %}
{'content_hash': '40a1d9957ac2131e75672ccc111b6342', 'timestamp': '', 'source': 'github', 'line_count': 39, 'max_line_length': 97, 'avg_line_length': 27.153846153846153, 'alnum_prop': 0.4995278564683664, 'repo_name': 'tzangms/PyConTW', 'id': 'ad6c57589b2eac8429f245fe8b81d0f133c9e133', 'size': '1059', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'pycon_project/templates/proposals/proposal_speaker_manage.html', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'JavaScript', 'bytes': '111665'}, {'name': 'Python', 'bytes': '218799'}]}
import argparse import logging import os import subprocess import sys from toil.wdl.utils import dict_from_JSON, get_analyzer, write_mappings from toil.wdl.wdl_synthesis import SynthesizeWDL logger = logging.getLogger(__name__) def main(): """ A program to run WDL input files using native Toil scripts. Calls two files, described below, wdl_analysis.py and wdl_synthesis.py: wdl_analysis reads the wdl and restructures them into 2 intermediate data structures before writing (python dictionaries): "wf_dictionary": containing the parsed workflow information. "tasks_dictionary": containing the parsed task information. wdl_synthesis takes the "wf_dictionary", "tasks_dictionary", and the JSON file and uses them to write a native python script for use with Toil. Requires a WDL file, and a JSON file. The WDL file contains ordered commands, and the JSON file contains input values for those commands. To run in Toil, these two files must be parsed, restructured into python dictionaries, and then compiled into a Toil formatted python script. This compiled Toil script is deleted unless the user specifies: "--dev_mode" as an option. The WDL parser was auto-generated from the Broad's current WDL grammar file: https://github.com/openwdl/wdl/blob/master/parsers/grammar.hgr using Scott Frazer's Hermes: https://github.com/scottfrazer/hermes Thank you Scott Frazer! Currently in alpha testing, and known to work with the Broad's GATK tutorial set for WDL on their main wdl site: software.broadinstitute.org/wdl/documentation/topic?name=wdl-tutorials And ENCODE's WDL workflow: github.com/ENCODE-DCC/pipeline-container/blob/master/local-workflows/encode_mapping_workflow.wdl Additional support to be broadened to include more features soon. """ parser = argparse.ArgumentParser(description='Runs WDL files with toil.') parser.add_argument('wdl_file', help='A WDL workflow file.') parser.add_argument('secondary_file', help='A secondary data file (json).') parser.add_argument("--jobStore", type=str, required=False, default=None) parser.add_argument('-o', '--outdir', required=False, default=os.getcwd(), help='Optionally specify the directory that outputs ' 'are written to. Default is the current working dir.') parser.add_argument('--dev_mode', required=False, default=False, help='1. Creates "AST.out", which holds the printed AST and ' '"mappings.out", which holds the parsed task, workflow ' 'dictionaries that were generated. ' '2. Saves the compiled toil script generated from the ' 'wdl/json files from deletion. ' '3. Skips autorunning the compiled python file.') parser.add_argument('--docker_user', required=False, default='root', help='The user permissions that the docker containers will be run ' 'with (and the permissions set on any output files produced). ' 'Default is "root". Setting this to None will set this to ' 'the current user.') parser.add_argument("--destBucket", type=str, required=False, default=False, help="Specify a cloud bucket endpoint for output files.") # wdl_run_args is an array containing all of the unknown arguments not # specified by the parser in this main. All of these will be passed down in # check_call later to run the compiled toil file. args, wdl_run_args = parser.parse_known_args() wdl_file = os.path.abspath(args.wdl_file) args.secondary_file = os.path.abspath(args.secondary_file) args.outdir = os.path.abspath(args.outdir) aWDL = get_analyzer(wdl_file=wdl_file) if args.dev_mode: aWDL.write_AST(out_dir=args.outdir) # read secondary file; create dictionary to hold variables if args.secondary_file.endswith('.json'): json_dict = dict_from_JSON(args.secondary_file) else: raise RuntimeError('Unsupported Secondary File Type. Use json.') aWDL.analyze() sWDL = SynthesizeWDL(aWDL.version, aWDL.tasks_dictionary, aWDL.workflows_dictionary, args.outdir, json_dict, args.docker_user, args.jobStore, args.destBucket) # use the AST dictionaries to write 4 strings # these are the future 4 sections of the compiled toil python file module_section = sWDL.write_modules() fn_section = sWDL.write_functions() main_section = sWDL.write_main() # write 3 strings to a python output file sWDL.write_python_file(module_section, fn_section, main_section, sWDL.output_file) if args.dev_mode: logger.debug('WDL file compiled to toil script.') write_mappings(aWDL) else: logger.debug('WDL file compiled to toil script. Running now.') exe = sys.executable if sys.executable else 'python' cmd = [exe, sWDL.output_file] cmd.extend(wdl_run_args) subprocess.check_call(cmd) os.remove(sWDL.output_file) if __name__ == '__main__': main()
{'content_hash': 'd2ff19791126ed2a9624b022ede71e3c', 'timestamp': '', 'source': 'github', 'line_count': 128, 'max_line_length': 100, 'avg_line_length': 43.8203125, 'alnum_prop': 0.631306828311642, 'repo_name': 'BD2KGenomics/slugflow', 'id': 'f322898179a8e9909962df78903f1e2f49eed815', 'size': '6213', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/toil/wdl/toilwdl.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Makefile', 'bytes': '4074'}, {'name': 'Python', 'bytes': '618803'}, {'name': 'Shell', 'bytes': '19115'}]}
/** * Runtime core classes. */ package com.asakusafw.runtime.core;
{'content_hash': '3b3a91241ad21872e03e2a4b76055def', 'timestamp': '', 'source': 'github', 'line_count': 5, 'max_line_length': 35, 'avg_line_length': 14.0, 'alnum_prop': 0.6857142857142857, 'repo_name': 'akirakw/asakusafw', 'id': '18f1b86e0b7448abf20d86e9e485f0a12a41cbf5', 'size': '682', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'core-project/asakusa-runtime/src/main/java/com/asakusafw/runtime/core/package-info.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '31'}, {'name': 'CSS', 'bytes': '650'}, {'name': 'Groovy', 'bytes': '275943'}, {'name': 'Java', 'bytes': '12250766'}, {'name': 'Lex', 'bytes': '12506'}, {'name': 'Shell', 'bytes': '10149'}]}
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{'content_hash': 'e038d6736d7ac13df1706d7465bcc1e7', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.23076923076923, 'alnum_prop': 0.6917293233082706, 'repo_name': 'mdoering/backbone', 'id': '2680f6be800e2121c013e3fc9f823d5f37a4d36b', 'size': '207', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Ericales/Sapotaceae/Pouteria/Pouteria adolfi-friedericii/ Syn. Sideroxylon adolfi-friedericii keniensis/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
layout: error_404 css_filename: lux.css ---
{'content_hash': 'bc2208b2330be9f4e05efa0707dcfa87', 'timestamp': '', 'source': 'github', 'line_count': 3, 'max_line_length': 21, 'avg_line_length': 14.666666666666666, 'alnum_prop': 0.7045454545454546, 'repo_name': 'jmlemetayer/abba', 'id': 'ad3e79646dda123c0c8db0d137a04c04cfb7d2da', 'size': '48', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'previews/lux/error_404.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Dockerfile', 'bytes': '564'}, {'name': 'HTML', 'bytes': '18278'}, {'name': 'JavaScript', 'bytes': '7420'}, {'name': 'Python', 'bytes': '4258'}, {'name': 'SCSS', 'bytes': '427185'}, {'name': 'Shell', 'bytes': '1220'}]}
/** * istanbul ignore next */ define(function(require, exports, module) { 'use strict'; var Log = require('../Log'), Utils = require('../Utils'); /** * @constructor * @alias RCSDK.core.ajax.XhrMock * @extends XMLHttpRequest */ function XhrMock(context) { // Service this.responses = require('./XhrResponse').$get(context); // Request this.async = true; this.method = ''; this.url = ''; this.requestHeaders = {}; this.withCredentials = false; // Response this.data = null; this.readyState = 0; this.responseHeaders = {}; this.status = 0; this.context = context; } XhrMock.prototype.getResponseHeader = function(header) { return this.responseHeaders[header.toLowerCase()]; }; XhrMock.prototype.setRequestHeader = function(header, value) { this.requestHeaders[header.toLowerCase()] = value; }; XhrMock.prototype.getAllResponseHeaders = function() { var res = []; Utils.forEach(this.responseHeaders, function(value, name) { res.push(name + ':' + value); }); return res.join('\n'); }; XhrMock.prototype.open = function(method, url, async) { this.method = method; this.url = url; this.async = async; }; XhrMock.prototype.send = function(data) { var contentType = this.getRequestHeader('Content-Type'); this.data = data; if (this.data && typeof this.data == 'string') { // For convenience encoded post data will be decoded if (contentType == 'application/json') this.data = JSON.parse(this.data); if (contentType == 'application/x-www-form-urlencoded') this.data = Utils.parseQueryString(this.data); } Log.debug('API REQUEST', this.method, this.url); var currentResponse = this.responses.find(this); if (!currentResponse) { setTimeout(function() { if (this.onerror) this.onerror(new Error('Unknown request: ' + this.url)); }.bind(this), 1); return; } this.setStatus(200); this.setResponseHeader('Content-Type', 'application/json'); var res = currentResponse.response(this), Promise = this.context.getPromise(), onLoad = function(res) { if (this.getResponseHeader('Content-Type') == 'application/json') res = JSON.stringify(res); this.responseText = res; setTimeout(function() { if (this.onload) this.onload(); }.bind(this), 1); }.bind(this); if (res instanceof Promise) { res.then(onLoad.bind(this)).catch(this.onerror.bind(this)); } else onLoad(res); }; XhrMock.prototype.abort = function() { Log.debug('XhrMock.destroy(): Aborted'); }; XhrMock.prototype.getRequestHeader = function(header) { return this.requestHeaders[header.toLowerCase()]; }; XhrMock.prototype.setResponseHeader = function(header, value) { this.responseHeaders[header.toLowerCase()] = value; }; XhrMock.prototype.setStatus = function(status) { this.status = status; return this; }; module.exports = { Class: XhrMock, /** * @static * @param {Context} context * @returns {XhrMock} */ $get: function(context) { return new XhrMock(context); } }; });
{'content_hash': '7457c6e18607ae8581dfdf5c7b6c9f5d', 'timestamp': '', 'source': 'github', 'line_count': 134, 'max_line_length': 114, 'avg_line_length': 26.955223880597014, 'alnum_prop': 0.5584163898117387, 'repo_name': 'grokify/ringcentral-cti-demo-js', 'id': '8f9bf19e03603c886ffc5ba1c280e79e8ef01faa', 'size': '3612', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'public/vendor/rcsdk/1.2.1/lib/core/xhr/XhrMock.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '4898'}, {'name': 'HTML', 'bytes': '116191'}, {'name': 'JavaScript', 'bytes': '29563'}]}
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _index = _interopRequireDefault(require("../../getWeekYear/index.js")); var _index2 = _interopRequireDefault(require("../_lib/convertToFP/index.js")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // This file is generated automatically by `scripts/build/fp.js`. Please, don't change it. var getWeekYear = (0, _index2.default)(_index.default, 1); var _default = getWeekYear; exports.default = _default; module.exports = exports.default;
{'content_hash': 'b7e2d8848cf022a8fd564a47934f1145', 'timestamp': '', 'source': 'github', 'line_count': 18, 'max_line_length': 95, 'avg_line_length': 33.333333333333336, 'alnum_prop': 0.7116666666666667, 'repo_name': 'BigBoss424/portfolio', 'id': 'bcca76c6adaf2999cede12bb76f80014bd2049fa', 'size': '600', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'v6/node_modules/date-fns/fp/getWeekYear/index.js', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2017 Couchbase, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "collections/vbucket_manifest.h" #include "collections/manifest.h" #include "collections/vbucket_serialised_manifest_entry.h" #include "vbucket.h" #include <JSON_checker.h> #include <cJSON.h> #include <cJSON_utils.h> #include <platform/make_unique.h> Collections::VB::Manifest::Manifest(const std::string& manifest) : defaultCollectionExists(false), separator(DefaultSeparator) { if (manifest.empty()) { // Empty manifest, initialise the manifest with the default collection addCollectionEntry(DefaultCollectionIdentifier, 0, 0, StoredValue::state_collection_open); return; } if (!checkUTF8JSON(reinterpret_cast<const unsigned char*>(manifest.data()), manifest.size())) { throw std::invalid_argument( "Collections::VBucket::Manifest input not valid json"); } unique_cJSON_ptr cjson(cJSON_Parse(manifest.c_str())); if (!cjson) { throw std::invalid_argument( "Collections::VBucket::Manifest cJSON cannot parse json"); } // Load the separator separator = getJsonEntry(cjson.get(), "separator"); // Load the collections array auto jsonCollections = cJSON_GetObjectItem(cjson.get(), "collections"); if (!jsonCollections || jsonCollections->type != cJSON_Array) { throw std::invalid_argument( "Collections::VBucket::Manifest cannot find valid " "collections: " + (!jsonCollections ? "nullptr" : std::to_string(jsonCollections->type))); } // Iterate the collections and load-em up. for (int ii = 0; ii < cJSON_GetArraySize(jsonCollections); ii++) { auto collection = cJSON_GetArrayItem(jsonCollections, ii); int revision = std::stoi(getJsonEntry(collection, "revision")); int64_t startSeqno = std::stoll(getJsonEntry(collection, "startSeqno")); int64_t endSeqno = std::stoll(getJsonEntry(collection, "endSeqno")); std::string collectionName(getJsonEntry(collection, "name")); addCollectionEntry(collectionName, revision, startSeqno, endSeqno); } } void Collections::VB::Manifest::update(::VBucket& vb, const Collections::Manifest& manifest) { std::vector<std::string> additions, deletions; std::tie(additions, deletions) = processManifest(manifest); if (separator != manifest.getSeparator()) { changeSeparator(vb, manifest.getSeparator(), manifest.getRevision(), OptionalSeqno{/*no-seqno*/}); } // Process additions to the manifest for (const auto& collection : additions) { addCollection(vb, collection, manifest.getRevision(), OptionalSeqno{/*no-seqno*/}); } // Process deletions to the manifest for (const auto& collection : deletions) { beginCollectionDelete(vb, collection, manifest.getRevision(), OptionalSeqno{/*no-seqno*/}); } } void Collections::VB::Manifest::addCollection(::VBucket& vb, cb::const_char_buffer collection, uint32_t revision, OptionalSeqno optionalSeqno) { auto seqno = queueSystemEvent(vb, SystemEvent::CreateCollection, collection, revision, optionalSeqno); LOG(EXTENSION_LOG_NOTICE, "collections: vb:%" PRIu16 " adding collection:%.*s, revision:%" PRIu32 ", seqno:%" PRIu64, vb.getId(), int(collection.size()), collection.data(), revision, seqno); addCollectionEntry( collection, revision, seqno, StoredValue::state_collection_open); } void Collections::VB::Manifest::addCollectionEntry( cb::const_char_buffer collection, uint32_t revision, int64_t startSeqno, int64_t endSeqno) { auto itr = map.find(collection); if (itr == map.end()) { auto m = std::make_unique<Collections::VB::ManifestEntry>( collection, revision, startSeqno, endSeqno); map.emplace(m->getCharBuffer(), std::move(m)); } else if (!itr->second->isOpen()) { itr->second->setRevision(revision); itr->second->setStartSeqno(startSeqno); } else { std::stringstream ss; ss << *itr->second; throw std::logic_error("addCollection: cannot add collection:" + cb::to_string(collection) + ", startSeqno:" + std::to_string(startSeqno) + ", endSeqno:" + std::to_string(endSeqno) + " " + ss.str()); } if (collection == DefaultCollectionIdentifier) { defaultCollectionExists = true; } } void Collections::VB::Manifest::beginCollectionDelete( ::VBucket& vb, cb::const_char_buffer collection, uint32_t revision, OptionalSeqno optionalSeqno) { auto seqno = queueSystemEvent(vb, SystemEvent::BeginDeleteCollection, collection, revision, optionalSeqno); LOG(EXTENSION_LOG_NOTICE, "collections: vb:%" PRIu16 " begin delete of collection:%.*s, revision:%" PRIu32 ", seqno:%" PRIu64, vb.getId(), int(collection.size()), collection.data(), revision, seqno); beginDeleteCollectionEntry(collection, revision, seqno); } void Collections::VB::Manifest::beginDeleteCollectionEntry( cb::const_char_buffer collection, uint32_t revision, int64_t seqno) { auto itr = map.find(collection); if (itr != map.end()) { itr->second->setRevision(revision); itr->second->setEndSeqno(seqno); } else { throw std::logic_error("beginDelCollection: did not find collection:" + cb::to_string(collection) + ", revision:" + std::to_string(revision) + ", seqno:" + std::to_string(seqno)); } if (collection == DefaultCollectionIdentifier) { defaultCollectionExists = false; } } void Collections::VB::Manifest::completeDeletion( ::VBucket& vb, cb::const_char_buffer collection, uint32_t revision) { auto itr = map.find(collection); LOG(EXTENSION_LOG_NOTICE, "collections: vb:%" PRIu16 " complete delete of collection:%.*s, revision:%" PRIu32, vb.getId(), int(collection.size()), collection.data(), revision); if (itr == map.end()) { throw std::logic_error("completeDeletion: could not find collection:" + cb::to_string(collection)); } if (itr->second->isExclusiveDeleting()) { // When we find that the collection is not open, we can hard delete it. // This means we are purging it completely from the manifest and will // generate a JSON manifest without an entry for the collection. queueSystemEvent(vb, SystemEvent::DeleteCollectionHard, collection, revision, OptionalSeqno{/*none*/}); map.erase(itr); } else if (itr->second->isOpenAndDeleting()) { // When we find that the collection open and deleting we can soft delete // it. This means we are just adjusting the endseqno so that the entry // returns true for isExclusiveOpen() queueSystemEvent(vb, SystemEvent::DeleteCollectionSoft, collection, itr->second->getRevision(), OptionalSeqno{/*none*/}); itr->second->resetEndSeqno(); // and reset the end to our special seqno } else { // This is an invalid request std::stringstream ss; ss << *itr->second; throw std::logic_error("completeDeletion: cannot delete:" + ss.str()); } } void Collections::VB::Manifest::changeSeparator( ::VBucket& vb, cb::const_char_buffer newSeparator, uint32_t revision, OptionalSeqno optionalSeqno) { // Can we change the separator? Only allowed to change if there are no // collections or the only collection is the default collection if (cannotChangeSeparator()) { std::stringstream ss; ss << *this; throw std::logic_error( "Collections::VB::Manifest::changeSeparator cannot change " "separator to " + cb::to_string(newSeparator) + " " + ss.str()); } else { LOG(EXTENSION_LOG_NOTICE, "collections: vb:%" PRIu16 " changing collection separator from:%s, to:%.*s", vb.getId(), separator.c_str(), int(newSeparator.size()), newSeparator.data()); // Change the separator then queue the event so the new separator // is recorded in the serialised manifest separator = std::string(newSeparator.data(), newSeparator.size()); // Queue an event so that the manifest is flushed and DCP can // replicate the change. (void)queueSeparatorChanged(vb, revision, optionalSeqno); } } Collections::VB::Manifest::processResult Collections::VB::Manifest::processManifest( const Collections::Manifest& manifest) const { std::vector<std::string> additions, deletions; for (const auto& manifestEntry : map) { // If the manifestEntry is open and not found in the new manifest it // must be deleted. if (manifestEntry.second->isOpen() && manifest.find(manifestEntry.second->getCollectionName()) == manifest.end()) { deletions.push_back(std::string( reinterpret_cast<const char*>(manifestEntry.first.data()), manifestEntry.first.size())); } } // iterate manifest and add all non-existent collection for (const auto& m : manifest) { // if we don't find the collection, then it must be an addition. // if we do find a name match, then check if the collection is in the // process of being deleted. auto itr = map.find(m); if (itr == map.end() || !itr->second->isOpen()) { additions.push_back(m); } } return std::make_pair(additions, deletions); } bool Collections::VB::Manifest::doesKeyContainValidCollection( const ::DocKey& key) const { const auto cKey = Collections::DocKey::make(key, separator); if (defaultCollectionExists && cKey.getDocNamespace() == DocNamespace::DefaultCollection) { return true; } else if (cKey.getDocNamespace() == DocNamespace::Collections) { auto itr = map.find({reinterpret_cast<const char*>(cKey.data()), cKey.getCollectionLen()}); if (itr != map.end()) { return itr->second->isOpen(); } } return false; } std::unique_ptr<Item> Collections::VB::Manifest::createSystemEvent( SystemEvent se, cb::const_char_buffer collection, uint32_t revision, OptionalSeqno seqno) const { // Create an item (to be queued and written to disk) that represents // the update of a collection and allows the checkpoint to update // the _local document with a persisted version of this object (the entire // manifest is persisted to disk as JSON). // The key for the item includes the name and revision to ensure a // checkpoint consumer (e.g. DCP) can transmit the full collection info. auto item = SystemEventFactory::make( se, separator, cb::to_string(collection) + separator + std::to_string(revision), getSerialisedDataSize(collection), seqno); // Quite rightly an Item's value is const, but in this case the Item is // owned only by the local scope so is safe to mutate (by const_cast force) populateWithSerialisedData( {const_cast<char*>(item->getData()), item->getNBytes()}, collection, revision); return item; } std::unique_ptr<Item> Collections::VB::Manifest::createSeparatorChangedEvent( uint32_t revision, OptionalSeqno seqno) const { // Create an item (to be queued and written to disk) that represents // the change of the separator. The item always has the same key. // We serialise the state of this object into the Item's value. auto item = SystemEventFactory::make(SystemEvent::CollectionsSeparatorChanged, separator, {/*empty string*/}, getSerialisedDataSize(), seqno); // Quite rightly an Item's value is const, but in this case the Item is // owned only by the local scope so is safe to mutate (by const_cast force) populateWithSerialisedData( {const_cast<char*>(item->getData()), item->getNBytes()}, revision); return item; } int64_t Collections::VB::Manifest::queueSystemEvent( ::VBucket& vb, SystemEvent se, cb::const_char_buffer collection, uint32_t revision, OptionalSeqno seq) const { // Create and transfer Item ownership to the VBucket return vb.queueItem( createSystemEvent(se, collection, revision, seq).release(), seq); } int64_t Collections::VB::Manifest::queueSeparatorChanged( ::VBucket& vb, uint32_t revision, OptionalSeqno seqno) const { // Create and transfer Item ownership to the VBucket return vb.queueItem(createSeparatorChangedEvent(revision, seqno).release(), seqno); } size_t Collections::VB::Manifest::getSerialisedDataSize( cb::const_char_buffer collection) const { size_t bytesNeeded = SerialisedManifest::getObjectSize(separator.size()); for (const auto& collectionEntry : map) { // Skip if a collection in the map matches the collection being changed if (collectionEntry.second->getCharBuffer() == collection) { continue; } bytesNeeded += SerialisedManifestEntry::getObjectSize( collectionEntry.second->getCollectionName().size()); } return bytesNeeded + SerialisedManifestEntry::getObjectSize(collection.size()); } size_t Collections::VB::Manifest::getSerialisedDataSize() const { size_t bytesNeeded = SerialisedManifest::getObjectSize(separator.size()); for (const auto& collectionEntry : map) { // Skip if a collection in the map matches the collection being changed bytesNeeded += SerialisedManifestEntry::getObjectSize( collectionEntry.second->getCollectionName().size()); } return bytesNeeded; } void Collections::VB::Manifest::populateWithSerialisedData( cb::char_buffer out, cb::const_char_buffer collection, uint32_t revision) const { auto* sMan = SerialisedManifest::make(out.data(), separator, revision, out); uint32_t itemCounter = 1; // always a final entry char* serial = sMan->getManifestEntryBuffer(); const std::unique_ptr<ManifestEntry>* finalEntry = nullptr; for (const auto& collectionEntry : map) { // Check if we find the mutated entry in the map (so we know if we're // deleting it) if (collectionEntry.second->getCharBuffer() == collection) { // If a collection in the map matches the collection being changed // save the iterator so we can use it when creating the final entry finalEntry = &collectionEntry.second; } else { itemCounter++; auto* sme = SerialisedManifestEntry::make( serial, *collectionEntry.second, out); serial = sme->nextEntry(); } } SerialisedManifestEntry* finalSme = nullptr; if (finalEntry) { // delete finalSme = SerialisedManifestEntry::make(serial, *finalEntry->get(), out); finalSme->setRevision(revision); } else { // create finalSme = SerialisedManifestEntry::make( serial, revision, collection, out); } sMan->setEntryCount(itemCounter); sMan->calculateFinalEntryOffest(finalSme); } void Collections::VB::Manifest::populateWithSerialisedData( cb::char_buffer out, uint32_t revision) const { auto* sMan = SerialisedManifest::make(out.data(), separator, revision, out); char* serial = sMan->getManifestEntryBuffer(); for (const auto& collectionEntry : map) { auto* sme = SerialisedManifestEntry::make( serial, *collectionEntry.second, out); serial = sme->nextEntry(); } sMan->setEntryCount(map.size()); } std::string Collections::VB::Manifest::serialToJson( SystemEvent se, cb::const_char_buffer buffer, int64_t finalEntrySeqno) { if (se == SystemEvent::CollectionsSeparatorChanged) { return serialToJson(buffer); } const auto* sMan = reinterpret_cast<const SerialisedManifest*>(buffer.data()); const char* serial = sMan->getManifestEntryBuffer(); std::string json = R"({"separator":")" + sMan->getSeparator() + R"(","collections":[)"; if (sMan->getEntryCount() > 1) { for (uint32_t ii = 1; ii < sMan->getEntryCount(); ii++) { const auto* sme = reinterpret_cast<const SerialisedManifestEntry*>(serial); json += sme->toJson(); serial = sme->nextEntry(); if (ii < sMan->getEntryCount() - 1) { json += ","; } } const auto* sme = reinterpret_cast<const SerialisedManifestEntry*>(serial); if (se != SystemEvent::DeleteCollectionHard) { json += "," + sme->toJson(se, finalEntrySeqno); } } else { const auto* sme = reinterpret_cast<const SerialisedManifestEntry*>(serial); json += sme->toJson(se, finalEntrySeqno); } json += "]}"; return json; } std::string Collections::VB::Manifest::serialToJson( cb::const_char_buffer buffer) { const auto* sMan = reinterpret_cast<const SerialisedManifest*>(buffer.data()); const char* serial = sMan->getManifestEntryBuffer(); std::string json = R"({"separator":")" + sMan->getSeparator() + R"(","collections":[)"; for (uint32_t ii = 0; ii < sMan->getEntryCount(); ii++) { const auto* sme = reinterpret_cast<const SerialisedManifestEntry*>(serial); json += sme->toJson(); serial = sme->nextEntry(); if (ii < sMan->getEntryCount() - 1) { json += ","; } } json += "]}"; return json; } const char* Collections::VB::Manifest::getJsonEntry(cJSON* cJson, const char* key) { auto jsonEntry = cJSON_GetObjectItem(cJson, key); if (!jsonEntry || jsonEntry->type != cJSON_String) { throw std::invalid_argument( "Collections::VB::Manifest::getJsonEntry(" + std::string(key) + ") : " + (!jsonEntry ? "nullptr" : std::to_string(jsonEntry->type))); } return jsonEntry->valuestring; } bool Collections::VB::Manifest::cannotChangeSeparator() const { // If any non-default collection exists that isOpen, cannot change separator for (const auto& manifestEntry : map) { // If the manifestEntry is open and not found in the new manifest it // must be deleted. if (manifestEntry.second->isOpen() && manifestEntry.second->getCharBuffer() != DefaultCollectionIdentifier) { // Collection is open and is not $default - cannot change return true; } } return false; } std::pair<cb::const_char_buffer, cb::const_byte_buffer> Collections::VB::Manifest::getSystemEventData( cb::const_char_buffer serialisedManifest) { const auto* sm = reinterpret_cast<const SerialisedManifest*>( serialisedManifest.data()); const auto* sme = sm->getFinalManifestEntry(); return std::make_pair(sme->getCollectionName(), sm->getRevisionBuffer()); } std::pair<cb::const_char_buffer, cb::const_byte_buffer> Collections::VB::Manifest::getSystemEventSeparatorData( cb::const_char_buffer serialisedManifest) { const auto* sm = reinterpret_cast<const SerialisedManifest*>( serialisedManifest.data()); return std::make_pair(sm->getSeparatorBuffer(), sm->getRevisionBuffer()); } std::ostream& Collections::VB::operator<<( std::ostream& os, const Collections::VB::Manifest& manifest) { os << "VBucket::Manifest: size:" << manifest.map.size() << std::endl; for (auto& m : manifest.map) { os << *m.second << std::endl; } return os; }
{'content_hash': '66a8c67aa791e49123fb176569d4518a', 'timestamp': '', 'source': 'github', 'line_count': 583, 'max_line_length': 91, 'avg_line_length': 38.11492281303602, 'alnum_prop': 0.5942576841726295, 'repo_name': 'membase/ep-engine', 'id': '3d43280b689fec93cf634f8787ce313f7568f68e', 'size': '22221', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/collections/vbucket_manifest.cc', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '27461'}, {'name': 'C++', 'bytes': '4263226'}, {'name': 'CMake', 'bytes': '24371'}, {'name': 'Python', 'bytes': '110621'}, {'name': 'Shell', 'bytes': '5120'}]}
package com.googlecode.totallylazy; import com.googlecode.totallylazy.functions.Callables; import com.googlecode.totallylazy.functions.Curried2; import com.googlecode.totallylazy.functions.Function1; import com.googlecode.totallylazy.predicates.Predicate; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import static com.googlecode.totallylazy.Callers.call; import static com.googlecode.totallylazy.Pair.pair; import static com.googlecode.totallylazy.predicates.Predicates.where; import static com.googlecode.totallylazy.Sequences.sequence; public class Maps { public static <K, V> Sequence<Pair<K, V>> pairs(final Map<K, V> map) { return entries(map).map(Maps.<K, V>entryToPair()); } public static <K, V> Function1<Map<K, V>, Sequence<Map.Entry<K, V>>> entries(Class<K> keyType, Class<V> valueType) { return entries(); } public static <K, V> Function1<Map<K, V>, Sequence<Map.Entry<K, V>>> entries() { return Maps::entries; } public static <K, V> Sequence<Map.Entry<K, V>> entries(final Map<K, V> map) { return sequence(map.entrySet()); } public static <K, V> Map<K, V> map() { return new LinkedHashMap<K, V>(); } public static <K, V> Map<K, V> map(K key, V value) { return map(pair(key, value)); } public static <K, V> Map<K, V> map(K key1, V value1, K key2, V value2) { return map(pair(key1, value1), pair(key2, value2)); } public static <K, V> Map<K, V> map(K key1, V value1, K key2, V value2, K key3, V value3) { return map(pair(key1, value1), pair(key2, value2), pair(key3, value3)); } public static <K, V> Map<K, V> map(K key1, V value1, K key2, V value2, K key3, V value3, K key4, V value4) { return map(pair(key1, value1), pair(key2, value2), pair(key3, value3), pair(key4, value4)); } public static <K, V> Map<K, V> map(K key1, V value1, K key2, V value2, K key3, V value3, K key4, V value4, K key5, V value5) { return map(pair(key1, value1), pair(key2, value2), pair(key3, value3), pair(key4, value4), pair(key5, value5)); } public static <K, V> Map<K, V> map(final Pair<? extends K, ? extends V> first) { return map(sequence(first)); } public static <K, V> Map<K, V> map(final Pair<? extends K, ? extends V> first, final Pair<? extends K, ? extends V> second) { return map(sequence(first, second)); } public static <K, V> Map<K, V> map(final Pair<? extends K, ? extends V> first, final Pair<? extends K, ? extends V> second, final Pair<? extends K, ? extends V> third) { return map(sequence(first, second, third)); } public static <K, V> Map<K, V> map(final Pair<? extends K, ? extends V> first, final Pair<? extends K, ? extends V> second, final Pair<? extends K, ? extends V> third, final Pair<? extends K, ? extends V> fourth) { return map(sequence(first, second, third, fourth)); } public static <K, V> Map<K, V> map(final Pair<? extends K, ? extends V> first, final Pair<? extends K, ? extends V> second, final Pair<? extends K, ? extends V> third, final Pair<? extends K, ? extends V> fourth, final Pair<? extends K, ? extends V> fifth) { return map(sequence(first, second, third, fourth, fifth)); } @SafeVarargs public static <K, V> Map<K, V> map(final Pair<? extends K, ? extends V>... entries) { return map(sequence(entries)); } @SafeVarargs public static <K, V> Map<K, V> map(final Map<K, V> seed, final Pair<? extends K, ? extends V>... entries) { return map(seed, sequence(entries)); } public static <K, V> Map<K, V> map(final Iterable<? extends Pair<? extends K, ? extends V>> entries) { return map(new LinkedHashMap<K, V>(), entries); } public static <K, V> Map<K, V> map(final Map<K, V> seed, final Iterable<? extends Pair<? extends K, ? extends V>> entries) { return map(seed, entries.iterator()); } public static <K, V> Map<K, V> map(final Iterator<? extends Pair<? extends K, ? extends V>> entries) { return map(new LinkedHashMap<K, V>(), entries); } public static <K, V> Map<K, V> map(final Map<K, V> seed, final Iterator<? extends Pair<? extends K, ? extends V>> entries) { while(entries.hasNext()){ Pair<? extends K, ? extends V> entry = entries.next(); seed.put(entry.first(), entry.second()); } return seed; } public static <T, Key> Map<Key, T> map(final Iterator<? extends T> iterator, final Function1<? super T, ? extends Key> callable) { return map(new LinkedHashMap<Key, T>(), iterator, callable); } public static <T, Key> Map<Key, T> map(final Map<Key, T> seed, final Iterator<? extends T> iterator, final Function1<? super T, ? extends Key> callable) { while (iterator.hasNext()) { final T next = iterator.next(); final Key key = call(callable, next); seed.put(key, next); } return seed; } public static <T, Key> Map<Key, T> map(final Iterable<? extends T> iterable, final Function1<? super T, ? extends Key> callable) { return map(iterable.iterator(), callable); } public static <T, Key> Map<Key, T> map(final Map<Key, T> seed, final Iterable<? extends T> iterable, final Function1<? super T, ? extends Key> callable) { return map(seed, iterable.iterator(), callable); } public static <K, V> Map<K, List<V>> multiMap(final Pair<? extends K, ? extends V> first, final Pair<? extends K, ? extends V> second) { return multiMap(sequence(first, second)); } public static <K, V> Map<K, List<V>> multiMap(final Pair<? extends K, ? extends V> first, final Pair<? extends K, ? extends V> second, final Pair<? extends K, ? extends V> third) { return multiMap(sequence(first, second, third)); } public static <K, V> Map<K, List<V>> multiMap(final Pair<? extends K, ? extends V> first, final Pair<? extends K, ? extends V> second, final Pair<? extends K, ? extends V> third, final Pair<? extends K, ? extends V> fourth) { return multiMap(sequence(first, second, third, fourth)); } public static <K, V> Map<K, List<V>> multiMap(final Pair<? extends K, ? extends V> first, final Pair<? extends K, ? extends V> second, final Pair<? extends K, ? extends V> third, final Pair<? extends K, ? extends V> fourth, final Pair<? extends K, ? extends V> fifth) { return multiMap(sequence(first, second, third, fourth, fifth)); } @SafeVarargs public static <K, V> Map<K, List<V>> multiMap(final Pair<? extends K, ? extends V>... entries) { return multiMap(sequence(entries)); } @SafeVarargs public static <K, V> Map<K, List<V>> multiMap(final Map<K, List<V>> seed, final Pair<? extends K, ? extends V>... entries) { return multiMap(seed, sequence(entries)); } public static <K, V> Map<K, List<V>> multiMap(final Iterable<? extends Pair<? extends K, ? extends V>> entries) { return multiMap(new LinkedHashMap<K, List<V>>(), entries); } public static <K, V> Map<K, List<V>> multiMap(final Map<K, List<V>> seed, final Iterable<? extends Pair<? extends K, ? extends V>> entries) { for (Pair<? extends K, ? extends V> entry : entries) { if (!seed.containsKey(entry.first())) { seed.put(entry.first(), new ArrayList<V>()); } seed.get(entry.first()).add(entry.second()); } return seed; } public static <T, Key> Map<Key, List<T>> multiMap(final Iterator<? extends T> iterator, final Function1<? super T, ? extends Key> callable) { return multiMap(new LinkedHashMap<Key, List<T>>(), iterator, callable); } public static <V, K> Map<K, List<V>> multiMap(final Map<K, List<V>> seed, final Iterator<? extends V> iterator, final Function1<? super V, ? extends K> callable) { while (iterator.hasNext()) { final V value = iterator.next(); final K key = call(callable, value); if (!seed.containsKey(key)) { seed.put(key, new ArrayList<V>()); } seed.get(key).add(value); } return seed; } public static <V, K> Map<K, List<V>> multiMap(final Iterable<? extends V> iterable, final Function1<? super V, ? extends K> callable) { return multiMap(iterable.iterator(), callable); } public static <V, K> Map<K, List<V>> multiMap(final Map<K, List<V>> seed, final Iterable<? extends V> iterable, final Function1<? super V, ? extends K> callable) { return multiMap(seed, iterable.iterator(), callable); } public static <K, V> Curried2<? super Map<K, List<V>>, ? super Pair<? extends K, ? extends V>, Map<K, List<V>>> asMultiValuedMap() { return (map, pair) -> { if (!map.containsKey(pair.first())) { map.put(pair.first(), new ArrayList<V>()); } map.get(pair.first()).add(pair.second()); return map; }; } public static <K, V> Curried2<? super Map<K, List<V>>, ? super Pair<? extends K, ? extends V>, Map<K, List<V>>> asMultiValuedMap(Class<K> key, Class<V> value) { return asMultiValuedMap(); } public static <K, V> Curried2<? super Map<K, V>, ? super Pair<K, V>, Map<K, V>> asMap() { return (map, pair) -> { map.put(pair.first(), pair.second()); return map; }; } public static <K, V> Curried2<? super Map<K, V>, ? super Pair<K, V>, Map<K, V>> asMap(Class<K> key, Class<V> value) { return asMap(); } public static <K, V> Function1<Pair<K, V>, Map.Entry<K, V>> pairToEntry() { return pair -> pair; } public static <K, V> Function1<Pair<K, V>, Map.Entry<K, V>> pairToEntry(final Class<K> keyClass, final Class<V> valueClass) { return pairToEntry(); } public static <K, V> Function1<Map.Entry<K, V>, Pair<K, V>> entryToPair() { return entry -> pair(entry.getKey(), entry.getValue()); } public static <K, V> Function1<Map.Entry<K, V>, Pair<K, V>> entryToPair(final Class<K> keyClass, final Class<V> valueClass) { return entryToPair(); } public static <K, V> Option<V> get(Map<K, V> map, K key) { return Option.option(map.get(key)); } public static <K, V> Option<V> find(Map<K, V> map, Predicate<? super K> predicate) { return pairs(map).find(where(Callables.<K>first(), predicate)).map(Callables.<V>second()); } public static <K, V> Map<K, V> filterKeys(Map<K, V> map, Predicate<? super K> predicate) { return map(pairs(map).filter(where(Callables.<K>first(), predicate))); } public static <K, V> Map<K, V> filterValues(Map<K, V> map, Predicate<? super V> predicate) { return map(pairs(map).filter(where(Callables.<V>second(), predicate))); } public static <K, V, NewK> Map<NewK, V> mapKeys(Map<K, V> map, Function1<? super K, ? extends NewK> transformer) { return map(pairs(map).map(Callables.<K, V, NewK>first(transformer))); } public static <K, V, NewV> Map<K, NewV> mapValues(Map<K, V> map, Function1<? super V, ? extends NewV> transformer) { return map(pairs(map).map(Callables.<K, V, NewV>second(transformer))); } public static <K, V> Map<K, V> fifoMap(final int maximumElements) { return new LinkedHashMap<K, V>(maximumElements) { protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return size() > maximumElements; } }; } public static <K, V> Map<K, V> lruMap(final int maximumElements) { return new LinkedHashMap<K, V>(maximumElements, 1f, true) { protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return size() > maximumElements; } }; } public static <K, V> Set<Map.Entry<K, V>> entrySet(final Iterable<? extends Pair<K, V>> map) { return sequence(map).map(Maps.<K, V>pairToEntry()).toSet(); } public static class functions { public static <K, V> Curried2<Map<K, V>, K, V> get() { return Map::get; } public static <K, V> Function1<K, V> getFrom(final Map<K, V> map) { return functions.<K,V>get().apply(map); } public static <K, V> Function1<Map<K, V>, V> valueFor(final K key) { return functions.<K,V>get().flip().apply(key); } public static <K, V> Function1<Map<K, V>, V> valueFor(final K key, final Class<V> vClass) { return valueFor(key); } } }
{'content_hash': '9f16fab5e3579ff803c03eb7d065eb71', 'timestamp': '', 'source': 'github', 'line_count': 294, 'max_line_length': 273, 'avg_line_length': 43.285714285714285, 'alnum_prop': 0.6115040075436114, 'repo_name': 'bodar/totallylazy', 'id': 'e2ffd2138578adb44f1099aafed219ce39a427be', 'size': '12726', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/com/googlecode/totallylazy/Maps.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '25'}, {'name': 'Java', 'bytes': '1370497'}, {'name': 'Shell', 'bytes': '919'}, {'name': 'Smalltalk', 'bytes': '41'}]}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="zh"> <head> <!-- Generated by javadoc (1.8.0_144) on Sat Jan 20 18:20:11 CST 2018 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>com.yan.core.controller (yan-demo 0.0.1-SNAPSHOT API)</title> <meta name="date" content="2018-01-20"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> </head> <body> <h1 class="bar"><a href="../../../../com/yan/core/controller/package-summary.html" target="classFrame">com.yan.core.controller</a></h1> <div class="indexContainer"> <h2 title="类">类</h2> <ul title="类"> <li><a href="BaseController.html" title="com.yan.core.controller中的类" target="classFrame">BaseController</a></li> <li><a href="ControllerSupport.html" title="com.yan.core.controller中的类" target="classFrame">ControllerSupport</a></li> </ul> </div> </body> </html>
{'content_hash': '785f7efe2842e861d39689f76b676c67', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 135, 'avg_line_length': 46.77272727272727, 'alnum_prop': 0.6754130223517979, 'repo_name': 'micyo202/yan_demo', 'id': 'f88a9ef7a70af05e6b617cabc122ee3656d54edd', 'size': '1047', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/webapp/resources/javadocs/com/yan/core/controller/package-frame.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '252326'}, {'name': 'HTML', 'bytes': '4431916'}, {'name': 'Java', 'bytes': '557348'}, {'name': 'JavaScript', 'bytes': '653669'}, {'name': 'PLpgSQL', 'bytes': '14689'}]}
#include "src/gpu/GrRenderTask.h" #include "src/gpu/GrRenderTargetPriv.h" #include "src/gpu/GrStencilAttachment.h" #include "src/gpu/GrTextureProxyPriv.h" #include "src/gpu/GrTextureResolveRenderTask.h" uint32_t GrRenderTask::CreateUniqueID() { static std::atomic<uint32_t> nextID{1}; uint32_t id; do { id = nextID++; } while (id == SK_InvalidUniqueID); return id; } GrRenderTask::GrRenderTask(sk_sp<GrSurfaceProxy> target) : fTarget(std::move(target)) , fUniqueID(CreateUniqueID()) , fFlags(0) { } GrRenderTask::~GrRenderTask() { if (fTarget && this == fTarget->getLastRenderTask()) { // Ensure the target proxy doesn't keep hold of a dangling back pointer. fTarget->setLastRenderTask(nullptr); } } #ifdef SK_DEBUG bool GrRenderTask::deferredProxiesAreInstantiated() const { for (int i = 0; i < fDeferredProxies.count(); ++i) { if (!fDeferredProxies[i]->isInstantiated()) { return false; } } return true; } #endif void GrRenderTask::makeClosed(const GrCaps& caps) { if (this->isClosed()) { return; } SkIRect targetUpdateBounds; if (ExpectedOutcome::kTargetDirty == this->onMakeClosed(caps, &targetUpdateBounds)) { SkASSERT(SkIRect::MakeWH(fTarget->width(), fTarget->height()).contains(targetUpdateBounds)); if (fTarget->requiresManualMSAAResolve()) { SkASSERT(fTarget->asRenderTargetProxy()); fTarget->asRenderTargetProxy()->markMSAADirty(targetUpdateBounds); } GrTextureProxy* textureProxy = fTarget->asTextureProxy(); if (textureProxy && GrMipMapped::kYes == textureProxy->mipMapped()) { textureProxy->markMipMapsDirty(); } } if (fTextureResolveTask) { this->addDependency(fTextureResolveTask); fTextureResolveTask->makeClosed(caps); fTextureResolveTask = nullptr; } this->setFlag(kClosed_Flag); } void GrRenderTask::prepare(GrOpFlushState* flushState) { for (int i = 0; i < fDeferredProxies.count(); ++i) { fDeferredProxies[i]->texPriv().scheduleUpload(flushState); } this->onPrepare(flushState); } // Add a GrRenderTask-based dependency void GrRenderTask::addDependency(GrRenderTask* dependedOn) { SkASSERT(!dependedOn->dependsOn(this)); // loops are bad SkASSERT(!this->dependsOn(dependedOn)); // caller should weed out duplicates fDependencies.push_back(dependedOn); dependedOn->addDependent(this); SkDEBUGCODE(this->validate()); } void GrRenderTask::addDependenciesFromOtherTask(GrRenderTask* otherTask) { SkASSERT(otherTask); for (GrRenderTask* task : otherTask->fDependencies) { // The task should not be adding a dependency to itself. SkASSERT(task != this); if (!this->dependsOn(task)) { this->addDependency(task); } } } // Convert from a GrSurface-based dependency to a GrRenderTask one void GrRenderTask::addDependency(GrSurfaceProxy* dependedOn, GrMipMapped mipMapped, GrTextureResolveManager textureResolveManager, const GrCaps& caps) { // If it is still receiving dependencies, this GrRenderTask shouldn't be closed SkASSERT(!this->isClosed()); GrRenderTask* dependedOnTask = dependedOn->getLastRenderTask(); if (dependedOnTask == this) { // self-read - presumably for dst reads. We don't need to do anything in this case. The // XferProcessor will detect what is happening and insert a texture barrier. SkASSERT(GrMipMapped::kNo == mipMapped); // We should never attempt a self-read on a surface that has a separate MSAA renderbuffer. SkASSERT(!dependedOn->requiresManualMSAAResolve()); SkASSERT(!dependedOn->asTextureProxy() || !dependedOn->asTextureProxy()->texPriv().isDeferred()); return; } if (dependedOnTask) { if (this->dependsOn(dependedOnTask) || fTextureResolveTask == dependedOnTask) { return; // don't add duplicate dependencies } // We are closing 'dependedOnTask' here bc the current contents of it are what 'this' // renderTask depends on. We need a break in 'dependedOnTask' so that the usage of // that state has a chance to execute. dependedOnTask->makeClosed(caps); } auto resolveFlags = GrSurfaceProxy::ResolveFlags::kNone; if (dependedOn->requiresManualMSAAResolve()) { auto* renderTargetProxy = dependedOn->asRenderTargetProxy(); SkASSERT(renderTargetProxy); if (renderTargetProxy->isMSAADirty()) { resolveFlags |= GrSurfaceProxy::ResolveFlags::kMSAA; } } GrTextureProxy* textureProxy = dependedOn->asTextureProxy(); if (GrMipMapped::kYes == mipMapped) { SkASSERT(textureProxy); if (GrMipMapped::kYes != textureProxy->mipMapped()) { // There are some cases where we might be given a non-mipmapped texture with a mipmap // filter. See skbug.com/7094. mipMapped = GrMipMapped::kNo; } else if (textureProxy->mipMapsAreDirty()) { resolveFlags |= GrSurfaceProxy::ResolveFlags::kMipMaps; } } // Does this proxy have msaa to resolve and/or mipmaps to regenerate? if (GrSurfaceProxy::ResolveFlags::kNone != resolveFlags) { if (!fTextureResolveTask) { fTextureResolveTask = textureResolveManager.newTextureResolveRenderTask(caps); } fTextureResolveTask->addProxy(sk_ref_sp(dependedOn), resolveFlags, caps); // addProxy() should have closed the texture proxy's previous task. SkASSERT(!dependedOnTask || dependedOnTask->isClosed()); SkASSERT(dependedOn->getLastRenderTask() == fTextureResolveTask); #ifdef SK_DEBUG // addProxy() should have called addDependency (in this instance, recursively) on // fTextureResolveTask. if (dependedOnTask) { SkASSERT(fTextureResolveTask->dependsOn(dependedOnTask)); } if (textureProxy && textureProxy->texPriv().isDeferred()) { SkASSERT(fTextureResolveTask->fDeferredProxies.back() == textureProxy); } // The GrTextureResolveRenderTask factory should have also marked the proxy clean, set the // last renderTask on the textureProxy to textureResolveTask, and closed textureResolveTask. if (GrRenderTargetProxy* renderTargetProxy = dependedOn->asRenderTargetProxy()) { SkASSERT(!renderTargetProxy->isMSAADirty()); } if (textureProxy) { SkASSERT(!textureProxy->mipMapsAreDirty()); } SkASSERT(dependedOn->getLastRenderTask() == fTextureResolveTask); #endif return; } if (textureProxy && textureProxy->texPriv().isDeferred()) { fDeferredProxies.push_back(textureProxy); } if (dependedOnTask) { this->addDependency(dependedOnTask); } } bool GrRenderTask::dependsOn(const GrRenderTask* dependedOn) const { for (int i = 0; i < fDependencies.count(); ++i) { if (fDependencies[i] == dependedOn) { return true; } } return false; } void GrRenderTask::addDependent(GrRenderTask* dependent) { fDependents.push_back(dependent); } #ifdef SK_DEBUG bool GrRenderTask::isDependedent(const GrRenderTask* dependent) const { for (int i = 0; i < fDependents.count(); ++i) { if (fDependents[i] == dependent) { return true; } } return false; } void GrRenderTask::validate() const { // TODO: check for loops and duplicates for (int i = 0; i < fDependencies.count(); ++i) { SkASSERT(fDependencies[i]->isDependedent(this)); } } #endif void GrRenderTask::closeThoseWhoDependOnMe(const GrCaps& caps) { for (int i = 0; i < fDependents.count(); ++i) { if (!fDependents[i]->isClosed()) { fDependents[i]->makeClosed(caps); } } } bool GrRenderTask::isInstantiated() const { // Some renderTasks (e.g. GrTransferFromRenderTask) don't have a target. if (!fTarget) { return true; } if (!fTarget->isInstantiated()) { return false; } int minStencilSampleCount = (fTarget->asRenderTargetProxy()) ? fTarget->asRenderTargetProxy()->numStencilSamples() : 0; if (minStencilSampleCount) { GrRenderTarget* rt = fTarget->peekRenderTarget(); SkASSERT(rt); GrStencilAttachment* stencil = rt->renderTargetPriv().getStencilAttachment(); if (!stencil) { return false; } SkASSERT(stencil->numSamples() >= minStencilSampleCount); } GrSurface* surface = fTarget->peekSurface(); if (surface->wasDestroyed()) { return false; } return true; } #ifdef SK_DEBUG void GrRenderTask::dump(bool printDependencies) const { SkDebugf("--------------------------------------------------------------\n"); SkDebugf("renderTaskID: %d - proxyID: %d - surfaceID: %d\n", fUniqueID, fTarget ? fTarget->uniqueID().asUInt() : -1, fTarget && fTarget->peekSurface() ? fTarget->peekSurface()->uniqueID().asUInt() : -1); if (printDependencies) { SkDebugf("I rely On (%d): ", fDependencies.count()); for (int i = 0; i < fDependencies.count(); ++i) { SkDebugf("%d, ", fDependencies[i]->fUniqueID); } SkDebugf("\n"); SkDebugf("(%d) Rely On Me: ", fDependents.count()); for (int i = 0; i < fDependents.count(); ++i) { SkDebugf("%d, ", fDependents[i]->fUniqueID); } SkDebugf("\n"); } } #endif
{'content_hash': 'aaa422eb983a158ba2c12d9bfdf4498b', 'timestamp': '', 'source': 'github', 'line_count': 296, 'max_line_length': 100, 'avg_line_length': 33.0777027027027, 'alnum_prop': 0.6313961801654581, 'repo_name': 'youtube/cobalt', 'id': 'a69c48ba0cc105eb4876f4e03bc68858d0e382ca', 'size': '9933', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'third_party/skia/src/gpu/GrRenderTask.cpp', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []}
package com.evolveum.midpoint.web.component.progress; import com.evolveum.midpoint.schema.ResourceShadowDiscriminator; import com.evolveum.midpoint.web.component.util.SimplePanel; import com.evolveum.midpoint.web.page.admin.server.dto.OperationResultStatusIcon; import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultStatusType; import org.apache.wicket.AttributeModifier; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.list.ListView; import org.apache.wicket.model.AbstractReadOnlyModel; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import java.util.List; import static com.evolveum.midpoint.model.api.ProgressInformation.ActivityType.RESOURCE_OBJECT_OPERATION; import static com.evolveum.midpoint.web.component.progress.ProgressReportActivityDto.ResourceOperationResult; /** * @author mederly */ public class ProgressPanel extends SimplePanel<ProgressDto> { private static final String ID_CONTENTS_PANEL = "contents"; private static final String ID_ACTIVITIES = "progressReportActivities"; private static final String ID_ACTIVITY_DESCRIPTION = "description"; private static final String ID_ACTIVITY_STATE = "status"; private static final String ID_ACTIVITY_COMMENT = "comment"; private static final String ID_LOG_ITEMS = "logItems"; private static final String ID_LOG_ITEM = "logItem"; private static final String ID_EXECUTION_TIME = "executionTime"; private long operationStartTime; // if 0, operation hasn't start yet private long operationDurationTime; // if >0, operation has finished private WebMarkupContainer contentsPanel; public ProgressPanel(String id) { super(id); } public ProgressPanel(String id, IModel<ProgressDto> model) { super(id, model); } protected void initLayout() { contentsPanel = new WebMarkupContainer(ID_CONTENTS_PANEL); contentsPanel.setOutputMarkupId(true); add(contentsPanel); ListView statusItemsListView = new ListView<ProgressReportActivityDto>(ID_ACTIVITIES, new AbstractReadOnlyModel<List<ProgressReportActivityDto>>() { @Override public List<ProgressReportActivityDto> getObject() { ProgressDto progressDto = ProgressPanel.this.getModelObject(); return progressDto.getProgressReportActivities(); } }) { protected void populateItem(final ListItem<ProgressReportActivityDto> item) { item.add(new Label(ID_ACTIVITY_DESCRIPTION, new AbstractReadOnlyModel<String>() { @Override public String getObject() { ProgressReportActivityDto si = item.getModelObject(); if (si.getActivityType() == RESOURCE_OBJECT_OPERATION && si.getResourceShadowDiscriminator() != null) { ResourceShadowDiscriminator rsd = si.getResourceShadowDiscriminator(); return createStringResource(rsd.getKind()).getString() + " (" + rsd.getIntent() + ") on " + si.getResourceName(); // TODO correct i18n } else { return createStringResource(si.getActivityType()).getString(); } } })); item.add(createImageLabel(ID_ACTIVITY_STATE, new AbstractReadOnlyModel<String>() { @Override public String getObject() { OperationResultStatusType statusType = item.getModelObject().getStatus(); if (statusType == null) { return null; } else { return OperationResultStatusIcon.parseOperationalResultStatus(statusType).getIcon(); } } }, new AbstractReadOnlyModel<String>() { @Override public String getObject() { // TODO why this does not work??? OperationResultStatusType statusType = item.getModelObject().getStatus(); // TODO i18n if (statusType == null) { return null; } else { return statusType.toString(); } } } )); item.add(new Label(ID_ACTIVITY_COMMENT, new AbstractReadOnlyModel<String>() { @Override public String getObject() { ProgressReportActivityDto si = item.getModelObject(); if (si.getResourceName() != null || si.getResourceOperationResultList() != null) { StringBuilder sb = new StringBuilder(); boolean first = true; if (si.getResourceOperationResultList() != null) { for (ResourceOperationResult ror : si.getResourceOperationResultList()) { if (!first) { sb.append(", "); } else { first = false; } sb.append(createStringResource("ChangeType." + ror.getChangeType()).getString()); sb.append(":"); sb.append(createStringResource(ror.getResultStatus()).getString()); } } if (si.getResourceObjectName() != null) { if (!first) { sb.append(" -> "); } sb.append(si.getResourceObjectName()); } return sb.toString(); } else { return null; } } })); } private Label createImageLabel(String id, IModel<String> cssClass, IModel<String> title) { Label label = new Label(id); label.add(AttributeModifier.replace("class", cssClass)); label.add(AttributeModifier.replace("title", title)); // does not work, currently return label; } }; contentsPanel.add(statusItemsListView); ListView logItemsListView = new ListView(ID_LOG_ITEMS, new AbstractReadOnlyModel<List>() { @Override public List getObject() { ProgressDto progressDto = ProgressPanel.this.getModelObject(); return progressDto.getLogItems(); } }) { protected void populateItem(ListItem item) { item.add(new Label(ID_LOG_ITEM, item.getModel())); } }; contentsPanel.add(logItemsListView); Label executionTime = new Label(ID_EXECUTION_TIME, new AbstractReadOnlyModel<String>() { @Override public String getObject() { if (operationDurationTime > 0) { return createStringResource("ProgressPanel.ExecutionTimeWhenFinished", operationDurationTime).getString(); } else if (operationStartTime > 0) { return createStringResource("ProgressPanel.ExecutionTimeWhenRunning", (System.currentTimeMillis()-operationStartTime)/1000).getString(); } else { return null; } } }); contentsPanel.add(executionTime); } // Note: do not setVisible(false) on the progress panel itself - it will disable AJAX refresh functionality attached to it. // Use the following two methods instead. public void show() { contentsPanel.setVisible(true); } public void hide() { contentsPanel.setVisible(false); } public void recordExecutionStart() { operationDurationTime = 0; operationStartTime = System.currentTimeMillis(); } public void recordExecutionStop() { operationDurationTime = System.currentTimeMillis() - operationStartTime; } }
{'content_hash': 'c66fa73aa9af6f8089e3835c17861b56', 'timestamp': '', 'source': 'github', 'line_count': 195, 'max_line_length': 156, 'avg_line_length': 45.656410256410254, 'alnum_prop': 0.5466696619117152, 'repo_name': 'gureronder/midpoint', 'id': '93c3ae246f6fac8e507885f04e6d00b878ea1f7a', 'size': '9504', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/progress/ProgressPanel.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '176525'}, {'name': 'Groovy', 'bytes': '10361'}, {'name': 'HTML', 'bytes': '450709'}, {'name': 'Java', 'bytes': '19619257'}, {'name': 'JavaScript', 'bytes': '70636'}, {'name': 'PLSQL', 'bytes': '2171'}, {'name': 'PLpgSQL', 'bytes': '3307'}, {'name': 'SQLPL', 'bytes': '4091'}, {'name': 'Shell', 'bytes': '3606'}]}
package rxquery; import junit.framework.TestCase; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import rx.Subscription; import rx.functions.Action0; import rx.functions.Action1; import rx.functions.Func0; import rx.schedulers.TestScheduler; public class RxQueryTest extends TestCase { public static final String QUERY_RESULT = "query_result"; public void testImmediate() throws Exception { TestScheduler background = new TestScheduler(); TestScheduler foreground = new TestScheduler(); Action1<Action0> executor = new Action1<Action0>() { @Override public void call(Action0 action0) { action0.call(); } }; RxQuery q = new RxQuery(background, foreground, 200, executor); final AtomicLong queryThread = new AtomicLong(); final AtomicLong resultThread = new AtomicLong(); q.immediate(new Func0<String>() { @Override public String call() { queryThread.set(Thread.currentThread().getId()); return QUERY_RESULT; } }).subscribe(new Action1<String>() { @Override public void call(String s) { assertEquals(QUERY_RESULT, s); resultThread.set(Thread.currentThread().getId()); } }); assertTrue(resultThread.get() != 0); assertEquals(queryThread.get(), resultThread.get()); assertEquals(queryThread.get(), Thread.currentThread().getId()); } public void testUpdatable() throws Exception { TestScheduler background = new TestScheduler(); TestScheduler foreground = new TestScheduler(); Action1<Action0> executor = new Action1<Action0>() { @Override public void call(Action0 action0) { action0.call(); } }; RxQuery q = new RxQuery(background, foreground, 200, executor); final AtomicInteger queryCounter = new AtomicInteger(); Subscription subscription1 = q.updatable("data", new Func0<String>() { @Override public String call() { queryCounter.incrementAndGet(); return QUERY_RESULT; } }).subscribe(); foreground.advanceTimeBy(300, TimeUnit.MILLISECONDS); assertEquals(1, queryCounter.get()); final Action0 action0 = new Action0() { @Override public void call() { } }; Subscription subscription2 = q.execution("data", new Action0() { @Override public void call() { action0.call(); } }).subscribe(); background.advanceTimeBy(300, TimeUnit.MILLISECONDS); foreground.advanceTimeBy(300, TimeUnit.MILLISECONDS); assertEquals(2, queryCounter.get()); } public void testExecution() throws Exception { TestScheduler background = new TestScheduler(); TestScheduler foreground = new TestScheduler(); Action1<Action0> executor = new Action1<Action0>() { @Override public void call(Action0 action0) { action0.call(); } }; RxQuery q = new RxQuery(background, foreground, 200, executor); final AtomicInteger queryCounter = new AtomicInteger(); final AtomicInteger executionCounter = new AtomicInteger(); q.updatable("data", new Func0<String>() { @Override public String call() { queryCounter.incrementAndGet(); return QUERY_RESULT; } }).subscribe(); q.execution("data", new Action0() { @Override public void call() { executionCounter.incrementAndGet(); } }).subscribe(); background.advanceTimeBy(300, TimeUnit.MILLISECONDS); assertEquals(1, executionCounter.get()); assertEquals(2, queryCounter.get()); q.execution("da!!!!!!ta", new Action0() { @Override public void call() { executionCounter.incrementAndGet(); } }).subscribe(); background.advanceTimeBy(300, TimeUnit.MILLISECONDS); assertEquals(2, queryCounter.get()); } }
{'content_hash': '6c6b7674ae84fc2c32e168c564c9f0a5', 'timestamp': '', 'source': 'github', 'line_count': 139, 'max_line_length': 78, 'avg_line_length': 31.93525179856115, 'alnum_prop': 0.584365848164001, 'repo_name': 'konmik/RxQuery', 'id': '497ef4c540d8be329a9c0e95065d899a3f53e5e3', 'size': '4439', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'rxquery/src/test/java/rxquery/RxQueryTest.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '10272'}]}
namespace aura { class Window; namespace client { class ScreenPositionClient; } } namespace display { class Display; class ManagedDisplayInfo; } namespace ash { class AshWindowTreeHost; class MirrorWindowTestApi; // An object that copies the content of the primary root window to a // mirror window. This also draws a mouse cursor as the mouse cursor // is typically drawn by the window system. class ASH_EXPORT MirrorWindowController : public aura::WindowTreeHostObserver, public AshWindowTreeHostDelegate { public: MirrorWindowController(); MirrorWindowController(const MirrorWindowController&) = delete; MirrorWindowController& operator=(const MirrorWindowController&) = delete; ~MirrorWindowController() override; // Updates the root window's bounds using |display_info|. // Creates the new root window if one doesn't exist. void UpdateWindow( const std::vector<display::ManagedDisplayInfo>& display_info); // Same as above, but using existing display info // for the mirrored display. void UpdateWindow(); // Close the mirror window if they're not necessary any longer. void CloseIfNotNecessary(); // aura::WindowTreeHostObserver overrides: void OnHostResized(aura::WindowTreeHost* host) override; // Returns the display::Display for the mirroring root window. display::Display GetDisplayForRootWindow(const aura::Window* root) const; // Returns the AshWindwoTreeHost created for |display_id|. AshWindowTreeHost* GetAshWindowTreeHostForDisplayId(int64_t display_id); // Returns all root windows hosting mirroring displays. aura::Window::Windows GetAllRootWindows() const; // AshWindowTreeHostDelegate: const display::Display* GetDisplayById(int64_t display_id) const override; void SetCurrentEventTargeterSourceHost( aura::WindowTreeHost* targeter_src_host) override; const aura::WindowTreeHost* current_event_targeter_src_host() const { return current_event_targeter_src_host_; } private: friend class MirrorWindowTestApi; struct MirroringHostInfo; // Close the mirror window. When |delay_host_deletion| is true, the window // tree host will be deleted in an another task on UI thread. This is // necessary to safely delete the WTH that is currently handling input events. void Close(bool delay_host_deletion); void CloseAndDeleteHost(MirroringHostInfo* host_info, bool delay_host_deletion); typedef std::map<int64_t, MirroringHostInfo*> MirroringHostInfoMap; MirroringHostInfoMap mirroring_host_info_map_; aura::WindowTreeHost* current_event_targeter_src_host_; display::DisplayManager::MultiDisplayMode multi_display_mode_; // The id of the display being mirrored. int64_t reflecting_source_id_ = display::kInvalidDisplayId; std::unique_ptr<aura::client::ScreenPositionClient> screen_position_client_; }; } // namespace ash #endif // ASH_DISPLAY_MIRROR_WINDOW_CONTROLLER_H_
{'content_hash': 'd22c1466f3e9afa7fb40d8e04d4204ff', 'timestamp': '', 'source': 'github', 'line_count': 91, 'max_line_length': 80, 'avg_line_length': 32.67032967032967, 'alnum_prop': 0.7510931718802556, 'repo_name': 'scheib/chromium', 'id': '6deca66b6d9972ea7031508fec7054f1de0dba04', 'size': '3570', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'ash/display/mirror_window_controller.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []}
import { IntersectionObserverPolyfill, nativeIntersectionObserverSupported, } from '../../../../src/intersection-observer-polyfill'; import { VisibilityManagerForDoc, VisibilityManagerForEmbed, } from '../visibility-manager'; import {VisibilityState} from '../../../../src/visibility-state'; import {documentStateFor} from '../../../../src/services'; import {layoutRectLtwh, rectIntersection} from '../../../../src/layout-rect'; class IntersectionObserverStub { constructor(callback, options) { this.callback = callback; this.options = options; this.elements = []; this.disconnected = false; } observe(element) { if (this.disconnected) { throw new Error('disconnected'); } if (!this.elements.includes(element)) { this.elements.push(element); } } unobserve(element) { if (this.disconnected) { throw new Error('disconnected'); } const index = this.elements.indexOf(element); if (index == -1) { throw new Error('element not found'); } this.elements.splice(index, 1); } disconnect() { if (this.disconnected) { throw new Error('disconnected'); } this.disconnected = true; } } describes.fakeWin('VisibilityManagerForDoc', {amp: true}, env => { let win; let ampdoc; let clock; let viewer, viewport; let root; let startVisibilityHandlerCount; let eventResolver, eventPromise; beforeEach(() => { win = env.win; ampdoc = env.ampdoc; clock = sandbox.useFakeTimers(); clock.tick(1); viewer = win.services.viewer.obj; sandbox.stub(viewer, 'getFirstVisibleTime', () => 1); viewport = win.services.viewport.obj; startVisibilityHandlerCount = viewer.visibilityObservable_.getHandlerCount(); root = new VisibilityManagerForDoc(ampdoc); win.IntersectionObserver = IntersectionObserverStub; win.IntersectionObserverEntry = function() {}; win.IntersectionObserverEntry.prototype.intersectionRatio = 1; eventPromise = new Promise(resolve => { eventResolver = resolve; }); }); it('should initialize correctly backgrounded', () => { viewer.setVisibilityState_(VisibilityState.HIDDEN); root = new VisibilityManagerForDoc(ampdoc); expect(root.parent).to.be.null; expect(root.ampdoc).to.equal(ampdoc); expect(root.getStartTime()).to.equal(viewer.getFirstVisibleTime()); expect(root.isBackgrounded()).to.be.true; expect(root.isBackgroundedAtStart()).to.be.true; expect(root.children_).to.be.null; // Don't take extra memory. // Will be initialized lazily expect(root.intersectionObserver_).to.be.null; // Root model starts invisible. expect(root.getRootVisibility()).to.equal(0); }); it('should initialize correctly foregrounded', () => { expect(root.parent).to.be.null; expect(root.ampdoc).to.equal(ampdoc); expect(root.getStartTime()).to.equal(viewer.getFirstVisibleTime()); expect(root.isBackgrounded()).to.be.false; expect(root.isBackgroundedAtStart()).to.be.false; // Will be initialized lazily expect(root.intersectionObserver_).to.be.null; // Root model starts invisible. expect(root.parent).to.be.null; expect(root.getRootVisibility()).to.equal(1); }); it('should switch visibility based on viewer for main doc', () => { expect(viewer.visibilityObservable_.getHandlerCount()) .equal(startVisibilityHandlerCount + 1); expect(root.getRootVisibility()).to.equal(1); // Go prerender. viewer.setVisibilityState_(VisibilityState.PRERENDER); expect(root.getRootVisibility()).to.equal(0); // Go hidden. viewer.setVisibilityState_(VisibilityState.HIDDEN); expect(root.getRootVisibility()).to.equal(0); // Go visible. viewer.setVisibilityState_(VisibilityState.VISIBLE); expect(root.getRootVisibility()).to.equal(1); expect(root.getStartTime()).to.equal(viewer.getFirstVisibleTime()); }); it('should switch visibility for in-a-box', () => { win.AMP_MODE = {runtime: 'inabox'}; root = new VisibilityManagerForDoc(ampdoc); // Check observer is correctly set. const inOb = root.intersectionObserver_; expect(inOb).to.be.instanceOf(IntersectionObserverStub); expect(inOb.elements).to.contain(win.document.documentElement); // Start as invisible. expect(root.getRootVisibility()).to.equal(0); // Unrelated event. const otherTarget = win.document.createElement('div'); inOb.callback([{ target: otherTarget, intersectionRatio: 0.3, }]); expect(root.getRootVisibility()).to.equal(0); // Move to the viewport. inOb.callback([ { target: otherTarget, intersectionRatio: 0.5, }, { target: win.document.documentElement, intersectionRatio: 0.3, }, ]); expect(root.getRootVisibility()).to.equal(0.3); // Back out of viewport. inOb.callback([ { target: win.document.documentElement, intersectionRatio: 0, }, ]); expect(root.getRootVisibility()).to.equal(0); }); it('should switch root model to no-visibility on dispose', () => { expect(root.getRootVisibility()).to.equal(1); root.dispose(); expect(root.getRootVisibility()).to.equal(0); }); it('should dispose everything', () => { const modelsDisposed = sandbox.spy(); const modelsCalled = sandbox.spy(); const otherTarget = win.document.createElement('div'); const spec = {totalTimeMin: 10}; root.listenRoot(spec, null, null, modelsCalled); root.listenElement(otherTarget, spec, null, null, modelsCalled); root.listenElement( otherTarget, {totalTimeMin: 20}, null, null, modelsCalled); expect(root.models_).to.have.length(3); root.models_.forEach(model => { model.unsubscribe(modelsDisposed); }); const otherUnsubscribes = sandbox.spy(); root.unsubscribe(otherUnsubscribes); root.unsubscribe(otherUnsubscribes); const inOb = root.intersectionObserver_; expect(inOb.elements).to.contain(otherTarget); root.dispose(); // All other models have been disposed. expect(root.models_).to.have.length(0); expect(modelsCalled).to.not.be.called; expect(modelsDisposed.callCount).to.equal(3); // All other unsubscribes have been called. expect(otherUnsubscribes.callCount).to.equal(2); // Viewer and viewport have been unsubscribed. expect(viewer.visibilityObservable_.getHandlerCount()) .equal(startVisibilityHandlerCount); // Intersection observer disconnected. expect(inOb.disconnected).to.be.true; expect(root.intersectionObserver_).to.be.null; expect(inOb.elements).to.not.contain(otherTarget); }); it('should polyfill and dispose intersection observer', () => { delete win.IntersectionObserver; const startScrollCount = viewport.scrollObservable_.getHandlerCount(); const startChangeCount = viewport.changeObservable_.getHandlerCount(); // Check observer is correctly set. const inOb = root.getIntersectionObserver_(); expect(inOb).to.be.instanceOf(IntersectionObserverPolyfill); expect(viewport.scrollObservable_.getHandlerCount()) .to.equal(startScrollCount + 1); expect(viewport.changeObservable_.getHandlerCount()) .to.equal(startChangeCount + 1); root.dispose(); expect(viewport.scrollObservable_.getHandlerCount()) .to.equal(startScrollCount); expect(viewport.changeObservable_.getHandlerCount()) .to.equal(startChangeCount); }); it('should support polyfill on non-amp root element', () => { delete win.IntersectionObserver; const inOb = root.getIntersectionObserver_(); const rootElement = win.document.documentElement; root.listenElement(rootElement, {}, null, null, eventResolver); expect(root.models_).to.have.length(1); const model = root.models_[0]; expect(inOb.observeEntries_).to.have.length(1); // AMP API is polyfilled. expect(rootElement.getLayoutBox).to.be.function; expect(rootElement.getOwner()).to.be.null; // Starts as invisible. expect(model.getVisibility_()).to.equal(0); // Trigger tick. sandbox.stub(viewport, 'getRect', () => { return layoutRectLtwh(0, 0, 100, 100); }); sandbox.stub(viewport, 'getLayoutRect', element => { if (element == rootElement) { return layoutRectLtwh(0, 50, 100, 100); } return null; }); expect(rootElement.getLayoutBox()) .to.contain({left: 0, top: 50, width: 100, height: 100}); viewport.scrollObservable_.fire({type: 'scroll'}); expect(model.getVisibility_()).to.equal(0.5); return eventPromise.then(() => { expect(inOb.observeEntries_).to.have.length(0); }); }); it('should listen on root', () => { clock.tick(1); const disposed = sandbox.spy(); const spec = {totalTimeMin: 10}; root.listenRoot(spec, null, null, eventResolver); expect(root.models_).to.have.length(1); const model = root.models_[0]; model.unsubscribe(disposed); expect(model.spec_.totalTimeMin).to.equal(10); expect(model.getVisibility_()).to.equal(1); // Go invisible. root.setRootVisibility(0); expect(model.getVisibility_()).to.equal(0); // Back to visible. root.setRootVisibility(1); expect(model.getVisibility_()).to.equal(1); // Fire event. clock.tick(11); return eventPromise.then(state => { expect(disposed).to.be.calledOnce; expect(root.models_).to.have.length(0); expect(state.totalVisibleTime).to.equal(10); expect(state.firstSeenTime).to.equal(1); expect(state.backgrounded).to.equal(0); expect(state.backgroundedAtStart).to.equal(0); expect(state.totalTime).to.equal(12); }); }); it('should listen on root with ready signal', () => { clock.tick(1); const disposed = sandbox.spy(); const spec = {totalTimeMin: 0}; const readyPromise = Promise.resolve().then(() => { clock.tick(21); }); root.listenRoot(spec, readyPromise, null, eventResolver); expect(root.models_).to.have.length(1); const model = root.models_[0]; model.unsubscribe(disposed); // Blocked by ready promise: visibility == 0. expect(model.getVisibility_()).to.equal(0); // Fire event. return eventPromise.then(state => { expect(model.getVisibility_()).to.equal(1); expect(disposed).to.be.calledOnce; expect(root.models_).to.have.length(0); expect(state.totalVisibleTime).to.equal(0); expect(state.firstSeenTime).to.equal(22); expect(state.backgrounded).to.equal(0); expect(state.backgroundedAtStart).to.equal(0); expect(state.totalTime).to.equal(22); }); }); it('should pass func to create readyReportPromise to model', () => { let testPromiseResolver; const disposed = sandbox.spy(); const testPromise = new Promise(resolve => { testPromiseResolver = resolve; }); root.listenRoot({}, null, () => { return testPromise; }, eventResolver); expect(root.models_).to.have.length(1); const model = root.models_[0]; model.unsubscribe(disposed); clock.tick(11); testPromiseResolver(); return eventPromise.then(state => { expect(disposed).to.be.calledOnce; expect(state.totalVisibleTime).to.equal(11); expect(state.totalTime).to.equal(11); expect(state.maxContinuousVisibleTime).to.equal(11); }); }); it('should unlisten root', () => { clock.tick(1); const disposed = sandbox.spy(); const spec = {totalTimeMin: 10}; const unlisten = root.listenRoot(spec, null, null, eventResolver); expect(root.models_).to.have.length(1); expect(Object.keys(root.trackedElements_)).to.have.length(0); expect(root.getIntersectionObserver_().elements).to.have.length(0); const model = root.models_[0]; model.unsubscribe(disposed); unlisten(); expect(root.models_).to.have.length(0); expect(disposed).to.be.calledOnce; }); it('should listen on a element', () => { clock.tick(1); const disposed = sandbox.spy(); const target = win.document.createElement('div'); const spec = {totalTimeMin: 10}; root.listenElement(target, spec, null, null, eventResolver); expect(root.models_).to.have.length(1); const model = root.models_[0]; model.unsubscribe(disposed); expect(model.spec_.totalTimeMin).to.equal(10); expect(target.__AMP_VIS_ID).to.be.ok; expect(root.trackedElements_[target.__AMP_VIS_ID].element).to.equal(target); const inOb = root.getIntersectionObserver_(); expect(inOb.elements).to.contain(target); expect(model.getVisibility_()).to.equal(0); // In viewport. inOb.callback([{ target, intersectionRatio: 0.3, }]); expect(model.getVisibility_()).to.equal(0.3); // Go invisible on root. root.setRootVisibility(0); expect(model.getVisibility_()).to.equal(0); // Back to visible on root. root.setRootVisibility(1); expect(model.getVisibility_()).to.equal(0.3); // Fire event. clock.tick(11); return eventPromise.then(state => { expect(disposed).to.be.calledOnce; expect(root.models_).to.have.length(0); expect(root.trackedElements_[target.__AMP_VIS_ID]).to.not.exist; expect(inOb.elements).to.not.contain(target); expect(state.totalVisibleTime).to.equal(10); expect(state.firstSeenTime).to.equal(1); expect(state.backgrounded).to.equal(0); expect(state.backgroundedAtStart).to.equal(0); expect(state.totalTime).to.equal(12); expect(state.elementX).to.be.undefined; }); }); it('should protect from invalid intersection values', () => { const target = win.document.createElement('div'); root.listenElement(target, {}, null, null, eventResolver); expect(root.models_).to.have.length(1); const model = root.models_[0]; const inOb = root.getIntersectionObserver_(); expect(model.getVisibility_()).to.equal(0); // Valid value. inOb.callback([{target, intersectionRatio: 0.3}]); expect(model.getVisibility_()).to.equal(0.3); // Invalid negative value. inOb.callback([{target, intersectionRatio: -0.01}]); expect(model.getVisibility_()).to.equal(0); inOb.callback([{target, intersectionRatio: -1000}]); expect(model.getVisibility_()).to.equal(0); // Invalid overflow value. inOb.callback([{target, intersectionRatio: 1.01}]); expect(model.getVisibility_()).to.equal(1); inOb.callback([{target, intersectionRatio: 1000}]); expect(model.getVisibility_()).to.equal(1); }); it('should listen on a element with different specs', () => { clock.tick(1); const inOb = root.getIntersectionObserver_(); const target = win.document.createElement('div'); // Listen to the first spec. const disposed1 = sandbox.spy(); const spec1 = {totalTimeMin: 10}; root.listenElement(target, spec1, null, null, eventResolver); expect(root.models_).to.have.length(1); const model1 = root.models_[0]; expect(model1.spec_.totalTimeMin).to.equal(10); model1.unsubscribe(disposed1); expect(target.__AMP_VIS_ID).to.be.ok; const trackedElement = root.trackedElements_[target.__AMP_VIS_ID]; expect(trackedElement.element).to.equal(target); expect(trackedElement.listeners).to.have.length(1); expect(inOb.elements).to.contain(target); // In viewport. inOb.callback([{ target, intersectionRatio: 0.3, }]); expect(model1.getVisibility_()).to.equal(0.3); expect(trackedElement.intersectionRatio).to.equal(0.3); // Second spec on the same element. const disposed2 = sandbox.spy(); const spec2 = {totalTimeMin: 20}; let eventResolver2; const eventPromise2 = new Promise(resolve => { eventResolver2 = resolve; }); root.listenElement(target, spec2, null, null, eventResolver2); expect(root.models_).to.have.length(2); const model2 = root.models_[1]; expect(model2.spec_.totalTimeMin).to.equal(20); model2.unsubscribe(disposed2); expect(trackedElement.listeners).to.have.length(2); // Immediately visible. expect(model2.getVisibility_()).to.equal(0.3); // Fire the first event. clock.tick(11); return eventPromise.then(state => { // First event fired. The first model should be cleaned up, but not // the other. expect(state.totalVisibleTime).to.equal(10); expect(disposed1).to.be.calledOnce; expect(root.models_).to.have.length(1); expect(root.trackedElements_[target.__AMP_VIS_ID]) .to.equal(trackedElement); expect(trackedElement.listeners).to.have.length(1); expect(inOb.elements).to.contain(target); // Fire the second event. clock.tick(10); return eventPromise2; }).then(state => { // Second event fired. Everything should be released now. expect(state.totalVisibleTime).to.equal(20); expect(disposed2).to.be.calledOnce; expect(root.models_).to.have.length(0); expect(root.trackedElements_[target.__AMP_VIS_ID]).to.not.exist; expect(trackedElement.listeners).to.have.length(0); expect(inOb.elements).to.not.contain(target); }); }); it('should listen on a resource', () => { clock.tick(1); const target = win.document.createElement('div'); const resource = { getLayoutBox() { return {top: 10, left: 11, width: 110, height: 111}; }, }; const resources = win.services.resources.obj; sandbox.stub(resources, 'getResourceForElementOptional', () => resource); const spec = {totalTimeMin: 10}; root.listenElement(target, spec, null, null, eventResolver); const inOb = root.getIntersectionObserver_(); inOb.callback([{ target, intersectionRatio: 0.3, }]); // Fire event. clock.tick(11); return eventPromise.then(state => { expect(state.totalVisibleTime).to.equal(10); expect(state.elementY).to.equal(10); expect(state.elementX).to.equal(11); expect(state.elementWidth).to.equal(110); expect(state.elementHeight).to.equal(111); }); }); }); describes.realWin('EmbedAnalyticsRoot', { amp: {ampdoc: 'fie'}, }, env => { let parentWin; let win; let ampdoc; let embed; let clock; let viewer; let parentRoot; let root; let inob; beforeEach(() => { parentWin = env.parentWin; win = env.win; ampdoc = env.ampdoc; embed = env.embed; embed.host = ampdoc.win.document.createElement('amp-host'); clock = sandbox.useFakeTimers(); clock.tick(1); viewer = parentWin.services.viewer.obj; sandbox.stub(viewer, 'getFirstVisibleTime', () => 1); parentRoot = new VisibilityManagerForDoc(ampdoc); parentWin.IntersectionObserver = IntersectionObserverStub; parentWin.IntersectionObserverEntry = function() {}; parentWin.IntersectionObserverEntry.prototype.intersectionRatio = 1; root = new VisibilityManagerForEmbed(parentRoot, embed); inob = parentRoot.getIntersectionObserver_(); }); it('should dispose with parent', () => { const unsubscribeSpy = sandbox.spy(); root.unsubscribe(unsubscribeSpy); expect(parentRoot.children_).to.have.length(1); expect(parentRoot.children_[0]).to.equal(root); parentRoot.dispose(); expect(parentRoot.children_).to.have.length(0); expect(unsubscribeSpy).to.be.calledOnce; }); it('should remove from parent when disposed', () => { const unsubscribeSpy = sandbox.spy(); root.unsubscribe(unsubscribeSpy); expect(parentRoot.children_).to.have.length(1); expect(parentRoot.children_[0]).to.equal(root); root.dispose(); expect(parentRoot.children_).to.have.length(0); expect(unsubscribeSpy).to.be.calledOnce; }); it('should initialize correctly backgrounded', () => { viewer.setVisibilityState_(VisibilityState.HIDDEN); root = new VisibilityManagerForEmbed(parentRoot, embed); expect(root.parent).to.equal(parentRoot); expect(root.ampdoc).to.equal(ampdoc); expect(root.getStartTime()).to.equal(embed.getStartTime()); expect(root.isBackgrounded()).to.be.true; expect(root.isBackgroundedAtStart()).to.be.true; // Root model starts invisible. expect(root.getRootVisibility()).to.equal(0); }); it('should initialize correctly foregrounded', () => { expect(root.parent).to.equal(parentRoot); expect(root.ampdoc).to.equal(ampdoc); expect(root.getStartTime()).to.equal(embed.getStartTime()); expect(root.isBackgrounded()).to.be.false; expect(root.isBackgroundedAtStart()).to.be.false; // Root model starts invisible. root.setRootVisibility(1); expect(root.getRootVisibility()).to.equal(1); }); it('should ask parent to observe host element', () => { const id = embed.host.__AMP_VIS_ID; expect(parentRoot.trackedElements_[id]).to.be.ok; root.dispose(); expect(parentRoot.trackedElements_[id]).to.be.undefined; }); it('should delegate observation to parent', () => { const inOb = { observe: sandbox.spy(), unobserve: sandbox.spy(), }; parentRoot.intersectionObserver_ = inOb; const listener = sandbox.spy(); const target = win.document.createElement('div'); // Observe. const unlisten = root.observe(target, listener); expect(inOb.observe).to.be.calledOnce; expect(inOb.observe).to.be.calledWith(target); const id = target.__AMP_VIS_ID; expect(parentRoot.trackedElements_[id]).to.be.ok; // Unobserve. unlisten(); expect(inOb.unobserve).to.be.calledOnce; expect(inOb.unobserve).to.be.calledWith(target); expect(parentRoot.trackedElements_[id]).to.be.undefined; }); it('should depend on parent for visibility', () => { const callbackSpy = sandbox.spy(); const otherTarget = win.document.createElement('div'); root.listenRoot({}, null, null, callbackSpy); expect(root.models_).to.have.length(1); const rootModel = root.models_[0]; root.listenElement(otherTarget, {}, null, null, callbackSpy); expect(root.models_).to.have.length(2); const elementModel = root.models_[1]; // Set up. expect(inob.elements).to.contain(embed.host); expect(inob.elements).to.contain(otherTarget); // Start state. expect(parentRoot.getRootVisibility()).to.equal(1); expect(root.getRootVisibility()).to.equal(0); expect(rootModel.getVisibility_()).to.equal(0); expect(elementModel.getVisibility_()).to.equal(0); // Make root visible. inob.callback([{ target: embed.host, intersectionRatio: 0.5, }]); expect(root.getRootVisibility()).to.equal(0.5); expect(rootModel.getVisibility_()).to.equal(0.5); expect(elementModel.getVisibility_()).to.equal(0); // Make element visible. inob.callback([{ target: otherTarget, intersectionRatio: 0.45, }]); expect(root.getRootVisibility()).to.equal(0.5); expect(rootModel.getVisibility_()).to.equal(0.5); expect(elementModel.getVisibility_()).to.equal(0.45); // Hide parent. viewer.setVisibilityState_(VisibilityState.HIDDEN); expect(parentRoot.getRootVisibility()).to.equal(0); expect(root.getRootVisibility()).to.equal(0); expect(rootModel.getVisibility_()).to.equal(0); expect(elementModel.getVisibility_()).to.equal(0); // Show parent. viewer.setVisibilityState_(VisibilityState.VISIBLE); expect(parentRoot.getRootVisibility()).to.equal(1); expect(root.getRootVisibility()).to.equal(0.5); expect(rootModel.getVisibility_()).to.equal(0.5); expect(elementModel.getVisibility_()).to.equal(0.45); // Hide root. inob.callback([{ target: embed.host, intersectionRatio: 0, }]); expect(root.getRootVisibility()).to.equal(0); expect(rootModel.getVisibility_()).to.equal(0); expect(elementModel.getVisibility_()).to.equal(0); // Update element. inob.callback([{ target: otherTarget, intersectionRatio: 0.55, }]); expect(root.getRootVisibility()).to.equal(0); expect(rootModel.getVisibility_()).to.equal(0); expect(elementModel.getVisibility_()).to.equal(0); // Show root. inob.callback([{ target: embed.host, intersectionRatio: 0.7, }]); expect(root.getRootVisibility()).to.equal(0.7); expect(rootModel.getVisibility_()).to.equal(0.7); expect(elementModel.getVisibility_()).to.equal(0.55); }); }); describes.realWin('VisibilityManager integrated', {amp: true}, env => { let win, doc; let ampdoc; let viewer; let resources; let clock, startTime; let scrollTop; let inObCallback; let observeSpy; let unobserveSpy; let visibility; let ampElement; let eventPromise, eventResolver; let eventPromise2, eventResolver2; let readyPromise, readyResolver; let readyReportPromise, readyReportResolver; beforeEach(() => { win = env.win; doc = win.document; ampdoc = env.ampdoc; viewer = win.services.viewer.obj; resources = win.services.resources.obj; observeSpy = sandbox.stub(); unobserveSpy = sandbox.stub(); const inob = callback => { inObCallback = callback; return { observe: observeSpy, unobserve: unobserveSpy, }; }; if (nativeIntersectionObserverSupported(ampdoc.win)) { sandbox.stub(win, 'IntersectionObserver', inob); } else { win.IntersectionObserver = inob; win.IntersectionObserverEntry = function() {}; win.IntersectionObserverEntry.prototype.intersectionRatio = 0; expect(nativeIntersectionObserverSupported(ampdoc.win)).to.be.true; } readyPromise = new Promise(resolve => { readyResolver = resolve; }); readyReportPromise = new Promise(resolve => { readyReportResolver = resolve; }); eventPromise = new Promise(resolve => { eventResolver = resolve; }); eventPromise2 = new Promise(resolve => { eventResolver2 = resolve; }); const docState = documentStateFor(win); sandbox.stub(docState, 'isHidden', () => false); sandbox.stub(viewer, 'getFirstVisibleTime', () => startTime); ampElement = doc.createElement('amp-img'); ampElement.id = 'abc'; ampElement.setAttribute('width', '100'); ampElement.setAttribute('height', '100'); doc.body.appendChild(ampElement); return new Promise(resolve => { if (resources.getResourceForElementOptional(ampElement)) { resolve(); } else { const interval = setInterval(() => { if (resources.getResourceForElementOptional(ampElement)) { clearInterval(interval); resolve(); } }, 4); } }).then(() => { clock = sandbox.useFakeTimers(); startTime = 10000; clock.tick(startTime); const resource = resources.getResourceForElement(ampElement); scrollTop = 10; sandbox.stub(resource, 'getLayoutBox', () => layoutRectLtwh(0, scrollTop, 100, 100)); }); }); function fireIntersect(intersectPercent) { scrollTop = 100 - intersectPercent; const entry = makeIntersectionEntry( [0, scrollTop, 100, 100], [0, 0, 100, 100]); inObCallback([entry]); } function makeIntersectionEntry(boundingClientRect, rootBounds) { boundingClientRect = layoutRectLtwh.apply(null, boundingClientRect); rootBounds = layoutRectLtwh.apply(null, rootBounds); const intersect = rectIntersection(boundingClientRect, rootBounds); const ratio = (intersect.width * intersect.height) / (boundingClientRect.width * boundingClientRect.height); return { intersectionRect: intersect, boundingClientRect, rootBounds, intersectionRatio: ratio, target: ampElement, }; } function isModelResolved(model) { return !model.eventResolver_; } it('should execute "visible" trigger with simple spec', () => { viewer.setVisibilityState_(VisibilityState.VISIBLE); visibility = new VisibilityManagerForDoc(ampdoc); visibility.listenElement(ampElement, {}, readyPromise, () => { return readyReportPromise; }, eventResolver); return Promise.resolve().then(() => { clock.tick(100); fireIntersect(25); // visible readyResolver(); }).then(() => { clock.tick(5); readyReportResolver(); return eventPromise; }).then(state => { expect(state).to.contains({ backgrounded: 0, backgroundedAtStart: 0, elementHeight: 100, elementWidth: 100, elementX: 0, elementY: 75, firstSeenTime: 100, lastSeenTime: 105, lastVisibleTime: 105, loadTimeVisibility: 25, maxVisiblePercentage: 25, minVisiblePercentage: 25, totalVisibleTime: 5, maxContinuousVisibleTime: 5, }); }); }); it('should triger "visible" with no duration condition', () => { viewer.setVisibilityState_(VisibilityState.VISIBLE); visibility = new VisibilityManagerForDoc(ampdoc); visibility.listenElement( ampElement, {visiblePercentageMin: 20}, readyPromise, null, eventResolver); // add multiple triggers on the same element visibility.listenElement( ampElement, {visiblePercentageMin: 30}, readyPromise, null, eventResolver2); // "observe" should not have been called since resource not loaded yet. expect(observeSpy).to.be.called; readyResolver(); return Promise.resolve().then(() => { expect(observeSpy).to.be.calledWith(ampElement); clock.tick(135); fireIntersect(5); // below visiblePercentageMin, no trigger clock.tick(100); fireIntersect(25); // above spec 1 min visible, trigger callback 1 return eventPromise.then(state => { expect(state).to.contains({ backgrounded: 0, backgroundedAtStart: 0, elementHeight: 100, elementWidth: 100, elementX: 0, elementY: 75, firstSeenTime: 135, lastSeenTime: 235, lastVisibleTime: 235, loadTimeVisibility: 5, maxVisiblePercentage: 25, minVisiblePercentage: 25, totalVisibleTime: 0, // duration metrics are always 0 maxContinuousVisibleTime: 0, // as it triggers immediately }); expect(unobserveSpy).to.not.be.called; clock.tick(100); fireIntersect(35); // above spec 2 min visible, trigger callback 2 return eventPromise2; }).then(state => { expect(state).to.contains({ backgrounded: 0, backgroundedAtStart: 0, elementHeight: 100, elementWidth: 100, elementX: 0, elementY: 65, firstSeenTime: 135, lastSeenTime: 335, lastVisibleTime: 335, loadTimeVisibility: 5, maxVisiblePercentage: 35, minVisiblePercentage: 35, totalVisibleTime: 0, // duration metrics is always 0 maxContinuousVisibleTime: 0, // as it triggers immediately }); }); }).then(() => { expect(unobserveSpy).to.be.called; // unobserve when all callback fired }); }); it('should trigger "visible" with duration condition', () => { viewer.setVisibilityState_(VisibilityState.VISIBLE); visibility = new VisibilityManagerForDoc(ampdoc); visibility.listenElement( ampElement, {continuousTimeMin: 1000}, readyPromise, null, eventResolver); const model = visibility.models_[0]; readyResolver(); return Promise.resolve().then(() => { expect(observeSpy).to.be.calledWith(ampElement); clock.tick(100); fireIntersect(25); // visible expect(isModelResolved(model)).to.be.false; clock.tick(999); fireIntersect(0); // this will reset the timer for continuous time expect(isModelResolved(model)).to.be.false; clock.tick(100); fireIntersect(5); // visible again. expect(isModelResolved(model)).to.be.false; clock.tick(100); // Enters background. this will reset the timer for continuous time viewer.setVisibilityState_(VisibilityState.HIDDEN); expect(isModelResolved(model)).to.be.false; clock.tick(2000); // this 2s should not be counted in visible time expect(isModelResolved(model)).to.be.false; viewer.setVisibilityState_(VisibilityState.VISIBLE); // now we're back clock.tick(100); fireIntersect(35); // keep being visible expect(isModelResolved(model)).to.be.false; clock.tick(899); // not yet! expect(isModelResolved(model)).to.be.false; clock.tick(1); // now fire expect(isModelResolved(model)).to.be.true; return eventPromise.then(state => { expect(state).to.contains({ backgrounded: 1, backgroundedAtStart: 0, elementHeight: 100, elementWidth: 100, elementX: 0, elementY: 65, firstSeenTime: 100, lastSeenTime: 4299, lastVisibleTime: 4299, loadTimeVisibility: 25, maxVisiblePercentage: 35, minVisiblePercentage: 5, totalVisibleTime: 2099, maxContinuousVisibleTime: 1000, }); }); }); }); it('should populate "backgrounded" and "backgroundedAtStart"', () => { viewer.setVisibilityState_(VisibilityState.HIDDEN); visibility = new VisibilityManagerForDoc(ampdoc); visibility.listenElement( ampElement, {}, readyPromise, null, eventResolver); viewer.setVisibilityState_(VisibilityState.VISIBLE); readyResolver(); return Promise.resolve().then(() => { expect(observeSpy).to.be.calledWith(ampElement); clock.tick(100); fireIntersect(25); // visible return eventPromise.then(state => { expect(state).to.contains({ backgroundedAtStart: 1, backgrounded: 1, }); }); }); }); });
{'content_hash': '2cd466c6cbb1bbdce565cf7b9889daa3', 'timestamp': '', 'source': 'github', 'line_count': 1082, 'max_line_length': 80, 'avg_line_length': 31.613678373382626, 'alnum_prop': 0.6533649067415074, 'repo_name': 'sklobovskaya/amphtml', 'id': '7d9093fa55e7599c6c2ea34967d1ecd824cf31d4', 'size': '34833', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'extensions/amp-analytics/0.1/test/test-visibility-manager.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '73680'}, {'name': 'Go', 'bytes': '7459'}, {'name': 'HTML', 'bytes': '876009'}, {'name': 'Java', 'bytes': '36596'}, {'name': 'JavaScript', 'bytes': '7538285'}, {'name': 'Protocol Buffer', 'bytes': '29210'}, {'name': 'Python', 'bytes': '82782'}, {'name': 'Ruby', 'bytes': '6079'}, {'name': 'Shell', 'bytes': '6942'}, {'name': 'Yacc', 'bytes': '20286'}]}
package com.yahoo.sketches.hive.quantiles; import java.util.List; import org.apache.hadoop.hive.ql.exec.Description; import org.apache.hadoop.hive.ql.exec.UDF; import org.apache.hadoop.io.BytesWritable; import com.yahoo.memory.Memory; import com.yahoo.sketches.quantiles.DoublesSketch; @Description( name = "GetCDF", value = "_FUNC_(sketch, split points...)", extended = "Returns an approximation to the Cumulative Distribution Function (CDF)" + " from a sketch given a set of split points (values)." + " Split points are an array of M unique, monotonically increasing values" + " that divide the real number line into M+1 consecutive disjoint intervals." + " The function returns an array of M+1 double valuess, the first M of which are approximations" + " to the ranks of the corresponding split points (fraction of input stream values that are less" + " than a split point). The last value is always 1." + " CDF can also be viewed as a cumulative version of PMF.") public class GetCdfFromDoublesSketchUDF extends UDF { /** * Returns a list of ranks (CDF) from a given sketch * @param serializedSketch serialized sketch * @param splitPoints list of unique and monotonically increasing values * @return list of fractions from 0 to 1 */ public List<Double> evaluate(final BytesWritable serializedSketch, final Double... splitPoints) { if (serializedSketch == null) { return null; } final DoublesSketch sketch = DoublesSketch.wrap(Memory.wrap(serializedSketch.getBytes())); final double[] cdf = sketch.getCDF(Util.objectsToPrimitives(splitPoints)); if (cdf == null) { return null; } return Util.primitivesToList(cdf); } }
{'content_hash': 'e594d051fe2e2223ce3ab67b2ad0f520', 'timestamp': '', 'source': 'github', 'line_count': 41, 'max_line_length': 100, 'avg_line_length': 41.21951219512195, 'alnum_prop': 0.737869822485207, 'repo_name': 'DataSketches/sketches-hive', 'id': 'f6ba456f07f319d42a22ab9877545dedf56ec920', 'size': '1833', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/com/yahoo/sketches/hive/quantiles/GetCdfFromDoublesSketchUDF.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '703777'}]}
<HTML> <HEAD> <meta charset="UTF-8"> <title>Crossword.Word.Builder.setStartColumn - library</title> <link rel="stylesheet" href="../../../../../style.css"> </HEAD> <BODY> <a href="../../../../index.html">library</a>&nbsp;/&nbsp;<a href="../../../index.html">org.akop.ararat.core</a>&nbsp;/&nbsp;<a href="../../index.html">Crossword</a>&nbsp;/&nbsp;<a href="../index.html">Word</a>&nbsp;/&nbsp;<a href="index.html">Builder</a>&nbsp;/&nbsp;<a href="./set-start-column.html">setStartColumn</a><br/> <br/> <h1>setStartColumn</h1> <a name="org.akop.ararat.core.Crossword.Word.Builder$setStartColumn(kotlin.Int)"></a> <code><span class="keyword">fun </span><span class="identifier">setStartColumn</span><span class="symbol">(</span><span class="identifier" id="org.akop.ararat.core.Crossword.Word.Builder$setStartColumn(kotlin.Int)/value">value</span><span class="symbol">:</span>&nbsp;<a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html"><span class="identifier">Int</span></a><span class="symbol">)</span><span class="symbol">: </span><a href="index.html"><span class="identifier">Builder</span></a></code> </BODY> </HTML>
{'content_hash': '9e2c0a12e95c10f4240c6496512ca504', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 515, 'avg_line_length': 81.71428571428571, 'alnum_prop': 0.6800699300699301, 'repo_name': 'pokebyte/ararat', 'id': 'ee0cbadc165def9189e87165da04f3693e983c96', 'size': '1144', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/library/org.akop.ararat.core/-crossword/-word/-builder/set-start-column.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '227338'}]}
using System; namespace System.Collections { public interface IStructuralComparable { int CompareTo(object? other, IComparer comparer); } }
{'content_hash': '6385ba9ca6e9494045fd96774941c589', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 57, 'avg_line_length': 17.88888888888889, 'alnum_prop': 0.7018633540372671, 'repo_name': 'wtgodbe/coreclr', 'id': '1849e367c41e2259a6d17b612449eb55891c4820', 'size': '365', 'binary': False, 'copies': '28', 'ref': 'refs/heads/master', 'path': 'src/System.Private.CoreLib/shared/System/Collections/IStructuralComparable.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '976648'}, {'name': 'Awk', 'bytes': '6904'}, {'name': 'Batchfile', 'bytes': '167893'}, {'name': 'C', 'bytes': '4862319'}, {'name': 'C#', 'bytes': '154822068'}, {'name': 'C++', 'bytes': '64306017'}, {'name': 'CMake', 'bytes': '723128'}, {'name': 'M4', 'bytes': '15214'}, {'name': 'Makefile', 'bytes': '46117'}, {'name': 'Objective-C', 'bytes': '14116'}, {'name': 'Perl', 'bytes': '23653'}, {'name': 'PowerShell', 'bytes': '132755'}, {'name': 'Python', 'bytes': '480080'}, {'name': 'Roff', 'bytes': '672227'}, {'name': 'Scala', 'bytes': '4102'}, {'name': 'Shell', 'bytes': '513230'}, {'name': 'Smalltalk', 'bytes': '635930'}, {'name': 'SuperCollider', 'bytes': '650'}, {'name': 'TeX', 'bytes': '126781'}, {'name': 'XSLT', 'bytes': '1016'}, {'name': 'Yacc', 'bytes': '157492'}]}
{% extends "layout.html" %} {% block styles %} <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='stylesheet.css') }}" /> {% endblock %} {% block body %} <div class="well"> <div class="container"> <h1>Request Password Reset</h1> </div> </div> <div class="container"> {% if success %} <p>We've sent you an email with further instructions. It should arrive soon. <a href="mailto:[email protected]">Email us</a> if you run into trouble.</p> {% else %} <p>Forgot your password? It's cool, happens to the best of us. We can help you reset it.</p> <div class="row"> <form class="form-horizontal col-md-6" role="form" action="/forgot-password" method="POST"> {% if bad_email %} <p>Double check your email address, we don't recognize you.</p> {% endif %} <div class="form-group"> <label for="email" class="col-sm-2 control-label">Email</label> <div class="col-sm-10"> <input type="text" class="form-control" id="email" placeholder="Email" name="email" value="{{ email }}"> </div> </div> <div class="form-group"> <div class="col-sm-10 col-sm-offset-2"> <input type="submit" value="Submit" class="btn btn-primary"> </div> </div> </form> <div class="col-md-6"> {% if errors %} <p class="text-danger">{{ errors }}</p> {% endif %} </div> </div> {% endif %} </div> {% endblock %}
{'content_hash': '98f14256ef8101d64d3cac2879b7f8bc', 'timestamp': '', 'source': 'github', 'line_count': 42, 'max_line_length': 130, 'avg_line_length': 38.404761904761905, 'alnum_prop': 0.5244885306881587, 'repo_name': 'ModulousSmash/Modulous', 'id': '81df2d88807202de8e386e94e2a81e07e9cb3ac0', 'size': '1613', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'templates/forgot.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '8077'}, {'name': 'CSS', 'bytes': '208709'}, {'name': 'CoffeeScript', 'bytes': '34512'}, {'name': 'HTML', 'bytes': '1531955'}, {'name': 'JavaScript', 'bytes': '365418'}, {'name': 'Mako', 'bytes': '412'}, {'name': 'PHP', 'bytes': '5957'}, {'name': 'Python', 'bytes': '187439'}]}
package cdzero2hero; import cdzero2hero.domain.User; import cdzero2hero.repository.InMemoryUserRepository; import cdzero2hero.repository.UserRepository; import cdzero2hero.test.categories.SmallTest; import org.junit.Test; import org.junit.experimental.categories.Category; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; @Category(SmallTest.class) public class InMemoryUserRepositoryTest { private static final String MR_TEST = "Mr. Test"; @Test public void addUser() { User mrTest = new User(MR_TEST); UserRepository repository = InMemoryUserRepository.INSTANCE; assertNull(repository.getUserByName(MR_TEST)); repository.addUser(mrTest); assertEquals(mrTest, repository.getUserByName(MR_TEST)); } }
{'content_hash': 'b2cca65ef3afcd1b845adfee4ba9e132', 'timestamp': '', 'source': 'github', 'line_count': 27, 'max_line_length': 68, 'avg_line_length': 29.703703703703702, 'alnum_prop': 0.7643391521197007, 'repo_name': 'FredrikDahlman/cdzero2hero-app-m5', 'id': 'd3802c62268c778a6f1467a3c58c23d0ecebfa11', 'size': '802', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/test/java/cdzero2hero/InMemoryUserRepositoryTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
package demo.java.v2c01io.RegExTest; import java.util.*; import java.util.regex.*; /** This program tests regular expression matching. Enter a pattern and strings to match, or hit Cancel to exit. If the pattern contains groups, the group boundaries are displayed in the match. @version 1.01 2004-05-11 @author Cay Horstmann */ public class RegExTest { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter pattern: "); String patternString = in.nextLine(); Pattern pattern = null; try { pattern = Pattern.compile(patternString); } catch (PatternSyntaxException e) { System.out.println("Pattern syntax error"); System.exit(1); } while (true) { System.out.println("Enter string to match: "); String input = in.nextLine(); if (input == null || input.equals("")) return; Matcher matcher = pattern.matcher(input); if (matcher.matches()) { System.out.println("Match"); int g = matcher.groupCount(); if (g > 0) { for (int i = 0; i < input.length(); i++) { for (int j = 1; j <= g; j++) if (i == matcher.start(j)) System.out.print('('); System.out.print(input.charAt(i)); for (int j = 1; j <= g; j++) if (i + 1 == matcher.end(j)) System.out.print(')'); } System.out.println(); } } else System.out.println("No match"); } } }
{'content_hash': '4b276288e65fb34cff2555f11f0fdafb', 'timestamp': '', 'source': 'github', 'line_count': 61, 'max_line_length': 55, 'avg_line_length': 28.81967213114754, 'alnum_prop': 0.49715585893060293, 'repo_name': 'myid999/javademo', 'id': '17d20cb3c81046016df0ad5b5a0b4f43aae6e20a', 'size': '1758', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'core/src/main/java/demo/java/v2c01io/RegExTest/RegExTest.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '23149'}, {'name': 'C++', 'bytes': '2165'}, {'name': 'HTML', 'bytes': '1835'}, {'name': 'Java', 'bytes': '889869'}, {'name': 'XSLT', 'bytes': '1368'}]}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.6"/> <title>FFXcodeProjectFileManager: FFXcodeProjectManager/ConfigurableObjects/Targets/Abstract Directory Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { searchBox.OnSelectItem(0); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">FFXcodeProjectFileManager </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.6 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="annotated.html"><span>Data&#160;Structures</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&#160;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&#160;</span>Data Structures</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&#160;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&#160;</span>Properties</a></div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="dir_5aea89a567fd7791d50fa4a01aee1f3d.html">FFXcodeProjectManager</a></li><li class="navelem"><a class="el" href="dir_6cf54b0f9b1114c3aa7cd76627303519.html">ConfigurableObjects</a></li><li class="navelem"><a class="el" href="dir_6eee9453888dbc7d51907b3fb1bc96d4.html">Targets</a></li><li class="navelem"><a class="el" href="dir_858f230c19093f0149bfff156c944b1d.html">Abstract</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">Abstract Directory Reference</div> </div> </div><!--header--> <div class="contents"> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="files"></a> Files</h2></td></tr> <tr class="memitem:_f_f_x_c_target_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>FFXCTarget.h</b> <a href="_f_f_x_c_target_8h_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:_f_f_x_c_target_8m"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>FFXCTarget.m</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Mon Mar 24 2014 09:10:25 for FFXcodeProjectFileManager by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.6 </small></address> </body> </html>
{'content_hash': 'ab5207d9429b82bd395ae9c6b181ef2f', 'timestamp': '', 'source': 'github', 'line_count': 100, 'max_line_length': 559, 'avg_line_length': 52.26, 'alnum_prop': 0.6748947569843092, 'repo_name': 'ffried/FFXcodeProjectManager', 'id': 'd0272aaabba21d4db9711e4f64f581900c3b5465', 'size': '5226', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Documentation/html/dir_858f230c19093f0149bfff156c944b1d.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '29559'}, {'name': 'JavaScript', 'bytes': '53776'}, {'name': 'Objective-C', 'bytes': '168403'}]}
<!DOCTYPE html> <html class="has-navbar-fixed-top"> <head> <meta charset="utf-8"> <title>Tag: spark streaming - Hexo</title> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/outdated-browser/1.1.5/outdatedbrowser.min.css"> <link rel="icon" href="/favicon.png"> <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Ovo|Source+Code+Pro"> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bulma/0.6.2/css/bulma.min.css"> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/lightgallery/1.6.8/css/lightgallery.min.css"> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/justifiedGallery/3.6.5/css/justifiedGallery.min.css"> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/atom-one-light.min.css"> <link rel="stylesheet" href="/css/style.css"> <script defer src="//use.fontawesome.com/releases/v5.0.8/js/all.js"></script> <script type='text/javascript' src='//platform-api.sharethis.com/js/sharethis.js#property=5b953a606ae21e0011fb0a8a&product=social-ab' async='async'></script> </head> <body> <nav class="navbar is-transparent is-fixed-top navbar-main" role="navigation" aria-label="main navigation"> <div class="container"> <div class="navbar-brand"> <a class="navbar-item navbar-logo" href="/"> <img src="/assets/avator/avator.jpg" alt="" height="28"> </a> <div class="navbar-burger"> <span></span> <span></span> <span></span> </div> </div> <div class="navbar-menu navbar-start"> <a class="navbar-item " href="/archives">Archives</a> <a class="navbar-item " href="/categories">Categories</a> <a class="navbar-item " href="/tags">Tags</a> <a class="navbar-item " href="/about">About</a> </div> <div class="navbar-menu navbar-end"> <a class="navbar-item search" title="Search" href="javascript:;"> <i class="fas fa-search"></i> </a> <a class="navbar-item" title="GitHub" href="https://github.com/ppoffice/hexo-theme-minos"> <i class="fab fa-github"></i> </a> </div> </div> </nav> <section class="section section-heading"> <div class="container"> <div class="content"> <h5>#spark streaming</h5> </div> </div> </section> <section class="section"> <div class="container"> <article class="article content gallery" itemscope itemprop="blogPost"> <h1 class="article-title is-size-3 is-size-4-mobile" itemprop="name"> <a href="/2019/01/01/newjourney2019/" itemprop="url">sparkStreaming</a> </h1> <div class="article-meta columns is-variable is-1 is-multiline is-mobile is-size-7-mobile"> <span class="column is-narrow"> <time datetime="2019-01-01T09:02:51.000Z" itemprop="datePublished">Jan 1 2019</time> </span> <span class="column is-narrow article-category"> <i class="far fa-folder"></i> <a class="article-category-link" href="/categories/spark/">spark</a> </span> <span class="column is-narrow"> a few seconds read (About 0 words) </span> </div> <div class="article-entry is-size-6-mobile" itemprop="articleBody"> </div> </article> </div> </section> <footer class="footer"> <div class="container"> <div class="columns content"> <div class="column is-narrow has-text-centered"> &copy; 2019 John Doe&nbsp; Powered by <a href="http://hexo.io/" target="_blank">Hexo</a> & <a href="http://github.com/ppoffice/hexo-theme-minos">Minos</a> </div> <div class="column is-hidden-mobile"></div> <div class="column is-narrow"> <div class="columns is-mobile is-multiline is-centered"> <a class="column is-narrow has-text-black" title="GitHub" href="https://github.com/ychenchen"> GitHub </a> </div> </div> </div> </div> </footer> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment-with-locales.min.js"></script> <!-- test if the browser is outdated --> <div id="outdated"> <h6>Your browser is out-of-date!</h6> <p>Update your browser to view this website correctly. <a id="btnUpdateBrowser" href="http://outdatedbrowser.com/">Update my browser now </a></p> <p class="last"><a href="#" id="btnCloseUpdateBrowser" title="Close">&times;</a></p> </div> <script src="//cdnjs.cloudflare.com/ajax/libs/outdated-browser/1.1.5/outdatedbrowser.min.js"></script> <script> $(document).ready(function () { // plugin function, place inside DOM ready function outdatedBrowser({ bgColor: '#f25648', color: '#ffffff', lowerThan: 'flex' }) }); </script> <script> window.FontAwesomeConfig = { searchPseudoElements: true } moment.locale("default"); </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=TeX-MML-AM_CHTML"></script> <script> MathJax.Hub.Config({ "HTML-CSS": {matchFontHeight: false}, SVG: {matchFontHeight: false}, CommonHTML: {matchFontHeight: false} }); </script> <script src="//cdnjs.cloudflare.com/ajax/libs/lightgallery/1.6.8/js/lightgallery-all.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/justifiedGallery/3.6.5/js/jquery.justifiedGallery.min.js"></script> <script> (function ($) { $(document).ready(function () { if (typeof($.fn.lightGallery) === 'function') { $('.article.gallery').lightGallery({ selector: '.gallery-item' }); } if (typeof($.fn.justifiedGallery) === 'function') { $('.justified-gallery').justifiedGallery(); } }); })(jQuery); </script> <script src="/js/script.js"></script> <div class="searchbox ins-search"> <div class="searchbox-mask"></div> <div class="searchbox-container ins-search-container"> <div class="searchbox-input-wrapper"> <input type="text" class="searchbox-input ins-search-input" placeholder="Type something..." /> <span class="searchbox-close ins-close ins-selectable"><i class="fa fa-times-circle"></i></span> </div> <div class="searchbox-result-wrapper ins-section-wrapper"> <div class="ins-section-container"></div> </div> </div> </div> <script> (function (window) { var INSIGHT_CONFIG = { TRANSLATION: { POSTS: 'Posts', PAGES: 'Pages', CATEGORIES: 'Categories', TAGS: 'Tags', UNTITLED: '(Untitled)', }, CONTENT_URL: '/content.json', }; window.INSIGHT_CONFIG = INSIGHT_CONFIG; })(window); </script> <script src="/js/insight.js"></script> </body> </html>
{'content_hash': '78f32eb7920f3c635a143a05fd2bc87e', 'timestamp': '', 'source': 'github', 'line_count': 276, 'max_line_length': 157, 'avg_line_length': 29.10144927536232, 'alnum_prop': 0.5414591633466136, 'repo_name': 'ychenchen/ychenchen.github.io', 'id': '3d0f97057748adc8ccb8b088a7916ce15784c424', 'size': '8032', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tags/spark-streaming/index.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '30816'}, {'name': 'HTML', 'bytes': '533760'}, {'name': 'JavaScript', 'bytes': '16030'}]}
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var VGridObservables = exports.VGridObservables = function () { function VGridObservables(vGrid, bindingEngine) { _classCallCheck(this, VGridObservables); this.bindingEngine = bindingEngine; this.vGrid = vGrid; this.subscriptionsAttributes = []; this.collectionSubscription = null; this.subscriptionsArray = []; } VGridObservables.prototype.enableObservablesCollection = function enableObservablesCollection() { var _this = this; var collectionSubscription = function collectionSubscription(x, y) { _this.disableObservablesArray(); _this.vGrid.vGridCollectionFiltered = _this.vGrid.vGridCollection.slice(0); _this.vGrid.checkKeys(); _this.vGrid.vGridCurrentRow = -1; _this.vGrid.vGridSort.reset(); if (!_this.vGrid.vGridConfig.keepFilterOnCollectionChange) { _this.vGrid.vGridSort.reset(); _this.vGrid.vGridGenerator.rebuildGridHeaderHtmlAndViewSlot(); _this.vGrid.vGridSelection.reset(); _this.vGrid.vGridConfig.keepFilterOnCollectionChange = false; } _this.vGrid.vGridGenerator.collectionChange(); _this.vGrid.vGridCurrentEntityRef = null; for (var k in _this.vGrid.vGridCurrentEntity) { if (_this.vGrid.vGridCurrentEntity.hasOwnProperty(k)) { _this.vGrid.vGridCurrentEntity[k] = undefined; } } _this.enableObservablesArray(); }; this.vGrid.__observers__.vGridCollection.subscribe(this.vGrid, collectionSubscription); this.collectioncallable = collectionSubscription; this.collectionSubscription = this.vGrid.__observers__.vGridCollection; }; VGridObservables.prototype.enableObservablesArray = function enableObservablesArray() { var _this2 = this; var arrayObserver = this.bindingEngine.collectionObserver(this.vGrid.vGridCollection).subscribe(function (arrayObserverChanges) { var colFiltered = _this2.vGrid.vGridCollectionFiltered; var col = _this2.vGrid.vGridCollection; var grid = _this2.vGrid.vGridGenerator; var curKey = -1; if (_this2.vGrid.vGridCurrentEntityRef) { curKey = _this2.vGrid.vGridCurrentEntityRef[_this2.vGrid.vGridRowKey]; } var curEntityValid = true; if (arrayObserverChanges.length > 0) { var added = false; var toRemove = []; arrayObserverChanges.forEach(function (observerChange) { if (observerChange.addedCount > 0) { for (var i = 0; i < observerChange.addedCount; i++) { colFiltered.push(col[observerChange.index + i]); _this2.vGrid.checkKey(col[observerChange.index + i]); } } if (observerChange.removed.length > 0) { observerChange.removed.forEach(function (x) { if (x[_this2.vGrid.vGridRowKey] === curKey) { curEntityValid = false; } var rowToRemove = -1; colFiltered.forEach(function (row, index) { if (row[_this2.vGrid.vGridRowKey] === x[_this2.vGrid.vGridRowKey]) { rowToRemove = index; } }); if (rowToRemove !== -1) { colFiltered.splice(rowToRemove, 1); } }); } }); var newRowNo = -1; if (!curEntityValid) { for (var k in _this2.vGrid.vGridCurrentEntity) { if (_this2.vGrid.vGridCurrentEntity.hasOwnProperty(k)) { _this2.vGrid.vGridCurrentEntity[k] = undefined; } } _this2.vGrid.vGridCurrentEntityRef = null; _this2.vGrid.vGridCurrentRow = -1; } else { if (curKey !== -1) { _this2.vGrid.vGridCollectionFiltered.forEach(function (x, index) { if (curKey === x[_this2.vGrid.vGridRowKey]) { _this2.vGrid.vGridCurrentRow = index; } }); } } grid.collectionChange(false); } }); this.subscriptionsArray = arrayObserver; }; VGridObservables.prototype.enableObservablesAttributes = function enableObservablesAttributes() { var _this3 = this; this.vGrid.vGridConfig.attAttributeObserve.forEach(function (property) { var propertyObserver = _this3.bindingEngine.propertyObserver(_this3.vGrid.vGridCurrentEntity, property).subscribe(function (newValue, oldValue) { var newValueCheck = newValue !== undefined && newValue !== null ? newValue.toString() : newValue; var oldValueCheck = oldValue !== undefined && oldValue !== null ? oldValue.toString() : oldValue; if (newValueCheck !== oldValueCheck && _this3.vGrid.vGridCurrentEntityRef) { _this3.vGrid.vGridCurrentEntityRef[property] = newValue; _this3.vGrid.vGridGenerator.rebindRowNumber(_this3.vGrid.vGridCurrentRow); } }); _this3.subscriptionsAttributes.push(propertyObserver); }); }; VGridObservables.prototype.disableObservablesCollection = function disableObservablesCollection() { this.collectionSubscription.unsubscribe(this.vGrid, this.collectioncallable); }; VGridObservables.prototype.disableObservablesArray = function disableObservablesArray() { this.subscriptionsArray.dispose(); this.subscriptionsArray = null; }; VGridObservables.prototype.disableObservablesAttributes = function disableObservablesAttributes() { for (var i = 0; i < this.subscriptionsAttributes.length; i++) { try { this.subscriptionsAttributes[i].dispose(); } catch (e) {} } this.subscriptionsAttributes = []; }; return VGridObservables; }();
{'content_hash': 'c834b2afa26d2b1b4805061275753aef', 'timestamp': '', 'source': 'github', 'line_count': 164, 'max_line_length': 153, 'avg_line_length': 36.03658536585366, 'alnum_prop': 0.6473773265651438, 'repo_name': 'Thanood/v-grid', 'id': 'bfe88be31ed0d3ac36d25e3cd5dc5dcf84c62104', 'size': '5910', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'dist/commonjs/vGrid/v-grid-observables.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '58545'}, {'name': 'HTML', 'bytes': '66426'}, {'name': 'JavaScript', 'bytes': '1314283'}]}
package sys.dht; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.List; import java.util.Set; import java.util.logging.Logger; import sys.net.api.Endpoint; import sys.utils.IP; public class DHT_Node { private static Logger Log = Logger.getLogger(DHT_Node.class.getName()); static Node self; static OrdinalDB db; public static Endpoint dhtEndpoint() { return self.dhtEndpoint; } public static void init(String dc, List<String> urls, Endpoint selfEndpoint) { db = new OrdinalDB().populate(dc, urls, selfEndpoint); self = db.self(); Log.info(String.format(IP.localHostname() + " dht comprises %d node(s): %s\n", db.nodes().size(), db.nodes())); } public static Set<Long> nodeKeys() { return db.nodeKeys(); } static public boolean isHandledLocally(final String key) { return resolveNextHop(key).key == self.key; } static public Endpoint resolveKey(final String key) { Node nextHop = resolveNextHop(key); return self.key == nextHop.key ? null : nextHop.dhtEndpoint; } static Node resolveNextHop(String key) { long key2key = longHashValue(key) & Node.MAX_KEY; return db.resolveKey(key2key); } static public long longHashValue(String key) { synchronized (digest) { digest.reset(); digest.update(key.getBytes()); return new BigInteger(1, digest.digest()).longValue() >>> 1; } } private static MessageDigest digest; static { try { digest = java.security.MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } }
{'content_hash': 'aaea9edd94fd29053b355e757ccb52f3', 'timestamp': '', 'source': 'github', 'line_count': 65, 'max_line_length': 113, 'avg_line_length': 24.676923076923078, 'alnum_prop': 0.7188279301745636, 'repo_name': 'SyncFree/Indigo', 'id': '2741a0dd50d4fff2db1fa41ed7058f6cf0f9ebee', 'size': '2400', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'TrueIndigo/src/sys/dht/DHT_Node.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Gnuplot', 'bytes': '24403'}, {'name': 'Groovy', 'bytes': '218006'}, {'name': 'Java', 'bytes': '838505'}, {'name': 'Shell', 'bytes': '128826'}]}
'use strict'; require('es6-promise').polyfill(); var chai = require('chai'); var expect = chai.expect; chai.use(require('sinon-chai')); chai.use(require('chai-hy-res')); chai.use(require('chai-as-promised')); chai.config.truncateThreshold = 0; var Context = require('../../src/context.js'); var WebLink = require('../../src/web_link.js'); var HalExtension = require('../../src/hal.js'); var JsonExtension = require('../../src/json.js'); var LinkHeaderExtension = require('../../src/link_header.js'); describe('WebLink', function () { describe('creating a web link', function() { var link; var http; var defaultOptions; beforeEach(function() { http = this.sinon.stub(); defaultOptions = {}; var extensions = [new HalExtension(), new JsonExtension(), new LinkHeaderExtension()]; var ctx = new Context(http, extensions, defaultOptions).forResource({ url: 'http://api.server.com/', headers: { 'content-type': 'application/hal+json' } }); link = new WebLink({ href: '/posts/123', title: 'Hypermedia and AngularJS' }, ctx); }); it('had the data properties', function() { expect(link.href).to.equal('/posts/123'); expect(link.title).to.equal('Hypermedia and AngularJS'); }); it('has a proper resolved URL', function() { expect(link.resolvedUrl()).to.equal('http://api.server.com/posts/123'); }); describe('following the link', function() { var resource; var httpResolve; var httpPromise; beforeEach(function() { httpPromise = new Promise(function(resolve) { httpResolve = resolve; }); http .withArgs(this.sinon.match({ url: 'http://api.server.com/posts/123' })) .returns(httpPromise); resource = link.follow(); }); it('is an unresolved resource', function() { expect(resource).to.be.an.unresolved.resource; }); it('passes an Accept header with extension content types, preferring the context content type', function() { var expectedHeaders = { 'Accept': 'application/hal+json,application/vnd.hal+json;q=0.5,application/json;q=0.5' }; expect(http) .to.be .calledWith(this.sinon.match.has('headers', expectedHeaders)); }); describe('once the request completes', function() { beforeEach(function() { httpResolve({data: { title: 'Hypermedia and AngularJS' }, headers: { 'content-type': 'application/hal+json' }, config: { url: 'http://api.server.com/posts/123' }}); return httpPromise; }); it('is a resolved resource', function() { expect(resource).to.be.a.resolved.resource; }); it('has the expected properties', function() { expect(resource.title).to.equal('Hypermedia and AngularJS'); }); }); }); describe('following a link that returns an error', function() { var resource; var httpPromise; beforeEach(function() { httpPromise = Promise.reject({data: {}, headers: {}, status: 404}); http .withArgs(this.sinon.match({ url: 'http://api.server.com/posts/123' })) .returns(httpPromise); resource = link.follow(); }); it('has the follow rejection in the $error', function() { return expect(resource.$promise).to.be.rejected.and.to.eventually.have.property('$error').eql({message: 'HTTP request to load resource failed', inner: {data: {}, headers: {}, status: 404}}); }); it('has a rejected promise with the resource', function() { return expect(resource.$promise).to.be.rejectedWith(resource); }); }); describe('following the link when there are default options', function() { beforeEach(function() { http.returns(Promise.resolve({})); defaultOptions.protocol = { headers: { 'Prefer': 'return=representation' } }; link.follow({ protocol: { headers: { 'Accept': 'text/plain' } } }); }); it('invokes the http request with the merged options', function() { var expectedHeaders = { 'Accept': 'text/plain', 'Prefer': 'return=representation' }; expect(http) .to.be .calledWith(this.sinon.match.has('headers', expectedHeaders)); }); }); }); describe('creating a templated web link', function() { var link; beforeEach(function() { link = new WebLink({ href: '/posts{/id}', templated: true }, new Context(), {}, []); }); it('is templated', function() { expect(link.templated).to.equal(true); }); it('processes the URI template for the resolved URL', function() { expect(link.resolvedUrl({ id: '123' })).to.equal('/posts/123'); }); describe('following the link without providing data in options', function() { it('should throw an exception', function() { var follow = function() { link.follow(); }; expect(follow).to.throw(Error); }); }); }); describe('creating a web link with type expectation provided', function() { var link; var http, httpPromise; beforeEach(function() { http = this.sinon.stub(); var extensions = [new HalExtension()]; link = new WebLink({ href: '/posts?page=2', type: 'application/json' }, new Context(http, extensions)); }); it('has the type', function() { expect(link.type).to.equal('application/json'); }); describe('following the link with no options provided', function() { it('sends the type in the Accept header', function() { httpPromise = new Promise(function() {}); http .withArgs(this.sinon.match.has('headers', { 'Accept': 'application/json' })) .returns(httpPromise); var res = link.follow(); expect(res).to.not.be.null; }); }); describe('following the link with explicit Accept header in options', function() { it('sends the provided Accept header', function() { httpPromise = new Promise(function() {}); http.withArgs(this.sinon.match.has('headers', { 'Accept': 'text/plain' })).returns(httpPromise); var res = link.follow({ protocol: { headers: { 'Accept': 'text/plain' } }}); expect(http) .to.be .calledWith(this.sinon.match.has('headers', { 'Accept': 'text/plain' })); expect(res).to.not.be.null; }); }); }); });
{'content_hash': '8417c46b7764e001b3e24e9ef29589b7', 'timestamp': '', 'source': 'github', 'line_count': 213, 'max_line_length': 198, 'avg_line_length': 30.976525821596244, 'alnum_prop': 0.5847226432252197, 'repo_name': 'petejohanson/hy-res', 'id': '685b162fbc4a0028798ef13faaa8735093b02521', 'size': '6598', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'test/spec/web_link.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '319891'}]}
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Struct template call_if_statement&lt;true, Then, internal_type&gt;</title> <link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.79.1"> <link rel="home" href="../../index.html" title="Chapter&#160;1.&#160;Boost.Contract 1.0.0"> <link rel="up" href="../../reference.html#header.boost.contract.call_if_hpp" title="Header &lt;boost/contract/call_if.hpp&gt;"> <link rel="prev" href="call_if_statement.html" title="Struct template call_if_statement"> <link rel="next" href="call_if_statem_idp43978560.html" title="Struct template call_if_statement&lt;true, Then, ThenResult&gt;"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td> <td align="center"><a href="../../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="call_if_statement.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../reference.html#header.boost.contract.call_if_hpp"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="call_if_statem_idp43978560.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="refentry"> <a name="boost.contract.call_if_statem_idp43963216"></a><div class="titlepage"></div> <div class="refnamediv"> <h2><span class="refentrytitle">Struct template call_if_statement&lt;true, Then, internal_type&gt;</span></h2> <p>boost::contract::call_if_statement&lt;true, Then, internal_type&gt; &#8212; Template specialization to dispatch between then-branch functor template calls that return void and the ones that return non-void. </p> </div> <h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2> <div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: &lt;<a class="link" href="../../reference.html#header.boost.contract.call_if_hpp" title="Header &lt;boost/contract/call_if.hpp&gt;">boost/contract/call_if.hpp</a>&gt; </span><span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> Then<span class="special">&gt;</span> <span class="keyword">struct</span> <a class="link" href="call_if_statem_idp43963216.html" title="Struct template call_if_statement&lt;true, Then, internal_type&gt;">call_if_statement</a><span class="special">&lt;</span><span class="keyword">true</span><span class="special">,</span> <span class="identifier">Then</span><span class="special">,</span> <span class="identifier">internal_type</span><span class="special">&gt;</span> <span class="special">:</span> <span class="keyword">public</span> boost::contract::call_if_statement&lt; true, Then, result_of&lt; Then()&gt;::type &gt; <span class="special">{</span> <span class="comment">// <a class="link" href="call_if_statem_idp43963216.html#boost.contract.call_if_statem_idp43963216construct-copy-destruct">construct/copy/destruct</a></span> <span class="keyword">explicit</span> <a class="link" href="call_if_statem_idp43963216.html#idp43974544-bb"><span class="identifier">call_if_statement</span></a><span class="special">(</span><span class="identifier">Then</span><span class="special">)</span><span class="special">;</span> <span class="special">}</span><span class="special">;</span></pre></div> <div class="refsect1"> <a name="idp97435296"></a><h2>Description</h2> <p>The base class is a call-if statement so the else and else-if statements can be specified if needed. Usually this class template is instantiated only via the return value of <code class="computeroutput"><a class="link" href="call_if.html" title="Function template call_if">boost::contract::call_if</a></code> and <code class="computeroutput"><a class="link" href="call_if_c.html" title="Function template call_if_c">boost::contract::call_if_c</a></code>.</p> <div class="note"><table border="0" summary="Note"> <tr> <td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="../../../../../../doc/src/images/note.png"></td> <th align="left">Note</th> </tr> <tr><td align="left" valign="top"><p>The <code class="computeroutput">result_of&lt;Then()&gt;::type</code> expression should be evaluated only when the static predicate is already checked to be <code class="computeroutput">true</code> (because <code class="computeroutput">Then()</code> is required to compile only in that case). Thus, this template specialization introduces an extra level of indirection necessary for proper lazy evaluation of this result-of expression.</p></td></tr> </table></div> <p> </p> <p><span class="bold"><strong>See Also:</strong></span></p> <p> <a class="link" href="../../boost_contract/extras.html#boost_contract.extras.assertion_requirements__templates_" title="Assertion Requirements (Templates)"> Assertion Requirements</a></p> <p> </p> <div class="refsect2"> <a name="idp97443632"></a><h3>Template Parameters</h3> <div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"> <pre class="literallayout"><span class="keyword">typename</span> Then</pre> <p>Type of functor template to call when the static predicate is <code class="computeroutput">true</code> (as it is for this template specialization). </p> </li></ol></div> </div> <div class="refsect2"> <a name="idp97447504"></a><h3> <a name="boost.contract.call_if_statem_idp43963216construct-copy-destruct"></a><code class="computeroutput">call_if_statement</code> public construct/copy/destruct</h3> <div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"> <pre class="literallayout"><span class="keyword">explicit</span> <a name="idp43974544-bb"></a><span class="identifier">call_if_statement</span><span class="special">(</span><span class="identifier">Then</span> f<span class="special">)</span><span class="special">;</span></pre>Construct this object with the then-branch functor template. <p> </p> <div class="variablelist"><table border="0" class="variablelist compact"> <colgroup> <col align="left" valign="top"> <col> </colgroup> <tbody><tr> <td><p><span class="term">Parameters:</span></p></td> <td><div class="variablelist"><table border="0" class="variablelist compact"> <colgroup> <col align="left" valign="top"> <col> </colgroup> <tbody><tr> <td><p><span class="term"><code class="computeroutput">f</code></span></p></td> <td><p>Then-branch nullary functor template. The functor template call <code class="computeroutput">f()</code> is compiled and called for this template specialization (because the if-statement static predicate is <code class="computeroutput">true</code>). The return type of <code class="computeroutput">f()</code> must be the same as (or implicitly convertible to) the return type of all other functor template calls specified for this call-if object. </p></td> </tr></tbody> </table></div></td> </tr></tbody> </table></div> </li></ol></div> </div> </div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2008-2018 Lorenzo Caminiti<p> Distributed under the Boost Software License, Version 1.0 (see accompanying file LICENSE_1_0.txt or a copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="call_if_statement.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../reference.html#header.boost.contract.call_if_hpp"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="call_if_statem_idp43978560.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
{'content_hash': 'ec9298b5fdc2dd7979e00fb0c785f681', 'timestamp': '', 'source': 'github', 'line_count': 109, 'max_line_length': 583, 'avg_line_length': 80.59633027522936, 'alnum_prop': 0.6860557768924302, 'repo_name': 'nawawi/poedit', 'id': '1e1715ed6c69f75677f6cc53bce7c66b74e487dd', 'size': '8785', 'binary': False, 'copies': '5', 'ref': 'refs/heads/stable', 'path': 'deps/boost/libs/contract/doc/html/boost/contract/call_if_statem_idp43963216.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '48113'}, {'name': 'C++', 'bytes': '1284178'}, {'name': 'Inno Setup', 'bytes': '11180'}, {'name': 'M4', 'bytes': '103958'}, {'name': 'Makefile', 'bytes': '9507'}, {'name': 'Objective-C', 'bytes': '16519'}, {'name': 'Objective-C++', 'bytes': '14681'}, {'name': 'Python', 'bytes': '6594'}, {'name': 'Ruby', 'bytes': '292'}, {'name': 'Shell', 'bytes': '11982'}]}
<?xml version="1.0" encoding="ISO-8859-1"?> <LEOSimulation version="2.5.0"> <STELAVersion>2.5.1</STELAVersion> <SpaceObject> <mass unit="kg">2.0</mass> <dragArea>0.055</dragArea> <reflectingArea>0.22</reflectingArea> <reflectivityCoefficient>1.5</reflectivityCoefficient> <orbitType>LEO</orbitType> <ConstantDragCoef> <cstDragCoef>2.1</cstDragCoef> </ConstantDragCoef> <name>IF4RT19B</name> </SpaceObject> <EphemerisManager version="2.5.0"> <initState> <bulletin version="2.5.0"> <date>2014-07-14T14:50:44.000</date> <Type2PosVel> <frame>CELESTIAL_MEAN_OF_DATE</frame> <nature>MEAN</nature> <semiMajorAxis unit="m">7000000.0</semiMajorAxis> <eccentricity>0.001</eccentricity> <inclination unit="rad">1.70169602069</inclination> <rAAN unit="rad">0.0</rAAN> <argOfPerigee unit="rad">0.0</argOfPerigee> <meanAnomaly unit="rad">0.0</meanAnomaly> </Type2PosVel> </bulletin> </initState> <finalState> <bulletin version="2.5.0"> <date>2023-05-10T02:04:26.264</date> <Type2PosVel> <frame>CELESTIAL_MEAN_OF_DATE</frame> <nature>MEAN</nature> <semiMajorAxis unit="m">6515230.837051147</semiMajorAxis> <eccentricity>5.930620142752188E-4</eccentricity> <inclination unit="rad">1.7006845891531233</inclination> <rAAN unit="rad">3.6883975272626275</rAAN> <argOfPerigee unit="rad">4.9584856319996105</argOfPerigee> <meanAnomaly unit="rad">5.238635197618677</meanAnomaly> </Type2PosVel> </bulletin> </finalState> </EphemerisManager> <author>CNES</author> <comment>LEO example simulation</comment> <simulationDuration unit="years">100.0</simulationDuration> <ephemerisStep unit="s">86400.0</ephemerisStep> <ttMinusUT1 unit="s">67.184</ttMinusUT1> <srpSwitch>true</srpSwitch> <sunSwitch>true</sunSwitch> <moonSwitch>true</moonSwitch> <extrapolationDuration>10891</extrapolationDuration> <warningFlag>false</warningFlag> <iterativeMode>false</iterativeMode> <GTOIntegrator> <Integrator> <effective_duration unit="years">8.820582752300558</effective_duration> <LOSCriteria1 version="2.5.0"> <status_criteria1>1</status_criteria1> <comment_criteria1>Lifetime :8.82 years</comment_criteria1> </LOSCriteria1> <LOSCriteria2 version="2.5.0"> <status_criteria2>3</status_criteria2> </LOSCriteria2> <LOSCriteria3 version="2.5.0"> <status_criteria3>3</status_criteria3> </LOSCriteria3> <LOSCriteria4 version="2.5.0"> <status_criteria4>3</status_criteria4> </LOSCriteria4> </Integrator> </GTOIntegrator> <modelType>GTO</modelType> <atmosModel>NRLMSISE-00</atmosModel> <VariableSolarActivity> <solActType>VARIABLE</solActType> </VariableSolarActivity> <integrationStep unit="s">86400.0</integrationStep> <dragSwitch>true</dragSwitch> <dragQuadPoints>33</dragQuadPoints> <atmosDragRecomputeStep>1</atmosDragRecomputeStep> <srpQuadPoints>11</srpQuadPoints> <reentryAltitude unit="m">120000.0</reentryAltitude> <iterationData> <funcValueAccuracy unit="days">10.0</funcValueAccuracy> <expDuration unit="years">24.75</expDuration> <simMinusExpDuration unit="years">75.25</simMinusExpDuration> <iterationMethod>FrozenOrbit</iterationMethod> </iterationData> <nbIntegrationStepTesseral>5.0</nbIntegrationStepTesseral> <zonalOrder>7</zonalOrder> </LEOSimulation>
{'content_hash': '2cbcde65572d1fbc3bb4205506804c8d', 'timestamp': '', 'source': 'github', 'line_count': 95, 'max_line_length': 74, 'avg_line_length': 35.36842105263158, 'alnum_prop': 0.7267857142857143, 'repo_name': 'pouyana/satgen', 'id': '941b85e587cf74d4dd7e470e1552f2d5c33047a0', 'size': '3360', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'sim/IF4RT19B_a_sim.xml_out_sim.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '552816'}, {'name': 'Matlab', 'bytes': '1015'}, {'name': 'Python', 'bytes': '227028'}]}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.9.1"/> <title>V8 API Reference Guide for node.js v0.6.0: Namespace Members</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">V8 API Reference Guide for node.js v0.6.0 </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.9.1 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li class="current"><a href="namespaces.html"><span>Namespaces</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li><a href="examples.html"><span>Examples</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="namespaces.html"><span>Namespace&#160;List</span></a></li> <li class="current"><a href="namespacemembers.html"><span>Namespace&#160;Members</span></a></li> </ul> </div> <div id="navrow3" class="tabs2"> <ul class="tablist"> <li><a href="namespacemembers.html"><span>All</span></a></li> <li class="current"><a href="namespacemembers_func.html"><span>Functions</span></a></li> <li><a href="namespacemembers_type.html"><span>Typedefs</span></a></li> <li><a href="namespacemembers_enum.html"><span>Enumerations</span></a></li> </ul> </div> </div><!-- top --> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="contents"> &#160;<ul> <li>ThrowException() : <a class="el" href="namespacev8.html#a2469af0ac719d39f77f20cf68dd9200e">v8</a> </li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Tue Aug 11 2015 23:47:28 for V8 API Reference Guide for node.js v0.6.0 by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.9.1 </small></address> </body> </html>
{'content_hash': '36f8fa6f3877dc79715c49b9e0620c3d', 'timestamp': '', 'source': 'github', 'line_count': 106, 'max_line_length': 154, 'avg_line_length': 40.89622641509434, 'alnum_prop': 0.6438292964244521, 'repo_name': 'v8-dox/v8-dox.github.io', 'id': '58002d8fccd129151d4d085d1f7dbf61758504ea', 'size': '4335', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '2dd68af/html/namespacemembers_func.html', 'mode': '33188', 'license': 'mit', 'language': []}
package org.apache.activemq.artemis.rest.queue; import javax.ws.rs.DefaultValue; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriInfo; import java.net.URI; import org.apache.activemq.artemis.api.core.ActiveMQException; import org.apache.activemq.artemis.api.core.client.ClientConsumer; import org.apache.activemq.artemis.api.core.client.ClientMessage; import org.apache.activemq.artemis.api.core.client.ClientSession; import org.apache.activemq.artemis.api.core.client.ClientSessionFactory; import org.apache.activemq.artemis.rest.ActiveMQRestLogger; import org.apache.activemq.artemis.rest.util.Constants; import org.apache.activemq.artemis.rest.util.LinkStrategy; import org.apache.activemq.artemis.jms.client.SelectorTranslator; /** * Auto-acknowleged consumer */ public class QueueConsumer { protected ClientSessionFactory factory; protected ClientSession session; protected ClientConsumer consumer; protected String destination; protected boolean closed; protected String id; protected long lastPing = System.currentTimeMillis(); protected DestinationServiceManager serviceManager; protected boolean autoAck = true; protected String selector; /** * token used to create consume-next links */ protected long previousIndex = -1; protected ConsumedMessage lastConsumed; public long getConsumeIndex() { if (lastConsumed == null) return -1; return lastConsumed.getMessageID(); } public DestinationServiceManager getServiceManager() { return serviceManager; } public void setServiceManager(DestinationServiceManager serviceManager) { this.serviceManager = serviceManager; } public long getLastPingTime() { return lastPing; } protected void ping(long offsetSecs) { lastPing = System.currentTimeMillis() + (offsetSecs * 1000); } public QueueConsumer(ClientSessionFactory factory, String destination, String id, DestinationServiceManager serviceManager, String selector) throws ActiveMQException { this.factory = factory; this.destination = destination; this.id = id; this.serviceManager = serviceManager; this.selector = selector; createSession(); } public String getId() { return id; } public boolean isClosed() { return closed; } public synchronized void shutdown() { if (closed) return; closed = true; lastConsumed = null; previousIndex = -2; try { consumer.close(); ActiveMQRestLogger.LOGGER.debug("Closed consumer: " + consumer); } catch (Exception e) { } try { session.close(); ActiveMQRestLogger.LOGGER.debug("Closed session: " + session); } catch (Exception e) { } session = null; consumer = null; } @Path("consume-next{index}") @POST public synchronized Response poll(@HeaderParam(Constants.WAIT_HEADER) @DefaultValue("0") long wait, @PathParam("index") long index, @Context UriInfo info) { ActiveMQRestLogger.LOGGER.debug("Handling POST request for \"" + info.getRequestUri() + "\""); if (closed) { UriBuilder builder = info.getBaseUriBuilder(); builder.path(info.getMatchedURIs().get(1)) .path("consume-next"); String uri = builder.build().toString(); // redirect to another consume-next return Response.status(307).location(URI.create(uri)).build(); } return checkIndexAndPoll(wait, info, info.getMatchedURIs().get(1), index); } protected Response checkIndexAndPoll(long wait, UriInfo info, String basePath, long index) { ping(wait); if (lastConsumed == null && index > 0) { return Response.status(412).entity("You are using an old consume-next link and are out of sync with the JMS session on the server").type("text/plain").build(); } if (lastConsumed != null) { if (index == previousIndex) { String token = Long.toString(lastConsumed.getMessageID()); return getMessageResponse(lastConsumed, info, basePath, token).build(); } if (index != lastConsumed.getMessageID()) { return Response.status(412).entity("You are using an old consume-next link and are out of sync with the JMS session on the server").type("text/plain").build(); } } try { return pollWithIndex(wait, info, basePath, index); } finally { ping(0); // ping again as we don't want wait time included in timeout. } } protected Response pollWithIndex(long wait, UriInfo info, String basePath, long index) { try { ClientMessage message = receive(wait); if (message == null) { Response.ResponseBuilder builder = Response.status(503).entity("Timed out waiting for message receive.").type("text/plain"); setPollTimeoutLinks(info, basePath, builder, Long.toString(index)); return builder.build(); } previousIndex = index; lastConsumed = ConsumedMessage.createConsumedMessage(message); String token = Long.toString(lastConsumed.getMessageID()); Response response = getMessageResponse(lastConsumed, info, basePath, token).build(); if (autoAck) message.acknowledge(); return response; } catch (Exception e) { throw new RuntimeException(e); } } protected void createSession() throws ActiveMQException { session = factory.createSession(true, true, 0); ActiveMQRestLogger.LOGGER.debug("Created session: " + session); if (selector == null) { consumer = session.createConsumer(destination); } else { consumer = session.createConsumer(destination, SelectorTranslator.convertToActiveMQFilterString(selector)); } ActiveMQRestLogger.LOGGER.debug("Created consumer: " + consumer); session.start(); } protected ClientMessage receiveFromConsumer(long timeoutSecs) throws Exception { ClientMessage m = null; if (timeoutSecs <= 0) { m = consumer.receive(1); } else { m = consumer.receive(timeoutSecs * 1000); } ActiveMQRestLogger.LOGGER.debug("Returning message " + m + " from consumer: " + consumer); return m; } protected ClientMessage receive(long timeoutSecs) throws Exception { return receiveFromConsumer(timeoutSecs); } protected void setPollTimeoutLinks(UriInfo info, String basePath, Response.ResponseBuilder builder, String index) { setSessionLink(builder, info, basePath); setConsumeNextLink(serviceManager.getLinkStrategy(), builder, info, basePath, index); } protected Response.ResponseBuilder getMessageResponse(ConsumedMessage msg, UriInfo info, String basePath, String index) { Response.ResponseBuilder responseBuilder = Response.ok(); setMessageResponseLinks(info, basePath, responseBuilder, index); msg.build(responseBuilder); return responseBuilder; } protected void setMessageResponseLinks(UriInfo info, String basePath, Response.ResponseBuilder responseBuilder, String index) { setConsumeNextLink(serviceManager.getLinkStrategy(), responseBuilder, info, basePath, index); setSessionLink(responseBuilder, info, basePath); } public static void setConsumeNextLink(LinkStrategy linkStrategy, Response.ResponseBuilder response, UriInfo info, String basePath, String index) { if (index == null) throw new IllegalArgumentException("index cannot be null"); UriBuilder builder = info.getBaseUriBuilder(); builder.path(basePath) .path("consume-next" + index); String uri = builder.build().toString(); linkStrategy.setLinkHeader(response, "consume-next", "consume-next", uri, MediaType.APPLICATION_FORM_URLENCODED); } public void setSessionLink(Response.ResponseBuilder response, UriInfo info, String basePath) { UriBuilder builder = info.getBaseUriBuilder(); builder.path(basePath); String uri = builder.build().toString(); serviceManager.getLinkStrategy().setLinkHeader(response, "consumer", "consumer", uri, MediaType.APPLICATION_XML); } }
{'content_hash': '5159296f1b91b5658cc30cd11edd9cb6', 'timestamp': '', 'source': 'github', 'line_count': 275, 'max_line_length': 171, 'avg_line_length': 31.716363636363635, 'alnum_prop': 0.6707177252923642, 'repo_name': 'jbertram/activemq-artemis-old', 'id': '9527d89dba3a07f95e8e908d37da585cc0272c66', 'size': '9522', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'artemis-rest/src/main/java/org/apache/activemq/artemis/rest/queue/QueueConsumer.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '2088'}, {'name': 'C++', 'bytes': '39402'}, {'name': 'CSS', 'bytes': '17995'}, {'name': 'HTML', 'bytes': '655853'}, {'name': 'Java', 'bytes': '16910061'}, {'name': 'JavaScript', 'bytes': '31054'}, {'name': 'Python', 'bytes': '3626'}, {'name': 'Ruby', 'bytes': '3412'}, {'name': 'Shell', 'bytes': '17315'}]}
package OptimizationTests.LoadHoistStoreSink.SimpleLoopStaticInt; public class Main { public static class A { public static int value; } public int testLoop(int a0) { A x; x = new A(); // pass a0, via parameter to isolate LHSS pass from other optimization passes for (int i = 0; i < 10; i++) { a0++; x.value = a0; } return x.value; } public void test() { System.out.println(testLoop(0x70000007)); } public static void main(String[] args) { new Main().test(); } }
{'content_hash': 'de7c262c15bc574da48cc38eb8a0df2c', 'timestamp': '', 'source': 'github', 'line_count': 36, 'max_line_length': 77, 'avg_line_length': 17.555555555555557, 'alnum_prop': 0.5189873417721519, 'repo_name': 'android-art-intel/marshmallow', 'id': 'e8d8593ac8e40027589e11695f3d8bc5bc9b5417', 'size': '1237', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'art-extension/opttests/src/OptimizationTests/LoadHoistStoreSink/SimpleLoopStaticInt/Main.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '505427'}, {'name': 'C', 'bytes': '57031'}, {'name': 'C++', 'bytes': '16360103'}, {'name': 'Java', 'bytes': '7260608'}, {'name': 'Lex', 'bytes': '1775'}, {'name': 'Makefile', 'bytes': '178336'}, {'name': 'Objective-J', 'bytes': '892'}, {'name': 'Python', 'bytes': '78048'}, {'name': 'Shell', 'bytes': '742921'}, {'name': 'Smali', 'bytes': '78883'}]}
require 'spec_helper' module Alf class Predicate describe Predicate, "factory methods" do before do subject.should be_a(Predicate) subject.expr.should be_a(Expr) end context "tautology" do subject{ Predicate.tautology } specify{ subject.to_ruby_code.should eq("->(t){ true }") } end context "contradiction" do subject{ Predicate.contradiction } specify{ subject.to_ruby_code.should eq("->(t){ false }") } end context "identifier" do subject{ Predicate.identifier(:x) } specify{ subject.to_ruby_code.should eq("->(t){ t.x }") } end context "eq" do subject{ Predicate.eq(:x, 2) } specify{ subject.to_ruby_code.should eq("->(t){ t.x == 2 }") } end context "neq" do subject{ Predicate.neq(:x, 2) } specify{ subject.to_ruby_code.should eq("->(t){ t.x != 2 }") } end context "lt" do subject{ Predicate.lt(:x, 2) } specify{ subject.to_ruby_code.should eq("->(t){ t.x < 2 }") } end context "lte" do subject{ Predicate.lte(:x, 2) } specify{ subject.to_ruby_code.should eq("->(t){ t.x <= 2 }") } end context "gt" do subject{ Predicate.gt(:x, 2) } specify{ subject.to_ruby_code.should eq("->(t){ t.x > 2 }") } end context "gte" do subject{ Predicate.gte(:x, 2) } specify{ subject.to_ruby_code.should eq("->(t){ t.x >= 2 }") } end context "literal" do subject{ Predicate.literal(2) } specify{ subject.to_ruby_code.should eq("->(t){ 2 }") } end context "native" do subject{ Predicate.native(lambda{}) } specify{ subject.expr.should be_a(Native) } end end end end
{'content_hash': '6a96df9ec0a4ceee43db062f477366e4', 'timestamp': '', 'source': 'github', 'line_count': 79, 'max_line_length': 70, 'avg_line_length': 23.050632911392405, 'alnum_prop': 0.5398132894014278, 'repo_name': 'alf-tool/alf-core', 'id': 'f0054e938f62b347ff9f3970cd2eee6b2df6c4e8', 'size': '1821', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spec/unit/alf-predicate/predicate/test_factory_methods.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '783335'}]}
"""Admin suppor for inlines Peter Cicman, Divio GmbH, 2008 """ from django.utils.text import capfirst, get_text_list from django.contrib.admin.util import flatten_fieldsets from django.http import HttpResponseRedirect from django.utils.encoding import force_unicode import re from copy import deepcopy from django.conf import settings from django import forms from django.contrib import admin from django.db.models import Model from django.forms.util import ErrorList, ValidationError from django.forms.models import BaseInlineFormSet, ModelFormMetaclass from django.utils.translation import ugettext as _ from django.template.loader import find_template from django.template import TemplateDoesNotExist from multilingual.languages import get_default_language from multilingual.utils import GLL MULTILINGUAL_PREFIX = '_ml__trans_' MULTILINGUAL_INLINE_PREFIX = '_ml__inline_trans_' def gll(func): def wrapped(cls, request, *args, **kwargs): cls.use_language = request.GET.get('lang', request.GET.get('language', get_default_language())) GLL.lock(cls.use_language) resp = func(cls, request, *args, **kwargs) GLL.release() return resp wrapped.__name__ = func.__name__ wrapped.__doc__ = func.__doc__ return wrapped def standard_get_fill_check_field(stdopts): if hasattr(stdopts, 'translation_model'): opts = stdopts.translation_model._meta for field in opts.fields: if field.name in ('language_code', 'master'): continue if not (field.blank or field.null): return field.name return None def relation_hack(form, fields, prefix=''): opts = form.instance._meta localm2m = [m2m.attname for m2m in opts.local_many_to_many] externalfk = [obj.field.related_query_name() for obj in opts.get_all_related_objects()] externalm2m = [m2m.get_accessor_name() for m2m in opts.get_all_related_many_to_many_objects()] for name, db_field in fields: full_name = '%s%s' % (prefix, name) if full_name in form.fields: value = getattr(form.instance, name, '') # check for (local) ForeignKeys if isinstance(value, Model): value = value.pk # check for (local) many to many fields elif name in localm2m: value = value.all() # check for (external) ForeignKeys elif name in externalfk: value = value.all() # check for (external) many to many fields elif name in externalm2m: value = value.all() form.fields[full_name].initial = value class MultilingualInlineModelForm(forms.ModelForm): def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=ErrorList, label_suffix=':', empty_permitted=False, instance=None): """ Fill initial ML Fields """ super(MultilingualInlineModelForm, self).__init__(data, files, auto_id, prefix, initial, error_class, label_suffix, empty_permitted, instance) # only read initial data if the object already exists, not if we're adding it! if self.instance.pk: relation_hack(self, get_translated_fields(self.instance), MULTILINGUAL_INLINE_PREFIX) class MultilingualInlineFormSet(BaseInlineFormSet): def get_queryset(self): if self.queryset is not None: qs = self.queryset else: qs = self.model._default_manager.get_query_set() if not qs.ordered: qs = qs.order_by(self.model._meta.pk.name) if self.max_num > 0: _queryset = qs[:self.max_num] else: _queryset = qs return _queryset def save_new(self, form, commit=True): """ NOTE: save_new method is completely overridden here, there's no other way to pretend double save otherwise. Just assign translated data to object """ kwargs = {self.fk.get_attname(): self.instance.pk} new_obj = self.model(**kwargs) self._prepare_multilingual_object(new_obj, form) return forms.save_instance(form, new_obj, exclude=[self._pk_field.name], commit=commit) def save_existing(self, form, instance, commit=True): """ NOTE: save_new method is completely overridden here, there's no other way to pretend double save otherwise. Just assign translated data to object """ self._prepare_multilingual_object(instance, form) return forms.save_instance(form, instance, exclude=[self._pk_field.name], commit=commit) def _prepare_multilingual_object(self, obj, form): opts = obj._meta for realname, fieldname in self.ml_fields.items(): field = opts.get_field_by_name(realname)[0] m = re.match(r'^%s(?P<field_name>.*)$' % MULTILINGUAL_INLINE_PREFIX, fieldname) if m: field.save_form_data(self.instance, form.cleaned_data[fieldname]) setattr(obj, realname, getattr(self.instance, realname.rsplit('_', 1)[0])) class MultilingualInlineAdmin(admin.TabularInline): formset = MultilingualInlineFormSet form = MultilingualInlineModelForm template = 'admin/multilingual/edit_inline/tabular.html' # css class added to inline box inline_css_class = None use_language = None fill_check_field = None #TODO: add some nice template def __init__(self, parent_model, admin_site): super(MultilingualInlineAdmin, self).__init__(parent_model, admin_site) if hasattr(self, 'use_fields'): # go around admin fields structure validation self.fields = self.use_fields def get_formset(self, request, obj=None, **kwargs): FormSet = super(MultilingualInlineAdmin, self).get_formset(request, obj, **kwargs) FormSet.use_language = GLL.language_code FormSet.ml_fields = {} for name, field in get_translated_fields(self.model, GLL.language_code): fieldname = '%s%s' % (MULTILINGUAL_INLINE_PREFIX, name) FormSet.form.base_fields[fieldname] = self.formfield_for_dbfield(field, request=request) FormSet.ml_fields[name] = fieldname return FormSet def queryset(self, request): """ Filter objects which don't have a value in this language """ qs = super(MultilingualInlineAdmin, self).queryset(request) # Don't now what the hell I was thinking here, but this code breaks stuff: # # checkfield = self.get_fill_check_field() # if checkfield is not None: # kwargs = {str('%s_%s__isnull' % (checkfield, GLL.language_code)): False} # from django.db.models.fields import CharField # if isinstance(self.model._meta.translation_model._meta.get_field_by_name(checkfield)[0], CharField): # kwargs[str('%s_%s__gt' % (checkfield, GLL.language_code))] = '' # return qs.filter(**kwargs) return qs.filter(translations__language_code=GLL.language_code).distinct() def get_fill_check_field(self): if self.fill_check_field is None: self.fill_check_field = standard_get_fill_check_field(self.model._meta) return self.fill_check_field class MultilingualModelAdminForm(forms.ModelForm): # for rendering / saving multilingual fields connecte to model, takes place # when admin per language is ussed def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=ErrorList, label_suffix=':', empty_permitted=False, instance=None): """ Fill up initial ML Fields """ super(MultilingualModelAdminForm, self).__init__(data, files, auto_id, prefix, initial, error_class, label_suffix, empty_permitted, instance) # only try to fill intial data if we are not adding an object! if self.instance.pk: fields = [(f, getattr(self.instance, "%s_%s" % (f, GLL.language_code), '')) for f in self.ml_fields] relation_hack(self, fields) def clean(self): cleaned_data = super(MultilingualModelAdminForm, self).clean() self.validate_ml_unique() return cleaned_data def validate_ml_unique(self): form_errors = [] if not hasattr(self.instance._meta, 'translation_model'): return for check in self.instance._meta.translation_model._meta.unique_together[:]: lookup_kwargs = {'language_code': GLL.language_code} for field_name in check: #local_name = "%s_%s" % (field_name, self.use_language) if self.cleaned_data.get(field_name) is not None: lookup_kwargs[field_name] = self.cleaned_data.get(field_name) if len(check) == 2 and 'master' in check and 'language_code' in check: continue qs = self.instance._meta.translation_model.objects.filter(**lookup_kwargs) if self.instance.pk is not None: qs = qs.exclude(master=self.instance.pk) if qs.count(): model_name = capfirst(self.instance._meta.verbose_name) field_labels = [] for field_name in check: if field_name == "language_code": field_labels.append(_("language")) elif field_name == "master": continue else: field_labels.append(self.instance._meta.translation_model._meta.get_field_by_name(field_name)[0].verbose_name) field_labels = get_text_list(field_labels, _('and')) form_errors.append( _(u"%(model_name)s with this %(field_label)s already exists.") % \ {'model_name': unicode(model_name), 'field_label': unicode(field_labels)} ) if form_errors: # Raise the unique together errors since they are considered # form-wide. raise ValidationError(form_errors) def save(self, commit=True): self._prepare_multilingual_object(self.instance, self) return super(MultilingualModelAdminForm, self).save(commit) def _prepare_multilingual_object(self, obj, form): opts = self.instance._meta for name in self.ml_fields: field = opts.get_field_by_name(name)[0] # respect save_form_data field.save_form_data(self.instance, form.cleaned_data[name]) setattr(obj, "%s_%s" % (name, GLL.language_code), getattr(self.instance, name)) class MultilingualModelAdmin(admin.ModelAdmin): # use special template to render tabs for languages on top change_form_template = "admin/multilingual/change_form.html" form = MultilingualModelAdminForm _multilingual_model_admin = True use_language = None fill_check_field = None _use_hacks = ['fieldsets', 'prepopulated_fields', 'readonly_fields'] class Media: css = { 'all': ('%smultilingual/admin/css/style.css' % settings.MEDIA_URL,) } def __init__(self, model, admin_site): for attr in self._use_hacks: if hasattr(self, 'use_%s' % attr): setattr(self, attr, getattr(self, 'use_%s' % attr)) super(MultilingualModelAdmin, self).__init__(model, admin_site) def get_fill_check_field(self): if self.fill_check_field is None: self.fill_check_field = standard_get_fill_check_field(self.model._meta) return self.fill_check_field def get_form(self, request, obj=None, **kwargs): # assign language to inlines, so they now how to render for inline in self.inline_instances: if isinstance(inline, MultilingualInlineAdmin): inline.use_language = GLL.language_code Form = super(MultilingualModelAdmin, self).get_form(request, obj, **kwargs) Form.ml_fields = {} for name, field in get_default_translated_fields(self.model): if not field.editable: continue form_field = self.formfield_for_dbfield(field, request=request) local_name = "%s_%s" % (name, GLL.language_code) Form.ml_fields[name] = form_field Form.base_fields[name] = form_field Form.use_language = GLL.language_code return Form def placeholder_plugin_filter(self, request, queryset): """ This is only used on models which use placeholders from the django-cms """ if not request: return queryset if GLL.is_active: return queryset.filter(language=GLL.language_code) return queryset @gll def change_view(self, *args, **kwargs): return super(MultilingualModelAdmin, self).change_view(*args, **kwargs) @gll def add_view(self, *args, **kwargs): return super(MultilingualModelAdmin, self).add_view(*args, **kwargs) @gll def delete_view(self, *args, **kwargs): return super(MultilingualModelAdmin, self).delete_view(*args, **kwargs) def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None): # add context variables filled_languages = [] fill_check_field = self.get_fill_check_field() if obj and fill_check_field is not None: from django.db.models.fields import CharField kwargs = {'%s__isnull' % fill_check_field:False} if isinstance(self.model._meta.translation_model._meta.get_field_by_name(fill_check_field)[0], CharField): kwargs['%s__gt' % fill_check_field] = '' filled_languages = [t[0] for t in obj.translations.filter(**kwargs).values_list('language_code')] context.update({ 'current_language_index': GLL.language_code, 'current_language_code': GLL.language_code, 'filled_languages': filled_languages, 'old_template': self.get_old_template(), }) return super(MultilingualModelAdmin, self).render_change_form(request, context, add, change, form_url, obj) def get_old_template(self): opts = self.model._meta app_label = opts.app_label search_templates = [ "admin/%s/%s/change_form.html" % (app_label, opts.object_name.lower()), "admin/%s/change_form.html" % app_label, "admin/change_form.html" ] for template in search_templates: try: find_template(template) return template except TemplateDoesNotExist: pass def response_change(self, request, obj): # because save & continue - so it shows the same language if request.POST.has_key("_continue"): opts = obj._meta msg = _('The %(name)s "%(obj)s" was changed successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(obj)} self.message_user(request, msg + ' ' + _("You may edit it again below.")) lang, path = request.GET.get('language', get_default_language()), request.path if lang: lang = "language=%s" % lang if request.REQUEST.has_key('_popup'): path += "?_popup=1" + "&%s" % lang else: path += "?%s" % lang return HttpResponseRedirect(path) return super(MultilingualModelAdmin, self).response_change(request, obj) def get_translated_fields(model, language=None): meta = model._meta if not hasattr(meta, 'translated_fields'): if hasattr(meta, 'translation_model'): meta = meta.translation_model._meta else: return # returns all the translatable fields, except of the default ones if not language: for name, (field, non_default) in meta.translated_fields.items(): if non_default: yield name, field else: # if language is defined return fields in the same order, like they are defined in the # translation class for field in meta.fields: if field.primary_key: continue name = field.name + "_%s" % language field = meta.translated_fields.get(name, None) if field: yield name, field[0] def get_default_translated_fields(model): if hasattr(model._meta, 'translation_model'): for name, (field, non_default) in model._meta.translation_model._meta.translated_fields.items(): if not non_default: yield name, field
{'content_hash': '90669dbd7df247e481c21e0d0a34d991', 'timestamp': '', 'source': 'github', 'line_count': 415, 'max_line_length': 143, 'avg_line_length': 41.60481927710843, 'alnum_prop': 0.5986331518591451, 'repo_name': 'ojii/django-multilingual-ng', 'id': '04c3e010dc7007efb4735c3b8a92c55754f4636b', 'size': '17266', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'multilingual/admin.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Python', 'bytes': '112011'}]}
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Marten.Events.Projections.Async; using Marten.Schema.Identity; namespace Marten.Events.Projections { public class ViewProjection<TView> : IProjection where TView : class, new() { private class EventHandler { public Func<IDocumentSession, object, Guid, Guid> IdSelector { get; } public Action<TView, object> Handler { get; } public EventHandler(Func<IDocumentSession, object, Guid, Guid> idSelector, Action<TView, object> handler) { IdSelector = idSelector; Handler = handler; } } private class EventProjection { public Guid ViewId { get; } public Action<TView> ProjectTo { get; } public EventProjection(EventHandler eventHandler, Guid viewId, IEvent @event) { ViewId = viewId; ProjectTo = view => eventHandler.Handler(view, @event.Data); } } private readonly IDictionary<Type, EventHandler> _handlers = new ConcurrentDictionary<Type, EventHandler>(); public Type[] Consumes => getUniqueEventTypes(); public Type Produces => typeof(TView); public AsyncOptions AsyncOptions { get; } = new AsyncOptions(); public ViewProjection<TView> ProjectEvent<TEvent>(Action<TView, TEvent> handler) where TEvent : class => projectEvent((session, @event, streamId) => streamId, handler); public ViewProjection<TView> ProjectEvent<TEvent>(Func<IDocumentSession, TEvent, Guid> viewIdSelector, Action<TView, TEvent> handler) where TEvent : class { if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector)); return projectEvent((session, @event, streamId) => viewIdSelector(session, @event as TEvent), handler); } public ViewProjection<TView> ProjectEvent<TEvent>(Func<TEvent, Guid> viewIdSelector, Action<TView, TEvent> handler) where TEvent : class { if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector)); return projectEvent((session, @event, streamId) => viewIdSelector(@event as TEvent), handler); } private ViewProjection<TView> projectEvent<TEvent>(Func<IDocumentSession, object, Guid, Guid> viewIdSelector, Action<TView, TEvent> handler) where TEvent : class { if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector)); if (handler == null) throw new ArgumentNullException(nameof(handler)); var eventHandler = new EventHandler(viewIdSelector, (view, @event) => handler(view, @event as TEvent)); _handlers.Add(typeof(TEvent), eventHandler); return this; } void IProjection.Apply(IDocumentSession session, EventStream[] streams) { var projections = getEventProjections(session, streams); var viewIds = projections.Select(projection => projection.ViewId).Distinct().ToArray(); var views = session.LoadMany<TView>(viewIds); applyProjections(session, projections, views); } async Task IProjection.ApplyAsync(IDocumentSession session, EventStream[] streams, CancellationToken token) { var projections = getEventProjections(session, streams); var viewIds = projections.Select(projection => projection.ViewId).Distinct().ToArray(); var views = await session.LoadManyAsync<TView>(token, viewIds); applyProjections(session, projections, views); } private void applyProjections(IDocumentSession session, IList<EventProjection> projections, IList<TView> views) { var viewMap = createViewMap(session, projections, views); foreach (var eventProjection in projections) { var view = viewMap[eventProjection.ViewId]; eventProjection.ProjectTo(view); } } private IDictionary<Guid, TView> createViewMap(IDocumentSession session, IList<EventProjection> projections, IList<TView> views) { var idAssigner = session.DocumentStore.Schema.IdAssignmentFor<TView>(); var resolver = session.DocumentStore.Schema.ResolverFor<TView>(); var viewMap = views.ToDictionary(view => (Guid) resolver.Identity(view), view => view); foreach (var projection in projections) { var viewId = projection.ViewId; TView view; if (!viewMap.TryGetValue(viewId, out view)) { view = newView(idAssigner, viewId); viewMap.Add(viewId, view); } session.Store(view); } return viewMap; } private static TView newView(IdAssignment<TView> idAssigner, Guid id) { var view = new TView(); idAssigner.Assign(view, id); return view; } private IList<EventProjection> getEventProjections(IDocumentSession session, EventStream[] streams) { var streamEvents = streams.SelectMany(stream => stream.Events.Select(@event => new { StreamId = stream.Id, Event = @event } )); var projections = new List<EventProjection>(); foreach (var streamEvent in streamEvents) { EventHandler handler; if (_handlers.TryGetValue(streamEvent.Event.Data.GetType(), out handler)) { var viewId = handler.IdSelector(session, streamEvent.Event.Data, streamEvent.StreamId); projections.Add(new EventProjection(handler, viewId, streamEvent.Event)); } } return projections; } private Type[] getUniqueEventTypes() { return _handlers.Keys .Union(_handlers.Keys) .Distinct() .ToArray(); } } }
{'content_hash': '2edab9870263806aade3de46d8a08e2a', 'timestamp': '', 'source': 'github', 'line_count': 157, 'max_line_length': 169, 'avg_line_length': 39.92993630573248, 'alnum_prop': 0.6152496410910832, 'repo_name': 'tim-cools/Marten', 'id': '43f9d21fe44f273273263cf3127be956ec3b5c59', 'size': '6269', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Marten/Events/Projections/ViewProjection.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '302'}, {'name': 'C#', 'bytes': '1969216'}, {'name': 'CSS', 'bytes': '50263'}, {'name': 'JavaScript', 'bytes': '449113'}, {'name': 'PLpgSQL', 'bytes': '3714'}, {'name': 'Ruby', 'bytes': '6200'}, {'name': 'SQLPL', 'bytes': '193'}]}
use strict; use Getopt::Long; # Tracepoint events use constant MM_VMSCAN_DIRECT_RECLAIM_BEGIN => 1; use constant MM_VMSCAN_DIRECT_RECLAIM_END => 2; use constant MM_VMSCAN_KSWAPD_WAKE => 3; use constant MM_VMSCAN_KSWAPD_SLEEP => 4; use constant MM_VMSCAN_LRU_SHRINK_ACTIVE => 5; use constant MM_VMSCAN_LRU_SHRINK_INACTIVE => 6; use constant MM_VMSCAN_LRU_ISOLATE => 7; use constant MM_VMSCAN_WRITEPAGE_FILE_SYNC => 8; use constant MM_VMSCAN_WRITEPAGE_ANON_SYNC => 9; use constant MM_VMSCAN_WRITEPAGE_FILE_ASYNC => 10; use constant MM_VMSCAN_WRITEPAGE_ANON_ASYNC => 11; use constant MM_VMSCAN_WRITEPAGE_ASYNC => 12; use constant EVENT_UNKNOWN => 13; # Per-order events use constant MM_VMSCAN_DIRECT_RECLAIM_BEGIN_PERORDER => 11; use constant MM_VMSCAN_WAKEUP_KSWAPD_PERORDER => 12; use constant MM_VMSCAN_KSWAPD_WAKE_PERORDER => 13; use constant HIGH_KSWAPD_REWAKEUP_PERORDER => 14; # Constants used to track state use constant STATE_DIRECT_BEGIN => 15; use constant STATE_DIRECT_ORDER => 16; use constant STATE_KSWAPD_BEGIN => 17; use constant STATE_KSWAPD_ORDER => 18; # High-level events extrapolated from tracepoints use constant HIGH_DIRECT_RECLAIM_LATENCY => 19; use constant HIGH_KSWAPD_LATENCY => 20; use constant HIGH_KSWAPD_REWAKEUP => 21; use constant HIGH_NR_SCANNED => 22; use constant HIGH_NR_TAKEN => 23; use constant HIGH_NR_RECLAIMED => 24; use constant HIGH_NR_CONTIG_DIRTY => 25; my %perprocesspid; my %perprocess; my %last_procmap; my $opt_ignorepid; my $opt_read_procstat; my $total_wakeup_kswapd; my ($total_direct_reclaim, $total_direct_nr_scanned); my ($total_direct_latency, $total_kswapd_latency); my ($total_direct_nr_reclaimed); my ($total_direct_writepage_file_sync, $total_direct_writepage_file_async); my ($total_direct_writepage_anon_sync, $total_direct_writepage_anon_async); my ($total_kswapd_nr_scanned, $total_kswapd_wake); my ($total_kswapd_writepage_file_sync, $total_kswapd_writepage_file_async); my ($total_kswapd_writepage_anon_sync, $total_kswapd_writepage_anon_async); my ($total_kswapd_nr_reclaimed); # Catch sigint and exit on request my $sigint_report = 0; my $sigint_exit = 0; my $sigint_pending = 0; my $sigint_received = 0; sub sigint_handler { my $current_time = time; if ($current_time - 2 > $sigint_received) { print "SIGINT received, report pending. Hit ctrl-c again to exit\n"; $sigint_report = 1; } else { if (!$sigint_exit) { print "Second SIGINT received quickly, exiting\n"; } $sigint_exit++; } if ($sigint_exit > 3) { print "Many SIGINTs received, exiting now without report\n"; exit; } $sigint_received = $current_time; $sigint_pending = 1; } $SIG{INT} = "sigint_handler"; # Parse command line options GetOptions( 'ignore-pid' => \$opt_ignorepid, 'read-procstat' => \$opt_read_procstat, ); # Defaults for dynamically discovered regex's my $regex_direct_begin_default = 'order=([0-9]*) may_writepage=([0-9]*) gfp_flags=([A-Z_|]*)'; my $regex_direct_end_default = 'nr_reclaimed=([0-9]*)'; my $regex_kswapd_wake_default = 'nid=([0-9]*) order=([0-9]*)'; my $regex_kswapd_sleep_default = 'nid=([0-9]*)'; my $regex_wakeup_kswapd_default = 'nid=([0-9]*) zid=([0-9]*) order=([0-9]*)'; my $regex_lru_isolate_default = 'isolate_mode=([0-9]*) order=([0-9]*) nr_requested=([0-9]*) nr_scanned=([0-9]*) nr_taken=([0-9]*) contig_taken=([0-9]*) contig_dirty=([0-9]*) contig_failed=([0-9]*)'; my $regex_lru_shrink_inactive_default = 'nid=([0-9]*) zid=([0-9]*) nr_scanned=([0-9]*) nr_reclaimed=([0-9]*) priority=([0-9]*) flags=([A-Z_|]*)'; my $regex_lru_shrink_active_default = 'lru=([A-Z_]*) nr_scanned=([0-9]*) nr_rotated=([0-9]*) priority=([0-9]*)'; my $regex_writepage_default = 'page=([0-9a-f]*) pfn=([0-9]*) flags=([A-Z_|]*)'; # Dyanically discovered regex my $regex_direct_begin; my $regex_direct_end; my $regex_kswapd_wake; my $regex_kswapd_sleep; my $regex_wakeup_kswapd; my $regex_lru_isolate; my $regex_lru_shrink_inactive; my $regex_lru_shrink_active; my $regex_writepage; # Static regex used. Specified like this for readability and for use with /o # (process_pid) (cpus ) ( time ) (tpoint ) (details) my $regex_traceevent = '\s*([a-zA-Z0-9-]*)\s*(\[[0-9]*\])\s*([0-9.]*):\s*([a-zA-Z_]*):\s*(.*)'; my $regex_statname = '[-0-9]*\s\((.*)\).*'; my $regex_statppid = '[-0-9]*\s\(.*\)\s[A-Za-z]\s([0-9]*).*'; sub generate_traceevent_regex { my $event = shift; my $default = shift; my $regex; # Read the event format or use the default if (!open (FORMAT, "/sys/kernel/debug/tracing/events/$event/format")) { print("WARNING: Event $event format string not found\n"); return $default; } else { my $line; while (!eof(FORMAT)) { $line = <FORMAT>; $line =~ s/, REC->.*//; if ($line =~ /^print fmt:\s"(.*)".*/) { $regex = $1; $regex =~ s/%s/\([0-9a-zA-Z|_]*\)/g; $regex =~ s/%p/\([0-9a-f]*\)/g; $regex =~ s/%d/\([-0-9]*\)/g; $regex =~ s/%ld/\([-0-9]*\)/g; $regex =~ s/%lu/\([0-9]*\)/g; } } } # Can't handle the print_flags stuff but in the context of this # script, it really doesn't matter $regex =~ s/\(REC.*\) \? __print_flags.*//; # Verify fields are in the right order my $tuple; foreach $tuple (split /\s/, $regex) { my ($key, $value) = split(/=/, $tuple); my $expected = shift; if ($key ne $expected) { print("WARNING: Format not as expected for event $event '$key' != '$expected'\n"); $regex =~ s/$key=\((.*)\)/$key=$1/; } } if (defined shift) { die("Fewer fields than expected in format"); } return $regex; } $regex_direct_begin = generate_traceevent_regex( "vmscan/mm_vmscan_direct_reclaim_begin", $regex_direct_begin_default, "order", "may_writepage", "gfp_flags"); $regex_direct_end = generate_traceevent_regex( "vmscan/mm_vmscan_direct_reclaim_end", $regex_direct_end_default, "nr_reclaimed"); $regex_kswapd_wake = generate_traceevent_regex( "vmscan/mm_vmscan_kswapd_wake", $regex_kswapd_wake_default, "nid", "order"); $regex_kswapd_sleep = generate_traceevent_regex( "vmscan/mm_vmscan_kswapd_sleep", $regex_kswapd_sleep_default, "nid"); $regex_wakeup_kswapd = generate_traceevent_regex( "vmscan/mm_vmscan_wakeup_kswapd", $regex_wakeup_kswapd_default, "nid", "zid", "order"); $regex_lru_isolate = generate_traceevent_regex( "vmscan/mm_vmscan_lru_isolate", $regex_lru_isolate_default, "isolate_mode", "order", "nr_requested", "nr_scanned", "nr_taken", "contig_taken", "contig_dirty", "contig_failed"); $regex_lru_shrink_inactive = generate_traceevent_regex( "vmscan/mm_vmscan_lru_shrink_inactive", $regex_lru_shrink_inactive_default, "nid", "zid", "nr_scanned", "nr_reclaimed", "priority", "flags"); $regex_lru_shrink_active = generate_traceevent_regex( "vmscan/mm_vmscan_lru_shrink_active", $regex_lru_shrink_active_default, "nid", "zid", "lru", "nr_scanned", "nr_rotated", "priority"); $regex_writepage = generate_traceevent_regex( "vmscan/mm_vmscan_writepage", $regex_writepage_default, "page", "pfn", "flags"); sub read_statline($) { my $pid = $_[0]; my $statline; if (open(STAT, "/proc/$pid/stat")) { $statline = <STAT>; close(STAT); } if ($statline eq '') { $statline = "-1 (UNKNOWN_PROCESS_NAME) R 0"; } return $statline; } sub guess_process_pid($$) { my $pid = $_[0]; my $statline = $_[1]; if ($pid == 0) { return "swapper-0"; } if ($statline !~ /$regex_statname/o) { die("Failed to math stat line for process name :: $statline"); } return "$1-$pid"; } # Convert sec.usec timestamp format sub timestamp_to_ms($) { my $timestamp = $_[0]; my ($sec, $usec) = split (/\./, $timestamp); return ($sec * 1000) + ($usec / 1000); } sub process_events { my $traceevent; my $process_pid; my $cpus; my $timestamp; my $tracepoint; my $details; my $statline; # Read each line of the event log EVENT_PROCESS: while ($traceevent = <STDIN>) { if ($traceevent =~ /$regex_traceevent/o) { $process_pid = $1; $timestamp = $3; $tracepoint = $4; $process_pid =~ /(.*)-([0-9]*)$/; my $process = $1; my $pid = $2; if ($process eq "") { $process = $last_procmap{$pid}; $process_pid = "$process-$pid"; } $last_procmap{$pid} = $process; if ($opt_read_procstat) { $statline = read_statline($pid); if ($opt_read_procstat && $process eq '') { $process_pid = guess_process_pid($pid, $statline); } } } else { next; } # Perl Switch() sucks majorly if ($tracepoint eq "mm_vmscan_direct_reclaim_begin") { $timestamp = timestamp_to_ms($timestamp); $perprocesspid{$process_pid}->{MM_VMSCAN_DIRECT_RECLAIM_BEGIN}++; $perprocesspid{$process_pid}->{STATE_DIRECT_BEGIN} = $timestamp; $details = $5; if ($details !~ /$regex_direct_begin/o) { print "WARNING: Failed to parse mm_vmscan_direct_reclaim_begin as expected\n"; print " $details\n"; print " $regex_direct_begin\n"; next; } my $order = $1; $perprocesspid{$process_pid}->{MM_VMSCAN_DIRECT_RECLAIM_BEGIN_PERORDER}[$order]++; $perprocesspid{$process_pid}->{STATE_DIRECT_ORDER} = $order; } elsif ($tracepoint eq "mm_vmscan_direct_reclaim_end") { # Count the event itself my $index = $perprocesspid{$process_pid}->{MM_VMSCAN_DIRECT_RECLAIM_END}; $perprocesspid{$process_pid}->{MM_VMSCAN_DIRECT_RECLAIM_END}++; # Record how long direct reclaim took this time if (defined $perprocesspid{$process_pid}->{STATE_DIRECT_BEGIN}) { $timestamp = timestamp_to_ms($timestamp); my $order = $perprocesspid{$process_pid}->{STATE_DIRECT_ORDER}; my $latency = ($timestamp - $perprocesspid{$process_pid}->{STATE_DIRECT_BEGIN}); $perprocesspid{$process_pid}->{HIGH_DIRECT_RECLAIM_LATENCY}[$index] = "$order-$latency"; } } elsif ($tracepoint eq "mm_vmscan_kswapd_wake") { $details = $5; if ($details !~ /$regex_kswapd_wake/o) { print "WARNING: Failed to parse mm_vmscan_kswapd_wake as expected\n"; print " $details\n"; print " $regex_kswapd_wake\n"; next; } my $order = $2; $perprocesspid{$process_pid}->{STATE_KSWAPD_ORDER} = $order; if (!$perprocesspid{$process_pid}->{STATE_KSWAPD_BEGIN}) { $timestamp = timestamp_to_ms($timestamp); $perprocesspid{$process_pid}->{MM_VMSCAN_KSWAPD_WAKE}++; $perprocesspid{$process_pid}->{STATE_KSWAPD_BEGIN} = $timestamp; $perprocesspid{$process_pid}->{MM_VMSCAN_KSWAPD_WAKE_PERORDER}[$order]++; } else { $perprocesspid{$process_pid}->{HIGH_KSWAPD_REWAKEUP}++; $perprocesspid{$process_pid}->{HIGH_KSWAPD_REWAKEUP_PERORDER}[$order]++; } } elsif ($tracepoint eq "mm_vmscan_kswapd_sleep") { # Count the event itself my $index = $perprocesspid{$process_pid}->{MM_VMSCAN_KSWAPD_SLEEP}; $perprocesspid{$process_pid}->{MM_VMSCAN_KSWAPD_SLEEP}++; # Record how long kswapd was awake $timestamp = timestamp_to_ms($timestamp); my $order = $perprocesspid{$process_pid}->{STATE_KSWAPD_ORDER}; my $latency = ($timestamp - $perprocesspid{$process_pid}->{STATE_KSWAPD_BEGIN}); $perprocesspid{$process_pid}->{HIGH_KSWAPD_LATENCY}[$index] = "$order-$latency"; $perprocesspid{$process_pid}->{STATE_KSWAPD_BEGIN} = 0; } elsif ($tracepoint eq "mm_vmscan_wakeup_kswapd") { $perprocesspid{$process_pid}->{MM_VMSCAN_WAKEUP_KSWAPD}++; $details = $5; if ($details !~ /$regex_wakeup_kswapd/o) { print "WARNING: Failed to parse mm_vmscan_wakeup_kswapd as expected\n"; print " $details\n"; print " $regex_wakeup_kswapd\n"; next; } my $order = $3; $perprocesspid{$process_pid}->{MM_VMSCAN_WAKEUP_KSWAPD_PERORDER}[$order]++; } elsif ($tracepoint eq "mm_vmscan_lru_isolate") { $details = $5; if ($details !~ /$regex_lru_isolate/o) { print "WARNING: Failed to parse mm_vmscan_lru_isolate as expected\n"; print " $details\n"; print " $regex_lru_isolate/o\n"; next; } my $isolate_mode = $1; my $nr_scanned = $4; my $nr_contig_dirty = $7; # To closer match vmstat scanning statistics, only count isolate_both # and isolate_inactive as scanning. isolate_active is rotation # isolate_inactive == 0 # isolate_active == 1 # isolate_both == 2 if ($isolate_mode != 1) { $perprocesspid{$process_pid}->{HIGH_NR_SCANNED} += $nr_scanned; } $perprocesspid{$process_pid}->{HIGH_NR_CONTIG_DIRTY} += $nr_contig_dirty; } elsif ($tracepoint eq "mm_vmscan_lru_shrink_inactive") { $details = $5; if ($details !~ /$regex_lru_shrink_inactive/o) { print "WARNING: Failed to parse mm_vmscan_lru_shrink_inactive as expected\n"; print " $details\n"; print " $regex_lru_shrink_inactive/o\n"; next; } my $nr_reclaimed = $4; $perprocesspid{$process_pid}->{HIGH_NR_RECLAIMED} += $nr_reclaimed; } elsif ($tracepoint eq "mm_vmscan_writepage") { $details = $5; if ($details !~ /$regex_writepage/o) { print "WARNING: Failed to parse mm_vmscan_writepage as expected\n"; print " $details\n"; print " $regex_writepage\n"; next; } my $flags = $3; my $file = 0; my $sync_io = 0; if ($flags =~ /RECLAIM_WB_FILE/) { $file = 1; } if ($flags =~ /RECLAIM_WB_SYNC/) { $sync_io = 1; } if ($sync_io) { if ($file) { $perprocesspid{$process_pid}->{MM_VMSCAN_WRITEPAGE_FILE_SYNC}++; } else { $perprocesspid{$process_pid}->{MM_VMSCAN_WRITEPAGE_ANON_SYNC}++; } } else { if ($file) { $perprocesspid{$process_pid}->{MM_VMSCAN_WRITEPAGE_FILE_ASYNC}++; } else { $perprocesspid{$process_pid}->{MM_VMSCAN_WRITEPAGE_ANON_ASYNC}++; } } } else { $perprocesspid{$process_pid}->{EVENT_UNKNOWN}++; } if ($sigint_pending) { last EVENT_PROCESS; } } } sub dump_stats { my $hashref = shift; my %stats = %$hashref; # Dump per-process stats my $process_pid; my $max_strlen = 0; # Get the maximum process name foreach $process_pid (keys %perprocesspid) { my $len = length($process_pid); if ($len > $max_strlen) { $max_strlen = $len; } } $max_strlen += 2; # Work out latencies printf("\n") if !$opt_ignorepid; printf("Reclaim latencies expressed as order-latency_in_ms\n") if !$opt_ignorepid; foreach $process_pid (keys %stats) { if (!$stats{$process_pid}->{HIGH_DIRECT_RECLAIM_LATENCY}[0] && !$stats{$process_pid}->{HIGH_KSWAPD_LATENCY}[0]) { next; } printf "%-" . $max_strlen . "s ", $process_pid if !$opt_ignorepid; my $index = 0; while (defined $stats{$process_pid}->{HIGH_DIRECT_RECLAIM_LATENCY}[$index] || defined $stats{$process_pid}->{HIGH_KSWAPD_LATENCY}[$index]) { if ($stats{$process_pid}->{HIGH_DIRECT_RECLAIM_LATENCY}[$index]) { printf("%s ", $stats{$process_pid}->{HIGH_DIRECT_RECLAIM_LATENCY}[$index]) if !$opt_ignorepid; my ($dummy, $latency) = split(/-/, $stats{$process_pid}->{HIGH_DIRECT_RECLAIM_LATENCY}[$index]); $total_direct_latency += $latency; } else { printf("%s ", $stats{$process_pid}->{HIGH_KSWAPD_LATENCY}[$index]) if !$opt_ignorepid; my ($dummy, $latency) = split(/-/, $stats{$process_pid}->{HIGH_KSWAPD_LATENCY}[$index]); $total_kswapd_latency += $latency; } $index++; } print "\n" if !$opt_ignorepid; } # Print out process activity printf("\n"); printf("%-" . $max_strlen . "s %8s %10s %8s %8s %8s %8s %8s %8s\n", "Process", "Direct", "Wokeup", "Pages", "Pages", "Pages", "Pages", "Time"); printf("%-" . $max_strlen . "s %8s %10s %8s %8s %8s %8s %8s %8s\n", "details", "Rclms", "Kswapd", "Scanned", "Rclmed", "Sync-IO", "ASync-IO", "Stalled"); foreach $process_pid (keys %stats) { if (!$stats{$process_pid}->{MM_VMSCAN_DIRECT_RECLAIM_BEGIN}) { next; } $total_direct_reclaim += $stats{$process_pid}->{MM_VMSCAN_DIRECT_RECLAIM_BEGIN}; $total_wakeup_kswapd += $stats{$process_pid}->{MM_VMSCAN_WAKEUP_KSWAPD}; $total_direct_nr_scanned += $stats{$process_pid}->{HIGH_NR_SCANNED}; $total_direct_nr_reclaimed += $stats{$process_pid}->{HIGH_NR_RECLAIMED}; $total_direct_writepage_file_sync += $stats{$process_pid}->{MM_VMSCAN_WRITEPAGE_FILE_SYNC}; $total_direct_writepage_anon_sync += $stats{$process_pid}->{MM_VMSCAN_WRITEPAGE_ANON_SYNC}; $total_direct_writepage_file_async += $stats{$process_pid}->{MM_VMSCAN_WRITEPAGE_FILE_ASYNC}; $total_direct_writepage_anon_async += $stats{$process_pid}->{MM_VMSCAN_WRITEPAGE_ANON_ASYNC}; my $index = 0; my $this_reclaim_delay = 0; while (defined $stats{$process_pid}->{HIGH_DIRECT_RECLAIM_LATENCY}[$index]) { my ($dummy, $latency) = split(/-/, $stats{$process_pid}->{HIGH_DIRECT_RECLAIM_LATENCY}[$index]); $this_reclaim_delay += $latency; $index++; } printf("%-" . $max_strlen . "s %8d %10d %8u %8u %8u %8u %8.3f", $process_pid, $stats{$process_pid}->{MM_VMSCAN_DIRECT_RECLAIM_BEGIN}, $stats{$process_pid}->{MM_VMSCAN_WAKEUP_KSWAPD}, $stats{$process_pid}->{HIGH_NR_SCANNED}, $stats{$process_pid}->{HIGH_NR_RECLAIMED}, $stats{$process_pid}->{MM_VMSCAN_WRITEPAGE_FILE_SYNC} + $stats{$process_pid}->{MM_VMSCAN_WRITEPAGE_ANON_SYNC}, $stats{$process_pid}->{MM_VMSCAN_WRITEPAGE_FILE_ASYNC} + $stats{$process_pid}->{MM_VMSCAN_WRITEPAGE_ANON_ASYNC}, $this_reclaim_delay / 1000); if ($stats{$process_pid}->{MM_VMSCAN_DIRECT_RECLAIM_BEGIN}) { print " "; for (my $order = 0; $order < 20; $order++) { my $count = $stats{$process_pid}->{MM_VMSCAN_DIRECT_RECLAIM_BEGIN_PERORDER}[$order]; if ($count != 0) { print "direct-$order=$count "; } } } if ($stats{$process_pid}->{MM_VMSCAN_WAKEUP_KSWAPD}) { print " "; for (my $order = 0; $order < 20; $order++) { my $count = $stats{$process_pid}->{MM_VMSCAN_WAKEUP_KSWAPD_PERORDER}[$order]; if ($count != 0) { print "wakeup-$order=$count "; } } } if ($stats{$process_pid}->{HIGH_NR_CONTIG_DIRTY}) { print " "; my $count = $stats{$process_pid}->{HIGH_NR_CONTIG_DIRTY}; if ($count != 0) { print "contig-dirty=$count "; } } print "\n"; } # Print out kswapd activity printf("\n"); printf("%-" . $max_strlen . "s %8s %10s %8s %8s %8s %8s\n", "Kswapd", "Kswapd", "Order", "Pages", "Pages", "Pages", "Pages"); printf("%-" . $max_strlen . "s %8s %10s %8s %8s %8s %8s\n", "Instance", "Wakeups", "Re-wakeup", "Scanned", "Rclmed", "Sync-IO", "ASync-IO"); foreach $process_pid (keys %stats) { if (!$stats{$process_pid}->{MM_VMSCAN_KSWAPD_WAKE}) { next; } $total_kswapd_wake += $stats{$process_pid}->{MM_VMSCAN_KSWAPD_WAKE}; $total_kswapd_nr_scanned += $stats{$process_pid}->{HIGH_NR_SCANNED}; $total_kswapd_nr_reclaimed += $stats{$process_pid}->{HIGH_NR_RECLAIMED}; $total_kswapd_writepage_file_sync += $stats{$process_pid}->{MM_VMSCAN_WRITEPAGE_FILE_SYNC}; $total_kswapd_writepage_anon_sync += $stats{$process_pid}->{MM_VMSCAN_WRITEPAGE_ANON_SYNC}; $total_kswapd_writepage_file_async += $stats{$process_pid}->{MM_VMSCAN_WRITEPAGE_FILE_ASYNC}; $total_kswapd_writepage_anon_async += $stats{$process_pid}->{MM_VMSCAN_WRITEPAGE_ANON_ASYNC}; printf("%-" . $max_strlen . "s %8d %10d %8u %8u %8i %8u", $process_pid, $stats{$process_pid}->{MM_VMSCAN_KSWAPD_WAKE}, $stats{$process_pid}->{HIGH_KSWAPD_REWAKEUP}, $stats{$process_pid}->{HIGH_NR_SCANNED}, $stats{$process_pid}->{HIGH_NR_RECLAIMED}, $stats{$process_pid}->{MM_VMSCAN_WRITEPAGE_FILE_SYNC} + $stats{$process_pid}->{MM_VMSCAN_WRITEPAGE_ANON_SYNC}, $stats{$process_pid}->{MM_VMSCAN_WRITEPAGE_FILE_ASYNC} + $stats{$process_pid}->{MM_VMSCAN_WRITEPAGE_ANON_ASYNC}); if ($stats{$process_pid}->{MM_VMSCAN_KSWAPD_WAKE}) { print " "; for (my $order = 0; $order < 20; $order++) { my $count = $stats{$process_pid}->{MM_VMSCAN_KSWAPD_WAKE_PERORDER}[$order]; if ($count != 0) { print "wake-$order=$count "; } } } if ($stats{$process_pid}->{HIGH_KSWAPD_REWAKEUP}) { print " "; for (my $order = 0; $order < 20; $order++) { my $count = $stats{$process_pid}->{HIGH_KSWAPD_REWAKEUP_PERORDER}[$order]; if ($count != 0) { print "rewake-$order=$count "; } } } printf("\n"); } # Print out summaries $total_direct_latency /= 1000; $total_kswapd_latency /= 1000; print "\nSummary\n"; print "Direct reclaims: $total_direct_reclaim\n"; print "Direct reclaim pages scanned: $total_direct_nr_scanned\n"; print "Direct reclaim pages reclaimed: $total_direct_nr_reclaimed\n"; print "Direct reclaim write file sync I/O: $total_direct_writepage_file_sync\n"; print "Direct reclaim write anon sync I/O: $total_direct_writepage_anon_sync\n"; print "Direct reclaim write file async I/O: $total_direct_writepage_file_async\n"; print "Direct reclaim write anon async I/O: $total_direct_writepage_anon_async\n"; print "Wake kswapd requests: $total_wakeup_kswapd\n"; printf "Time stalled direct reclaim: %-1.2f seconds\n", $total_direct_latency; print "\n"; print "Kswapd wakeups: $total_kswapd_wake\n"; print "Kswapd pages scanned: $total_kswapd_nr_scanned\n"; print "Kswapd pages reclaimed: $total_kswapd_nr_reclaimed\n"; print "Kswapd reclaim write file sync I/O: $total_kswapd_writepage_file_sync\n"; print "Kswapd reclaim write anon sync I/O: $total_kswapd_writepage_anon_sync\n"; print "Kswapd reclaim write file async I/O: $total_kswapd_writepage_file_async\n"; print "Kswapd reclaim write anon async I/O: $total_kswapd_writepage_anon_async\n"; printf "Time kswapd awake: %-1.2f seconds\n", $total_kswapd_latency; } sub aggregate_perprocesspid() { my $process_pid; my $process; undef %perprocess; foreach $process_pid (keys %perprocesspid) { $process = $process_pid; $process =~ s/-([0-9])*$//; if ($process eq '') { $process = "NO_PROCESS_NAME"; } $perprocess{$process}->{MM_VMSCAN_DIRECT_RECLAIM_BEGIN} += $perprocesspid{$process_pid}->{MM_VMSCAN_DIRECT_RECLAIM_BEGIN}; $perprocess{$process}->{MM_VMSCAN_KSWAPD_WAKE} += $perprocesspid{$process_pid}->{MM_VMSCAN_KSWAPD_WAKE}; $perprocess{$process}->{MM_VMSCAN_WAKEUP_KSWAPD} += $perprocesspid{$process_pid}->{MM_VMSCAN_WAKEUP_KSWAPD}; $perprocess{$process}->{HIGH_KSWAPD_REWAKEUP} += $perprocesspid{$process_pid}->{HIGH_KSWAPD_REWAKEUP}; $perprocess{$process}->{HIGH_NR_SCANNED} += $perprocesspid{$process_pid}->{HIGH_NR_SCANNED}; $perprocess{$process}->{HIGH_NR_RECLAIMED} += $perprocesspid{$process_pid}->{HIGH_NR_RECLAIMED}; $perprocess{$process}->{MM_VMSCAN_WRITEPAGE_FILE_SYNC} += $perprocesspid{$process_pid}->{MM_VMSCAN_WRITEPAGE_FILE_SYNC}; $perprocess{$process}->{MM_VMSCAN_WRITEPAGE_ANON_SYNC} += $perprocesspid{$process_pid}->{MM_VMSCAN_WRITEPAGE_ANON_SYNC}; $perprocess{$process}->{MM_VMSCAN_WRITEPAGE_FILE_ASYNC} += $perprocesspid{$process_pid}->{MM_VMSCAN_WRITEPAGE_FILE_ASYNC}; $perprocess{$process}->{MM_VMSCAN_WRITEPAGE_ANON_ASYNC} += $perprocesspid{$process_pid}->{MM_VMSCAN_WRITEPAGE_ANON_ASYNC}; for (my $order = 0; $order < 20; $order++) { $perprocess{$process}->{MM_VMSCAN_DIRECT_RECLAIM_BEGIN_PERORDER}[$order] += $perprocesspid{$process_pid}->{MM_VMSCAN_DIRECT_RECLAIM_BEGIN_PERORDER}[$order]; $perprocess{$process}->{MM_VMSCAN_WAKEUP_KSWAPD_PERORDER}[$order] += $perprocesspid{$process_pid}->{MM_VMSCAN_WAKEUP_KSWAPD_PERORDER}[$order]; $perprocess{$process}->{MM_VMSCAN_KSWAPD_WAKE_PERORDER}[$order] += $perprocesspid{$process_pid}->{MM_VMSCAN_KSWAPD_WAKE_PERORDER}[$order]; } # Aggregate direct reclaim latencies my $wr_index = $perprocess{$process}->{MM_VMSCAN_DIRECT_RECLAIM_END}; my $rd_index = 0; while (defined $perprocesspid{$process_pid}->{HIGH_DIRECT_RECLAIM_LATENCY}[$rd_index]) { $perprocess{$process}->{HIGH_DIRECT_RECLAIM_LATENCY}[$wr_index] = $perprocesspid{$process_pid}->{HIGH_DIRECT_RECLAIM_LATENCY}[$rd_index]; $rd_index++; $wr_index++; } $perprocess{$process}->{MM_VMSCAN_DIRECT_RECLAIM_END} = $wr_index; # Aggregate kswapd latencies my $wr_index = $perprocess{$process}->{MM_VMSCAN_KSWAPD_SLEEP}; my $rd_index = 0; while (defined $perprocesspid{$process_pid}->{HIGH_KSWAPD_LATENCY}[$rd_index]) { $perprocess{$process}->{HIGH_KSWAPD_LATENCY}[$wr_index] = $perprocesspid{$process_pid}->{HIGH_KSWAPD_LATENCY}[$rd_index]; $rd_index++; $wr_index++; } $perprocess{$process}->{MM_VMSCAN_DIRECT_RECLAIM_END} = $wr_index; } } sub report() { if (!$opt_ignorepid) { dump_stats(\%perprocesspid); } else { aggregate_perprocesspid(); dump_stats(\%perprocess); } } # Process events or signals until neither is available sub signal_loop() { my $sigint_processed; do { $sigint_processed = 0; process_events(); # Handle pending signals if any if ($sigint_pending) { my $current_time = time; if ($sigint_exit) { print "Received exit signal\n"; $sigint_pending = 0; } if ($sigint_report) { if ($current_time >= $sigint_received + 2) { report(); $sigint_report = 0; $sigint_pending = 0; $sigint_processed = 1; } } } } while ($sigint_pending || $sigint_processed); } signal_loop(); report();
{'content_hash': 'b88ea3b9fd063b20adf9bf510e0bd369', 'timestamp': '', 'source': 'github', 'line_count': 702, 'max_line_length': 198, 'avg_line_length': 35.70940170940171, 'alnum_prop': 0.6394207754906653, 'repo_name': 'sahdman/rpi_android_kernel', 'id': '12cecc83cd91c658c71524bba59762b83f810829', 'size': '25609', 'binary': False, 'copies': '2059', 'ref': 'refs/heads/master', 'path': 'linux-3.1.9/Documentation/trace/postprocess/trace-vmscan-postprocess.pl', 'mode': '33188', 'license': 'mit', 'language': []}
class ApplicationController < ActionController::Base skip_before_filter :verify_authenticity_token before_filter :cors_preflight_check after_filter :cors_set_access_control_headers # Metodos CORS def cors_set_access_control_headers headers['Access-Control-Allow-Origin'] = '*' headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization' headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS, DELETE' headers['Access-Control-Max-Age'] = "1728000" end # If this is a preflight OPTIONS request, then short-circuit the # request, return only the necessary headers and return an empty # text/plain. def cors_preflight_check if request.method == "OPTIONS" headers['Access-Control-Allow-Origin'] = '*' headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE' headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization' headers['Access-Control-Max-Age'] = '1728000' render :text => '', :content_type => 'application/json' end end end
{'content_hash': '8fa5f287cf8db77ca957c82c4334bb1b', 'timestamp': '', 'source': 'github', 'line_count': 28, 'max_line_length': 111, 'avg_line_length': 39.857142857142854, 'alnum_prop': 0.706989247311828, 'repo_name': 'brahian609/mailman_example', 'id': '4000b42d06a76fdba7ccee120f7a9ca864cdca47', 'size': '1116', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/controllers/application_controller.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1839'}, {'name': 'CoffeeScript', 'bytes': '229'}, {'name': 'HTML', 'bytes': '37496'}, {'name': 'JavaScript', 'bytes': '641'}, {'name': 'Ruby', 'bytes': '85124'}]}
From Initial Baby steps to Pro in GO Programming
{'content_hash': '78e4afa2ede24b9352eb87b6682876bd', 'timestamp': '', 'source': 'github', 'line_count': 1, 'max_line_length': 48, 'avg_line_length': 49.0, 'alnum_prop': 0.8163265306122449, 'repo_name': 'prakhar21/Go', 'id': '7b6e6def53e86b573ad68d25b60a9162e49d037e', 'size': '54', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Go', 'bytes': '9901'}]}
import javax.swing.DefaultListModel; import javax.swing.JOptionPane; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author iliana */ public class BaleadasBinarias extends javax.swing.JFrame { /** * Creates new form BaleadasBinarias */ public BaleadasBinarias() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { OrdenBaleada = new javax.swing.JDialog(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); jButton5 = new javax.swing.JButton(); jLabel6 = new javax.swing.JLabel(); jButton7 = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); tf_nombre = new javax.swing.JTextField(); tf_telefono = new javax.swing.JTextField(); tf_efectivo = new javax.swing.JTextField(); jScrollPane1 = new javax.swing.JScrollPane(); ta_direccion = new javax.swing.JTextArea(); b_agregar = new javax.swing.JButton(); b_modificar = new javax.swing.JButton(); jScrollPane2 = new javax.swing.JScrollPane(); lista = new javax.swing.JList<>(); jScrollPane3 = new javax.swing.JScrollPane(); arbol = new javax.swing.JTree(); jButton1 = new javax.swing.JButton(); jButton6 = new javax.swing.JButton(); jButton8 = new javax.swing.JButton(); jButton2.setText("Baleadas Especiales"); jButton2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton2MouseClicked(evt); } }); jButton3.setText("Baleadas Binarias"); jButton3.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton3MouseClicked(evt); } }); jButton4.setText("Baleadas Reloaded"); jButton4.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton4MouseClicked(evt); } }); jButton5.setText("Baleadas OutOfBounce"); jButton5.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton5MouseClicked(evt); } }); jLabel6.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel6.setText("Agregar orden"); jButton7.setText("Agregar orden"); jButton7.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton7MouseClicked(evt); } }); javax.swing.GroupLayout OrdenBaleadaLayout = new javax.swing.GroupLayout(OrdenBaleada.getContentPane()); OrdenBaleada.getContentPane().setLayout(OrdenBaleadaLayout); OrdenBaleadaLayout.setHorizontalGroup( OrdenBaleadaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(OrdenBaleadaLayout.createSequentialGroup() .addGroup(OrdenBaleadaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(OrdenBaleadaLayout.createSequentialGroup() .addContainerGap() .addGroup(OrdenBaleadaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 144, Short.MAX_VALUE) .addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(OrdenBaleadaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGroup(OrdenBaleadaLayout.createSequentialGroup() .addGap(111, 111, 111) .addComponent(jLabel6) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) .addGroup(OrdenBaleadaLayout.createSequentialGroup() .addGap(103, 103, 103) .addComponent(jButton7) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); OrdenBaleadaLayout.setVerticalGroup( OrdenBaleadaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(OrdenBaleadaLayout.createSequentialGroup() .addGap(8, 8, 8) .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(OrdenBaleadaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(OrdenBaleadaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(jButton7) .addContainerGap(18, Short.MAX_VALUE)) ); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel1.setText("Baleadas Binarias"); jLabel2.setText("Nombre"); jLabel3.setText("Numero de Telefono"); jLabel4.setText("Efectivo"); jLabel5.setText("Direccion"); ta_direccion.setColumns(20); ta_direccion.setRows(5); jScrollPane1.setViewportView(ta_direccion); b_agregar.setText("Agregar"); b_agregar.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { b_agregarMouseClicked(evt); } }); b_modificar.setText("Modificar"); b_modificar.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { b_modificarMouseClicked(evt); } }); lista.setModel(new DefaultListModel()); jScrollPane2.setViewportView(lista); javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("Ordenes"); arbol.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1)); jScrollPane3.setViewportView(arbol); jButton1.setText("Agregar orden"); jButton1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton1MouseClicked(evt); } }); jButton6.setText("Eliminar"); jButton6.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton6MouseClicked(evt); } }); jButton8.setText("Agregar al Arbol"); jButton8.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton8MouseClicked(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jLabel1) .addGap(333, 333, 333)) .addGroup(layout.createSequentialGroup() .addGap(37, 37, 37) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel3) .addComponent(jLabel2) .addComponent(jLabel4) .addComponent(jLabel5)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(tf_nombre) .addComponent(tf_telefono) .addComponent(tf_efectivo) .addComponent(jScrollPane1) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(b_agregar) .addComponent(jButton1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(b_modificar)))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(43, 43, 43) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(96, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton8) .addGap(127, 127, 127)))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addGap(77, 77, 77) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGap(29, 29, 29) .addComponent(jLabel1) .addGap(26, 26, 26) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(tf_nombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(tf_telefono, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(tf_efectivo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel5) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(b_agregar) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(b_modificar) .addComponent(jButton8))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton1) .addComponent(jButton6)) .addContainerGap(105, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void b_agregarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_b_agregarMouseClicked // TODO add your handling code here: DefaultListModel modelo = (DefaultListModel)lista.getModel(); try { modelo.addElement(new Clientes(tf_nombre.getText(), Integer.parseInt(tf_telefono.getText()), Integer.parseInt(tf_efectivo.getText()), ta_direccion.getText())); lista.setModel(modelo); tf_nombre.setText(""); tf_telefono.setText(""); tf_efectivo.setText(""); ta_direccion.setText(""); } catch (Exception e) { JOptionPane.showMessageDialog(this, "No se puede agregar la informacion"); } }//GEN-LAST:event_b_agregarMouseClicked private void b_modificarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_b_modificarMouseClicked // TODO add your handling code here: DefaultListModel modelo = (DefaultListModel)lista.getModel(); if (lista.getSelectedIndex() >= 0) { try { modelo.addElement(new Clientes(tf_nombre.getText(), Integer.parseInt(tf_telefono.getText()), Integer.parseInt(tf_efectivo.getText()), ta_direccion.getText())); //lista.setModel(modelo); tf_nombre.setText(""); tf_telefono.setText(""); tf_efectivo.setText(""); ta_direccion.setText(""); modelo.remove(lista.getSelectedIndex()); } catch (Exception e) { JOptionPane.showMessageDialog(this, "No se puede modificar la informacion"); } } }//GEN-LAST:event_b_modificarMouseClicked private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked // TODO add your handling code here: this.OrdenBaleada.setModal(true); OrdenBaleada.pack(); OrdenBaleada.setLocationRelativeTo(this); OrdenBaleada.setVisible(true); }//GEN-LAST:event_jButton1MouseClicked private void jButton4MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton4MouseClicked // TODO add your handling code here: DefaultListModel modelo = (DefaultListModel)lista.getModel(); if (lista.getSelectedIndex() >= 0) { ((Clientes)modelo.get(lista.getSelectedIndex())).getBaleada().add(new BaleadasReloaded()); }else{ JOptionPane.showMessageDialog(this, "No selecciono a un cliente de la lista"); } }//GEN-LAST:event_jButton4MouseClicked private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton3MouseClicked // TODO add your handling code here: DefaultListModel modelo = (DefaultListModel)lista.getModel(); if (lista.getSelectedIndex() >= 0) { ((Clientes)modelo.get(lista.getSelectedIndex())).getBaleada().add(new BaleadaBinaria()); }else{ JOptionPane.showMessageDialog(this, "No selecciono a un cliente de la lista"); } }//GEN-LAST:event_jButton3MouseClicked private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton2MouseClicked // TODO add your handling code here: DefaultListModel modelo = (DefaultListModel)lista.getModel(); if (lista.getSelectedIndex() >= 0) { ((Clientes)modelo.get(lista.getSelectedIndex())).getBaleada().add(new BaleadasEspciales()); }else{ JOptionPane.showMessageDialog(this, "No selecciono a un cliente de la lista"); } }//GEN-LAST:event_jButton2MouseClicked private void jButton5MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton5MouseClicked // TODO add your handling code here: DefaultListModel modelo = (DefaultListModel)lista.getModel(); if (lista.getSelectedIndex() >= 0) { ((Clientes)modelo.get(lista.getSelectedIndex())).getBaleada().add(new BaleadasOutOfBounce()); }else{ JOptionPane.showMessageDialog(this, "No selecciono a un cliente de la lista"); } }//GEN-LAST:event_jButton5MouseClicked private void jButton7MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton7MouseClicked // TODO add your handling code here: this.OrdenBaleada.setVisible(false); }//GEN-LAST:event_jButton7MouseClicked private void jButton6MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton6MouseClicked // TODO add your handling code here:. DefaultListModel modelo = (DefaultListModel)lista.getModel(); if (lista.getSelectedIndex() >= 0) { modelo.remove(lista.getSelectedIndex()); }else{ JOptionPane.showMessageDialog(this, "No selecciono a un cliente de la lista"); } }//GEN-LAST:event_jButton6MouseClicked private void jButton8MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton8MouseClicked // TODO add your handling code here: if (lista.getSelectedIndex() >= 0) { DefaultTreeModel m = (DefaultTreeModel)arbol.getModel(); DefaultListModel p = (DefaultListModel) lista.getModel(); DefaultMutableTreeNode raiz = (DefaultMutableTreeNode)m.getRoot(); DefaultMutableTreeNode orden; orden = new DefaultMutableTreeNode ("Orden: "+cont); } }//GEN-LAST:event_jButton8MouseClicked /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(BaleadasBinarias.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(BaleadasBinarias.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(BaleadasBinarias.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(BaleadasBinarias.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new BaleadasBinarias().setVisible(true); } }); } DefaultMutableTreeNode nodo; int cont = 0; // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JDialog OrdenBaleada; private javax.swing.JTree arbol; private javax.swing.JButton b_agregar; private javax.swing.JButton b_modificar; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JButton jButton5; private javax.swing.JButton jButton6; private javax.swing.JButton jButton7; private javax.swing.JButton jButton8; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JList<String> lista; private javax.swing.JTextArea ta_direccion; private javax.swing.JTextField tf_efectivo; private javax.swing.JTextField tf_nombre; private javax.swing.JTextField tf_telefono; // End of variables declaration//GEN-END:variables }
{'content_hash': '3be9fbc36b3367ba0aaddffce0ffb35d', 'timestamp': '', 'source': 'github', 'line_count': 465, 'max_line_length': 187, 'avg_line_length': 51.402150537634405, 'alnum_prop': 0.6359300476947536, 'repo_name': 'IlianaPinto/Lab5_IlianaPintoP2', 'id': 'fd875d8e4255d5f17ecd04e04dc4e4358b7596b0', 'size': '23902', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Lab5_IlianaPintoP2/src/BaleadasBinarias.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '31509'}]}
Simulations of mate choice with information filtering.
{'content_hash': 'a8730765b304bb93ec646df57db3876b', 'timestamp': '', 'source': 'github', 'line_count': 1, 'max_line_length': 54, 'avg_line_length': 55.0, 'alnum_prop': 0.8545454545454545, 'repo_name': 'danilogmuniz/informationFiltering', 'id': '58664efda3a3215b62ac2299ee618d4506d57c1c', 'size': '78', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'R', 'bytes': '5173'}]}
<!-- Do not edit this file. It is automatically generated by API Documenter. --> [Home](./index.md) &gt; [puppeteer](./puppeteer.md) &gt; [Protocol](./puppeteer.protocol.md) &gt; [DOM](./puppeteer.protocol.dom.md) &gt; [RequestNodeRequest](./puppeteer.protocol.dom.requestnoderequest.md) ## Protocol.DOM.RequestNodeRequest interface <b>Signature:</b> ```typescript export interface RequestNodeRequest ``` ## Properties | Property | Type | Description | | --- | --- | --- | | [objectId](./puppeteer.protocol.dom.requestnoderequest.objectid.md) | [Runtime.RemoteObjectId](./puppeteer.protocol.runtime.remoteobjectid.md) | JavaScript object id to convert into node. |
{'content_hash': '12f0db6429533a49bc0be78037e486b3', 'timestamp': '', 'source': 'github', 'line_count': 18, 'max_line_length': 206, 'avg_line_length': 38.55555555555556, 'alnum_prop': 0.6974063400576369, 'repo_name': 'GoogleChrome/puppeteer', 'id': '868f9bcc1e4d29f79457f52282ed9a9b23ebf703', 'size': '694', 'binary': False, 'copies': '1', 'ref': 'refs/heads/1060080_cross_origin_iframe', 'path': 'new-docs/puppeteer.protocol.dom.requestnoderequest.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '393'}, {'name': 'HTML', 'bytes': '17624'}, {'name': 'JavaScript', 'bytes': '1087838'}, {'name': 'TypeScript', 'bytes': '8164'}]}