text
stringlengths
2
99.9k
meta
dict
--- # Copyright (C) 2016-2017 Robin Schneider <[email protected]> # Copyright (C) 2016-2017 DebOps <https://debops.org/> # SPDX-License-Identifier: GPL-3.0-only - name: Install and manage the caching HTTP proxy Apt-Cacher NG. collections: [ 'debops.debops', 'debops.roles01', 'debops.roles02', 'debops.roles03' ] hosts: [ 'debops_service_apt_cacher_ng' ] become: True environment: '{{ inventory__environment | d({}) | combine(inventory__group_environment | d({})) | combine(inventory__host_environment | d({})) }}' roles: - role: keyring tags: [ 'role::keyring', 'skip::keyring', 'role::nginx' ] keyring__dependent_apt_keys: - '{{ nginx__keyring__dependent_apt_keys }}' - role: etc_services tags: [ 'role::etc_services', 'skip::etc_services' ] etc_services__dependent_list: - '{{ apt_cacher_ng__etc_services__dependent_list }}' - role: apt_preferences tags: [ 'role::apt_preferences', 'skip::apt_preferences' ] apt_preferences__dependent_list: - '{{ apt_cacher_ng__apt_preferences__dependent_list }}' - '{{ nginx_apt_preferences_dependent_list }}' - role: ferm tags: [ 'role::ferm', 'skip::ferm' ] ferm__dependent_rules: - '{{ apt_cacher_ng__ferm__dependent_rules }}' - '{{ nginx_ferm_dependent_rules }}' - role: python tags: [ 'role::python', 'skip::python' ] python__dependent_packages3: - '{{ nginx__python__dependent_packages3 }}' python__dependent_packages2: - '{{ nginx__python__dependent_packages2 }}' - role: nginx tags: [ 'role::nginx', 'skip::nginx' ] nginx_servers: - '{{ apt_cacher_ng__nginx__servers }}' nginx_upstreams: - '{{ apt_cacher_ng__nginx__upstream }}' - role: apt_cacher_ng tags: [ 'role::apt_cacher_ng', 'skip::apt_cacher_ng' ]
{ "pile_set_name": "Github" }
<schemalist> <enum id='org.gtk.test.MyEnum'> <value nick='nospam' value='0'/> <value nick='spam' value='1'/> <value nick='ham' value='2'/> <value nick='eggs' value='3'/> <value nick='bangers' value='4'/> <value nick='mash' value='5'/> </enum> <schema id='org.gtk.test.schema'> <key name='test' enum='org.gtk.test.MyEnum'> <default>'spam'</default> <choices/> </key> </schema> </schemalist>
{ "pile_set_name": "Github" }
.view-settings { display: flex; justify-content: center; padding-top: 50px; } .settings__nav { padding: 0 30px; width: 150px; margin-left: -150px; } .settings__content { padding: 10px 15px; width: 400px; max-width: calc(100% - 170px); }
{ "pile_set_name": "Github" }
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * When "break Identifier" is evaluated, (break, empty, Identifier) is returned * * @path ch12/12.8/S12.8_A4_T3.js * @description Using embedded and labeled loops, breaking to outer loop */ LABEL_OUT : var x=0, y=0, xx=0, yy=0; (function(){ LABEL_DO_LOOP : do { LABEL_IN : x++; if(x===10)return; LABEL_NESTED_LOOP : do { LABEL_IN_NESTED : xx++; if(xx===10)return; break LABEL_DO_LOOP; LABEL_IN_NESTED_2 : yy++; } while (0); LABEL_IN_2 : y++; function IN_DO_FUNC(){} } while(0); LABEL_ANOTHER_LOOP : do { ; } while(0); function OUT_FUNC(){} })(); ////////////////////////////////////////////////////////////////////////////// //CHECK#1 if ((x!==1)&&(y!==0)&&(xx!==1)&(yy!==0)) { $ERROR('#1: x === 1 and y === 0 and xx === 1 and yy === 0. Actual: x==='+x+' and y==='+y+' and xx==='+xx+' and yy==='+yy ); } // //////////////////////////////////////////////////////////////////////////////
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?><!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'><html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Twisted Documentation: Interrupted Responses</title> <link href="../stylesheet.css" rel="stylesheet" type="text/css"/> </head> <body bgcolor="white"> <h1 class="title">Interrupted Responses</h1> <div class="toc"><ol/></div> <div class="content"> <span/> <p>The previous example had a Resource that generates its response asynchronously rather than immediately upon the call to its render method. When generating responses asynchronously, the possibility is introduced that the connection to the client may be lost before the response is generated. In such a case, it is often desirable to abandon the response generation entirely, since there is nothing to do with the data once it is produced. This example shows how to be notified that the connection has been lost.</p> <p>This example will build upon the <a href="asynchronous.html" shape="rect">asynchronous responses example</a> which simply (if not very realistically) generated its response after a fixed delay. We will expand that resource so that as soon as the client connection is lost, the delayed event is cancelled and the response is never generated.</p> <p>The feature this example relies on is provided by another <code class="API"><a href="http://twistedmatrix.com/documents/11.0.0/api/twisted.web.server.Request.html" title="twisted.web.server.Request">Request</a></code> method: <code class="API"><a href="http://twistedmatrix.com/documents/11.0.0/api/twisted.web.http.Request.notifyFinish.html" title="twisted.web.http.Request.notifyFinish">notifyFinish</a></code>. This method returns a new Deferred which will fire with <code>None</code> if the request is successfully responded to or with an error otherwise - for example if the connection is lost before the response is sent.</p> <p>The example starts in a familiar way, with the requisite Twisted imports and a resource class with the same <code>_delayedRender</code> used previously:</p> <pre class="python"><p class="py-linenumber">1 2 3 4 5 6 7 8 </p><span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">web</span>.<span class="py-src-variable">resource</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">Resource</span> <span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">web</span>.<span class="py-src-variable">server</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">NOT_DONE_YET</span> <span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">internet</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">reactor</span> <span class="py-src-keyword">class</span> <span class="py-src-identifier">DelayedResource</span>(<span class="py-src-parameter">Resource</span>): <span class="py-src-keyword">def</span> <span class="py-src-identifier">_delayedRender</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">request</span>): <span class="py-src-variable">request</span>.<span class="py-src-variable">write</span>(<span class="py-src-string">&quot;&lt;html&gt;&lt;body&gt;Sorry to keep you waiting.&lt;/body&gt;&lt;/html&gt;&quot;</span>) <span class="py-src-variable">request</span>.<span class="py-src-variable">finish</span>() </pre> <p>Before defining the render method, we're going to define an errback (an errback being a callback that gets called when there's an error), though. This will be the errback attached to the <code>Deferred</code> returned by <code>Request.notifyFinish</code>. It will cancel the delayed call to <code>_delayedRender</code>.</p> <pre class="python"><p class="py-linenumber">1 2 3 </p>... <span class="py-src-keyword">def</span> <span class="py-src-identifier">_responseFailed</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">err</span>, <span class="py-src-parameter">call</span>): <span class="py-src-variable">call</span>.<span class="py-src-variable">cancel</span>() </pre> <p>Finally, the render method will set up the delayed call just as it did before, and return <code>NOT_DONE_YET</code> likewise. However, it will also use <code>Request.notifyFinish</code> to make sure <code>_responseFailed</code> is called if appropriate.</p> <pre class="python"><p class="py-linenumber">1 2 3 4 5 </p>... <span class="py-src-keyword">def</span> <span class="py-src-identifier">render_GET</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">request</span>): <span class="py-src-variable">call</span> = <span class="py-src-variable">reactor</span>.<span class="py-src-variable">callLater</span>(<span class="py-src-number">5</span>, <span class="py-src-variable">self</span>.<span class="py-src-variable">_delayedRender</span>, <span class="py-src-variable">request</span>) <span class="py-src-variable">request</span>.<span class="py-src-variable">notifyFinish</span>().<span class="py-src-variable">addErrback</span>(<span class="py-src-variable">self</span>.<span class="py-src-variable">_responseFailed</span>, <span class="py-src-variable">call</span>) <span class="py-src-keyword">return</span> <span class="py-src-variable">NOT_DONE_YET</span> </pre> <p>Notice that since <code>_responseFailed</code> needs a reference to the delayed call object in order to cancel it, we passed that object to <code>addErrback</code>. Any additional arguments passed to <code>addErrback</code> (or <code>addCallback</code>) will be passed along to the errback after the <code class="API"><a href="http://twistedmatrix.com/documents/11.0.0/api/twisted.python.failure.Failure.html" title="twisted.python.failure.Failure">Failure</a></code> instance which is always passed as the first argument. Passing <code>call</code> here means it will be passed to <code>_responseFailed</code>, where it is expected and required.</p> <p>That covers almost all the code for this example. Here's the entire example without interruptions, as an <a href="rpy-scripts.html" shape="rect">rpy script</a>:</p> <pre class="python"><p class="py-linenumber"> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 </p><span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">web</span>.<span class="py-src-variable">resource</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">Resource</span> <span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">web</span>.<span class="py-src-variable">server</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">NOT_DONE_YET</span> <span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">internet</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">reactor</span> <span class="py-src-keyword">class</span> <span class="py-src-identifier">DelayedResource</span>(<span class="py-src-parameter">Resource</span>): <span class="py-src-keyword">def</span> <span class="py-src-identifier">_delayedRender</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">request</span>): <span class="py-src-variable">request</span>.<span class="py-src-variable">write</span>(<span class="py-src-string">&quot;&lt;html&gt;&lt;body&gt;Sorry to keep you waiting.&lt;/body&gt;&lt;/html&gt;&quot;</span>) <span class="py-src-variable">request</span>.<span class="py-src-variable">finish</span>() <span class="py-src-keyword">def</span> <span class="py-src-identifier">_responseFailed</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">err</span>, <span class="py-src-parameter">call</span>): <span class="py-src-variable">call</span>.<span class="py-src-variable">cancel</span>() <span class="py-src-keyword">def</span> <span class="py-src-identifier">render_GET</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">request</span>): <span class="py-src-variable">call</span> = <span class="py-src-variable">reactor</span>.<span class="py-src-variable">callLater</span>(<span class="py-src-number">5</span>, <span class="py-src-variable">self</span>.<span class="py-src-variable">_delayedRender</span>, <span class="py-src-variable">request</span>) <span class="py-src-variable">request</span>.<span class="py-src-variable">notifyFinish</span>().<span class="py-src-variable">addErrback</span>(<span class="py-src-variable">self</span>.<span class="py-src-variable">_responseFailed</span>, <span class="py-src-variable">call</span>) <span class="py-src-keyword">return</span> <span class="py-src-variable">NOT_DONE_YET</span> <span class="py-src-variable">resource</span> = <span class="py-src-variable">DelayedResource</span>() </pre> <p>Toss this into <code>example.rpy</code>, fire it up with <code>twistd -n web --path .</code>, and hit <a href="http://localhost:8080/example.rpy" shape="rect">http://localhost:8080/example.rpy</a>. If you wait five seconds, you'll get the page content. If you interrupt the request before then, say by hitting escape (in Firefox, at least), then you'll see perhaps the most boring demonstration ever - no page content, and nothing in the server logs. Success!</p> </div> <p><a href="../index.html">Index</a></p> <span class="version">Version: 11.0.0</span> </body> </html>
{ "pile_set_name": "Github" }
# DO NOT MODIFY. This file was generated by # github.com/GoogleCloudPlatform/google-cloud-common/testing/firestore/cmd/generate-firestore-tests/generate-firestore-tests.go. # The Delete sentinel must be the value of a field. Deletes are implemented by # turning the path to the Delete sentinel into a FieldPath, and FieldPaths do not # support array indexing. description: "update-paths: Delete cannot be in an array value" update_paths: < doc_ref_path: "projects/projectID/databases/(default)/documents/C/d" field_paths: < field: "a" > json_values: "[1, 2, \"Delete\"]" is_error: true >
{ "pile_set_name": "Github" }
# Copyright (C) 2010-2015 Cuckoo Foundation. # This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org # See the file 'docs/LICENSE' for copying permission. from django import forms from submission.models import Comment, Tag class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ["message"] class TagForm(forms.ModelForm): class Meta: model = Tag fields = ["name"]
{ "pile_set_name": "Github" }
import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "PolyTrend", cycle_length = 12, transform = "Difference", sigma = 0.0, exog_count = 0, ar_order = 12);
{ "pile_set_name": "Github" }
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.data.processor.data.entity; import com.google.common.collect.ImmutableMap; import org.spongepowered.api.data.DataTransactionResult; import org.spongepowered.api.data.key.Keys; import org.spongepowered.api.data.manipulator.immutable.entity.ImmutableRespawnLocation; import org.spongepowered.api.data.manipulator.mutable.entity.RespawnLocationData; import org.spongepowered.api.data.value.ValueContainer; import org.spongepowered.api.data.value.immutable.ImmutableMapValue; import org.spongepowered.api.data.value.mutable.MapValue; import org.spongepowered.api.entity.living.player.User; import org.spongepowered.api.util.RespawnLocation; import org.spongepowered.common.data.manipulator.mutable.entity.SpongeRespawnLocationData; import org.spongepowered.common.data.processor.common.AbstractSingleDataSingleTargetProcessor; import org.spongepowered.common.data.value.immutable.ImmutableSpongeMapValue; import org.spongepowered.common.data.value.mutable.SpongeMapValue; import org.spongepowered.common.bridge.entity.player.BedLocationsBridge; import java.util.Map; import java.util.Optional; import java.util.UUID; public class RespawnLocationDataProcessor extends AbstractSingleDataSingleTargetProcessor<User, Map<UUID, RespawnLocation>, MapValue<UUID, RespawnLocation>, RespawnLocationData, ImmutableRespawnLocation> { public RespawnLocationDataProcessor() { super(Keys.RESPAWN_LOCATIONS, User.class); } @Override public DataTransactionResult removeFrom(ValueContainer<?> container) { if (container instanceof BedLocationsBridge) { ImmutableMap<UUID, RespawnLocation> removed = ((BedLocationsBridge) container).bridge$removeAllBeds(); if (!removed.isEmpty()) { return DataTransactionResult.successRemove(constructImmutableValue(removed)); } return DataTransactionResult.successNoData(); } return DataTransactionResult.failNoData(); } @Override protected boolean set(User user, Map<UUID, RespawnLocation> value) { if (user instanceof BedLocationsBridge) { return ((BedLocationsBridge) user).bridge$setBedLocations(value); } return false; } @Override protected Optional<Map<UUID, RespawnLocation>> getVal(User user) { if (user instanceof BedLocationsBridge) { return Optional.of(((BedLocationsBridge) user).bridge$getBedlocations()); } return Optional.empty(); } @Override protected MapValue<UUID, RespawnLocation> constructValue(Map<UUID, RespawnLocation> actualValue) { return new SpongeMapValue<>(Keys.RESPAWN_LOCATIONS, actualValue); } @Override protected ImmutableMapValue<UUID, RespawnLocation> constructImmutableValue(Map<UUID, RespawnLocation> value) { return new ImmutableSpongeMapValue<>(Keys.RESPAWN_LOCATIONS, value); } @Override protected RespawnLocationData createManipulator() { return new SpongeRespawnLocationData(); } }
{ "pile_set_name": "Github" }
/** * @license AngularJS v1.3.3 * (c) 2010-2014 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular, undefined) { 'use strict'; /** * @ngdoc object * @name angular.mock * @description * * Namespace from 'angular-mocks.js' which contains testing related code. */ angular.mock = {}; /** * ! This is a private undocumented service ! * * @name $browser * * @description * This service is a mock implementation of {@link ng.$browser}. It provides fake * implementation for commonly used browser apis that are hard to test, e.g. setTimeout, xhr, * cookies, etc... * * The api of this service is the same as that of the real {@link ng.$browser $browser}, except * that there are several helper methods available which can be used in tests. */ angular.mock.$BrowserProvider = function() { this.$get = function() { return new angular.mock.$Browser(); }; }; angular.mock.$Browser = function() { var self = this; this.isMock = true; self.$$url = "http://server/"; self.$$lastUrl = self.$$url; // used by url polling fn self.pollFns = []; // TODO(vojta): remove this temporary api self.$$completeOutstandingRequest = angular.noop; self.$$incOutstandingRequestCount = angular.noop; // register url polling fn self.onUrlChange = function(listener) { self.pollFns.push( function() { if (self.$$lastUrl !== self.$$url || self.$$state !== self.$$lastState) { self.$$lastUrl = self.$$url; self.$$lastState = self.$$state; listener(self.$$url, self.$$state); } } ); return listener; }; self.$$checkUrlChange = angular.noop; self.cookieHash = {}; self.lastCookieHash = {}; self.deferredFns = []; self.deferredNextId = 0; self.defer = function(fn, delay) { delay = delay || 0; self.deferredFns.push({time:(self.defer.now + delay), fn:fn, id: self.deferredNextId}); self.deferredFns.sort(function(a, b) { return a.time - b.time;}); return self.deferredNextId++; }; /** * @name $browser#defer.now * * @description * Current milliseconds mock time. */ self.defer.now = 0; self.defer.cancel = function(deferId) { var fnIndex; angular.forEach(self.deferredFns, function(fn, index) { if (fn.id === deferId) fnIndex = index; }); if (fnIndex !== undefined) { self.deferredFns.splice(fnIndex, 1); return true; } return false; }; /** * @name $browser#defer.flush * * @description * Flushes all pending requests and executes the defer callbacks. * * @param {number=} number of milliseconds to flush. See {@link #defer.now} */ self.defer.flush = function(delay) { if (angular.isDefined(delay)) { self.defer.now += delay; } else { if (self.deferredFns.length) { self.defer.now = self.deferredFns[self.deferredFns.length - 1].time; } else { throw new Error('No deferred tasks to be flushed'); } } while (self.deferredFns.length && self.deferredFns[0].time <= self.defer.now) { self.deferredFns.shift().fn(); } }; self.$$baseHref = '/'; self.baseHref = function() { return this.$$baseHref; }; }; angular.mock.$Browser.prototype = { /** * @name $browser#poll * * @description * run all fns in pollFns */ poll: function poll() { angular.forEach(this.pollFns, function(pollFn) { pollFn(); }); }, addPollFn: function(pollFn) { this.pollFns.push(pollFn); return pollFn; }, url: function(url, replace, state) { if (angular.isUndefined(state)) { state = null; } if (url) { this.$$url = url; // Native pushState serializes & copies the object; simulate it. this.$$state = angular.copy(state); return this; } return this.$$url; }, state: function() { return this.$$state; }, cookies: function(name, value) { if (name) { if (angular.isUndefined(value)) { delete this.cookieHash[name]; } else { if (angular.isString(value) && //strings only value.length <= 4096) { //strict cookie storage limits this.cookieHash[name] = value; } } } else { if (!angular.equals(this.cookieHash, this.lastCookieHash)) { this.lastCookieHash = angular.copy(this.cookieHash); this.cookieHash = angular.copy(this.cookieHash); } return this.cookieHash; } }, notifyWhenNoOutstandingRequests: function(fn) { fn(); } }; /** * @ngdoc provider * @name $exceptionHandlerProvider * * @description * Configures the mock implementation of {@link ng.$exceptionHandler} to rethrow or to log errors * passed to the `$exceptionHandler`. */ /** * @ngdoc service * @name $exceptionHandler * * @description * Mock implementation of {@link ng.$exceptionHandler} that rethrows or logs errors passed * to it. See {@link ngMock.$exceptionHandlerProvider $exceptionHandlerProvider} for configuration * information. * * * ```js * describe('$exceptionHandlerProvider', function() { * * it('should capture log messages and exceptions', function() { * * module(function($exceptionHandlerProvider) { * $exceptionHandlerProvider.mode('log'); * }); * * inject(function($log, $exceptionHandler, $timeout) { * $timeout(function() { $log.log(1); }); * $timeout(function() { $log.log(2); throw 'banana peel'; }); * $timeout(function() { $log.log(3); }); * expect($exceptionHandler.errors).toEqual([]); * expect($log.assertEmpty()); * $timeout.flush(); * expect($exceptionHandler.errors).toEqual(['banana peel']); * expect($log.log.logs).toEqual([[1], [2], [3]]); * }); * }); * }); * ``` */ angular.mock.$ExceptionHandlerProvider = function() { var handler; /** * @ngdoc method * @name $exceptionHandlerProvider#mode * * @description * Sets the logging mode. * * @param {string} mode Mode of operation, defaults to `rethrow`. * * - `rethrow`: If any errors are passed to the handler in tests, it typically means that there * is a bug in the application or test, so this mock will make these tests fail. * - `log`: Sometimes it is desirable to test that an error is thrown, for this case the `log` * mode stores an array of errors in `$exceptionHandler.errors`, to allow later * assertion of them. See {@link ngMock.$log#assertEmpty assertEmpty()} and * {@link ngMock.$log#reset reset()} */ this.mode = function(mode) { switch (mode) { case 'rethrow': handler = function(e) { throw e; }; break; case 'log': var errors = []; handler = function(e) { if (arguments.length == 1) { errors.push(e); } else { errors.push([].slice.call(arguments, 0)); } }; handler.errors = errors; break; default: throw new Error("Unknown mode '" + mode + "', only 'log'/'rethrow' modes are allowed!"); } }; this.$get = function() { return handler; }; this.mode('rethrow'); }; /** * @ngdoc service * @name $log * * @description * Mock implementation of {@link ng.$log} that gathers all logged messages in arrays * (one array per logging level). These arrays are exposed as `logs` property of each of the * level-specific log function, e.g. for level `error` the array is exposed as `$log.error.logs`. * */ angular.mock.$LogProvider = function() { var debug = true; function concat(array1, array2, index) { return array1.concat(Array.prototype.slice.call(array2, index)); } this.debugEnabled = function(flag) { if (angular.isDefined(flag)) { debug = flag; return this; } else { return debug; } }; this.$get = function() { var $log = { log: function() { $log.log.logs.push(concat([], arguments, 0)); }, warn: function() { $log.warn.logs.push(concat([], arguments, 0)); }, info: function() { $log.info.logs.push(concat([], arguments, 0)); }, error: function() { $log.error.logs.push(concat([], arguments, 0)); }, debug: function() { if (debug) { $log.debug.logs.push(concat([], arguments, 0)); } } }; /** * @ngdoc method * @name $log#reset * * @description * Reset all of the logging arrays to empty. */ $log.reset = function() { /** * @ngdoc property * @name $log#log.logs * * @description * Array of messages logged using {@link ng.$log#log `log()`}. * * @example * ```js * $log.log('Some Log'); * var first = $log.log.logs.unshift(); * ``` */ $log.log.logs = []; /** * @ngdoc property * @name $log#info.logs * * @description * Array of messages logged using {@link ng.$log#info `info()`}. * * @example * ```js * $log.info('Some Info'); * var first = $log.info.logs.unshift(); * ``` */ $log.info.logs = []; /** * @ngdoc property * @name $log#warn.logs * * @description * Array of messages logged using {@link ng.$log#warn `warn()`}. * * @example * ```js * $log.warn('Some Warning'); * var first = $log.warn.logs.unshift(); * ``` */ $log.warn.logs = []; /** * @ngdoc property * @name $log#error.logs * * @description * Array of messages logged using {@link ng.$log#error `error()`}. * * @example * ```js * $log.error('Some Error'); * var first = $log.error.logs.unshift(); * ``` */ $log.error.logs = []; /** * @ngdoc property * @name $log#debug.logs * * @description * Array of messages logged using {@link ng.$log#debug `debug()`}. * * @example * ```js * $log.debug('Some Error'); * var first = $log.debug.logs.unshift(); * ``` */ $log.debug.logs = []; }; /** * @ngdoc method * @name $log#assertEmpty * * @description * Assert that all of the logging methods have no logged messages. If any messages are present, * an exception is thrown. */ $log.assertEmpty = function() { var errors = []; angular.forEach(['error', 'warn', 'info', 'log', 'debug'], function(logLevel) { angular.forEach($log[logLevel].logs, function(log) { angular.forEach(log, function(logItem) { errors.push('MOCK $log (' + logLevel + '): ' + String(logItem) + '\n' + (logItem.stack || '')); }); }); }); if (errors.length) { errors.unshift("Expected $log to be empty! Either a message was logged unexpectedly, or " + "an expected log message was not checked and removed:"); errors.push(''); throw new Error(errors.join('\n---------\n')); } }; $log.reset(); return $log; }; }; /** * @ngdoc service * @name $interval * * @description * Mock implementation of the $interval service. * * Use {@link ngMock.$interval#flush `$interval.flush(millis)`} to * move forward by `millis` milliseconds and trigger any functions scheduled to run in that * time. * * @param {function()} fn A function that should be called repeatedly. * @param {number} delay Number of milliseconds between each function call. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat * indefinitely. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. * @returns {promise} A promise which will be notified on each iteration. */ angular.mock.$IntervalProvider = function() { this.$get = ['$browser', '$rootScope', '$q', '$$q', function($browser, $rootScope, $q, $$q) { var repeatFns = [], nextRepeatId = 0, now = 0; var $interval = function(fn, delay, count, invokeApply) { var iteration = 0, skipApply = (angular.isDefined(invokeApply) && !invokeApply), deferred = (skipApply ? $$q : $q).defer(), promise = deferred.promise; count = (angular.isDefined(count)) ? count : 0; promise.then(null, null, fn); promise.$$intervalId = nextRepeatId; function tick() { deferred.notify(iteration++); if (count > 0 && iteration >= count) { var fnIndex; deferred.resolve(iteration); angular.forEach(repeatFns, function(fn, index) { if (fn.id === promise.$$intervalId) fnIndex = index; }); if (fnIndex !== undefined) { repeatFns.splice(fnIndex, 1); } } if (skipApply) { $browser.defer.flush(); } else { $rootScope.$apply(); } } repeatFns.push({ nextTime:(now + delay), delay: delay, fn: tick, id: nextRepeatId, deferred: deferred }); repeatFns.sort(function(a, b) { return a.nextTime - b.nextTime;}); nextRepeatId++; return promise; }; /** * @ngdoc method * @name $interval#cancel * * @description * Cancels a task associated with the `promise`. * * @param {promise} promise A promise from calling the `$interval` function. * @returns {boolean} Returns `true` if the task was successfully cancelled. */ $interval.cancel = function(promise) { if (!promise) return false; var fnIndex; angular.forEach(repeatFns, function(fn, index) { if (fn.id === promise.$$intervalId) fnIndex = index; }); if (fnIndex !== undefined) { repeatFns[fnIndex].deferred.reject('canceled'); repeatFns.splice(fnIndex, 1); return true; } return false; }; /** * @ngdoc method * @name $interval#flush * @description * * Runs interval tasks scheduled to be run in the next `millis` milliseconds. * * @param {number=} millis maximum timeout amount to flush up until. * * @return {number} The amount of time moved forward. */ $interval.flush = function(millis) { now += millis; while (repeatFns.length && repeatFns[0].nextTime <= now) { var task = repeatFns[0]; task.fn(); task.nextTime += task.delay; repeatFns.sort(function(a, b) { return a.nextTime - b.nextTime;}); } return millis; }; return $interval; }]; }; /* jshint -W101 */ /* The R_ISO8061_STR regex is never going to fit into the 100 char limit! * This directive should go inside the anonymous function but a bug in JSHint means that it would * not be enacted early enough to prevent the warning. */ var R_ISO8061_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?:\:?(\d\d)(?:\:?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/; function jsonStringToDate(string) { var match; if (match = string.match(R_ISO8061_STR)) { var date = new Date(0), tzHour = 0, tzMin = 0; if (match[9]) { tzHour = int(match[9] + match[10]); tzMin = int(match[9] + match[11]); } date.setUTCFullYear(int(match[1]), int(match[2]) - 1, int(match[3])); date.setUTCHours(int(match[4] || 0) - tzHour, int(match[5] || 0) - tzMin, int(match[6] || 0), int(match[7] || 0)); return date; } return string; } function int(str) { return parseInt(str, 10); } function padNumber(num, digits, trim) { var neg = ''; if (num < 0) { neg = '-'; num = -num; } num = '' + num; while (num.length < digits) num = '0' + num; if (trim) num = num.substr(num.length - digits); return neg + num; } /** * @ngdoc type * @name angular.mock.TzDate * @description * * *NOTE*: this is not an injectable instance, just a globally available mock class of `Date`. * * Mock of the Date type which has its timezone specified via constructor arg. * * The main purpose is to create Date-like instances with timezone fixed to the specified timezone * offset, so that we can test code that depends on local timezone settings without dependency on * the time zone settings of the machine where the code is running. * * @param {number} offset Offset of the *desired* timezone in hours (fractions will be honored) * @param {(number|string)} timestamp Timestamp representing the desired time in *UTC* * * @example * !!!! WARNING !!!!! * This is not a complete Date object so only methods that were implemented can be called safely. * To make matters worse, TzDate instances inherit stuff from Date via a prototype. * * We do our best to intercept calls to "unimplemented" methods, but since the list of methods is * incomplete we might be missing some non-standard methods. This can result in errors like: * "Date.prototype.foo called on incompatible Object". * * ```js * var newYearInBratislava = new TzDate(-1, '2009-12-31T23:00:00Z'); * newYearInBratislava.getTimezoneOffset() => -60; * newYearInBratislava.getFullYear() => 2010; * newYearInBratislava.getMonth() => 0; * newYearInBratislava.getDate() => 1; * newYearInBratislava.getHours() => 0; * newYearInBratislava.getMinutes() => 0; * newYearInBratislava.getSeconds() => 0; * ``` * */ angular.mock.TzDate = function(offset, timestamp) { var self = new Date(0); if (angular.isString(timestamp)) { var tsStr = timestamp; self.origDate = jsonStringToDate(timestamp); timestamp = self.origDate.getTime(); if (isNaN(timestamp)) throw { name: "Illegal Argument", message: "Arg '" + tsStr + "' passed into TzDate constructor is not a valid date string" }; } else { self.origDate = new Date(timestamp); } var localOffset = new Date(timestamp).getTimezoneOffset(); self.offsetDiff = localOffset * 60 * 1000 - offset * 1000 * 60 * 60; self.date = new Date(timestamp + self.offsetDiff); self.getTime = function() { return self.date.getTime() - self.offsetDiff; }; self.toLocaleDateString = function() { return self.date.toLocaleDateString(); }; self.getFullYear = function() { return self.date.getFullYear(); }; self.getMonth = function() { return self.date.getMonth(); }; self.getDate = function() { return self.date.getDate(); }; self.getHours = function() { return self.date.getHours(); }; self.getMinutes = function() { return self.date.getMinutes(); }; self.getSeconds = function() { return self.date.getSeconds(); }; self.getMilliseconds = function() { return self.date.getMilliseconds(); }; self.getTimezoneOffset = function() { return offset * 60; }; self.getUTCFullYear = function() { return self.origDate.getUTCFullYear(); }; self.getUTCMonth = function() { return self.origDate.getUTCMonth(); }; self.getUTCDate = function() { return self.origDate.getUTCDate(); }; self.getUTCHours = function() { return self.origDate.getUTCHours(); }; self.getUTCMinutes = function() { return self.origDate.getUTCMinutes(); }; self.getUTCSeconds = function() { return self.origDate.getUTCSeconds(); }; self.getUTCMilliseconds = function() { return self.origDate.getUTCMilliseconds(); }; self.getDay = function() { return self.date.getDay(); }; // provide this method only on browsers that already have it if (self.toISOString) { self.toISOString = function() { return padNumber(self.origDate.getUTCFullYear(), 4) + '-' + padNumber(self.origDate.getUTCMonth() + 1, 2) + '-' + padNumber(self.origDate.getUTCDate(), 2) + 'T' + padNumber(self.origDate.getUTCHours(), 2) + ':' + padNumber(self.origDate.getUTCMinutes(), 2) + ':' + padNumber(self.origDate.getUTCSeconds(), 2) + '.' + padNumber(self.origDate.getUTCMilliseconds(), 3) + 'Z'; }; } //hide all methods not implemented in this mock that the Date prototype exposes var unimplementedMethods = ['getUTCDay', 'getYear', 'setDate', 'setFullYear', 'setHours', 'setMilliseconds', 'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate', 'setUTCFullYear', 'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes', 'setUTCMonth', 'setUTCSeconds', 'setYear', 'toDateString', 'toGMTString', 'toJSON', 'toLocaleFormat', 'toLocaleString', 'toLocaleTimeString', 'toSource', 'toString', 'toTimeString', 'toUTCString', 'valueOf']; angular.forEach(unimplementedMethods, function(methodName) { self[methodName] = function() { throw new Error("Method '" + methodName + "' is not implemented in the TzDate mock"); }; }); return self; }; //make "tzDateInstance instanceof Date" return true angular.mock.TzDate.prototype = Date.prototype; /* jshint +W101 */ angular.mock.animate = angular.module('ngAnimateMock', ['ng']) .config(['$provide', function($provide) { var reflowQueue = []; $provide.value('$$animateReflow', function(fn) { var index = reflowQueue.length; reflowQueue.push(fn); return function cancel() { reflowQueue.splice(index, 1); }; }); $provide.decorator('$animate', ['$delegate', '$$asyncCallback', '$timeout', '$browser', function($delegate, $$asyncCallback, $timeout, $browser) { var animate = { queue: [], cancel: $delegate.cancel, enabled: $delegate.enabled, triggerCallbackEvents: function() { $$asyncCallback.flush(); }, triggerCallbackPromise: function() { $timeout.flush(0); }, triggerCallbacks: function() { this.triggerCallbackEvents(); this.triggerCallbackPromise(); }, triggerReflow: function() { angular.forEach(reflowQueue, function(fn) { fn(); }); reflowQueue = []; } }; angular.forEach( ['animate','enter','leave','move','addClass','removeClass','setClass'], function(method) { animate[method] = function() { animate.queue.push({ event: method, element: arguments[0], options: arguments[arguments.length - 1], args: arguments }); return $delegate[method].apply($delegate, arguments); }; }); return animate; }]); }]); /** * @ngdoc function * @name angular.mock.dump * @description * * *NOTE*: this is not an injectable instance, just a globally available function. * * Method for serializing common angular objects (scope, elements, etc..) into strings, useful for * debugging. * * This method is also available on window, where it can be used to display objects on debug * console. * * @param {*} object - any object to turn into string. * @return {string} a serialized string of the argument */ angular.mock.dump = function(object) { return serialize(object); function serialize(object) { var out; if (angular.isElement(object)) { object = angular.element(object); out = angular.element('<div></div>'); angular.forEach(object, function(element) { out.append(angular.element(element).clone()); }); out = out.html(); } else if (angular.isArray(object)) { out = []; angular.forEach(object, function(o) { out.push(serialize(o)); }); out = '[ ' + out.join(', ') + ' ]'; } else if (angular.isObject(object)) { if (angular.isFunction(object.$eval) && angular.isFunction(object.$apply)) { out = serializeScope(object); } else if (object instanceof Error) { out = object.stack || ('' + object.name + ': ' + object.message); } else { // TODO(i): this prevents methods being logged, // we should have a better way to serialize objects out = angular.toJson(object, true); } } else { out = String(object); } return out; } function serializeScope(scope, offset) { offset = offset || ' '; var log = [offset + 'Scope(' + scope.$id + '): {']; for (var key in scope) { if (Object.prototype.hasOwnProperty.call(scope, key) && !key.match(/^(\$|this)/)) { log.push(' ' + key + ': ' + angular.toJson(scope[key])); } } var child = scope.$$childHead; while (child) { log.push(serializeScope(child, offset + ' ')); child = child.$$nextSibling; } log.push('}'); return log.join('\n' + offset); } }; /** * @ngdoc service * @name $httpBackend * @description * Fake HTTP backend implementation suitable for unit testing applications that use the * {@link ng.$http $http service}. * * *Note*: For fake HTTP backend implementation suitable for end-to-end testing or backend-less * development please see {@link ngMockE2E.$httpBackend e2e $httpBackend mock}. * * During unit testing, we want our unit tests to run quickly and have no external dependencies so * we don’t want to send [XHR](https://developer.mozilla.org/en/xmlhttprequest) or * [JSONP](http://en.wikipedia.org/wiki/JSONP) requests to a real server. All we really need is * to verify whether a certain request has been sent or not, or alternatively just let the * application make requests, respond with pre-trained responses and assert that the end result is * what we expect it to be. * * This mock implementation can be used to respond with static or dynamic responses via the * `expect` and `when` apis and their shortcuts (`expectGET`, `whenPOST`, etc). * * When an Angular application needs some data from a server, it calls the $http service, which * sends the request to a real server using $httpBackend service. With dependency injection, it is * easy to inject $httpBackend mock (which has the same API as $httpBackend) and use it to verify * the requests and respond with some testing data without sending a request to a real server. * * There are two ways to specify what test data should be returned as http responses by the mock * backend when the code under test makes http requests: * * - `$httpBackend.expect` - specifies a request expectation * - `$httpBackend.when` - specifies a backend definition * * * # Request Expectations vs Backend Definitions * * Request expectations provide a way to make assertions about requests made by the application and * to define responses for those requests. The test will fail if the expected requests are not made * or they are made in the wrong order. * * Backend definitions allow you to define a fake backend for your application which doesn't assert * if a particular request was made or not, it just returns a trained response if a request is made. * The test will pass whether or not the request gets made during testing. * * * <table class="table"> * <tr><th width="220px"></th><th>Request expectations</th><th>Backend definitions</th></tr> * <tr> * <th>Syntax</th> * <td>.expect(...).respond(...)</td> * <td>.when(...).respond(...)</td> * </tr> * <tr> * <th>Typical usage</th> * <td>strict unit tests</td> * <td>loose (black-box) unit testing</td> * </tr> * <tr> * <th>Fulfills multiple requests</th> * <td>NO</td> * <td>YES</td> * </tr> * <tr> * <th>Order of requests matters</th> * <td>YES</td> * <td>NO</td> * </tr> * <tr> * <th>Request required</th> * <td>YES</td> * <td>NO</td> * </tr> * <tr> * <th>Response required</th> * <td>optional (see below)</td> * <td>YES</td> * </tr> * </table> * * In cases where both backend definitions and request expectations are specified during unit * testing, the request expectations are evaluated first. * * If a request expectation has no response specified, the algorithm will search your backend * definitions for an appropriate response. * * If a request didn't match any expectation or if the expectation doesn't have the response * defined, the backend definitions are evaluated in sequential order to see if any of them match * the request. The response from the first matched definition is returned. * * * # Flushing HTTP requests * * The $httpBackend used in production always responds to requests asynchronously. If we preserved * this behavior in unit testing, we'd have to create async unit tests, which are hard to write, * to follow and to maintain. But neither can the testing mock respond synchronously; that would * change the execution of the code under test. For this reason, the mock $httpBackend has a * `flush()` method, which allows the test to explicitly flush pending requests. This preserves * the async api of the backend, while allowing the test to execute synchronously. * * * # Unit testing with mock $httpBackend * The following code shows how to setup and use the mock backend when unit testing a controller. * First we create the controller under test: * ```js // The module code angular .module('MyApp', []) .controller('MyController', MyController); // The controller code function MyController($scope, $http) { var authToken; $http.get('/auth.py').success(function(data, status, headers) { authToken = headers('A-Token'); $scope.user = data; }); $scope.saveMessage = function(message) { var headers = { 'Authorization': authToken }; $scope.status = 'Saving...'; $http.post('/add-msg.py', message, { headers: headers } ).success(function(response) { $scope.status = ''; }).error(function() { $scope.status = 'ERROR!'; }); }; } ``` * * Now we setup the mock backend and create the test specs: * ```js // testing controller describe('MyController', function() { var $httpBackend, $rootScope, createController, authRequestHandler; // Set up the module beforeEach(module('MyApp')); beforeEach(inject(function($injector) { // Set up the mock http service responses $httpBackend = $injector.get('$httpBackend'); // backend definition common for all tests authRequestHandler = $httpBackend.when('GET', '/auth.py') .respond({userId: 'userX'}, {'A-Token': 'xxx'}); // Get hold of a scope (i.e. the root scope) $rootScope = $injector.get('$rootScope'); // The $controller service is used to create instances of controllers var $controller = $injector.get('$controller'); createController = function() { return $controller('MyController', {'$scope' : $rootScope }); }; })); afterEach(function() { $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); }); it('should fetch authentication token', function() { $httpBackend.expectGET('/auth.py'); var controller = createController(); $httpBackend.flush(); }); it('should fail authentication', function() { // Notice how you can change the response even after it was set authRequestHandler.respond(401, ''); $httpBackend.expectGET('/auth.py'); var controller = createController(); $httpBackend.flush(); expect($rootScope.status).toBe('Failed...'); }); it('should send msg to server', function() { var controller = createController(); $httpBackend.flush(); // now you don’t care about the authentication, but // the controller will still send the request and // $httpBackend will respond without you having to // specify the expectation and response for this request $httpBackend.expectPOST('/add-msg.py', 'message content').respond(201, ''); $rootScope.saveMessage('message content'); expect($rootScope.status).toBe('Saving...'); $httpBackend.flush(); expect($rootScope.status).toBe(''); }); it('should send auth header', function() { var controller = createController(); $httpBackend.flush(); $httpBackend.expectPOST('/add-msg.py', undefined, function(headers) { // check if the header was send, if it wasn't the expectation won't // match the request and the test will fail return headers['Authorization'] == 'xxx'; }).respond(201, ''); $rootScope.saveMessage('whatever'); $httpBackend.flush(); }); }); ``` */ angular.mock.$HttpBackendProvider = function() { this.$get = ['$rootScope', createHttpBackendMock]; }; /** * General factory function for $httpBackend mock. * Returns instance for unit testing (when no arguments specified): * - passing through is disabled * - auto flushing is disabled * * Returns instance for e2e testing (when `$delegate` and `$browser` specified): * - passing through (delegating request to real backend) is enabled * - auto flushing is enabled * * @param {Object=} $delegate Real $httpBackend instance (allow passing through if specified) * @param {Object=} $browser Auto-flushing enabled if specified * @return {Object} Instance of $httpBackend mock */ function createHttpBackendMock($rootScope, $delegate, $browser) { var definitions = [], expectations = [], responses = [], responsesPush = angular.bind(responses, responses.push), copy = angular.copy; function createResponse(status, data, headers, statusText) { if (angular.isFunction(status)) return status; return function() { return angular.isNumber(status) ? [status, data, headers, statusText] : [200, status, data]; }; } // TODO(vojta): change params to: method, url, data, headers, callback function $httpBackend(method, url, data, callback, headers, timeout, withCredentials) { var xhr = new MockXhr(), expectation = expectations[0], wasExpected = false; function prettyPrint(data) { return (angular.isString(data) || angular.isFunction(data) || data instanceof RegExp) ? data : angular.toJson(data); } function wrapResponse(wrapped) { if (!$browser && timeout && timeout.then) timeout.then(handleTimeout); return handleResponse; function handleResponse() { var response = wrapped.response(method, url, data, headers); xhr.$$respHeaders = response[2]; callback(copy(response[0]), copy(response[1]), xhr.getAllResponseHeaders(), copy(response[3] || '')); } function handleTimeout() { for (var i = 0, ii = responses.length; i < ii; i++) { if (responses[i] === handleResponse) { responses.splice(i, 1); callback(-1, undefined, ''); break; } } } } if (expectation && expectation.match(method, url)) { if (!expectation.matchData(data)) throw new Error('Expected ' + expectation + ' with different data\n' + 'EXPECTED: ' + prettyPrint(expectation.data) + '\nGOT: ' + data); if (!expectation.matchHeaders(headers)) throw new Error('Expected ' + expectation + ' with different headers\n' + 'EXPECTED: ' + prettyPrint(expectation.headers) + '\nGOT: ' + prettyPrint(headers)); expectations.shift(); if (expectation.response) { responses.push(wrapResponse(expectation)); return; } wasExpected = true; } var i = -1, definition; while ((definition = definitions[++i])) { if (definition.match(method, url, data, headers || {})) { if (definition.response) { // if $browser specified, we do auto flush all requests ($browser ? $browser.defer : responsesPush)(wrapResponse(definition)); } else if (definition.passThrough) { $delegate(method, url, data, callback, headers, timeout, withCredentials); } else throw new Error('No response defined !'); return; } } throw wasExpected ? new Error('No response defined !') : new Error('Unexpected request: ' + method + ' ' + url + '\n' + (expectation ? 'Expected ' + expectation : 'No more request expected')); } /** * @ngdoc method * @name $httpBackend#when * @description * Creates a new backend definition. * * @param {string} method HTTP method. * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives * data string and returns true if the data is as expected. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header * object and returns true if the headers match the current definition. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. * * - respond – * `{function([status,] data[, headers, statusText]) * | function(function(method, url, data, headers)}` * – The respond method takes a set of static data to be returned or a function that can * return an array containing response status (number), response data (string), response * headers (Object), and the text for the status (string). The respond method returns the * `requestHandler` object for possible overrides. */ $httpBackend.when = function(method, url, data, headers) { var definition = new MockHttpExpectation(method, url, data, headers), chain = { respond: function(status, data, headers, statusText) { definition.passThrough = undefined; definition.response = createResponse(status, data, headers, statusText); return chain; } }; if ($browser) { chain.passThrough = function() { definition.response = undefined; definition.passThrough = true; return chain; }; } definitions.push(definition); return chain; }; /** * @ngdoc method * @name $httpBackend#whenGET * @description * Creates a new backend definition for GET requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenHEAD * @description * Creates a new backend definition for HEAD requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenDELETE * @description * Creates a new backend definition for DELETE requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenPOST * @description * Creates a new backend definition for POST requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives * data string and returns true if the data is as expected. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenPUT * @description * Creates a new backend definition for PUT requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives * data string and returns true if the data is as expected. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenJSONP * @description * Creates a new backend definition for JSONP requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ createShortMethods('when'); /** * @ngdoc method * @name $httpBackend#expect * @description * Creates a new request expectation. * * @param {string} method HTTP method. * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that * receives data string and returns true if the data is as expected, or Object if request body * is in JSON format. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header * object and returns true if the headers match the current expectation. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. * * - respond – * `{function([status,] data[, headers, statusText]) * | function(function(method, url, data, headers)}` * – The respond method takes a set of static data to be returned or a function that can * return an array containing response status (number), response data (string), response * headers (Object), and the text for the status (string). The respond method returns the * `requestHandler` object for possible overrides. */ $httpBackend.expect = function(method, url, data, headers) { var expectation = new MockHttpExpectation(method, url, data, headers), chain = { respond: function(status, data, headers, statusText) { expectation.response = createResponse(status, data, headers, statusText); return chain; } }; expectations.push(expectation); return chain; }; /** * @ngdoc method * @name $httpBackend#expectGET * @description * Creates a new request expectation for GET requests. For more info see `expect()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {Object=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. See #expect for more info. */ /** * @ngdoc method * @name $httpBackend#expectHEAD * @description * Creates a new request expectation for HEAD requests. For more info see `expect()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {Object=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#expectDELETE * @description * Creates a new request expectation for DELETE requests. For more info see `expect()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {Object=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#expectPOST * @description * Creates a new request expectation for POST requests. For more info see `expect()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that * receives data string and returns true if the data is as expected, or Object if request body * is in JSON format. * @param {Object=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#expectPUT * @description * Creates a new request expectation for PUT requests. For more info see `expect()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that * receives data string and returns true if the data is as expected, or Object if request body * is in JSON format. * @param {Object=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#expectPATCH * @description * Creates a new request expectation for PATCH requests. For more info see `expect()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that * receives data string and returns true if the data is as expected, or Object if request body * is in JSON format. * @param {Object=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#expectJSONP * @description * Creates a new request expectation for JSONP requests. For more info see `expect()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ createShortMethods('expect'); /** * @ngdoc method * @name $httpBackend#flush * @description * Flushes all pending requests using the trained responses. * * @param {number=} count Number of responses to flush (in the order they arrived). If undefined, * all pending requests will be flushed. If there are no pending requests when the flush method * is called an exception is thrown (as this typically a sign of programming error). */ $httpBackend.flush = function(count, digest) { if (digest !== false) $rootScope.$digest(); if (!responses.length) throw new Error('No pending request to flush !'); if (angular.isDefined(count) && count !== null) { while (count--) { if (!responses.length) throw new Error('No more pending request to flush !'); responses.shift()(); } } else { while (responses.length) { responses.shift()(); } } $httpBackend.verifyNoOutstandingExpectation(digest); }; /** * @ngdoc method * @name $httpBackend#verifyNoOutstandingExpectation * @description * Verifies that all of the requests defined via the `expect` api were made. If any of the * requests were not made, verifyNoOutstandingExpectation throws an exception. * * Typically, you would call this method following each test case that asserts requests using an * "afterEach" clause. * * ```js * afterEach($httpBackend.verifyNoOutstandingExpectation); * ``` */ $httpBackend.verifyNoOutstandingExpectation = function(digest) { if (digest !== false) $rootScope.$digest(); if (expectations.length) { throw new Error('Unsatisfied requests: ' + expectations.join(', ')); } }; /** * @ngdoc method * @name $httpBackend#verifyNoOutstandingRequest * @description * Verifies that there are no outstanding requests that need to be flushed. * * Typically, you would call this method following each test case that asserts requests using an * "afterEach" clause. * * ```js * afterEach($httpBackend.verifyNoOutstandingRequest); * ``` */ $httpBackend.verifyNoOutstandingRequest = function() { if (responses.length) { throw new Error('Unflushed requests: ' + responses.length); } }; /** * @ngdoc method * @name $httpBackend#resetExpectations * @description * Resets all request expectations, but preserves all backend definitions. Typically, you would * call resetExpectations during a multiple-phase test when you want to reuse the same instance of * $httpBackend mock. */ $httpBackend.resetExpectations = function() { expectations.length = 0; responses.length = 0; }; return $httpBackend; function createShortMethods(prefix) { angular.forEach(['GET', 'DELETE', 'JSONP', 'HEAD'], function(method) { $httpBackend[prefix + method] = function(url, headers) { return $httpBackend[prefix](method, url, undefined, headers); }; }); angular.forEach(['PUT', 'POST', 'PATCH'], function(method) { $httpBackend[prefix + method] = function(url, data, headers) { return $httpBackend[prefix](method, url, data, headers); }; }); } } function MockHttpExpectation(method, url, data, headers) { this.data = data; this.headers = headers; this.match = function(m, u, d, h) { if (method != m) return false; if (!this.matchUrl(u)) return false; if (angular.isDefined(d) && !this.matchData(d)) return false; if (angular.isDefined(h) && !this.matchHeaders(h)) return false; return true; }; this.matchUrl = function(u) { if (!url) return true; if (angular.isFunction(url.test)) return url.test(u); if (angular.isFunction(url)) return url(u); return url == u; }; this.matchHeaders = function(h) { if (angular.isUndefined(headers)) return true; if (angular.isFunction(headers)) return headers(h); return angular.equals(headers, h); }; this.matchData = function(d) { if (angular.isUndefined(data)) return true; if (data && angular.isFunction(data.test)) return data.test(d); if (data && angular.isFunction(data)) return data(d); if (data && !angular.isString(data)) { return angular.equals(angular.fromJson(angular.toJson(data)), angular.fromJson(d)); } return data == d; }; this.toString = function() { return method + ' ' + url; }; } function createMockXhr() { return new MockXhr(); } function MockXhr() { // hack for testing $http, $httpBackend MockXhr.$$lastInstance = this; this.open = function(method, url, async) { this.$$method = method; this.$$url = url; this.$$async = async; this.$$reqHeaders = {}; this.$$respHeaders = {}; }; this.send = function(data) { this.$$data = data; }; this.setRequestHeader = function(key, value) { this.$$reqHeaders[key] = value; }; this.getResponseHeader = function(name) { // the lookup must be case insensitive, // that's why we try two quick lookups first and full scan last var header = this.$$respHeaders[name]; if (header) return header; name = angular.lowercase(name); header = this.$$respHeaders[name]; if (header) return header; header = undefined; angular.forEach(this.$$respHeaders, function(headerVal, headerName) { if (!header && angular.lowercase(headerName) == name) header = headerVal; }); return header; }; this.getAllResponseHeaders = function() { var lines = []; angular.forEach(this.$$respHeaders, function(value, key) { lines.push(key + ': ' + value); }); return lines.join('\n'); }; this.abort = angular.noop; } /** * @ngdoc service * @name $timeout * @description * * This service is just a simple decorator for {@link ng.$timeout $timeout} service * that adds a "flush" and "verifyNoPendingTasks" methods. */ angular.mock.$TimeoutDecorator = ['$delegate', '$browser', function($delegate, $browser) { /** * @ngdoc method * @name $timeout#flush * @description * * Flushes the queue of pending tasks. * * @param {number=} delay maximum timeout amount to flush up until */ $delegate.flush = function(delay) { $browser.defer.flush(delay); }; /** * @ngdoc method * @name $timeout#verifyNoPendingTasks * @description * * Verifies that there are no pending tasks that need to be flushed. */ $delegate.verifyNoPendingTasks = function() { if ($browser.deferredFns.length) { throw new Error('Deferred tasks to flush (' + $browser.deferredFns.length + '): ' + formatPendingTasksAsString($browser.deferredFns)); } }; function formatPendingTasksAsString(tasks) { var result = []; angular.forEach(tasks, function(task) { result.push('{id: ' + task.id + ', ' + 'time: ' + task.time + '}'); }); return result.join(', '); } return $delegate; }]; angular.mock.$RAFDecorator = ['$delegate', function($delegate) { var queue = []; var rafFn = function(fn) { var index = queue.length; queue.push(fn); return function() { queue.splice(index, 1); }; }; rafFn.supported = $delegate.supported; rafFn.flush = function() { if (queue.length === 0) { throw new Error('No rAF callbacks present'); } var length = queue.length; for (var i = 0; i < length; i++) { queue[i](); } queue = []; }; return rafFn; }]; angular.mock.$AsyncCallbackDecorator = ['$delegate', function($delegate) { var callbacks = []; var addFn = function(fn) { callbacks.push(fn); }; addFn.flush = function() { angular.forEach(callbacks, function(fn) { fn(); }); callbacks = []; }; return addFn; }]; /** * */ angular.mock.$RootElementProvider = function() { this.$get = function() { return angular.element('<div ng-app></div>'); }; }; /** * @ngdoc module * @name ngMock * @packageName angular-mocks * @description * * # ngMock * * The `ngMock` module provides support to inject and mock Angular services into unit tests. * In addition, ngMock also extends various core ng services such that they can be * inspected and controlled in a synchronous manner within test code. * * * <div doc-module-components="ngMock"></div> * */ angular.module('ngMock', ['ng']).provider({ $browser: angular.mock.$BrowserProvider, $exceptionHandler: angular.mock.$ExceptionHandlerProvider, $log: angular.mock.$LogProvider, $interval: angular.mock.$IntervalProvider, $httpBackend: angular.mock.$HttpBackendProvider, $rootElement: angular.mock.$RootElementProvider }).config(['$provide', function($provide) { $provide.decorator('$timeout', angular.mock.$TimeoutDecorator); $provide.decorator('$$rAF', angular.mock.$RAFDecorator); $provide.decorator('$$asyncCallback', angular.mock.$AsyncCallbackDecorator); $provide.decorator('$rootScope', angular.mock.$RootScopeDecorator); }]); /** * @ngdoc module * @name ngMockE2E * @module ngMockE2E * @packageName angular-mocks * @description * * The `ngMockE2E` is an angular module which contains mocks suitable for end-to-end testing. * Currently there is only one mock present in this module - * the {@link ngMockE2E.$httpBackend e2e $httpBackend} mock. */ angular.module('ngMockE2E', ['ng']).config(['$provide', function($provide) { $provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator); }]); /** * @ngdoc service * @name $httpBackend * @module ngMockE2E * @description * Fake HTTP backend implementation suitable for end-to-end testing or backend-less development of * applications that use the {@link ng.$http $http service}. * * *Note*: For fake http backend implementation suitable for unit testing please see * {@link ngMock.$httpBackend unit-testing $httpBackend mock}. * * This implementation can be used to respond with static or dynamic responses via the `when` api * and its shortcuts (`whenGET`, `whenPOST`, etc) and optionally pass through requests to the * real $httpBackend for specific requests (e.g. to interact with certain remote apis or to fetch * templates from a webserver). * * As opposed to unit-testing, in an end-to-end testing scenario or in scenario when an application * is being developed with the real backend api replaced with a mock, it is often desirable for * certain category of requests to bypass the mock and issue a real http request (e.g. to fetch * templates or static files from the webserver). To configure the backend with this behavior * use the `passThrough` request handler of `when` instead of `respond`. * * Additionally, we don't want to manually have to flush mocked out requests like we do during unit * testing. For this reason the e2e $httpBackend flushes mocked out requests * automatically, closely simulating the behavior of the XMLHttpRequest object. * * To setup the application to run with this http backend, you have to create a module that depends * on the `ngMockE2E` and your application modules and defines the fake backend: * * ```js * myAppDev = angular.module('myAppDev', ['myApp', 'ngMockE2E']); * myAppDev.run(function($httpBackend) { * phones = [{name: 'phone1'}, {name: 'phone2'}]; * * // returns the current list of phones * $httpBackend.whenGET('/phones').respond(phones); * * // adds a new phone to the phones array * $httpBackend.whenPOST('/phones').respond(function(method, url, data) { * var phone = angular.fromJson(data); * phones.push(phone); * return [200, phone, {}]; * }); * $httpBackend.whenGET(/^\/templates\//).passThrough(); * //... * }); * ``` * * Afterwards, bootstrap your app with this new module. */ /** * @ngdoc method * @name $httpBackend#when * @module ngMockE2E * @description * Creates a new backend definition. * * @param {string} method HTTP method. * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(string|RegExp)=} data HTTP request body. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header * object and returns true if the headers match the current definition. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. * * - respond – * `{function([status,] data[, headers, statusText]) * | function(function(method, url, data, headers)}` * – The respond method takes a set of static data to be returned or a function that can return * an array containing response status (number), response data (string), response headers * (Object), and the text for the status (string). * - passThrough – `{function()}` – Any request matching a backend definition with * `passThrough` handler will be passed through to the real backend (an XHR request will be made * to the server.) * - Both methods return the `requestHandler` object for possible overrides. */ /** * @ngdoc method * @name $httpBackend#whenGET * @module ngMockE2E * @description * Creates a new backend definition for GET requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenHEAD * @module ngMockE2E * @description * Creates a new backend definition for HEAD requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenDELETE * @module ngMockE2E * @description * Creates a new backend definition for DELETE requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenPOST * @module ngMockE2E * @description * Creates a new backend definition for POST requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(string|RegExp)=} data HTTP request body. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenPUT * @module ngMockE2E * @description * Creates a new backend definition for PUT requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(string|RegExp)=} data HTTP request body. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenPATCH * @module ngMockE2E * @description * Creates a new backend definition for PATCH requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(string|RegExp)=} data HTTP request body. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenJSONP * @module ngMockE2E * @description * Creates a new backend definition for JSONP requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. */ angular.mock.e2e = {}; angular.mock.e2e.$httpBackendDecorator = ['$rootScope', '$delegate', '$browser', createHttpBackendMock]; /** * @ngdoc type * @name $rootScope.Scope * @module ngMock * @description * {@link ng.$rootScope.Scope Scope} type decorated with helper methods useful for testing. These * methods are automatically available on any {@link ng.$rootScope.Scope Scope} instance when * `ngMock` module is loaded. * * In addition to all the regular `Scope` methods, the following helper methods are available: */ angular.mock.$RootScopeDecorator = function($delegate) { var $rootScopePrototype = Object.getPrototypeOf($delegate); $rootScopePrototype.$countChildScopes = countChildScopes; $rootScopePrototype.$countWatchers = countWatchers; return $delegate; // ------------------------------------------------------------------------------------------ // /** * @ngdoc method * @name $rootScope.Scope#$countChildScopes * @module ngMock * @description * Counts all the direct and indirect child scopes of the current scope. * * The current scope is excluded from the count. The count includes all isolate child scopes. * * @returns {number} Total number of child scopes. */ function countChildScopes() { // jshint validthis: true var count = 0; // exclude the current scope var pendingChildHeads = [this.$$childHead]; var currentScope; while (pendingChildHeads.length) { currentScope = pendingChildHeads.shift(); while (currentScope) { count += 1; pendingChildHeads.push(currentScope.$$childHead); currentScope = currentScope.$$nextSibling; } } return count; } /** * @ngdoc method * @name $rootScope.Scope#$countWatchers * @module ngMock * @description * Counts all the watchers of direct and indirect child scopes of the current scope. * * The watchers of the current scope are included in the count and so are all the watchers of * isolate child scopes. * * @returns {number} Total number of watchers. */ function countWatchers() { // jshint validthis: true var count = this.$$watchers ? this.$$watchers.length : 0; // include the current scope var pendingChildHeads = [this.$$childHead]; var currentScope; while (pendingChildHeads.length) { currentScope = pendingChildHeads.shift(); while (currentScope) { count += currentScope.$$watchers ? currentScope.$$watchers.length : 0; pendingChildHeads.push(currentScope.$$childHead); currentScope = currentScope.$$nextSibling; } } return count; } }; if (window.jasmine || window.mocha) { var currentSpec = null, isSpecRunning = function() { return !!currentSpec; }; (window.beforeEach || window.setup)(function() { currentSpec = this; }); (window.afterEach || window.teardown)(function() { var injector = currentSpec.$injector; angular.forEach(currentSpec.$modules, function(module) { if (module && module.$$hashKey) { module.$$hashKey = undefined; } }); currentSpec.$injector = null; currentSpec.$modules = null; currentSpec = null; if (injector) { injector.get('$rootElement').off(); injector.get('$browser').pollFns.length = 0; } // clean up jquery's fragment cache angular.forEach(angular.element.fragments, function(val, key) { delete angular.element.fragments[key]; }); MockXhr.$$lastInstance = null; angular.forEach(angular.callbacks, function(val, key) { delete angular.callbacks[key]; }); angular.callbacks.counter = 0; }); /** * @ngdoc function * @name angular.mock.module * @description * * *NOTE*: This function is also published on window for easy access.<br> * *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha * * This function registers a module configuration code. It collects the configuration information * which will be used when the injector is created by {@link angular.mock.inject inject}. * * See {@link angular.mock.inject inject} for usage example * * @param {...(string|Function|Object)} fns any number of modules which are represented as string * aliases or as anonymous module initialization functions. The modules are used to * configure the injector. The 'ng' and 'ngMock' modules are automatically loaded. If an * object literal is passed they will be registered as values in the module, the key being * the module name and the value being what is returned. */ window.module = angular.mock.module = function() { var moduleFns = Array.prototype.slice.call(arguments, 0); return isSpecRunning() ? workFn() : workFn; ///////////////////// function workFn() { if (currentSpec.$injector) { throw new Error('Injector already created, can not register a module!'); } else { var modules = currentSpec.$modules || (currentSpec.$modules = []); angular.forEach(moduleFns, function(module) { if (angular.isObject(module) && !angular.isArray(module)) { modules.push(function($provide) { angular.forEach(module, function(value, key) { $provide.value(key, value); }); }); } else { modules.push(module); } }); } } }; /** * @ngdoc function * @name angular.mock.inject * @description * * *NOTE*: This function is also published on window for easy access.<br> * *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha * * The inject function wraps a function into an injectable function. The inject() creates new * instance of {@link auto.$injector $injector} per test, which is then used for * resolving references. * * * ## Resolving References (Underscore Wrapping) * Often, we would like to inject a reference once, in a `beforeEach()` block and reuse this * in multiple `it()` clauses. To be able to do this we must assign the reference to a variable * that is declared in the scope of the `describe()` block. Since we would, most likely, want * the variable to have the same name of the reference we have a problem, since the parameter * to the `inject()` function would hide the outer variable. * * To help with this, the injected parameters can, optionally, be enclosed with underscores. * These are ignored by the injector when the reference name is resolved. * * For example, the parameter `_myService_` would be resolved as the reference `myService`. * Since it is available in the function body as _myService_, we can then assign it to a variable * defined in an outer scope. * * ``` * // Defined out reference variable outside * var myService; * * // Wrap the parameter in underscores * beforeEach( inject( function(_myService_){ * myService = _myService_; * })); * * // Use myService in a series of tests. * it('makes use of myService', function() { * myService.doStuff(); * }); * * ``` * * See also {@link angular.mock.module angular.mock.module} * * ## Example * Example of what a typical jasmine tests looks like with the inject method. * ```js * * angular.module('myApplicationModule', []) * .value('mode', 'app') * .value('version', 'v1.0.1'); * * * describe('MyApp', function() { * * // You need to load modules that you want to test, * // it loads only the "ng" module by default. * beforeEach(module('myApplicationModule')); * * * // inject() is used to inject arguments of all given functions * it('should provide a version', inject(function(mode, version) { * expect(version).toEqual('v1.0.1'); * expect(mode).toEqual('app'); * })); * * * // The inject and module method can also be used inside of the it or beforeEach * it('should override a version and test the new version is injected', function() { * // module() takes functions or strings (module aliases) * module(function($provide) { * $provide.value('version', 'overridden'); // override version here * }); * * inject(function(version) { * expect(version).toEqual('overridden'); * }); * }); * }); * * ``` * * @param {...Function} fns any number of functions which will be injected using the injector. */ var ErrorAddingDeclarationLocationStack = function(e, errorForStack) { this.message = e.message; this.name = e.name; if (e.line) this.line = e.line; if (e.sourceId) this.sourceId = e.sourceId; if (e.stack && errorForStack) this.stack = e.stack + '\n' + errorForStack.stack; if (e.stackArray) this.stackArray = e.stackArray; }; ErrorAddingDeclarationLocationStack.prototype.toString = Error.prototype.toString; window.inject = angular.mock.inject = function() { var blockFns = Array.prototype.slice.call(arguments, 0); var errorForStack = new Error('Declaration Location'); return isSpecRunning() ? workFn.call(currentSpec) : workFn; ///////////////////// function workFn() { var modules = currentSpec.$modules || []; var strictDi = !!currentSpec.$injectorStrict; modules.unshift('ngMock'); modules.unshift('ng'); var injector = currentSpec.$injector; if (!injector) { if (strictDi) { // If strictDi is enabled, annotate the providerInjector blocks angular.forEach(modules, function(moduleFn) { if (typeof moduleFn === "function") { angular.injector.$$annotate(moduleFn); } }); } injector = currentSpec.$injector = angular.injector(modules, strictDi); currentSpec.$injectorStrict = strictDi; } for (var i = 0, ii = blockFns.length; i < ii; i++) { if (currentSpec.$injectorStrict) { // If the injector is strict / strictDi, and the spec wants to inject using automatic // annotation, then annotate the function here. injector.annotate(blockFns[i]); } try { /* jshint -W040 *//* Jasmine explicitly provides a `this` object when calling functions */ injector.invoke(blockFns[i] || angular.noop, this); /* jshint +W040 */ } catch (e) { if (e.stack && errorForStack) { throw new ErrorAddingDeclarationLocationStack(e, errorForStack); } throw e; } finally { errorForStack = null; } } } }; angular.mock.inject.strictDi = function(value) { value = arguments.length ? !!value : true; return isSpecRunning() ? workFn() : workFn; function workFn() { if (value !== currentSpec.$injectorStrict) { if (currentSpec.$injector) { throw new Error('Injector already created, can not modify strict annotations'); } else { currentSpec.$injectorStrict = value; } } } }; } })(window, window.angular);
{ "pile_set_name": "Github" }
module Jekyll class Stevenson attr_accessor :log_level LOG_LEVELS = { debug: 0, info: 1, warn: 2, error: 3 } # Public: Create a new instance of Stevenson, Jekyll's logger # # level - (optional, symbol) the log level # # Returns nothing def initialize(level = :info) @log_level = level end # Public: Print a jekyll debug message to stdout # # topic - the topic of the message, e.g. "Configuration file", "Deprecation", etc. # message - the message detail # # Returns nothing def debug(topic, message = nil) $stdout.puts(message(topic, message)) if should_log(:debug) end # Public: Print a jekyll message to stdout # # topic - the topic of the message, e.g. "Configuration file", "Deprecation", etc. # message - the message detail # # Returns nothing def info(topic, message = nil) $stdout.puts(message(topic, message)) if should_log(:info) end # Public: Print a jekyll message to stderr # # topic - the topic of the message, e.g. "Configuration file", "Deprecation", etc. # message - the message detail # # Returns nothing def warn(topic, message = nil) $stderr.puts(message(topic, message).yellow) if should_log(:warn) end # Public: Print a jekyll error message to stderr # # topic - the topic of the message, e.g. "Configuration file", "Deprecation", etc. # message - the message detail # # Returns nothing def error(topic, message = nil) $stderr.puts(message(topic, message).red) if should_log(:error) end # Public: Print a Jekyll error message to stderr and immediately abort the process # # topic - the topic of the message, e.g. "Configuration file", "Deprecation", etc. # message - the message detail (can be omitted) # # Returns nothing def abort_with(topic, message = nil) error(topic, message) abort end # Public: Build a Jekyll topic method # # topic - the topic of the message, e.g. "Configuration file", "Deprecation", etc. # message - the message detail # # Returns the formatted message def message(topic, message) formatted_topic(topic) + message.to_s.gsub(/\s+/, ' ') end # Public: Format the topic # # topic - the topic of the message, e.g. "Configuration file", "Deprecation", etc. # # Returns the formatted topic statement def formatted_topic(topic) "#{topic} ".rjust(20) end # Public: Determine whether the current log level warrants logging at the # proposed level. # # level_of_message - the log level of the message (symbol) # # Returns true if the log level of the message is greater than or equal to # this logger's log level. def should_log(level_of_message) LOG_LEVELS.fetch(log_level) <= LOG_LEVELS.fetch(level_of_message) end end end
{ "pile_set_name": "Github" }
package sarama import "time" //CreateAclsResponse is a an acl response creation type type CreateAclsResponse struct { ThrottleTime time.Duration AclCreationResponses []*AclCreationResponse } func (c *CreateAclsResponse) encode(pe packetEncoder) error { pe.putInt32(int32(c.ThrottleTime / time.Millisecond)) if err := pe.putArrayLength(len(c.AclCreationResponses)); err != nil { return err } for _, aclCreationResponse := range c.AclCreationResponses { if err := aclCreationResponse.encode(pe); err != nil { return err } } return nil } func (c *CreateAclsResponse) decode(pd packetDecoder, version int16) (err error) { throttleTime, err := pd.getInt32() if err != nil { return err } c.ThrottleTime = time.Duration(throttleTime) * time.Millisecond n, err := pd.getArrayLength() if err != nil { return err } c.AclCreationResponses = make([]*AclCreationResponse, n) for i := 0; i < n; i++ { c.AclCreationResponses[i] = new(AclCreationResponse) if err := c.AclCreationResponses[i].decode(pd, version); err != nil { return err } } return nil } func (c *CreateAclsResponse) key() int16 { return 30 } func (c *CreateAclsResponse) version() int16 { return 0 } func (c *CreateAclsResponse) headerVersion() int16 { return 0 } func (c *CreateAclsResponse) requiredVersion() KafkaVersion { return V0_11_0_0 } //AclCreationResponse is an acl creation response type type AclCreationResponse struct { Err KError ErrMsg *string } func (a *AclCreationResponse) encode(pe packetEncoder) error { pe.putInt16(int16(a.Err)) if err := pe.putNullableString(a.ErrMsg); err != nil { return err } return nil } func (a *AclCreationResponse) decode(pd packetDecoder, version int16) (err error) { kerr, err := pd.getInt16() if err != nil { return err } a.Err = KError(kerr) if a.ErrMsg, err = pd.getNullableString(); err != nil { return err } return nil }
{ "pile_set_name": "Github" }
{ "manifest_version": 2, "name": "a11y.css", "description": "a11y.css provides warnings about possible risks and mistakes that exist in HTML code through a style sheet. This extension also provides several accessibility-related utilities.", "version": "1.0.8", "applications": { "gecko": { "id": "a11y.css@ffoodd" } }, "permissions": [ "activeTab", "storage", "tabs" ], "browser_action": { "default_title": "a11y.css", "default_popup": "popup/index.html", "default_icon": { "19": "icons/a11y-css_19.png", "38": "icons/a11y-css_38.png" } }, "background": { "scripts": [ "/scripts/browser-polyfill.min.js", "/scripts/background/main.js" ], "persistent": true }, "content_scripts": [ { "matches": [ "<all_urls>" ], "js": [ "/scripts/browser-polyfill.min.js", "/scripts/injected/checkalts.js", "/scripts/injected/textspacing.js" ], "run_at": "document_end" } ], "icons": { "16": "icons/a11y-css_16.png", "48": "icons/a11y-css_48.png", "128": "icons/a11y-css_128.png" }, "web_accessible_resources": [ "icons/info.svg", "icons/ko.svg", "icons/ok.svg", "scripts/injected/checkalts.js", "css/*" ] }
{ "pile_set_name": "Github" }
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_APP_LIST_SEARCH_ARC_APP_RESULT_H_ #define CHROME_BROWSER_UI_APP_LIST_SEARCH_ARC_APP_RESULT_H_ #include <memory> #include <string> #include "base/macros.h" #include "chrome/browser/ui/app_icon_loader_delegate.h" #include "chrome/browser/ui/app_list/search/app_result.h" class AppListControllerDelegate; class ArcAppContextMenu; class ArcAppIconLoader; class Profile; namespace app_list { class ArcAppResult : public AppResult, public AppIconLoaderDelegate { public: ArcAppResult(Profile* profile, const std::string& app_id, AppListControllerDelegate* controller, bool is_recommendation); ~ArcAppResult() override; // SearchResult overrides: void Open(int event_flags) override; std::unique_ptr<SearchResult> Duplicate() const override; ui::MenuModel* GetContextMenuModel() override; // AppContextMenuDelegate overrides: void ExecuteLaunchCommand(int event_flags) override; // AppIconLoaderDelegate overrides: void OnAppImageUpdated(const std::string& app_id, const gfx::ImageSkia& image) override; private: std::unique_ptr<ArcAppIconLoader> icon_loader_; std::unique_ptr<ArcAppContextMenu> context_menu_; DISALLOW_COPY_AND_ASSIGN(ArcAppResult); }; } // namespace app_list #endif // CHROME_BROWSER_UI_APP_LIST_SEARCH_ARC_APP_RESULT_H_
{ "pile_set_name": "Github" }
/* * Copyright (C) 2017-2019 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include "EditingBehaviorTypes.h" namespace WebCore { // NOTEs // 1) EditingMacBehavior comprises Tiger, Leopard, SnowLeopard and iOS builds, as well as QtWebKit when built on Mac; // 2) EditingWindowsBehavior comprises Win32 build; // 3) EditingUnixBehavior comprises all unix-based systems, but Darwin/MacOS (and then abusing the terminology); // 99) MacEditingBehavior is used as a fallback. inline EditingBehaviorType editingBehaviorTypeForPlatform() { #if PLATFORM(IOS_FAMILY) return EditingIOSBehavior; #elif OS(DARWIN) return EditingMacBehavior; #elif OS(WINDOWS) return EditingWindowsBehavior; #elif OS(UNIX) return EditingUnixBehavior; #else // Fallback return EditingMacBehavior; #endif } #if PLATFORM(COCOA) static const bool defaultYouTubeFlashPluginReplacementEnabled = true; #else static const bool defaultYouTubeFlashPluginReplacementEnabled = false; #endif #if PLATFORM(IOS_FAMILY) static const bool defaultFixedBackgroundsPaintRelativeToDocument = true; static const bool defaultAcceleratedCompositingForFixedPositionEnabled = true; static const bool defaultAllowsInlineMediaPlayback = false; static const bool defaultInlineMediaPlaybackRequiresPlaysInlineAttribute = true; static const bool defaultVideoPlaybackRequiresUserGesture = true; static const bool defaultAudioPlaybackRequiresUserGesture = true; static const bool defaultMediaDataLoadsAutomatically = false; static const bool defaultShouldRespectImageOrientation = true; static const bool defaultImageSubsamplingEnabled = true; static const bool defaultScrollingTreeIncludesFrames = true; static const bool defaultMediaControlsScaleWithPageZoom = true; static const bool defaultQuickTimePluginReplacementEnabled = true; static const bool defaultRequiresUserGestureToLoadVideo = true; #else static const bool defaultFixedBackgroundsPaintRelativeToDocument = false; static const bool defaultAcceleratedCompositingForFixedPositionEnabled = false; static const bool defaultAllowsInlineMediaPlayback = true; static const bool defaultInlineMediaPlaybackRequiresPlaysInlineAttribute = false; static const bool defaultVideoPlaybackRequiresUserGesture = false; static const bool defaultAudioPlaybackRequiresUserGesture = false; static const bool defaultMediaDataLoadsAutomatically = true; static const bool defaultShouldRespectImageOrientation = false; static const bool defaultImageSubsamplingEnabled = false; static const bool defaultScrollingTreeIncludesFrames = false; static const bool defaultMediaControlsScaleWithPageZoom = true; static const bool defaultQuickTimePluginReplacementEnabled = false; static const bool defaultRequiresUserGestureToLoadVideo = false; #endif static const bool defaultAllowsPictureInPictureMediaPlayback = true; static const double defaultIncrementalRenderingSuppressionTimeoutInSeconds = 5; #if USE(UNIFIED_TEXT_CHECKING) static const bool defaultUnifiedTextCheckerEnabled = true; #else static const bool defaultUnifiedTextCheckerEnabled = false; #endif static const bool defaultSmartInsertDeleteEnabled = true; static const bool defaultSelectTrailingWhitespaceEnabled = false; #if ENABLE(VIDEO) && (USE(AVFOUNDATION) || USE(GSTREAMER) || USE(MEDIA_FOUNDATION) || PLATFORM(JAVA)) static const bool defaultMediaEnabled = true; #else static const bool defaultMediaEnabled = false; #endif #if (PLATFORM(IOS_FAMILY) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 120000) || (PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101400) || PLATFORM(WATCHOS) static const bool defaultConicGradient = true; #else static const bool defaultConicGradient = false; #endif #if ENABLE(APPLE_PAY_REMOTE_UI) static const bool defaultApplePayEnabled = true; #else static const bool defaultApplePayEnabled = false; #endif }
{ "pile_set_name": "Github" }
### Use GridFS with `gridfs-stream` as a storage **Deprecation warning:** The `gridfs-stream` [has not been updated in a long time](https://github.com/aheckmann/gridfs-stream) and is therefore considered deprecated. An alternative is to use the Mongo driver's native `GridFSBucket`, which is also [described in this wiki](https://github.com/VeliovGroup/Meteor-Files/wiki/GridFS-Bucket-Integration). Example below shows how to handle (store, serve, remove) uploaded files via GridFS. Please note - by default all files will be served with `200` response code, which is fine if you planning to deal only with small files, or not planning to serve files back to users (*use only upload and storage*). For support of `206` partial content see [this article](https://github.com/VeliovGroup/Meteor-Files/wiki/GridFS---206-Streaming). ### Preparation Firstly you need to install [gridfs-stream](https://github.com/aheckmann/gridfs-stream): ```shell npm install --save gridfs-stream ``` Or: ```shell meteor npm install --save gridfs-stream ``` #### Create collection Create a `FilesCollection` instance: ```javascript import { Meteor } from 'meteor/meteor'; import { FilesCollection } from 'meteor/ostrio:files'; export const Images = new FilesCollection({ debug: false, // Change to `true` for debugging collectionName: 'images', allowClientCode: false, onBeforeUpload(file) { if (file.size <= 10485760 && /png|jpg|jpeg/i.test(file.extension)) return true; return 'Please upload image, with size equal or less than 10MB'; }, }); if (Meteor.isServer) { Images.denyClient(); } ``` #### Get required packages and create up gfs instance Import and set up required variables: ```javascript import Grid from 'gridfs-stream'; // We'll use this package to work with GridFS import fs from 'fs'; // Required to read files initially uploaded via Meteor-Files import { MongoInternals } from 'meteor/mongo'; // Set up gfs instance let gfs; if (Meteor.isServer) { gfs = Grid( MongoInternals.defaultRemoteCollectionDriver().mongo.db, MongoInternals.NpmModule ); } ``` #### Store and serve files from GridFS Add `onAfterUpload` and `interceptDownload` hooks that would move file to GridFS once it's uploaded, and serve file from GridFS on request: ```javascript onAfterUpload(image) { // Move file to GridFS Object.keys(image.versions).forEach(versionName => { const metadata = { versionName, imageId: image._id, storedAt: new Date() }; // Optional const writeStream = gfs.createWriteStream({ filename: image.name, metadata }); fs.createReadStream(image.versions[versionName].path).pipe(writeStream); writeStream.on('close', Meteor.bindEnvironment(file => { const property = `versions.${versionName}.meta.gridFsFileId`; // Convert ObjectID to String. Because Meteor (EJSON?) seems to convert it to a // LocalCollection.ObjectID, which GFS doesn't understand. this.collection.update(image._id, { $set: { [property]: file._id.toString() } }); this.unlink(this.collection.findOne(image._id), versionName); // Unlink file by version from FS })); }); }, interceptDownload(http, image, versionName) { const _id = (image.versions[versionName].meta || {}).gridFsFileId; if (_id) { const readStream = gfs.createReadStream({ _id }); readStream.on('error', err => { throw err; }); readStream.pipe(http.response); } return Boolean(_id); // Serve file from either GridFS or FS if it wasn't uploaded yet } ``` #### Handle removing From now we can store/serve files to/from GridFS. But what will happen if we decide to delete an image? An Image document will be deleted, but a GridFS record will stay in db forever! That's not what we want, right? So let's fix this by adding `onAfterRemove` hook: ```javascript onAfterRemove(images) { images.forEach(image => { Object.keys(image.versions).forEach(versionName => { const _id = (image.versions[versionName].meta || {}).gridFsFileId; if (_id) gfs.remove({ _id }, err => { if (err) throw err; }); }); }); } ``` #### Final result Here's a final code: ```javascript import { Meteor } from 'meteor/meteor'; import { FilesCollection } from 'meteor/ostrio:files'; import Grid from 'gridfs-stream'; import { MongoInternals } from 'meteor/mongo'; import fs from 'fs'; let gfs; if (Meteor.isServer) { gfs = Grid( MongoInternals.defaultRemoteCollectionDriver().mongo.db, MongoInternals.NpmModule ); } export const Images = new FilesCollection({ collectionName: 'images', allowClientCode: false, debug: Meteor.isServer && process.env.NODE_ENV === 'development', onBeforeUpload(file) { if (file.size <= 10485760 && /png|jpg|jpeg/i.test(file.extension)) return true; return 'Please upload image, with size equal or less than 10MB'; }, onAfterUpload(image) { // Move file to GridFS Object.keys(image.versions).forEach(versionName => { const metadata = { versionName, imageId: image._id, storedAt: new Date() }; // Optional const writeStream = gfs.createWriteStream({ filename: image.name, metadata }); fs.createReadStream(image.versions[versionName].path).pipe(writeStream); writeStream.on('close', Meteor.bindEnvironment(file => { const property = `versions.${versionName}.meta.gridFsFileId`; // If we store the ObjectID itself, Meteor (EJSON?) seems to convert it to a // LocalCollection.ObjectID, which GFS doesn't understand. this.collection.update(image._id, { $set: { [property]: file._id.toString() } }); this.unlink(this.collection.findOne(image._id), versionName); // Unlink files from FS })); }); }, interceptDownload(http, image, versionName) { // Serve file from GridFS const _id = (image.versions[versionName].meta || {}).gridFsFileId; if (_id) { const readStream = gfs.createReadStream({ _id }); readStream.on('error', err => { // File not found Error handling without Server Crash http.response.statusCode = 404; http.response.end('file not found'); console.log(`chunk of file ${file._id}/${file.name} was not found`); }); http.response.setHeader('Cache-Control', this.cacheControl); readStream.pipe(http.response); } return Boolean(_id); // Serve file from either GridFS or FS if it wasn't uploaded yet }, onAfterRemove(images) { // Remove corresponding file from GridFS images.forEach(image => { Object.keys(image.versions).forEach(versionName => { const _id = (image.versions[versionName].meta || {}).gridFsFileId; if (_id) gfs.remove({ _id }, err => { if (err) throw err; }); }); }); } }); if (Meteor.isServer) { Images.denyClient(); } ```
{ "pile_set_name": "Github" }
#!/usr/bin/env python # -*- coding: utf-8 -*- """ trace/generated-tracers.h """ __author__ = "Lluís Vilanova <[email protected]>" __copyright__ = "Copyright 2012-2014, Lluís Vilanova <[email protected]>" __license__ = "GPL version 2 or (at your option) any later version" __maintainer__ = "Stefan Hajnoczi" __email__ = "[email protected]" from tracetool import out def generate(events, backend): out('/* This file is autogenerated by tracetool, do not edit. */', '', '#ifndef TRACE__GENERATED_TRACERS_H', '#define TRACE__GENERATED_TRACERS_H', '', '#include "qemu-common.h"', '') backend.generate_begin(events) for e in events: out('', 'static inline void %(api)s(%(args)s)', '{', api=e.api(), args=e.args) if "disable" not in e.properties: backend.generate(e) out('}') backend.generate_end(events) out('#endif /* TRACE__GENERATED_TRACERS_H */')
{ "pile_set_name": "Github" }
#!/bin/bash echo "Waiting 60s for services to start" # Wait for services to become available sleep 60 echo "Testing DefectDojo Service" curl -s -o "/dev/null" $DD_BASE_URL -m 120 CR=$(curl --insecure -s -m 10 -I "${DD_BASE_URL}login?next=/" | egrep "^HTTP" | cut -d' ' -f2) if [ "$CR" != 200 ]; then echo "ERROR: cannot display login screen; got HTTP code $CR" exit 1 fi # Run available unittests with a simple setup # All available Integrationtest Scripts are activated below # If successsful, A successs message is printed and the script continues # If any script is unsuccesssful a failure message is printed and the test script # Exits with status code of 1 function fail() { echo "Error: $1 test failed\n" exit 1 } function success() { echo "Success: $1 test passed\n" } test="Product type integration tests" echo "Running: $test" if python3 tests/Product_type_unit_test.py ; then success $test else fail $test fi test="Product integration tests" echo "Running: $test" if python3 tests/Product_unit_test.py ; then success $test else fail $test fi test="Endpoint integration tests" echo "Running: $test" if python3 tests/Endpoint_unit_test.py ; then success $test else fail $test fi test="Engagement integration tests" echo "Running: $test" if python3 tests/Engagement_unit_test.py ; then success $test else fail $test fi test="Environment integration tests" echo "Running: $test" if python3 tests/Environment_unit_test.py ; then success $test else fail $test fi test="Finding integration tests" echo "Running: $test" if python3 tests/Finding_unit_test.py ; then success $test else fail $test fi test="Test integration tests" echo "Running: $test" if python3 tests/Test_unit_test.py ; then success $test else fail $test fi test=echo "User integration tests" echo "Running: $test" if python3 tests/User_unit_test.py ; then success $test else fail $test fi test="Ibm Appscan integration test" echo "Running: $test" if python3 tests/ibm_appscan_test.py ; then success $test else fail $test fi # all smoke tests are already covered by other testcases above/below # test="Smoke integration test" # echo "Running: $test" # if python3 tests/smoke_test.py ; then # success $test # else # fail $test # fi test="Check Status test" echo "Running: $test" if python3 tests/check_status.py ; then success $test else fail $test fi test="Dedupe integration tests" echo "Running: $test" if python3 tests/dedupe_unit_test.py ; then success $test else fail $test fi # The below tests are commented out because they are still an unstable work in progress ## Once Ready they can be uncommented. # echo "Import Scanner integration test" # if python3 tests/Import_scanner_unit_test.py ; then # echo "Success: Import Scanner integration tests passed" # else # echo "Error: Import Scanner integration test failed"; exit 1 # fi # echo "Check Status UI integration test" # if python3 tests/check_status_ui.py ; then # echo "Success: Check Status UI tests passed" # else # echo "Error: Check Status UI test failed"; exit 1 # fi # echo "Zap integration test" # if python3 tests/zap.py ; then # echo "Success: zap integration tests passed" # else # echo "Error: Zap integration test failed"; exit 1 # fi exec echo "Done Running all configured integration tests."
{ "pile_set_name": "Github" }
/* * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) * * Copyright (c) 2018 Andrey Semashev */ /*! * \file atomic/detail/type_traits/is_iec559.hpp * * This header defines \c is_iec559 type trait */ #ifndef BOOST_ATOMIC_DETAIL_TYPE_TRAITS_IS_IEC559_HPP_INCLUDED_ #define BOOST_ATOMIC_DETAIL_TYPE_TRAITS_IS_IEC559_HPP_INCLUDED_ #include <limits> #include <boost/atomic/detail/config.hpp> #ifdef BOOST_HAS_PRAGMA_ONCE #pragma once #endif namespace boost { namespace atomics { namespace detail { template< typename T > struct is_iec559 { static BOOST_CONSTEXPR_OR_CONST bool value = !!std::numeric_limits< T >::is_iec559; }; #if defined(BOOST_HAS_FLOAT128) // libstdc++ does not specialize numeric_limits for __float128 template< > struct is_iec559< boost::float128_type > { static BOOST_CONSTEXPR_OR_CONST bool value = true; }; #endif // defined(BOOST_HAS_FLOAT128) } // namespace detail } // namespace atomics } // namespace boost #endif // BOOST_ATOMIC_DETAIL_TYPE_TRAITS_IS_IEC559_HPP_INCLUDED_
{ "pile_set_name": "Github" }
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ @org.spongepowered.api.util.annotation.NonnullByDefault package org.spongepowered.common.mixin.optimization.network.play.server;
{ "pile_set_name": "Github" }
{"type":"FeatureCollection","properties":{"kind":"state","state":"MN"},"features":[ {"type":"Feature","properties":{"kind":"county","name":"Becker","state":"MN"},"geometry":{"type":"MultiPolygon","coordinates":[[[[-95.1694,47.1545],[-95.1639,46.8040],[-95.1639,46.7164],[-96.1772,46.7164],[-96.1936,47.1490],[-96.0676,47.1490],[-95.5528,47.1490]]]]}} ]}
{ "pile_set_name": "Github" }
/* * 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 mf.org.apache.html.dom; import mf.org.w3c.dom.Node; import mf.org.w3c.dom.html.HTMLTableCellElement; import mf.org.w3c.dom.html.HTMLTableRowElement; /** * @author <a href="mailto:[email protected]">Assaf Arkin</a> * @version $Revision: 1029415 $ $Date: 2010-10-31 13:02:22 -0400 (Sun, 31 Oct 2010) $ * @xerces.internal * @see mf.org.w3c.dom.html.HTMLTableCellElement * @see mf.org.apache.xerces.dom.ElementImpl */ public class HTMLTableCellElementImpl extends HTMLElementImpl implements HTMLTableCellElement { private static final long serialVersionUID = -2406518157464313922L; /** * Constructor requires owner document. * * @param owner The owner HTML document */ public HTMLTableCellElementImpl(HTMLDocumentImpl owner, String name) { super(owner, name); } @Override public int getCellIndex() { Node parent; Node child; int index; parent = getParentNode(); index = 0; if (parent instanceof HTMLTableRowElement) { child = parent.getFirstChild(); while (child != null) { if (child instanceof HTMLTableCellElement) { if (child == this) return index; ++index; } child = child.getNextSibling(); } } return -1; } @Override public void setCellIndex(int cellIndex) { Node parent; Node child; parent = getParentNode(); if (parent instanceof HTMLTableRowElement) { child = parent.getFirstChild(); while (child != null) { if (child instanceof HTMLTableCellElement) { if (cellIndex == 0) { if (this != child) parent.insertBefore(this, child); return; } --cellIndex; } child = child.getNextSibling(); } } parent.appendChild(this); } @Override public String getAbbr() { return getAttribute("abbr"); } @Override public void setAbbr(String abbr) { setAttribute("abbr", abbr); } @Override public String getAlign() { return capitalize(getAttribute("align")); } @Override public void setAlign(String align) { setAttribute("align", align); } @Override public String getAxis() { return getAttribute("axis"); } @Override public void setAxis(String axis) { setAttribute("axis", axis); } @Override public String getBgColor() { return getAttribute("bgcolor"); } @Override public void setBgColor(String bgColor) { setAttribute("bgcolor", bgColor); } @Override public String getCh() { String ch; // Make sure that the access key is a single character. ch = getAttribute("char"); if (ch != null && ch.length() > 1) ch = ch.substring(0, 1); return ch; } @Override public void setCh(String ch) { // Make sure that the access key is a single character. if (ch != null && ch.length() > 1) ch = ch.substring(0, 1); setAttribute("char", ch); } @Override public String getChOff() { return getAttribute("charoff"); } @Override public void setChOff(String chOff) { setAttribute("charoff", chOff); } @Override public int getColSpan() { return getInteger(getAttribute("colspan")); } @Override public void setColSpan(int colspan) { setAttribute("colspan", String.valueOf(colspan)); } @Override public String getHeaders() { return getAttribute("headers"); } @Override public void setHeaders(String headers) { setAttribute("headers", headers); } @Override public String getHeight() { return getAttribute("height"); } @Override public void setHeight(String height) { setAttribute("height", height); } @Override public boolean getNoWrap() { return getBinary("nowrap"); } @Override public void setNoWrap(boolean noWrap) { setAttribute("nowrap", noWrap); } @Override public int getRowSpan() { return getInteger(getAttribute("rowspan")); } @Override public void setRowSpan(int rowspan) { setAttribute("rowspan", String.valueOf(rowspan)); } @Override public String getScope() { return getAttribute("scope"); } @Override public void setScope(String scope) { setAttribute("scope", scope); } @Override public String getVAlign() { return capitalize(getAttribute("valign")); } @Override public void setVAlign(String vAlign) { setAttribute("valign", vAlign); } @Override public String getWidth() { return getAttribute("width"); } @Override public void setWidth(String width) { setAttribute("width", width); } }
{ "pile_set_name": "Github" }
# $ ./triton ./src/testers/qemu-test-x86_64.py ./src/samples/ir_test_suite/qemu-test-x86_64 from __future__ import print_function from triton import * import pintool as Pintool # Get the Triton context over the pintool Triton = Pintool.getTritonContext() def sbefore(instruction): Triton.concretizeAllRegister() Triton.concretizeAllMemory() return def cafter(instruction): ofIgnored = [ OPCODE.X86.RCL, OPCODE.X86.RCR, OPCODE.X86.ROL, OPCODE.X86.ROR, OPCODE.X86.SAR, OPCODE.X86.SHL, OPCODE.X86.SHLD, OPCODE.X86.SHR, OPCODE.X86.SHRD, ] bad = list() regs = Triton.getParentRegisters() for reg in regs: cvalue = Pintool.getCurrentRegisterValue(reg) se = Triton.getSymbolicRegister(reg) if se is None: continue expr = se.getAst() svalue = expr.evaluate() # Check register if cvalue != svalue: if reg.getName() == 'of' and instruction.getType() in ofIgnored: continue bad.append({ 'reg': reg.getName(), 'svalue': svalue, 'cvalue': cvalue, 'expr': se.getAst() }) if bad: dump = '[KO] %#x: %s (%d register error(s))' %(instruction.getAddress(), instruction.getDisassembly(), len(bad)) for w in bad: dump += '\n Register : %s' %(w['reg']) dump += '\n Symbolic Value : %016x' %(w['svalue']) dump += '\n Concrete Value : %016x' %(w['cvalue']) dump += '\n Expression : %s' %(w['expr']) print(dump) with open('./semantics_issues', 'a') as fd: fd.write(dump+'\n') if len(instruction.getSymbolicExpressions()) == 0: dump = '[unsupported] %#x: %s' %(instruction.getAddress(), instruction.getDisassembly()) print(dump) with open('./semantics_issues', 'a') as fd: fd.write(dump+'\n') return return if __name__ == '__main__': Pintool.setupImageWhitelist(['qemu-test-x86_64']) Pintool.startAnalysisFromSymbol('main') Pintool.insertCall(cafter, Pintool.INSERT_POINT.AFTER) Pintool.insertCall(sbefore, Pintool.INSERT_POINT.BEFORE_SYMPROC) Pintool.runProgram()
{ "pile_set_name": "Github" }
# termui [![Build Status](https://travis-ci.org/gizak/termui.svg?branch=master)](https://travis-ci.org/gizak/termui) [![Doc Status](https://godoc.org/github.com/gizak/termui?status.png)](https://godoc.org/github.com/gizak/termui) <img src="./_example/dashboard.gif" alt="demo cast under osx 10.10; Terminal.app; Menlo Regular 12pt.)" width="80%"> `termui` is a cross-platform, easy-to-compile, and fully-customizable terminal dashboard. It is inspired by [blessed-contrib](https://github.com/yaronn/blessed-contrib), but purely in Go. Now version v2 has arrived! It brings new event system, new theme system, new `Buffer` interface and specific colour text rendering. (some docs are missing, but it will be completed soon!) ## Installation `master` mirrors v2 branch, to install: go get -u github.com/gizak/termui It is recommanded to use locked deps by using [glide](https://glide.sh): move to `termui` src directory then run `glide up`. For the compatible reason, you can choose to install the legacy version of `termui`: go get gopkg.in/gizak/termui.v1 ## Usage ### Layout To use `termui`, the very first thing you may want to know is how to manage layout. `termui` offers two ways of doing this, known as absolute layout and grid layout. __Absolute layout__ Each widget has an underlying block structure which basically is a box model. It has border, label and padding properties. A border of a widget can be chosen to hide or display (with its border label), you can pick a different front/back colour for the border as well. To display such a widget at a specific location in terminal window, you need to assign `.X`, `.Y`, `.Height`, `.Width` values for each widget before sending it to `.Render`. Let's demonstrate these by a code snippet: `````go import ui "github.com/gizak/termui" // <- ui shortcut, optional func main() { err := ui.Init() if err != nil { panic(err) } defer ui.Close() p := ui.NewPar(":PRESS q TO QUIT DEMO") p.Height = 3 p.Width = 50 p.TextFgColor = ui.ColorWhite p.BorderLabel = "Text Box" p.BorderFg = ui.ColorCyan g := ui.NewGauge() g.Percent = 50 g.Width = 50 g.Height = 3 g.Y = 11 g.BorderLabel = "Gauge" g.BarColor = ui.ColorRed g.BorderFg = ui.ColorWhite g.BorderLabelFg = ui.ColorCyan ui.Render(p, g) // feel free to call Render, it's async and non-block // event handler... } ````` Note that components can be overlapped (I'd rather call this a feature...), `Render(rs ...Renderer)` renders its args from left to right (i.e. each component's weight is arising from left to right). __Grid layout:__ <img src="./_example/grid.gif" alt="grid" width="60%"> Grid layout uses [12 columns grid system](http://www.w3schools.com/bootstrap/bootstrap_grid_system.asp) with expressive syntax. To use `Grid`, all we need to do is build a widget tree consisting of `Row`s and `Col`s (Actually a `Col` is also a `Row` but with a widget endpoint attached). ```go import ui "github.com/gizak/termui" // init and create widgets... // build ui.Body.AddRows( ui.NewRow( ui.NewCol(6, 0, widget0), ui.NewCol(6, 0, widget1)), ui.NewRow( ui.NewCol(3, 0, widget2), ui.NewCol(3, 0, widget30, widget31, widget32), ui.NewCol(6, 0, widget4))) // calculate layout ui.Body.Align() ui.Render(ui.Body) ``` ### Events `termui` ships with a http-like event mux handling system. All events are channeled up from different sources (typing, click, windows resize, custom event) and then encoded as universal `Event` object. `Event.Path` indicates the event type and `Event.Data` stores the event data struct. Add a handler to a certain event is easy as below: ```go // handle key q pressing ui.Handle("/sys/kbd/q", func(ui.Event) { // press q to quit ui.StopLoop() }) ui.Handle("/sys/kbd/C-x", func(ui.Event) { // handle Ctrl + x combination }) ui.Handle("/sys/kbd", func(ui.Event) { // handle all other key pressing }) // handle a 1s timer ui.Handle("/timer/1s", func(e ui.Event) { t := e.Data.(ui.EvtTimer) // t is a EvtTimer if t.Count%2 ==0 { // do something } }) ui.Loop() // block until StopLoop is called ``` ### Widgets Click image to see the corresponding demo codes. [<img src="./_example/par.png" alt="par" type="image/png" width="45%">](https://github.com/gizak/termui/blob/master/_example/par.go) [<img src="./_example/list.png" alt="list" type="image/png" width="45%">](https://github.com/gizak/termui/blob/master/_example/list.go) [<img src="./_example/gauge.png" alt="gauge" type="image/png" width="45%">](https://github.com/gizak/termui/blob/master/_example/gauge.go) [<img src="./_example/linechart.png" alt="linechart" type="image/png" width="45%">](https://github.com/gizak/termui/blob/master/_example/linechart.go) [<img src="./_example/barchart.png" alt="barchart" type="image/png" width="45%">](https://github.com/gizak/termui/blob/master/_example/barchart.go) [<img src="./_example/mbarchart.png" alt="barchart" type="image/png" width="45%">](https://github.com/gizak/termui/blob/master/_example/mbarchart.go) [<img src="./_example/sparklines.png" alt="sparklines" type="image/png" width="45%">](https://github.com/gizak/termui/blob/master/_example/sparklines.go) [<img src="./_example/table.png" alt="table" type="image/png" width="45%">](https://github.com/gizak/termui/blob/master/_example/table.go) ## GoDoc [godoc](https://godoc.org/github.com/gizak/termui) ## TODO - [x] Grid layout - [x] Event system - [x] Canvas widget - [x] Refine APIs - [ ] Focusable widgets ## Changelog ## License This library is under the [MIT License](http://opensource.org/licenses/MIT)
{ "pile_set_name": "Github" }
// // Solar.swift // Dynamic Dark Mode // // Created by Apollo Zhu on 11/17/18. // Copyright © 2018-2020 Dynamic Dark Mode. All rights reserved. // import Solar public enum Zenith: Int { case official case civil case nautical case astronomical case custom @available(macOS 10.15, *) case system } extension Zenith { static let hasZenithTypeSystem: Bool = { if #available(macOS 10.15, *) { return true } return false }() var hasSunriseSunsetTime: Bool { switch self { case .official, .civil, .nautical, .astronomical: return true case .custom, .system: return false } } } extension Solar { var sunriseSunsetTime: (sunrise: Date, sunset: Date) { switch preferences.scheduleZenithType { case .custom, .system: fatalError("No custom zenith type in solar") case .official: return (sunrise!, sunset!) case .civil: return (civilSunrise!, civilSunset!) case .nautical: return (nauticalSunrise!, nauticalSunset!) case .astronomical: return (astronomicalSunrise!, astronomicalSunset!) } } } extension DateComponents: Comparable { public static func < (lhs: DateComponents, rhs: DateComponents) -> Bool { return lhs.hour! < rhs.hour! || lhs.hour! == rhs.hour! && lhs.minute! < rhs.minute! } }
{ "pile_set_name": "Github" }
# Record and Playback with Resample When [Rec] button on an audio board is pressed, this example will record, and when the button is released, it will play back the recorded file. For the Recorder: - We will set up I2S and get audio at sample rate 48000 Hz, 16-bits, stereo. - Using resample-filter to convert to 16000 Hz, 16-bits, 1 channel. - Encode with Wav encoder - Write to microSD For the Playback: - We will read the recorded file, with sample rate 16000 Hz, 16-bits, 1 channel, - Decode with WAV decoder - Using resample-filter to convert to 48000 Hz, 16-bits, 2 channel. - Write the audio to I2S ## Compatibility This example is will run on boards marked with green checkbox. Please remember to select the board in menuconfig as discussed is section *Usage* below. | Board Name | Getting Started | Chip | Compatible | |-------------------|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------:|:--------------------------------------------------------------------:|:-----------------------------------------------------------------:| | ESP32-LyraT | [![alt text](../../../docs/_static/esp32-lyrat-v4.3-side-small.jpg "ESP32-LyraT")](https://docs.espressif.com/projects/esp-adf/en/latest/get-started/get-started-esp32-lyrat.html) | <img src="../../../docs/_static/ESP32.svg" height="85" alt="ESP32"> | ![alt text](../../../docs/_static/yes-button.png "Compatible") | | ESP32-LyraTD-MSC | [![alt text](../../../docs/_static/esp32-lyratd-msc-v2.2-small.jpg "ESP32-LyraTD-MSC")](https://docs.espressif.com/projects/esp-adf/en/latest/get-started/get-started-esp32-lyratd-msc.html) | <img src="../../../docs/_static/ESP32.svg" height="85" alt="ESP32"> | ![alt text](../../../docs/_static/yes-button.png "Compatible") | | ESP32-LyraT-Mini | [![alt text](../../../docs/_static/esp32-lyrat-mini-v1.2-small.jpg "ESP32-LyraT-Mini")](https://docs.espressif.com/projects/esp-adf/en/latest/get-started/get-started-esp32-lyrat-mini.html) | <img src="../../../docs/_static/ESP32.svg" height="85" alt="ESP32"> | ![alt text](../../../docs/_static/yes-button.png "Compatible") | | ESP32-Korvo-DU1906 | [![alt text](../../../docs/_static/esp32-korvo-du1906-v1.1-small.jpg "ESP32-Korvo-DU1906")](https://docs.espressif.com/projects/esp-adf/en/latest/get-started/get-started-esp32-korvo-du1906.html) | <img src="../../../docs/_static/ESP32.svg" height="85" alt="ESP32"> | ![alt text](../../../docs/_static/no-button.png "Compatible") | | ESP32-S2-Kaluga-1 Kit | [![alt text](../../../docs/_static/esp32-s2-kaluga-1-kit-small.png "ESP32-S2-Kaluga-1 Kit")](https://docs.espressif.com/projects/esp-idf/en/latest/esp32s2/hw-reference/esp32s2/user-guide-esp32-s2-kaluga-1-kit.html) | <img src="../../../docs/_static/ESP32-S2.svg" height="100" alt="ESP32-S2"> | ![alt text](../../../docs/_static/no-button.png "Compatible") | ## Usage Prepare the audio board: - Connect speakers or headphones to the board. - Insert a microSD card. Configure the example: - Select compatible audio board in `menuconfig` > `Audio HAL`. Load and run the example: - By using [Rec] button on the ESP32-LyraT board, when the button is pressed, it will start recording, and when the button is released, it will play back the recorded file. - To stop the pipeline press [Mode] button on the ESP32-LyraT board.
{ "pile_set_name": "Github" }
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/test/rgb_value.h" namespace remoting { namespace test { RGBValue::RGBValue() : red(0), green(0), blue(0) {} RGBValue::RGBValue(uint8_t r, uint8_t g, uint8_t b) : red(r), green(g), blue(b) {} RGBValue::~RGBValue() = default; } // namespace test } // namespace remoting
{ "pile_set_name": "Github" }
version https://git-lfs.github.com/spec/v1 oid sha256:206ea60cf8af678cb478d998554ae92ea90b90bc70877df016f6287341e35538 size 9154452
{ "pile_set_name": "Github" }
/* readpng.c * * Copyright (c) 2013 John Cunningham Bowler * * Last changed in libpng 1.6.1 [March 28, 2013] * * This code is released under the libpng license. * For conditions of distribution and use, see the disclaimer * and license in png.h * * Load an arbitrary number of PNG files (from the command line, or, if there * are no arguments on the command line, from stdin) then run a time test by * reading each file by row. The test does nothing with the read result and * does no transforms. The only output is a time as a floating point number of * seconds with 9 decimal digits. */ #include <stdlib.h> #include <stdio.h> #include <string.h> #if defined(HAVE_CONFIG_H) && !defined(PNG_NO_CONFIG_H) # include <config.h> #endif /* Define the following to use this test against your installed libpng, rather * than the one being built here: */ #ifdef PNG_FREESTANDING_TESTS # include <png.h> #else # include "../../png.h" #endif static int read_png(FILE *fp) { png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,0,0,0); png_infop info_ptr = NULL; png_bytep row = NULL, display = NULL; if (png_ptr == NULL) return 0; if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); if (row != NULL) free(row); if (display != NULL) free(display); return 0; } png_init_io(png_ptr, fp); info_ptr = png_create_info_struct(png_ptr); if (info_ptr == NULL) png_error(png_ptr, "OOM allocating info structure"); png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_ALWAYS, NULL, 0); png_read_info(png_ptr, info_ptr); { png_size_t rowbytes = png_get_rowbytes(png_ptr, info_ptr); row = malloc(rowbytes); display = malloc(rowbytes); if (row == NULL || display == NULL) png_error(png_ptr, "OOM allocating row buffers"); { png_uint_32 height = png_get_image_height(png_ptr, info_ptr); int passes = png_set_interlace_handling(png_ptr); int pass; png_start_read_image(png_ptr); for (pass = 0; pass < passes; ++pass) { png_uint_32 y = height; /* NOTE: this trashes the row each time; interlace handling won't * work, but this avoids memory thrashing for speed testing. */ while (y-- > 0) png_read_row(png_ptr, row, display); } } } /* Make sure to read to the end of the file: */ png_read_end(png_ptr, info_ptr); png_destroy_read_struct(&png_ptr, &info_ptr, NULL); free(row); free(display); return 1; } int main(void) { /* Exit code 0 on success. */ return !read_png(stdin); }
{ "pile_set_name": "Github" }
/********************************************************************************/ /* Projeto: Biblioteca ZeusMDFe */ /* Biblioteca C# para emissão de Manifesto Eletrônico Fiscal de Documentos */ /* (https://mdfe-portal.sefaz.rs.gov.br/ */ /* */ /* Direitos Autorais Reservados (c) 2014 Adenilton Batista da Silva */ /* Zeusdev Tecnologia LTDA ME */ /* */ /* Você pode obter a última versão desse arquivo no GitHub */ /* localizado em https://github.com/adeniltonbs/Zeus.Net.NFe.NFCe */ /* */ /* */ /* Esta biblioteca é software livre; você pode redistribuí-la e/ou modificá-la */ /* sob os termos da Licença Pública Geral Menor do GNU conforme publicada pela */ /* Free Software Foundation; tanto a versão 2.1 da Licença, ou (a seu critério) */ /* qualquer versão posterior. */ /* */ /* Esta biblioteca é distribuída na expectativa de que seja útil, porém, SEM */ /* NENHUMA GARANTIA; nem mesmo a garantia implícita de COMERCIABILIDADE OU */ /* ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral Menor*/ /* do GNU para mais detalhes. (Arquivo LICENÇA.TXT ou LICENSE.TXT) */ /* */ /* Você deve ter recebido uma cópia da Licença Pública Geral Menor do GNU junto*/ /* com esta biblioteca; se não, escreva para a Free Software Foundation, Inc., */ /* no endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. */ /* Você também pode obter uma copia da licença em: */ /* http://www.opensource.org/licenses/lgpl-license.php */ /* */ /* Zeusdev Tecnologia LTDA ME - [email protected] */ /* http://www.zeusautomacao.com.br/ */ /* Rua Comendador Francisco josé da Cunha, 111 - Itabaiana - SE - 49500-000 */ /********************************************************************************/ using System.Security.Cryptography.X509Certificates; namespace MDFe.Wsdl.Configuracao { public class WsdlConfiguracao { public string Url { get; set; } public string CodigoIbgeEstado { get; set; } public string Versao { get; set; } public X509Certificate2 CertificadoDigital { get; set; } public int TimeOut { get; set; } } }
{ "pile_set_name": "Github" }
# Works the same as find_package, but forwards the "REQUIRED" and "QUIET" arguments # used for the current package. For this to work, the first parameter must be the # prefix of the current package, then the prefix of the new package etc, which are # passed to find_package. macro (libfind_package PREFIX) set (LIBFIND_PACKAGE_ARGS ${ARGN}) if (${PREFIX}_FIND_QUIETLY) set (LIBFIND_PACKAGE_ARGS ${LIBFIND_PACKAGE_ARGS} QUIET) endif (${PREFIX}_FIND_QUIETLY) if (${PREFIX}_FIND_REQUIRED) set (LIBFIND_PACKAGE_ARGS ${LIBFIND_PACKAGE_ARGS} REQUIRED) endif (${PREFIX}_FIND_REQUIRED) find_package(${LIBFIND_PACKAGE_ARGS}) endmacro (libfind_package) # CMake developers made the UsePkgConfig system deprecated in the same release (2.6) # where they added pkg_check_modules. Consequently I need to support both in my scripts # to avoid those deprecated warnings. Here's a helper that does just that. # Works identically to pkg_check_modules, except that no checks are needed prior to use. macro (libfind_pkg_check_modules PREFIX PKGNAME) if (${CMAKE_MAJOR_VERSION} EQUAL 2 AND ${CMAKE_MINOR_VERSION} EQUAL 4) include(UsePkgConfig) pkgconfig(${PKGNAME} ${PREFIX}_INCLUDE_DIRS ${PREFIX}_LIBRARY_DIRS ${PREFIX}_LDFLAGS ${PREFIX}_CFLAGS) else (${CMAKE_MAJOR_VERSION} EQUAL 2 AND ${CMAKE_MINOR_VERSION} EQUAL 4) find_package(PkgConfig) if (PKG_CONFIG_FOUND) pkg_check_modules(${PREFIX} ${PKGNAME}) endif (PKG_CONFIG_FOUND) endif (${CMAKE_MAJOR_VERSION} EQUAL 2 AND ${CMAKE_MINOR_VERSION} EQUAL 4) endmacro (libfind_pkg_check_modules) # Do the final processing once the paths have been detected. # If include dirs are needed, ${PREFIX}_PROCESS_INCLUDES should be set to contain # all the variables, each of which contain one include directory. # Ditto for ${PREFIX}_PROCESS_LIBS and library files. # Will set ${PREFIX}_FOUND, ${PREFIX}_INCLUDE_DIRS and ${PREFIX}_LIBRARIES. # Also handles errors in case library detection was required, etc. macro (libfind_process PREFIX) # Skip processing if already processed during this run if (NOT ${PREFIX}_FOUND) # Start with the assumption that the library was found set (${PREFIX}_FOUND TRUE) # Process all includes and set _FOUND to false if any are missing foreach (i ${${PREFIX}_PROCESS_INCLUDES}) if (${i}) set (${PREFIX}_INCLUDE_DIRS ${${PREFIX}_INCLUDE_DIRS} ${${i}}) mark_as_advanced(${i}) else (${i}) set (${PREFIX}_FOUND FALSE) endif (${i}) endforeach (i) # Process all libraries and set _FOUND to false if any are missing foreach (i ${${PREFIX}_PROCESS_LIBS}) if (${i}) set (${PREFIX}_LIBRARIES ${${PREFIX}_LIBRARIES} ${${i}}) mark_as_advanced(${i}) else (${i}) set (${PREFIX}_FOUND FALSE) endif (${i}) endforeach (i) # Print message and/or exit on fatal error if (${PREFIX}_FOUND) if (NOT ${PREFIX}_FIND_QUIETLY) message (STATUS "Found ${PREFIX} ${${PREFIX}_VERSION}") endif (NOT ${PREFIX}_FIND_QUIETLY) else (${PREFIX}_FOUND) if (${PREFIX}_FIND_REQUIRED) foreach (i ${${PREFIX}_PROCESS_INCLUDES} ${${PREFIX}_PROCESS_LIBS}) message("${i}=${${i}}") endforeach (i) message (FATAL_ERROR "Required library ${PREFIX} NOT FOUND.\nInstall the library (dev version) and try again. If the library is already installed, use ccmake to set the missing variables manually.") endif (${PREFIX}_FIND_REQUIRED) endif (${PREFIX}_FOUND) endif (NOT ${PREFIX}_FOUND) endmacro (libfind_process) macro(libfind_library PREFIX basename) set(TMP "") if(MSVC80) set(TMP -vc80) endif(MSVC80) if(MSVC90) set(TMP -vc90) endif(MSVC90) set(${PREFIX}_LIBNAMES ${basename}${TMP}) if(${ARGC} GREATER 2) set(${PREFIX}_LIBNAMES ${basename}${TMP}-${ARGV2}) string(REGEX REPLACE "\\." "_" TMP ${${PREFIX}_LIBNAMES}) set(${PREFIX}_LIBNAMES ${${PREFIX}_LIBNAMES} ${TMP}) endif(${ARGC} GREATER 2) find_library(${PREFIX}_LIBRARY NAMES ${${PREFIX}_LIBNAMES} PATHS ${${PREFIX}_PKGCONF_LIBRARY_DIRS} ) endmacro(libfind_library)
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!-- 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. --> <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" > <suite name="JSR-346-TCK" verbose="2" configfailurepolicy="continue" > <listeners> <!-- debug --> <!--listener class-name="org.apache.openejb.tck.cdi.embedded.GCListener"/--> <!-- Required - avoid randomly mixed test method execution --> <listener class-name="org.jboss.cdi.tck.impl.testng.SingleTestClassMethodInterceptor"/> <!-- Optional - intended for debug purpose only --> <listener class-name="org.jboss.cdi.tck.impl.testng.ConfigurationLoggingListener"/> <listener class-name="org.jboss.cdi.tck.impl.testng.ProgressLoggingTestListener"/> <!-- Optional - it's recommended to disable the default JUnit XML reporter --> <!-- too slow to be there by default <listener class-name="org.testng.reporters.SuiteHTMLReporter"/> <listener class-name="org.testng.reporters.FailedReporter"/> <listener class-name="org.testng.reporters.XMLReporter"/> <listener class-name="org.testng.reporters.EmailableReporter"/> <listener class-name="org.apache.openejb.tck.testng.HTMLReporter"/> --> </listeners> <test name="JSR-346 TCK"> <packages> <package name="org.jboss.cdi.tck.tests.*"> <!-- CHALLENGED TCK TESTS: clarifying this in the EG --> <exclude name="org.jboss.cdi.tck.tests.inheritance.specialization.simple"/> <!-- CDITCK-432 --> <exclude name="org.jboss.cdi.tck.tests.decorators.builtin.event.complex"/> </package> <package name="org.jboss.cdi.tck.interceptors.tests.*"/> </packages> <classes> <!-- in discussion --> <!-- seems when InjectionPoint injection in for an EJB injection point then it should be null, any real reason? --> <class name="org.jboss.cdi.tck.tests.lookup.injectionpoint.non.contextual.NonContextualInjectionPointTest"> <methods> <exclude name="testNonContextualEjbInjectionPointGetBean" /> </methods> </class> <!-- Tests broken in the CDI-2.0 TCK: --> <!-- https://issues.jboss.org/projects/CDITCK/issues/CDITCK-602, invalid assumption that a situation cannot be resolved --> <class name="org.jboss.cdi.tck.tests.lookup.modules.specialization.SpecializationModularity03Test"> <methods><exclude name=".*"/></methods> </class> <class name="org.jboss.cdi.tck.tests.lookup.modules.specialization.SpecializationModularity05Test"> <methods><exclude name=".*"/></methods> </class> <class name="org.jboss.cdi.tck.tests.lookup.modules.specialization.SpecializationModularity06Test"> <methods><exclude name=".*"/></methods> </class> <class name="org.jboss.cdi.tck.tests.lookup.modules.specialization.SpecializationModularity07Test"> <methods><exclude name=".*"/></methods> </class> <!-- https://issues.jboss.org/projects/CDITCK/issues/CDITCK-600, uses illegal fireEvent to @ApplicationScoped bean in ProcessInjectionTarget --> <class name="org.jboss.cdi.tck.tests.extensions.lifecycle.processInjectionTarget.WrappedInjectionTargetTest"> <methods> <exclude name=".*"/> </methods> </class> <!-- https://issues.jboss.org/projects/CDITCK/issues/CDITCK-576 --> <class name="org.jboss.cdi.tck.tests.context.passivating.dependency.builtin.BuiltinBeanPassivationDependencyTest"> <methods> <exclude name="testInjectionPoint"/> </methods> </class> <!-- https://issues.jboss.org/browse/CDITCK-577 --> <class name="org.jboss.cdi.tck.tests.definition.bean.BeanDefinitionTest"> <methods> <exclude name="testRawBeanTypes"/> </methods> </class> <!-- https://issues.jboss.org/browse/CDITCK-432 --> <class name="org.jboss.cdi.tck.tests.decorators.builtin.event.complex.ComplexEventDecoratorTest"> <methods><exclude name=".*"/></methods> </class> <!-- https://issues.jboss.org/browse/CDITCK-578, https://issues.jboss.org/browse/CDITCK-579 --> <class name="org.jboss.cdi.tck.tests.definition.bean.custom.CustomBeanImplementationTest"> <methods> <exclude name="testCustomBeanIsPassivationCapable"/> <exclude name="testCustomBeanIsPassivationCapableDependency"/> <exclude name="testInjectionPointGetMemberIsUsedToDetermineTheClassThatDeclaresAnInjectionPoint"/> </methods> </class> <!-- this tests Weld specific internals --> <class name="org.jboss.cdi.tck.tests.definition.bean.types.illegal.BeanTypesWithIllegalTypeTest"> <methods><exclude name=".*"/></methods> </class> <!-- https://issues.jboss.org/browse/CDITCK-580 --> <class name="org.jboss.cdi.tck.tests.inheritance.specialization.simple.SimpleBeanSpecializationTest"> <methods><exclude name=".*"/></methods> </class> <!-- https://issues.jboss.org/browse/CDI-498 dots in EL names are not allowed by the EL spec. --> <class name="org.jboss.cdi.tck.tests.lookup.el.ResolutionByNameTest"> <methods><exclude name="testBeanNameWithSeparatedListOfELIdentifiers"/></methods> </class> <!-- OWB provides a bit more for @New than CDI requires https://issues.jboss.org/browse/CDITCK-581 --> <class name="org.jboss.cdi.tck.tests.lookup.dynamic.DynamicLookupTest"> <methods> <exclude name="testNewBeanNotEnabledWithouInjectionPoint"/> <exclude name="testDuplicateBindingsThrowsException"/> </methods> </class> <!-- https://issues.jboss.org/browse/CDITCK-586 --> <class name="org.jboss.cdi.tck.tests.event.observer.async.basic.MixedObserversTest"> <methods><exclude name="testAsyncObserversCalledInDifferentThread"/></methods> </class> <!-- https://issues.jboss.org/browse/CDITCK-588 equals on AnnotatedType --> <!-- https://issues.jboss.org/browse/CDITCK-589 because the ct predicate ends up randomly removing from the wrong ct --> <class name="org.jboss.cdi.tck.tests.extensions.configurators.annotatedTypeConfigurator.AnnotatedTypeConfiguratorTest"> <methods><exclude name=".*"/></methods> </class> <!-- https://issues.jboss.org/browse/CDITCK-573 should be solved with tck 2.0.1.Final --> <class name="org.jboss.cdi.tck.tests.extensions.configurators.bean.BeanConfiguratorTest"> <methods><exclude name=".*"/></methods> </class> <!-- https://issues.jboss.org/browse/CDITCK-591 --> <class name="org.jboss.cdi.tck.tests.extensions.alternative.metadata.AlternativeMetadataTest"> <methods><exclude name=".*"/></methods> </class> <!-- https://issues.jboss.org/browse/CDI-581 , both tests...--> <class name="org.jboss.cdi.tck.tests.extensions.lifecycle.processBeanAttributes.specialization.VetoTest"> <methods><exclude name=".*"/></methods> </class> <class name="org.jboss.cdi.tck.tests.extensions.lifecycle.processBeanAttributes.specialization.SpecializationTest"> <methods><exclude name=".*"/></methods> </class> <!-- CDITCK-466 --> <class name="org.jboss.cdi.tck.tests.extensions.lifecycle.bbd.broken.passivatingScope.AddingPassivatingScopeTest"> <methods> <exclude name=".*"/> </methods> </class> <!-- ears so not in web profile, Note: can be switch on if passing but dont let them block the build --> <class name="org.jboss.cdi.tck.tests.lookup.dependency.resolution.broken.ambiguous.ear.MultiModuleSessionBeanAmbiguousDependencyTest"><methods><exclude name=".*" /></methods></class> <class name="org.jboss.cdi.tck.tests.lookup.modules.interceptors.InterceptorModularityTest"><methods><exclude name=".*" /></methods></class> <class name="org.jboss.cdi.tck.tests.lookup.modules.specialization.SpecializationModularity03Test"><methods><exclude name=".*" /></methods></class> <class name="org.jboss.cdi.tck.tests.lookup.modules.specialization.SpecializationModularity05Test"><methods><exclude name=".*" /></methods></class> <class name="org.jboss.cdi.tck.tests.lookup.modules.specialization.SpecializationModularity06Test"><methods><exclude name=".*" /></methods></class> <class name="org.jboss.cdi.tck.tests.lookup.modules.specialization.SpecializationModularity07Test"><methods><exclude name=".*" /></methods></class> <class name="org.jboss.cdi.tck.tests.lookup.modules.SpecializedBeanInjectionNotAvailableTest"><methods><exclude name=".*" /></methods></class> <class name="org.jboss.cdi.tck.tests.deployment.packaging.installedLibrary.InstalledLibraryEarTest"><methods><exclude name=".*" /></methods></class> <class name="org.jboss.cdi.tck.tests.decorators.ordering.global.EnterpriseDecoratorOrderingTest"><methods><exclude name=".*" /></methods></class> <class name="org.jboss.cdi.tck.tests.interceptors.ordering.global.EnterpriseInterceptorOrderingTest"><methods><exclude name=".*" /></methods></class> <class name="org.jboss.cdi.tck.tests.context.application.event.ApplicationScopeEventMultiWarTest"><methods><exclude name=".*" /></methods></class> <class name="org.jboss.cdi.tck.tests.deployment.packaging.ear.modules.EnterpriseArchiveModulesTest"><methods><exclude name=".*" /></methods></class> <class name="org.jboss.cdi.tck.tests.context.passivating.dependency.resource.remote.ResourcePassivationDependencyTest"><methods><exclude name=".*" /></methods></class> <class name="org.jboss.cdi.tck.tests.lookup.modules.InterModuleELResolutionTest"><methods><exclude name=".*" /></methods></class> <class name="org.jboss.cdi.tck.tests.deployment.packaging.ear.MultiWebModuleWithExtensionTest"><methods><exclude name=".*" /></methods></class> <class name="org.jboss.cdi.tck.tests.deployment.discovery.enterprise.EnterpriseBeanDiscoveryTest"> <!-- this one is an ear + behavior is broken by design, TODO: find the associated jira issue --> <methods> <exclude name=".*" /> </methods> </class> </classes> </test> </suite>
{ "pile_set_name": "Github" }
南九州畑作営農改善資金融通臨時措置法施行規則 (昭和四十三年四月十七日農林省令第二十二号)最終改正:昭和五三年七月五日農林省令第四九号  南九州畑作営農改善資金融通臨時措置法 (昭和四十三年法律第十七号)第六条第一項 及び第二項第七号 の規定に基づき、南九州畑作営農改善資金融通臨時措置法施行規則を次のように定める。 (貸付資格の認定申請) 第一条  南九州畑作営農改善資金融通臨時措置法 (以下「法」という。)第六条第一項 の申請書の提出は、同項 の認定を受けようとする者の住所地を管轄する市町村長を経由してしなければならない。 (営農改善計画の記載事項) 第二条  法第六条第二項第七号 の農林水産省令で定める事項は、営農改善資金(法第四条 に規定する営農改善資金をいう。以下同じ。)の貸付けを受けようとする者が営農改善資金以外の資金の貸付けを受けている場合において、その貸付金の償還計画とする。    附 則  この省令は、公布の日から施行する。    附 則 (昭和五三年七月五日農林省令第四九号) 抄 第一条  この省令は、公布の日から施行する。
{ "pile_set_name": "Github" }
# Lines starting with '#' and sections without content # are not displayed by a call to 'details' # [Website] http://www.astromeridian.ru/news/drugba_megdu_mughinami_i_genhinami.html [filters] http://reklama-centr.com/view2.php?title=%C4%F0%F3%E6%E1%E0%20%EC%E5%E6%E4%F3%20%EC%F3%E6%F7%E8%ED%E0%EC%E8%20%E8%20%E6%E5%ED%F9%E8%ED%E0%EC%E8%20%ED%E5%20%E8%F1%EA%EB%FE%F7%E0%E5%F2%20%F1%E5%EA%F1%F3%E0%EB%FC%ED%EE%E3%EE%20%E2%EB%E5%F7%E5%ED%E8%FF&referrer=&lang=en-US http://reklama-centr.com/ctr.php?ref= http://reklama-centr.com/pic/04.jpg [other] # Any other details [comments] nitrox
{ "pile_set_name": "Github" }
<?xml version="1.0"?> <entity_profile> <profile id="SuperAdmin"> <name>SuperAdmin</name> </profile> </entity_profile>
{ "pile_set_name": "Github" }
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <memory> // allocator: // pointer allocate(size_type n, allocator<void>::const_pointer hint=0); #include <memory> #include <new> #include <cstdlib> #include <cassert> int new_called = 0; void* operator new(std::size_t s) throw(std::bad_alloc) { ++new_called; assert(s == 3 * sizeof(int)); return std::malloc(s); } void operator delete(void* p) throw() { --new_called; std::free(p); } int A_constructed = 0; struct A { int data; A() {++A_constructed;} A(const A&) {++A_constructed;} ~A() {--A_constructed;} }; int main() { std::allocator<A> a; assert(new_called == 0); assert(A_constructed == 0); A* ap = a.allocate(3); assert(new_called == 1); assert(A_constructed == 0); a.deallocate(ap, 3); assert(new_called == 0); assert(A_constructed == 0); A* ap2 = a.allocate(3, (const void*)5); assert(new_called == 1); assert(A_constructed == 0); a.deallocate(ap2, 3); assert(new_called == 0); assert(A_constructed == 0); }
{ "pile_set_name": "Github" }
#region Copyright (C) 2005-2009 Team MediaPortal /* * Copyright (C) 2005-2009 Team MediaPortal * http://www.team-mediaportal.com * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This Program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Make; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * http://www.gnu.org/copyleft/gpl.html * */ #endregion /* _____________________________________________________________________________ UninstallModePage _____________________________________________________________________________ */ !ifndef UninstallModePage_INCLUDED !define UninstallModePage_INCLUDED Var UnInstallMode Var uninstModePage.optBtn0 Var uninstModePage.optBtn0.state Var uninstModePage.optBtn1 Var uninstModePage.optBtn1.state Var uninstModePage.optBtn2 Var uninstModePage.optBtn2.state Function un.UninstallModePage ${If} $frominstall == 1 StrCpy $UnInstallMode 0 Abort ${EndIf} !insertmacro MUI_HEADER_TEXT "$(TEXT_UNMODE_HEADER)" "$(TEXT_UNMODE_HEADER2)" nsDialogs::Create /NOUNLOAD 1018 ;${NSD_CreateLabel} 0 0 100% 24u "$(TEXT_UNMODE_INFO)" ;Pop $R1 ${NSD_CreateRadioButton} 20u 20u -20u 8u "$(TEXT_UNMODE_OPT0)" Pop $uninstModePage.optBtn0 ${NSD_OnClick} $uninstModePage.optBtn0 un.UninstallModePageUpdateSelection ${NSD_CreateLabel} 30u 30u -30u 24u "$(TEXT_UNMODE_OPT0_DESC)" ${NSD_CreateRadioButton} 20u 60u -20u 8u "$(TEXT_UNMODE_OPT1)" Pop $uninstModePage.optBtn1 ${NSD_OnClick} $uninstModePage.optBtn1 un.UninstallModePageUpdateSelection ${NSD_CreateLabel} 30u 70u -30u 24u "$(TEXT_UNMODE_OPT1_DESC)" ${NSD_CreateRadioButton} 20u 100u -20u 8u "$(TEXT_UNMODE_OPT2)" Pop $uninstModePage.optBtn2 ${NSD_OnClick} $uninstModePage.optBtn2 un.UninstallModePageUpdateSelection ${NSD_CreateLabel} 30u 110u -30u 24u "$(TEXT_UNMODE_OPT2_DESC)" SendMessage $uninstModePage.optBtn0 ${BM_SETCHECK} ${BST_CHECKED} 0 nsDialogs::Show FunctionEnd Function un.UninstallModePageUpdateSelection ${NSD_GetState} $uninstModePage.optBtn0 $uninstModePage.optBtn0.state ${NSD_GetState} $uninstModePage.optBtn1 $uninstModePage.optBtn1.state ${NSD_GetState} $uninstModePage.optBtn2 $uninstModePage.optBtn2.state ${If} $uninstModePage.optBtn1.state == ${BST_CHECKED} StrCpy $UnInstallMode 1 ${ElseIf} $uninstModePage.optBtn2.state == ${BST_CHECKED} StrCpy $UnInstallMode 2 ${Else} StrCpy $UnInstallMode 0 ${EndIf} FunctionEnd Function un.UninstallModePageLeave ${If} $UnInstallMode == 1 MessageBox MB_YESNO|MB_ICONEXCLAMATION|MB_DEFBUTTON2 "$(TEXT_UNMODE_OPT1_MSGBOX)" IDYES +2 Abort ${ElseIf} $UnInstallMode == 2 MessageBox MB_YESNO|MB_ICONEXCLAMATION|MB_DEFBUTTON2 "$(TEXT_UNMODE_OPT2_MSGBOX)" IDYES +2 Abort ${EndIf} FunctionEnd !endif # UninstallModePage_INCLUDED
{ "pile_set_name": "Github" }
# You can specialize this file for each language. # For example, for French create a messages.fr file #
{ "pile_set_name": "Github" }
using System; using System.Threading; using System.Threading.Tasks; namespace EasyNetQ { /// <summary> /// Provides a simple Publish API to schedule a message to be published at some time in the future. /// </summary> public interface IScheduler { /// <summary> /// Schedule a message to be published at some time in the future /// </summary> /// <typeparam name="T">The message type</typeparam> /// <param name="message">The message to response with</param> /// <param name="delay">The delay for message to publish in future</param> /// <param name="configure"> /// Fluent configuration e.g. x => x.WithTopic("*.brighton").WithPriority(2) /// </param> /// <param name="cancellationToken">The cancellation token</param> Task FuturePublishAsync<T>( T message, TimeSpan delay, Action<IFuturePublishConfiguration> configure, CancellationToken cancellationToken = default ); } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <root> <!-- Microsoft ResX Schema Version 2.0 The primary goals of this format is to allow a simple XML format that is mostly human readable. The generation and parsing of the various data types are done through the TypeConverter classes associated with the data types. Example: ... ado.net/XML headers & schema ... <resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="version">2.0</resheader> <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data> <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> <value>[base64 mime encoded serialized .NET Framework object]</value> </data> <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> <comment>This is a comment</comment> </data> There are any number of "resheader" rows that contain simple name/value pairs. Each data row contains a name, and value. The row also contains a type or mimetype. Type corresponds to a .NET class that support text/value conversion through the TypeConverter architecture. Classes that don't support this are serialized and stored with the mimetype set. The mimetype is used for serialized objects, and tells the ResXResourceReader how to depersist the object. This is currently not extensible. For a given mimetype the value must be set accordingly: Note - application/x-microsoft.net.object.binary.base64 is the format that the ResXResourceWriter will generate, however the reader can read any of the formats listed below. mimetype: application/x-microsoft.net.object.binary.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.soap.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Soap.SoapFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.bytearray.base64 value : The object must be serialized into a byte array : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:import namespace="http://www.w3.org/XML/1998/namespace" /> <xsd:element name="root" msdata:IsDataSet="true"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:element name="metadata"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" /> </xsd:sequence> <xsd:attribute name="name" use="required" type="xsd:string" /> <xsd:attribute name="type" type="xsd:string" /> <xsd:attribute name="mimetype" type="xsd:string" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="assembly"> <xsd:complexType> <xsd:attribute name="alias" type="xsd:string" /> <xsd:attribute name="name" type="xsd:string" /> </xsd:complexType> </xsd:element> <xsd:element name="data"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" /> <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="resheader"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" /> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema> <resheader name="resmimetype"> <value>text/microsoft-resx</value> </resheader> <resheader name="version"> <value>2.0</value> </resheader> <resheader name="reader"> <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <resheader name="writer"> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <metadata name="MenuStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"> <value>17, 17</value> </metadata> <metadata name="ContextMenuStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"> <value>132, 17</value> </metadata> </root>
{ "pile_set_name": "Github" }
/* crypto/sha/sha512.c */ /* ==================================================================== * Copyright (c) 2004 The OpenSSL Project. All rights reserved * according to the OpenSSL license [found in ../../LICENSE]. * ==================================================================== */ #include <openssl/opensslconf.h> #if !defined(OPENSSL_NO_SHA) && !defined(OPENSSL_NO_SHA512) /*- * IMPLEMENTATION NOTES. * * As you might have noticed 32-bit hash algorithms: * * - permit SHA_LONG to be wider than 32-bit (case on CRAY); * - optimized versions implement two transform functions: one operating * on [aligned] data in host byte order and one - on data in input * stream byte order; * - share common byte-order neutral collector and padding function * implementations, ../md32_common.h; * * Neither of the above applies to this SHA-512 implementations. Reasons * [in reverse order] are: * * - it's the only 64-bit hash algorithm for the moment of this writing, * there is no need for common collector/padding implementation [yet]; * - by supporting only one transform function [which operates on * *aligned* data in input stream byte order, big-endian in this case] * we minimize burden of maintenance in two ways: a) collector/padding * function is simpler; b) only one transform function to stare at; * - SHA_LONG64 is required to be exactly 64-bit in order to be able to * apply a number of optimizations to mitigate potential performance * penalties caused by previous design decision; * * Caveat lector. * * Implementation relies on the fact that "long long" is 64-bit on * both 32- and 64-bit platforms. If some compiler vendor comes up * with 128-bit long long, adjustment to sha.h would be required. * As this implementation relies on 64-bit integer type, it's totally * inappropriate for platforms which don't support it, most notably * 16-bit platforms. * <[email protected]> */ # include <stdlib.h> # include <string.h> # include <openssl/crypto.h> # include <openssl/sha.h> # include <openssl/opensslv.h> # include "cryptlib.h" const char SHA512_version[] = "SHA-512" OPENSSL_VERSION_PTEXT; # if defined(__i386) || defined(__i386__) || defined(_M_IX86) || \ defined(__x86_64) || defined(_M_AMD64) || defined(_M_X64) || \ defined(__s390__) || defined(__s390x__) || \ defined(__aarch64__) || \ defined(SHA512_ASM) # define SHA512_BLOCK_CAN_MANAGE_UNALIGNED_DATA # endif fips_md_init_ctx(SHA384, SHA512) { c->h[0] = U64(0xcbbb9d5dc1059ed8); c->h[1] = U64(0x629a292a367cd507); c->h[2] = U64(0x9159015a3070dd17); c->h[3] = U64(0x152fecd8f70e5939); c->h[4] = U64(0x67332667ffc00b31); c->h[5] = U64(0x8eb44a8768581511); c->h[6] = U64(0xdb0c2e0d64f98fa7); c->h[7] = U64(0x47b5481dbefa4fa4); c->Nl = 0; c->Nh = 0; c->num = 0; c->md_len = SHA384_DIGEST_LENGTH; return 1; } fips_md_init(SHA512) { c->h[0] = U64(0x6a09e667f3bcc908); c->h[1] = U64(0xbb67ae8584caa73b); c->h[2] = U64(0x3c6ef372fe94f82b); c->h[3] = U64(0xa54ff53a5f1d36f1); c->h[4] = U64(0x510e527fade682d1); c->h[5] = U64(0x9b05688c2b3e6c1f); c->h[6] = U64(0x1f83d9abfb41bd6b); c->h[7] = U64(0x5be0cd19137e2179); c->Nl = 0; c->Nh = 0; c->num = 0; c->md_len = SHA512_DIGEST_LENGTH; return 1; } # ifndef SHA512_ASM static # endif void sha512_block_data_order(SHA512_CTX *ctx, const void *in, size_t num); int SHA512_Final(unsigned char *md, SHA512_CTX *c) { unsigned char *p = (unsigned char *)c->u.p; size_t n = c->num; p[n] = 0x80; /* There always is a room for one */ n++; if (n > (sizeof(c->u) - 16)) memset(p + n, 0, sizeof(c->u) - n), n = 0, sha512_block_data_order(c, p, 1); memset(p + n, 0, sizeof(c->u) - 16 - n); # ifdef B_ENDIAN c->u.d[SHA_LBLOCK - 2] = c->Nh; c->u.d[SHA_LBLOCK - 1] = c->Nl; # else p[sizeof(c->u) - 1] = (unsigned char)(c->Nl); p[sizeof(c->u) - 2] = (unsigned char)(c->Nl >> 8); p[sizeof(c->u) - 3] = (unsigned char)(c->Nl >> 16); p[sizeof(c->u) - 4] = (unsigned char)(c->Nl >> 24); p[sizeof(c->u) - 5] = (unsigned char)(c->Nl >> 32); p[sizeof(c->u) - 6] = (unsigned char)(c->Nl >> 40); p[sizeof(c->u) - 7] = (unsigned char)(c->Nl >> 48); p[sizeof(c->u) - 8] = (unsigned char)(c->Nl >> 56); p[sizeof(c->u) - 9] = (unsigned char)(c->Nh); p[sizeof(c->u) - 10] = (unsigned char)(c->Nh >> 8); p[sizeof(c->u) - 11] = (unsigned char)(c->Nh >> 16); p[sizeof(c->u) - 12] = (unsigned char)(c->Nh >> 24); p[sizeof(c->u) - 13] = (unsigned char)(c->Nh >> 32); p[sizeof(c->u) - 14] = (unsigned char)(c->Nh >> 40); p[sizeof(c->u) - 15] = (unsigned char)(c->Nh >> 48); p[sizeof(c->u) - 16] = (unsigned char)(c->Nh >> 56); # endif sha512_block_data_order(c, p, 1); if (md == 0) return 0; switch (c->md_len) { /* Let compiler decide if it's appropriate to unroll... */ case SHA384_DIGEST_LENGTH: for (n = 0; n < SHA384_DIGEST_LENGTH / 8; n++) { SHA_LONG64 t = c->h[n]; *(md++) = (unsigned char)(t >> 56); *(md++) = (unsigned char)(t >> 48); *(md++) = (unsigned char)(t >> 40); *(md++) = (unsigned char)(t >> 32); *(md++) = (unsigned char)(t >> 24); *(md++) = (unsigned char)(t >> 16); *(md++) = (unsigned char)(t >> 8); *(md++) = (unsigned char)(t); } break; case SHA512_DIGEST_LENGTH: for (n = 0; n < SHA512_DIGEST_LENGTH / 8; n++) { SHA_LONG64 t = c->h[n]; *(md++) = (unsigned char)(t >> 56); *(md++) = (unsigned char)(t >> 48); *(md++) = (unsigned char)(t >> 40); *(md++) = (unsigned char)(t >> 32); *(md++) = (unsigned char)(t >> 24); *(md++) = (unsigned char)(t >> 16); *(md++) = (unsigned char)(t >> 8); *(md++) = (unsigned char)(t); } break; /* ... as well as make sure md_len is not abused. */ default: return 0; } return 1; } int SHA384_Final(unsigned char *md, SHA512_CTX *c) { return SHA512_Final(md, c); } int SHA512_Update(SHA512_CTX *c, const void *_data, size_t len) { SHA_LONG64 l; unsigned char *p = c->u.p; const unsigned char *data = (const unsigned char *)_data; if (len == 0) return 1; l = (c->Nl + (((SHA_LONG64) len) << 3)) & U64(0xffffffffffffffff); if (l < c->Nl) c->Nh++; if (sizeof(len) >= 8) c->Nh += (((SHA_LONG64) len) >> 61); c->Nl = l; if (c->num != 0) { size_t n = sizeof(c->u) - c->num; if (len < n) { memcpy(p + c->num, data, len), c->num += (unsigned int)len; return 1; } else { memcpy(p + c->num, data, n), c->num = 0; len -= n, data += n; sha512_block_data_order(c, p, 1); } } if (len >= sizeof(c->u)) { # ifndef SHA512_BLOCK_CAN_MANAGE_UNALIGNED_DATA if ((size_t)data % sizeof(c->u.d[0]) != 0) while (len >= sizeof(c->u)) memcpy(p, data, sizeof(c->u)), sha512_block_data_order(c, p, 1), len -= sizeof(c->u), data += sizeof(c->u); else # endif sha512_block_data_order(c, data, len / sizeof(c->u)), data += len, len %= sizeof(c->u), data -= len; } if (len != 0) memcpy(p, data, len), c->num = (int)len; return 1; } int SHA384_Update(SHA512_CTX *c, const void *data, size_t len) { return SHA512_Update(c, data, len); } void SHA512_Transform(SHA512_CTX *c, const unsigned char *data) { # ifndef SHA512_BLOCK_CAN_MANAGE_UNALIGNED_DATA if ((size_t)data % sizeof(c->u.d[0]) != 0) memcpy(c->u.p, data, sizeof(c->u.p)), data = c->u.p; # endif sha512_block_data_order(c, data, 1); } unsigned char *SHA384(const unsigned char *d, size_t n, unsigned char *md) { SHA512_CTX c; static unsigned char m[SHA384_DIGEST_LENGTH]; if (md == NULL) md = m; SHA384_Init(&c); SHA512_Update(&c, d, n); SHA512_Final(md, &c); OPENSSL_cleanse(&c, sizeof(c)); return (md); } unsigned char *SHA512(const unsigned char *d, size_t n, unsigned char *md) { SHA512_CTX c; static unsigned char m[SHA512_DIGEST_LENGTH]; if (md == NULL) md = m; SHA512_Init(&c); SHA512_Update(&c, d, n); SHA512_Final(md, &c); OPENSSL_cleanse(&c, sizeof(c)); return (md); } # ifndef SHA512_ASM static const SHA_LONG64 K512[80] = { U64(0x428a2f98d728ae22), U64(0x7137449123ef65cd), U64(0xb5c0fbcfec4d3b2f), U64(0xe9b5dba58189dbbc), U64(0x3956c25bf348b538), U64(0x59f111f1b605d019), U64(0x923f82a4af194f9b), U64(0xab1c5ed5da6d8118), U64(0xd807aa98a3030242), U64(0x12835b0145706fbe), U64(0x243185be4ee4b28c), U64(0x550c7dc3d5ffb4e2), U64(0x72be5d74f27b896f), U64(0x80deb1fe3b1696b1), U64(0x9bdc06a725c71235), U64(0xc19bf174cf692694), U64(0xe49b69c19ef14ad2), U64(0xefbe4786384f25e3), U64(0x0fc19dc68b8cd5b5), U64(0x240ca1cc77ac9c65), U64(0x2de92c6f592b0275), U64(0x4a7484aa6ea6e483), U64(0x5cb0a9dcbd41fbd4), U64(0x76f988da831153b5), U64(0x983e5152ee66dfab), U64(0xa831c66d2db43210), U64(0xb00327c898fb213f), U64(0xbf597fc7beef0ee4), U64(0xc6e00bf33da88fc2), U64(0xd5a79147930aa725), U64(0x06ca6351e003826f), U64(0x142929670a0e6e70), U64(0x27b70a8546d22ffc), U64(0x2e1b21385c26c926), U64(0x4d2c6dfc5ac42aed), U64(0x53380d139d95b3df), U64(0x650a73548baf63de), U64(0x766a0abb3c77b2a8), U64(0x81c2c92e47edaee6), U64(0x92722c851482353b), U64(0xa2bfe8a14cf10364), U64(0xa81a664bbc423001), U64(0xc24b8b70d0f89791), U64(0xc76c51a30654be30), U64(0xd192e819d6ef5218), U64(0xd69906245565a910), U64(0xf40e35855771202a), U64(0x106aa07032bbd1b8), U64(0x19a4c116b8d2d0c8), U64(0x1e376c085141ab53), U64(0x2748774cdf8eeb99), U64(0x34b0bcb5e19b48a8), U64(0x391c0cb3c5c95a63), U64(0x4ed8aa4ae3418acb), U64(0x5b9cca4f7763e373), U64(0x682e6ff3d6b2b8a3), U64(0x748f82ee5defb2fc), U64(0x78a5636f43172f60), U64(0x84c87814a1f0ab72), U64(0x8cc702081a6439ec), U64(0x90befffa23631e28), U64(0xa4506cebde82bde9), U64(0xbef9a3f7b2c67915), U64(0xc67178f2e372532b), U64(0xca273eceea26619c), U64(0xd186b8c721c0c207), U64(0xeada7dd6cde0eb1e), U64(0xf57d4f7fee6ed178), U64(0x06f067aa72176fba), U64(0x0a637dc5a2c898a6), U64(0x113f9804bef90dae), U64(0x1b710b35131c471b), U64(0x28db77f523047d84), U64(0x32caab7b40c72493), U64(0x3c9ebe0a15c9bebc), U64(0x431d67c49c100d4c), U64(0x4cc5d4becb3e42b6), U64(0x597f299cfc657e2a), U64(0x5fcb6fab3ad6faec), U64(0x6c44198c4a475817) }; # ifndef PEDANTIC # if defined(__GNUC__) && __GNUC__>=2 && !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM) # if defined(__x86_64) || defined(__x86_64__) # define ROTR(a,n) ({ SHA_LONG64 ret; \ asm ("rorq %1,%0" \ : "=r"(ret) \ : "J"(n),"0"(a) \ : "cc"); ret; }) # if !defined(B_ENDIAN) # define PULL64(x) ({ SHA_LONG64 ret=*((const SHA_LONG64 *)(&(x))); \ asm ("bswapq %0" \ : "=r"(ret) \ : "0"(ret)); ret; }) # endif # elif (defined(__i386) || defined(__i386__)) && !defined(B_ENDIAN) # if defined(I386_ONLY) # define PULL64(x) ({ const unsigned int *p=(const unsigned int *)(&(x));\ unsigned int hi=p[0],lo=p[1]; \ asm("xchgb %%ah,%%al;xchgb %%dh,%%dl;"\ "roll $16,%%eax; roll $16,%%edx; "\ "xchgb %%ah,%%al;xchgb %%dh,%%dl;" \ : "=a"(lo),"=d"(hi) \ : "0"(lo),"1"(hi) : "cc"); \ ((SHA_LONG64)hi)<<32|lo; }) # else # define PULL64(x) ({ const unsigned int *p=(const unsigned int *)(&(x));\ unsigned int hi=p[0],lo=p[1]; \ asm ("bswapl %0; bswapl %1;" \ : "=r"(lo),"=r"(hi) \ : "0"(lo),"1"(hi)); \ ((SHA_LONG64)hi)<<32|lo; }) # endif # elif (defined(_ARCH_PPC) && defined(__64BIT__)) || defined(_ARCH_PPC64) # define ROTR(a,n) ({ SHA_LONG64 ret; \ asm ("rotrdi %0,%1,%2" \ : "=r"(ret) \ : "r"(a),"K"(n)); ret; }) # elif defined(__aarch64__) # define ROTR(a,n) ({ SHA_LONG64 ret; \ asm ("ror %0,%1,%2" \ : "=r"(ret) \ : "r"(a),"I"(n)); ret; }) # if defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && \ __BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__ # define PULL64(x) ({ SHA_LONG64 ret; \ asm ("rev %0,%1" \ : "=r"(ret) \ : "r"(*((const SHA_LONG64 *)(&(x))))); ret; }) # endif # endif # elif defined(_MSC_VER) # if defined(_WIN64) /* applies to both IA-64 and AMD64 */ # pragma intrinsic(_rotr64) # define ROTR(a,n) _rotr64((a),n) # endif # if defined(_M_IX86) && !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM) # if defined(I386_ONLY) static SHA_LONG64 __fastcall __pull64be(const void *x) { _asm mov edx,[ecx + 0] _asm mov eax,[ecx + 4] _asm xchg dh, dl _asm xchg ah, al _asm rol edx, 16 _asm rol eax, 16 _asm xchg dh, dl _asm xchg ah, al} # else static SHA_LONG64 __fastcall __pull64be(const void *x) { _asm mov edx,[ecx + 0] _asm mov eax,[ecx + 4] _asm bswap edx _asm bswap eax} # endif # define PULL64(x) __pull64be(&(x)) # if _MSC_VER<=1200 # pragma inline_depth(0) # endif # endif # endif # endif # ifndef PULL64 # define B(x,j) (((SHA_LONG64)(*(((const unsigned char *)(&x))+j)))<<((7-j)*8)) # define PULL64(x) (B(x,0)|B(x,1)|B(x,2)|B(x,3)|B(x,4)|B(x,5)|B(x,6)|B(x,7)) # endif # ifndef ROTR # define ROTR(x,s) (((x)>>s) | (x)<<(64-s)) # endif # define Sigma0(x) (ROTR((x),28) ^ ROTR((x),34) ^ ROTR((x),39)) # define Sigma1(x) (ROTR((x),14) ^ ROTR((x),18) ^ ROTR((x),41)) # define sigma0(x) (ROTR((x),1) ^ ROTR((x),8) ^ ((x)>>7)) # define sigma1(x) (ROTR((x),19) ^ ROTR((x),61) ^ ((x)>>6)) # define Ch(x,y,z) (((x) & (y)) ^ ((~(x)) & (z))) # define Maj(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z))) # if defined(__i386) || defined(__i386__) || defined(_M_IX86) /* * This code should give better results on 32-bit CPU with less than * ~24 registers, both size and performance wise... */ static void sha512_block_data_order(SHA512_CTX *ctx, const void *in, size_t num) { const SHA_LONG64 *W = in; SHA_LONG64 A, E, T; SHA_LONG64 X[9 + 80], *F; int i; while (num--) { F = X + 80; A = ctx->h[0]; F[1] = ctx->h[1]; F[2] = ctx->h[2]; F[3] = ctx->h[3]; E = ctx->h[4]; F[5] = ctx->h[5]; F[6] = ctx->h[6]; F[7] = ctx->h[7]; for (i = 0; i < 16; i++, F--) { # ifdef B_ENDIAN T = W[i]; # else T = PULL64(W[i]); # endif F[0] = A; F[4] = E; F[8] = T; T += F[7] + Sigma1(E) + Ch(E, F[5], F[6]) + K512[i]; E = F[3] + T; A = T + Sigma0(A) + Maj(A, F[1], F[2]); } for (; i < 80; i++, F--) { T = sigma0(F[8 + 16 - 1]); T += sigma1(F[8 + 16 - 14]); T += F[8 + 16] + F[8 + 16 - 9]; F[0] = A; F[4] = E; F[8] = T; T += F[7] + Sigma1(E) + Ch(E, F[5], F[6]) + K512[i]; E = F[3] + T; A = T + Sigma0(A) + Maj(A, F[1], F[2]); } ctx->h[0] += A; ctx->h[1] += F[1]; ctx->h[2] += F[2]; ctx->h[3] += F[3]; ctx->h[4] += E; ctx->h[5] += F[5]; ctx->h[6] += F[6]; ctx->h[7] += F[7]; W += SHA_LBLOCK; } } # elif defined(OPENSSL_SMALL_FOOTPRINT) static void sha512_block_data_order(SHA512_CTX *ctx, const void *in, size_t num) { const SHA_LONG64 *W = in; SHA_LONG64 a, b, c, d, e, f, g, h, s0, s1, T1, T2; SHA_LONG64 X[16]; int i; while (num--) { a = ctx->h[0]; b = ctx->h[1]; c = ctx->h[2]; d = ctx->h[3]; e = ctx->h[4]; f = ctx->h[5]; g = ctx->h[6]; h = ctx->h[7]; for (i = 0; i < 16; i++) { # ifdef B_ENDIAN T1 = X[i] = W[i]; # else T1 = X[i] = PULL64(W[i]); # endif T1 += h + Sigma1(e) + Ch(e, f, g) + K512[i]; T2 = Sigma0(a) + Maj(a, b, c); h = g; g = f; f = e; e = d + T1; d = c; c = b; b = a; a = T1 + T2; } for (; i < 80; i++) { s0 = X[(i + 1) & 0x0f]; s0 = sigma0(s0); s1 = X[(i + 14) & 0x0f]; s1 = sigma1(s1); T1 = X[i & 0xf] += s0 + s1 + X[(i + 9) & 0xf]; T1 += h + Sigma1(e) + Ch(e, f, g) + K512[i]; T2 = Sigma0(a) + Maj(a, b, c); h = g; g = f; f = e; e = d + T1; d = c; c = b; b = a; a = T1 + T2; } ctx->h[0] += a; ctx->h[1] += b; ctx->h[2] += c; ctx->h[3] += d; ctx->h[4] += e; ctx->h[5] += f; ctx->h[6] += g; ctx->h[7] += h; W += SHA_LBLOCK; } } # else # define ROUND_00_15(i,a,b,c,d,e,f,g,h) do { \ T1 += h + Sigma1(e) + Ch(e,f,g) + K512[i]; \ h = Sigma0(a) + Maj(a,b,c); \ d += T1; h += T1; } while (0) # define ROUND_16_80(i,j,a,b,c,d,e,f,g,h,X) do { \ s0 = X[(j+1)&0x0f]; s0 = sigma0(s0); \ s1 = X[(j+14)&0x0f]; s1 = sigma1(s1); \ T1 = X[(j)&0x0f] += s0 + s1 + X[(j+9)&0x0f]; \ ROUND_00_15(i+j,a,b,c,d,e,f,g,h); } while (0) static void sha512_block_data_order(SHA512_CTX *ctx, const void *in, size_t num) { const SHA_LONG64 *W = in; SHA_LONG64 a, b, c, d, e, f, g, h, s0, s1, T1; SHA_LONG64 X[16]; int i; while (num--) { a = ctx->h[0]; b = ctx->h[1]; c = ctx->h[2]; d = ctx->h[3]; e = ctx->h[4]; f = ctx->h[5]; g = ctx->h[6]; h = ctx->h[7]; # ifdef B_ENDIAN T1 = X[0] = W[0]; ROUND_00_15(0, a, b, c, d, e, f, g, h); T1 = X[1] = W[1]; ROUND_00_15(1, h, a, b, c, d, e, f, g); T1 = X[2] = W[2]; ROUND_00_15(2, g, h, a, b, c, d, e, f); T1 = X[3] = W[3]; ROUND_00_15(3, f, g, h, a, b, c, d, e); T1 = X[4] = W[4]; ROUND_00_15(4, e, f, g, h, a, b, c, d); T1 = X[5] = W[5]; ROUND_00_15(5, d, e, f, g, h, a, b, c); T1 = X[6] = W[6]; ROUND_00_15(6, c, d, e, f, g, h, a, b); T1 = X[7] = W[7]; ROUND_00_15(7, b, c, d, e, f, g, h, a); T1 = X[8] = W[8]; ROUND_00_15(8, a, b, c, d, e, f, g, h); T1 = X[9] = W[9]; ROUND_00_15(9, h, a, b, c, d, e, f, g); T1 = X[10] = W[10]; ROUND_00_15(10, g, h, a, b, c, d, e, f); T1 = X[11] = W[11]; ROUND_00_15(11, f, g, h, a, b, c, d, e); T1 = X[12] = W[12]; ROUND_00_15(12, e, f, g, h, a, b, c, d); T1 = X[13] = W[13]; ROUND_00_15(13, d, e, f, g, h, a, b, c); T1 = X[14] = W[14]; ROUND_00_15(14, c, d, e, f, g, h, a, b); T1 = X[15] = W[15]; ROUND_00_15(15, b, c, d, e, f, g, h, a); # else T1 = X[0] = PULL64(W[0]); ROUND_00_15(0, a, b, c, d, e, f, g, h); T1 = X[1] = PULL64(W[1]); ROUND_00_15(1, h, a, b, c, d, e, f, g); T1 = X[2] = PULL64(W[2]); ROUND_00_15(2, g, h, a, b, c, d, e, f); T1 = X[3] = PULL64(W[3]); ROUND_00_15(3, f, g, h, a, b, c, d, e); T1 = X[4] = PULL64(W[4]); ROUND_00_15(4, e, f, g, h, a, b, c, d); T1 = X[5] = PULL64(W[5]); ROUND_00_15(5, d, e, f, g, h, a, b, c); T1 = X[6] = PULL64(W[6]); ROUND_00_15(6, c, d, e, f, g, h, a, b); T1 = X[7] = PULL64(W[7]); ROUND_00_15(7, b, c, d, e, f, g, h, a); T1 = X[8] = PULL64(W[8]); ROUND_00_15(8, a, b, c, d, e, f, g, h); T1 = X[9] = PULL64(W[9]); ROUND_00_15(9, h, a, b, c, d, e, f, g); T1 = X[10] = PULL64(W[10]); ROUND_00_15(10, g, h, a, b, c, d, e, f); T1 = X[11] = PULL64(W[11]); ROUND_00_15(11, f, g, h, a, b, c, d, e); T1 = X[12] = PULL64(W[12]); ROUND_00_15(12, e, f, g, h, a, b, c, d); T1 = X[13] = PULL64(W[13]); ROUND_00_15(13, d, e, f, g, h, a, b, c); T1 = X[14] = PULL64(W[14]); ROUND_00_15(14, c, d, e, f, g, h, a, b); T1 = X[15] = PULL64(W[15]); ROUND_00_15(15, b, c, d, e, f, g, h, a); # endif for (i = 16; i < 80; i += 16) { ROUND_16_80(i, 0, a, b, c, d, e, f, g, h, X); ROUND_16_80(i, 1, h, a, b, c, d, e, f, g, X); ROUND_16_80(i, 2, g, h, a, b, c, d, e, f, X); ROUND_16_80(i, 3, f, g, h, a, b, c, d, e, X); ROUND_16_80(i, 4, e, f, g, h, a, b, c, d, X); ROUND_16_80(i, 5, d, e, f, g, h, a, b, c, X); ROUND_16_80(i, 6, c, d, e, f, g, h, a, b, X); ROUND_16_80(i, 7, b, c, d, e, f, g, h, a, X); ROUND_16_80(i, 8, a, b, c, d, e, f, g, h, X); ROUND_16_80(i, 9, h, a, b, c, d, e, f, g, X); ROUND_16_80(i, 10, g, h, a, b, c, d, e, f, X); ROUND_16_80(i, 11, f, g, h, a, b, c, d, e, X); ROUND_16_80(i, 12, e, f, g, h, a, b, c, d, X); ROUND_16_80(i, 13, d, e, f, g, h, a, b, c, X); ROUND_16_80(i, 14, c, d, e, f, g, h, a, b, X); ROUND_16_80(i, 15, b, c, d, e, f, g, h, a, X); } ctx->h[0] += a; ctx->h[1] += b; ctx->h[2] += c; ctx->h[3] += d; ctx->h[4] += e; ctx->h[5] += f; ctx->h[6] += g; ctx->h[7] += h; W += SHA_LBLOCK; } } # endif # endif /* SHA512_ASM */ #else /* !OPENSSL_NO_SHA512 */ # if defined(PEDANTIC) || defined(__DECC) || defined(OPENSSL_SYS_MACOSX) static void *dummy = &dummy; # endif #endif /* !OPENSSL_NO_SHA512 */
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProjectGuid>{55DEDF5E-4BA2-498C-AB7A-B7EF2E41F79A}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>msdyncrmWorkflowTools_Class</RootNamespace> <AssemblyName>msdyncrmWorkflowTools_Class</AssemblyName> <TargetFrameworkVersion>v4.6.2</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> <SccProjectName>SAK</SccProjectName> <SccLocalPath>SAK</SccLocalPath> <SccAuxPath>SAK</SccAuxPath> <SccProvider>SAK</SccProvider> <TargetFrameworkProfile /> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="Microsoft.Crm.Sdk.Proxy, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> <HintPath>..\packages\Microsoft.CrmSdk.CoreAssemblies.9.0.2.21\lib\net462\Microsoft.Crm.Sdk.Proxy.dll</HintPath> </Reference> <Reference Include="Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> <HintPath>..\packages\Microsoft.IdentityModel.6.1.7600.16394\lib\net35\Microsoft.IdentityModel.dll</HintPath> <Private>True</Private> </Reference> <Reference Include="Microsoft.Xrm.Sdk, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> <HintPath>..\packages\Microsoft.CrmSdk.CoreAssemblies.9.0.2.21\lib\net462\Microsoft.Xrm.Sdk.dll</HintPath> </Reference> <Reference Include="Microsoft.Xrm.Sdk.Workflow, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> <HintPath>..\packages\Microsoft.CrmSdk.Workflow.9.0.2.21\lib\net462\Microsoft.Xrm.Sdk.Workflow.dll</HintPath> </Reference> <Reference Include="PresentationFramework" /> <Reference Include="System" /> <Reference Include="System.Activities" /> <Reference Include="System.Activities.Presentation" /> <Reference Include="System.Core" /> <Reference Include="System.DirectoryServices" /> <Reference Include="System.DirectoryServices.AccountManagement" /> <Reference Include="System.Drawing" /> <Reference Include="System.IdentityModel" /> <Reference Include="System.Runtime.Serialization" /> <Reference Include="System.Security" /> <Reference Include="System.ServiceModel" /> <Reference Include="System.ServiceModel.Web" /> <Reference Include="System.Web" /> <Reference Include="System.Workflow.Activities" /> <Reference Include="System.Workflow.ComponentModel" /> <Reference Include="System.Workflow.Runtime" /> <Reference Include="System.Xml.Linq" /> <Reference Include="System.Data.DataSetExtensions" /> <Reference Include="Microsoft.CSharp" /> <Reference Include="System.Data" /> <Reference Include="System.Net.Http" /> <Reference Include="System.Xml" /> </ItemGroup> <ItemGroup> <Compile Include="msdyncrmWorkflowTools_Class.cs" /> <Compile Include="Newtonsoft\Bson\BsonBinaryType.cs" /> <Compile Include="Newtonsoft\Bson\BsonBinaryWriter.cs" /> <Compile Include="Newtonsoft\Bson\BsonObjectId.cs" /> <Compile Include="Newtonsoft\Bson\BsonReader.cs" /> <Compile Include="Newtonsoft\Bson\BsonToken.cs" /> <Compile Include="Newtonsoft\Bson\BsonType.cs" /> <Compile Include="Newtonsoft\Bson\BsonWriter.cs" /> <Compile Include="Newtonsoft\ConstructorHandling.cs" /> <Compile Include="Newtonsoft\Converters\BinaryConverter.cs" /> <Compile Include="Newtonsoft\Converters\BsonObjectIdConverter.cs" /> <Compile Include="Newtonsoft\Converters\CustomCreationConverter.cs" /> <Compile Include="Newtonsoft\Converters\DataSetConverter.cs" /> <Compile Include="Newtonsoft\Converters\DataTableConverter.cs" /> <Compile Include="Newtonsoft\Converters\DateTimeConverterBase.cs" /> <Compile Include="Newtonsoft\Converters\DiscriminatedUnionConverter.cs" /> <Compile Include="Newtonsoft\Converters\EntityKeyMemberConverter.cs" /> <Compile Include="Newtonsoft\Converters\ExpandoObjectConverter.cs" /> <Compile Include="Newtonsoft\Converters\IsoDateTimeConverter.cs" /> <Compile Include="Newtonsoft\Converters\JavaScriptDateTimeConverter.cs" /> <Compile Include="Newtonsoft\Converters\JsonValueConverter.cs" /> <Compile Include="Newtonsoft\Converters\KeyValuePairConverter.cs" /> <Compile Include="Newtonsoft\Converters\RegexConverter.cs" /> <Compile Include="Newtonsoft\Converters\StringEnumConverter.cs" /> <Compile Include="Newtonsoft\Converters\VersionConverter.cs" /> <Compile Include="Newtonsoft\Converters\XmlNodeConverter.cs" /> <Compile Include="Newtonsoft\DateFormatHandling.cs" /> <Compile Include="Newtonsoft\DateParseHandling.cs" /> <Compile Include="Newtonsoft\DateTimeZoneHandling.cs" /> <Compile Include="Newtonsoft\DefaultValueHandling.cs" /> <Compile Include="Newtonsoft\FloatFormatHandling.cs" /> <Compile Include="Newtonsoft\FloatParseHandling.cs" /> <Compile Include="Newtonsoft\FormatterAssemblyStyle.cs" /> <Compile Include="Newtonsoft\Formatting.cs" /> <Compile Include="Newtonsoft\IArrayPool.cs" /> <Compile Include="Newtonsoft\IJsonLineInfo.cs" /> <Compile Include="Newtonsoft\JsonArrayAttribute.cs" /> <Compile Include="Newtonsoft\JsonConstructorAttribute.cs" /> <Compile Include="Newtonsoft\JsonContainerAttribute.cs" /> <Compile Include="Newtonsoft\JsonConvert.cs" /> <Compile Include="Newtonsoft\JsonConverter.cs" /> <Compile Include="Newtonsoft\JsonConverterAttribute.cs" /> <Compile Include="Newtonsoft\JsonConverterCollection.cs" /> <Compile Include="Newtonsoft\JsonDictionaryAttribute.cs" /> <Compile Include="Newtonsoft\JsonException.cs" /> <Compile Include="Newtonsoft\JsonExtensionDataAttribute.cs" /> <Compile Include="Newtonsoft\JsonIgnoreAttribute.cs" /> <Compile Include="Newtonsoft\JsonObjectAttribute.cs" /> <Compile Include="Newtonsoft\JsonPosition.cs" /> <Compile Include="Newtonsoft\JsonPropertyAttribute.cs" /> <Compile Include="Newtonsoft\JsonReader.cs" /> <Compile Include="Newtonsoft\JsonReaderException.cs" /> <Compile Include="Newtonsoft\JsonRequiredAttribute.cs" /> <Compile Include="Newtonsoft\JsonSerializationException.cs" /> <Compile Include="Newtonsoft\JsonSerializer.cs" /> <Compile Include="Newtonsoft\JsonSerializerSettings.cs" /> <Compile Include="Newtonsoft\JsonTextReader.cs" /> <Compile Include="Newtonsoft\JsonTextWriter.cs" /> <Compile Include="Newtonsoft\JsonToken.cs" /> <Compile Include="Newtonsoft\JsonValidatingReader.cs" /> <Compile Include="Newtonsoft\JsonWriter.cs" /> <Compile Include="Newtonsoft\JsonWriterException.cs" /> <Compile Include="Newtonsoft\Linq\CommentHandling.cs" /> <Compile Include="Newtonsoft\Linq\Extensions.cs" /> <Compile Include="Newtonsoft\Linq\IJEnumerable.cs" /> <Compile Include="Newtonsoft\Linq\JArray.cs" /> <Compile Include="Newtonsoft\Linq\JConstructor.cs" /> <Compile Include="Newtonsoft\Linq\JContainer.cs" /> <Compile Include="Newtonsoft\Linq\JEnumerable.cs" /> <Compile Include="Newtonsoft\Linq\JObject.cs" /> <Compile Include="Newtonsoft\Linq\JProperty.cs" /> <Compile Include="Newtonsoft\Linq\JPropertyDescriptor.cs" /> <Compile Include="Newtonsoft\Linq\JPropertyKeyedCollection.cs" /> <Compile Include="Newtonsoft\Linq\JRaw.cs" /> <Compile Include="Newtonsoft\Linq\JsonLoadSettings.cs" /> <Compile Include="Newtonsoft\Linq\JsonMergeSettings.cs" /> <Compile Include="Newtonsoft\Linq\JsonPath\ArrayIndexFilter.cs" /> <Compile Include="Newtonsoft\Linq\JsonPath\ArrayMultipleIndexFilter.cs" /> <Compile Include="Newtonsoft\Linq\JsonPath\ArraySliceFilter.cs" /> <Compile Include="Newtonsoft\Linq\JsonPath\FieldFilter.cs" /> <Compile Include="Newtonsoft\Linq\JsonPath\FieldMultipleFilter.cs" /> <Compile Include="Newtonsoft\Linq\JsonPath\JPath.cs" /> <Compile Include="Newtonsoft\Linq\JsonPath\PathFilter.cs" /> <Compile Include="Newtonsoft\Linq\JsonPath\QueryExpression.cs" /> <Compile Include="Newtonsoft\Linq\JsonPath\QueryFilter.cs" /> <Compile Include="Newtonsoft\Linq\JsonPath\ScanFilter.cs" /> <Compile Include="Newtonsoft\Linq\JToken.cs" /> <Compile Include="Newtonsoft\Linq\JTokenEqualityComparer.cs" /> <Compile Include="Newtonsoft\Linq\JTokenReader.cs" /> <Compile Include="Newtonsoft\Linq\JTokenType.cs" /> <Compile Include="Newtonsoft\Linq\JTokenWriter.cs" /> <Compile Include="Newtonsoft\Linq\JValue.cs" /> <Compile Include="Newtonsoft\Linq\MergeArrayHandling.cs" /> <Compile Include="Newtonsoft\Linq\MergeNullValueHandling.cs" /> <Compile Include="Newtonsoft\MemberSerialization.cs" /> <Compile Include="Newtonsoft\MetadataPropertyHandling.cs" /> <Compile Include="Newtonsoft\MissingMemberHandling.cs" /> <Compile Include="Newtonsoft\NullValueHandling.cs" /> <Compile Include="Newtonsoft\ObjectCreationHandling.cs" /> <Compile Include="Newtonsoft\PreserveReferencesHandling.cs" /> <Compile Include="Newtonsoft\ReferenceLoopHandling.cs" /> <Compile Include="Newtonsoft\Required.cs" /> <Compile Include="Newtonsoft\Schema\Extensions.cs" /> <Compile Include="Newtonsoft\Schema\JsonSchema.cs" /> <Compile Include="Newtonsoft\Schema\JsonSchemaBuilder.cs" /> <Compile Include="Newtonsoft\Schema\JsonSchemaConstants.cs" /> <Compile Include="Newtonsoft\Schema\JsonSchemaException.cs" /> <Compile Include="Newtonsoft\Schema\JsonSchemaGenerator.cs" /> <Compile Include="Newtonsoft\Schema\JsonSchemaModel.cs" /> <Compile Include="Newtonsoft\Schema\JsonSchemaModelBuilder.cs" /> <Compile Include="Newtonsoft\Schema\JsonSchemaNode.cs" /> <Compile Include="Newtonsoft\Schema\JsonSchemaNodeCollection.cs" /> <Compile Include="Newtonsoft\Schema\JsonSchemaResolver.cs" /> <Compile Include="Newtonsoft\Schema\JsonSchemaType.cs" /> <Compile Include="Newtonsoft\Schema\JsonSchemaWriter.cs" /> <Compile Include="Newtonsoft\Schema\UndefinedSchemaIdHandling.cs" /> <Compile Include="Newtonsoft\Schema\ValidationEventArgs.cs" /> <Compile Include="Newtonsoft\Schema\ValidationEventHandler.cs" /> <Compile Include="Newtonsoft\SerializationBinder.cs" /> <Compile Include="Newtonsoft\Serialization\CachedAttributeGetter.cs" /> <Compile Include="Newtonsoft\Serialization\CamelCaseNamingStrategy.cs" /> <Compile Include="Newtonsoft\Serialization\CamelCasePropertyNamesContractResolver.cs" /> <Compile Include="Newtonsoft\Serialization\DefaultContractResolver.cs" /> <Compile Include="Newtonsoft\Serialization\DefaultNamingStrategy.cs" /> <Compile Include="Newtonsoft\Serialization\DefaultReferenceResolver.cs" /> <Compile Include="Newtonsoft\Serialization\DefaultSerializationBinder.cs" /> <Compile Include="Newtonsoft\Serialization\DiagnosticsTraceWriter.cs" /> <Compile Include="Newtonsoft\Serialization\DynamicValueProvider.cs" /> <Compile Include="Newtonsoft\Serialization\ErrorContext.cs" /> <Compile Include="Newtonsoft\Serialization\ErrorEventArgs.cs" /> <Compile Include="Newtonsoft\Serialization\ExpressionValueProvider.cs" /> <Compile Include="Newtonsoft\Serialization\IAttributeProvider.cs" /> <Compile Include="Newtonsoft\Serialization\IContractResolver.cs" /> <Compile Include="Newtonsoft\Serialization\IReferenceResolver.cs" /> <Compile Include="Newtonsoft\Serialization\ITraceWriter.cs" /> <Compile Include="Newtonsoft\Serialization\IValueProvider.cs" /> <Compile Include="Newtonsoft\Serialization\JsonArrayContract.cs" /> <Compile Include="Newtonsoft\Serialization\JsonContainerContract.cs" /> <Compile Include="Newtonsoft\Serialization\JsonContract.cs" /> <Compile Include="Newtonsoft\Serialization\JsonDictionaryContract.cs" /> <Compile Include="Newtonsoft\Serialization\JsonDynamicContract.cs" /> <Compile Include="Newtonsoft\Serialization\JsonFormatterConverter.cs" /> <Compile Include="Newtonsoft\Serialization\JsonISerializableContract.cs" /> <Compile Include="Newtonsoft\Serialization\JsonLinqContract.cs" /> <Compile Include="Newtonsoft\Serialization\JsonObjectContract.cs" /> <Compile Include="Newtonsoft\Serialization\JsonPrimitiveContract.cs" /> <Compile Include="Newtonsoft\Serialization\JsonProperty.cs" /> <Compile Include="Newtonsoft\Serialization\JsonPropertyCollection.cs" /> <Compile Include="Newtonsoft\Serialization\JsonSerializerInternalBase.cs" /> <Compile Include="Newtonsoft\Serialization\JsonSerializerInternalReader.cs" /> <Compile Include="Newtonsoft\Serialization\JsonSerializerInternalWriter.cs" /> <Compile Include="Newtonsoft\Serialization\JsonSerializerProxy.cs" /> <Compile Include="Newtonsoft\Serialization\JsonStringContract.cs" /> <Compile Include="Newtonsoft\Serialization\JsonTypeReflector.cs" /> <Compile Include="Newtonsoft\Serialization\MemoryTraceWriter.cs" /> <Compile Include="Newtonsoft\Serialization\NamingStrategy.cs" /> <Compile Include="Newtonsoft\Serialization\ObjectConstructor.cs" /> <Compile Include="Newtonsoft\Serialization\OnErrorAttribute.cs" /> <Compile Include="Newtonsoft\Serialization\ReflectionAttributeProvider.cs" /> <Compile Include="Newtonsoft\Serialization\ReflectionValueProvider.cs" /> <Compile Include="Newtonsoft\Serialization\SnakeCaseNamingStrategy.cs" /> <Compile Include="Newtonsoft\Serialization\TraceJsonReader.cs" /> <Compile Include="Newtonsoft\Serialization\TraceJsonWriter.cs" /> <Compile Include="Newtonsoft\StringEscapeHandling.cs" /> <Compile Include="Newtonsoft\TraceLevel.cs" /> <Compile Include="Newtonsoft\TypeNameHandling.cs" /> <Compile Include="Newtonsoft\Utilities\Base64Encoder.cs" /> <Compile Include="Newtonsoft\Utilities\BidirectionalDictionary.cs" /> <Compile Include="Newtonsoft\Utilities\CollectionUtils.cs" /> <Compile Include="Newtonsoft\Utilities\CollectionWrapper.cs" /> <Compile Include="Newtonsoft\Utilities\ConvertUtils.cs" /> <Compile Include="Newtonsoft\Utilities\DateTimeParser.cs" /> <Compile Include="Newtonsoft\Utilities\DateTimeUtils.cs" /> <Compile Include="Newtonsoft\Utilities\DictionaryWrapper.cs" /> <Compile Include="Newtonsoft\Utilities\DynamicProxy.cs" /> <Compile Include="Newtonsoft\Utilities\DynamicProxyMetaObject.cs" /> <Compile Include="Newtonsoft\Utilities\DynamicReflectionDelegateFactory.cs" /> <Compile Include="Newtonsoft\Utilities\DynamicUtils.cs" /> <Compile Include="Newtonsoft\Utilities\EnumUtils.cs" /> <Compile Include="Newtonsoft\Utilities\EnumValue.cs" /> <Compile Include="Newtonsoft\Utilities\ExpressionReflectionDelegateFactory.cs" /> <Compile Include="Newtonsoft\Utilities\FSharpUtils.cs" /> <Compile Include="Newtonsoft\Utilities\ILGeneratorExtensions.cs" /> <Compile Include="Newtonsoft\Utilities\ImmutableCollectionsUtils.cs" /> <Compile Include="Newtonsoft\Utilities\JavaScriptUtils.cs" /> <Compile Include="Newtonsoft\Utilities\JsonTokenUtils.cs" /> <Compile Include="Newtonsoft\Utilities\LateBoundReflectionDelegateFactory.cs" /> <Compile Include="Newtonsoft\Utilities\LinqBridge.cs" /> <Compile Include="Newtonsoft\Utilities\MathUtils.cs" /> <Compile Include="Newtonsoft\Utilities\MethodCall.cs" /> <Compile Include="Newtonsoft\Utilities\MiscellaneousUtils.cs" /> <Compile Include="Newtonsoft\Utilities\PropertyNameTable.cs" /> <Compile Include="Newtonsoft\Utilities\ReflectionDelegateFactory.cs" /> <Compile Include="Newtonsoft\Utilities\ReflectionObject.cs" /> <Compile Include="Newtonsoft\Utilities\ReflectionUtils.cs" /> <Compile Include="Newtonsoft\Utilities\StringBuffer.cs" /> <Compile Include="Newtonsoft\Utilities\StringReference.cs" /> <Compile Include="Newtonsoft\Utilities\StringUtils.cs" /> <Compile Include="Newtonsoft\Utilities\ThreadSafeStore.cs" /> <Compile Include="Newtonsoft\Utilities\TypeExtensions.cs" /> <Compile Include="Newtonsoft\Utilities\ValidationUtils.cs" /> <Compile Include="Newtonsoft\WriteState.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <ItemGroup> <None Include="app.config" /> <None Include="packages.config" /> <None Include="Scripts\jquery-2.1.1.min.map" /> </ItemGroup> <ItemGroup> <Content Include="Scripts\jquery-2.1.1.intellisense.js" /> <Content Include="Scripts\jquery-2.1.1.js" /> <Content Include="Scripts\jquery-2.1.1.min.js" /> <Content Include="Scripts\nugetexample.js" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>
{ "pile_set_name": "Github" }
package pkg type Arg interface { Foo() int } type Intf interface { F() Arg }
{ "pile_set_name": "Github" }
WORKSPACE=${WORKSPACE:-$( cd $(dirname $0)/../../.. ; pwd -P )} XBMC_PLATFORM_DIR=ios . $WORKSPACE/tools/buildsteps/defaultenv . $WORKSPACE/tools/buildsteps/$XBMC_PLATFORM_DIR/make-native-depends #clear the build failed file rm -f $WORKSPACE/project/cmake/$FAILED_BUILD_FILENAME ALL_BINARY_ADDONS_BUILT="1" #only build binary addons when requested by env/jenkins if [ "$BUILD_BINARY_ADDONS" == "true" ] then for addon in $BINARY_ADDONS do echo "building $addon" git clean -xffd $WORKSPACE/$BINARY_ADDONS_ROOT/$addon INSTALL_PREFIX="../../../../../build/addons/" cd $WORKSPACE/$BINARY_ADDONS_ROOT/$addon;make -j $BUILDTHREADS V=99 VERBOSE=1 INSTALL_PREFIX="$INSTALL_PREFIX" || ALL_BINARY_ADDONS_BUILT="0" done fi if [ "$ALL_BINARY_ADDONS_BUILT" == "1" ] then tagSuccessFulBuild $WORKSPACE/project/cmake else #mark the build failure in the filesystem but leave jenkins running tagFailedBuild $WORKSPACE/project/cmake fi
{ "pile_set_name": "Github" }
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "butil/hash.h" #include <string> #include <vector> #include <gtest/gtest.h> namespace butil { TEST(HashTest, String) { std::string str; // Empty string (should hash to 0). str = ""; EXPECT_EQ(0u, Hash(str)); // Simple test. str = "hello world"; EXPECT_EQ(2794219650u, Hash(str)); // Change one bit. str = "helmo world"; EXPECT_EQ(1006697176u, Hash(str)); // Insert a null byte. str = "hello world"; str[5] = '\0'; EXPECT_EQ(2319902537u, Hash(str)); // Test that the bytes after the null contribute to the hash. str = "hello worle"; str[5] = '\0'; EXPECT_EQ(553904462u, Hash(str)); // Extremely long string. // Also tests strings with high bit set, and null byte. std::vector<char> long_string_buffer; for (int i = 0; i < 4096; ++i) long_string_buffer.push_back((i % 256) - 128); str.assign(&long_string_buffer.front(), long_string_buffer.size()); EXPECT_EQ(2797962408u, Hash(str)); // All possible lengths (mod 4). Tests separate code paths. Also test with // final byte high bit set (regression test for http://crbug.com/90659). // Note that the 1 and 3 cases have a weird bug where the final byte is // treated as a signed char. It was decided on the above bug discussion to // enshrine that behaviour as "correct" to avoid invalidating existing hashes. // Length mod 4 == 0. str = "hello w\xab"; EXPECT_EQ(615571198u, Hash(str)); // Length mod 4 == 1. str = "hello wo\xab"; EXPECT_EQ(623474296u, Hash(str)); // Length mod 4 == 2. str = "hello wor\xab"; EXPECT_EQ(4278562408u, Hash(str)); // Length mod 4 == 3. str = "hello worl\xab"; EXPECT_EQ(3224633008u, Hash(str)); } TEST(HashTest, CString) { const char* str; // Empty string (should hash to 0). str = ""; EXPECT_EQ(0u, Hash(str, strlen(str))); // Simple test. str = "hello world"; EXPECT_EQ(2794219650u, Hash(str, strlen(str))); // Ensure that it stops reading after the given length, and does not expect a // null byte. str = "hello world; don't read this part"; EXPECT_EQ(2794219650u, Hash(str, strlen("hello world"))); } } // namespace butil
{ "pile_set_name": "Github" }
/* * Copyright 2013 Haiku, Inc. All rights reserved. * Distributed under the terms of the MIT License. * * Authors: * Paweł Dziepak, [email protected] */ #ifndef KERNEL_UTIL_RANDOM_H #define KERNEL_UTIL_RANDOM_H #include <smp.h> #include <SupportDefs.h> #define MAX_FAST_RANDOM_VALUE 0x7fff #define MAX_RANDOM_VALUE 0x7fffffffu #define MAX_SECURE_RANDOM_VALUE 0xffffffffu static const int kFastRandomShift = 15; static const int kRandomShift = 31; static const int kSecureRandomShift = 32; #ifdef __cplusplus extern "C" { #endif unsigned int fast_random_value(void); unsigned int random_value(void); unsigned int secure_random_value(void); #ifdef __cplusplus } #endif #ifdef __cplusplus template<typename T> T fast_get_random() { size_t shift = 0; T random = 0; while (shift < sizeof(T) * 8) { random |= (T)fast_random_value() << shift; shift += kFastRandomShift; } return random; } template<typename T> T get_random() { size_t shift = 0; T random = 0; while (shift < sizeof(T) * 8) { random |= (T)random_value() << shift; shift += kRandomShift; } return random; } template<typename T> T secure_get_random() { size_t shift = 0; T random = 0; while (shift < sizeof(T) * 8) { random |= (T)secure_random_value() << shift; shift += kSecureRandomShift; } return random; } #endif // __cplusplus #endif // KERNEL_UTIL_RANDOM_H
{ "pile_set_name": "Github" }
<ion-nav [root]="rootPage"></ion-nav>
{ "pile_set_name": "Github" }
ManifestFileVersion: 0 CRC: 1553149540 Hashes: AssetFileHash: serializedVersion: 2 Hash: dbef744f77c814ae3f1b113918af7630 TypeTreeHash: serializedVersion: 2 Hash: 3f7d0c5e0986ec71841622bcb2f9be1c HashAppended: 0 ClassTypes: - Class: 83 Script: {instanceID: 0} Assets: - Assets/Resources.KingTexas/BuildAssetBundleFromSingle/Audio/CountDownGo.mp3 Dependencies: []
{ "pile_set_name": "Github" }
--TEST-- similar_text(), error tests for missing parameters --CREDITS-- Mats Lindh <mats at lindh.no> #Testfest php.no --FILE-- <?php /* Prototype : proto int similar_text(string str1, string str2 [, float percent]) * Description: Calculates the similarity between two strings * Source code: ext/standard/string.c */ $extra_arg = 10; echo "\n-- Testing similar_text() function with more than expected no. of arguments --\n"; similar_text("abc", "def", $percent, $extra_arg); echo "\n-- Testing similar_text() function with less than expected no. of arguments --\n"; similar_text("abc"); ?> ===DONE=== --EXPECTF-- -- Testing similar_text() function with more than expected no. of arguments -- Warning: similar_text() expects at most 3 parameters, 4 given in %s on line %d -- Testing similar_text() function with less than expected no. of arguments -- Warning: similar_text() expects at least 2 parameters, 1 given in %s on line %d ===DONE===
{ "pile_set_name": "Github" }
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package sts const ( // ErrCodeExpiredTokenException for service response error code // "ExpiredTokenException". // // The web identity token that was passed is expired or is not valid. Get a // new identity token from the identity provider and then retry the request. ErrCodeExpiredTokenException = "ExpiredTokenException" // ErrCodeIDPCommunicationErrorException for service response error code // "IDPCommunicationError". // // The request could not be fulfilled because the identity provider (IDP) that // was asked to verify the incoming identity token could not be reached. This // is often a transient error caused by network conditions. Retry the request // a limited number of times so that you don't exceed the request rate. If the // error persists, the identity provider might be down or not responding. ErrCodeIDPCommunicationErrorException = "IDPCommunicationError" // ErrCodeIDPRejectedClaimException for service response error code // "IDPRejectedClaim". // // The identity provider (IdP) reported that authentication failed. This might // be because the claim is invalid. // // If this error is returned for the AssumeRoleWithWebIdentity operation, it // can also mean that the claim has expired or has been explicitly revoked. ErrCodeIDPRejectedClaimException = "IDPRejectedClaim" // ErrCodeInvalidAuthorizationMessageException for service response error code // "InvalidAuthorizationMessageException". // // The error returned if the message passed to DecodeAuthorizationMessage was // invalid. This can happen if the token contains invalid characters, such as // linebreaks. ErrCodeInvalidAuthorizationMessageException = "InvalidAuthorizationMessageException" // ErrCodeInvalidIdentityTokenException for service response error code // "InvalidIdentityToken". // // The web identity token that was passed could not be validated by AWS. Get // a new identity token from the identity provider and then retry the request. ErrCodeInvalidIdentityTokenException = "InvalidIdentityToken" // ErrCodeMalformedPolicyDocumentException for service response error code // "MalformedPolicyDocument". // // The request was rejected because the policy document was malformed. The error // message describes the specific error. ErrCodeMalformedPolicyDocumentException = "MalformedPolicyDocument" // ErrCodePackedPolicyTooLargeException for service response error code // "PackedPolicyTooLarge". // // The request was rejected because the total packed size of the session policies // and session tags combined was too large. An AWS conversion compresses the // session policy document, session policy ARNs, and session tags into a packed // binary format that has a separate limit. The error message indicates by percentage // how close the policies and tags are to the upper size limit. For more information, // see Passing Session Tags in STS (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html) // in the IAM User Guide. // // You could receive this error even though you meet other defined session policy // and session tag limits. For more information, see IAM and STS Entity Character // Limits (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) // in the IAM User Guide. ErrCodePackedPolicyTooLargeException = "PackedPolicyTooLarge" // ErrCodeRegionDisabledException for service response error code // "RegionDisabledException". // // STS is not activated in the requested region for the account that is being // asked to generate credentials. The account administrator must use the IAM // console to activate STS in that region. For more information, see Activating // and Deactivating AWS STS in an AWS Region (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) // in the IAM User Guide. ErrCodeRegionDisabledException = "RegionDisabledException" )
{ "pile_set_name": "Github" }
# -*- coding: utf-8 -*- # # Copyright (c) 2013 the BabelFish authors. All rights reserved. # Use of this source code is governed by the 3-clause BSD license # that can be found in the LICENSE file. # from __future__ import unicode_literals from . import LanguageConverter from ..exceptions import LanguageConvertError from ..language import LANGUAGE_MATRIX class LanguageTypeConverter(LanguageConverter): FULLNAME = {'A': 'ancient', 'C': 'constructed', 'E': 'extinct', 'H': 'historical', 'L': 'living', 'S': 'special'} SYMBOLS = {} for iso_language in LANGUAGE_MATRIX: SYMBOLS[iso_language.alpha3] = iso_language.type codes = set(SYMBOLS.values()) def convert(self, alpha3, country=None, script=None): if self.SYMBOLS[alpha3] in self.FULLNAME: return self.FULLNAME[self.SYMBOLS[alpha3]] raise LanguageConvertError(alpha3, country, script)
{ "pile_set_name": "Github" }
<?php /* * This file is part of the Monolog package. * * (c) Jordi Boggiano <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Monolog\Handler; use Monolog\Formatter\FormatterInterface; /** * Sampling handler * * A sampled event stream can be useful for logging high frequency events in * a production environment where you only need an idea of what is happening * and are not concerned with capturing every occurrence. Since the decision to * handle or not handle a particular event is determined randomly, the * resulting sampled log is not guaranteed to contain 1/N of the events that * occurred in the application, but based on the Law of large numbers, it will * tend to be close to this ratio with a large number of attempts. * * @author Bryan Davis <[email protected]> * @author Kunal Mehta <[email protected]> */ class SamplingHandler extends AbstractHandler { /** * @var callable|HandlerInterface $handler */ protected $handler; /** * @var int $factor */ protected $factor; /** * @param callable|HandlerInterface $handler Handler or factory callable($record|null, $samplingHandler). * @param int $factor Sample factor */ public function __construct($handler, $factor) { parent::__construct(); $this->handler = $handler; $this->factor = $factor; if (!$this->handler instanceof HandlerInterface && !is_callable($this->handler)) { throw new \RuntimeException("The given handler (".json_encode($this->handler).") is not a callable nor a Monolog\Handler\HandlerInterface object"); } } public function isHandling(array $record) { return $this->getHandler($record)->isHandling($record); } public function handle(array $record) { if ($this->isHandling($record) && mt_rand(1, $this->factor) === 1) { if ($this->processors) { foreach ($this->processors as $processor) { $record = call_user_func($processor, $record); } } $this->getHandler($record)->handle($record); } return false === $this->bubble; } /** * Return the nested handler * * If the handler was provided as a factory callable, this will trigger the handler's instantiation. * * @return HandlerInterface */ public function getHandler(array $record = null) { if (!$this->handler instanceof HandlerInterface) { $this->handler = call_user_func($this->handler, $record, $this); if (!$this->handler instanceof HandlerInterface) { throw new \RuntimeException("The factory callable should return a HandlerInterface"); } } return $this->handler; } /** * {@inheritdoc} */ public function setFormatter(FormatterInterface $formatter) { $this->getHandler()->setFormatter($formatter); return $this; } /** * {@inheritdoc} */ public function getFormatter() { return $this->getHandler()->getFormatter(); } }
{ "pile_set_name": "Github" }
# -*- coding: utf-8 -*- # Self-tests for the user-friendly Crypto.Random interface # # Written in 2013 by Dwayne C. Litzenberger <[email protected]> # # =================================================================== # The contents of this file are dedicated to the public domain. To # the extent that dedication to the public domain is not available, # everyone is granted a worldwide, perpetual, royalty-free, # non-exclusive license to exercise all rights associated with the # contents of this file for any purpose whatsoever. # No rights are reserved. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # =================================================================== """Self-test suite for generic Crypto.Random stuff """ from __future__ import nested_scopes __revision__ = "$Id$" import binascii import pprint import unittest import os import time import sys if sys.version_info[0] == 2 and sys.version_info[1] == 1: from Crypto.Util.py21compat import * from Crypto.Util.py3compat import * try: import multiprocessing except ImportError: multiprocessing = None import Crypto.Random._UserFriendlyRNG import Crypto.Random.random class RNGForkTest(unittest.TestCase): def _get_reseed_count(self): """ Get `FortunaAccumulator.reseed_count`, the global count of the number of times that the PRNG has been reseeded. """ rng_singleton = Crypto.Random._UserFriendlyRNG._get_singleton() rng_singleton._lock.acquire() try: return rng_singleton._fa.reseed_count finally: rng_singleton._lock.release() def runTest(self): # Regression test for CVE-2013-1445. We had a bug where, under the # right conditions, two processes might see the same random sequence. if sys.platform.startswith('win'): # windows can't fork assert not hasattr(os, 'fork') # ... right? return # Wait 150 ms so that we don't trigger the rate-limit prematurely. time.sleep(0.15) reseed_count_before = self._get_reseed_count() # One or both of these calls together should trigger a reseed right here. Crypto.Random._UserFriendlyRNG._get_singleton().reinit() Crypto.Random.get_random_bytes(1) reseed_count_after = self._get_reseed_count() self.assertNotEqual(reseed_count_before, reseed_count_after) # sanity check: test should reseed parent before forking rfiles = [] for i in range(10): rfd, wfd = os.pipe() if os.fork() == 0: # child os.close(rfd) f = os.fdopen(wfd, "wb") Crypto.Random.atfork() data = Crypto.Random.get_random_bytes(16) f.write(data) f.close() os._exit(0) # parent os.close(wfd) rfiles.append(os.fdopen(rfd, "rb")) results = [] results_dict = {} for f in rfiles: data = binascii.hexlify(f.read()) results.append(data) results_dict[data] = 1 f.close() if len(results) != len(results_dict.keys()): raise AssertionError("RNG output duplicated across fork():\n%s" % (pprint.pformat(results))) # For RNGMultiprocessingForkTest def _task_main(q): a = Crypto.Random.get_random_bytes(16) time.sleep(0.1) # wait 100 ms b = Crypto.Random.get_random_bytes(16) q.put(binascii.b2a_hex(a)) q.put(binascii.b2a_hex(b)) q.put(None) # Wait for acknowledgment class RNGMultiprocessingForkTest(unittest.TestCase): def runTest(self): # Another regression test for CVE-2013-1445. This is basically the # same as RNGForkTest, but less compatible with old versions of Python, # and a little easier to read. n_procs = 5 manager = multiprocessing.Manager() queues = [manager.Queue(1) for i in range(n_procs)] # Reseed the pool time.sleep(0.15) Crypto.Random._UserFriendlyRNG._get_singleton().reinit() Crypto.Random.get_random_bytes(1) # Start the child processes pool = multiprocessing.Pool(processes=n_procs, initializer=Crypto.Random.atfork) map_result = pool.map_async(_task_main, queues) # Get the results, ensuring that no pool processes are reused. aa = [queues[i].get(30) for i in range(n_procs)] bb = [queues[i].get(30) for i in range(n_procs)] res = list(zip(aa, bb)) # Shut down the pool map_result.get(30) pool.close() pool.join() # Check that the results are unique if len(set(aa)) != len(aa) or len(set(res)) != len(res): raise AssertionError("RNG output duplicated across fork():\n%s" % (pprint.pformat(res),)) def get_tests(config={}): tests = [] tests += [RNGForkTest()] if multiprocessing is not None: tests += [RNGMultiprocessingForkTest()] return tests if __name__ == '__main__': suite = lambda: unittest.TestSuite(get_tests()) unittest.main(defaultTest='suite') # vim:set ts=4 sw=4 sts=4 expandtab:
{ "pile_set_name": "Github" }
/* * Copyright (C) Igor Sysoev */ #include <ngx_config.h> #include <ngx_core.h> #include <ngx_http.h> static ngx_int_t ngx_http_static_handler(ngx_http_request_t *r); static ngx_int_t ngx_http_static_init(ngx_conf_t *cf); ngx_http_module_t ngx_http_static_module_ctx = { NULL, /* preconfiguration */ ngx_http_static_init, /* postconfiguration */ NULL, /* create main configuration */ NULL, /* init main configuration */ NULL, /* create server configuration */ NULL, /* merge server configuration */ NULL, /* create location configuration */ NULL /* merge location configuration */ }; ngx_module_t ngx_http_static_module = { NGX_MODULE_V1, &ngx_http_static_module_ctx, /* module context */ NULL, /* module directives */ NGX_HTTP_MODULE, /* module type */ NULL, /* init master */ NULL, /* init module */ NULL, /* init process */ NULL, /* init thread */ NULL, /* exit thread */ NULL, /* exit process */ NULL, /* exit master */ NGX_MODULE_V1_PADDING }; static ngx_int_t ngx_http_static_handler(ngx_http_request_t *r) { u_char *last, *location; size_t root, len; ngx_str_t path; ngx_int_t rc; ngx_uint_t level; ngx_log_t *log; ngx_buf_t *b; ngx_chain_t out; ngx_open_file_info_t of; ngx_http_core_loc_conf_t *clcf; if (!(r->method & (NGX_HTTP_GET|NGX_HTTP_HEAD|NGX_HTTP_POST))) { return NGX_HTTP_NOT_ALLOWED; } if (r->uri.data[r->uri.len - 1] == '/') { return NGX_DECLINED; } log = r->connection->log; /* * ngx_http_map_uri_to_path() allocates memory for terminating '\0' * so we do not need to reserve memory for '/' for possible redirect */ last = ngx_http_map_uri_to_path(r, &path, &root, 0); if (last == NULL) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } path.len = last - path.data; ngx_log_debug1(NGX_LOG_DEBUG_HTTP, log, 0, "http filename: \"%s\"", path.data); clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module); ngx_memzero(&of, sizeof(ngx_open_file_info_t)); of.read_ahead = clcf->read_ahead; of.directio = clcf->directio; of.valid = clcf->open_file_cache_valid; of.min_uses = clcf->open_file_cache_min_uses; of.errors = clcf->open_file_cache_errors; of.events = clcf->open_file_cache_events; if (ngx_open_cached_file(clcf->open_file_cache, &path, &of, r->pool) != NGX_OK) { switch (of.err) { case 0: return NGX_HTTP_INTERNAL_SERVER_ERROR; case NGX_ENOENT: case NGX_ENOTDIR: case NGX_ENAMETOOLONG: level = NGX_LOG_ERR; rc = NGX_HTTP_NOT_FOUND; break; case NGX_EACCES: level = NGX_LOG_ERR; rc = NGX_HTTP_FORBIDDEN; break; default: level = NGX_LOG_CRIT; rc = NGX_HTTP_INTERNAL_SERVER_ERROR; break; } if (rc != NGX_HTTP_NOT_FOUND || clcf->log_not_found) { ngx_log_error(level, log, of.err, "%s \"%s\" failed", of.failed, path.data); } return rc; } r->root_tested = !r->error_page; ngx_log_debug1(NGX_LOG_DEBUG_HTTP, log, 0, "http static fd: %d", of.fd); if (of.is_dir) { ngx_log_debug0(NGX_LOG_DEBUG_HTTP, log, 0, "http dir"); r->headers_out.location = ngx_palloc(r->pool, sizeof(ngx_table_elt_t)); if (r->headers_out.location == NULL) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } len = r->uri.len + 1; if (!clcf->alias && clcf->root_lengths == NULL && r->args.len == 0) { location = path.data + clcf->root.len; *last = '/'; } else { if (r->args.len) { len += r->args.len + 1; } location = ngx_pnalloc(r->pool, len); if (location == NULL) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } last = ngx_copy(location, r->uri.data, r->uri.len); *last = '/'; if (r->args.len) { *++last = '?'; ngx_memcpy(++last, r->args.data, r->args.len); } } /* * we do not need to set the r->headers_out.location->hash and * r->headers_out.location->key fields */ r->headers_out.location->value.len = len; r->headers_out.location->value.data = location; return NGX_HTTP_MOVED_PERMANENTLY; } #if !(NGX_WIN32) /* the not regular files are probably Unix specific */ if (!of.is_file) { ngx_log_error(NGX_LOG_CRIT, log, 0, "\"%s\" is not a regular file", path.data); return NGX_HTTP_NOT_FOUND; } #endif if (r->method & NGX_HTTP_POST) { return NGX_HTTP_NOT_ALLOWED; } rc = ngx_http_discard_request_body(r); if (rc != NGX_OK) { return rc; } log->action = "sending response to client"; r->headers_out.status = NGX_HTTP_OK; r->headers_out.content_length_n = of.size; r->headers_out.last_modified_time = of.mtime; if (ngx_http_set_content_type(r) != NGX_OK) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } if (r != r->main && of.size == 0) { return ngx_http_send_header(r); } r->allow_ranges = 1; /* we need to allocate all before the header would be sent */ b = ngx_pcalloc(r->pool, sizeof(ngx_buf_t)); if (b == NULL) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } b->file = ngx_pcalloc(r->pool, sizeof(ngx_file_t)); if (b->file == NULL) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } rc = ngx_http_send_header(r); if (rc == NGX_ERROR || rc > NGX_OK || r->header_only) { return rc; } b->file_pos = 0; b->file_last = of.size; b->in_file = b->file_last ? 1: 0; b->last_buf = (r == r->main) ? 1: 0; b->last_in_chain = 1; b->file->fd = of.fd; b->file->name = path; b->file->log = log; b->file->directio = of.is_directio; out.buf = b; out.next = NULL; return ngx_http_output_filter(r, &out); } static ngx_int_t ngx_http_static_init(ngx_conf_t *cf) { ngx_http_handler_pt *h; ngx_http_core_main_conf_t *cmcf; cmcf = ngx_http_conf_get_module_main_conf(cf, ngx_http_core_module); h = ngx_array_push(&cmcf->phases[NGX_HTTP_CONTENT_PHASE].handlers); if (h == NULL) { return NGX_ERROR; } *h = ngx_http_static_handler; return NGX_OK; }
{ "pile_set_name": "Github" }
// // Copyright (c) 2012 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // VertexDeclarationCache.cpp: Implements a helper class to construct and cache vertex declarations. #include "libANGLE/renderer/d3d/d3d9/VertexDeclarationCache.h" #include "libANGLE/VertexAttribute.h" #include "libANGLE/formatutils.h" #include "libANGLE/renderer/d3d/ProgramD3D.h" #include "libANGLE/renderer/d3d/d3d9/VertexBuffer9.h" #include "libANGLE/renderer/d3d/d3d9/formatutils9.h" namespace rx { VertexDeclarationCache::VertexDeclarationCache() : mMaxLru(0) { for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++) { mVertexDeclCache[i].vertexDeclaration = NULL; mVertexDeclCache[i].lruCount = 0; } for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++) { mAppliedVBs[i].serial = 0; } mLastSetVDecl = NULL; mInstancingEnabled = true; } VertexDeclarationCache::~VertexDeclarationCache() { for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++) { SafeRelease(mVertexDeclCache[i].vertexDeclaration); } } gl::Error VertexDeclarationCache::applyDeclaration( IDirect3DDevice9 *device, const std::vector<TranslatedAttribute> &attributes, gl::Program *program, GLint start, GLsizei instances, GLsizei *repeatDraw) { ASSERT(gl::MAX_VERTEX_ATTRIBS >= attributes.size()); *repeatDraw = 1; const size_t invalidAttribIndex = attributes.size(); size_t indexedAttribute = invalidAttribIndex; size_t instancedAttribute = invalidAttribIndex; if (instances == 0) { for (size_t i = 0; i < attributes.size(); ++i) { if (attributes[i].divisor != 0) { // If a divisor is set, it still applies even if an instanced draw was not used, so treat // as a single-instance draw. instances = 1; break; } } } if (instances > 0) { // Find an indexed attribute to be mapped to D3D stream 0 for (size_t i = 0; i < attributes.size(); i++) { if (attributes[i].active) { if (indexedAttribute == invalidAttribIndex && attributes[i].divisor == 0) { indexedAttribute = i; } else if (instancedAttribute == invalidAttribIndex && attributes[i].divisor != 0) { instancedAttribute = i; } if (indexedAttribute != invalidAttribIndex && instancedAttribute != invalidAttribIndex) break; // Found both an indexed and instanced attribute } } // The validation layer checks that there is at least one active attribute with a zero divisor as per // the GL_ANGLE_instanced_arrays spec. ASSERT(indexedAttribute != invalidAttribIndex); } D3DCAPS9 caps; device->GetDeviceCaps(&caps); D3DVERTEXELEMENT9 elements[gl::MAX_VERTEX_ATTRIBS + 1]; D3DVERTEXELEMENT9 *element = &elements[0]; ProgramD3D *programD3D = GetImplAs<ProgramD3D>(program); const auto &semanticIndexes = programD3D->getAttribLocationToD3DSemantics(); for (size_t i = 0; i < attributes.size(); i++) { if (attributes[i].active) { // Directly binding the storage buffer is not supported for d3d9 ASSERT(attributes[i].storage == NULL); int stream = static_cast<int>(i); if (instances > 0) { // Due to a bug on ATI cards we can't enable instancing when none of the attributes are instanced. if (instancedAttribute == invalidAttribIndex) { *repeatDraw = instances; } else { if (i == indexedAttribute) { stream = 0; } else if (i == 0) { stream = static_cast<int>(indexedAttribute); } UINT frequency = 1; if (attributes[i].divisor == 0) { frequency = D3DSTREAMSOURCE_INDEXEDDATA | instances; } else { frequency = D3DSTREAMSOURCE_INSTANCEDATA | attributes[i].divisor; } device->SetStreamSourceFreq(stream, frequency); mInstancingEnabled = true; } } VertexBuffer9 *vertexBuffer = GetAs<VertexBuffer9>(attributes[i].vertexBuffer.get()); unsigned int offset = 0; ANGLE_TRY_RESULT(attributes[i].computeOffset(start), offset); if (mAppliedVBs[stream].serial != attributes[i].serial || mAppliedVBs[stream].stride != attributes[i].stride || mAppliedVBs[stream].offset != offset) { device->SetStreamSource(stream, vertexBuffer->getBuffer(), offset, attributes[i].stride); mAppliedVBs[stream].serial = attributes[i].serial; mAppliedVBs[stream].stride = attributes[i].stride; mAppliedVBs[stream].offset = offset; } gl::VertexFormatType vertexformatType = gl::GetVertexFormatType(*attributes[i].attribute, GL_FLOAT); const d3d9::VertexFormat &d3d9VertexInfo = d3d9::GetVertexFormatInfo(caps.DeclTypes, vertexformatType); element->Stream = static_cast<WORD>(stream); element->Offset = 0; element->Type = static_cast<BYTE>(d3d9VertexInfo.nativeFormat); element->Method = D3DDECLMETHOD_DEFAULT; element->Usage = D3DDECLUSAGE_TEXCOORD; element->UsageIndex = static_cast<BYTE>(semanticIndexes[i]); element++; } } if (instances == 0 || instancedAttribute == invalidAttribIndex) { if (mInstancingEnabled) { for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++) { device->SetStreamSourceFreq(i, 1); } mInstancingEnabled = false; } } static const D3DVERTEXELEMENT9 end = D3DDECL_END(); *(element++) = end; for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++) { VertexDeclCacheEntry *entry = &mVertexDeclCache[i]; if (memcmp(entry->cachedElements, elements, (element - elements) * sizeof(D3DVERTEXELEMENT9)) == 0 && entry->vertexDeclaration) { entry->lruCount = ++mMaxLru; if(entry->vertexDeclaration != mLastSetVDecl) { device->SetVertexDeclaration(entry->vertexDeclaration); mLastSetVDecl = entry->vertexDeclaration; } return gl::Error(GL_NO_ERROR); } } VertexDeclCacheEntry *lastCache = mVertexDeclCache; for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++) { if (mVertexDeclCache[i].lruCount < lastCache->lruCount) { lastCache = &mVertexDeclCache[i]; } } if (lastCache->vertexDeclaration != NULL) { SafeRelease(lastCache->vertexDeclaration); // mLastSetVDecl is set to the replacement, so we don't have to worry // about it. } memcpy(lastCache->cachedElements, elements, (element - elements) * sizeof(D3DVERTEXELEMENT9)); HRESULT result = device->CreateVertexDeclaration(elements, &lastCache->vertexDeclaration); if (FAILED(result)) { return gl::Error(GL_OUT_OF_MEMORY, "Failed to create internal vertex declaration, result: 0x%X.", result); } device->SetVertexDeclaration(lastCache->vertexDeclaration); mLastSetVDecl = lastCache->vertexDeclaration; lastCache->lruCount = ++mMaxLru; return gl::Error(GL_NO_ERROR); } void VertexDeclarationCache::markStateDirty() { for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++) { mAppliedVBs[i].serial = 0; } mLastSetVDecl = NULL; mInstancingEnabled = true; // Forces it to be disabled when not used } }
{ "pile_set_name": "Github" }
<?php namespace Oro\Bundle\ApiBundle\Util; /** * Provides a set of static methods to simplify working with "{@inheritdoc}" * and "{@inheritdoc:description}" placeholders in descriptions of API resources. */ class InheritDocUtil { /** The inheritdoc placeholder */ private const PLACEHOLDER = '{@inheritdoc}'; /** The placeholder for the entity or field description */ private const PLACEHOLDER_DESCRIPTION = '{@inheritdoc:description}'; /** * Checks whether the given string contains the inheritdoc placeholder. * * @param string|null $text * * @return bool */ public static function hasInheritDoc(?string $text): bool { return $text && false !== strpos($text, self::PLACEHOLDER); } /** * Replaces the inheritdoc placeholder in $text with $inheritText. * * @param string $text * @param string|null $inheritText * * @return string */ public static function replaceInheritDoc(string $text, ?string $inheritText): string { return self::doReplaceInheritDoc(self::PLACEHOLDER, $text, $inheritText); } /** * Checks whether the given string contains the placeholder for the entity or field description. * * @param string|null $text * * @return bool */ public static function hasDescriptionInheritDoc(?string $text): bool { return $text && false !== strpos($text, self::PLACEHOLDER_DESCRIPTION); } /** * Replaces the placeholder for the entity or field description inheritdoc in $text with $inheritText. * * @param string $text * @param string|null $inheritText * * @return string */ public static function replaceDescriptionInheritDoc(string $text, ?string $inheritText): string { return self::doReplaceInheritDoc(self::PLACEHOLDER_DESCRIPTION, $text, $inheritText); } /** * Replaces the given inheritdoc placeholder in $text with $inheritText. * * @param string $placeholder * @param string $text * @param string|null $inheritText * * @return string */ private static function doReplaceInheritDoc(string $placeholder, string $text, ?string $inheritText): string { $inheritText = (string)$inheritText; // try avoid paragraph tag inside another paragraph tag, e.g.: // - <p><p>inherited text</p></p> // - <p><p>inherited</p><p>text</p></p> // - <p>some <p>inherited</p> text</p> // try to avoid paragraph tag inside inlining inheritdoc, // e.g.if text is "text {@inheritdoc}" and injected text is "<p>injected</p>", // the result should be "text injected", not "text <p>injected</p>" $placeholderWithParagraph = '<p>' . $placeholder . '</p>'; if (false !== strpos($text, $placeholderWithParagraph)) { if (self::hasParagraphTag($inheritText)) { return str_replace($placeholderWithParagraph, $inheritText, $text); } } elseif (self::isEnclosedByParagraphTag($inheritText)) { return str_replace($placeholder, self::removeEnclosedParagraphTag($inheritText), $text); } return str_replace($placeholder, $inheritText, $text); } /** * @param string $text * * @return bool */ private static function hasParagraphTag(string $text): bool { return false !== strpos($text, '<p>'); } /** * @param string $text * * @return bool */ private static function isEnclosedByParagraphTag(string $text): bool { if (\strlen($text) < 7 || false === strpos($text, '</p>', -4) || 0 !== strncmp($text, '<p>', 3)) { return false; } return false === strpos($text, '<p>', 3); } /** * @param string $text * * @return string */ private static function removeEnclosedParagraphTag(string $text): string { return substr($text, 3, -4); } }
{ "pile_set_name": "Github" }
//===--- RAIIObjectsForParser.h - RAII helpers for the parser ---*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines and implements the some simple RAII objects that are used // by the parser to manage bits in recursion. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_LIB_PARSE_RAIIOBJECTSFORPARSER_H #define LLVM_CLANG_LIB_PARSE_RAIIOBJECTSFORPARSER_H #include "clang/Parse/ParseDiagnostic.h" #include "clang/Parse/Parser.h" #include "clang/Sema/DelayedDiagnostic.h" #include "clang/Sema/ParsedTemplate.h" #include "clang/Sema/Sema.h" namespace clang { // TODO: move ParsingClassDefinition here. // TODO: move TentativeParsingAction here. /// A RAII object used to temporarily suppress access-like /// checking. Access-like checks are those associated with /// controlling the use of a declaration, like C++ access control /// errors and deprecation warnings. They are contextually /// dependent, in that they can only be resolved with full /// information about what's being declared. They are also /// suppressed in certain contexts, like the template arguments of /// an explicit instantiation. However, those suppression contexts /// cannot necessarily be fully determined in advance; for /// example, something starting like this: /// template <> class std::vector<A::PrivateType> /// might be the entirety of an explicit instantiation: /// template <> class std::vector<A::PrivateType>; /// or just an elaborated type specifier: /// template <> class std::vector<A::PrivateType> make_vector<>(); /// Therefore this class collects all the diagnostics and permits /// them to be re-delayed in a new context. class SuppressAccessChecks { Sema &S; sema::DelayedDiagnosticPool DiagnosticPool; Sema::ParsingDeclState State; bool Active; public: /// Begin suppressing access-like checks SuppressAccessChecks(Parser &P, bool activate = true) : S(P.getActions()), DiagnosticPool(nullptr) { if (activate) { State = S.PushParsingDeclaration(DiagnosticPool); Active = true; } else { Active = false; } } SuppressAccessChecks(SuppressAccessChecks &&Other) : S(Other.S), DiagnosticPool(std::move(Other.DiagnosticPool)), State(Other.State), Active(Other.Active) { Other.Active = false; } void operator=(SuppressAccessChecks &&Other) = delete; void done() { assert(Active && "trying to end an inactive suppression"); S.PopParsingDeclaration(State, nullptr); Active = false; } void redelay() { assert(!Active && "redelaying without having ended first"); if (!DiagnosticPool.pool_empty()) S.redelayDiagnostics(DiagnosticPool); assert(DiagnosticPool.pool_empty()); } ~SuppressAccessChecks() { if (Active) done(); } }; /// RAII object used to inform the actions that we're /// currently parsing a declaration. This is active when parsing a /// variable's initializer, but not when parsing the body of a /// class or function definition. class ParsingDeclRAIIObject { Sema &Actions; sema::DelayedDiagnosticPool DiagnosticPool; Sema::ParsingDeclState State; bool Popped; ParsingDeclRAIIObject(const ParsingDeclRAIIObject &) = delete; void operator=(const ParsingDeclRAIIObject &) = delete; public: enum NoParent_t { NoParent }; ParsingDeclRAIIObject(Parser &P, NoParent_t _) : Actions(P.getActions()), DiagnosticPool(nullptr) { push(); } /// Creates a RAII object whose pool is optionally parented by another. ParsingDeclRAIIObject(Parser &P, const sema::DelayedDiagnosticPool *parentPool) : Actions(P.getActions()), DiagnosticPool(parentPool) { push(); } /// Creates a RAII object and, optionally, initialize its /// diagnostics pool by stealing the diagnostics from another /// RAII object (which is assumed to be the current top pool). ParsingDeclRAIIObject(Parser &P, ParsingDeclRAIIObject *other) : Actions(P.getActions()), DiagnosticPool(other ? other->DiagnosticPool.getParent() : nullptr) { if (other) { DiagnosticPool.steal(other->DiagnosticPool); other->abort(); } push(); } ~ParsingDeclRAIIObject() { abort(); } sema::DelayedDiagnosticPool &getDelayedDiagnosticPool() { return DiagnosticPool; } const sema::DelayedDiagnosticPool &getDelayedDiagnosticPool() const { return DiagnosticPool; } /// Resets the RAII object for a new declaration. void reset() { abort(); push(); } /// Signals that the context was completed without an appropriate /// declaration being parsed. void abort() { pop(nullptr); } void complete(Decl *D) { assert(!Popped && "ParsingDeclaration has already been popped!"); pop(D); } /// Unregister this object from Sema, but remember all the /// diagnostics that were emitted into it. void abortAndRemember() { pop(nullptr); } private: void push() { State = Actions.PushParsingDeclaration(DiagnosticPool); Popped = false; } void pop(Decl *D) { if (!Popped) { Actions.PopParsingDeclaration(State, D); Popped = true; } } }; /// A class for parsing a DeclSpec. class ParsingDeclSpec : public DeclSpec { ParsingDeclRAIIObject ParsingRAII; public: ParsingDeclSpec(Parser &P) : DeclSpec(P.getAttrFactory()), ParsingRAII(P, ParsingDeclRAIIObject::NoParent) {} ParsingDeclSpec(Parser &P, ParsingDeclRAIIObject *RAII) : DeclSpec(P.getAttrFactory()), ParsingRAII(P, RAII) {} const sema::DelayedDiagnosticPool &getDelayedDiagnosticPool() const { return ParsingRAII.getDelayedDiagnosticPool(); } void complete(Decl *D) { ParsingRAII.complete(D); } void abort() { ParsingRAII.abort(); } }; /// A class for parsing a declarator. class ParsingDeclarator : public Declarator { ParsingDeclRAIIObject ParsingRAII; public: ParsingDeclarator(Parser &P, const ParsingDeclSpec &DS, DeclaratorContext C) : Declarator(DS, C), ParsingRAII(P, &DS.getDelayedDiagnosticPool()) { } const ParsingDeclSpec &getDeclSpec() const { return static_cast<const ParsingDeclSpec&>(Declarator::getDeclSpec()); } ParsingDeclSpec &getMutableDeclSpec() const { return const_cast<ParsingDeclSpec&>(getDeclSpec()); } void clear() { Declarator::clear(); ParsingRAII.reset(); } void complete(Decl *D) { ParsingRAII.complete(D); } }; /// A class for parsing a field declarator. class ParsingFieldDeclarator : public FieldDeclarator { ParsingDeclRAIIObject ParsingRAII; public: ParsingFieldDeclarator(Parser &P, const ParsingDeclSpec &DS) : FieldDeclarator(DS), ParsingRAII(P, &DS.getDelayedDiagnosticPool()) { } const ParsingDeclSpec &getDeclSpec() const { return static_cast<const ParsingDeclSpec&>(D.getDeclSpec()); } ParsingDeclSpec &getMutableDeclSpec() const { return const_cast<ParsingDeclSpec&>(getDeclSpec()); } void complete(Decl *D) { ParsingRAII.complete(D); } }; /// ExtensionRAIIObject - This saves the state of extension warnings when /// constructed and disables them. When destructed, it restores them back to /// the way they used to be. This is used to handle __extension__ in the /// parser. class ExtensionRAIIObject { ExtensionRAIIObject(const ExtensionRAIIObject &) = delete; void operator=(const ExtensionRAIIObject &) = delete; DiagnosticsEngine &Diags; public: ExtensionRAIIObject(DiagnosticsEngine &diags) : Diags(diags) { Diags.IncrementAllExtensionsSilenced(); } ~ExtensionRAIIObject() { Diags.DecrementAllExtensionsSilenced(); } }; /// ColonProtectionRAIIObject - This sets the Parser::ColonIsSacred bool and /// restores it when destroyed. This says that "foo:" should not be /// considered a possible typo for "foo::" for error recovery purposes. class ColonProtectionRAIIObject { Parser &P; bool OldVal; public: ColonProtectionRAIIObject(Parser &p, bool Value = true) : P(p), OldVal(P.ColonIsSacred) { P.ColonIsSacred = Value; } /// restore - This can be used to restore the state early, before the dtor /// is run. void restore() { P.ColonIsSacred = OldVal; } ~ColonProtectionRAIIObject() { restore(); } }; /// RAII object that makes '>' behave either as an operator /// or as the closing angle bracket for a template argument list. class GreaterThanIsOperatorScope { bool &GreaterThanIsOperator; bool OldGreaterThanIsOperator; public: GreaterThanIsOperatorScope(bool &GTIO, bool Val) : GreaterThanIsOperator(GTIO), OldGreaterThanIsOperator(GTIO) { GreaterThanIsOperator = Val; } ~GreaterThanIsOperatorScope() { GreaterThanIsOperator = OldGreaterThanIsOperator; } }; class InMessageExpressionRAIIObject { bool &InMessageExpression; bool OldValue; public: InMessageExpressionRAIIObject(Parser &P, bool Value) : InMessageExpression(P.InMessageExpression), OldValue(P.InMessageExpression) { InMessageExpression = Value; } ~InMessageExpressionRAIIObject() { InMessageExpression = OldValue; } }; /// RAII object that makes sure paren/bracket/brace count is correct /// after declaration/statement parsing, even when there's a parsing error. class ParenBraceBracketBalancer { Parser &P; unsigned short ParenCount, BracketCount, BraceCount; public: ParenBraceBracketBalancer(Parser &p) : P(p), ParenCount(p.ParenCount), BracketCount(p.BracketCount), BraceCount(p.BraceCount) { } ~ParenBraceBracketBalancer() { P.AngleBrackets.clear(P); P.ParenCount = ParenCount; P.BracketCount = BracketCount; P.BraceCount = BraceCount; } }; class PoisonSEHIdentifiersRAIIObject { PoisonIdentifierRAIIObject Ident_AbnormalTermination; PoisonIdentifierRAIIObject Ident_GetExceptionCode; PoisonIdentifierRAIIObject Ident_GetExceptionInfo; PoisonIdentifierRAIIObject Ident__abnormal_termination; PoisonIdentifierRAIIObject Ident__exception_code; PoisonIdentifierRAIIObject Ident__exception_info; PoisonIdentifierRAIIObject Ident___abnormal_termination; PoisonIdentifierRAIIObject Ident___exception_code; PoisonIdentifierRAIIObject Ident___exception_info; public: PoisonSEHIdentifiersRAIIObject(Parser &Self, bool NewValue) : Ident_AbnormalTermination(Self.Ident_AbnormalTermination, NewValue), Ident_GetExceptionCode(Self.Ident_GetExceptionCode, NewValue), Ident_GetExceptionInfo(Self.Ident_GetExceptionInfo, NewValue), Ident__abnormal_termination(Self.Ident__abnormal_termination, NewValue), Ident__exception_code(Self.Ident__exception_code, NewValue), Ident__exception_info(Self.Ident__exception_info, NewValue), Ident___abnormal_termination(Self.Ident___abnormal_termination, NewValue), Ident___exception_code(Self.Ident___exception_code, NewValue), Ident___exception_info(Self.Ident___exception_info, NewValue) { } }; /// RAII class that helps handle the parsing of an open/close delimiter /// pair, such as braces { ... } or parentheses ( ... ). class BalancedDelimiterTracker : public GreaterThanIsOperatorScope { Parser& P; tok::TokenKind Kind, Close, FinalToken; SourceLocation (Parser::*Consumer)(); SourceLocation LOpen, LClose; unsigned short &getDepth() { switch (Kind) { case tok::l_brace: return P.BraceCount; case tok::l_square: return P.BracketCount; case tok::l_paren: return P.ParenCount; default: llvm_unreachable("Wrong token kind"); } } bool diagnoseOverflow(); bool diagnoseMissingClose(); public: BalancedDelimiterTracker(Parser& p, tok::TokenKind k, tok::TokenKind FinalToken = tok::semi) : GreaterThanIsOperatorScope(p.GreaterThanIsOperator, true), P(p), Kind(k), FinalToken(FinalToken) { switch (Kind) { default: llvm_unreachable("Unexpected balanced token"); case tok::l_brace: Close = tok::r_brace; Consumer = &Parser::ConsumeBrace; break; case tok::l_paren: Close = tok::r_paren; Consumer = &Parser::ConsumeParen; break; case tok::l_square: Close = tok::r_square; Consumer = &Parser::ConsumeBracket; break; } } SourceLocation getOpenLocation() const { return LOpen; } SourceLocation getCloseLocation() const { return LClose; } SourceRange getRange() const { return SourceRange(LOpen, LClose); } bool consumeOpen() { if (!P.Tok.is(Kind)) return true; if (getDepth() < P.getLangOpts().BracketDepth) { LOpen = (P.*Consumer)(); return false; } return diagnoseOverflow(); } bool expectAndConsume(unsigned DiagID = diag::err_expected, const char *Msg = "", tok::TokenKind SkipToTok = tok::unknown); bool consumeClose() { if (P.Tok.is(Close)) { LClose = (P.*Consumer)(); return false; } else if (P.Tok.is(tok::semi) && P.NextToken().is(Close)) { SourceLocation SemiLoc = P.ConsumeToken(); P.Diag(SemiLoc, diag::err_unexpected_semi) << Close << FixItHint::CreateRemoval(SourceRange(SemiLoc, SemiLoc)); LClose = (P.*Consumer)(); return false; } return diagnoseMissingClose(); } void skipToEnd(); }; /// RAIIObject to destroy the contents of a SmallVector of /// TemplateIdAnnotation pointers and clear the vector. class DestroyTemplateIdAnnotationsRAIIObj { SmallVectorImpl<TemplateIdAnnotation *> &Container; public: DestroyTemplateIdAnnotationsRAIIObj( SmallVectorImpl<TemplateIdAnnotation *> &Container) : Container(Container) {} ~DestroyTemplateIdAnnotationsRAIIObj() { for (SmallVectorImpl<TemplateIdAnnotation *>::iterator I = Container.begin(), E = Container.end(); I != E; ++I) (*I)->Destroy(); Container.clear(); } }; } // end namespace clang #endif
{ "pile_set_name": "Github" }
; RUN: opt < %s -cost-model -costmodel-reduxcost=true -analyze -mcpu=core2 -mtriple=x86_64-apple-darwin | FileCheck %s ; RUN: opt < %s -cost-model -costmodel-reduxcost=true -analyze -mcpu=corei7 -mtriple=x86_64-apple-darwin | FileCheck %s --check-prefix=SSE3 ; RUN: opt < %s -cost-model -costmodel-reduxcost=true -analyze -mcpu=corei7-avx -mtriple=x86_64-apple-darwin | FileCheck %s --check-prefix=AVX ; RUN: opt < %s -cost-model -costmodel-reduxcost=true -analyze -mcpu=core-avx2 -mtriple=x86_64-apple-darwin | FileCheck %s --check-prefix=AVX2 define fastcc float @reduction_cost_float(<4 x float> %rdx) { %rdx.shuf = shufflevector <4 x float> %rdx, <4 x float> undef, <4 x i32> <i32 2, i32 3, i32 undef, i32 undef> %bin.rdx = fadd <4 x float> %rdx, %rdx.shuf %rdx.shuf7 = shufflevector <4 x float> %bin.rdx, <4 x float> undef, <4 x i32> <i32 1, i32 undef, i32 undef, i32 undef> %bin.rdx8 = fadd <4 x float> %bin.rdx, %rdx.shuf7 ; Check that we recognize the tree starting at the extractelement as a ; reduction. ; CHECK-LABEL: reduction_cost ; CHECK: cost of 9 {{.*}} extractelement %r = extractelement <4 x float> %bin.rdx8, i32 0 ret float %r } define fastcc i32 @reduction_cost_int(<8 x i32> %rdx) { %rdx.shuf = shufflevector <8 x i32> %rdx, <8 x i32> undef, <8 x i32> <i32 4 , i32 5, i32 6, i32 7, i32 undef, i32 undef, i32 undef, i32 undef> %bin.rdx = add <8 x i32> %rdx, %rdx.shuf %rdx.shuf.2 = shufflevector <8 x i32> %bin.rdx, <8 x i32> undef, <8 x i32> <i32 2 , i32 3, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef> %bin.rdx.2 = add <8 x i32> %bin.rdx, %rdx.shuf.2 %rdx.shuf.3 = shufflevector <8 x i32> %bin.rdx.2, <8 x i32> undef, <8 x i32> <i32 1 , i32 undef, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef> %bin.rdx.3 = add <8 x i32> %bin.rdx.2, %rdx.shuf.3 ; CHECK-LABEL: reduction_cost_int ; CHECK: cost of 23 {{.*}} extractelement %r = extractelement <8 x i32> %bin.rdx.3, i32 0 ret i32 %r } define fastcc float @pairwise_hadd(<4 x float> %rdx, float %f1) { %rdx.shuf.0.0 = shufflevector <4 x float> %rdx, <4 x float> undef, <4 x i32> <i32 0, i32 2 , i32 undef, i32 undef> %rdx.shuf.0.1 = shufflevector <4 x float> %rdx, <4 x float> undef, <4 x i32> <i32 1, i32 3, i32 undef, i32 undef> %bin.rdx.0 = fadd <4 x float> %rdx.shuf.0.0, %rdx.shuf.0.1 %rdx.shuf.1.0 = shufflevector <4 x float> %bin.rdx.0, <4 x float> undef, <4 x i32> <i32 0, i32 undef, i32 undef, i32 undef> %rdx.shuf.1.1 = shufflevector <4 x float> %bin.rdx.0, <4 x float> undef, <4 x i32> <i32 1, i32 undef, i32 undef, i32 undef> %bin.rdx.1 = fadd <4 x float> %rdx.shuf.1.0, %rdx.shuf.1.1 ; CHECK-LABEL: pairwise_hadd ; CHECK: cost of 11 {{.*}} extractelement %r = extractelement <4 x float> %bin.rdx.1, i32 0 %r2 = fadd float %r, %f1 ret float %r2 } define fastcc float @pairwise_hadd_assoc(<4 x float> %rdx, float %f1) { %rdx.shuf.0.0 = shufflevector <4 x float> %rdx, <4 x float> undef, <4 x i32> <i32 0, i32 2 , i32 undef, i32 undef> %rdx.shuf.0.1 = shufflevector <4 x float> %rdx, <4 x float> undef, <4 x i32> <i32 1, i32 3, i32 undef, i32 undef> %bin.rdx.0 = fadd <4 x float> %rdx.shuf.0.1, %rdx.shuf.0.0 %rdx.shuf.1.0 = shufflevector <4 x float> %bin.rdx.0, <4 x float> undef, <4 x i32> <i32 0, i32 undef, i32 undef, i32 undef> %rdx.shuf.1.1 = shufflevector <4 x float> %bin.rdx.0, <4 x float> undef, <4 x i32> <i32 1, i32 undef, i32 undef, i32 undef> %bin.rdx.1 = fadd <4 x float> %rdx.shuf.1.0, %rdx.shuf.1.1 ; CHECK-LABEL: pairwise_hadd_assoc ; CHECK: cost of 11 {{.*}} extractelement %r = extractelement <4 x float> %bin.rdx.1, i32 0 %r2 = fadd float %r, %f1 ret float %r2 } define fastcc float @pairwise_hadd_skip_first(<4 x float> %rdx, float %f1) { %rdx.shuf.0.0 = shufflevector <4 x float> %rdx, <4 x float> undef, <4 x i32> <i32 0, i32 2 , i32 undef, i32 undef> %rdx.shuf.0.1 = shufflevector <4 x float> %rdx, <4 x float> undef, <4 x i32> <i32 1, i32 3, i32 undef, i32 undef> %bin.rdx.0 = fadd <4 x float> %rdx.shuf.0.0, %rdx.shuf.0.1 %rdx.shuf.1.1 = shufflevector <4 x float> %bin.rdx.0, <4 x float> undef, <4 x i32> <i32 1, i32 undef, i32 undef, i32 undef> %bin.rdx.1 = fadd <4 x float> %bin.rdx.0, %rdx.shuf.1.1 ; CHECK-LABEL: pairwise_hadd_skip_first ; CHECK: cost of 11 {{.*}} extractelement %r = extractelement <4 x float> %bin.rdx.1, i32 0 %r2 = fadd float %r, %f1 ret float %r2 } define fastcc double @no_pairwise_reduction2double(<2 x double> %rdx, double %f1) { %rdx.shuf = shufflevector <2 x double> %rdx, <2 x double> undef, <2 x i32> <i32 1, i32 undef> %bin.rdx = fadd <2 x double> %rdx, %rdx.shuf ; SSE3: cost of 2 {{.*}} extractelement ; AVX: cost of 2 {{.*}} extractelement ; AVX2: cost of 2 {{.*}} extractelement %r = extractelement <2 x double> %bin.rdx, i32 0 ret double %r } define fastcc float @no_pairwise_reduction4float(<4 x float> %rdx, float %f1) { %rdx.shuf = shufflevector <4 x float> %rdx, <4 x float> undef, <4 x i32> <i32 2, i32 3, i32 undef, i32 undef> %bin.rdx = fadd <4 x float> %rdx, %rdx.shuf %rdx.shuf7 = shufflevector <4 x float> %bin.rdx, <4 x float> undef, <4 x i32> <i32 1, i32 undef, i32 undef, i32 undef> %bin.rdx8 = fadd <4 x float> %bin.rdx, %rdx.shuf7 ; SSE3: cost of 4 {{.*}} extractelement ; AVX: cost of 3 {{.*}} extractelement ; AVX2: cost of 3 {{.*}} extractelement %r = extractelement <4 x float> %bin.rdx8, i32 0 ret float %r } define fastcc double @no_pairwise_reduction4double(<4 x double> %rdx, double %f1) { %rdx.shuf = shufflevector <4 x double> %rdx, <4 x double> undef, <4 x i32> <i32 2, i32 3, i32 undef, i32 undef> %bin.rdx = fadd <4 x double> %rdx, %rdx.shuf %rdx.shuf7 = shufflevector <4 x double> %bin.rdx, <4 x double> undef, <4 x i32> <i32 1, i32 undef, i32 undef, i32 undef> %bin.rdx8 = fadd <4 x double> %bin.rdx, %rdx.shuf7 ; AVX: cost of 3 {{.*}} extractelement ; AVX2: cost of 3 {{.*}} extractelement %r = extractelement <4 x double> %bin.rdx8, i32 0 ret double %r } define fastcc float @no_pairwise_reduction8float(<8 x float> %rdx, float %f1) { %rdx.shuf3 = shufflevector <8 x float> %rdx, <8 x float> undef, <8 x i32> <i32 4, i32 5, i32 6, i32 7,i32 undef, i32 undef, i32 undef, i32 undef> %bin.rdx4 = fadd <8 x float> %rdx, %rdx.shuf3 %rdx.shuf = shufflevector <8 x float> %bin.rdx4, <8 x float> undef, <8 x i32> <i32 2, i32 3, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef> %bin.rdx = fadd <8 x float> %bin.rdx4, %rdx.shuf %rdx.shuf7 = shufflevector <8 x float> %bin.rdx, <8 x float> undef, <8 x i32> <i32 1, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef> %bin.rdx8 = fadd <8 x float> %bin.rdx, %rdx.shuf7 ; AVX: cost of 4 {{.*}} extractelement ; AVX2: cost of 4 {{.*}} extractelement %r = extractelement <8 x float> %bin.rdx8, i32 0 ret float %r } define fastcc i64 @no_pairwise_reduction2i64(<2 x i64> %rdx, i64 %f1) { %rdx.shuf = shufflevector <2 x i64> %rdx, <2 x i64> undef, <2 x i32> <i32 1, i32 undef> %bin.rdx = add <2 x i64> %rdx, %rdx.shuf ; SSE3: cost of 2 {{.*}} extractelement ; AVX: cost of 1 {{.*}} extractelement ; AVX2: cost of 1 {{.*}} extractelement %r = extractelement <2 x i64> %bin.rdx, i32 0 ret i64 %r } define fastcc i32 @no_pairwise_reduction4i32(<4 x i32> %rdx, i32 %f1) { %rdx.shuf = shufflevector <4 x i32> %rdx, <4 x i32> undef, <4 x i32> <i32 2, i32 3, i32 undef, i32 undef> %bin.rdx = add <4 x i32> %rdx, %rdx.shuf %rdx.shuf7 = shufflevector <4 x i32> %bin.rdx, <4 x i32> undef, <4 x i32> <i32 1, i32 undef, i32 undef, i32 undef> %bin.rdx8 = add <4 x i32> %bin.rdx, %rdx.shuf7 ; SSE3: cost of 3 {{.*}} extractelement ; AVX: cost of 3 {{.*}} extractelement ; AVX2: cost of 3 {{.*}} extractelement %r = extractelement <4 x i32> %bin.rdx8, i32 0 ret i32 %r } define fastcc i64 @no_pairwise_reduction4i64(<4 x i64> %rdx, i64 %f1) { %rdx.shuf = shufflevector <4 x i64> %rdx, <4 x i64> undef, <4 x i32> <i32 2, i32 3, i32 undef, i32 undef> %bin.rdx = add <4 x i64> %rdx, %rdx.shuf %rdx.shuf7 = shufflevector <4 x i64> %bin.rdx, <4 x i64> undef, <4 x i32> <i32 1, i32 undef, i32 undef, i32 undef> %bin.rdx8 = add <4 x i64> %bin.rdx, %rdx.shuf7 ; AVX: cost of 3 {{.*}} extractelement ; AVX2: cost of 3 {{.*}} extractelement %r = extractelement <4 x i64> %bin.rdx8, i32 0 ret i64 %r } define fastcc i16 @no_pairwise_reduction8i16(<8 x i16> %rdx, i16 %f1) { %rdx.shuf3 = shufflevector <8 x i16> %rdx, <8 x i16> undef, <8 x i32> <i32 4, i32 5, i32 6, i32 7,i32 undef, i32 undef, i32 undef, i32 undef> %bin.rdx4 = add <8 x i16> %rdx, %rdx.shuf3 %rdx.shuf = shufflevector <8 x i16> %bin.rdx4, <8 x i16> undef, <8 x i32> <i32 2, i32 3, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef> %bin.rdx = add <8 x i16> %bin.rdx4, %rdx.shuf %rdx.shuf7 = shufflevector <8 x i16> %bin.rdx, <8 x i16> undef, <8 x i32> <i32 1, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef> %bin.rdx8 = add <8 x i16> %bin.rdx, %rdx.shuf7 ; SSE3: cost of 4 {{.*}} extractelement ; AVX: cost of 4 {{.*}} extractelement ; AVX2: cost of 4 {{.*}} extractelement %r = extractelement <8 x i16> %bin.rdx8, i32 0 ret i16 %r } define fastcc i32 @no_pairwise_reduction8i32(<8 x i32> %rdx, i32 %f1) { %rdx.shuf3 = shufflevector <8 x i32> %rdx, <8 x i32> undef, <8 x i32> <i32 4, i32 5, i32 6, i32 7,i32 undef, i32 undef, i32 undef, i32 undef> %bin.rdx4 = add <8 x i32> %rdx, %rdx.shuf3 %rdx.shuf = shufflevector <8 x i32> %bin.rdx4, <8 x i32> undef, <8 x i32> <i32 2, i32 3, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef> %bin.rdx = add <8 x i32> %bin.rdx4, %rdx.shuf %rdx.shuf7 = shufflevector <8 x i32> %bin.rdx, <8 x i32> undef, <8 x i32> <i32 1, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef> %bin.rdx8 = add <8 x i32> %bin.rdx, %rdx.shuf7 ; AVX: cost of 5 {{.*}} extractelement ; AVX2: cost of 5 {{.*}} extractelement %r = extractelement <8 x i32> %bin.rdx8, i32 0 ret i32 %r } define fastcc double @pairwise_reduction2double(<2 x double> %rdx, double %f1) { %rdx.shuf.1.0 = shufflevector <2 x double> %rdx, <2 x double> undef, <2 x i32> <i32 0, i32 undef> %rdx.shuf.1.1 = shufflevector <2 x double> %rdx, <2 x double> undef, <2 x i32> <i32 1, i32 undef> %bin.rdx8 = fadd <2 x double> %rdx.shuf.1.0, %rdx.shuf.1.1 ; SSE3: cost of 2 {{.*}} extractelement ; AVX: cost of 2 {{.*}} extractelement ; AVX2: cost of 2 {{.*}} extractelement %r = extractelement <2 x double> %bin.rdx8, i32 0 ret double %r } define fastcc float @pairwise_reduction4float(<4 x float> %rdx, float %f1) { %rdx.shuf.0.0 = shufflevector <4 x float> %rdx, <4 x float> undef, <4 x i32> <i32 0, i32 2, i32 undef, i32 undef> %rdx.shuf.0.1 = shufflevector <4 x float> %rdx, <4 x float> undef, <4 x i32> <i32 1, i32 3, i32 undef, i32 undef> %bin.rdx = fadd <4 x float> %rdx.shuf.0.0, %rdx.shuf.0.1 %rdx.shuf.1.0 = shufflevector <4 x float> %bin.rdx, <4 x float> undef, <4 x i32> <i32 0, i32 undef, i32 undef, i32 undef> %rdx.shuf.1.1 = shufflevector <4 x float> %bin.rdx, <4 x float> undef, <4 x i32> <i32 1, i32 undef, i32 undef, i32 undef> %bin.rdx8 = fadd <4 x float> %rdx.shuf.1.0, %rdx.shuf.1.1 ; SSE3: cost of 4 {{.*}} extractelement ; AVX: cost of 4 {{.*}} extractelement ; AVX2: cost of 4 {{.*}} extractelement %r = extractelement <4 x float> %bin.rdx8, i32 0 ret float %r } define fastcc double @pairwise_reduction4double(<4 x double> %rdx, double %f1) { %rdx.shuf.0.0 = shufflevector <4 x double> %rdx, <4 x double> undef, <4 x i32> <i32 0, i32 2, i32 undef, i32 undef> %rdx.shuf.0.1 = shufflevector <4 x double> %rdx, <4 x double> undef, <4 x i32> <i32 1, i32 3, i32 undef, i32 undef> %bin.rdx = fadd <4 x double> %rdx.shuf.0.0, %rdx.shuf.0.1 %rdx.shuf.1.0 = shufflevector <4 x double> %bin.rdx, <4 x double> undef, <4 x i32> <i32 0, i32 undef, i32 undef, i32 undef> %rdx.shuf.1.1 = shufflevector <4 x double> %bin.rdx, <4 x double> undef, <4 x i32> <i32 1, i32 undef, i32 undef, i32 undef> %bin.rdx8 = fadd <4 x double> %rdx.shuf.1.0, %rdx.shuf.1.1 ; AVX: cost of 5 {{.*}} extractelement ; AVX2: cost of 5 {{.*}} extractelement %r = extractelement <4 x double> %bin.rdx8, i32 0 ret double %r } define fastcc float @pairwise_reduction8float(<8 x float> %rdx, float %f1) { %rdx.shuf.0.0 = shufflevector <8 x float> %rdx, <8 x float> undef, <8 x i32> <i32 0, i32 2, i32 4, i32 6,i32 undef, i32 undef, i32 undef, i32 undef> %rdx.shuf.0.1 = shufflevector <8 x float> %rdx, <8 x float> undef, <8 x i32> <i32 1, i32 3, i32 5, i32 7,i32 undef, i32 undef, i32 undef, i32 undef> %bin.rdx = fadd <8 x float> %rdx.shuf.0.0, %rdx.shuf.0.1 %rdx.shuf.1.0 = shufflevector <8 x float> %bin.rdx, <8 x float> undef,<8 x i32> <i32 0, i32 2, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef> %rdx.shuf.1.1 = shufflevector <8 x float> %bin.rdx, <8 x float> undef,<8 x i32> <i32 1, i32 3, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef> %bin.rdx8 = fadd <8 x float> %rdx.shuf.1.0, %rdx.shuf.1.1 %rdx.shuf.2.0 = shufflevector <8 x float> %bin.rdx8, <8 x float> undef,<8 x i32> <i32 0, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef> %rdx.shuf.2.1 = shufflevector <8 x float> %bin.rdx8, <8 x float> undef,<8 x i32> <i32 1, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef> %bin.rdx9 = fadd <8 x float> %rdx.shuf.2.0, %rdx.shuf.2.1 ; AVX: cost of 7 {{.*}} extractelement ; AVX2: cost of 7 {{.*}} extractelement %r = extractelement <8 x float> %bin.rdx9, i32 0 ret float %r } define fastcc i64 @pairwise_reduction2i64(<2 x i64> %rdx, i64 %f1) { %rdx.shuf.1.0 = shufflevector <2 x i64> %rdx, <2 x i64> undef, <2 x i32> <i32 0, i32 undef> %rdx.shuf.1.1 = shufflevector <2 x i64> %rdx, <2 x i64> undef, <2 x i32> <i32 1, i32 undef> %bin.rdx8 = add <2 x i64> %rdx.shuf.1.0, %rdx.shuf.1.1 ; SSE3: cost of 2 {{.*}} extractelement ; AVX: cost of 1 {{.*}} extractelement ; AVX2: cost of 1 {{.*}} extractelement %r = extractelement <2 x i64> %bin.rdx8, i32 0 ret i64 %r } define fastcc i32 @pairwise_reduction4i32(<4 x i32> %rdx, i32 %f1) { %rdx.shuf.0.0 = shufflevector <4 x i32> %rdx, <4 x i32> undef, <4 x i32> <i32 0, i32 2, i32 undef, i32 undef> %rdx.shuf.0.1 = shufflevector <4 x i32> %rdx, <4 x i32> undef, <4 x i32> <i32 1, i32 3, i32 undef, i32 undef> %bin.rdx = add <4 x i32> %rdx.shuf.0.0, %rdx.shuf.0.1 %rdx.shuf.1.0 = shufflevector <4 x i32> %bin.rdx, <4 x i32> undef, <4 x i32> <i32 0, i32 undef, i32 undef, i32 undef> %rdx.shuf.1.1 = shufflevector <4 x i32> %bin.rdx, <4 x i32> undef, <4 x i32> <i32 1, i32 undef, i32 undef, i32 undef> %bin.rdx8 = add <4 x i32> %rdx.shuf.1.0, %rdx.shuf.1.1 ; SSE3: cost of 3 {{.*}} extractelement ; AVX: cost of 3 {{.*}} extractelement ; AVX2: cost of 3 {{.*}} extractelement %r = extractelement <4 x i32> %bin.rdx8, i32 0 ret i32 %r } define fastcc i64 @pairwise_reduction4i64(<4 x i64> %rdx, i64 %f1) { %rdx.shuf.0.0 = shufflevector <4 x i64> %rdx, <4 x i64> undef, <4 x i32> <i32 0, i32 2, i32 undef, i32 undef> %rdx.shuf.0.1 = shufflevector <4 x i64> %rdx, <4 x i64> undef, <4 x i32> <i32 1, i32 3, i32 undef, i32 undef> %bin.rdx = add <4 x i64> %rdx.shuf.0.0, %rdx.shuf.0.1 %rdx.shuf.1.0 = shufflevector <4 x i64> %bin.rdx, <4 x i64> undef, <4 x i32> <i32 0, i32 undef, i32 undef, i32 undef> %rdx.shuf.1.1 = shufflevector <4 x i64> %bin.rdx, <4 x i64> undef, <4 x i32> <i32 1, i32 undef, i32 undef, i32 undef> %bin.rdx8 = add <4 x i64> %rdx.shuf.1.0, %rdx.shuf.1.1 ; AVX: cost of 5 {{.*}} extractelement ; AVX2: cost of 5 {{.*}} extractelement %r = extractelement <4 x i64> %bin.rdx8, i32 0 ret i64 %r } define fastcc i16 @pairwise_reduction8i16(<8 x i16> %rdx, i16 %f1) { %rdx.shuf.0.0 = shufflevector <8 x i16> %rdx, <8 x i16> undef, <8 x i32> <i32 0, i32 2, i32 4, i32 6,i32 undef, i32 undef, i32 undef, i32 undef> %rdx.shuf.0.1 = shufflevector <8 x i16> %rdx, <8 x i16> undef, <8 x i32> <i32 1, i32 3, i32 5, i32 7,i32 undef, i32 undef, i32 undef, i32 undef> %bin.rdx = add <8 x i16> %rdx.shuf.0.0, %rdx.shuf.0.1 %rdx.shuf.1.0 = shufflevector <8 x i16> %bin.rdx, <8 x i16> undef,<8 x i32> <i32 0, i32 2, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef> %rdx.shuf.1.1 = shufflevector <8 x i16> %bin.rdx, <8 x i16> undef,<8 x i32> <i32 1, i32 3, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef> %bin.rdx8 = add <8 x i16> %rdx.shuf.1.0, %rdx.shuf.1.1 %rdx.shuf.2.0 = shufflevector <8 x i16> %bin.rdx8, <8 x i16> undef,<8 x i32> <i32 0, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef> %rdx.shuf.2.1 = shufflevector <8 x i16> %bin.rdx8, <8 x i16> undef,<8 x i32> <i32 1, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef> %bin.rdx9 = add <8 x i16> %rdx.shuf.2.0, %rdx.shuf.2.1 ; SSE3: cost of 5 {{.*}} extractelement ; AVX: cost of 5 {{.*}} extractelement ; AVX2: cost of 5 {{.*}} extractelement %r = extractelement <8 x i16> %bin.rdx9, i32 0 ret i16 %r } define fastcc i32 @pairwise_reduction8i32(<8 x i32> %rdx, i32 %f1) { %rdx.shuf.0.0 = shufflevector <8 x i32> %rdx, <8 x i32> undef, <8 x i32> <i32 0, i32 2, i32 4, i32 6,i32 undef, i32 undef, i32 undef, i32 undef> %rdx.shuf.0.1 = shufflevector <8 x i32> %rdx, <8 x i32> undef, <8 x i32> <i32 1, i32 3, i32 5, i32 7,i32 undef, i32 undef, i32 undef, i32 undef> %bin.rdx = add <8 x i32> %rdx.shuf.0.0, %rdx.shuf.0.1 %rdx.shuf.1.0 = shufflevector <8 x i32> %bin.rdx, <8 x i32> undef,<8 x i32> <i32 0, i32 2, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef> %rdx.shuf.1.1 = shufflevector <8 x i32> %bin.rdx, <8 x i32> undef,<8 x i32> <i32 1, i32 3, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef> %bin.rdx8 = add <8 x i32> %rdx.shuf.1.0, %rdx.shuf.1.1 %rdx.shuf.2.0 = shufflevector <8 x i32> %bin.rdx8, <8 x i32> undef,<8 x i32> <i32 0, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef> %rdx.shuf.2.1 = shufflevector <8 x i32> %bin.rdx8, <8 x i32> undef,<8 x i32> <i32 1, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef, i32 undef> %bin.rdx9 = add <8 x i32> %rdx.shuf.2.0, %rdx.shuf.2.1 ; AVX: cost of 5 {{.*}} extractelement ; AVX2: cost of 5 {{.*}} extractelement %r = extractelement <8 x i32> %bin.rdx9, i32 0 ret i32 %r }
{ "pile_set_name": "Github" }
耗了一点时间。本以为需要DP一下,把做过的n存一下。后来发现,其实就是剥皮,一层一层,是一个central-depth-first的,钻到底时候,return n=1,或者n=2的case,然后开始backtracking。 难的case先不handle.到底之后来一次O(n) scan. 总共的时间起码是O(n/2) + O(n), 所以还是O(n) ``` /* A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). Find all strobogrammatic numbers that are of length = n. For example, Given n = 2, return ["11","69","88","96"]. Hint: Try to use recursion and notice that it should recurse with n - 2 instead of n - 1. Tags: Math Recursion Similar Problems: (E) Strobogrammatic Number, (H) Strobogrammatic Number III */ /* Thoughts: For n, there can be k kinds of combination. Save it to map(n,k-list) For n+2, there can be x + k-kinds-of-inner-number + y; Treat n=0,1,2 differently. Then recurse on rest, layer by layer At end end, do a O(n) scan to remove non-wanted items. */ public class Solution { private HashMap<String, String> candidate = new HashMap<String, String>(); public List<String> findStrobogrammatic(int n) { List<String> rst = new ArrayList<String>(); candidate.put("0", "0"); candidate.put("1", "1"); candidate.put("8", "8"); candidate.put("6", "9"); candidate.put("9", "6"); rst = searchAndCombine(n); for (int i = 0; i < rst.size(); i++) { if ((Long.parseLong(rst.get(i))+"").length() != n) { rst.remove(i); i--; } } return rst; } public List<String> searchAndCombine(int n) { List<String> list = new ArrayList<String>(); if (n <= 0) { return list; } else if (n == 1) { list.add("0"); list.add("1"); list.add("8"); return list; } else if (n == 2){ list.add("69"); list.add("11"); list.add("88"); list.add("96"); list.add("00"); return list; }else {//n >= 2 List<String> temp = searchAndCombine(n - 2); for (String str : temp) { for (Map.Entry<String, String> entry : candidate.entrySet()) { list.add(entry.getKey() + str + entry.getValue()); } } } return list; } } ```
{ "pile_set_name": "Github" }
; RUN: llc < %s -march=nvptx -mcpu=sm_20 | FileCheck %s declare i8 @llvm.nvvm.ldu.global.i.i8.p1i8(i8 addrspace(1)* %ptr, i32 %align) declare i32 @llvm.nvvm.ldu.global.i.i32.p1i32(i32 addrspace(1)* %ptr, i32 %align) declare i8 @llvm.nvvm.ldg.global.i.i8.p1i8(i8 addrspace(1)* %ptr, i32 %align) declare i32 @llvm.nvvm.ldg.global.i.i32.p1i32(i32 addrspace(1)* %ptr, i32 %align) ; CHECK: func0 define i8 @func0(i8 addrspace(1)* %ptr) { ; ldu.global.u8 %val = tail call i8 @llvm.nvvm.ldu.global.i.i8.p1i8(i8 addrspace(1)* %ptr, i32 4) ret i8 %val } ; CHECK: func1 define i32 @func1(i32 addrspace(1)* %ptr) { ; ldu.global.u32 %val = tail call i32 @llvm.nvvm.ldu.global.i.i32.p1i32(i32 addrspace(1)* %ptr, i32 4) ret i32 %val } ; CHECK: func2 define i8 @func2(i8 addrspace(1)* %ptr) { ; ld.global.nc.u8 %val = tail call i8 @llvm.nvvm.ldg.global.i.i8.p1i8(i8 addrspace(1)* %ptr, i32 4) ret i8 %val } ; CHECK: func3 define i32 @func3(i32 addrspace(1)* %ptr) { ; ld.global.nc.u32 %val = tail call i32 @llvm.nvvm.ldg.global.i.i32.p1i32(i32 addrspace(1)* %ptr, i32 4) ret i32 %val }
{ "pile_set_name": "Github" }
using Gadfly, RDatasets, Compose set_default_plot_size(6inch, 9inch) vstack( plot(sin, 0, 25, xintercept=[0, pi, 2pi, 3pi], yintercept=[0, -1, 1], Geom.hline(style=[:dot,[1mm,1mm],:solid]), Geom.vline(style=:dashdot)), plot(dataset("datasets", "iris"), x="SepalLength", y="SepalWidth", Geom.point, yintercept=[2.5, 4.0], Geom.hline(color=["orange","red"], size=[2mm,3mm])), plot(dataset("ggplot2", "mpg"), x="Cty", y="Hwy", Geom.point, intercept=[0], slope=[1], Geom.abline(color="red", style=:dash), Guide.annotation(compose(context(), text(0.1w, 0.9h, "y=x", hright, vbottom), fill(colorant"red"), svgclass("marker")))) )
{ "pile_set_name": "Github" }
/*============================================================================= Copyright (c) 2016-2020 Joel de Guzman Distributed under the MIT License [ https://opensource.org/licenses/MIT ] =============================================================================*/ #include <elements/element/gallery/radio_button.hpp> namespace cycfi { namespace elements { void radio_button_element::draw(context const& ctx) { auto& canvas_ = ctx.canvas; auto canvas_state = canvas_.new_state(); auto const& theme_ = get_theme(); rect box = ctx.bounds.move(15, 0); float size = box.height(); float radius = size/2; float dot_radius = radius/2.5; box.width(size); point center = center_point(box); bool state = value() > 1; bool hilite = value() & 1; if (state) { color c1 = state ? (hilite? theme_.indicator_hilite_color : theme_.indicator_bright_color) : colors::black.opacity(theme_.element_background_opacity) ; canvas_.begin_path(); canvas_.fill_style(c1); canvas_.circle(circle(center, dot_radius)); canvas_.fill(); } auto line_width = theme_.controls_frame_stroke_width; color outline_color = hilite? theme_.frame_hilite_color : theme_.frame_color; canvas_.line_width(line_width); canvas_.begin_path(); canvas_.circle(circle(center, radius-1)); canvas_.stroke_style(outline_color); canvas_.stroke(); // Pseudo glow auto glow_width = hilite? line_width*2 : line_width; canvas_.circle(circle(center, radius-(glow_width/3))); canvas_.line_width(glow_width); canvas_.stroke_style(outline_color.opacity(0.1)); canvas_.stroke(); canvas_.fill_style(theme_.label_font_color); canvas_.font( theme_.label_font, theme_.label_font_size ); canvas_.text_align(canvas_.left | canvas_.middle); float cx = box.right + 10; float cy = ctx.bounds.top + (ctx.bounds.height() / 2); canvas_.fill_text(point{ cx, cy }, _text.c_str()); } }}
{ "pile_set_name": "Github" }
// FoalTS import { Config, Context, Hook, HookDecorator, HttpResponseBadRequest } from '../../core'; import { ApiParameter, ApiResponse, IApiPathParameter, IApiSchema } from '../../openapi'; import { getAjvInstance } from '../utils'; import { isFunction } from './is-function.util'; /** * Hook - Validate a specific path parameter against an AJV schema. * * @export * @param {string} name - Path parameter name. * @param {(object | ((controller: any) => object))} schema - Schema used to * validate the path parameter. * @param {{ openapi?: boolean }} [options={}] - Options. * @param {boolean} [options.openapi] - Add OpenApi metadata. * @returns {HookDecorator} The hook. */ export function ValidatePathParam( name: string, schema: object | ((controller: any) => object), options: { openapi?: boolean } = {} ): HookDecorator { const ajv = getAjvInstance(); function validate(this: any, ctx: Context) { const paramsSchema = { properties: { [name]: isFunction(schema) ? schema(this) : schema }, required: [ name ], type: 'object', }; if (!ajv.validate(paramsSchema, ctx.request.params)) { return new HttpResponseBadRequest({ pathParams: ajv.errors }); } } return (target: any, propertyKey?: string) => { Hook(validate)(target, propertyKey); if (options.openapi === false || (options.openapi === undefined && !Config.get2('settings.openapi.useHooks', 'boolean')) ) { return; } function makeParameter(schema: IApiSchema): IApiPathParameter { return { in: 'path', name, required: true, schema }; } const apiPathParameter = isFunction(schema) ? (c: any) => makeParameter(schema(c)) : makeParameter(schema); ApiParameter(apiPathParameter)(target, propertyKey); ApiResponse(400, { description: 'Bad request.' })(target, propertyKey); }; }
{ "pile_set_name": "Github" }
<?xml version="1.0"?> <ZopeData> <record id="1" aka="AAAAAAAAAAE="> <pickle> <global name="ProxyField" module="Products.ERP5Form.ProxyField"/> </pickle> <pickle> <dictionary> <item> <key> <string>delegated_list</string> </key> <value> <list/> </value> </item> <item> <key> <string>id</string> </key> <value> <string>my_activity</string> </value> </item> <item> <key> <string>message_values</string> </key> <value> <dictionary> <item> <key> <string>external_validator_failed</string> </key> <value> <string>The input failed the external validator.</string> </value> </item> </dictionary> </value> </item> <item> <key> <string>overrides</string> </key> <value> <dictionary> <item> <key> <string>field_id</string> </key> <value> <string></string> </value> </item> <item> <key> <string>form_id</string> </key> <value> <string></string> </value> </item> <item> <key> <string>target</string> </key> <value> <string></string> </value> </item> </dictionary> </value> </item> <item> <key> <string>tales</string> </key> <value> <dictionary> <item> <key> <string>field_id</string> </key> <value> <string></string> </value> </item> <item> <key> <string>form_id</string> </key> <value> <string></string> </value> </item> <item> <key> <string>target</string> </key> <value> <string></string> </value> </item> </dictionary> </value> </item> <item> <key> <string>values</string> </key> <value> <dictionary> <item> <key> <string>field_id</string> </key> <value> <string>my_activity</string> </value> </item> <item> <key> <string>form_id</string> </key> <value> <string>PurchaseTradeCondition_viewFieldLibrary</string> </value> </item> <item> <key> <string>target</string> </key> <value> <string>Click to edit the target</string> </value> </item> </dictionary> </value> </item> </dictionary> </pickle> </record> </ZopeData>
{ "pile_set_name": "Github" }
package com.geniusgithub.mediaplayer.widget; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RadialGradient; import android.graphics.Shader; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.OvalShape; import android.os.Build; import android.support.v4.view.ViewCompat; import android.util.AttributeSet; import android.view.animation.LinearInterpolator; import android.widget.ImageView; public class ShadowImageView extends ImageView { private static final int KEY_SHADOW_COLOR = 0x1E000000; private static final int FILL_SHADOW_COLOR = 0x3D000000; private static final float X_OFFSET = 0f; private static final float Y_OFFSET = 1.75f; private static final float SHADOW_RADIUS = 24f; private static final int SHADOW_ELEVATION = 16; // private static final int DEFAULT_BACKGROUND_COLOR = 0xFF3C5F78; private static final int DEFAULT_BACKGROUND_COLOR = 0x00000000; private int mShadowRadius; // Animation private ObjectAnimator mRotateAnimator; private long mLastAnimationValue; public ShadowImageView(Context context) { this(context, null); } public ShadowImageView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public ShadowImageView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) @SuppressWarnings("unused") public ShadowImageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(); } private void init() { final float density = getContext().getResources().getDisplayMetrics().density; final int shadowXOffset = (int) (density * X_OFFSET); final int shadowYOffset = (int) (density * Y_OFFSET); mShadowRadius = (int) (density * SHADOW_RADIUS); ShapeDrawable circle; if (elevationSupported()) { circle = new ShapeDrawable(new OvalShape()); ViewCompat.setElevation(this, SHADOW_ELEVATION * density); } else { OvalShape oval = new OvalShadow(mShadowRadius); circle = new ShapeDrawable(oval); ViewCompat.setLayerType(this, ViewCompat.LAYER_TYPE_SOFTWARE, circle.getPaint()); circle.getPaint().setShadowLayer(mShadowRadius, shadowXOffset, shadowYOffset, KEY_SHADOW_COLOR); final int padding = mShadowRadius; // set padding so the inner image sits correctly within the shadow. setPadding(padding, padding, padding, padding); } circle.getPaint().setAntiAlias(true); circle.getPaint().setColor(DEFAULT_BACKGROUND_COLOR); if (getBackground() == null){ setBackground(circle); } mRotateAnimator = ObjectAnimator.ofFloat(this, "rotation", 0f, 360f); mRotateAnimator.setDuration(3600); mRotateAnimator.setInterpolator(new LinearInterpolator()); mRotateAnimator.setRepeatMode(ValueAnimator.RESTART); mRotateAnimator.setRepeatCount(ValueAnimator.INFINITE); } private boolean elevationSupported() { return android.os.Build.VERSION.SDK_INT >= 21; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); if (!elevationSupported()) { setMeasuredDimension(getMeasuredWidth() + mShadowRadius * 2, getMeasuredHeight() + mShadowRadius * 2); } } // Animation public void startRotateAnimation() { mRotateAnimator.cancel(); mRotateAnimator.start(); } public void cancelRotateAnimation() { mLastAnimationValue = 0; mRotateAnimator.cancel(); } public void pauseRotateAnimation() { mLastAnimationValue = mRotateAnimator.getCurrentPlayTime(); mRotateAnimator.cancel(); } public void resumeRotateAnimation() { mRotateAnimator.start(); mRotateAnimator.setCurrentPlayTime(mLastAnimationValue); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); if (mRotateAnimator != null) { mRotateAnimator.cancel(); mRotateAnimator = null; } } /** * Draw oval shadow below ImageView under lollipop. */ private class OvalShadow extends OvalShape { private RadialGradient mRadialGradient; private Paint mShadowPaint; OvalShadow(int shadowRadius) { super(); mShadowPaint = new Paint(); mShadowRadius = shadowRadius; updateRadialGradient((int) rect().width()); } @Override protected void onResize(float width, float height) { super.onResize(width, height); updateRadialGradient((int) width); } @Override public void draw(Canvas canvas, Paint paint) { final int viewWidth = ShadowImageView.this.getWidth(); final int viewHeight = ShadowImageView.this.getHeight(); canvas.drawCircle(viewWidth / 2, viewHeight / 2, viewWidth / 2, mShadowPaint); canvas.drawCircle(viewWidth / 2, viewHeight / 2, viewWidth / 2 - mShadowRadius, paint); } private void updateRadialGradient(int diameter) { mRadialGradient = new RadialGradient(diameter / 2, diameter / 2, mShadowRadius, new int[]{FILL_SHADOW_COLOR, Color.TRANSPARENT}, null, Shader.TileMode.CLAMP); mShadowPaint.setShader(mRadialGradient); } } }
{ "pile_set_name": "Github" }
import openfl.display.GraphicsEndFill; class GraphicsEndFillTest { public static function __init__() { Mocha.describe("GraphicsEndFill", function() { Mocha.it("new", function() { // TODO: Confirm functionality var endFill = new GraphicsEndFill(); Assert.notEqual(endFill, null); }); }); } }
{ "pile_set_name": "Github" }
--- ../../../openwrt_trunk/package/libs/libconfig/Makefile.orig +++ ../../../openwrt_trunk/package/libs/libconfig/Makefile @@ -52,8 +52,8 @@ endef define Package/libconfig/install - $(INSTALL_DIR) $(1)/usr/lib - $(CP) $(PKG_INSTALL_DIR)/usr/lib/libconfig.so* $(1)/usr/lib/ + $(INSTALL_DIR) $(1)/opt/lib + $(CP) $(PKG_INSTALL_DIR)/opt/lib/libconfig.so* $(1)/opt/lib/ endef $(eval $(call BuildPackage,libconfig))
{ "pile_set_name": "Github" }
/** * Copyright 2014, Yahoo! Inc. * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ import React from 'react'; function About () { return <p>This is a description of the site.</p>; } export default About;
{ "pile_set_name": "Github" }
# try13_no_initial_cocoapods A new flutter project. ## Getting Started For help getting started with Flutter, view our online [documentation](http://flutter.io/).
{ "pile_set_name": "Github" }
@checkout Feature: Selecting an order payment method In order to pay for my order in a convenient way for me As a Customer I want to be able to choose a payment method Background: Given the store operates on a single channel in "United States" And the store has a product "PHP T-Shirt" priced at "$19.99" And the store ships everywhere for free And the store allows paying with "Paypal Express Checkout" And I am a logged in customer @ui @api Scenario: Selecting a payment method Given I have product "PHP T-Shirt" in the cart And I specified the billing address as "Ankh Morpork", "Frost Alley", "90210", "United States" for "Jon Snow" And I select "Free" shipping method And I complete the shipping step When I select "Paypal Express Checkout" payment method And I complete the payment step Then I should be on the checkout complete step
{ "pile_set_name": "Github" }
#include <asm-generic/irq_regs.h>
{ "pile_set_name": "Github" }
/* * Copyright (c) GeoWorks 1992 -- All Rights Reserved * * PROJECT: PC GEOS * MODULE: * FILE: uiWrapTextControl.ui * * AUTHOR: Jon Witort * * REVISION HISTORY: * Name Date Description * ---- ---- ----------- * jon 10 jun 1992 initial perversion * * DESCRIPTION: * UI description for GrObjWrapTextControl stuff * * $Id: uiObscureAttrControl.ui,v 1.1 97/04/04 18:05:31 newdeal Exp $ * */ start GrObjObscureAttrControlUI, notDetachable; GrObjObscureAttrBooleanGroup = GenBooleanGroup { genStates = default -usable; children = InstructionBoolean, InsOrDelMoveBoolean, InsOrDelResizeBoolean, InsOrDelDeleteBoolean; applyMsg = MSG_GOOAC_CHANGE_OBSCURE_ATTRS; destination = "TO_OBJ_BLOCK_OUTPUT"; } InstructionBoolean = GenBoolean { #ifdef GPC_INSTRUCTIONS moniker = "Instructions"; #else moniker = 'A', "Annotation"; #endif identifier = "mask GOAF_INSTRUCTION"; } InsOrDelMoveBoolean = GenBoolean { moniker = 'M', "Allow Move During Insert/Delete Space"; identifier = "mask GOAF_INSERT_DELETE_MOVE_ALLOWED"; } InsOrDelResizeBoolean = GenBoolean { moniker = 'R', "Allow Resize During Insert/Delete Space"; identifier = "mask GOAF_INSERT_DELETE_RESIZE_ALLOWED"; } InsOrDelDeleteBoolean = GenBoolean { moniker = 'D', "Allow Delete During Insert/Delete Space"; identifier = "mask GOAF_INSERT_DELETE_DELETE_ALLOWED"; } GrObjWrapTextList = GenItemGroup { genStates = default -usable; children = WrapTightlyItem, WrapAroundRectItem, WrapInsideItem, DontWrapItem; moniker = 'W', "Wrap Text Type"; applyMsg = MSG_GOOAC_SET_WRAP_TEXT_TYPE; destination = "TO_OBJ_BLOCK_OUTPUT"; } WrapTightlyItem = GenItem { moniker = 'T', "Wrap Tightly"; identifier = GOWTT_WRAP_AROUND_TIGHTLY; } WrapAroundRectItem = GenItem { moniker = 'R', "Wrap Around Rectangle"; identifier = GOWTT_WRAP_AROUND_RECT; } WrapInsideItem = GenItem { moniker = 'I', "Wrap Inside Object"; identifier = GOWTT_WRAP_INSIDE; } DontWrapItem = GenItem { moniker = 'D', "Don't Wrap"; identifier = GOWTT_DONT_WRAP; } end GrObjObscureAttrControlUI; start GrObjControlUIStrings, data; chunk GOOACName = "Obscure Object Attributes"; chunk InstructionName = "Annotation"; chunk InsOrDelMoveName = "Allow Move during Insert/Delete"; chunk InsOrDelResizeName = "Allow Resize during Insert/Delete"; chunk InsOrDelDeleteName = "Allow Delete during Insert/Delete"; chunk WrapTightlyName = "Wrap Tightly"; chunk WrapAroundRectName = "Wrap Around Rectangle"; chunk WrapInsideName = "Wrap Inside Object"; chunk DontWrapName = "Don't Wrap"; end GrObjControlUIStrings;
{ "pile_set_name": "Github" }
#include <nano/crypto_lib/random_pool.hpp> #include <nano/lib/threading.hpp> #include <nano/node/election.hpp> #include <nano/node/testing.hpp> #include <nano/node/transport/udp.hpp> #include <nano/test_common/testutil.hpp> #include <gtest/gtest.h> #include <boost/format.hpp> #include <boost/unordered_set.hpp> #include <numeric> #include <random> using namespace std::chrono_literals; TEST (system, generate_mass_activity) { nano::system system; nano::node_config node_config (nano::get_available_port (), system.logging); node_config.enable_voting = false; // Prevent blocks cementing auto node = system.add_node (node_config); system.wallet (0)->insert_adhoc (nano::dev_genesis_key.prv); uint32_t count (20); system.generate_mass_activity (count, *system.nodes[0]); auto transaction (system.nodes[0]->store.tx_begin_read ()); for (auto i (system.nodes[0]->store.latest_begin (transaction)), n (system.nodes[0]->store.latest_end ()); i != n; ++i) { } } TEST (system, generate_mass_activity_long) { nano::system system; nano::node_config node_config (nano::get_available_port (), system.logging); node_config.enable_voting = false; // Prevent blocks cementing auto node = system.add_node (node_config); system.wallet (0)->wallets.watcher->stop (); // Stop work watcher nano::thread_runner runner (system.io_ctx, system.nodes[0]->config.io_threads); system.wallet (0)->insert_adhoc (nano::dev_genesis_key.prv); uint32_t count (1000000000); system.generate_mass_activity (count, *system.nodes[0]); auto transaction (system.nodes[0]->store.tx_begin_read ()); for (auto i (system.nodes[0]->store.latest_begin (transaction)), n (system.nodes[0]->store.latest_end ()); i != n; ++i) { } system.stop (); runner.join (); } TEST (system, receive_while_synchronizing) { std::vector<boost::thread> threads; { nano::system system; nano::node_config node_config (nano::get_available_port (), system.logging); node_config.enable_voting = false; // Prevent blocks cementing auto node = system.add_node (node_config); nano::thread_runner runner (system.io_ctx, system.nodes[0]->config.io_threads); system.wallet (0)->insert_adhoc (nano::dev_genesis_key.prv); uint32_t count (1000); system.generate_mass_activity (count, *system.nodes[0]); nano::keypair key; auto node1 (std::make_shared<nano::node> (system.io_ctx, nano::get_available_port (), nano::unique_path (), system.alarm, system.logging, system.work)); ASSERT_FALSE (node1->init_error ()); auto channel (std::make_shared<nano::transport::channel_udp> (node1->network.udp_channels, system.nodes[0]->network.endpoint (), node1->network_params.protocol.protocol_version)); node1->network.send_keepalive (channel); auto wallet (node1->wallets.create (1)); wallet->insert_adhoc (nano::dev_genesis_key.prv); // For voting ASSERT_EQ (key.pub, wallet->insert_adhoc (key.prv)); node1->start (); system.nodes.push_back (node1); system.alarm.add (std::chrono::steady_clock::now () + std::chrono::milliseconds (200), ([&system, &key]() { auto hash (system.wallet (0)->send_sync (nano::dev_genesis_key.pub, key.pub, system.nodes[0]->config.receive_minimum.number ())); auto transaction (system.nodes[0]->store.tx_begin_read ()); auto block (system.nodes[0]->store.block_get (transaction, hash)); std::string block_text; block->serialize_json (block_text); })); ASSERT_TIMELY (10s, !node1->balance (key.pub).is_zero ()); node1->stop (); system.stop (); runner.join (); } for (auto i (threads.begin ()), n (threads.end ()); i != n; ++i) { i->join (); } } TEST (ledger, deep_account_compute) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_FALSE (store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair key; auto balance (nano::genesis_amount - 1); nano::send_block send (genesis.hash (), key.pub, balance, nano::dev_genesis_key.prv, nano::dev_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send).code); nano::open_block open (send.hash (), nano::dev_genesis_key.pub, key.pub, key.prv, key.pub, *pool.generate (key.pub)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, open).code); auto sprevious (send.hash ()); auto rprevious (open.hash ()); for (auto i (0), n (100000); i != n; ++i) { balance -= 1; nano::send_block send (sprevious, key.pub, balance, nano::dev_genesis_key.prv, nano::dev_genesis_key.pub, *pool.generate (sprevious)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send).code); sprevious = send.hash (); nano::receive_block receive (rprevious, send.hash (), key.prv, key.pub, *pool.generate (rprevious)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, receive).code); rprevious = receive.hash (); if (i % 100 == 0) { std::cerr << i << ' '; } ledger.account (transaction, sprevious); ledger.balance (transaction, rprevious); } } TEST (wallet, multithreaded_send_async) { std::vector<boost::thread> threads; { nano::system system (1); nano::keypair key; auto wallet_l (system.wallet (0)); wallet_l->insert_adhoc (nano::dev_genesis_key.prv); wallet_l->insert_adhoc (key.prv); for (auto i (0); i < 20; ++i) { threads.push_back (boost::thread ([wallet_l, &key]() { for (auto i (0); i < 1000; ++i) { wallet_l->send_async (nano::dev_genesis_key.pub, key.pub, 1000, [](std::shared_ptr<nano::block> block_a) { ASSERT_FALSE (block_a == nullptr); ASSERT_FALSE (block_a->hash ().is_zero ()); }); } })); } ASSERT_TIMELY (1000s, system.nodes[0]->balance (nano::dev_genesis_key.pub) == (nano::genesis_amount - 20 * 1000 * 1000)); } for (auto i (threads.begin ()), n (threads.end ()); i != n; ++i) { i->join (); } } TEST (store, load) { nano::system system (1); std::vector<boost::thread> threads; for (auto i (0); i < 100; ++i) { threads.push_back (boost::thread ([&system]() { for (auto i (0); i != 1000; ++i) { auto transaction (system.nodes[0]->store.tx_begin_write ()); for (auto j (0); j != 10; ++j) { nano::account account; nano::random_pool::generate_block (account.bytes.data (), account.bytes.size ()); system.nodes[0]->store.confirmation_height_put (transaction, account, { 0, nano::block_hash (0) }); system.nodes[0]->store.account_put (transaction, account, nano::account_info ()); } } })); } for (auto & i : threads) { i.join (); } } // ulimit -n increasing may be required TEST (node, fork_storm) { nano::node_flags flags; flags.disable_max_peers_per_ip = true; nano::system system (64, nano::transport::transport_type::tcp, flags); system.wallet (0)->insert_adhoc (nano::dev_genesis_key.prv); auto previous (system.nodes[0]->latest (nano::dev_genesis_key.pub)); auto balance (system.nodes[0]->balance (nano::dev_genesis_key.pub)); ASSERT_FALSE (previous.is_zero ()); for (auto j (0); j != system.nodes.size (); ++j) { balance -= 1; nano::keypair key; nano::send_block send (previous, key.pub, balance, nano::dev_genesis_key.prv, nano::dev_genesis_key.pub, 0); system.nodes[j]->work_generate_blocking (send); previous = send.hash (); for (auto i (0); i != system.nodes.size (); ++i) { auto send_result (system.nodes[i]->process (send)); ASSERT_EQ (nano::process_result::progress, send_result.code); nano::keypair rep; auto open (std::make_shared<nano::open_block> (previous, rep.pub, key.pub, key.prv, key.pub, 0)); system.nodes[i]->work_generate_blocking (*open); auto open_result (system.nodes[i]->process (*open)); ASSERT_EQ (nano::process_result::progress, open_result.code); auto transaction (system.nodes[i]->store.tx_begin_read ()); system.nodes[i]->network.flood_block (open); } } auto again (true); int iteration (0); while (again) { auto empty = 0; auto single = 0; std::for_each (system.nodes.begin (), system.nodes.end (), [&](std::shared_ptr<nano::node> const & node_a) { if (node_a->active.empty ()) { ++empty; } else { nano::unique_lock<std::mutex> lock (node_a->active.mutex); auto election = node_a->active.roots.begin ()->election; lock.unlock (); if (election->votes ().size () == 1) { ++single; } } }); ASSERT_NO_ERROR (system.poll ()); if ((iteration & 0xff) == 0) { std::cerr << "Empty: " << empty << " single: " << single << std::endl; } again = empty != 0 || single != 0; ++iteration; } ASSERT_TRUE (true); } namespace { size_t heard_count (std::vector<uint8_t> const & nodes) { auto result (0); for (auto i (nodes.begin ()), n (nodes.end ()); i != n; ++i) { switch (*i) { case 0: break; case 1: ++result; break; case 2: ++result; break; } } return result; } } TEST (broadcast, world_broadcast_simulate) { auto node_count (10000); // 0 = starting state // 1 = heard transaction // 2 = repeated transaction std::vector<uint8_t> nodes; nodes.resize (node_count, 0); nodes[0] = 1; auto any_changed (true); auto message_count (0); while (any_changed) { any_changed = false; for (auto i (nodes.begin ()), n (nodes.end ()); i != n; ++i) { switch (*i) { case 0: break; case 1: for (auto j (nodes.begin ()), m (nodes.end ()); j != m; ++j) { ++message_count; switch (*j) { case 0: *j = 1; any_changed = true; break; case 1: break; case 2: break; } } *i = 2; any_changed = true; break; case 2: break; default: ASSERT_FALSE (true); break; } } } auto count (heard_count (nodes)); (void)count; } TEST (broadcast, sqrt_broadcast_simulate) { auto node_count (10000); auto broadcast_count (std::ceil (std::sqrt (node_count))); // 0 = starting state // 1 = heard transaction // 2 = repeated transaction std::vector<uint8_t> nodes; nodes.resize (node_count, 0); nodes[0] = 1; auto any_changed (true); uint64_t message_count (0); while (any_changed) { any_changed = false; for (auto i (nodes.begin ()), n (nodes.end ()); i != n; ++i) { switch (*i) { case 0: break; case 1: for (auto j (0); j != broadcast_count; ++j) { ++message_count; auto entry (nano::random_pool::generate_word32 (0, node_count - 1)); switch (nodes[entry]) { case 0: nodes[entry] = 1; any_changed = true; break; case 1: break; case 2: break; } } *i = 2; any_changed = true; break; case 2: break; default: ASSERT_FALSE (true); break; } } } auto count (heard_count (nodes)); (void)count; } TEST (peer_container, random_set) { nano::system system (1); auto old (std::chrono::steady_clock::now ()); auto current (std::chrono::steady_clock::now ()); for (auto i (0); i < 10000; ++i) { auto list (system.nodes[0]->network.random_set (15)); } auto end (std::chrono::steady_clock::now ()); (void)end; auto old_ms (std::chrono::duration_cast<std::chrono::milliseconds> (current - old)); (void)old_ms; auto new_ms (std::chrono::duration_cast<std::chrono::milliseconds> (end - current)); (void)new_ms; } // Can take up to 2 hours TEST (store, unchecked_load) { nano::system system (1); auto & node (*system.nodes[0]); auto block (std::make_shared<nano::send_block> (0, 0, 0, nano::dev_genesis_key.prv, nano::dev_genesis_key.pub, 0)); constexpr auto num_unchecked = 1000000; for (auto i (0); i < 1000000; ++i) { auto transaction (node.store.tx_begin_write ()); node.store.unchecked_put (transaction, i, block); } auto transaction (node.store.tx_begin_read ()); ASSERT_EQ (num_unchecked, node.store.unchecked_count (transaction)); } TEST (store, vote_load) { nano::system system (1); auto & node (*system.nodes[0]); auto block (std::make_shared<nano::send_block> (0, 0, 0, nano::dev_genesis_key.prv, nano::dev_genesis_key.pub, 0)); for (auto i (0); i < 1000000; ++i) { auto vote (std::make_shared<nano::vote> (nano::dev_genesis_key.pub, nano::dev_genesis_key.prv, i, block)); node.vote_processor.vote (vote, std::make_shared<nano::transport::channel_loopback> (node)); } } TEST (store, pruned_load) { nano::logger_mt logger; auto path (nano::unique_path ()); constexpr auto num_pruned = 2000000; auto const expected_result = nano::using_rocksdb_in_tests () ? num_pruned : num_pruned / 2; constexpr auto batch_size = 20; boost::unordered_set<nano::block_hash> hashes; { auto store = nano::make_store (logger, path); ASSERT_FALSE (store->init_error ()); for (auto i (0); i < num_pruned / batch_size; ++i) { { auto transaction (store->tx_begin_write ()); for (auto k (0); k < batch_size; ++k) { nano::block_hash random_hash; nano::random_pool::generate_block (random_hash.bytes.data (), random_hash.bytes.size ()); store->pruned_put (transaction, random_hash); } } if (!nano::using_rocksdb_in_tests ()) { auto transaction (store->tx_begin_write ()); for (auto k (0); k < batch_size / 2; ++k) { auto hash (hashes.begin ()); store->pruned_del (transaction, *hash); hashes.erase (hash); } } } auto transaction (store->tx_begin_read ()); ASSERT_EQ (expected_result, store->pruned_count (transaction)); } // Reinitialize store { auto store = nano::make_store (logger, path); ASSERT_FALSE (store->init_error ()); auto transaction (store->tx_begin_read ()); ASSERT_EQ (expected_result, store->pruned_count (transaction)); } } TEST (wallets, rep_scan) { nano::system system (1); auto & node (*system.nodes[0]); auto wallet (system.wallet (0)); { auto transaction (node.wallets.tx_begin_write ()); for (auto i (0); i < 10000; ++i) { wallet->deterministic_insert (transaction); } } auto begin (std::chrono::steady_clock::now ()); node.wallets.foreach_representative ([](nano::public_key const & pub_a, nano::raw_key const & prv_a) { }); ASSERT_LT (std::chrono::steady_clock::now () - begin, std::chrono::milliseconds (5)); } TEST (node, mass_vote_by_hash) { nano::system system (1); system.wallet (0)->insert_adhoc (nano::dev_genesis_key.prv); nano::block_hash previous (nano::genesis_hash); nano::keypair key; std::vector<std::shared_ptr<nano::state_block>> blocks; for (auto i (0); i < 10000; ++i) { auto block (std::make_shared<nano::state_block> (nano::dev_genesis_key.pub, previous, nano::dev_genesis_key.pub, nano::genesis_amount - (i + 1) * nano::Gxrb_ratio, key.pub, nano::dev_genesis_key.prv, nano::dev_genesis_key.pub, *system.work.generate (previous))); previous = block->hash (); blocks.push_back (block); } for (auto i (blocks.begin ()), n (blocks.end ()); i != n; ++i) { system.nodes[0]->block_processor.add (*i, nano::seconds_since_epoch ()); } } namespace nano { TEST (confirmation_height, many_accounts_single_confirmation) { nano::system system; nano::node_config node_config (nano::get_available_port (), system.logging); node_config.online_weight_minimum = 100; node_config.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled; auto node = system.add_node (node_config); system.wallet (0)->insert_adhoc (nano::dev_genesis_key.prv); // The number of frontiers should be more than the nano::confirmation_height::unbounded_cutoff to test the amount of blocks confirmed is correct. node->confirmation_height_processor.batch_write_size = 500; auto const num_accounts = nano::confirmation_height::unbounded_cutoff * 2 + 50; nano::keypair last_keypair = nano::dev_genesis_key; auto last_open_hash = node->latest (nano::dev_genesis_key.pub); { auto transaction = node->store.tx_begin_write (); for (auto i = num_accounts - 1; i > 0; --i) { nano::keypair key; system.wallet (0)->insert_adhoc (key.prv); nano::send_block send (last_open_hash, key.pub, node->config.online_weight_minimum.number (), last_keypair.prv, last_keypair.pub, *system.work.generate (last_open_hash)); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send).code); nano::open_block open (send.hash (), last_keypair.pub, key.pub, key.prv, key.pub, *system.work.generate (key.pub)); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, open).code); last_open_hash = open.hash (); last_keypair = key; } } // Call block confirm on the last open block which will confirm everything { auto block = node->block (last_open_hash); ASSERT_NE (nullptr, block); auto election_insertion_result (node->active.insert (block)); ASSERT_TRUE (election_insertion_result.inserted); ASSERT_NE (nullptr, election_insertion_result.election); election_insertion_result.election->force_confirm (); } ASSERT_TIMELY (120s, node->ledger.block_confirmed (node->store.tx_begin_read (), last_open_hash)); // All frontiers (except last) should have 2 blocks and both should be confirmed auto transaction = node->store.tx_begin_read (); for (auto i (node->store.latest_begin (transaction)), n (node->store.latest_end ()); i != n; ++i) { auto & account = i->first; auto & account_info = i->second; auto count = (account != last_keypair.pub) ? 2 : 1; nano::confirmation_height_info confirmation_height_info; ASSERT_FALSE (node->store.confirmation_height_get (transaction, account, confirmation_height_info)); ASSERT_EQ (count, confirmation_height_info.height); ASSERT_EQ (count, account_info.block_count); } auto cemented_count = 0; for (auto i (node->ledger.store.confirmation_height_begin (transaction)), n (node->ledger.store.confirmation_height_end ()); i != n; ++i) { cemented_count += i->second.height; } ASSERT_EQ (cemented_count, node->ledger.cache.cemented_count); ASSERT_EQ (node->ledger.stats.count (nano::stat::type::confirmation_height, nano::stat::detail::blocks_confirmed, nano::stat::dir::in), num_accounts * 2 - 2); ASSERT_EQ (node->ledger.stats.count (nano::stat::type::confirmation_height, nano::stat::detail::blocks_confirmed_bounded, nano::stat::dir::in), num_accounts * 2 - 2); ASSERT_EQ (node->ledger.stats.count (nano::stat::type::confirmation_height, nano::stat::detail::blocks_confirmed_unbounded, nano::stat::dir::in), 0); ASSERT_TIMELY (40s, (node->ledger.cache.cemented_count - 1) == node->stats.count (nano::stat::type::confirmation_observer, nano::stat::detail::all, nano::stat::dir::out)); ASSERT_TIMELY (10s, node->active.election_winner_details_size () == 0); } TEST (confirmation_height, many_accounts_many_confirmations) { nano::system system; nano::node_config node_config (nano::get_available_port (), system.logging); node_config.online_weight_minimum = 100; node_config.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled; auto node = system.add_node (node_config); system.wallet (0)->insert_adhoc (nano::dev_genesis_key.prv); node->confirmation_height_processor.batch_write_size = 500; auto const num_accounts = nano::confirmation_height::unbounded_cutoff * 2 + 50; auto ladev_genesis = node->latest (nano::dev_genesis_key.pub); std::vector<std::shared_ptr<nano::open_block>> open_blocks; { auto transaction = node->store.tx_begin_write (); for (auto i = num_accounts - 1; i > 0; --i) { nano::keypair key; system.wallet (0)->insert_adhoc (key.prv); nano::send_block send (ladev_genesis, key.pub, node->config.online_weight_minimum.number (), nano::dev_genesis_key.prv, nano::dev_genesis_key.pub, *system.work.generate (ladev_genesis)); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send).code); auto open = std::make_shared<nano::open_block> (send.hash (), nano::dev_genesis_key.pub, key.pub, key.prv, key.pub, *system.work.generate (key.pub)); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, *open).code); open_blocks.push_back (std::move (open)); ladev_genesis = send.hash (); } } // Confirm all of the accounts for (auto & open_block : open_blocks) { auto election_insertion_result (node->active.insert (open_block)); ASSERT_TRUE (election_insertion_result.inserted); ASSERT_NE (nullptr, election_insertion_result.election); election_insertion_result.election->force_confirm (); } auto const num_blocks_to_confirm = (num_accounts - 1) * 2; ASSERT_TIMELY (1500s, node->stats.count (nano::stat::type::confirmation_height, nano::stat::detail::blocks_confirmed, nano::stat::dir::in) == num_blocks_to_confirm); auto num_confirmed_bounded = node->ledger.stats.count (nano::stat::type::confirmation_height, nano::stat::detail::blocks_confirmed_bounded, nano::stat::dir::in); ASSERT_GE (num_confirmed_bounded, nano::confirmation_height::unbounded_cutoff); ASSERT_EQ (node->ledger.stats.count (nano::stat::type::confirmation_height, nano::stat::detail::blocks_confirmed_unbounded, nano::stat::dir::in), num_blocks_to_confirm - num_confirmed_bounded); ASSERT_TIMELY (60s, (node->ledger.cache.cemented_count - 1) == node->stats.count (nano::stat::type::confirmation_observer, nano::stat::detail::all, nano::stat::dir::out)); auto transaction = node->store.tx_begin_read (); auto cemented_count = 0; for (auto i (node->ledger.store.confirmation_height_begin (transaction)), n (node->ledger.store.confirmation_height_end ()); i != n; ++i) { cemented_count += i->second.height; } ASSERT_EQ (num_blocks_to_confirm + 1, cemented_count); ASSERT_EQ (cemented_count, node->ledger.cache.cemented_count); ASSERT_TIMELY (20s, (node->ledger.cache.cemented_count - 1) == node->stats.count (nano::stat::type::confirmation_observer, nano::stat::detail::all, nano::stat::dir::out)); ASSERT_TIMELY (10s, node->active.election_winner_details_size () == 0); } TEST (confirmation_height, long_chains) { nano::system system; nano::node_config node_config (nano::get_available_port (), system.logging); node_config.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled; auto node = system.add_node (node_config); nano::keypair key1; system.wallet (0)->insert_adhoc (nano::dev_genesis_key.prv); nano::block_hash latest (node->latest (nano::dev_genesis_key.pub)); system.wallet (0)->insert_adhoc (key1.prv); node->confirmation_height_processor.batch_write_size = 500; auto const num_blocks = nano::confirmation_height::unbounded_cutoff * 2 + 50; // First open the other account nano::send_block send (latest, key1.pub, nano::genesis_amount - nano::Gxrb_ratio + num_blocks + 1, nano::dev_genesis_key.prv, nano::dev_genesis_key.pub, *system.work.generate (latest)); nano::open_block open (send.hash (), nano::genesis_account, key1.pub, key1.prv, key1.pub, *system.work.generate (key1.pub)); { auto transaction = node->store.tx_begin_write (); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, open).code); } // Bulk send from genesis account to destination account auto previous_genesis_chain_hash = send.hash (); auto previous_destination_chain_hash = open.hash (); { auto transaction = node->store.tx_begin_write (); for (auto i = num_blocks - 1; i > 0; --i) { nano::send_block send (previous_genesis_chain_hash, key1.pub, nano::genesis_amount - nano::Gxrb_ratio + i + 1, nano::dev_genesis_key.prv, nano::dev_genesis_key.pub, *system.work.generate (previous_genesis_chain_hash)); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send).code); nano::receive_block receive (previous_destination_chain_hash, send.hash (), key1.prv, key1.pub, *system.work.generate (previous_destination_chain_hash)); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, receive).code); previous_genesis_chain_hash = send.hash (); previous_destination_chain_hash = receive.hash (); } } // Send one from destination to genesis and pocket it nano::send_block send1 (previous_destination_chain_hash, nano::dev_genesis_key.pub, nano::Gxrb_ratio - 2, key1.prv, key1.pub, *system.work.generate (previous_destination_chain_hash)); auto receive1 (std::make_shared<nano::state_block> (nano::dev_genesis_key.pub, previous_genesis_chain_hash, nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio + 1, send1.hash (), nano::dev_genesis_key.prv, nano::dev_genesis_key.pub, *system.work.generate (previous_genesis_chain_hash))); // Unpocketed. Send to a non-existing account to prevent auto receives from the wallet adjusting expected confirmation height nano::keypair key2; nano::state_block send2 (nano::genesis_account, receive1->hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio, key2.pub, nano::dev_genesis_key.prv, nano::dev_genesis_key.pub, *system.work.generate (receive1->hash ())); { auto transaction = node->store.tx_begin_write (); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send1).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, *receive1).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send2).code); } // Call block confirm on the existing receive block on the genesis account which will confirm everything underneath on both accounts { auto election_insertion_result (node->active.insert (receive1)); ASSERT_TRUE (election_insertion_result.inserted); ASSERT_NE (nullptr, election_insertion_result.election); election_insertion_result.election->force_confirm (); } ASSERT_TIMELY (30s, node->ledger.block_confirmed (node->store.tx_begin_read (), receive1->hash ())); auto transaction (node->store.tx_begin_read ()); nano::account_info account_info; ASSERT_FALSE (node->store.account_get (transaction, nano::dev_genesis_key.pub, account_info)); nano::confirmation_height_info confirmation_height_info; ASSERT_FALSE (node->store.confirmation_height_get (transaction, nano::dev_genesis_key.pub, confirmation_height_info)); ASSERT_EQ (num_blocks + 2, confirmation_height_info.height); ASSERT_EQ (num_blocks + 3, account_info.block_count); // Includes the unpocketed send ASSERT_FALSE (node->store.account_get (transaction, key1.pub, account_info)); ASSERT_FALSE (node->store.confirmation_height_get (transaction, key1.pub, confirmation_height_info)); ASSERT_EQ (num_blocks + 1, confirmation_height_info.height); ASSERT_EQ (num_blocks + 1, account_info.block_count); auto cemented_count = 0; for (auto i (node->ledger.store.confirmation_height_begin (transaction)), n (node->ledger.store.confirmation_height_end ()); i != n; ++i) { cemented_count += i->second.height; } ASSERT_EQ (cemented_count, node->ledger.cache.cemented_count); ASSERT_EQ (node->ledger.stats.count (nano::stat::type::confirmation_height, nano::stat::detail::blocks_confirmed, nano::stat::dir::in), num_blocks * 2 + 2); ASSERT_EQ (node->ledger.stats.count (nano::stat::type::confirmation_height, nano::stat::detail::blocks_confirmed_bounded, nano::stat::dir::in), num_blocks * 2 + 2); ASSERT_EQ (node->ledger.stats.count (nano::stat::type::confirmation_height, nano::stat::detail::blocks_confirmed_unbounded, nano::stat::dir::in), 0); ASSERT_TIMELY (40s, (node->ledger.cache.cemented_count - 1) == node->stats.count (nano::stat::type::confirmation_observer, nano::stat::detail::all, nano::stat::dir::out)); ASSERT_TIMELY (10s, node->active.election_winner_details_size () == 0); } TEST (confirmation_height, dynamic_algorithm) { nano::system system; nano::node_config node_config (nano::get_available_port (), system.logging); node_config.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled; auto node = system.add_node (node_config); nano::genesis genesis; nano::keypair key; system.wallet (0)->insert_adhoc (nano::dev_genesis_key.prv); auto const num_blocks = nano::confirmation_height::unbounded_cutoff; auto ladev_genesis = node->latest (nano::dev_genesis_key.pub); std::vector<std::shared_ptr<nano::state_block>> state_blocks; for (auto i = 0; i < num_blocks; ++i) { auto send (std::make_shared<nano::state_block> (nano::dev_genesis_key.pub, ladev_genesis, nano::dev_genesis_key.pub, nano::genesis_amount - i - 1, key.pub, nano::dev_genesis_key.prv, nano::dev_genesis_key.pub, *system.work.generate (ladev_genesis))); ladev_genesis = send->hash (); state_blocks.push_back (send); } { auto transaction = node->store.tx_begin_write (); for (auto const & block : state_blocks) { ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, *block).code); } } node->confirmation_height_processor.add (state_blocks.front ()->hash ()); ASSERT_TIMELY (20s, node->ledger.cache.cemented_count == 2); node->confirmation_height_processor.add (ladev_genesis); ASSERT_TIMELY (20s, node->ledger.cache.cemented_count == num_blocks + 1); ASSERT_EQ (node->ledger.stats.count (nano::stat::type::confirmation_height, nano::stat::detail::blocks_confirmed, nano::stat::dir::in), num_blocks); ASSERT_EQ (node->ledger.stats.count (nano::stat::type::confirmation_height, nano::stat::detail::blocks_confirmed_bounded, nano::stat::dir::in), 1); ASSERT_EQ (node->ledger.stats.count (nano::stat::type::confirmation_height, nano::stat::detail::blocks_confirmed_unbounded, nano::stat::dir::in), num_blocks - 1); ASSERT_TIMELY (10s, node->active.election_winner_details_size () == 0); } /* * This tests an issue of incorrect cemented block counts during the transition of conf height algorithms * The scenario was as follows: * - There is at least 1 pending write entry in the unbounded conf height processor * - 0 blocks currently awaiting processing in the main conf height processor class * - A block was confirmed when hit the chain in the pending write above but was not a block higher than it. * - It must be in `confirmation_height_processor::pause ()` function so that `pause` is set (and the difference between the number * of blocks uncemented is > unbounded_cutoff so that it hits the bounded processor), the main `run` loop on the conf height processor is iterated. * * This cause unbounded pending entries not to be written, and then the bounded processor would write them, causing some inconsistencies. */ TEST (confirmation_height, dynamic_algorithm_no_transition_while_pending) { // Repeat in case of intermittent issues not replicating the issue talked about above. for (auto _ = 0; _ < 3; ++_) { nano::system system; nano::node_config node_config (nano::get_available_port (), system.logging); node_config.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled; nano::node_flags node_flags; node_flags.force_use_write_database_queue = true; auto node = system.add_node (node_config, node_flags); nano::keypair key; system.wallet (0)->insert_adhoc (nano::dev_genesis_key.prv); auto ladev_genesis = node->latest (nano::dev_genesis_key.pub); std::vector<std::shared_ptr<nano::state_block>> state_blocks; auto const num_blocks = nano::confirmation_height::unbounded_cutoff - 2; auto add_block_to_genesis_chain = [&](nano::write_transaction & transaction) { static int num = 0; auto send (std::make_shared<nano::state_block> (nano::dev_genesis_key.pub, ladev_genesis, nano::dev_genesis_key.pub, nano::genesis_amount - num - 1, key.pub, nano::dev_genesis_key.prv, nano::dev_genesis_key.pub, *system.work.generate (ladev_genesis))); ladev_genesis = send->hash (); state_blocks.push_back (send); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, *send).code); ++num; }; for (auto i = 0; i < num_blocks; ++i) { auto transaction = node->store.tx_begin_write (); add_block_to_genesis_chain (transaction); } { auto write_guard = node->write_database_queue.wait (nano::writer::testing); // To limit any data races we are not calling node.block_confirm node->confirmation_height_processor.add (state_blocks.back ()->hash ()); nano::timer<> timer; timer.start (); while (node->confirmation_height_processor.current ().is_zero ()) { ASSERT_LT (timer.since_start (), 2s); } // Pausing prevents any writes in the outer while loop in the confirmation height processor (implementation detail) node->confirmation_height_processor.pause (); timer.restart (); ASSERT_TIMELY (10s, node->confirmation_height_processor.unbounded_processor.pending_writes_size != 0); { // Make it so that the number of blocks exceed the unbounded cutoff would go into the bounded processor (but shouldn't due to unbounded pending writes) auto transaction = node->store.tx_begin_write (); add_block_to_genesis_chain (transaction); add_block_to_genesis_chain (transaction); } // Make sure this is at a height lower than the block in the add () call above node->confirmation_height_processor.add (state_blocks.front ()->hash ()); node->confirmation_height_processor.unpause (); } ASSERT_TIMELY (10s, node->ledger.cache.cemented_count == num_blocks + 1); ASSERT_EQ (node->ledger.stats.count (nano::stat::type::confirmation_height, nano::stat::detail::blocks_confirmed, nano::stat::dir::in), num_blocks); ASSERT_EQ (node->ledger.stats.count (nano::stat::type::confirmation_height, nano::stat::detail::blocks_confirmed_bounded, nano::stat::dir::in), 0); ASSERT_EQ (node->ledger.stats.count (nano::stat::type::confirmation_height, nano::stat::detail::blocks_confirmed_unbounded, nano::stat::dir::in), num_blocks); ASSERT_TIMELY (10s, node->active.election_winner_details_size () == 0); } } TEST (confirmation_height, many_accounts_send_receive_self) { nano::system system; nano::node_config node_config (nano::get_available_port (), system.logging); node_config.online_weight_minimum = 100; node_config.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled; node_config.active_elections_size = 400000; nano::node_flags node_flags; node_flags.confirmation_height_processor_mode = nano::confirmation_height_mode::unbounded; auto node = system.add_node (node_config); system.wallet (0)->insert_adhoc (nano::dev_genesis_key.prv); #ifndef NDEBUG auto const num_accounts = 10000; #else auto const num_accounts = 100000; #endif auto ladev_genesis = node->latest (nano::dev_genesis_key.pub); std::vector<nano::keypair> keys; std::vector<std::shared_ptr<nano::open_block>> open_blocks; { auto transaction = node->store.tx_begin_write (); for (auto i = 0; i < num_accounts; ++i) { nano::keypair key; keys.emplace_back (key); nano::send_block send (ladev_genesis, key.pub, nano::genesis_amount - 1 - i, nano::dev_genesis_key.prv, nano::dev_genesis_key.pub, *system.work.generate (ladev_genesis)); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send).code); auto open = std::make_shared<nano::open_block> (send.hash (), nano::dev_genesis_key.pub, key.pub, key.prv, key.pub, *system.work.generate (key.pub)); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, *open).code); open_blocks.push_back (std::move (open)); ladev_genesis = send.hash (); } } // Confirm all of the accounts for (auto & open_block : open_blocks) { node->block_confirm (open_block); auto election = node->active.election (open_block->qualified_root ()); ASSERT_NE (nullptr, election); election->force_confirm (); } system.deadline_set (100s); auto num_blocks_to_confirm = num_accounts * 2; while (node->stats.count (nano::stat::type::confirmation_height, nano::stat::detail::blocks_confirmed, nano::stat::dir::in) != num_blocks_to_confirm) { ASSERT_NO_ERROR (system.poll ()); } std::vector<std::shared_ptr<nano::send_block>> send_blocks; std::vector<std::shared_ptr<nano::receive_block>> receive_blocks; for (int i = 0; i < open_blocks.size (); ++i) { auto open_block = open_blocks[i]; auto & keypair = keys[i]; send_blocks.emplace_back (std::make_shared<nano::send_block> (open_block->hash (), keypair.pub, 1, keypair.prv, keypair.pub, *system.work.generate (open_block->hash ()))); receive_blocks.emplace_back (std::make_shared<nano::receive_block> (send_blocks.back ()->hash (), send_blocks.back ()->hash (), keypair.prv, keypair.pub, *system.work.generate (send_blocks.back ()->hash ()))); } // Now send and receive to self for (int i = 0; i < open_blocks.size (); ++i) { node->process_active (send_blocks[i]); node->process_active (receive_blocks[i]); } system.deadline_set (300s); num_blocks_to_confirm = num_accounts * 4; while (node->stats.count (nano::stat::type::confirmation_height, nano::stat::detail::blocks_confirmed, nano::stat::dir::in) != num_blocks_to_confirm) { ASSERT_NO_ERROR (system.poll ()); } system.deadline_set (200s); while ((node->ledger.cache.cemented_count - 1) != node->stats.count (nano::stat::type::confirmation_observer, nano::stat::detail::all, nano::stat::dir::out)) { ASSERT_NO_ERROR (system.poll ()); } auto transaction = node->store.tx_begin_read (); auto cemented_count = 0; for (auto i (node->ledger.store.confirmation_height_begin (transaction)), n (node->ledger.store.confirmation_height_end ()); i != n; ++i) { cemented_count += i->second.height; } ASSERT_EQ (num_blocks_to_confirm + 1, cemented_count); ASSERT_EQ (cemented_count, node->ledger.cache.cemented_count); system.deadline_set (60s); while ((node->ledger.cache.cemented_count - 1) != node->stats.count (nano::stat::type::confirmation_observer, nano::stat::detail::all, nano::stat::dir::out)) { ASSERT_NO_ERROR (system.poll ()); } system.deadline_set (60s); while (node->active.election_winner_details_size () > 0) { ASSERT_NO_ERROR (system.poll ()); } } // Same as the many_accounts_send_receive_self test, except works on the confirmation height processor directly // as opposed to active transactions which implicitly calls confirmation height processor. TEST (confirmation_height, many_accounts_send_receive_self_no_elections) { if (nano::using_rocksdb_in_tests ()) { // Don't test this in rocksdb mode return; } nano::logger_mt logger; auto path (nano::unique_path ()); auto store = nano::make_store (logger, path); ASSERT_TRUE (!store->init_error ()); nano::genesis genesis; nano::stat stats; nano::ledger ledger (*store, stats); nano::write_database_queue write_database_queue (false); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); std::atomic<bool> stopped{ false }; boost::latch initialized_latch{ 0 }; nano::block_hash block_hash_being_processed{ 0 }; nano::confirmation_height_processor confirmation_height_processor{ ledger, write_database_queue, 10ms, logger, initialized_latch, confirmation_height_mode::automatic }; auto const num_accounts = 100000; auto ladev_genesis = nano::genesis_hash; std::vector<nano::keypair> keys; std::vector<std::shared_ptr<nano::open_block>> open_blocks; nano::system system; { auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.cache); // Send from genesis account to all other accounts and create open block for them for (auto i = 0; i < num_accounts; ++i) { nano::keypair key; keys.emplace_back (key); nano::send_block send (ladev_genesis, key.pub, nano::genesis_amount - 1 - i, nano::dev_genesis_key.prv, nano::dev_genesis_key.pub, *pool.generate (ladev_genesis)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send).code); auto open = std::make_shared<nano::open_block> (send.hash (), nano::dev_genesis_key.pub, key.pub, key.prv, key.pub, *pool.generate (key.pub)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, *open).code); open_blocks.push_back (std::move (open)); ladev_genesis = send.hash (); } } for (auto & open_block : open_blocks) { confirmation_height_processor.add (open_block->hash ()); } system.deadline_set (1000s); auto num_blocks_to_confirm = num_accounts * 2; while (stats.count (nano::stat::type::confirmation_height, nano::stat::detail::blocks_confirmed, nano::stat::dir::in) != num_blocks_to_confirm) { ASSERT_NO_ERROR (system.poll ()); } std::vector<std::shared_ptr<nano::send_block>> send_blocks; std::vector<std::shared_ptr<nano::receive_block>> receive_blocks; // Now add all send/receive blocks { auto transaction (store->tx_begin_write ()); for (int i = 0; i < open_blocks.size (); ++i) { auto open_block = open_blocks[i]; auto & keypair = keys[i]; send_blocks.emplace_back (std::make_shared<nano::send_block> (open_block->hash (), keypair.pub, 1, keypair.prv, keypair.pub, *system.work.generate (open_block->hash ()))); receive_blocks.emplace_back (std::make_shared<nano::receive_block> (send_blocks.back ()->hash (), send_blocks.back ()->hash (), keypair.prv, keypair.pub, *system.work.generate (send_blocks.back ()->hash ()))); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, *send_blocks.back ()).code); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, *receive_blocks.back ()).code); } } // Randomize the order that send and receive blocks are added to the confirmation height processor std::random_device rd; std::mt19937 g (rd ()); std::shuffle (send_blocks.begin (), send_blocks.end (), g); std::mt19937 g1 (rd ()); std::shuffle (receive_blocks.begin (), receive_blocks.end (), g1); // Now send and receive to self for (int i = 0; i < open_blocks.size (); ++i) { confirmation_height_processor.add (send_blocks[i]->hash ()); confirmation_height_processor.add (receive_blocks[i]->hash ()); } system.deadline_set (1000s); num_blocks_to_confirm = num_accounts * 4; while (stats.count (nano::stat::type::confirmation_height, nano::stat::detail::blocks_confirmed, nano::stat::dir::in) != num_blocks_to_confirm) { ASSERT_NO_ERROR (system.poll ()); } while (!confirmation_height_processor.current ().is_zero ()) { ASSERT_NO_ERROR (system.poll ()); } auto transaction = store->tx_begin_read (); auto cemented_count = 0; for (auto i (store->confirmation_height_begin (transaction)), n (store->confirmation_height_end ()); i != n; ++i) { cemented_count += i->second.height; } ASSERT_EQ (num_blocks_to_confirm + 1, cemented_count); ASSERT_EQ (cemented_count, ledger.cache.cemented_count); } // Can take up to 1 hour (recommend modifying test work difficulty base level to speed this up) TEST (confirmation_height, prioritize_frontiers_overwrite) { nano::system system; nano::node_config node_config (nano::get_available_port (), system.logging); node_config.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled; auto node = system.add_node (node_config); system.wallet (0)->insert_adhoc (nano::dev_genesis_key.prv); auto num_accounts = node->active.max_priority_cementable_frontiers * 2; nano::keypair last_keypair = nano::dev_genesis_key; auto last_open_hash = node->latest (nano::dev_genesis_key.pub); // Clear confirmation height so that the genesis account has the same amount of uncemented blocks as the other frontiers { auto transaction = node->store.tx_begin_write (); node->store.confirmation_height_clear (transaction); } { auto transaction = node->store.tx_begin_write (); for (auto i = num_accounts - 1; i > 0; --i) { nano::keypair key; system.wallet (0)->insert_adhoc (key.prv); nano::send_block send (last_open_hash, key.pub, nano::Gxrb_ratio - 1, last_keypair.prv, last_keypair.pub, *system.work.generate (last_open_hash)); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send).code); nano::open_block open (send.hash (), last_keypair.pub, key.pub, key.prv, key.pub, *system.work.generate (key.pub)); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, open).code); last_open_hash = open.hash (); last_keypair = key; } } auto transaction = node->store.tx_begin_read (); { // Fill both priority frontier collections. node->active.prioritize_frontiers_for_confirmation (transaction, std::chrono::seconds (60), std::chrono::seconds (60)); ASSERT_EQ (node->active.priority_cementable_frontiers_size () + node->active.priority_wallet_cementable_frontiers_size (), num_accounts); // Confirm the last frontier has the least number of uncemented blocks auto last_frontier_it = node->active.priority_cementable_frontiers.get<1> ().end (); --last_frontier_it; ASSERT_EQ (last_frontier_it->account, last_keypair.pub); ASSERT_EQ (last_frontier_it->blocks_uncemented, 1); } // Add a new frontier with 1 block, it should not be added to the frontier container because it is not higher than any already in the maxed out container nano::keypair key; auto ladev_genesis = node->latest (nano::dev_genesis_key.pub); nano::send_block send (ladev_genesis, key.pub, nano::Gxrb_ratio - 1, nano::dev_genesis_key.prv, nano::dev_genesis_key.pub, *system.work.generate (ladev_genesis)); nano::open_block open (send.hash (), nano::dev_genesis_key.pub, key.pub, key.prv, key.pub, *system.work.generate (key.pub)); { auto transaction = node->store.tx_begin_write (); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, open).code); } transaction.refresh (); node->active.prioritize_frontiers_for_confirmation (transaction, std::chrono::seconds (60), std::chrono::seconds (60)); ASSERT_EQ (node->active.priority_cementable_frontiers_size (), num_accounts / 2); ASSERT_EQ (node->active.priority_wallet_cementable_frontiers_size (), num_accounts / 2); // The account now has an extra block (2 in total) so has 1 more uncemented block than the next smallest frontier in the collection. nano::send_block send1 (send.hash (), key.pub, nano::Gxrb_ratio - 2, nano::dev_genesis_key.prv, nano::dev_genesis_key.pub, *system.work.generate (send.hash ())); nano::receive_block receive (open.hash (), send1.hash (), key.prv, key.pub, *system.work.generate (open.hash ())); { auto transaction = node->store.tx_begin_write (); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send1).code); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, receive).code); } // Confirm that it gets replaced transaction.refresh (); node->active.prioritize_frontiers_for_confirmation (transaction, std::chrono::seconds (60), std::chrono::seconds (60)); ASSERT_EQ (node->active.priority_cementable_frontiers_size (), num_accounts / 2); ASSERT_EQ (node->active.priority_wallet_cementable_frontiers_size (), num_accounts / 2); ASSERT_EQ (node->active.priority_cementable_frontiers.find (last_keypair.pub), node->active.priority_cementable_frontiers.end ()); ASSERT_NE (node->active.priority_cementable_frontiers.find (key.pub), node->active.priority_cementable_frontiers.end ()); // Check there are no matching accounts found in both containers for (auto it = node->active.priority_cementable_frontiers.begin (); it != node->active.priority_cementable_frontiers.end (); ++it) { ASSERT_EQ (node->active.priority_wallet_cementable_frontiers.find (it->account), node->active.priority_wallet_cementable_frontiers.end ()); } } } namespace { class data { public: std::atomic<bool> awaiting_cache{ false }; std::atomic<bool> keep_requesting_metrics{ true }; std::shared_ptr<nano::node> node; std::chrono::system_clock::time_point orig_time; std::atomic_flag orig_time_set = ATOMIC_FLAG_INIT; }; class shared_data { public: nano::util::counted_completion write_completion{ 0 }; std::atomic<bool> done{ false }; }; template <typename T> void callback_process (shared_data & shared_data_a, data & data, T & all_node_data_a, std::chrono::system_clock::time_point last_updated) { if (!data.orig_time_set.test_and_set ()) { data.orig_time = last_updated; } if (data.awaiting_cache && data.orig_time != last_updated) { data.keep_requesting_metrics = false; } if (data.orig_time != last_updated) { data.awaiting_cache = true; data.orig_time = last_updated; } shared_data_a.write_completion.increment (); }; } TEST (telemetry, ongoing_requests) { nano::system system; nano::node_flags node_flags; node_flags.disable_initial_telemetry_requests = true; auto node_client = system.add_node (node_flags); auto node_server = system.add_node (node_flags); wait_peer_connections (system); ASSERT_EQ (0, node_client->telemetry->telemetry_data_size ()); ASSERT_EQ (0, node_server->telemetry->telemetry_data_size ()); ASSERT_EQ (0, node_client->stats.count (nano::stat::type::bootstrap, nano::stat::detail::telemetry_ack, nano::stat::dir::in)); ASSERT_EQ (0, node_client->stats.count (nano::stat::type::bootstrap, nano::stat::detail::telemetry_req, nano::stat::dir::out)); ASSERT_TIMELY (20s, node_client->stats.count (nano::stat::type::message, nano::stat::detail::telemetry_ack, nano::stat::dir::in) == 1 && node_server->stats.count (nano::stat::type::message, nano::stat::detail::telemetry_ack, nano::stat::dir::in) == 1); // Wait till the next ongoing will be called, and add a 1s buffer for the actual processing auto time = std::chrono::steady_clock::now (); ASSERT_TIMELY (10s, std::chrono::steady_clock::now () >= (time + node_client->telemetry->cache_plus_buffer_cutoff_time () + 1s)); ASSERT_EQ (2, node_client->stats.count (nano::stat::type::message, nano::stat::detail::telemetry_ack, nano::stat::dir::in)); ASSERT_EQ (2, node_client->stats.count (nano::stat::type::message, nano::stat::detail::telemetry_req, nano::stat::dir::in)); ASSERT_EQ (2, node_client->stats.count (nano::stat::type::message, nano::stat::detail::telemetry_req, nano::stat::dir::out)); ASSERT_EQ (2, node_server->stats.count (nano::stat::type::message, nano::stat::detail::telemetry_ack, nano::stat::dir::in)); ASSERT_EQ (2, node_server->stats.count (nano::stat::type::message, nano::stat::detail::telemetry_req, nano::stat::dir::in)); ASSERT_EQ (2, node_server->stats.count (nano::stat::type::message, nano::stat::detail::telemetry_req, nano::stat::dir::out)); } namespace nano { namespace transport { TEST (telemetry, simultaneous_requests) { nano::system system; nano::node_flags node_flags; node_flags.disable_initial_telemetry_requests = true; const auto num_nodes = 4; for (int i = 0; i < num_nodes; ++i) { system.add_node (node_flags); } wait_peer_connections (system); std::vector<std::thread> threads; const auto num_threads = 4; std::array<data, num_nodes> node_data{}; for (auto i = 0; i < num_nodes; ++i) { node_data[i].node = system.nodes[i]; } shared_data shared_data; // Create a few threads where each node sends out telemetry request messages to all other nodes continuously, until the cache it reached and subsequently expired. // The test waits until all telemetry_ack messages have been received. for (int i = 0; i < num_threads; ++i) { threads.emplace_back ([&node_data, &shared_data]() { while (std::any_of (node_data.cbegin (), node_data.cend (), [](auto const & data) { return data.keep_requesting_metrics.load (); })) { for (auto & data : node_data) { // Keep calling get_metrics_async until the cache has been saved and then become outdated (after a certain period of time) for each node if (data.keep_requesting_metrics) { shared_data.write_completion.increment_required_count (); // Pick first peer to be consistent auto peer = data.node->network.tcp_channels.channels[0].channel; data.node->telemetry->get_metrics_single_peer_async (peer, [&shared_data, &data, &node_data](nano::telemetry_data_response const & telemetry_data_response_a) { ASSERT_FALSE (telemetry_data_response_a.error); callback_process (shared_data, data, node_data, telemetry_data_response_a.telemetry_data.timestamp); }); } std::this_thread::sleep_for (1ms); } } shared_data.write_completion.await_count_for (20s); shared_data.done = true; }); } ASSERT_TIMELY (30s, shared_data.done); ASSERT_TRUE (std::all_of (node_data.begin (), node_data.end (), [](auto const & data) { return !data.keep_requesting_metrics; })); for (auto & thread : threads) { thread.join (); } } } } TEST (telemetry, under_load) { nano::system system; nano::node_config node_config (nano::get_available_port (), system.logging); node_config.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled; nano::node_flags node_flags; node_flags.disable_initial_telemetry_requests = true; auto node = system.add_node (node_config, node_flags); node_config.peering_port = nano::get_available_port (); auto node1 = system.add_node (node_config, node_flags); nano::genesis genesis; nano::keypair key; nano::keypair key1; system.wallet (0)->insert_adhoc (nano::dev_genesis_key.prv); system.wallet (0)->insert_adhoc (key.prv); auto ladev_genesis = node->latest (nano::dev_genesis_key.pub); auto num_blocks = 150000; auto send (std::make_shared<nano::state_block> (nano::dev_genesis_key.pub, ladev_genesis, nano::dev_genesis_key.pub, nano::genesis_amount - num_blocks, key.pub, nano::dev_genesis_key.prv, nano::dev_genesis_key.pub, *system.work.generate (ladev_genesis))); node->process_active (send); ladev_genesis = send->hash (); auto open (std::make_shared<nano::state_block> (key.pub, 0, key.pub, num_blocks, send->hash (), key.prv, key.pub, *system.work.generate (key.pub))); node->process_active (open); auto latest_key = open->hash (); auto thread_func = [key1, &system, node, num_blocks](nano::keypair const & keypair, nano::block_hash const & latest, nano::uint128_t const initial_amount) { auto latest_l = latest; for (int i = 0; i < num_blocks; ++i) { auto send (std::make_shared<nano::state_block> (keypair.pub, latest_l, keypair.pub, initial_amount - i - 1, key1.pub, keypair.prv, keypair.pub, *system.work.generate (latest_l))); latest_l = send->hash (); node->process_active (send); } }; std::thread thread1 (thread_func, nano::dev_genesis_key, ladev_genesis, nano::genesis_amount - num_blocks); std::thread thread2 (thread_func, key, latest_key, num_blocks); ASSERT_TIMELY (200s, node1->ledger.cache.block_count == num_blocks * 2 + 3); thread1.join (); thread2.join (); for (auto const & node : system.nodes) { ASSERT_EQ (0, node->stats.count (nano::stat::type::telemetry, nano::stat::detail::failed_send_telemetry_req)); ASSERT_EQ (0, node->stats.count (nano::stat::type::telemetry, nano::stat::detail::request_within_protection_cache_zone)); ASSERT_EQ (0, node->stats.count (nano::stat::type::telemetry, nano::stat::detail::unsolicited_telemetry_ack)); ASSERT_EQ (0, node->stats.count (nano::stat::type::telemetry, nano::stat::detail::no_response_received)); } } TEST (telemetry, all_peers_use_single_request_cache) { nano::system system; nano::node_flags node_flags; node_flags.disable_ongoing_telemetry_requests = true; node_flags.disable_initial_telemetry_requests = true; auto node_client = system.add_node (node_flags); auto node_server = system.add_node (node_flags); wait_peer_connections (system); // Request telemetry metrics nano::telemetry_data telemetry_data; { std::atomic<bool> done{ false }; auto channel = node_client->network.find_channel (node_server->network.endpoint ()); node_client->telemetry->get_metrics_single_peer_async (channel, [&done, &telemetry_data](nano::telemetry_data_response const & response_a) { telemetry_data = response_a.telemetry_data; done = true; }); ASSERT_TIMELY (10s, done); } auto responses = node_client->telemetry->get_metrics (); ASSERT_EQ (telemetry_data, responses.begin ()->second); // Confirm only 1 request was made ASSERT_EQ (1, node_client->stats.count (nano::stat::type::message, nano::stat::detail::telemetry_ack, nano::stat::dir::in)); ASSERT_EQ (0, node_client->stats.count (nano::stat::type::message, nano::stat::detail::telemetry_req, nano::stat::dir::in)); ASSERT_EQ (1, node_client->stats.count (nano::stat::type::message, nano::stat::detail::telemetry_req, nano::stat::dir::out)); ASSERT_EQ (0, node_server->stats.count (nano::stat::type::message, nano::stat::detail::telemetry_ack, nano::stat::dir::in)); ASSERT_EQ (1, node_server->stats.count (nano::stat::type::message, nano::stat::detail::telemetry_req, nano::stat::dir::in)); ASSERT_EQ (0, node_server->stats.count (nano::stat::type::message, nano::stat::detail::telemetry_req, nano::stat::dir::out)); std::this_thread::sleep_for (node_server->telemetry->cache_plus_buffer_cutoff_time ()); // Should be empty responses = node_client->telemetry->get_metrics (); ASSERT_TRUE (responses.empty ()); { std::atomic<bool> done{ false }; auto channel = node_client->network.find_channel (node_server->network.endpoint ()); node_client->telemetry->get_metrics_single_peer_async (channel, [&done, &telemetry_data](nano::telemetry_data_response const & response_a) { telemetry_data = response_a.telemetry_data; done = true; }); ASSERT_TIMELY (10s, done); } responses = node_client->telemetry->get_metrics (); ASSERT_EQ (telemetry_data, responses.begin ()->second); ASSERT_EQ (2, node_client->stats.count (nano::stat::type::message, nano::stat::detail::telemetry_ack, nano::stat::dir::in)); ASSERT_EQ (0, node_client->stats.count (nano::stat::type::message, nano::stat::detail::telemetry_req, nano::stat::dir::in)); ASSERT_EQ (2, node_client->stats.count (nano::stat::type::message, nano::stat::detail::telemetry_req, nano::stat::dir::out)); ASSERT_EQ (0, node_server->stats.count (nano::stat::type::message, nano::stat::detail::telemetry_ack, nano::stat::dir::in)); ASSERT_EQ (2, node_server->stats.count (nano::stat::type::message, nano::stat::detail::telemetry_req, nano::stat::dir::in)); ASSERT_EQ (0, node_server->stats.count (nano::stat::type::message, nano::stat::detail::telemetry_req, nano::stat::dir::out)); } TEST (telemetry, many_nodes) { nano::system system; nano::node_flags node_flags; node_flags.disable_ongoing_telemetry_requests = true; node_flags.disable_initial_telemetry_requests = true; node_flags.disable_request_loop = true; // The telemetry responses can timeout if using a large number of nodes under sanitizers, so lower the number. const auto num_nodes = (is_sanitizer_build || nano::running_within_valgrind ()) ? 4 : 10; for (auto i = 0; i < num_nodes; ++i) { nano::node_config node_config (nano::get_available_port (), system.logging); // Make a metric completely different for each node so we can check afterwards that there are no duplicates node_config.bandwidth_limit = 100000 + i; auto node = std::make_shared<nano::node> (system.io_ctx, nano::unique_path (), system.alarm, node_config, system.work, node_flags); node->start (); system.nodes.push_back (node); } // Merge peers after creating nodes as some backends (RocksDB) can take a while to initialize nodes (Windows/Debug for instance) // and timeouts can occur between nodes while starting up many nodes synchronously. for (auto const & node : system.nodes) { for (auto const & other_node : system.nodes) { if (node != other_node) { node->network.merge_peer (other_node->network.endpoint ()); } } } wait_peer_connections (system); // Give all nodes a non-default number of blocks nano::keypair key; nano::genesis genesis; nano::state_block send (nano::dev_genesis_key.pub, genesis.hash (), nano::dev_genesis_key.pub, nano::genesis_amount - nano::Mxrb_ratio, key.pub, nano::dev_genesis_key.prv, nano::dev_genesis_key.pub, *system.work.generate (genesis.hash ())); for (auto node : system.nodes) { auto transaction (node->store.tx_begin_write ()); ASSERT_EQ (nano::process_result::progress, node->ledger.process (transaction, send).code); } // This is the node which will request metrics from all other nodes auto node_client = system.nodes.front (); std::mutex mutex; std::vector<nano::telemetry_data> telemetry_datas; auto peers = node_client->network.list (num_nodes - 1); ASSERT_EQ (peers.size (), num_nodes - 1); for (auto const & peer : peers) { node_client->telemetry->get_metrics_single_peer_async (peer, [&telemetry_datas, &mutex](nano::telemetry_data_response const & response_a) { ASSERT_FALSE (response_a.error); nano::lock_guard<std::mutex> guard (mutex); telemetry_datas.push_back (response_a.telemetry_data); }); } system.deadline_set (20s); nano::unique_lock<std::mutex> lk (mutex); while (telemetry_datas.size () != num_nodes - 1) { lk.unlock (); ASSERT_NO_ERROR (system.poll ()); lk.lock (); } // Check the metrics nano::network_params params; for (auto & data : telemetry_datas) { ASSERT_EQ (data.unchecked_count, 0); ASSERT_EQ (data.cemented_count, 1); ASSERT_LE (data.peer_count, 9); ASSERT_EQ (data.account_count, 1); ASSERT_TRUE (data.block_count == 2); ASSERT_EQ (data.protocol_version, params.protocol.telemetry_protocol_version_min); ASSERT_GE (data.bandwidth_cap, 100000); ASSERT_LT (data.bandwidth_cap, 100000 + system.nodes.size ()); ASSERT_EQ (data.major_version, nano::get_major_node_version ()); ASSERT_EQ (data.minor_version, nano::get_minor_node_version ()); ASSERT_EQ (data.patch_version, nano::get_patch_node_version ()); ASSERT_EQ (data.pre_release_version, nano::get_pre_release_node_version ()); ASSERT_EQ (data.maker, 0); ASSERT_LT (data.uptime, 100); ASSERT_EQ (data.genesis_block, genesis.hash ()); ASSERT_LE (data.timestamp, std::chrono::system_clock::now ()); ASSERT_EQ (data.active_difficulty, system.nodes.front ()->active.active_difficulty ()); } // We gave some nodes different bandwidth caps, confirm they are not all the same auto bandwidth_cap = telemetry_datas.front ().bandwidth_cap; telemetry_datas.erase (telemetry_datas.begin ()); auto all_bandwidth_limits_same = std::all_of (telemetry_datas.begin (), telemetry_datas.end (), [bandwidth_cap](auto & telemetry_data) { return telemetry_data.bandwidth_cap == bandwidth_cap; }); ASSERT_FALSE (all_bandwidth_limits_same); } // Similar to signature_checker.boundary_checks but more exhaustive. Can take up to 1 minute TEST (signature_checker, mass_boundary_checks) { // sizes container must be in incrementing order std::vector<size_t> sizes{ 0, 1 }; auto add_boundary = [&sizes](size_t boundary) { sizes.insert (sizes.end (), { boundary - 1, boundary, boundary + 1 }); }; for (auto i = 1; i <= 10; ++i) { add_boundary (nano::signature_checker::batch_size * i); } for (auto num_threads = 0; num_threads < 5; ++num_threads) { nano::signature_checker checker (num_threads); auto max_size = *(sizes.end () - 1); std::vector<nano::uint256_union> hashes; hashes.reserve (max_size); std::vector<unsigned char const *> messages; messages.reserve (max_size); std::vector<size_t> lengths; lengths.reserve (max_size); std::vector<unsigned char const *> pub_keys; pub_keys.reserve (max_size); std::vector<unsigned char const *> signatures; signatures.reserve (max_size); nano::keypair key; nano::state_block block (key.pub, 0, key.pub, 0, 0, key.prv, key.pub, 0); auto last_size = 0; for (auto size : sizes) { // The size needed to append to existing containers, saves re-initializing from scratch each iteration auto extra_size = size - last_size; std::vector<int> verifications; verifications.resize (size); for (auto i (0); i < extra_size; ++i) { hashes.push_back (block.hash ()); messages.push_back (hashes.back ().bytes.data ()); lengths.push_back (sizeof (decltype (hashes)::value_type)); pub_keys.push_back (block.hashables.account.bytes.data ()); signatures.push_back (block.signature.bytes.data ()); } nano::signature_check_set check = { size, messages.data (), lengths.data (), pub_keys.data (), signatures.data (), verifications.data () }; checker.verify (check); bool all_valid = std::all_of (verifications.cbegin (), verifications.cend (), [](auto verification) { return verification == 1; }); ASSERT_TRUE (all_valid); last_size = size; } } } // Test the node epoch_upgrader with a large number of accounts and threads // Possible to manually add work peers TEST (node, mass_epoch_upgrader) { auto perform_test = [](size_t const batch_size) { unsigned threads = 5; size_t total_accounts = 2500; #ifndef NDEBUG total_accounts /= 5; #endif struct info { nano::keypair key; nano::block_hash pending_hash; }; std::vector<info> opened (total_accounts / 2); std::vector<info> unopened (total_accounts / 2); nano::system system; nano::node_config node_config (nano::get_available_port (), system.logging); node_config.work_threads = 4; //node_config.work_peers = { { "192.168.1.101", 7000 } }; auto & node = *system.add_node (node_config); auto balance = node.balance (nano::dev_genesis_key.pub); auto latest = node.latest (nano::dev_genesis_key.pub); nano::uint128_t amount = 1; // Send to all accounts std::array<std::vector<info> *, 2> all{ &opened, &unopened }; for (auto & accounts : all) { for (auto & info : *accounts) { balance -= amount; nano::state_block_builder builder; std::error_code ec; auto block = builder .account (nano::dev_genesis_key.pub) .previous (latest) .balance (balance) .link (info.key.pub) .representative (nano::dev_genesis_key.pub) .sign (nano::dev_genesis_key.prv, nano::dev_genesis_key.pub) .work (*node.work_generate_blocking (latest, nano::work_threshold (nano::work_version::work_1, nano::block_details (nano::epoch::epoch_0, false, false, false)))) .build (ec); ASSERT_FALSE (ec); ASSERT_NE (nullptr, block); ASSERT_EQ (nano::process_result::progress, node.process (*block).code); latest = block->hash (); info.pending_hash = block->hash (); } } ASSERT_EQ (1 + total_accounts, node.ledger.cache.block_count); ASSERT_EQ (1, node.ledger.cache.account_count); // Receive for half of accounts for (auto const & info : opened) { nano::state_block_builder builder; std::error_code ec; auto block = builder .account (info.key.pub) .previous (0) .balance (amount) .link (info.pending_hash) .representative (info.key.pub) .sign (info.key.prv, info.key.pub) .work (*node.work_generate_blocking (info.key.pub, nano::work_threshold (nano::work_version::work_1, nano::block_details (nano::epoch::epoch_0, false, false, false)))) .build (ec); ASSERT_FALSE (ec); ASSERT_NE (nullptr, block); ASSERT_EQ (nano::process_result::progress, node.process (*block).code); } ASSERT_EQ (1 + total_accounts + opened.size (), node.ledger.cache.block_count); ASSERT_EQ (1 + opened.size (), node.ledger.cache.account_count); nano::keypair epoch_signer (nano::dev_genesis_key); auto const block_count_before = node.ledger.cache.block_count.load (); auto const total_to_upgrade = 1 + total_accounts; std::cout << "Mass upgrading " << total_to_upgrade << " accounts" << std::endl; while (node.ledger.cache.block_count != block_count_before + total_to_upgrade) { auto const pre_upgrade = node.ledger.cache.block_count.load (); auto upgrade_count = std::min<size_t> (batch_size, block_count_before + total_to_upgrade - pre_upgrade); ASSERT_FALSE (node.epoch_upgrader (epoch_signer.prv.as_private_key (), nano::epoch::epoch_1, upgrade_count, threads)); // Already ongoing - should fail ASSERT_TRUE (node.epoch_upgrader (epoch_signer.prv.as_private_key (), nano::epoch::epoch_1, upgrade_count, threads)); system.deadline_set (60s); while (node.ledger.cache.block_count != pre_upgrade + upgrade_count) { ASSERT_NO_ERROR (system.poll ()); std::this_thread::sleep_for (200ms); std::cout << node.ledger.cache.block_count - block_count_before << " / " << total_to_upgrade << std::endl; } std::this_thread::sleep_for (50ms); } auto expected_blocks = block_count_before + total_accounts + 1; ASSERT_EQ (expected_blocks, node.ledger.cache.block_count); // Check upgrade { auto transaction (node.store.tx_begin_read ()); auto block_count_sum = 0; for (auto i (node.store.latest_begin (transaction)); i != node.store.latest_end (); ++i) { nano::account_info info (i->second); ASSERT_EQ (info.epoch (), nano::epoch::epoch_1); block_count_sum += info.block_count; } ASSERT_EQ (expected_blocks, block_count_sum); } }; // Test with a limited number of upgrades and an unlimited perform_test (42); perform_test (std::numeric_limits<size_t>::max ()); } TEST (node, mass_block_new) { nano::system system; nano::node_config node_config (nano::get_available_port (), system.logging); node_config.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled; auto & node = *system.add_node (node_config); node.network_params.network.request_interval_ms = 500; #ifndef NDEBUG auto const num_blocks = 5000; #else auto const num_blocks = 50000; #endif std::cout << num_blocks << " x4 blocks" << std::endl; // Upgrade to epoch_2 system.upgrade_genesis_epoch (node, nano::epoch::epoch_1); system.upgrade_genesis_epoch (node, nano::epoch::epoch_2); auto next_block_count = num_blocks + 3; auto process_all = [&](std::vector<std::shared_ptr<nano::state_block>> const & blocks_a) { for (auto const & block : blocks_a) { node.process_active (block); } ASSERT_TIMELY (200s, node.ledger.cache.block_count == next_block_count); next_block_count += num_blocks; node.block_processor.flush (); // Clear all active { nano::lock_guard<std::mutex> guard (node.active.mutex); node.active.roots.clear (); node.active.blocks.clear (); } }; nano::genesis genesis; nano::keypair key; std::vector<nano::keypair> keys (num_blocks); nano::state_block_builder builder; std::vector<std::shared_ptr<nano::state_block>> send_blocks; auto send_threshold (nano::work_threshold (nano::work_version::work_1, nano::block_details (nano::epoch::epoch_2, true, false, false))); auto ladev_genesis = node.latest (nano::dev_genesis_key.pub); for (auto i = 0; i < num_blocks; ++i) { auto send = builder.make_block () .account (nano::dev_genesis_key.pub) .previous (ladev_genesis) .balance (nano::genesis_amount - i - 1) .representative (nano::dev_genesis_key.pub) .link (keys[i].pub) .sign (nano::dev_genesis_key.prv, nano::dev_genesis_key.pub) .work (*system.work.generate (nano::work_version::work_1, ladev_genesis, send_threshold)) .build (); ladev_genesis = send->hash (); send_blocks.push_back (std::move (send)); } std::cout << "Send blocks built, start processing" << std::endl; nano::timer<> timer; timer.start (); process_all (send_blocks); std::cout << "Send blocks time: " << timer.stop ().count () << " " << timer.unit () << "\n\n"; std::vector<std::shared_ptr<nano::state_block>> open_blocks; auto receive_threshold (nano::work_threshold (nano::work_version::work_1, nano::block_details (nano::epoch::epoch_2, false, true, false))); for (auto i = 0; i < num_blocks; ++i) { auto const & key = keys[i]; auto open = builder.make_block () .account (key.pub) .previous (0) .balance (1) .representative (key.pub) .link (send_blocks[i]->hash ()) .sign (key.prv, key.pub) .work (*system.work.generate (nano::work_version::work_1, key.pub, receive_threshold)) .build (); open_blocks.push_back (std::move (open)); } std::cout << "Open blocks built, start processing" << std::endl; timer.restart (); process_all (open_blocks); std::cout << "Open blocks time: " << timer.stop ().count () << " " << timer.unit () << "\n\n"; // These blocks are from each key to themselves std::vector<std::shared_ptr<nano::state_block>> send_blocks2; for (auto i = 0; i < num_blocks; ++i) { auto const & key = keys[i]; auto const & latest = open_blocks[i]; auto send2 = builder.make_block () .account (key.pub) .previous (latest->hash ()) .balance (0) .representative (key.pub) .link (key.pub) .sign (key.prv, key.pub) .work (*system.work.generate (nano::work_version::work_1, latest->hash (), send_threshold)) .build (); send_blocks2.push_back (std::move (send2)); } std::cout << "Send2 blocks built, start processing" << std::endl; timer.restart (); process_all (send_blocks2); std::cout << "Send2 blocks time: " << timer.stop ().count () << " " << timer.unit () << "\n\n"; // Each key receives the previously sent blocks std::vector<std::shared_ptr<nano::state_block>> receive_blocks; for (auto i = 0; i < num_blocks; ++i) { auto const & key = keys[i]; auto const & latest = send_blocks2[i]; auto send2 = builder.make_block () .account (key.pub) .previous (latest->hash ()) .balance (1) .representative (key.pub) .link (latest->hash ()) .sign (key.prv, key.pub) .work (*system.work.generate (nano::work_version::work_1, latest->hash (), receive_threshold)) .build (); receive_blocks.push_back (std::move (send2)); } std::cout << "Receive blocks built, start processing" << std::endl; timer.restart (); process_all (receive_blocks); std::cout << "Receive blocks time: " << timer.stop ().count () << " " << timer.unit () << "\n\n"; }
{ "pile_set_name": "Github" }
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Jun 9 2015 22:53:21). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2014 by Steve Nygard. // #import "ICPAgentSharedPhotoStreamUserNotificationEvent.h" @interface ICPAgentVideoConversionFailureUserNotificationEvent : ICPAgentSharedPhotoStreamUserNotificationEvent { } + (id)type; + (id)eventWithUserNotificationManager:(id)arg1 album:(id)arg2 info:(id)arg3; - (void)postUserNotification; - (id)coalescingAggregateEvent; - (id)matchingIdentifier; - (id)coalescingKey; - (BOOL)shouldCoalesce; - (id)initWithUserNotificationManager:(id)arg1 album:(id)arg2 info:(id)arg3; @end
{ "pile_set_name": "Github" }
/** * Returns a curried equivalent of the provided function. * @see http://ramdajs.com/docs/#curry */ // // poor man's version, using a given return value rather than using `typeof` based on the given argument types: // function curry<Args extends any[], Ret>(fn: (...args: Args) => Ret): Curried<Args, Ret>; // type Curried< // ArgsAsked, // Ret, // ArgsPrevious = [] // if we can't have empty tuple I guess any[] might also destructures to nothing; that might do. // > = < // ArgsGiven extends any[] = ArgsGiven, // ArgsAll extends [...ArgsPrevious, ...ArgsGiven] // = [...ArgsPrevious, ...ArgsGiven] // >(...args: ArgsGiven) => // If< // TupleHasIndex<ArgsAll, TupleLastIndex<ArgsAsked>>, // Ret, // Curried<ArgsAsked, Ret, ArgsAll> // >;
{ "pile_set_name": "Github" }
{ "parent": "minecraft:item/generated", "textures": { "layer0": "botania:block/red_double_flower_top" } }
{ "pile_set_name": "Github" }
/* ** Splint - annotation-assisted static program checker ** Copyright (C) 1994-2003 University of Virginia, ** Massachusetts Institute of Technology ** ** This program is free software; you can redistribute it and/or modify it ** under the terms of the GNU General Public License as published by the ** Free Software Foundation; either version 2 of the License, or (at your ** option) any later version. ** ** This program is distributed in the hope that it will be useful, but ** WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** General Public License for more details. ** ** The GNU General Public License is available from http://www.gnu.org/ or ** the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, ** MA 02111-1307, USA. ** ** For information on splint: [email protected] ** To report a bug: [email protected] ** For more information: http://www.splint.org */ /* ** scanline.c ** ** MODULE DESCRIPTION: ** ** This module scans one line of Larch C Interface Language (LCL) input at ** a time. ** ** The input is source text, line at a time. The output is a sequence ** of tokens, reported by call-out LSLScanFreshToken. ** ** This organization allows implementation of line-at-a-time incremental ** scanning. The incremental mechanism is in the driving module scan.c. ** ** The main loop of the scanner keys on the leading character. ** Within the loop are actions which collect the rest of the ** token starting with the character. Various careful hacks ** show up to disambiguate tokens that break the general pattern ** (Examples, \/ and /\). White space is passed and the loop ** goes once again without calling LSLScanFreshToken (). ** The line ends with a null. ** ** AUTHORS: ** ** JPW, GAF, Yang Meng Tan */ # include "splintMacros.nf" # include "basic.h" # include "gram.h" # include "lclscan.h" # include "scanline.h" # include "lclscanline.h" # include "lcltokentable.h" # include "lclsyntable.h" /*@constant int CHARSIZE;@*/ # define CHARSIZE 256 /* on an 8-bit machine */ /*@notfunction@*/ # define LCLMOVECHAR() \ do { *bufPtr++ = currentChar; currentChar = *currentLine++; \ colNumber++; } while (FALSE) /*@notfunction@*/ # define LOOKAHEADCHAR() (*currentLine) /*@notfunction@*/ # define LOOKAHEADTWICECHAR() (*(currentLine + 1)) /*@constant static int MAXCHAR;@*/ # define MAXCHAR 512 /* storage for a lexeme */ /* ** Printname for the TokenCode NOTTOKEN (also 1st one reserved) ** Printname for the TokenCode BADTOKEN (also last one reserved) */ /*@constant static observer char *FIRSTRESERVEDNAME;@*/ # define FIRSTRESERVEDNAME "?" /* ** The scanner establishes lexical boundaries by first switching ** on the leading character of the pending lexeme. */ typedef enum { STARTCNUM, /* First character of a C number. */ STARTCNUMDOT, /* "." only starts a C number if digit follows*/ STARTCSTR, /* First character of a C string. */ STARTCCHAR, /* First character of a C character. */ STARTWIDE, /* slash L starts both string and character. */ STARTSLASH, /* "/" starts caret, comment comment, operator */ STARTOTHER /* Everything else. */ } StartCharType; static void ScanCComment (void); static void ScanEscape (void); static void ScanCString (void); static void ScanCChar (void); static void ScanCNumber (void); static void LocalUserError (/*@temp@*/ char *); /* ** Array to store character class defintions and record end-of-comment ** characters. */ static charClassData LCLcharClass[LASTCHAR + 1]; /* ** Data shared between routines LCLScanLine, ScanCString, ScanCChar, ** ScanCNumber. LCLScanLine was getting too big for one routine and ** passing this data was rather cumbersome. Making this data global seemed ** to be the simpliest solution. */ /* evs - sounds bogus to me! */ static int colNumber; static int startCol; static char *currentLine; static char currentChar; static ltokenCode tokenCode; static lsymbol tokenSym; static char *bufPtr; static bool inComment; static /*@only@*/ ltoken commentTok; static ltokenCode prevTokenCode; /* to disambiguate ' */ static StartCharType startClass[CHARSIZE] = { STARTOTHER, /* ^@ 00x */ STARTOTHER, /* ^a 01x */ STARTOTHER, /* ^b 02x */ STARTOTHER, /* ^c 03x */ STARTOTHER, /* ^d 04x */ STARTOTHER, /* ^e 05x */ STARTOTHER, /* ^f 06x */ STARTOTHER, /* ^g BELL 07x */ STARTOTHER, /* ^h BACKSPACE 08x */ STARTOTHER, /* ^i TAB 09x */ STARTOTHER, /* ^j NEWLINE 0Ax */ STARTOTHER, /* ^k 0Bx */ STARTOTHER, /* ^l FORMFEED 0Cx */ STARTOTHER, /* ^m RETURN 0Dx */ STARTOTHER, /* ^n 0Ex */ STARTOTHER, /* ^o 0Fx */ STARTOTHER, /* ^p 10x */ STARTOTHER, /* ^q 11x */ STARTOTHER, /* ^r 12x */ STARTOTHER, /* ^s 13x */ STARTOTHER, /* ^t 14x */ STARTOTHER, /* ^u 15x */ STARTOTHER, /* ^v 16x */ STARTOTHER, /* ^w 17x */ STARTOTHER, /* ^x 18x */ STARTOTHER, /* ^y 19x */ STARTOTHER, /* ^z 1Ax */ STARTOTHER, /* ^[ ESC 1Bx */ STARTOTHER, /* ^slash 1Cx */ STARTOTHER, /* ^] 1Dx */ STARTOTHER, /* ^^ 1Ex */ STARTOTHER, /* ^_ 1Fx */ STARTOTHER, /* BLANK 20x */ STARTOTHER, /* ! 21x */ STARTCSTR, /* " 22x */ STARTOTHER, /* # 23x */ STARTOTHER, /* $ (may be changed in reset) 24x */ STARTOTHER, /* % 25x */ STARTOTHER, /* & 26x */ STARTCCHAR, /* ' 27x */ STARTOTHER, /* ( 28x */ STARTOTHER, /* ) 29x */ STARTOTHER, /* * 2Ax */ STARTOTHER, /* + 2Bx */ STARTOTHER, /* , 2Cx */ STARTOTHER, /* - 2Dx */ STARTCNUMDOT, /* . 2Ex */ STARTSLASH, /* / 2Fx */ STARTCNUM, /* 0 30x */ STARTCNUM, /* 1 31x */ STARTCNUM, /* 2 32x */ STARTCNUM, /* 3 33x */ STARTCNUM, /* 4 34x */ STARTCNUM, /* 5 35x */ STARTCNUM, /* 6 36x */ STARTCNUM, /* 7 37x */ STARTCNUM, /* 8 38x */ STARTCNUM, /* 9 39x */ STARTOTHER, /* : 3Ax */ STARTOTHER, /* ; 3Bx */ STARTOTHER, /* < 3Cx */ STARTOTHER, /* = 3Dx */ STARTOTHER, /* > 3Ex */ STARTOTHER, /* ? 3Fx */ STARTOTHER, /* @ 40x */ STARTOTHER, /* A 41x */ STARTOTHER, /* B 42x */ STARTOTHER, /* C 43x */ STARTOTHER, /* D 44x */ STARTOTHER, /* E 45x */ STARTOTHER, /* F 46x */ STARTOTHER, /* G 47x */ STARTOTHER, /* H 48x */ STARTOTHER, /* I 49x */ STARTOTHER, /* J 4Ax */ STARTOTHER, /* K 4Bx */ STARTOTHER, /* L 4Cx */ STARTOTHER, /* M 4Dx */ STARTOTHER, /* N 4Ex */ STARTOTHER, /* O 4Fx */ STARTOTHER, /* P 50x */ STARTOTHER, /* Q 51x */ STARTOTHER, /* R 52x */ STARTOTHER, /* S 53x */ STARTOTHER, /* T 54x */ STARTOTHER, /* U 55x */ STARTOTHER, /* V 56x */ STARTOTHER, /* W 57x */ STARTOTHER, /* X 58x */ STARTOTHER, /* Y 59x */ STARTOTHER, /* Z 5Ax */ STARTOTHER, /* [ 5Bx */ STARTWIDE, /* slash 5Cx */ STARTOTHER, /* ] 5Dx */ STARTOTHER, /* ^ 5Ex */ STARTOTHER, /* _ 5Fx */ STARTOTHER, /* ` 60x */ STARTOTHER, /* a 61x */ STARTOTHER, /* b 62x */ STARTOTHER, /* c 63x */ STARTOTHER, /* d 64x */ STARTOTHER, /* e 65x */ STARTOTHER, /* f 66x */ STARTOTHER, /* g 67x */ STARTOTHER, /* h 68x */ STARTOTHER, /* i 69x */ STARTOTHER, /* j 6Ax */ STARTOTHER, /* k 6Bx */ STARTOTHER, /* l 6Cx */ STARTOTHER, /* m 6Dx */ STARTOTHER, /* n 6Ex */ STARTOTHER, /* o 6Fx */ STARTOTHER, /* p 70x */ STARTOTHER, /* q 71x */ STARTOTHER, /* r 72x */ STARTOTHER, /* s 73x */ STARTOTHER, /* t 74x */ STARTOTHER, /* u 75x */ STARTOTHER, /* v 76x */ STARTOTHER, /* w 77x */ STARTOTHER, /* x 78x */ STARTOTHER, /* y 79x */ STARTOTHER, /* z 7Ax */ STARTOTHER, /* { 7Dx */ STARTOTHER, /* | 7Cx */ STARTOTHER, /* } 7Dx */ STARTOTHER, /* ~ 7Ex */ STARTOTHER, STARTOTHER /* RUBOUT 7Fx */ }; /* ** Given a character code, its status as part of an decimal escape sequence ** can be derived from this table. Digits 0-9 allowed. */ static bool isDigit[CHARSIZE] = { FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE }; /* * Given a character code, its status as part of an octal escape sequence * can be derived from this table. Digits 0-7 allowed. */ static bool isOigit[CHARSIZE] = { FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE }; /* * Given a character code, its status as part of a hex escape sequence * can be derived from this table. Digits, a-f, A-F allowed. */ static bool isXigit[CHARSIZE] = { FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE }; /* * Given a character code, its status as part of a C string * can be derived from this table. Everything but quotes and newline * are allowed. */ static bool isStrChar[CHARSIZE] = { TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE }; /* * Given a character code, its status as part of a C Character * can be derived from this table. Everything but quotes and newline * are allowed. */ static bool isCharChar[CHARSIZE] = { TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE }; /* ** Given a character code, its status as part of a string or character ** simple escape sequence ('slash'', 'slash"', 'slash?', 'slashslash', ** 'slasha', 'slashb', 'slashf', 'slashn', 'slasht', and 'slashv') ** can be derived from this table. ''', '"', '?', 'slash', 'a', ** 'b', 'f', 'n', 't', and 'v' are allowed. */ static bool isSimpleEscape[CHARSIZE] = { FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE }; static bool reportEOL; static bool reportComments; static lsymbol firstReserved; static char tokenBuffer[MAXCHAR]; static const charClassData charClassDef[] = { /* Control characters */ { SINGLECHAR, FALSE }, /* 0 NULL */ { SINGLECHAR, FALSE }, /* 1 CTRL-A */ { SINGLECHAR, FALSE }, /* 2 CTRL-B */ { SINGLECHAR, FALSE }, /* 3 CTRL-C */ { SINGLECHAR, FALSE }, /* 4 CTRL-D */ { SINGLECHAR, FALSE }, /* 5 CTRL-E */ { SINGLECHAR, FALSE }, /* 6 CTRL-F */ { SINGLECHAR, FALSE }, /* 7 CTRL-G */ { SINGLECHAR, FALSE }, /* 8 CTRL-H */ /* defined formatting characters */ { WHITECHAR, FALSE }, /* 9 CTRL-I TAB */ { CHC_NULL, TRUE }, /* 10 CTRL-J EOL */ /* more control characters */ { SINGLECHAR, FALSE }, /* 11 CTRL-K */ { WHITECHAR, FALSE }, /* 12 CTRL-L */ { SINGLECHAR, FALSE }, /* 13 CTRL-M */ { SINGLECHAR, FALSE }, /* 14 CTRL-N */ { SINGLECHAR, FALSE }, /* 15 CTRL-O */ { SINGLECHAR, FALSE }, /* 16 CTRL-P */ { SINGLECHAR, FALSE }, /* 17 CTRL-Q */ { SINGLECHAR, FALSE }, /* 18 CTRL-R */ { SINGLECHAR, FALSE }, /* 19 CTRL-S */ { SINGLECHAR, FALSE }, /* 20 CTRL-T */ { SINGLECHAR, FALSE }, /* 21 CTRL-U */ { SINGLECHAR, FALSE }, /* 22 CTRL-V */ { SINGLECHAR, FALSE }, /* 23 CTRL-W */ { SINGLECHAR, FALSE }, /* 24 CTRL-X */ { SINGLECHAR, FALSE }, /* 25 CTRL-Y */ { SINGLECHAR, FALSE }, /* 26 CTRL-Z */ { SINGLECHAR, FALSE }, /* 27 CTRL-[ ESC */ { SINGLECHAR, FALSE }, /* 28 CTRL-slash FS */ { SINGLECHAR, FALSE }, /* 29 CTRL-] GS */ { SINGLECHAR, FALSE }, /* 30 CTRL-^ RS */ { SINGLECHAR, FALSE }, /* 31 CTRL-_ US */ /* Special printing characters */ { WHITECHAR, FALSE }, /* 32 space */ { SINGLECHAR, FALSE }, /* 33 ! */ { SINGLECHAR, FALSE }, /* 34 " */ { SINGLECHAR, FALSE }, /* 35 # */ { SINGLECHAR, FALSE }, /* 36 $ */ { SINGLECHAR, FALSE }, /* 37 % */ { SINGLECHAR, FALSE }, /* 38 & */ { SINGLECHAR, FALSE }, /* 39 ' */ /* Reserved characters */ { PERMCHAR, FALSE }, /* 40 ( */ { PERMCHAR, FALSE }, /* 41 ) */ { PERMCHAR, FALSE }, /* 42 * */ { OPCHAR, FALSE }, /* 43 + */ { PERMCHAR, FALSE }, /* 44 , */ { OPCHAR, FALSE }, /* 45 - */ { OPCHAR, FALSE }, /* 46 . */ { OPCHAR, FALSE }, /* 47 / */ /* Numbers */ { IDCHAR, FALSE }, /* 48 0 */ { IDCHAR, FALSE }, /* 49 1 */ { IDCHAR, FALSE }, /* 50 2 */ { IDCHAR, FALSE }, /* 51 3 */ { IDCHAR, FALSE }, /* 52 4 */ { IDCHAR, FALSE }, /* 53 5 */ { IDCHAR, FALSE }, /* 54 6 */ { IDCHAR, FALSE }, /* 55 7 */ { IDCHAR, FALSE }, /* 56 8 */ { IDCHAR, FALSE }, /* 57 9 */ /* More reserved and special printing characters */ { PERMCHAR, FALSE }, /* 58 : */ { PERMCHAR, FALSE }, /* 59; */ { OPCHAR, FALSE }, /* 60 < */ { OPCHAR, FALSE }, /* 61 = */ { OPCHAR, FALSE }, /* 62 > */ { SINGLECHAR, FALSE }, /* 63 ? */ { SINGLECHAR, FALSE }, /* 64 @ */ /* Uppercase Alphabetics */ { IDCHAR, FALSE }, /* 65 A */ { IDCHAR, FALSE }, /* 66 B */ { IDCHAR, FALSE }, /* 67 C */ { IDCHAR, FALSE }, /* 68 D */ { IDCHAR, FALSE }, /* 69 E */ { IDCHAR, FALSE }, /* 70 F */ { IDCHAR, FALSE }, /* 71 G */ { IDCHAR, FALSE }, /* 72 H */ { IDCHAR, FALSE }, /* 73 I */ { IDCHAR, FALSE }, /* 74 J */ { IDCHAR, FALSE }, /* 75 K */ { IDCHAR, FALSE }, /* 76 L */ { IDCHAR, FALSE }, /* 77 M */ { IDCHAR, FALSE }, /* 78 N */ { IDCHAR, FALSE }, /* 79 O */ { IDCHAR, FALSE }, /* 80 P */ { IDCHAR, FALSE }, /* 81 Q */ { IDCHAR, FALSE }, /* 82 R */ { IDCHAR, FALSE }, /* 83 S */ { IDCHAR, FALSE }, /* 84 T */ { IDCHAR, FALSE }, /* 85 U */ { IDCHAR, FALSE }, /* 86 V */ { IDCHAR, FALSE }, /* 87 W */ { IDCHAR, FALSE }, /* 88 X */ { IDCHAR, FALSE }, /* 89 Y */ { IDCHAR, FALSE }, /* 90 Z */ /* Still more reserved and special printing characters */ { PERMCHAR, FALSE }, /* 91 [ */ { CHC_EXTENSION, FALSE }, /* 92 slash */ { PERMCHAR, FALSE }, /* 93 ] */ { SINGLECHAR, FALSE }, /* 94 ^ */ { IDCHAR, FALSE }, /* 95 _ */ { SINGLECHAR, FALSE }, /* 96 ` */ /* Lowercase alphabetics */ { IDCHAR, FALSE }, /* 97 a */ { IDCHAR, FALSE }, /* 98 b */ { IDCHAR, FALSE }, /* 99 c */ { IDCHAR, FALSE }, /* 100 d */ { IDCHAR, FALSE }, /* 101 e */ { IDCHAR, FALSE }, /* 102 f */ { IDCHAR, FALSE }, /* 103 g */ { IDCHAR, FALSE }, /* 104 h */ { IDCHAR, FALSE }, /* 105 i */ { IDCHAR, FALSE }, /* 106 j */ { IDCHAR, FALSE }, /* 107 k */ { IDCHAR, FALSE }, /* 108 l */ { IDCHAR, FALSE }, /* 109 m */ { IDCHAR, FALSE }, /* 110 n */ { IDCHAR, FALSE }, /* 111 o */ { IDCHAR, FALSE }, /* 112 p */ { IDCHAR, FALSE }, /* 113 q */ { IDCHAR, FALSE }, /* 114 r */ { IDCHAR, FALSE }, /* 115 s */ { IDCHAR, FALSE }, /* 116 t */ { IDCHAR, FALSE }, /* 117 u */ { IDCHAR, FALSE }, /* 118 v */ { IDCHAR, FALSE }, /* 119 w */ { IDCHAR, FALSE }, /* 120 x */ { IDCHAR, FALSE }, /* 121 y */ { IDCHAR, FALSE }, /* 122 z */ { SINGLECHAR, FALSE }, /* 123 { */ { SINGLECHAR, FALSE }, /* 124 | */ { SINGLECHAR, FALSE }, /* 125 } */ { SINGLECHAR, FALSE }, /* 126 ~ */ { SINGLECHAR, FALSE }, /* 127 DEL */ /* MCS - unused in English */ { SINGLECHAR, FALSE }, /* 128 */ { SINGLECHAR, FALSE }, /* 129 */ { SINGLECHAR, FALSE }, /* 130 */ { SINGLECHAR, FALSE }, /* 131 */ { SINGLECHAR, FALSE }, /* 132 */ { SINGLECHAR, FALSE }, /* 133 */ { SINGLECHAR, FALSE }, /* 134 */ { SINGLECHAR, FALSE }, /* 135 */ { SINGLECHAR, FALSE }, /* 136 */ { SINGLECHAR, FALSE }, /* 137 */ { SINGLECHAR, FALSE }, /* 138 */ { SINGLECHAR, FALSE }, /* 139 */ { SINGLECHAR, FALSE }, /* 140 */ { SINGLECHAR, FALSE }, /* 141 */ { SINGLECHAR, FALSE }, /* 142 */ { SINGLECHAR, FALSE }, /* 143 */ { SINGLECHAR, FALSE }, /* 144 */ { SINGLECHAR, FALSE }, /* 145 */ { SINGLECHAR, FALSE }, /* 146 */ { SINGLECHAR, FALSE }, /* 147 */ { SINGLECHAR, FALSE }, /* 148 */ { SINGLECHAR, FALSE }, /* 149 */ { SINGLECHAR, FALSE }, /* 150 */ { SINGLECHAR, FALSE }, /* 151 */ { SINGLECHAR, FALSE }, /* 152 */ { SINGLECHAR, FALSE }, /* 153 */ { SINGLECHAR, FALSE }, /* 154 */ { SINGLECHAR, FALSE }, /* 155 */ { SINGLECHAR, FALSE }, /* 156 */ { SINGLECHAR, FALSE }, /* 157 */ { SINGLECHAR, FALSE }, /* 158 */ { SINGLECHAR, FALSE }, /* 159 */ { SINGLECHAR, FALSE }, /* 160 */ { SINGLECHAR, FALSE }, /* 161 */ { SINGLECHAR, FALSE }, /* 162 */ { SINGLECHAR, FALSE }, /* 163 */ { SINGLECHAR, FALSE }, /* 164 */ { SINGLECHAR, FALSE }, /* 165 */ { SINGLECHAR, FALSE }, /* 166 */ { SINGLECHAR, FALSE }, /* 167 */ { SINGLECHAR, FALSE }, /* 168 */ { SINGLECHAR, FALSE }, /* 169 */ { SINGLECHAR, FALSE }, /* 170 */ { SINGLECHAR, FALSE }, /* 171 */ { SINGLECHAR, FALSE }, /* 172 */ { SINGLECHAR, FALSE }, /* 173 */ { SINGLECHAR, FALSE }, /* 174 */ { SINGLECHAR, FALSE }, /* 175 */ { SINGLECHAR, FALSE }, /* 176 */ { SINGLECHAR, FALSE }, /* 177 */ { SINGLECHAR, FALSE }, /* 178 */ { SINGLECHAR, FALSE }, /* 179 */ { SINGLECHAR, FALSE }, /* 180 */ { SINGLECHAR, FALSE }, /* 181 */ { SINGLECHAR, FALSE }, /* 182 */ { SINGLECHAR, FALSE }, /* 183 */ { SINGLECHAR, FALSE }, /* 184 */ { SINGLECHAR, FALSE }, /* 185 */ { SINGLECHAR, FALSE }, /* 186 */ { SINGLECHAR, FALSE }, /* 187 */ { SINGLECHAR, FALSE }, /* 188 */ { SINGLECHAR, FALSE }, /* 189 */ { SINGLECHAR, FALSE }, /* 190 */ { SINGLECHAR, FALSE }, /* 191 */ { SINGLECHAR, FALSE }, /* 192 */ { SINGLECHAR, FALSE }, /* 193 */ { SINGLECHAR, FALSE }, /* 194 */ { SINGLECHAR, FALSE }, /* 195 */ { SINGLECHAR, FALSE }, /* 196 */ { SINGLECHAR, FALSE }, /* 197 */ { SINGLECHAR, FALSE }, /* 198 */ { SINGLECHAR, FALSE }, /* 199 */ { SINGLECHAR, FALSE }, /* 200 */ { SINGLECHAR, FALSE }, /* 201 */ { SINGLECHAR, FALSE }, /* 202 */ { SINGLECHAR, FALSE }, /* 203 */ { SINGLECHAR, FALSE }, /* 204 */ { SINGLECHAR, FALSE }, /* 205 */ { SINGLECHAR, FALSE }, /* 206 */ { SINGLECHAR, FALSE }, /* 207 */ { SINGLECHAR, FALSE }, /* 208 */ { SINGLECHAR, FALSE }, /* 209 */ { SINGLECHAR, FALSE }, /* 210 */ { SINGLECHAR, FALSE }, /* 211 */ { SINGLECHAR, FALSE }, /* 212 */ { SINGLECHAR, FALSE }, /* 213 */ { SINGLECHAR, FALSE }, /* 214 */ { SINGLECHAR, FALSE }, /* 215 */ { SINGLECHAR, FALSE }, /* 216 */ { SINGLECHAR, FALSE }, /* 217 */ { SINGLECHAR, FALSE }, /* 218 */ { SINGLECHAR, FALSE }, /* 219 */ { SINGLECHAR, FALSE }, /* 220 */ { SINGLECHAR, FALSE }, /* 221 */ { SINGLECHAR, FALSE }, /* 222 */ { SINGLECHAR, FALSE }, /* 223 */ { SINGLECHAR, FALSE }, /* 224 */ { SINGLECHAR, FALSE }, /* 225 */ { SINGLECHAR, FALSE }, /* 226 */ { SINGLECHAR, FALSE }, /* 227 */ { SINGLECHAR, FALSE }, /* 228 */ { SINGLECHAR, FALSE }, /* 229 */ { SINGLECHAR, FALSE }, /* 230 */ { SINGLECHAR, FALSE }, /* 231 */ { SINGLECHAR, FALSE }, /* 232 */ { SINGLECHAR, FALSE }, /* 233 */ { SINGLECHAR, FALSE }, /* 234 */ { SINGLECHAR, FALSE }, /* 235 */ { SINGLECHAR, FALSE }, /* 236 */ { SINGLECHAR, FALSE }, /* 237 */ { SINGLECHAR, FALSE }, /* 238 */ { SINGLECHAR, FALSE }, /* 239 */ { SINGLECHAR, FALSE }, /* 240 */ { SINGLECHAR, FALSE }, /* 241 */ { SINGLECHAR, FALSE }, /* 242 */ { SINGLECHAR, FALSE }, /* 243 */ { SINGLECHAR, FALSE }, /* 244 */ { SINGLECHAR, FALSE }, /* 245 */ { SINGLECHAR, FALSE }, /* 246 */ { SINGLECHAR, FALSE }, /* 247 */ { SINGLECHAR, FALSE }, /* 248 */ { SINGLECHAR, FALSE }, /* 249 */ { SINGLECHAR, FALSE }, /* 250 */ { SINGLECHAR, FALSE }, /* 251 */ { SINGLECHAR, FALSE }, /* 252 */ { SINGLECHAR, FALSE }, /* 253 */ { SINGLECHAR, FALSE }, /* 254 */ { SINGLECHAR, FALSE } /* 255 */ }; void ScanCComment (void) { inComment = TRUE; for (;;) { switch (currentChar) { case '*': LCLMOVECHAR (); if (currentChar == '/') { LCLMOVECHAR (); inComment = FALSE; return; } /*@switchbreak@*/ break; case '\n': return; default: LCLMOVECHAR (); } } } void ScanEscape (void) { if (isSimpleEscape[(int)currentChar]) { LCLMOVECHAR (); /* discard simple escape character. */ } else if (currentChar == 'x') { LCLMOVECHAR (); /* discard 'x'. */ if (!isXigit[(int)currentChar]) { LocalUserError ("at least one hex digit must follow '\\x'"); } while (isXigit[(int)currentChar]) { LCLMOVECHAR (); /* discard hex digits. */ } } else if (isOigit[(int)currentChar]) { LCLMOVECHAR (); /* discard first hex digit. */ if (isOigit[(int)currentChar]) { LCLMOVECHAR (); /* discard second hex digit. */ } if (isOigit[(int)currentChar]) { LCLMOVECHAR (); /* discard third hex digit. */ } } else { LocalUserError ("invalid escape sequence in a C string or character"); } } void ScanCString (void) { if (currentChar == '\\' && LOOKAHEADCHAR () == 'L') { LCLMOVECHAR (); /* discard slash */ LCLMOVECHAR (); /* discard 'L'. */ } if (currentChar == '\"') { LCLMOVECHAR (); /* discard opening quote. */ while (currentChar != '\"') { if (isStrChar[(int)currentChar]) { LCLMOVECHAR (); /* discard string character. */ } else if (currentChar == '\\') { LCLMOVECHAR (); /* discard slash */ ScanEscape (); } else if (currentChar == '\n') { LocalUserError ("Unterminated C string"); } else { LocalUserError ("Invalid character in C string"); } } LCLMOVECHAR (); /* discard closing quote */ } else { LocalUserError ("C string must start with '\"'"); } *bufPtr = '\0'; /* null terminate in buffer */ tokenSym = lsymbol_fromChars (&tokenBuffer[0]); tokenCode = LLT_LCSTRING; } void ScanCChar (void) { if (currentChar == '\\' && LOOKAHEADCHAR () == 'L') { LCLMOVECHAR (); /* discard slash */ LCLMOVECHAR (); /* discard 'L'. */ } if (currentChar == '\'') { LCLMOVECHAR (); /* discard opening quote */ while (currentChar != '\'') { if (isCharChar[(int)currentChar]) { LCLMOVECHAR (); /* discard string character. */ } else if (currentChar == '\\') { LCLMOVECHAR (); /* discard slash */ ScanEscape (); } else if (currentChar == '\n') { LocalUserError ("Unterminated C character constant"); } else { LocalUserError ("Invalid character in C character"); } } LCLMOVECHAR (); /* discard closing quote */ } else { LocalUserError ("Invalid C character"); } *bufPtr = '\0'; /* null terminate in buffer */ tokenSym = lsymbol_fromChars (&tokenBuffer[0]); tokenCode = LLT_CCHAR; } void ScanCNumber (void) { tokenCode = LLT_CINTEGER; switch (currentChar) { case '.': LCLMOVECHAR (); tokenCode = LLT_CFLOAT; if (!isDigit[(int)currentChar]) { LocalUserError ("at least one digit must follow '.'"); } while (isDigit[(int)currentChar]) { LCLMOVECHAR (); } if (currentChar == 'e' || currentChar == 'E') { LCLMOVECHAR (); /* discard 'e' or 'E'. */ if (currentChar == '+' || currentChar == '-') { LCLMOVECHAR (); } if (!isDigit[(int)currentChar]) { LocalUserError ("digit must follow exponent"); } while (isDigit[(int)currentChar]) { LCLMOVECHAR (); } } if (currentChar == 'f' || currentChar == 'l' || currentChar == 'F' || currentChar == 'L') { LCLMOVECHAR (); } break; case '0': LCLMOVECHAR (); /* discard '0'. */ switch (currentChar) { case 'x': case 'X': LCLMOVECHAR (); if (!isXigit[(int)currentChar]) { LocalUserError ("hex digit must follow 'x' or 'X'"); } while (isXigit[(int)currentChar]) { LCLMOVECHAR (); } /*@switchbreak@*/ break; default: /* ** Could either be an octal number or a floating point ** number. Scan decimal digits so don't run into ** problems if turns out problems if it is an fp ** number. Let converter/parser catch bad octal ** numbers. e.g. 018 not caught by scanner. */ while (isDigit[(int)currentChar]) { LCLMOVECHAR (); } switch (currentChar) { case '.': LCLMOVECHAR (); /* discard '.'. */ tokenCode = LLT_CFLOAT; while (isDigit[(int)currentChar]) { LCLMOVECHAR (); } if (currentChar == 'e' || currentChar == 'E') { LCLMOVECHAR (); /* discard 'e' or 'E'. */ if (currentChar == '+' || currentChar == '-') { LCLMOVECHAR (); } if (!isDigit[(int)currentChar]) { LocalUserError ("digit must follow exponent"); } while (isDigit[(int)currentChar]) { LCLMOVECHAR (); } } if (currentChar == 'f' || currentChar == 'l' || currentChar == 'F' || currentChar == 'L') { LCLMOVECHAR (); } /*@switchbreak@*/ break; case 'e': case 'E': LCLMOVECHAR (); tokenCode = LLT_CFLOAT; if (currentChar == '+' || currentChar == '-') { LCLMOVECHAR (); } if (!isDigit[(int)currentChar]) { LocalUserError ("digit must follow exponent"); } while (isDigit[(int)currentChar]) { LCLMOVECHAR (); } if (currentChar == 'f' || currentChar == 'l' || currentChar == 'F' || currentChar == 'L') { LCLMOVECHAR (); } /*@switchbreak@*/ break; default: /* Scan integer suffix. */ switch (currentChar) { case 'u': case 'U': LCLMOVECHAR (); if (currentChar == 'l' || currentChar == 'L') { LCLMOVECHAR (); } /*@switchbreak@*/ break; case 'l': case 'L': LCLMOVECHAR (); if (currentChar == 'u' || currentChar == 'U') { LCLMOVECHAR (); } /*@switchbreak@*/ break; } /*@switchbreak@*/ break; } } /* Scan integer suffix. */ switch (currentChar) { case 'u': case 'U': LCLMOVECHAR (); if (currentChar == 'l' || currentChar == 'L') { LCLMOVECHAR (); } /*@switchbreak@*/ break; case 'l': case 'L': LCLMOVECHAR (); if (currentChar == 'u' || currentChar == 'U') { LCLMOVECHAR (); } /*@switchbreak@*/ break; } break; default: if (isDigit[(int)currentChar]) { while (isDigit[(int)currentChar]) { LCLMOVECHAR (); } switch (currentChar) { case '.': LCLMOVECHAR (); /* discard '.'. */ tokenCode = LLT_CFLOAT; while (isDigit[(int)currentChar]) { LCLMOVECHAR (); } if (currentChar == 'e' || currentChar == 'E') { LCLMOVECHAR (); if (currentChar == '+' || currentChar == '-') { LCLMOVECHAR (); } if (!isDigit[(int)currentChar]) { LocalUserError ("digit must follow exponent"); } while (isDigit[(int)currentChar]) { LCLMOVECHAR (); } } if (currentChar == 'f' || currentChar == 'l' || currentChar == 'F' || currentChar == 'L') { LCLMOVECHAR (); } /*@switchbreak@*/ break; case 'e': case 'E': LCLMOVECHAR (); tokenCode = LLT_CFLOAT; if (currentChar == '+' || currentChar == '-') { LCLMOVECHAR (); } if (!isDigit[(int)currentChar]) { LocalUserError ("digit must follow exponent"); } while (isDigit[(int)currentChar]) { LCLMOVECHAR (); } if (currentChar == 'f' || currentChar == 'l' || currentChar == 'F' || currentChar == 'L') { LCLMOVECHAR (); } /*@switchbreak@*/ break; default: switch (currentChar) { case 'u': case 'U': LCLMOVECHAR (); if (currentChar == 'l' || currentChar == 'L') { LCLMOVECHAR (); } /*@switchbreak@*/ break; case 'l': case 'L': LCLMOVECHAR (); if (currentChar == 'u' || currentChar == 'U') { LCLMOVECHAR (); } /*@switchbreak@*/ break; } /*@switchbreak@*/ break; } } else { LocalUserError ("invalid C number"); } break; } *bufPtr = '\0'; tokenSym = lsymbol_fromChars (&tokenBuffer[0]); } static void ScanOther (void) { switch (LCLScanCharClass (currentChar)) { case CHC_NULL: tokenSym = lsymbol_fromChars ("E O L"); tokenCode = LLT_EOL; break; /* identifiers */ case IDCHAR: while (LCLScanCharClass (currentChar) == IDCHAR) { /* identifier: find end */ LCLMOVECHAR (); } *bufPtr = '\0'; /* null terminate in buffer */ tokenSym = lsymbol_fromChars (&tokenBuffer[0]); tokenCode = simpleId; break; /* one-character tokens */ case SINGLECHAR: case PERMCHAR: LCLMOVECHAR (); *bufPtr = '\0'; tokenSym = lsymbol_fromChars (&tokenBuffer[0]); tokenCode = simpleOp; break; /* operator symbols */ case OPCHAR: if (currentChar == '.' && LOOKAHEADCHAR () == '.' && LOOKAHEADTWICECHAR () == '.') { LCLMOVECHAR (); LCLMOVECHAR (); LCLMOVECHAR (); *bufPtr = '\0'; tokenSym = lsymbol_fromChars ("..."); tokenCode = LLT_TELIPSIS; } else { if (currentChar == '/' && LOOKAHEADCHAR () == '\\') { LCLMOVECHAR (); LCLMOVECHAR (); } else { while (LCLScanCharClass (currentChar) == OPCHAR) { LCLMOVECHAR (); } } *bufPtr = '\0'; tokenSym = lsymbol_fromChars (&tokenBuffer[0]); tokenCode = simpleOp; } break; /* white space */ case WHITECHAR: /*@-loopswitchbreak@*/ /*@-switchswitchbreak@*/ switch (currentChar) { case '\t': LCLMOVECHAR (); /* tabs only count as one character */ break; case '\v': case '\f': LCLMOVECHAR (); colNumber--; /* does not change column */ break; default: LCLMOVECHAR (); break; } /*@=switchswitchbreak@*/ *bufPtr = '\0'; tokenSym = lsymbol_fromChars (&tokenBuffer[0]); tokenCode = LLT_WHITESPACE; break; /* symbols */ case CHC_EXTENSION: LCLMOVECHAR (); /*@-switchswitchbreak@*/ switch (currentChar) { /* open and close */ case '(': LCLMOVECHAR (); while (LCLScanCharClass (currentChar) == IDCHAR) { LCLMOVECHAR (); } *bufPtr = '\0'; tokenSym = lsymbol_fromChars (&tokenBuffer[0]); tokenCode = openSym; break; case ')': LCLMOVECHAR (); while (LCLScanCharClass (currentChar) == IDCHAR) { LCLMOVECHAR (); } *bufPtr = '\0'; tokenSym = lsymbol_fromChars (&tokenBuffer[0]); tokenCode = closeSym; break; /* separator */ case ',': LCLMOVECHAR (); while (LCLScanCharClass (currentChar) == IDCHAR) { LCLMOVECHAR (); } *bufPtr = '\0'; tokenSym = lsymbol_fromChars (&tokenBuffer[0]); tokenCode = sepSym; break; /* simpleid */ case ':': LCLMOVECHAR (); while (LCLScanCharClass (currentChar) == IDCHAR) { LCLMOVECHAR (); } *bufPtr = '\0'; tokenSym = lsymbol_fromChars (&tokenBuffer[0]); tokenCode = simpleId; break; default: if (LCLScanCharClass (currentChar) == IDCHAR) { do { LCLMOVECHAR (); } while (LCLScanCharClass (currentChar) == IDCHAR); *bufPtr = '\0'; tokenSym = lsymbol_fromChars (&tokenBuffer[0]); tokenCode = simpleOp; } else { /* ** Meets none of the above. Take the extension ** character and the character following and treat ** together as a SINGLECHAR. SINGLECHARs tranlate into ** SIMPLEOPs. */ LCLMOVECHAR (); *bufPtr = '\0'; tokenSym = lsymbol_fromChars (&tokenBuffer[0]); tokenCode = simpleOp; } break; /*@=switchswitchbreak@*/ } break; default: LocalUserError ("unexpected character in input"); return; } /*@=loopswitchbreak@*/ } static bool nextCanBeCharLiteral (ltokenCode c) { switch (c) { /* A ' following these tokens starts a C character literal. */ case logicalOp: case equationSym: case eqSepSym: case openSym: case sepSym: case simpleOp: case LLT_COMMA: case LLT_EQUALS: case LLT_LBRACE: case LLT_LBRACKET: case LLT_LPAR: case eqOp: case LLT_BE: case LLT_ELSE: case LLT_ENSURES: case LLT_IF: case LLT_CONSTRAINT: case LLT_REQUIRES: case LLT_CHECKS: case LLT_BODY: case LLT_THEN: return (TRUE); /* A ' following these tokens means post */ case selectSym: case closeSym: case simpleId: case preSym: case anySym: case postSym: case LLT_QUOTE: case LLT_RBRACE: case LLT_RBRACKET: case LLT_RPAR: case LLT_RESULT: return (FALSE); /* Neither a C character literal nor post should follow these tokens */ case quantifierSym: case mapSym: case markerSym: case LLT_COLON: case LLT_SEMI: case LLT_VERTICALBAR: case LLT_MULOP: case LLT_CCHAR: case LLT_CFLOAT: case LLT_CINTEGER: case LLT_LCSTRING: case LLT_ALL: case LLT_ANYTHING: case LLT_CONSTANT: case LLT_FOR: case LLT_IMMUTABLE: case LLT_OBJ: case LLT_OUT: case LLT_IMPORTS: case LLT_ISSUB: case LLT_LET: case LLT_MODIFIES: case LLT_CLAIMS: case LLT_MUTABLE: case LLT_FRESH: case LLT_NOTHING: case LLT_PRIVATE: case LLT_SPEC: case LLT_SIZEOF: case LLT_TAGGEDUNION: case LLT_TYPE: case LLT_UNCHANGED: case LLT_USES: case LLT_CHAR: case LLT_CONST: case LLT_DOUBLE: case LLT_ENUM: case LLT_FLOAT: case LLT_INT: case LLT_TYPEDEF_NAME: case LLT_LONG: case LLT_SHORT: case LLT_STRUCT: case LLT_SIGNED: case LLT_UNKNOWN: case LLT_UNION: case LLT_UNSIGNED: case LLT_VOID: case LLT_VOLATILE: return (FALSE); /* These tokens should have been ignored */ case NOTTOKEN: case commentSym: case LLT_WHITESPACE: case LLT_EOL: case LEOFTOKEN: llcontbuglit ("scanline: nextCanBeChar"); return FALSE; BADDEFAULT; } BADEXIT; } void LCLScanLine (char *line) { ltoken newToken; lsymbol CCommentSym = lsymbol_fromChars ("/*"); size_t linelength = strlen (line); static bool inSpecComment = FALSE; line[(int)linelength] = '\n'; currentLine = line; currentChar = *currentLine++; context_processedSpecLine (); incLine (); colNumber = 1; if (inComment) { ScanCComment (); if (reportComments) { *bufPtr = '\0'; newToken = ltoken_createRaw (simpleId, lsymbol_fromChars (&tokenBuffer[0])); LCLScanFreshToken (newToken); } } if (inSpecComment) { if (currentChar == '*' && LOOKAHEADCHAR () == '/') { LCLMOVECHAR (); LCLMOVECHAR (); inSpecComment = FALSE; } } /*@+loopexec@*/ for (;;) { if (inSpecComment && currentChar == '*' && LOOKAHEADCHAR () == '/') { LCLMOVECHAR (); LCLMOVECHAR (); inSpecComment = FALSE; } bufPtr = &tokenBuffer[0]; startCol = colNumber; /*@-loopswitchbreak@*/ switch (startClass[(int)currentChar]) { case STARTCNUM: ScanCNumber (); break; case STARTCNUMDOT: if (isDigit[(int) LOOKAHEADCHAR ()]) { ScanCNumber (); } else { ScanOther (); } break; case STARTCSTR: ScanCString (); break; case STARTCCHAR: if (nextCanBeCharLiteral (prevTokenCode)) { ScanCChar (); } else { ScanOther (); } break; case STARTWIDE: if (LOOKAHEADCHAR () == 'L' && LOOKAHEADTWICECHAR () == '\"') { ScanCString (); } else if (LOOKAHEADCHAR () == 'L' && LOOKAHEADTWICECHAR () == '\'') { ScanCChar (); } else { ScanOther (); } break; case STARTSLASH: if (LOOKAHEADCHAR () == '*') { LCLMOVECHAR (); LCLMOVECHAR (); if (currentChar == '@') { char *s = mstring_createEmpty (); LCLMOVECHAR (); while (currentChar != '\0' && currentChar != ' ' && currentChar != '*' && currentChar != '\t' && currentChar != '\n') { s = mstring_append (s, currentChar); LCLMOVECHAR (); } if (mstring_equal (s, "alt")) { tokenCode = LLT_VERTICALBAR; tokenSym = lsymbol_fromChars ("|"); inSpecComment = TRUE; } else { ScanCComment (); tokenCode = commentSym; tokenSym = CCommentSym; } sfree (s); break; } else { ScanCComment (); tokenCode = commentSym; tokenSym = CCommentSym; break; } } else { ScanOther (); } break; case STARTOTHER: ScanOther (); break; default: llcontbuglit ("LCLScanLine: bad case"); break; } /*@=loopswitchbreak@*/ /* ** Above code only "guessed" at token type. Insert it into the ** TokenTable. If the token already exists, it is returned as ** previously defined. If it does not exist, it is inserted as the ** token code computed above. */ newToken = LCLInsertToken (tokenCode, tokenSym, lsymbol_undefined, FALSE); if (LCLIsSyn (ltoken_getText (newToken))) { /* ** Token is a synonym. Get the actual token and set the raw ** text to the synonym name. */ newToken = ltoken_copy (LCLGetTokenForSyn (ltoken_getText (newToken))); ltoken_setRawText (newToken, tokenSym); } else { newToken = ltoken_copy (newToken); } ltoken_setCol (newToken, startCol); ltoken_setLine (newToken, inputStream_thisLineNumber (LCLScanSource ())); ltoken_setFileName (newToken, inputStream_fileName (LCLScanSource ())); if (ltoken_getCode (newToken) == commentSym) { if (tokenSym == CCommentSym) { /* C-style comment */ ltoken_free (commentTok); commentTok = ltoken_copy (newToken); if (!inComment && reportComments) { *bufPtr = '\0'; ltoken_setRawText (newToken, lsymbol_fromChars (&tokenBuffer[0])); LCLScanFreshToken (newToken); } else { ltoken_free (newToken); } } else { /* LSL-style comment */ bufPtr = &tokenBuffer[0]; while (!LCLIsEndComment (currentChar)) { LCLMOVECHAR (); } if (LCLScanCharClass (currentChar) != CHC_NULL) { /* Not EOL character. Toss it out. */ LCLMOVECHAR (); } if (reportComments) { *bufPtr = '\0'; ltoken_setRawText (newToken, lsymbol_fromChars (&tokenBuffer[0])); LCLScanFreshToken (newToken); } else { ltoken_free (newToken); } } } else if (ltoken_getCode (newToken) == LLT_EOL) { if (reportEOL) { LCLScanFreshToken (newToken); } else { ltoken_free (newToken); } line[(int) linelength] = '\0'; return; } else if (ltoken_getCode (newToken) != LLT_WHITESPACE) { prevTokenCode = ltoken_getCode (newToken); LCLScanFreshToken (newToken); } else { ltoken_free (newToken); } } /*@=loopexec@*/ } /*@exposed@*/ ltoken LCLScanEofToken (void) { ltoken t = LCLInsertToken (LEOFTOKEN, lsymbol_fromChars ("E O F"), 0, TRUE); if (inComment) { lclerror (commentTok, cstring_makeLiteral ("Unterminated comment")); } ltoken_setCol (t, colNumber); ltoken_setLine (t, inputStream_thisLineNumber (LCLScanSource ())); ltoken_setFileName (t, inputStream_fileName (LCLScanSource ())); return t; } void LCLReportEolTokens (bool setting) { reportEOL = setting; } static void LocalUserError (char *msg) { inputStream s = LCLScanSource (); llfatalerror (message ("%s:%d,%d: %s", inputStream_fileName (s), inputStream_thisLineNumber (s), colNumber, cstring_fromChars (msg))); } void LCLScanLineInit (void) { int i; setCodePoint (); reportEOL = FALSE; reportComments = FALSE; for (i = 0; i <= LASTCHAR; i++) { LCLcharClass[i] = charClassDef[i]; } setCodePoint (); /* ** Make sure first postion is never used because use the 0th index to ** mean empty. */ firstReserved = lsymbol_fromChars (FIRSTRESERVEDNAME); setCodePoint (); /* Predefined LSL Tokens */ ltoken_forall = LCLReserveToken (quantifierSym, "\\forall"); setCodePoint (); ltoken_exists = LCLReserveToken (quantifierSym, "\\exists"); ltoken_implies = LCLReserveToken (logicalOp, "\\implies"); ltoken_eqsep = LCLReserveToken (eqSepSym, "\\eqsep"); ltoken_select = LCLReserveToken (selectSym, "\\select"); ltoken_open = LCLReserveToken (openSym, "\\open"); ltoken_sep = LCLReserveToken (sepSym, "\\,"); ltoken_close = LCLReserveToken (closeSym, "\\close"); ltoken_id = LCLReserveToken (simpleId, "\\:"); ltoken_arrow = LCLReserveToken (mapSym, "\\arrow"); ltoken_marker = LCLReserveToken (markerSym, "\\marker"); ltoken_pre = LCLReserveToken (preSym, "\\pre"); ltoken_post = LCLReserveToken (postSym, "\\post"); ltoken_comment = LCLReserveToken (commentSym, "\\comment"); ltoken_any = LCLReserveToken (anySym, "\\any"); ltoken_result = LCLReserveToken (LLT_RESULT, "result"); ltoken_typename = LCLReserveToken (LLT_TYPEDEF_NAME, "TYPEDEF_NAME"); ltoken_setIdType (ltoken_typename, SID_TYPE); /* ** Not context_getBoolName () --- "bool" is built in to LCL. ** This is bogus, but necessary for a lot of old lcl files. */ ltoken_bool = LCLReserveToken (LLT_TYPEDEF_NAME, "bool"); ltoken_lbracked = LCLReserveToken (LLT_LBRACKET, "["); ltoken_rbracket = LCLReserveToken (LLT_RBRACKET, "]"); (void) LCLReserveToken (LLT_COLON, ":"); (void) LCLReserveToken (LLT_COMMA, ","); (void) LCLReserveToken (LLT_EQUALS, "="); (void) LCLReserveToken (LLT_LBRACE, "{"); (void) LCLReserveToken (LLT_LPAR, "("); (void) LCLReserveToken (LLT_RBRACE, "}"); (void) LCLReserveToken (LLT_RPAR, ")"); (void) LCLReserveToken (LLT_SEMI, ";"); (void) LCLReserveToken (LLT_VERTICALBAR, "|"); (void) LCLReserveToken (LLT_MULOP, "*"); (void) LCLReserveToken (LLT_WHITESPACE, " "); (void) LCLReserveToken (LLT_WHITESPACE, "\t"); (void) LCLReserveToken (LLT_WHITESPACE, "\f"); (void) LCLReserveToken (LLT_WHITESPACE, "\n"); (void) LCLReserveToken (LEOFTOKEN, "E O F"); (void) LCLReserveToken (LLT_EOL, "E O L"); /* LSL Keywords */ ltoken_and = LCLReserveToken (logicalOp, "\\and"); ltoken_or = LCLReserveToken (logicalOp, "\\or"); ltoken_equals = LCLReserveToken (equationSym, "\\equals"); ltoken_eq = LCLReserveToken (eqOp, "\\eq"); ltoken_neq = LCLReserveToken (eqOp, "\\neq"); ltoken_not = LCLReserveToken (simpleOp, "\\not"); ltoken_true = LCLReserveToken (simpleId, "true"); ltoken_false = LCLReserveToken (simpleId, "false"); /* LCL Keywords */ (void) LCLReserveToken (LLT_ALL, "all"); (void) LCLReserveToken (LLT_ANYTHING, "anything"); (void) LCLReserveToken (LLT_BE, "be"); (void) LCLReserveToken (LLT_CONSTANT, "constant"); (void) LCLReserveToken (LLT_CHECKS, "checks"); (void) LCLReserveToken (LLT_ELSE, "else"); (void) LCLReserveToken (LLT_ENSURES, "ensures"); (void) LCLReserveToken (LLT_FOR, "for"); (void) LCLReserveToken (LLT_IF, "if"); (void) LCLReserveToken (LLT_IMMUTABLE, "immutable"); (void) LCLReserveToken (LLT_OBJ, "obj"); (void) LCLReserveToken (LLT_OUT, "out"); (void) LCLReserveToken (LLT_ITER, "iter"); (void) LCLReserveToken (LLT_YIELD, "yield"); (void) LCLReserveToken (LLT_PARTIAL, "partial"); (void) LCLReserveToken (LLT_ONLY, "only"); (void) LCLReserveToken (LLT_UNDEF, "undef"); (void) LCLReserveToken (LLT_KILLED, "killed"); (void) LCLReserveToken (LLT_OWNED, "owned"); (void) LCLReserveToken (LLT_DEPENDENT, "dependent"); (void) LCLReserveToken (LLT_PARTIAL, "partial"); (void) LCLReserveToken (LLT_RELDEF, "reldef"); (void) LCLReserveToken (LLT_KEEP, "keep"); (void) LCLReserveToken (LLT_KEPT, "kept"); (void) LCLReserveToken (LLT_TEMP, "temp"); (void) LCLReserveToken (LLT_SHARED, "shared"); (void) LCLReserveToken (LLT_RELNULL, "relnull"); (void) LCLReserveToken (LLT_RELDEF, "reldef"); (void) LCLReserveToken (LLT_CHECKED, "checked"); (void) LCLReserveToken (LLT_UNCHECKED, "unchecked"); (void) LCLReserveToken (LLT_CHECKEDSTRICT, "checkedstrict"); (void) LCLReserveToken (LLT_CHECKMOD, "checkmod"); (void) LCLReserveToken (LLT_TRUENULL, "truenull"); (void) LCLReserveToken (LLT_FALSENULL, "falsenull"); (void) LCLReserveToken (LLT_LNULL, "null"); (void) LCLReserveToken (LLT_LNOTNULL, "notnull"); (void) LCLReserveToken (LLT_RETURNED, "returned"); (void) LCLReserveToken (LLT_OBSERVER, "observer"); (void) LCLReserveToken (LLT_EXPOSED, "exposed"); (void) LCLReserveToken (LLT_REFCOUNTED, "refcounted"); (void) LCLReserveToken (LLT_REFS, "refs"); (void) LCLReserveToken (LLT_NEWREF, "newref"); (void) LCLReserveToken (LLT_TEMPREF, "tempref"); (void) LCLReserveToken (LLT_KILLREF, "killref"); (void) LCLReserveToken (LLT_NULLTERMINATED, "nullterminated"); (void) LCLReserveToken (LLT_EXITS, "exits"); (void) LCLReserveToken (LLT_MAYEXIT, "mayexit"); (void) LCLReserveToken (LLT_TRUEEXIT, "trueexit"); (void) LCLReserveToken (LLT_FALSEEXIT, "falseexit"); (void) LCLReserveToken (LLT_NEVEREXIT, "neverexit"); (void) LCLReserveToken (LLT_SEF, "sef"); (void) LCLReserveToken (LLT_UNUSED, "unused"); (void) LCLReserveToken (LLT_UNIQUE, "unique"); (void) LCLReserveToken (LLT_IMPORTS, "imports"); (void) LCLReserveToken (LLT_CONSTRAINT, "constraint"); (void) LCLReserveToken (LLT_LET, "let"); (void) LCLReserveToken (LLT_MODIFIES, "modifies"); (void) LCLReserveToken (LLT_CLAIMS, "claims"); (void) LCLReserveToken (LLT_BODY, "body"); (void) LCLReserveToken (LLT_MUTABLE, "mutable"); (void) LCLReserveToken (LLT_FRESH, "fresh"); (void) LCLReserveToken (LLT_NOTHING, "nothing"); (void) LCLReserveToken (LLT_INTERNAL, "internalState"); (void) LCLReserveToken (LLT_FILESYS, "fileSystem"); (void) LCLReserveToken (LLT_PRIVATE, "private"); (void) LCLReserveToken (LLT_SPEC, "spec"); (void) LCLReserveToken (LLT_REQUIRES, "requires"); (void) LCLReserveToken (LLT_SIZEOF, "sizeof"); (void) LCLReserveToken (LLT_TAGGEDUNION, "taggedunion"); (void) LCLReserveToken (LLT_THEN, "then"); (void) LCLReserveToken (LLT_TYPE, "type"); (void) LCLReserveToken (LLT_TYPEDEF, "typedef"); (void) LCLReserveToken (LLT_UNCHANGED, "unchanged"); (void) LCLReserveToken (LLT_USES, "uses"); (void) LCLReserveToken (LLT_PRINTFLIKE, "printflike"); (void) LCLReserveToken (LLT_SCANFLIKE, "scanflike"); (void) LCLReserveToken (LLT_MESSAGELIKE, "messagelike"); /* LCL C Keywords */ (void) LCLReserveToken (LLT_CHAR, "char"); (void) LCLReserveToken (LLT_CONST, "const"); (void) LCLReserveToken (LLT_DOUBLE, "double"); (void) LCLReserveToken (LLT_ENUM, "enum"); /* comment out so we can add in lclinit.lci: synonym double float */ /* LCLReserveToken (LLT_FLOAT, "float"); */ /* But we need to make the scanner parse "float" not as a simpleId, but as a TYPEDEF_NAME. This is done later in abstract_init */ (void) LCLReserveToken (LLT_INT, "int"); (void) LCLReserveToken (LLT_LONG, "long"); (void) LCLReserveToken (LLT_SHORT, "short"); (void) LCLReserveToken (LLT_STRUCT, "struct"); (void) LCLReserveToken (LLT_SIGNED, "signed"); (void) LCLReserveToken (LLT_UNION, "union"); (void) LCLReserveToken (LLT_UNKNOWN, "__unknown"); (void) LCLReserveToken (LLT_UNSIGNED, "unsigned"); (void) LCLReserveToken (LLT_VOID, "void"); (void) LCLReserveToken (LLT_VOLATILE, "volatile"); setCodePoint (); } void LCLScanLineReset (void) { inComment = FALSE; prevTokenCode = LLT_LPAR; /* Presume first ' starts literal */ } void LCLScanLineCleanup (void) { } bool LCLIsEndComment (char c) { return LCLcharClass[(int)(c)].endCommentChar; } charCode LCLScanCharClass (char c) { return LCLcharClass[(int)(c)].code; } void LCLSetCharClass (char c, charCode cod) { LCLcharClass[(int)(c)].code = (cod); } void LCLSetEndCommentChar (char c, bool flag) { LCLcharClass[(int)(c)].endCommentChar = flag; }
{ "pile_set_name": "Github" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_144) on Wed Sep 06 08:23:35 PDT 2017 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class javax.faces.annotation.ManagedProperty (Java(TM) EE 8 Specification APIs)</title> <meta name="date" content="2017-09-06"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class javax.faces.annotation.ManagedProperty (Java(TM) EE 8 Specification APIs)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../javax/faces/annotation/ManagedProperty.html" title="annotation in javax.faces.annotation">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="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?javax/faces/annotation/class-use/ManagedProperty.html" target="_top">Frames</a></li> <li><a href="ManagedProperty.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class javax.faces.annotation.ManagedProperty" class="title">Uses of Class<br>javax.faces.annotation.ManagedProperty</h2> </div> <div class="classUseContainer">No usage of javax.faces.annotation.ManagedProperty</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../javax/faces/annotation/ManagedProperty.html" title="annotation in javax.faces.annotation">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="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?javax/faces/annotation/class-use/ManagedProperty.html" target="_top">Frames</a></li> <li><a href="ManagedProperty.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 1996-2017, <a href="http://www.oracle.com">Oracle</a> and/or its affiliates. All Rights Reserved. Use is subject to <a href="../../../../doc-files/speclicense.html" target="_top">license terms</a>.</small></p> </body> </html>
{ "pile_set_name": "Github" }
/* * Copyright (C) 2017-2019 Alibaba Group Holding Limited */ #include "stdio.h" #include "soc.h" #include "dtest.h" #include "drv_spi.h" #include "pin.h" #include "test_driver_config.h" #define OPERATE_ADDR 0x0 #define OPERATE_LEN 256 #define SPIFLASH_BASE_VALUE 0x0 #define SPI_TEST_BAUD 0x300000 /* 300KHZ*/ uint8_t input[OPERATE_LEN] = {0}; uint8_t output[OPERATE_LEN] = {0}; spi_handle_t g_spi_handle; static uint8_t erase_read_flag = 0; static uint8_t program_read_flag = 0; extern int32_t w25q64flash_read_id(spi_handle_t handle, uint32_t *id_num); extern int32_t w25q64flash_erase_sector(spi_handle_t handle, uint32_t addr); extern int32_t w25q64flash_erase_chip(spi_handle_t handle); extern int32_t w25q64flash_program_data(spi_handle_t handle, uint32_t addr, const void *data, uint32_t cnt); extern int32_t w25q64flash_read_data(spi_handle_t handle, uint32_t addr, void *data, uint32_t cnt); typedef struct { int32_t baud; spi_mode_e mode; spi_format_e format; spi_bit_order_e order; spi_ss_mode_e ss_mode; int32_t bit_width; uint32_t expect_out; } spi_test_t; static spi_test_t spi_config_cases[] = { {SPI_TEST_BAUD, SPI_MODE_MASTER, SPI_FORMAT_CPOL1_CPHA1 + 1, SPI_ORDER_MSB2LSB, SPI_SS_MASTER_SW, 8, CSI_DRV_ERRNO_SPI_BASE | SPI_ERROR_FRAME_FORMAT}, {1, SPI_MODE_MASTER, SPI_FORMAT_CPOL0_CPHA0, SPI_ORDER_MSB2LSB, SPI_SS_MASTER_HW_OUTPUT, 8, CSI_DRV_ERRNO_SPI_BASE | DRV_ERROR_PARAMETER}, {SPI_TEST_BAUD, SPI_MODE_MASTER, SPI_FORMAT_CPOL0_CPHA0, SPI_ORDER_MSB2LSB, SPI_SS_MASTER_HW_OUTPUT, 8, 0}, {SPI_TEST_BAUD, SPI_MODE_MASTER, SPI_FORMAT_CPOL0_CPHA0, SPI_ORDER_MSB2LSB, SPI_SS_MASTER_SW, 8, 0}, {SPI_TEST_BAUD, SPI_MODE_MASTER, SPI_FORMAT_CPOL0_CPHA0, SPI_ORDER_MSB2LSB, SPI_SS_MASTER_SW, 1, CSI_DRV_ERRNO_SPI_BASE | SPI_ERROR_DATA_BITS}, {SPI_TEST_BAUD, SPI_MODE_MASTER, SPI_FORMAT_CPOL0_CPHA0, SPI_ORDER_MSB2LSB, SPI_SS_MASTER_SW, 17, CSI_DRV_ERRNO_SPI_BASE | SPI_ERROR_DATA_BITS}, }; static void spi_event_cb_fun(int32_t idx, spi_event_e event) { } static void test_w25q64fv_read(void) { w25q64flash_read_data(g_spi_handle, OPERATE_ADDR, output, OPERATE_LEN); int i; for (i = 0; i < OPERATE_LEN; i++) { if (output[i] != input[i]) { program_read_flag = 1; break; } } ASSERT_TRUE(program_read_flag == 0); int ret; ret = csi_spi_uninitialize(g_spi_handle); ASSERT_TRUE(ret == 0); } static void test_w25q64fv_program(void) { int i; for (i = 0; i < sizeof(input); i++) { input[i] = i + SPIFLASH_BASE_VALUE; } memset(output, 0xfb, sizeof(output)); w25q64flash_program_data(g_spi_handle, OPERATE_ADDR, input, OPERATE_LEN); } static void test_w25q64fv_sector_erase(void) { w25q64flash_erase_sector(g_spi_handle, OPERATE_ADDR); w25q64flash_read_data(g_spi_handle, OPERATE_ADDR, output, OPERATE_LEN); int i; for (i = 0; i < OPERATE_LEN; i++) { if (output[i] != 0xff) { erase_read_flag = 1; break; } } ASSERT_TRUE(erase_read_flag == 0); } void test_pin_spi_init(void) { drv_pinmux_config(TEST_PIN_SPI_MISO, TEST_PIN_SPI_MISO_FUNC); drv_pinmux_config(TEST_PIN_SPI_MOSI, TEST_PIN_SPI_MOSI_FUNC); drv_pinmux_config(TEST_PIN_SPI_CS, TEST_PIN_SPI_CS_FUNC); drv_pinmux_config(TEST_PIN_SPI_SCK, TEST_PIN_SPI_SCK_FUNC); } static void test_w25q64fv_read_id(void) { uint8_t id[3] = {0x11, 0x11}; test_pin_spi_init(); /* initialize spi driver */ g_spi_handle = csi_spi_initialize(TEST_SPI_IDX, spi_event_cb_fun); ASSERT_TRUE(g_spi_handle != NULL); w25q64flash_read_id(g_spi_handle, (uint32_t *)&id); printf("the spiflash id is %x %x\r\n", id[0], id[1]); } static void test_csi_spi_config(void) { int32_t ret; uint32_t i; spi_handle_t spi_handle; /* initialize spi driver */ spi_handle = csi_spi_initialize(TEST_SPI_IDX, NULL); ASSERT_TRUE(spi_handle != NULL); for (i = 0; i < sizeof(spi_config_cases) / (sizeof(spi_test_t)); i++) { ret = csi_spi_config(spi_handle, spi_config_cases[i].baud, spi_config_cases[i].mode, spi_config_cases[i].format, spi_config_cases[i].order, spi_config_cases[i].ss_mode, spi_config_cases[i].bit_width); ASSERT_TRUE(ret == spi_config_cases[i].expect_out); } } int test_spi() { dtest_suite_info_t test_suite_info = { "test_spi", NULL, NULL, NULL, NULL }; dtest_suite_t *test_suite = dtest_add_suite(&test_suite_info); dtest_case_info_t test_case_info_array[] = { { "test_w25q64fv_read", test_w25q64fv_read, SPI_TEST_W25Q64FV_READ_EN }, { "test_w25q64fv_program", test_w25q64fv_program, SPI_TEST_W25Q64FV_PROGRAM_EN }, { "test_w25q64fv_sector_erase", test_w25q64fv_sector_erase, SPI_TEST_W25Q64FV_SECTOR_ERASE_EN }, { "test_w25q64fv_read_id", test_w25q64fv_read_id, SPI_TEST_W25Q64FV_RDID_EN }, { "test_csi_spi_config", test_csi_spi_config, SPI_TEST_CONFIG_INTERFACE_EN }, { NULL, NULL } }; dtest_add_cases(test_suite, test_case_info_array); return 0; }
{ "pile_set_name": "Github" }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. export { OneOfField } from './OneOfField';
{ "pile_set_name": "Github" }
<!-- Description: feed title content xml:base overrides parent element Expect: bozo and feed['title_detail']['base'] == u'http://example.com/test/' --> <feed version="0.3" xmlns="http://purl.org/atom/ns#" xml:base="http://example.com/parent/"> <title type="application/xhtml+xml" xml:base="http://example.com/test/"><div xmlns="http://www.w3.org/1999/xhtml">Example <a href="test.html">test</a></div></title> </feed
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <root> <!-- Microsoft ResX Schema Version 2.0 The primary goals of this format is to allow a simple XML format that is mostly human readable. The generation and parsing of the various data types are done through the TypeConverter classes associated with the data types. Example: ... ado.net/XML headers & schema ... <resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="version">2.0</resheader> <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data> <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> <value>[base64 mime encoded serialized .NET Framework object]</value> </data> <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> <comment>This is a comment</comment> </data> There are any number of "resheader" rows that contain simple name/value pairs. Each data row contains a name, and value. The row also contains a type or mimetype. Type corresponds to a .NET class that support text/value conversion through the TypeConverter architecture. Classes that don't support this are serialized and stored with the mimetype set. The mimetype is used for serialized objects, and tells the ResXResourceReader how to depersist the object. This is currently not extensible. For a given mimetype the value must be set accordingly: Note - application/x-microsoft.net.object.binary.base64 is the format that the ResXResourceWriter will generate, however the reader can read any of the formats listed below. mimetype: application/x-microsoft.net.object.binary.base64 value : The object must be serialized with : System.Serialization.Formatters.Binary.BinaryFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.soap.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Soap.SoapFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.bytearray.base64 value : The object must be serialized into a byte array : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:element name="root" msdata:IsDataSet="true"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:element name="metadata"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" /> <xsd:attribute name="type" type="xsd:string" /> <xsd:attribute name="mimetype" type="xsd:string" /> </xsd:complexType> </xsd:element> <xsd:element name="assembly"> <xsd:complexType> <xsd:attribute name="alias" type="xsd:string" /> <xsd:attribute name="name" type="xsd:string" /> </xsd:complexType> </xsd:element> <xsd:element name="data"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" /> <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> </xsd:complexType> </xsd:element> <xsd:element name="resheader"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" /> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema> <resheader name="resmimetype"> <value>text/microsoft-resx</value> </resheader> <resheader name="version"> <value>2.0</value> </resheader> <resheader name="reader"> <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <resheader name="writer"> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> </root>
{ "pile_set_name": "Github" }
#!/bin/bash # Importing useful functions for cc testing if [ -f ./func.sh ]; then source ./func.sh elif [ -f scripts/func.sh ]; then source scripts/func.sh fi ## Join all the peers to the channel echo_b "=== Join peers ${PEERS} from org ${ORGS} into ${APP_CHANNEL}... ===" for org in "${ORGS[@]}" do for peer in "${PEERS[@]}" do channelJoin ${APP_CHANNEL} $org $peer done done echo_g "=== Join peers ${PEERS} from org ${ORGS} into ${APP_CHANNEL} Complete ===" echo
{ "pile_set_name": "Github" }
# # Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License version 2 only, as # published by the Free Software Foundation. Oracle designates this # particular file as subject to the "Classpath" exception as provided # by Oracle in the LICENSE file that accompanied this code. # # This code is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License # version 2 for more details (a copy is included in the LICENSE file that # accompanied this code). # # You should have received a copy of the GNU General Public License version # 2 along with this work; if not, write to the Free Software Foundation, # Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. # # Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA # or visit www.oracle.com if you need additional information or have any # questions. # # (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved # (C) Copyright IBM Corp. 1996 - 1999 - All Rights Reserved # # The original version of this source code and documentation # is copyrighted and owned by Taligent, Inc., a wholly-owned # subsidiary of IBM. These materials are provided under terms # of a License Agreement between Taligent and Sun. This technology # is protected by multiple US and International patents. # # This notice and attribution to Taligent may not be removed. # Taligent is a registered trademark of Taligent, Inc. ISK=kr.
{ "pile_set_name": "Github" }
object i0 extends collection.immutable.Double class i1(i2: i0) extends ((( 5 i2: String) { def i2 = 0 } class i3 extends i0 { private def i1: String = "" } object i4 extends i1 { val List(i2 => Int) = i2() new i2() {} } i2.asInstanceOf[i4] } trait i5 { var i6 = if (i3) map(_._) }
{ "pile_set_name": "Github" }
#import <Foundation/NSObject.h> #import <stdint.h> @class NSArray, NSString; enum { NSUndoCloseGroupingRunLoopOrdering = 350000 }; FOUNDATION_EXPORT NSString * const NSUndoManagerGroupIsDiscardableKey; FOUNDATION_EXPORT NSString * const NSUndoManagerCheckpointNotification; FOUNDATION_EXPORT NSString * const NSUndoManagerWillUndoChangeNotification; FOUNDATION_EXPORT NSString * const NSUndoManagerWillRedoChangeNotification; FOUNDATION_EXPORT NSString * const NSUndoManagerDidUndoChangeNotification; FOUNDATION_EXPORT NSString * const NSUndoManagerDidRedoChangeNotification; FOUNDATION_EXPORT NSString * const NSUndoManagerDidOpenUndoGroupNotification; FOUNDATION_EXPORT NSString * const NSUndoManagerWillCloseUndoGroupNotification; FOUNDATION_EXPORT NSString * const NSUndoManagerDidCloseUndoGroupNotification; @interface NSUndoManager : NSObject - (void)beginUndoGrouping; - (void)endUndoGrouping; - (NSInteger)groupingLevel; - (void)disableUndoRegistration; - (void)enableUndoRegistration; - (BOOL)isUndoRegistrationEnabled; - (BOOL)groupsByEvent; - (void)setGroupsByEvent:(BOOL)groupsByEvent; - (void)setLevelsOfUndo:(NSUInteger)levels; - (NSUInteger)levelsOfUndo; - (void)setRunLoopModes:(NSArray *)runLoopModes; - (NSArray *)runLoopModes; - (void)undo; - (void)redo; - (void)undoNestedGroup; - (BOOL)canUndo; - (BOOL)canRedo; - (BOOL)isUndoing; - (BOOL)isRedoing; - (void)removeAllActions; - (void)removeAllActionsWithTarget:(id)target; - (void)registerUndoWithTarget:(id)target selector:(SEL)selector object:(id)anObject; - (id)prepareWithInvocationTarget:(id)target; - (void)setActionIsDiscardable:(BOOL)discardable; - (BOOL)undoActionIsDiscardable; - (BOOL)redoActionIsDiscardable; - (NSString *)undoActionName; - (NSString *)redoActionName; - (void)setActionName:(NSString *)actionName; - (NSString *)undoMenuItemTitle; - (NSString *)redoMenuItemTitle; - (NSString *)undoMenuTitleForUndoActionName:(NSString *)actionName; - (NSString *)redoMenuTitleForUndoActionName:(NSString *)actionName; @end
{ "pile_set_name": "Github" }
var assert = require('assert'); var wordwrap = require('wordwrap'); var fs = require('fs'); var idleness = fs.readFileSync(__dirname + '/idleness.txt', 'utf8'); exports.stop80 = function () { var lines = wordwrap(80)(idleness).split(/\n/); var words = idleness.split(/\s+/); lines.forEach(function (line) { assert.ok(line.length <= 80, 'line > 80 columns'); var chunks = line.match(/\S/) ? line.split(/\s+/) : []; assert.deepEqual(chunks, words.splice(0, chunks.length)); }); }; exports.start20stop60 = function () { var lines = wordwrap(20, 100)(idleness).split(/\n/); var words = idleness.split(/\s+/); lines.forEach(function (line) { assert.ok(line.length <= 100, 'line > 100 columns'); var chunks = line .split(/\s+/) .filter(function (x) { return x.match(/\S/) }) ; assert.deepEqual(chunks, words.splice(0, chunks.length)); assert.deepEqual(line.slice(0, 20), new Array(20 + 1).join(' ')); }); };
{ "pile_set_name": "Github" }
#include <core.p4> #define V1MODEL_VERSION 20180101 #include <v1model.p4> header Ethernet { bit<48> src; bit<48> dst; bit<16> type; } struct parsed_packet_t { Ethernet eth; } struct local_metadata_t { } parser parse(packet_in pk, out parsed_packet_t hdr, inout local_metadata_t local_metadata, inout standard_metadata_t standard_metadata) { state start { pk.extract<Ethernet>(hdr.eth); transition accept; } } control ingress(inout parsed_packet_t hdr, inout local_metadata_t local_metadata, inout standard_metadata_t standard_metadata) { @hidden action parser_errorbmv2l30() { hdr.eth.setValid(); hdr.eth.type = 16w0; hdr.eth.src = 48w0; hdr.eth.dst = 48w0; } @hidden action parser_errorbmv2l35() { standard_metadata.egress_spec = 9w0; } @hidden table tbl_parser_errorbmv2l30 { actions = { parser_errorbmv2l30(); } const default_action = parser_errorbmv2l30(); } @hidden table tbl_parser_errorbmv2l35 { actions = { parser_errorbmv2l35(); } const default_action = parser_errorbmv2l35(); } apply { if (standard_metadata.parser_error == error.PacketTooShort) { tbl_parser_errorbmv2l30.apply(); } tbl_parser_errorbmv2l35.apply(); } } control egress(inout parsed_packet_t hdr, inout local_metadata_t local_metadata, inout standard_metadata_t standard_metadata) { apply { } } control deparser(packet_out b, in parsed_packet_t hdr) { apply { b.emit<Ethernet>(hdr.eth); } } control verify_checks(inout parsed_packet_t hdr, inout local_metadata_t local_metadata) { apply { } } control compute_checksum(inout parsed_packet_t hdr, inout local_metadata_t local_metadata) { apply { } } V1Switch<parsed_packet_t, local_metadata_t>(parse(), verify_checks(), ingress(), egress(), compute_checksum(), deparser()) main;
{ "pile_set_name": "Github" }
\ This file was automatically generated by Zimpl \ set I := { 1..10 }; \ var x[I] integer >= -10 <= 10; \ subto c1: vif x[1] < 0 then x[2] == 9 end; \ subto c2: vif x[1] <= 0 then x[2] == 8 end; \ subto c3: vif x[1] == 0 then x[2] == 7 end; \ subto c4: vif x[1] != 0 then x[2] == 6 end; \ subto c5: vif x[1] >= 0 then x[2] == 5 end; \ subto c6: vif x[1] > 0 then x[2] == 4 end; \ subto c7: forall <i> in I with i < 4 : vif vabs(x[1] + x[2]) <= 5 then x[3] + x[4] >= 5 else x[5] + x[6] >= 8 end; \ subto c8: vif 3 * x[1] + x[2] != 7 then sum <i> in I : x[i] <= 17 else sum <i> in I : x[i] >= 5 end; \ subto c9: vif x[1] == 1 and x[2] > 5 or x[1] == 2 and x[2] < 8 then x[3] == 7 end; \ subto c10: vif x[1] != 1 xor not x[2] == 5 then x[3] <= 2 end; \Problem name: vinst.zpl Minimize Objective: Subject to c1_1_a_0: + __c1_1_xm_1@b - __c1_1_xp_0@a + x#1 = 0 c1_1_b_1: - __c1_1_xp_0@a + __c1_1_bp_2@c <= 0 c1_1_c_2: - __c1_1_xm_1@b + __c1_1_bm_3@d <= 0 c1_1_d_3: - __c1_1_xp_0@a +10 __c1_1_bp_2@c >= 0 c1_1_e_4: - __c1_1_xm_1@b +10 __c1_1_bm_3@d >= 0 c1_1_f_5: + __c1_1_bm_3@d + __c1_1_bp_2@c <= 1 c1_1_g_6: - __c1_1_bm_3@d + __c1_1_re_4@e = 0 c1_1_t_r: + x#2 + __c1_1_re_4@e <= 10 c1_1_t_l: + x#2 -19 __c1_1_re_4@e >= -10 c2_1_a_7: + __c2_1_xm_6@10 - __c2_1_xp_5@f + x#1 = 0 c2_1_b_8: - __c2_1_xp_5@f + __c2_1_bp_7@11 <= 0 c2_1_c_9: - __c2_1_xm_6@10 + __c2_1_bm_8@12 <= 0 c2_1_d_10: - __c2_1_xp_5@f +10 __c2_1_bp_7@11 >= 0 c2_1_e_11: - __c2_1_xm_6@10 +10 __c2_1_bm_8@12 >= 0 c2_1_f_12: + __c2_1_bm_8@12 + __c2_1_bp_7@11 <= 1 c2_1_g_13: + __c2_1_bp_7@11 + __c2_1_re_9@13 = 1 c2_1_t_r: + x#2 +2 __c2_1_re_9@13 <= 10 c2_1_t_l: + x#2 -18 __c2_1_re_9@13 >= -10 c3_1_a_14: + __c3_1_xm_11@15 - __c3_1_xp_10@14 + x#1 = 0 c3_1_b_15: - __c3_1_xp_10@14 + __c3_1_bp_12@16 <= 0 c3_1_c_16: - __c3_1_xm_11@15 + __c3_1_bm_13@17 <= 0 c3_1_d_17: - __c3_1_xp_10@14 +10 __c3_1_bp_12@16 >= 0 c3_1_e_18: - __c3_1_xm_11@15 +10 __c3_1_bm_13@17 >= 0 c3_1_f_19: + __c3_1_bm_13@17 + __c3_1_bp_12@16 + __c3_1_re_14@18 = 1 c3_1_t_r: + x#2 +3 __c3_1_re_14@18 <= 10 c3_1_t_l: + x#2 -17 __c3_1_re_14@18 >= -10 c4_1_a_20: + __c4_1_xm_16@1a - __c4_1_xp_15@19 + x#1 = 0 c4_1_b_21: - __c4_1_xp_15@19 + __c4_1_bp_17@1b <= 0 c4_1_c_22: - __c4_1_xm_16@1a + __c4_1_bm_18@1c <= 0 c4_1_d_23: - __c4_1_xp_15@19 +10 __c4_1_bp_17@1b >= 0 c4_1_e_24: - __c4_1_xm_16@1a +10 __c4_1_bm_18@1c >= 0 c4_1_f_25: - __c4_1_bm_18@1c - __c4_1_bp_17@1b + __c4_1_re_19@1d = 0 c4_1_t_r: + x#2 +4 __c4_1_re_19@1d <= 10 c4_1_t_l: + x#2 -16 __c4_1_re_19@1d >= -10 c5_1_a_26: + __c5_1_xm_21@1f - __c5_1_xp_20@1e + x#1 = 0 c5_1_b_27: - __c5_1_xp_20@1e + __c5_1_bp_22@20 <= 0 c5_1_c_28: - __c5_1_xm_21@1f + __c5_1_bm_23@21 <= 0 c5_1_d_29: - __c5_1_xp_20@1e +10 __c5_1_bp_22@20 >= 0 c5_1_e_30: - __c5_1_xm_21@1f +10 __c5_1_bm_23@21 >= 0 c5_1_f_31: + __c5_1_bm_23@21 + __c5_1_bp_22@20 <= 1 c5_1_g_32: + __c5_1_bm_23@21 + __c5_1_re_24@22 = 1 c5_1_t_r: + x#2 +5 __c5_1_re_24@22 <= 10 c5_1_t_l: + x#2 -15 __c5_1_re_24@22 >= -10 c6_1_a_33: + __c6_1_xm_26@24 - __c6_1_xp_25@23 + x#1 = 0 c6_1_b_34: - __c6_1_xp_25@23 + __c6_1_bp_27@25 <= 0 c6_1_c_35: - __c6_1_xm_26@24 + __c6_1_bm_28@26 <= 0 c6_1_d_36: - __c6_1_xp_25@23 +10 __c6_1_bp_27@25 >= 0 c6_1_e_37: - __c6_1_xm_26@24 +10 __c6_1_bm_28@26 >= 0 c6_1_f_38: + __c6_1_bm_28@26 + __c6_1_bp_27@25 <= 1 c6_1_g_39: - __c6_1_bp_27@25 + __c6_1_re_29@27 = 0 c6_1_t_r: + x#2 +6 __c6_1_re_29@27 <= 10 c6_1_t_l: + x#2 -14 __c6_1_re_29@27 >= -10 c7_1_a_40: + __c7_1_xm_31@29 - __c7_1_xp_30@28 + x#2 + x#1 = 0 c7_1_b_41: - __c7_1_xp_30@28 +20 __c7_1_bp_32@2a >= 0 c7_1_c_42: + __c7_1_xm_31@29 +20 __c7_1_bp_32@2a <= 20 c7_1_d_43: - __c7_1_xm_31@29 - __c7_1_xp_30@28 + __c7_1_re_33@2b = 0 c7_1_a_44: + __c7_1_xm_35@2d - __c7_1_xp_34@2c + __c7_1_re_33@2b = 5 c7_1_b_45: - __c7_1_xp_34@2c + __c7_1_bp_36@2e <= 0 c7_1_c_46: - __c7_1_xm_35@2d + __c7_1_bm_37@2f <= 0 c7_1_d_47: - __c7_1_xp_34@2c +15 __c7_1_bp_36@2e >= 0 c7_1_e_48: - __c7_1_xm_35@2d +5 __c7_1_bm_37@2f >= 0 c7_1_f_49: + __c7_1_bm_37@2f + __c7_1_bp_36@2e <= 1 c7_1_g_50: + __c7_1_bp_36@2e + __c7_1_re_38@30 = 1 c7_1_t_l: + x#4 + x#3 -25 __c7_1_re_38@30 >= -20 c7_1_e_l: + x#6 + x#5 +28 __c7_1_re_38@30 >= 8 c7_2_a_51: + __c7_2_xm_40@32 - __c7_2_xp_39@31 + x#2 + x#1 = 0 c7_2_b_52: - __c7_2_xp_39@31 +20 __c7_2_bp_41@33 >= 0 c7_2_c_53: + __c7_2_xm_40@32 +20 __c7_2_bp_41@33 <= 20 c7_2_d_54: - __c7_2_xm_40@32 - __c7_2_xp_39@31 + __c7_2_re_42@34 = 0 c7_2_a_55: + __c7_2_xm_44@36 - __c7_2_xp_43@35 + __c7_2_re_42@34 = 5 c7_2_b_56: - __c7_2_xp_43@35 + __c7_2_bp_45@37 <= 0 c7_2_c_57: - __c7_2_xm_44@36 + __c7_2_bm_46@38 <= 0 c7_2_d_58: - __c7_2_xp_43@35 +15 __c7_2_bp_45@37 >= 0 c7_2_e_59: - __c7_2_xm_44@36 +5 __c7_2_bm_46@38 >= 0 c7_2_f_60: + __c7_2_bm_46@38 + __c7_2_bp_45@37 <= 1 c7_2_g_61: + __c7_2_bp_45@37 + __c7_2_re_47@39 = 1 c7_2_t_l: + x#4 + x#3 -25 __c7_2_re_47@39 >= -20 c7_2_e_l: + x#6 + x#5 +28 __c7_2_re_47@39 >= 8 c7_3_a_62: + __c7_3_xm_49@3b - __c7_3_xp_48@3a + x#2 + x#1 = 0 c7_3_b_63: - __c7_3_xp_48@3a +20 __c7_3_bp_50@3c >= 0 c7_3_c_64: + __c7_3_xm_49@3b +20 __c7_3_bp_50@3c <= 20 c7_3_d_65: - __c7_3_xm_49@3b - __c7_3_xp_48@3a + __c7_3_re_51@3d = 0 c7_3_a_66: + __c7_3_xm_53@3f - __c7_3_xp_52@3e + __c7_3_re_51@3d = 5 c7_3_b_67: - __c7_3_xp_52@3e + __c7_3_bp_54@40 <= 0 c7_3_c_68: - __c7_3_xm_53@3f + __c7_3_bm_55@41 <= 0 c7_3_d_69: - __c7_3_xp_52@3e +15 __c7_3_bp_54@40 >= 0 c7_3_e_70: - __c7_3_xm_53@3f +5 __c7_3_bm_55@41 >= 0 c7_3_f_71: + __c7_3_bm_55@41 + __c7_3_bp_54@40 <= 1 c7_3_g_72: + __c7_3_bp_54@40 + __c7_3_re_56@42 = 1 c7_3_t_l: + x#4 + x#3 -25 __c7_3_re_56@42 >= -20 c7_3_e_l: + x#6 + x#5 +28 __c7_3_re_56@42 >= 8 c8_1_a_73: + __c8_1_xm_58@44 - __c8_1_xp_57@43 + x#2 +3 x#1 = 7 c8_1_b_74: - __c8_1_xp_57@43 + __c8_1_bp_59@45 <= 0 c8_1_c_75: - __c8_1_xm_58@44 + __c8_1_bm_60@46 <= 0 c8_1_d_76: - __c8_1_xp_57@43 +33 __c8_1_bp_59@45 >= 0 c8_1_e_77: - __c8_1_xm_58@44 +47 __c8_1_bm_60@46 >= 0 c8_1_f_78: - __c8_1_bm_60@46 - __c8_1_bp_59@45 + __c8_1_re_61@47 = 0 c8_1_t_r: + x#10 + x#9 + x#8 + x#7 + x#6 + x#5 + x#4 + x#3 + x#2 + x#1 +83 __c8_1_re_61@47 <= 100 c8_1_e_l: + x#10 + x#9 + x#8 + x#7 + x#6 + x#5 + x#4 + x#3 + x#2 + x#1 +105 __c8_1_re_61@47 >= 5 c9_1_a_79: + __c9_1_xm_63@49 - __c9_1_xp_62@48 + x#1 = 1 c9_1_b_80: - __c9_1_xp_62@48 + __c9_1_bp_64@4a <= 0 c9_1_c_81: - __c9_1_xm_63@49 + __c9_1_bm_65@4b <= 0 c9_1_d_82: - __c9_1_xp_62@48 +9 __c9_1_bp_64@4a >= 0 c9_1_e_83: - __c9_1_xm_63@49 +11 __c9_1_bm_65@4b >= 0 c9_1_f_84: + __c9_1_bm_65@4b + __c9_1_bp_64@4a + __c9_1_re_66@4c = 1 c9_1_a_85: + __c9_1_xm_68@4e - __c9_1_xp_67@4d + x#2 = 5 c9_1_b_86: - __c9_1_xp_67@4d + __c9_1_bp_69@4f <= 0 c9_1_c_87: - __c9_1_xm_68@4e + __c9_1_bm_70@50 <= 0 c9_1_d_88: - __c9_1_xp_67@4d +5 __c9_1_bp_69@4f >= 0 c9_1_e_89: - __c9_1_xm_68@4e +15 __c9_1_bm_70@50 >= 0 c9_1_f_90: + __c9_1_bm_70@50 + __c9_1_bp_69@4f <= 1 c9_1_g_91: - __c9_1_bp_69@4f + __c9_1_re_71@51 = 0 c9_1_a_92: - __c9_1_re_72@52 + __c9_1_re_66@4c >= 0 c9_1_b_93: - __c9_1_re_72@52 + __c9_1_re_71@51 >= 0 c9_1_c_94: - __c9_1_re_72@52 + __c9_1_re_71@51 + __c9_1_re_66@4c <= 1 c9_1_a_95: + __c9_1_xm_74@54 - __c9_1_xp_73@53 + x#1 = 2 c9_1_b_96: - __c9_1_xp_73@53 + __c9_1_bp_75@55 <= 0 c9_1_c_97: - __c9_1_xm_74@54 + __c9_1_bm_76@56 <= 0 c9_1_d_98: - __c9_1_xp_73@53 +8 __c9_1_bp_75@55 >= 0 c9_1_e_99: - __c9_1_xm_74@54 +12 __c9_1_bm_76@56 >= 0 c9_1_f_100: + __c9_1_bm_76@56 + __c9_1_bp_75@55 + __c9_1_re_77@57 = 1 c9_1_a_101: + __c9_1_xm_79@59 - __c9_1_xp_78@58 + x#2 = 8 c9_1_b_102: - __c9_1_xp_78@58 + __c9_1_bp_80@5a <= 0 c9_1_c_103: - __c9_1_xm_79@59 + __c9_1_bm_81@5b <= 0 c9_1_d_104: - __c9_1_xp_78@58 +2 __c9_1_bp_80@5a >= 0 c9_1_e_105: - __c9_1_xm_79@59 +18 __c9_1_bm_81@5b >= 0 c9_1_f_106: + __c9_1_bm_81@5b + __c9_1_bp_80@5a <= 1 c9_1_g_107: - __c9_1_bm_81@5b + __c9_1_re_82@5c = 0 c9_1_a_108: - __c9_1_re_83@5d + __c9_1_re_77@57 >= 0 c9_1_b_109: - __c9_1_re_83@5d + __c9_1_re_82@5c >= 0 c9_1_c_110: - __c9_1_re_83@5d + __c9_1_re_82@5c + __c9_1_re_77@57 <= 1 c9_1_a_111: - __c9_1_re_84@5e + __c9_1_re_72@52 <= 0 c9_1_b_112: - __c9_1_re_84@5e + __c9_1_re_83@5d <= 0 c9_1_c_113: - __c9_1_re_84@5e + __c9_1_re_83@5d + __c9_1_re_72@52 >= 0 c9_1_t_r: + x#3 +3 __c9_1_re_84@5e <= 10 c9_1_t_l: + x#3 -17 __c9_1_re_84@5e >= -10 c10_1_a_114: + __c10_1_xm_86@60 - __c10_1_xp_85@5f + x#1 = 1 c10_1_b_115: - __c10_1_xp_85@5f + __c10_1_bp_87@61 <= 0 c10_1_c_116: - __c10_1_xm_86@60 + __c10_1_bm_88@62 <= 0 c10_1_d_117: - __c10_1_xp_85@5f +9 __c10_1_bp_87@61 >= 0 c10_1_e_118: - __c10_1_xm_86@60 +11 __c10_1_bm_88@62 >= 0 c10_1_f_119: - __c10_1_bm_88@62 - __c10_1_bp_87@61 + __c10_1_re_89@63 = 0 c10_1_a_120: + __c10_1_xm_91@65 - __c10_1_xp_90@64 + x#2 = 5 c10_1_b_121: - __c10_1_xp_90@64 + __c10_1_bp_92@66 <= 0 c10_1_c_122: - __c10_1_xm_91@65 + __c10_1_bm_93@67 <= 0 c10_1_d_123: - __c10_1_xp_90@64 +5 __c10_1_bp_92@66 >= 0 c10_1_e_124: - __c10_1_xm_91@65 +15 __c10_1_bm_93@67 >= 0 c10_1_f_125: + __c10_1_bm_93@67 + __c10_1_bp_92@66 + __c10_1_re_94@68 = 1 c10_1_a_126: + __c10_1_re_95@69 + __c10_1_re_94@68 = 1 c10_1_a_127: - __c10_1_re_96@6a + __c10_1_re_95@69 + __c10_1_re_89@63 >= 0 c10_1_b_128: - __c10_1_re_96@6a - __c10_1_re_95@69 + __c10_1_re_89@63 <= 0 c10_1_c_129: + __c10_1_re_96@6a - __c10_1_re_95@69 + __c10_1_re_89@63 >= 0 c10_1_d_130: + __c10_1_re_96@6a + __c10_1_re_95@69 + __c10_1_re_89@63 <= 2 c10_1_t_r: + x#3 +8 __c10_1_re_96@6a <= 10 Bounds -10 <= x#1 <= 10 -10 <= x#2 <= 10 -10 <= x#3 <= 10 -10 <= x#4 <= 10 -10 <= x#5 <= 10 -10 <= x#6 <= 10 -10 <= x#7 <= 10 -10 <= x#8 <= 10 -10 <= x#9 <= 10 -10 <= x#10 <= 10 0 <= __c1_1_xp_0@a <= 10 0 <= __c1_1_xm_1@b <= 10 0 <= __c1_1_bp_2@c <= 1 0 <= __c1_1_bm_3@d <= 1 0 <= __c1_1_re_4@e <= 1 0 <= __c2_1_xp_5@f <= 10 0 <= __c2_1_xm_6@10 <= 10 0 <= __c2_1_bp_7@11 <= 1 0 <= __c2_1_bm_8@12 <= 1 0 <= __c2_1_re_9@13 <= 1 0 <= __c3_1_xp_10@14 <= 10 0 <= __c3_1_xm_11@15 <= 10 0 <= __c3_1_bp_12@16 <= 1 0 <= __c3_1_bm_13@17 <= 1 0 <= __c3_1_re_14@18 <= 1 0 <= __c4_1_xp_15@19 <= 10 0 <= __c4_1_xm_16@1a <= 10 0 <= __c4_1_bp_17@1b <= 1 0 <= __c4_1_bm_18@1c <= 1 0 <= __c4_1_re_19@1d <= 1 0 <= __c5_1_xp_20@1e <= 10 0 <= __c5_1_xm_21@1f <= 10 0 <= __c5_1_bp_22@20 <= 1 0 <= __c5_1_bm_23@21 <= 1 0 <= __c5_1_re_24@22 <= 1 0 <= __c6_1_xp_25@23 <= 10 0 <= __c6_1_xm_26@24 <= 10 0 <= __c6_1_bp_27@25 <= 1 0 <= __c6_1_bm_28@26 <= 1 0 <= __c6_1_re_29@27 <= 1 0 <= __c7_1_xp_30@28 <= 20 0 <= __c7_1_xm_31@29 <= 20 0 <= __c7_1_bp_32@2a <= 1 0 <= __c7_1_re_33@2b <= 20 0 <= __c7_1_xp_34@2c <= 15 0 <= __c7_1_xm_35@2d <= 5 0 <= __c7_1_bp_36@2e <= 1 0 <= __c7_1_bm_37@2f <= 1 0 <= __c7_1_re_38@30 <= 1 0 <= __c7_2_xp_39@31 <= 20 0 <= __c7_2_xm_40@32 <= 20 0 <= __c7_2_bp_41@33 <= 1 0 <= __c7_2_re_42@34 <= 20 0 <= __c7_2_xp_43@35 <= 15 0 <= __c7_2_xm_44@36 <= 5 0 <= __c7_2_bp_45@37 <= 1 0 <= __c7_2_bm_46@38 <= 1 0 <= __c7_2_re_47@39 <= 1 0 <= __c7_3_xp_48@3a <= 20 0 <= __c7_3_xm_49@3b <= 20 0 <= __c7_3_bp_50@3c <= 1 0 <= __c7_3_re_51@3d <= 20 0 <= __c7_3_xp_52@3e <= 15 0 <= __c7_3_xm_53@3f <= 5 0 <= __c7_3_bp_54@40 <= 1 0 <= __c7_3_bm_55@41 <= 1 0 <= __c7_3_re_56@42 <= 1 0 <= __c8_1_xp_57@43 <= 33 0 <= __c8_1_xm_58@44 <= 47 0 <= __c8_1_bp_59@45 <= 1 0 <= __c8_1_bm_60@46 <= 1 0 <= __c8_1_re_61@47 <= 1 0 <= __c9_1_xp_62@48 <= 9 0 <= __c9_1_xm_63@49 <= 11 0 <= __c9_1_bp_64@4a <= 1 0 <= __c9_1_bm_65@4b <= 1 0 <= __c9_1_re_66@4c <= 1 0 <= __c9_1_xp_67@4d <= 5 0 <= __c9_1_xm_68@4e <= 15 0 <= __c9_1_bp_69@4f <= 1 0 <= __c9_1_bm_70@50 <= 1 0 <= __c9_1_re_71@51 <= 1 0 <= __c9_1_re_72@52 <= 1 0 <= __c9_1_xp_73@53 <= 8 0 <= __c9_1_xm_74@54 <= 12 0 <= __c9_1_bp_75@55 <= 1 0 <= __c9_1_bm_76@56 <= 1 0 <= __c9_1_re_77@57 <= 1 0 <= __c9_1_xp_78@58 <= 2 0 <= __c9_1_xm_79@59 <= 18 0 <= __c9_1_bp_80@5a <= 1 0 <= __c9_1_bm_81@5b <= 1 0 <= __c9_1_re_82@5c <= 1 0 <= __c9_1_re_83@5d <= 1 0 <= __c9_1_re_84@5e <= 1 0 <= __c10_1_xp_85@5f <= 9 0 <= __c10_1_xm_86@60 <= 11 0 <= __c10_1_bp_87@61 <= 1 0 <= __c10_1_bm_88@62 <= 1 0 <= __c10_1_re_89@63 <= 1 0 <= __c10_1_xp_90@64 <= 5 0 <= __c10_1_xm_91@65 <= 15 0 <= __c10_1_bp_92@66 <= 1 0 <= __c10_1_bm_93@67 <= 1 0 <= __c10_1_re_94@68 <= 1 0 <= __c10_1_re_95@69 <= 1 0 <= __c10_1_re_96@6a <= 1 General x#1 x#2 x#3 x#4 x#5 x#6 x#7 x#8 x#9 x#10 __c1_1_xp_0@a __c1_1_xm_1@b __c1_1_bp_2@c __c1_1_bm_3@d __c1_1_re_4@e __c2_1_xp_5@f __c2_1_xm_6@10 __c2_1_bp_7@11 __c2_1_bm_8@12 __c2_1_re_9@13 __c3_1_xp_10@14 __c3_1_xm_11@15 __c3_1_bp_12@16 __c3_1_bm_13@17 __c3_1_re_14@18 __c4_1_xp_15@19 __c4_1_xm_16@1a __c4_1_bp_17@1b __c4_1_bm_18@1c __c4_1_re_19@1d __c5_1_xp_20@1e __c5_1_xm_21@1f __c5_1_bp_22@20 __c5_1_bm_23@21 __c5_1_re_24@22 __c6_1_xp_25@23 __c6_1_xm_26@24 __c6_1_bp_27@25 __c6_1_bm_28@26 __c6_1_re_29@27 __c7_1_xp_30@28 __c7_1_xm_31@29 __c7_1_bp_32@2a __c7_1_re_33@2b __c7_1_xp_34@2c __c7_1_xm_35@2d __c7_1_bp_36@2e __c7_1_bm_37@2f __c7_1_re_38@30 __c7_2_xp_39@31 __c7_2_xm_40@32 __c7_2_bp_41@33 __c7_2_re_42@34 __c7_2_xp_43@35 __c7_2_xm_44@36 __c7_2_bp_45@37 __c7_2_bm_46@38 __c7_2_re_47@39 __c7_3_xp_48@3a __c7_3_xm_49@3b __c7_3_bp_50@3c __c7_3_re_51@3d __c7_3_xp_52@3e __c7_3_xm_53@3f __c7_3_bp_54@40 __c7_3_bm_55@41 __c7_3_re_56@42 __c8_1_xp_57@43 __c8_1_xm_58@44 __c8_1_bp_59@45 __c8_1_bm_60@46 __c8_1_re_61@47 __c9_1_xp_62@48 __c9_1_xm_63@49 __c9_1_bp_64@4a __c9_1_bm_65@4b __c9_1_re_66@4c __c9_1_xp_67@4d __c9_1_xm_68@4e __c9_1_bp_69@4f __c9_1_bm_70@50 __c9_1_re_71@51 __c9_1_re_72@52 __c9_1_xp_73@53 __c9_1_xm_74@54 __c9_1_bp_75@55 __c9_1_bm_76@56 __c9_1_re_77@57 __c9_1_xp_78@58 __c9_1_xm_79@59 __c9_1_bp_80@5a __c9_1_bm_81@5b __c9_1_re_82@5c __c9_1_re_83@5d __c9_1_re_84@5e __c10_1_xp_85@5f __c10_1_xm_86@60 __c10_1_bp_87@61 __c10_1_bm_88@62 __c10_1_re_89@63 __c10_1_xp_90@64 __c10_1_xm_91@65 __c10_1_bp_92@66 __c10_1_bm_93@67 __c10_1_re_94@68 __c10_1_re_95@69 __c10_1_re_96@6a End
{ "pile_set_name": "Github" }
/***************************************************************************/ /* */ /* t1cmap.h */ /* */ /* Type 1 character map support (specification). */ /* */ /* Copyright 2002, 2003, 2006 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __T1CMAP_H__ #define __T1CMAP_H__ #include <ft2build.h> #include FT_INTERNAL_OBJECTS_H #include FT_INTERNAL_TYPE1_TYPES_H FT_BEGIN_HEADER /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** TYPE1 STANDARD (AND EXPERT) ENCODING CMAPS *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ /* standard (and expert) encoding cmaps */ typedef struct T1_CMapStdRec_* T1_CMapStd; typedef struct T1_CMapStdRec_ { FT_CMapRec cmap; const FT_UShort* code_to_sid; PS_Adobe_Std_StringsFunc sid_to_string; FT_UInt num_glyphs; const char* const* glyph_names; } T1_CMapStdRec; FT_CALLBACK_TABLE const FT_CMap_ClassRec t1_cmap_standard_class_rec; FT_CALLBACK_TABLE const FT_CMap_ClassRec t1_cmap_expert_class_rec; /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** TYPE1 CUSTOM ENCODING CMAP *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ typedef struct T1_CMapCustomRec_* T1_CMapCustom; typedef struct T1_CMapCustomRec_ { FT_CMapRec cmap; FT_UInt first; FT_UInt count; FT_UShort* indices; } T1_CMapCustomRec; FT_CALLBACK_TABLE const FT_CMap_ClassRec t1_cmap_custom_class_rec; /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** TYPE1 SYNTHETIC UNICODE ENCODING CMAP *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ /* unicode (synthetic) cmaps */ FT_CALLBACK_TABLE const FT_CMap_ClassRec t1_cmap_unicode_class_rec; /* */ FT_END_HEADER #endif /* __T1CMAP_H__ */ /* END */
{ "pile_set_name": "Github" }
"use strict"; module.exports = require("./is-implemented")() ? Array.prototype.fill : require("./shim");
{ "pile_set_name": "Github" }
BINARIES=ypause.exe !INCLUDE "..\config\common.mk" !IF $(PDB)==1 LINKPDB=/Pdb:ypause.pdb !ENDIF CFLAGS=$(CFLAGS) -DPAUSE_VER_MAJOR=$(PAUSE_VER_MAJOR) -DPAUSE_VER_MINOR=$(PAUSE_VER_MINOR) BIN_OBJS=\ pause.obj \ MOD_OBJS=\ mod_pause.obj \ compile: $(BIN_OBJS) builtins.lib ypause.exe: $(BIN_OBJS) ..\lib\yorilib.lib ..\crt\yoricrt.lib @echo $@ @$(LINK) $(LDFLAGS) -entry:$(YENTRY) $(BIN_OBJS) $(LIBS) $(CRTLIB) ..\lib\yorilib.lib -version:$(PAUSE_VER_MAJOR).$(PAUSE_VER_MINOR) $(LINKPDB) -out:$@ mod_pause.obj: pause.c @echo $@ @$(CC) -c -DYORI_BUILTIN=1 $(CFLAGS) -Fo$@ pause.c builtins.lib: $(MOD_OBJS) @echo $@ @$(LIB32) $(LIBFLAGS) $(MOD_OBJS) -out:$@
{ "pile_set_name": "Github" }
#include "winLongitude.h" /*********************************************************** * Constructor * ***********************************************************/ WinLongitude::WinLongitude(int _width, int _height, int _samplingRate, int _hopSize, SourceManager *_sourceManager) { // Create temporary widget this->tmpWidget = new QWidget(this); this->setWidget(this->tmpWidget); // Set size of the window this->width = _width; this->height = _height; this->frameGeometry().setWidth(this->width); this->frameGeometry().setHeight(this->height); // Save information this->samplingRate = _samplingRate; this->hopSize = _hopSize; this->mainManager = _sourceManager; // Create plot this->mainPlot = new PlotLongitude(this->width,this->height,this->samplingRate,this->hopSize,this->mainManager); this->mainPlot->updateGraph(); // Create grid this->mainGrid = new QGridLayout(this->tmpWidget); this->mainGrid->setMargin(0); // Add plot to grid this->mainGrid->addWidget(this->mainPlot); } /*********************************************************** * Destructor * ***********************************************************/ WinLongitude::~WinLongitude() { delete this->mainGrid; delete this->mainPlot; delete this->tmpWidget; } /*********************************************************** * Refresh * ***********************************************************/ void WinLongitude::updatePlot() { this->mainPlot->updateGraph(); } void WinLongitude::initPlot() { this->mainPlot->initPlot(); } /*********************************************************** * Mutator * ***********************************************************/ // +-------------------------------------------------------+ // | Time scale | // +-------------------------------------------------------+ void WinLongitude::setXMin(float _xMin) { this->mainPlot->setXMin(_xMin); } void WinLongitude::setXMax(float _xMax) { this->mainPlot->setXMax(_xMax); } void WinLongitude::setXInterval(float _xInterval) { this->mainPlot->setXInterval(_xInterval); } // +-------------------------------------------------------+ // | Background | // +-------------------------------------------------------+ void WinLongitude::setColorBackground(QColor _colorBackground) { this->mainPlot->setColorBackground(_colorBackground); } // +-------------------------------------------------------+ // | Trace | // +-------------------------------------------------------+ void WinLongitude::setSizePoint(int _sizePoint) { this->mainPlot->setSizePoint(_sizePoint); } // +-------------------------------------------------------+ // | Axes | // +-------------------------------------------------------+ void WinLongitude::setColorHorizontalBar(QColor _colorHorizontalBar) { this->mainPlot->setColorHorizontalBar(_colorHorizontalBar); } void WinLongitude::setColorVerticalBar(QColor _colorVerticalBar) { this->mainPlot->setColorVerticalBar(_colorVerticalBar); }
{ "pile_set_name": "Github" }
# Hamming Calculate the Hamming Distance between two DNA strands. Your body is made up of cells that contain DNA. Those cells regularly wear out and need replacing, which they achieve by dividing into daughter cells. In fact, the average human body experiences about 10 quadrillion cell divisions in a lifetime! When cells divide, their DNA replicates too. Sometimes during this process mistakes happen and single pieces of DNA get encoded with the incorrect information. If we compare two strands of DNA and count the differences between them we can see how many mistakes occurred. This is known as the "Hamming Distance". We read DNA using the letters C,A,G and T. Two strands might look like this: GAGCCTACTAACGGGAT CATCGTAATGACGGCCT ^ ^ ^ ^ ^ ^^ They have 7 differences, and therefore the Hamming Distance is 7. The Hamming Distance is useful for lots of things in science, not just biology, so it's a nice phrase to be familiar with :) # Implementation notes The Hamming distance is only defined for sequences of equal length, so an attempt to calculate it between sequences of different lengths should not work. The general handling of this situation (e.g., raising an exception vs returning a special value) may differ between languages. ## Elm Installation Refer to the [Installing Elm](https://exercism.io/tracks/elm/installation) page for information about installing elm. ## Writing the Code The code you have to write is located inside the `src/` directory of the exercise. Elm automatically installs packages dependencies the first time you run the tests so we can start by running the tests from the exercise directory with: ```bash $ elm-test ``` To automatically run tests again when you save changes: ```bash $ elm-test --watch ``` As you work your way through the tests suite in the file `tests/Tests.elm`, be sure to remove the `skip <|` calls from each test until you get them all passing! ## Source The Calculating Point Mutations problem at Rosalind [http://rosalind.info/problems/hamm/](http://rosalind.info/problems/hamm/) ## Submitting Incomplete Solutions It is possible to submit an incomplete solution so you can see how others have completed the exercise.
{ "pile_set_name": "Github" }
using System; using System.Text; using System.Collections; using Server; using Server.Items; namespace Server.Engines.ConPVP { #if false [Flipable( 0x9A8, 0xE80 )] public class StakesContainer : LockableContainer { private Mobile m_Initiator; private Participant m_Participant; private Hashtable m_Owners; public override bool CheckItemUse( Mobile from, Item item ) { Mobile owner = (Mobile)m_Owners[item]; if ( owner != null && owner != from ) return false; return base.CheckItemUse( from, item ); } public override bool CheckTarget( Mobile from, Server.Targeting.Target targ, object targeted ) { Mobile owner = (Mobile)m_Owners[targeted]; if ( owner != null && owner != from ) return false; return base.CheckTarget( from, targ, targeted ); } public override bool CheckLift(Mobile from, Item item) { Mobile owner = (Mobile)m_Owners[item]; if ( owner != null && owner != from ) return false; return base.CheckLift( from, item ); } public void ReturnItems() { ArrayList items = new ArrayList( this.Items ); for ( int i = 0; i < items.Count; ++i ) { Item item = (Item)items[i]; Mobile owner = (Mobile)m_Owners[item]; if ( owner == null || owner.Deleted ) owner = m_Initiator; if ( owner == null || owner.Deleted ) return; if ( item.LootType != LootType.Blessed || !owner.PlaceInBackpack( item ) ) owner.BankBox.DropItem( item ); } } public override bool TryDropItem( Mobile from, Item dropped, bool sendFullMessage ) { if ( m_Participant == null || !m_Participant.Contains( from ) ) { if ( sendFullMessage ) from.SendMessage( "You are not allowed to place items here." ); return false; } if ( dropped is Container || dropped.Stackable ) { if ( sendFullMessage ) from.SendMessage( "That item cannot be used as stakes." ); return false; } if ( !base.TryDropItem( from, dropped, sendFullMessage ) ) return false; if ( from != null ) m_Owners[dropped] = from; return true; } public override void RemoveItem( Item item ) { base.RemoveItem( item ); m_Owners.Remove( item ); } public StakesContainer( DuelContext context, Participant participant ) : base( 0x9A8 ) { Movable = false; m_Initiator = context.Initiator; m_Participant = participant; m_Owners = new Hashtable(); } public StakesContainer( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } #endif }
{ "pile_set_name": "Github" }
package bndtools.editor.contents; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import org.bndtools.api.ILogger; import org.bndtools.api.Logger; import org.bndtools.utils.collections.CollectionUtils; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.StyledCellLabelProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.ViewerCell; import org.eclipse.jface.viewers.ViewerDropAdapter; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DropTargetEvent; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.dnd.TransferData; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.swt.widgets.ToolItem; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.forms.IManagedForm; import org.eclipse.ui.forms.SectionPart; import org.eclipse.ui.forms.editor.IFormPage; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.Section; import org.eclipse.ui.ide.ResourceUtil; import org.eclipse.ui.part.ResourceTransfer; import org.eclipse.ui.plugin.AbstractUIPlugin; import aQute.bnd.build.model.BndEditModel; import aQute.bnd.osgi.Constants; import bndtools.Plugin; import bndtools.internal.testcaseselection.ITestCaseFilter; import bndtools.internal.testcaseselection.JavaSearchScopeTestCaseLister; import bndtools.internal.testcaseselection.TestCaseSelectionDialog; public class TestSuitesPart extends SectionPart implements PropertyChangeListener { private static final ILogger logger = Logger.getLogger(TestSuitesPart.class); private BndEditModel model; private List<String> testSuites; private TableViewer viewer; private final Image imgUp = AbstractUIPlugin .imageDescriptorFromPlugin(Plugin.PLUGIN_ID, "/icons/arrow_up.png") .createImage(); private final Image imgDown = AbstractUIPlugin .imageDescriptorFromPlugin(Plugin.PLUGIN_ID, "/icons/arrow_down.png") .createImage(); public TestSuitesPart(Composite parent, FormToolkit toolkit, int style) { super(parent, toolkit, style); createSection(getSection(), toolkit); } private void createSection(Section section, FormToolkit toolkit) { section.setText(Messages.TestSuitesPart_section_junit_tests); Composite composite = toolkit.createComposite(section); section.setClient(composite); // Section toolbar buttons ToolBar toolbar = new ToolBar(section, SWT.FLAT); section.setTextClient(toolbar); final ToolItem addItem = new ToolItem(toolbar, SWT.PUSH); addItem.setImage(PlatformUI.getWorkbench() .getSharedImages() .getImage(ISharedImages.IMG_OBJ_ADD)); addItem.setToolTipText(Messages.TestSuitesPart_add); final ToolItem removeItem = new ToolItem(toolbar, SWT.PUSH); removeItem.setImage(PlatformUI.getWorkbench() .getSharedImages() .getImage(ISharedImages.IMG_TOOL_DELETE)); removeItem.setDisabledImage(PlatformUI.getWorkbench() .getSharedImages() .getImage(ISharedImages.IMG_TOOL_DELETE_DISABLED)); removeItem.setToolTipText(Messages.TestSuitesPart_remove); removeItem.setEnabled(false); Table table = toolkit.createTable(composite, SWT.FULL_SELECTION | SWT.MULTI | SWT.BORDER); viewer = new TableViewer(table); viewer.setContentProvider(new ArrayContentProvider()); viewer.setLabelProvider(new TestSuiteLabelProvider()); toolbar = new ToolBar(composite, SWT.FLAT | SWT.HORIZONTAL | SWT.RIGHT); final ToolItem btnMoveUp = new ToolItem(toolbar, SWT.PUSH); btnMoveUp.setText("Up"); btnMoveUp.setImage(imgUp); btnMoveUp.setEnabled(false); final ToolItem btnMoveDown = new ToolItem(toolbar, SWT.PUSH); btnMoveDown.setText("Down"); btnMoveDown.setImage(imgDown); btnMoveDown.setEnabled(false); // LISTENERS viewer.addSelectionChangedListener(event -> { ISelection selection = event.getSelection(); boolean enabled = selection != null && !selection.isEmpty(); removeItem.setEnabled(enabled); btnMoveUp.setEnabled(enabled); btnMoveDown.setEnabled(enabled); getManagedForm().fireSelectionChanged(TestSuitesPart.this, selection); }); viewer.addOpenListener(event -> { String name = (String) ((IStructuredSelection) event.getSelection()).getFirstElement(); if (name != null) doOpenSource(name); }); viewer.addDropSupport(DND.DROP_COPY | DND.DROP_MOVE, new Transfer[] { ResourceTransfer.getInstance() }, new TestSuiteListDropAdapter()); addItem.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { doAdd(); } }); removeItem.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { doRemove(); } }); table.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { if (e.character == SWT.DEL) { doRemove(); } else if (e.character == '+') { doAdd(); } } }); btnMoveUp.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { doMoveUp(); } }); btnMoveDown.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { doMoveDown(); } }); // Layout GridLayout layout; layout = new GridLayout(1, false); layout.marginHeight = 0; layout.marginWidth = 0; layout.verticalSpacing = 0; layout.horizontalSpacing = 0; composite.setLayout(layout); GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); // gd.widthHint = 75; gd.heightHint = 75; table.setLayoutData(gd); toolbar.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); } void doOpenSource(String name) { IJavaProject javaProj = getJavaProject(); if (javaProj != null) { try { IType type = javaProj.findType(name); if (type != null) JavaUI.openInEditor(type, true, true); } catch (PartInitException e) { e.printStackTrace(); } catch (JavaModelException e) { e.printStackTrace(); } } } void doAdd() { // Prepare the exclusion list based on existing test cases final Set<String> testSuitesSet = new HashSet<>(testSuites); // Create a filter from the exclusion list ITestCaseFilter filter = testCaseName -> !testSuitesSet.contains(testCaseName); IFormPage page = (IFormPage) getManagedForm().getContainer(); IWorkbenchWindow window = page.getEditorSite() .getWorkbenchWindow(); // Prepare the package lister from the Java project IJavaProject javaProject = getJavaProject(); if (javaProject == null) { MessageDialog.openError(getSection().getShell(), "Error", "Cannot add test cases: unable to find a Java project associated with the editor input."); return; } IJavaSearchScope searchScope = SearchEngine.createJavaSearchScope(new IJavaElement[] { javaProject }); JavaSearchScopeTestCaseLister testCaseLister = new JavaSearchScopeTestCaseLister(searchScope, window); // Create and open the dialog TestCaseSelectionDialog dialog = new TestCaseSelectionDialog(getSection().getShell(), testCaseLister, filter, Messages.TestSuitesPart_title); dialog.setSourceOnly(true); dialog.setMultipleSelection(true); if (dialog.open() == Window.OK) { Object[] results = dialog.getResult(); List<String> added = new LinkedList<>(); // Select the results for (Object result : results) { String newTestSuites = (String) result; if (testSuites.add(newTestSuites)) { added.add(newTestSuites); } } // Update the model and view if (!added.isEmpty()) { viewer.add(added.toArray()); markDirty(); } } } void doRemove() { IStructuredSelection sel = (IStructuredSelection) viewer.getSelection(); if (!sel.isEmpty()) { testSuites.removeAll(sel.toList()); viewer.remove(sel.toArray()); markDirty(); validate(); } } void doMoveUp() { int[] selectedIndexes = findSelectedIndexes(); if (CollectionUtils.moveUp(testSuites, selectedIndexes)) { viewer.refresh(); validate(); markDirty(); } } void doMoveDown() { int[] selectedIndexes = findSelectedIndexes(); if (CollectionUtils.moveDown(testSuites, selectedIndexes)) { viewer.refresh(); validate(); markDirty(); } } int[] findSelectedIndexes() { Object[] selection = ((IStructuredSelection) viewer.getSelection()).toArray(); int[] selectionIndexes = new int[selection.length]; for (int i = 0; i < selection.length; i++) { selectionIndexes[i] = testSuites.indexOf(selection[i]); } return selectionIndexes; } @Override public void initialize(IManagedForm form) { super.initialize(form); this.model = (BndEditModel) form.getInput(); this.model.addPropertyChangeListener(Constants.TESTCASES, this); } @Override public void refresh() { List<String> modelList = model.getTestSuites(); testSuites = new ArrayList<>(modelList); viewer.setInput(testSuites); validate(); } private void validate() {} @Override public void commit(boolean onSave) { try { model.removePropertyChangeListener(Constants.TESTCASES, this); model.setTestSuites(testSuites.isEmpty() ? null : testSuites); } finally { model.addPropertyChangeListener(Constants.TESTCASES, this); super.commit(onSave); } } @Override public void propertyChange(PropertyChangeEvent evt) { String propertyName = evt.getPropertyName(); if (Constants.TESTCASES.equals(propertyName)) { IFormPage page = (IFormPage) getManagedForm().getContainer(); if (page.isActive()) { refresh(); } else { markStale(); } } else if (Constants.PRIVATE_PACKAGE.equals(propertyName) || Constants.EXPORT_PACKAGE.equals(propertyName)) { validate(); } } IJavaProject getJavaProject() { IFormPage page = (IFormPage) getManagedForm().getContainer(); IEditorInput input = page.getEditorInput(); IFile file = ResourceUtil.getFile(input); if (file != null) { return JavaCore.create(file.getProject()); } return null; } private class TestSuiteListDropAdapter extends ViewerDropAdapter { protected TestSuiteListDropAdapter() { super(viewer); } @Override public void dragEnter(DropTargetEvent event) { event.detail = DND.DROP_COPY; super.dragEnter(event); } @Override public boolean validateDrop(Object target, int operation, TransferData transferType) { return ResourceTransfer.getInstance() .isSupportedType(transferType); } @Override public boolean performDrop(Object data) { Object target = getCurrentTarget(); int loc = getCurrentLocation(); int insertionIndex = -1; if (target != null) { insertionIndex = testSuites.indexOf(target); if (insertionIndex > -1 && loc == LOCATION_ON || loc == LOCATION_AFTER) insertionIndex++; } List<String> addedNames = new ArrayList<>(); if (data instanceof IResource[]) { IResource[] resources = (IResource[]) data; for (IResource resource : resources) { IJavaElement javaElement = JavaCore.create(resource); if (javaElement != null) { try { if (javaElement instanceof IType) { IType type = (IType) javaElement; if (type.isClass() && Flags.isPublic(type.getFlags())) { String typeName = type.getPackageFragment() .getElementName() + "." + type.getElementName(); //$NON-NLS-1$ addedNames.add(typeName); } } else if (javaElement instanceof ICompilationUnit) { IType[] allTypes = ((ICompilationUnit) javaElement).getAllTypes(); for (IType type : allTypes) { if (type.isClass() && Flags.isPublic(type.getFlags())) { String typeName = type.getPackageFragment() .getElementName() + "." + type.getElementName(); //$NON-NLS-1$ addedNames.add(typeName); } } } } catch (JavaModelException e) { logger.logError(Messages.TestSuitesPart_errorJavaType, e); } } } } if (!addedNames.isEmpty()) { if (insertionIndex == -1 || insertionIndex == testSuites.size()) { testSuites.addAll(addedNames); viewer.add(addedNames.toArray()); } else { testSuites.addAll(insertionIndex, addedNames); viewer.refresh(); } viewer.setSelection(new StructuredSelection(addedNames), true); validate(); markDirty(); } return true; } } } class TestSuiteLabelProvider extends StyledCellLabelProvider { private final Image suiteImg = AbstractUIPlugin.imageDescriptorFromPlugin(Plugin.PLUGIN_ID, "/icons/tsuite.gif") .createImage(); // private Image testImg = // AbstractUIPlugin.imageDescriptorFromPlugin(Plugin.PLUGIN_ID, // "/icons/test.gif").createImage(); @Override public void update(ViewerCell cell) { String fqName = (String) cell.getElement(); cell.setText(fqName); cell.setImage(suiteImg); } @Override public void dispose() { super.dispose(); suiteImg.dispose(); } }
{ "pile_set_name": "Github" }
/* Copyright Rene Rivera 2008-2015 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef MSGPACK_PREDEF_COMPILER_GREENHILLS_H #define MSGPACK_PREDEF_COMPILER_GREENHILLS_H #include <rpc/msgpack/predef/version_number.h> #include <rpc/msgpack/predef/make.h> /*` [heading `MSGPACK_COMP_GHS`] [@http://en.wikipedia.org/wiki/Green_Hills_Software Green Hills C/C++] compiler. Version number available as major, minor, and patch. [table [[__predef_symbol__] [__predef_version__]] [[`__ghs`] [__predef_detection__]] [[`__ghs__`] [__predef_detection__]] [[`__GHS_VERSION_NUMBER__`] [V.R.P]] [[`__ghs`] [V.R.P]] ] */ #define MSGPACK_COMP_GHS MSGPACK_VERSION_NUMBER_NOT_AVAILABLE #if defined(__ghs) || defined(__ghs__) # if !defined(MSGPACK_COMP_GHS_DETECTION) && defined(__GHS_VERSION_NUMBER__) # define MSGPACK_COMP_GHS_DETECTION MSGPACK_PREDEF_MAKE_10_VRP(__GHS_VERSION_NUMBER__) # endif # if !defined(MSGPACK_COMP_GHS_DETECTION) && defined(__ghs) # define MSGPACK_COMP_GHS_DETECTION MSGPACK_PREDEF_MAKE_10_VRP(__ghs) # endif # if !defined(MSGPACK_COMP_GHS_DETECTION) # define MSGPACK_COMP_GHS_DETECTION MSGPACK_VERSION_NUMBER_AVAILABLE # endif #endif #ifdef MSGPACK_COMP_GHS_DETECTION # if defined(MSGPACK_PREDEF_DETAIL_COMP_DETECTED) # define MSGPACK_COMP_GHS_EMULATED MSGPACK_COMP_GHS_DETECTION # else # undef MSGPACK_COMP_GHS # define MSGPACK_COMP_GHS MSGPACK_COMP_GHS_DETECTION # endif # define MSGPACK_COMP_GHS_AVAILABLE # include <rpc/msgpack/predef/detail/comp_detected.h> #endif #define MSGPACK_COMP_GHS_NAME "Green Hills C/C++" #endif #include <rpc/msgpack/predef/detail/test.h> MSGPACK_PREDEF_DECLARE_TEST(MSGPACK_COMP_GHS,MSGPACK_COMP_GHS_NAME) #ifdef MSGPACK_COMP_GHS_EMULATED #include <rpc/msgpack/predef/detail/test.h> MSGPACK_PREDEF_DECLARE_TEST(MSGPACK_COMP_GHS_EMULATED,MSGPACK_COMP_GHS_NAME) #endif
{ "pile_set_name": "Github" }
using CadEditor; using System.Collections.Generic; //css_include three_eyes_story/ThreeUtils.cs; public class Data { public OffsetRec getScreensOffset() { return new OffsetRec(0x14f44 , 14 , 64, 8, 8); } public OffsetRec getBigBlocksOffset() { return new OffsetRec(0x14dac, 1 , 0x4000); } public int getBigBlocksCount() { return 102; } public GetBigBlocksFunc getBigBlocksFunc() { return ThreeUtils.getBigBlocks; } public SetBigBlocksFunc setBigBlocksFunc() { return ThreeUtils.setBigBlocks;} public OffsetRec getBlocksOffset() { return new OffsetRec(0x14c9c , 1 , 0x440); } public int getBlocksCount() { return 68; } public int getPalBytesAddr() { return 0x15344; } public GetBlocksFunc getBlocksFunc() { return ThreeUtils.getBlocks;} public SetBlocksFunc setBlocksFunc() { return ThreeUtils.setBlocks;} public OffsetRec getVideoOffset() { return new OffsetRec(0x0 , 1 , 0x1000); } public GetVideoPageAddrFunc getVideoPageAddrFunc() { return ThreeUtils.fakeVideoAddr(); } public GetVideoChunkFunc getVideoChunkFunc() { return ThreeUtils.getVideoChunk(new[] {"chr1-2.bin"}); } public SetVideoChunkFunc setVideoChunkFunc() { return null; } public OffsetRec getPalOffset() { return new OffsetRec(0x0 , 1 , 16); } public GetPalFunc getPalFunc() { return ThreeUtils.readPalFromBin(new[] {"pal1-2.bin"}); } public SetPalFunc setPalFunc() { return null;} public bool isBigBlockEditorEnabled() { return true; } public bool isBlockEditorEnabled() { return true; } public bool isEnemyEditorEnabled() { return false; } }
{ "pile_set_name": "Github" }
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Author: Frank Osterfeld, KDAB ([email protected]) ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ****************************************************************************/ #pragma once #include <QMetaType> #include <QSharedDataPointer> #include <QVector> QT_BEGIN_NAMESPACE class QString; QT_END_NAMESPACE namespace Valgrind { namespace XmlProtocol { class Stack; class Suppression; /** * Error kinds, specific to memcheck */ enum MemcheckErrorKind { InvalidFree, MismatchedFree, InvalidRead, InvalidWrite, InvalidJump, Overlap, InvalidMemPool, UninitCondition, UninitValue, SyscallParam, ClientCheck, Leak_DefinitelyLost, Leak_PossiblyLost, Leak_StillReachable, Leak_IndirectlyLost, MemcheckErrorKindCount }; enum PtrcheckErrorKind { SorG, Heap, Arith, SysParam }; enum HelgrindErrorKind { Race, UnlockUnlocked, UnlockForeign, UnlockBogus, PthAPIerror, LockOrder, Misc }; class Error { public: Error(); ~Error(); Error(const Error &other); Error &operator=(const Error &other); void swap(Error &other); bool operator==(const Error &other) const; bool operator!=(const Error &other) const; qint64 unique() const; void setUnique(qint64 unique); qint64 tid() const; void setTid(qint64); QString what() const; void setWhat(const QString &what); int kind() const; void setKind(int kind); QVector<Stack> stacks() const; void setStacks(const QVector<Stack> &stacks); Suppression suppression() const; void setSuppression(const Suppression &suppression); //memcheck quint64 leakedBytes() const; void setLeakedBytes(quint64); qint64 leakedBlocks() const; void setLeakedBlocks(qint64 blocks); //helgrind qint64 helgrindThreadId() const; void setHelgrindThreadId( qint64 threadId ); QString toXml() const; private: class Private; QSharedDataPointer<Private> d; }; } // namespace XmlProtocol } // namespace Valgrind Q_DECLARE_METATYPE(Valgrind::XmlProtocol::Error)
{ "pile_set_name": "Github" }
package org.jetlinks.community.elastic.search.aggreation.metrics; import lombok.*; import org.jetlinks.community.elastic.search.aggreation.enums.MetricsType; import java.util.Map; /** * @author bsetfeng * @since 1.0 **/ @Getter @Setter @AllArgsConstructor @NoArgsConstructor @Builder public class MetricsResponse { private Map<MetricsType, MetricsResponseSingleValue> results; private MetricsResponseSingleValue singleResult; public MetricsResponseSingleValue getSingleResult() { if (singleResult == null) { this.singleResult = results.entrySet() .stream() .findFirst() .map(Map.Entry::getValue) .orElse(MetricsResponseSingleValue.empty()); } return singleResult; } }
{ "pile_set_name": "Github" }