content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Javascript
Javascript
more clean up
6ef2798ee0d91f4e123142be664455fe018c16ef
<ide><path>src/objects/Mesh.js <ide> Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), { <ide> var uvC = new Vector2(); <ide> <ide> var barycoord = new Vector3(); <add> var triangle = new Triangle(); <ide> <ide> var intersectionPoint = new Vector3(); <ide> var intersectionPointWorld = new Vector3(); <add> var faceNormal = new Vector3(); <ide> <ide> function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) { <ide> <ide> Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), { <ide> <ide> } <ide> <del> intersection.face = new Face3( a, b, c, Triangle.normal( vA, vB, vC ) ); <add> var face = new Face3( a, b, c ); <add> <add> triangle.set( vA, vB, vC ).normal( faceNormal ); <add> face.normal.copy( faceNormal ); <add> <add> intersection.face = face; <ide> intersection.faceIndex = a; <ide> <ide> } <ide><path>src/objects/Points.js <ide> Points.prototype = Object.assign( Object.create( Object3D.prototype ), { <ide> var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); <ide> var localThresholdSq = localThreshold * localThreshold; <ide> var position = new Vector3(); <add> var intersectPoint = new Vector3(); <ide> <ide> function testPoint( point, index ) { <ide> <ide> var rayPointDistanceSq = ray.distanceSqToPoint( point ); <ide> <ide> if ( rayPointDistanceSq < localThresholdSq ) { <ide> <del> var intersectPoint = ray.closestPointToPoint( point ); <add> ray.closestPointToPoint( point, intersectPoint ); <ide> intersectPoint.applyMatrix4( matrixWorld ); <ide> <ide> var distance = raycaster.ray.origin.distanceTo( intersectPoint );
2
Java
Java
remove use of threadlocal
348ecce42a98fe2dfa087245b22200944b19cbcc
<ide><path>src/main/java/rx/schedulers/TrampolineScheduler.java <ide> public Worker createWorker() { <ide> /* package accessible for unit tests */TrampolineScheduler() { <ide> } <ide> <del> private static final ThreadLocal<PriorityQueue<TimedAction>> QUEUE = new ThreadLocal<PriorityQueue<TimedAction>>() { <del> @Override <del> protected PriorityQueue<TimedAction> initialValue() { <del> return new PriorityQueue<TimedAction>(); <del> } <del> }; <del> <ide> volatile int counter; <ide> static final AtomicIntegerFieldUpdater<TrampolineScheduler> COUNTER_UPDATER = AtomicIntegerFieldUpdater.newUpdater(TrampolineScheduler.class, "counter"); <ide> <ide> private class InnerCurrentThreadScheduler extends Scheduler.Worker implements Subscription { <ide> <add> final PriorityQueue<TimedAction> queue = new PriorityQueue<TimedAction>(); <ide> private final BooleanSubscription innerSubscription = new BooleanSubscription(); <ide> private final AtomicInteger wip = new AtomicInteger(); <ide> <ide> private Subscription enqueue(Action0 action, long execTime) { <ide> if (innerSubscription.isUnsubscribed()) { <ide> return Subscriptions.empty(); <ide> } <del> PriorityQueue<TimedAction> queue = QUEUE.get(); <ide> final TimedAction timedAction = new TimedAction(action, execTime, COUNTER_UPDATER.incrementAndGet(TrampolineScheduler.this)); <ide> queue.add(timedAction); <ide> <ide> private Subscription enqueue(Action0 action, long execTime) { <ide> <ide> @Override <ide> public void call() { <del> PriorityQueue<TimedAction> _q = QUEUE.get(); <add> PriorityQueue<TimedAction> _q = queue; <ide> if (_q != null) { <ide> _q.remove(timedAction); <ide> }
1
Javascript
Javascript
remove unreachable check in internalconnect
ff566276da239a8d2ecc2ebb93719b2242c2b749
<ide><path>lib/net.js <ide> function internalConnect( <ide> if (addressType === 4) { <ide> localAddress = localAddress || '0.0.0.0'; <ide> err = self._handle.bind(localAddress, localPort); <del> } else if (addressType === 6) { <add> } else { // addressType === 6 <ide> localAddress = localAddress || '::'; <ide> err = self._handle.bind6(localAddress, localPort); <del> } else { <del> self.destroy(new ERR_INVALID_ADDRESS_FAMILY(addressType)); <del> return; <ide> } <ide> debug('binding to localAddress: %s and localPort: %d (addressType: %d)', <ide> localAddress, localPort, addressType);
1
Ruby
Ruby
integrate upgrade with cask
210d22e8199f2482b28f550838a33cca47380ce4
<ide><path>Library/Homebrew/cmd/upgrade.rb <ide> require "formula_installer" <ide> require "install" <ide> require "upgrade" <add>require "cask/cmd" <add>require "cask/utils" <add>require "cask/macos" <ide> <ide> module Homebrew <ide> module_function <ide> def upgrade_args <ide> description: "Print install times for each formula at the end of the run." <ide> switch "-n", "--dry-run", <ide> description: "Show what would be upgraded, but do not actually upgrade anything." <add> switch "--greedy", <add> description: "Upgrade casks with `auto_updates` or `version :latest`" <ide> conflicts "--build-from-source", "--force-bottle" <ide> formula_options <ide> end <ide> def upgrade <ide> outdated = Formula.installed.select do |f| <ide> f.outdated?(fetch_head: args.fetch_HEAD?) <ide> end <del> <del> exit 0 if outdated.empty? <add> casks = [] # Upgrade all installed casks <ide> else <del> outdated = args.resolved_formulae.select do |f| <add> formulae, casks = args.resolved_formulae_casks <add> outdated, not_outdated = formulae.partition do |f| <ide> f.outdated?(fetch_head: args.fetch_HEAD?) <ide> end <ide> <del> (args.resolved_formulae - outdated).each do |f| <add> not_outdated.each do |f| <ide> versions = f.installed_kegs.map(&:version) <ide> if versions.empty? <ide> ofail "#{f.full_specified_name} not installed" <ide> def upgrade <ide> opoo "#{f.full_specified_name} #{version} already installed" <ide> end <ide> end <del> return if outdated.empty? <ide> end <ide> <add> upgrade_outdated_formulae(outdated) <add> upgrade_outdated_casks(casks) <add> end <add> <add> def upgrade_outdated_formulae(outdated) <add> return if outdated.empty? <add> <ide> pinned = outdated.select(&:pinned?) <ide> outdated -= pinned <ide> formulae_to_install = outdated.map(&:latest_formula) <ide> def upgrade <ide> <ide> Homebrew.messages.display_messages <ide> end <add> <add> def upgrade_outdated_casks(casks) <add> cask_upgrade = Cask::Cmd::Upgrade.new(casks) <add> cask_upgrade.force = args.force? <add> cask_upgrade.dry_run = args.dry_run? <add> cask_upgrade.greedy = args.greedy? <add> cask_upgrade.run <add> end <ide> end
1
Text
Text
fix some typos in the new docs
94049150b1d5fea6d6fa904db55b68169adc52ba
<ide><path>docs/api/Store.md <ide> # Store <ide> <del>A store holds the whole [state tree](../Glossary.md#state) of your application. <del>The only way to change the state inside it is to dispatch an [action](../Glossary.md#action) on it. <add>A store holds the whole [state tree](../Glossary.md#state) of your application. <add>The only way to change the state inside it is to dispatch an [action](../Glossary.md#action) on it. <ide> <del>A store is not a class. It’s just an object with a few methods on it. <add>A store is not a class. It’s just an object with a few methods on it. <ide> To create it, pass your root [reducing function](../Glossary.md#reducer) to [`createStore`](createStore.md). <ide> <ide> >##### A Note for Flux Users <ide> To create it, pass your root [reducing function](../Glossary.md#reducer) to [`cr <ide> <ide> ### <a id='getState'></a>[`getState()`](#getState) <ide> <del>Returns the current state tree of your application. <add>Returns the current state tree of your application. <ide> It is equal to the last value returned by the store’s reducer. <ide> <ide> #### Returns <ide> The store’s reducing function will be called with the current [`getState()`](# <ide> <ide> <sup>†</sup> The “vanilla” store implementation you get by calling [`createStore`](createStore.md) only supports plain object actions and hands them immediately to the reducer. <ide> <del>However, if you wrap [`createStore`](createStore.md) with [`applyMiddleware`](applyMiddleware.md), the middleware can interpret actions differently, and provide support for dispathing [intents](../Glossary.md#intent). Intents are usually asynchronous primitives like Promises, Observables, or thunks. <add>However, if you wrap [`createStore`](createStore.md) with [`applyMiddleware`](applyMiddleware.md), the middleware can interpret actions differently, and provide support for dispatching [intents](../Glossary.md#intent). Intents are usually asynchronous primitives like Promises, Observables, or thunks. <ide> <ide> Middleware is created by the community and does not ship with Redux by default. You need to explicitly install packages like [redux-thunk](https://github.com/gaearon/redux-thunk) or [redux-promise](https://github.com/acdlite/redux-promise) to use it. You may also create your own middleware. <ide> <ide> let currentValue; <ide> function handleChange() { <ide> let previousValue = currentValue; <ide> currentValue = select(store.getState()); <del> <add> <ide> if (previousValue !== currentValue) { <ide> console.log('Some deep nested property changed from', previousValue, 'to', currentValue); <ide> } <ide> handleChange(); <ide> <ide> >##### Deprecated <ide> <del>>This API has been [deprecated](https://github.com/gaearon/redux/issues/350). <add>>This API has been [deprecated](https://github.com/gaearon/redux/issues/350). <ide> >It will be removed when we find a better solution for this problem. <ide> <ide> Returns the reducer currently used by the store to calculate the state. <ide> It is an advanced API. You might only need this if you implement a hot reloading <ide> <ide> >##### Deprecated <ide> <del>>This API has been [deprecated](https://github.com/gaearon/redux/issues/350). <add>>This API has been [deprecated](https://github.com/gaearon/redux/issues/350). <ide> >It will be removed when we find a better solution for this problem. <ide> <ide> Replaces the reducer currently used by the store to calculate the state. <ide><path>docs/api/applyMiddleware.md <ide> # `applyMiddleware(...middlewares)` <ide> <del>Middleware is the suggested way to extend Redux with custom functionality. Middleware lets you wrap the store’s [`dispatch`](Store.md#dispatch) method for fun and profit. The key feature of middleware is that it is composable. Multiple middleware can be combined together, where each middleware requires no knowledge of the what comes before or after it in the chain. <add>Middleware is the suggested way to extend Redux with custom functionality. Middleware lets you wrap the store’s [`dispatch`](Store.md#dispatch) method for fun and profit. The key feature of middleware is that it is composable. Multiple middleware can be combined together, where each middleware requires no knowledge of what comes before or after it in the chain. <ide> <del>The most common use case for the middleware is to support asynchronous actions without much boilerplate code or a dependency on a library like [Rx](https://github.com/Reactive-Extensions/RxJS). It does so by letting you dispatch [intents](../Glossary.md#intent) in addition to actions. <add>The most common use case for the middleware is to support asynchronous actions without much boilerplate code or a dependency or a library like [Rx](https://github.com/Reactive-Extensions/RxJS). It does so by letting you dispatch [intents](../Glossary.md#intent) in addition to actions. <ide> <del>For example, [redux-thunk](https://github.com/gaearon/redux-thunk) lets the action creators invert control by dispatching functions that receive [`dispatch`](Store.md#dispatch) as an argument and may call it asynchronously. These functions are called *thunks*. Another example of middleware is [redux-promise](https://github.com/acdlite/redux-promise) that lets you dispatch a [Promise](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise) intent, which translated into a raw action when the Promise resolves. <add>For example, [redux-thunk](https://github.com/gaearon/redux-thunk) lets the action creators invert control by dispatching functions that receive [`dispatch`](Store.md#dispatch) as an argument and may call it asynchronously. These functions are called *thunks*. Another example of middleware is [redux-promise](https://github.com/acdlite/redux-promise) that lets you dispatch a [Promise](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise) intent, which is translated into a raw action when the Promise resolves. <ide> <ide> Middleware is not baked into [`createStore`](createStore.md) and is not a fundamental part of the Redux architecture, but we consider it useful enough to be supported right in the core. This way, there is a single standard way to extend [`dispatch`](Store.md#dispatch) in the ecosystem, and different middleware may compete in expressiveness and utility. <ide> <ide> Middleware is not baked into [`createStore`](createStore.md) and is not a fundam <ide> ```js <ide> import { createStore, applyMiddleware } from 'redux'; <ide> import thunk from 'redux-thunk'; <del>import sandwhiches from './reducers'; <add>import sandwiches from './reducers'; <ide> <ide> // applyMiddleware supercharges createStore with middleware: <ide> let createStoreWithMiddleware = applyMiddleware(thunk)(createStore); <ide> <ide> // We can use it exactly like “vanilla” createStore. <del>let store = createStoreWithMiddleware(sandwhiches); <add>let store = createStoreWithMiddleware(sandhiches); <ide> <ide> function fetchSecretSauce() { <ide> return fetch('https://www.google.com/search?q=secret+sauce'); <ide> function fetchSecretSauce() { <ide> <ide> function makeASandwich(forPerson, secretSauce) { <ide> return { <del> type: 'MAKE_SANDWHICH', <add> type: 'MAKE_SANDWICH', <ide> forPerson, <ide> secretSauce <ide> }; <ide> function makeASandwichWithSecretSauce(forPerson) { <ide> return function (dispatch) { <ide> return fetchSecretSauce().then( <ide> sauce => dispatch(makeASandwich(forPerson, sauce)), <del> error => dispatch(apologize('The Sandwhich Shop', forPerson, error)) <add> error => dispatch(apologize('The Sandwich Shop', forPerson, error)) <ide> ); <ide> }; <ide> } <ide> store.dispatch( <ide> // actions and intents from other action creators, <ide> // and I can build my control flow with Promises. <ide> <del>function makeSandwhichesForEverybody() { <add>function makeSandwichesForEverybody() { <ide> return function (dispatch, getState) { <del> if (!getState().sandwhiches.isShopOpen) { <add> if (!getState().sandwiches.isShopOpen) { <ide> <ide> // You don’t have to return Promises, but it’s a handy convention <ide> // so the caller can always call .then() on async dispatch result. <ide> function makeSandwhichesForEverybody() { <ide> // sending synchronously rendering the app. <ide> <ide> store.dispatch( <del> makeSandwhichesForEverybody() <add> makeSandwichesForEverybody() <ide> ).then(() => <ide> response.send(React.renderToString(<MyApp store={store} />)) <ide> ); <ide> store.dispatch( <ide> import { connect } from 'react-redux'; <ide> import { Component } from 'react'; <ide> <del>class SandwhichShop extends Component { <add>class SandwichShop extends Component { <ide> componentDidMount() { <ide> this.props.dispatch( <ide> makeASandwichWithSecretSauce(this.props.forPerson) <ide> class SandwhichShop extends Component { <ide> if (nextProps.forPerson !== this.props.forPerson) { <ide> this.props.dispatch( <ide> makeASandwichWithSecretSauce(nextProps.forPerson) <del> ); <add> ); <ide> } <ide> } <ide> <ide> render() { <del> return <p>{this.props.sandwhiches.join('mustard')}</p> <add> return <p>{this.props.sandwiches.join('mustard')}</p> <ide> } <ide> } <ide> <ide> export default connect( <del> SandwhichShop, <add> SandwichShop, <ide> state => ({ <del> sandwiches: state.sandwhiches <add> sandwiches: state.sandwiches <ide> }) <ide> ); <ide> ``` <ide><path>docs/api/bindActionCreators.md <ide> import * as TodoActionCreators from './TodoActionCreators'; <ide> console.log(TodoActionCreators); <ide> // { <ide> // addTodo: Function, <del>// removeTodo: function <add>// removeTodo: Function <ide> // } <ide> <ide> class TodoListContainer extends Component { <ide> export default connect( <ide> <ide> * You might ask: why don’t we bind the action creators to the store instance right away, like in classical Flux? The problem is that this won’t work well with universal apps that need to render on the server. Most likely you want to have a separate store instance per request so you can prepare them with different data, but binding action creators during their definition means you’re stuck with a single store instance for all requests. <ide> <del>* If you use ES5, instead of `import * as` syntax you can just pass `require('./TodoActionCreators')` to `bindActionCreators` as the first argument. The only thing it cares about is that the values of the `actionCreators` arguments are functions. The module system doesn’t matter. <ide>\ No newline at end of file <add>* If you use ES5, instead of `import * as` syntax you can just pass `require('./TodoActionCreators')` to `bindActionCreators` as the first argument. The only thing it cares about is that the values of the `actionCreators` arguments are functions. The module system doesn’t matter. <ide><path>docs/api/combineReducers.md <ide> The resulting reducer calls every child reducer, and gather their results into a <ide> <ide> #### Returns <ide> <del>(*Function*): A reducer that that invokes every reducer inside the `reducers` object, and constructs a state object with the same shape. <add>(*Function*): A reducer that invokes every reducer inside the `reducers` object, and constructs a state object with the same shape. <ide> <ide> #### Notes <ide>
4
Python
Python
reorganize exceptions for english and german
311b30ab357260b4be940cdc0925a6a05e63e962
<ide><path>spacy/de/__init__.py <ide> from ..language import Language <ide> from ..attrs import LANG <ide> from . import language_data <add>from ..util import update_exc <add> <add>from ..language_data import EMOTICONS <add>from .language_data import ORTH_ONLY <add>from .language_data import strings_to_exc <add>from .language_data import get_time_exc <add> <add> <add>TOKENIZER_EXCEPTIONS = dict(language_data.TOKENIZER_EXCEPTIONS) <add>TOKENIZER_PREFIXES = tuple(language_data.TOKENIZER_PREFIXES) <add>TOKENIZER_SUFFIXES = tuple(language_data.TOKENIZER_SUFFIXES) <add>TOKENIZER_INFIXES = tuple(language_data.TOKENIZER_INFIXES) <add>TAG_MAP = dict(language_data.TAG_MAP) <add>STOP_WORDS = set(language_data.STOP_WORDS) <add> <add> <add>update_exc(TOKENIZER_EXCEPTIONS, strings_to_exc(EMOTICONS)) <add>update_exc(TOKENIZER_EXCEPTIONS, strings_to_exc(ORTH_ONLY)) <add>update_exc(TOKENIZER_EXCEPTIONS, get_time_exc(range(1, 24 + 1))) <ide> <ide> <ide> class German(Language): <ide> class Defaults(Language.Defaults): <ide> tokenizer_exceptions = dict(language_data.TOKENIZER_EXCEPTIONS) <ide> lex_attr_getters = dict(Language.Defaults.lex_attr_getters) <ide> lex_attr_getters[LANG] = lambda text: 'de' <del> <del> prefixes = tuple(language_data.TOKENIZER_PREFIXES) <del> <del> suffixes = tuple(language_data.TOKENIZER_SUFFIXES) <del> <del> infixes = tuple(language_data.TOKENIZER_INFIXES) <del> <del> tag_map = dict(language_data.TAG_MAP) <del> <del> stop_words = set(language_data.STOP_WORDS) <ide> <add> tokenizer_exceptions = TOKENIZER_EXCEPTIONS <add> prefixes = TOKENIZER_PREFIXES <add> suffixes = TOKENIZER_SUFFIXES <add> infixes = TOKENIZER_INFIXES <add> tag_map = TAG_MAP <add> stop_words = STOP_WORDS <ide><path>spacy/de/language_data.py <ide> import re <ide> <ide> from ..symbols import * <del>from ..language_data import EMOTICONS <add> <add> <add>def strings_to_exc(orths): <add> return {orth: [{ORTH: orth}] for orth in orths} <add> <add> <add>def get_time_exc(hours): <add> exc = {} <add> for hour in hours: <add> # currently only supporting formats like "10h", not "10 Uhr" <add> exc["%dh" % hour] = [ <add> {ORTH: hour}, <add> {ORTH: "h", LEMMA: "Uhr"} <add> ] <add> return exc <ide> <ide> <ide> PRON_LEMMA = "-PRON-" <ide> } <ide> <ide> <del>self_map = [ <add>ORTH_ONLY = [ <ide> "''", <ide> "\\\")", <ide> "<space>", <ide><path>spacy/en/__init__.py <ide> from ..vocab import Vocab <ide> from ..tokenizer import Tokenizer <ide> from ..attrs import LANG <add>from ..util import update_exc <add> <add>from ..language_data import EMOTICONS <add>from .language_data import ORTH_ONLY <add>from .language_data import strings_to_exc <add>from .language_data import get_time_exc <add> <add> <add>TOKENIZER_EXCEPTIONS = dict(language_data.TOKENIZER_EXCEPTIONS) <add>TOKENIZER_PREFIXES = tuple(language_data.TOKENIZER_PREFIXES) <add>TOKENIZER_SUFFIXES = tuple(language_data.TOKENIZER_SUFFIXES) <add>TOKENIZER_INFIXES = tuple(language_data.TOKENIZER_INFIXES) <add>TAG_MAP = dict(language_data.TAG_MAP) <add>STOP_WORDS = set(language_data.STOP_WORDS) <add> <add> <add>update_exc(TOKENIZER_EXCEPTIONS, strings_to_exc(EMOTICONS)) <add>update_exc(TOKENIZER_EXCEPTIONS, strings_to_exc(ORTH_ONLY)) <add>update_exc(TOKENIZER_EXCEPTIONS, get_time_exc(range(1, 12 + 1))) <ide> <ide> <ide> class English(Language): <ide> class Defaults(Language.Defaults): <ide> lex_attr_getters = dict(Language.Defaults.lex_attr_getters) <ide> lex_attr_getters[LANG] = lambda text: 'en' <ide> <del> tokenizer_exceptions = dict(language_data.TOKENIZER_EXCEPTIONS) <del> <del> prefixes = tuple(language_data.TOKENIZER_PREFIXES) <del> <del> suffixes = tuple(language_data.TOKENIZER_SUFFIXES) <del> <del> infixes = tuple(language_data.TOKENIZER_INFIXES) <del> <del> tag_map = dict(language_data.TAG_MAP) <del> <del> stop_words = set(language_data.STOP_WORDS) <add> tokenizer_exceptions = TOKENIZER_EXCEPTIONS <add> prefixes = TOKENIZER_PREFIXES <add> suffixes = TOKENIZER_SUFFIXES <add> infixes = TOKENIZER_INFIXES <add> tag_map = TAG_MAP <add> stop_words = STOP_WORDS <ide><path>spacy/en/language_data.py <ide> import re <ide> <ide> from ..symbols import * <del>from ..language_data import EMOTICONS <add> <add> <add>def strings_to_exc(orths): <add> return {orth: [{ORTH: orth}] for orth in orths} <add> <add> <add>def get_time_exc(hours): <add> exc = {} <add> for hour in hours: <add> exc["%da.m." % hour] = [ <add> {ORTH: hour}, <add> {ORTH: "a.m."} <add> ] <add> <add> exc["%dp.m." % hour] = [ <add> {ORTH: hour}, <add> {ORTH: "p.m."} <add> ] <add> <add> exc["%dam" % hour] = [ <add> {ORTH: hour}, <add> {ORTH: "am", LEMMA: "a.m."} <add> ] <add> <add> exc["%dpm" % hour] = [ <add> {ORTH: hour}, <add> {ORTH: "pm", LEMMA: "p.m."} <add> ] <add> return exc <ide> <ide> <ide> PRON_LEMMA = "-PRON-" <ide> } <ide> <ide> <del>self_map = [ <add>ORTH_ONLY = [ <ide> "''", <ide> "\")", <ide> "a.", <ide> "z." <ide> ] <ide> <del>for orths in [self_map, EMOTICONS]: <del> overlap = set(TOKENIZER_EXCEPTIONS.keys()).intersection(set(orths)) <del> assert not overlap, overlap <del> TOKENIZER_EXCEPTIONS.update({orth: [{ORTH: orth}] for orth in orths}) <del> <ide> <ide> TOKENIZER_PREFIXES = r''' <ide> ,
4
Ruby
Ruby
remove concurrent map require
e57826234ee49b987dfe7101dca183af3262d5ab
<ide><path>activesupport/lib/active_support/testing/time_helpers.rb <ide> <ide> require "active_support/core_ext/module/redefine_method" <ide> require "active_support/core_ext/time/calculations" <del>require "concurrent/map" <ide> <ide> module ActiveSupport <ide> module Testing
1
Text
Text
use code markup/markdown in headers
24f24d909e8c4b5ecd4af1f8a6be83b81c7651bc
<ide><path>doc/api/os.md <ide> properties. It can be accessed using: <ide> const os = require('os'); <ide> ``` <ide> <del>## os.EOL <add>## `os.EOL` <ide> <!-- YAML <ide> added: v0.7.8 <ide> --> <ide> The operating system-specific end-of-line marker. <ide> * `\n` on POSIX <ide> * `\r\n` on Windows <ide> <del>## os.arch() <add>## `os.arch()` <ide> <!-- YAML <ide> added: v0.5.0 <ide> --> <ide> compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'mips'`, <ide> <ide> The return value is equivalent to [`process.arch`][]. <ide> <del>## os.constants <add>## `os.constants` <ide> <!-- YAML <ide> added: v6.3.0 <ide> --> <ide> Contains commonly used operating system-specific constants for error codes, <ide> process signals, and so on. The specific constants defined are described in <ide> [OS Constants](#os_os_constants_1). <ide> <del>## os.cpus() <add>## `os.cpus()` <ide> <!-- YAML <ide> added: v0.3.3 <ide> --> <ide> The properties included on each object include: <ide> `nice` values are POSIX-only. On Windows, the `nice` values of all processors <ide> are always 0. <ide> <del>## os.endianness() <add>## `os.endianness()` <ide> <!-- YAML <ide> added: v0.9.4 <ide> --> <ide> binary was compiled. <ide> <ide> Possible values are `'BE'` for big endian and `'LE'` for little endian. <ide> <del>## os.freemem() <add>## `os.freemem()` <ide> <!-- YAML <ide> added: v0.3.3 <ide> --> <ide> added: v0.3.3 <ide> <ide> Returns the amount of free system memory in bytes as an integer. <ide> <del>## os.getPriority(\[pid\]) <add>## `os.getPriority([pid])` <ide> <!-- YAML <ide> added: v10.10.0 <ide> --> <ide> added: v10.10.0 <ide> Returns the scheduling priority for the process specified by `pid`. If `pid` is <ide> not provided or is `0`, the priority of the current process is returned. <ide> <del>## os.homedir() <add>## `os.homedir()` <ide> <!-- YAML <ide> added: v2.3.0 <ide> --> <ide> uses the [effective UID][EUID] to look up the user's home directory. <ide> On Windows, it uses the `USERPROFILE` environment variable if defined. <ide> Otherwise it uses the path to the profile directory of the current user. <ide> <del>## os.hostname() <add>## `os.hostname()` <ide> <!-- YAML <ide> added: v0.3.3 <ide> --> <ide> added: v0.3.3 <ide> <ide> Returns the hostname of the operating system as a string. <ide> <del>## os.loadavg() <add>## `os.loadavg()` <ide> <!-- YAML <ide> added: v0.3.3 <ide> --> <ide> system and expressed as a fractional number. <ide> The load average is a Unix-specific concept. On Windows, the return value is <ide> always `[0, 0, 0]`. <ide> <del>## os.networkInterfaces() <add>## `os.networkInterfaces()` <ide> <!-- YAML <ide> added: v0.6.0 <ide> --> <ide> The properties available on the assigned network address object include: <ide> } <ide> ``` <ide> <del>## os.platform() <add>## `os.platform()` <ide> <!-- YAML <ide> added: v0.5.0 <ide> --> <ide> The return value is equivalent to [`process.platform`][]. <ide> The value `'android'` may also be returned if Node.js is built on the Android <ide> operating system. [Android support is experimental][Android building]. <ide> <del>## os.release() <add>## `os.release()` <ide> <!-- YAML <ide> added: v0.3.3 <ide> --> <ide> On POSIX systems, the operating system release is determined by calling <ide> [uname(3)][]. On Windows, `GetVersionExW()` is used. See <ide> https://en.wikipedia.org/wiki/Uname#Examples for more information. <ide> <del>## os.setPriority(\[pid, \]priority) <add>## `os.setPriority([pid, ]priority)` <ide> <!-- YAML <ide> added: v10.10.0 <ide> --> <ide> On Windows, setting priority to `PRIORITY_HIGHEST` requires elevated user <ide> privileges. Otherwise the set priority will be silently reduced to <ide> `PRIORITY_HIGH`. <ide> <del>## os.tmpdir() <add>## `os.tmpdir()` <ide> <!-- YAML <ide> added: v0.9.9 <ide> changes: <ide> changes: <ide> Returns the operating system's default directory for temporary files as a <ide> string. <ide> <del>## os.totalmem() <add>## `os.totalmem()` <ide> <!-- YAML <ide> added: v0.3.3 <ide> --> <ide> added: v0.3.3 <ide> <ide> Returns the total amount of system memory in bytes as an integer. <ide> <del>## os.type() <add>## `os.type()` <ide> <!-- YAML <ide> added: v0.3.3 <ide> --> <ide> returns `'Linux'` on Linux, `'Darwin'` on macOS, and `'Windows_NT'` on Windows. <ide> See https://en.wikipedia.org/wiki/Uname#Examples for additional information <ide> about the output of running [uname(3)][] on various operating systems. <ide> <del>## os.uptime() <add>## `os.uptime()` <ide> <!-- YAML <ide> added: v0.3.3 <ide> changes: <ide> changes: <ide> <ide> Returns the system uptime in number of seconds. <ide> <del>## os.userInfo(\[options\]) <add>## `os.userInfo([options])` <ide> <!-- YAML <ide> added: v6.0.0 <ide> -->
1
Ruby
Ruby
remove old compatibility methods not being used
bc50cb31d6b1064463b371cf428e7eb6fcbf2fd3
<ide><path>actionpack/lib/action_controller/base.rb <ide> module ActionController <ide> # <ide> # Title: <%= @post.title %> <ide> # <del> # You don't have to rely on the automated rendering. For example, actions that could result in the rendering of different templates <add> # You don't have to rely on the automated rendering. For example, actions that could result in the rendering of different templates <ide> # will use the manual rendering methods: <ide> # <ide> # def search <ide> module ActionController <ide> # == Redirects <ide> # <ide> # Redirects are used to move from one action to another. For example, after a <tt>create</tt> action, which stores a blog entry to the <del> # database, we might like to show the user the new entry. Because we're following good DRY principles (Don't Repeat Yourself), we're <add> # database, we might like to show the user the new entry. Because we're following good DRY principles (Don't Repeat Yourself), we're <ide> # going to reuse (and redirect to) a <tt>show</tt> action that we'll assume has already been created. The code might look like this: <ide> # <ide> # def create <ide><path>actionpack/lib/action_controller/metal/compatibility.rb <ide> def rescue_action(env) <ide> end <ide> end <ide> <del> # For old tests <del> def initialize_template_class(*) end <del> def assign_shortcuts(*) end <del> <ide> def _normalize_options(options) <ide> options[:text] = nil if options.delete(:nothing) == true <ide> options[:text] = " " if options.key?(:text) && options[:text].nil? <ide><path>actionpack/test/controller/caching_test.rb <ide> def setup <ide> @controller.params = @params <ide> @controller.request = @request <ide> @controller.response = @response <del> @controller.send(:initialize_template_class, @response) <del> @controller.send(:assign_shortcuts, @request, @response) <ide> end <ide> <ide> def test_fragment_cache_key <ide><path>actionpack/test/controller/view_paths_test.rb <ide> def hello_world; render(:template => 'test/hello_world'); end <ide> end <ide> <ide> def setup <del> # TestController.view_paths = nil <del> <ide> @request = ActionController::TestRequest.new <ide> @response = ActionController::TestResponse.new <del> <ide> @controller = TestController.new <del> # Following is needed in order to setup @controller.template object properly <del> @controller.send :assign_shortcuts, @request, @response <del> @controller.send :initialize_template_class, @response <del> <ide> @paths = TestController.view_paths <ide> end <ide>
4
Ruby
Ruby
handle dependencies of moved/renamed formulae
8b30abe0600df5c9d3da5b4c31ca88a71a1c3e03
<ide><path>Library/Homebrew/keg.rb <ide> def self.find_some_installed_dependents(kegs) <ide> end <ide> <ide> keg_names = kegs.map(&:name) <del> kegs_by_source = kegs.group_by { |k| [k.name, Tab.for_keg(k).tap] } <add> kegs_by_source = kegs.group_by do |keg| <add> begin <add> # First, attempt to resolve the keg to a formula <add> # to get up-to-date name and tap information. <add> f = keg.to_formula <add> [f.name, f.tap] <add> rescue FormulaUnavailableError <add> # If the formula for the keg can't be found, <add> # fall back to the information in the tab. <add> [keg.name, Tab.for_keg(keg).tap] <add> end <add> end <ide> <ide> remaining_formulae.each do |dependent| <ide> required = dependent.missing_dependencies(hide: keg_names) <ide><path>Library/Homebrew/test/keg_test.rb <ide> def test_unknown_formula <ide> t.source["tap"] = "some/tap" <ide> t.source["path"] = nil <ide> end <add> <ide> dependencies [{ "full_name" => "some/tap/foo", "version" => "1.0" }] <ide> assert_equal [@dependent], @keg.installed_dependents <ide> assert_equal [[@keg], ["bar 1.0"]], Keg.find_some_installed_dependents([@keg]) <ide> def test_a_dependency_with_no_tap_in_tab <ide> Formula["bar"].class.depends_on "baz" <ide> <ide> result = Keg.find_some_installed_dependents([@keg, @tap_dep]) <del> assert_equal [[@tap_dep], ["bar"]], result <add> assert_equal [[@keg, @tap_dep], ["bar"]], result <ide> end <ide> <ide> def test_no_dependencies_anywhere <ide> def test_uninstalling_dependent_and_dependency <ide> assert_nil Keg.find_some_installed_dependents([@keg, @dependent]) <ide> end <ide> <add> def test_renamed_dependency <add> dependencies nil <add> <add> stub_formula_loader Formula["foo"], "homebrew/core/foo-old" <add> renamed_path = HOMEBREW_CELLAR/"foo-old" <add> (HOMEBREW_CELLAR/"foo").rename(renamed_path) <add> renamed_keg = Keg.new(renamed_path.join("1.0")) <add> <add> Formula["bar"].class.depends_on "foo" <add> <add> result = Keg.find_some_installed_dependents([renamed_keg]) <add> assert_equal [[renamed_keg], ["bar"]], result <add> ensure <add> # Move it back to where it was so it'll be cleaned up. <add> (HOMEBREW_CELLAR/"foo-old").rename(HOMEBREW_CELLAR/"foo") <add> end <add> <ide> def test_empty_dependencies_in_tab <ide> dependencies [] <ide> assert_empty @keg.installed_dependents
2
Javascript
Javascript
remove invariant hack for jest
85801ef87491e25323d3d8f9cb387f96776f3ff8
<ide><path>Libraries/Animated/src/Interpolation.js <ide> /* eslint no-bitwise: 0 */ <ide> 'use strict'; <ide> <add>var invariant = require('invariant'); <ide> var normalizeColor = require('normalizeColor'); <ide> <del>// TODO(#7644673): fix this hack once github jest actually checks invariants <del>var invariant = function(condition, message) { <del> if (!condition) { <del> var error = new Error(message); <del> (error: any).framesToPop = 1; // $FlowIssue <del> throw error; <del> } <del>}; <del> <ide> type ExtrapolateType = 'extend' | 'identity' | 'clamp'; <ide> <ide> export type InterpolationConfigType = {
1
Python
Python
fix mypy errors at even_tree algo
a5bcf0f6749a93a44f7a981edc9b0e35fbd066f2
<ide><path>graphs/even_tree.py <ide> from collections import defaultdict <ide> <ide> <del>def dfs(start): <add>def dfs(start: int) -> int: <ide> """DFS traversal""" <ide> # pylint: disable=redefined-outer-name <ide> ret = 1 <ide> visited[start] = True <del> for v in tree.get(start): <add> for v in tree[start]: <ide> if v not in visited: <ide> ret += dfs(v) <ide> if ret % 2 == 0: <ide> def even_tree(): <ide> if __name__ == "__main__": <ide> n, m = 10, 9 <ide> tree = defaultdict(list) <del> visited = {} <del> cuts = [] <add> visited: dict[int, bool] = {} <add> cuts: list[int] = [] <ide> count = 0 <ide> edges = [(2, 1), (3, 1), (4, 3), (5, 2), (6, 1), (7, 2), (8, 6), (9, 8), (10, 8)] <ide> for u, v in edges:
1
Ruby
Ruby
add install check for top-level info
80ae0e6d95aa67be0648af9318fad0d849898dc9
<ide><path>Library/Homebrew/install.rb <ide> def install f <ide> puts 'This can often be fixed by passing "--mandir=#{man}" to configure.' <ide> end <ide> <add> # Check for info pages that aren't in share/info <add> if (f.prefix+'info').exist? <add> opoo 'A top-level "info" folder was found.' <add> puts "Homebrew suggests that info pages live under share." <add> puts 'This can often be fixed by passing "--infodir=#{info}" to configure.' <add> end <add> <ide> # Check for Jars in lib <ide> if File.exist?(f.lib) <ide> unless f.lib.children.select{|g| g.to_s =~ /\.jar$/}.empty?
1
Python
Python
add textcat docstring
ebf9a7acbf06a9f9f8aaab9657d82012c569014c
<ide><path>spacy/pipeline/textcat.py <ide> default_score_weights={"cats_score": 1.0}, <ide> ) <ide> def make_textcat( <del> nlp: Language, name: str, model: Model, labels: Iterable[str] <add> nlp: Language, name: str, model: Model[List[Doc], List[Floats2d]], labels: Iterable[str] <ide> ) -> "TextCategorizer": <add> """Create a TextCategorizer compoment. The text categorizer predicts categories <add> over a whole document. It can learn one or more labels, and the labels can <add> be mutually exclusive (i.e. one true label per doc) or non-mutually exclusive <add> (i.e. zero or more labels may be true per doc). The multi-label setting is <add> controlled by the model instance that's provided. <add> <add> model (Model[List[Doc], List[Floats2d]]): A model instance that predicts <add> scores for each category. <add> labels (list): A list of categories to learn. If empty, the model infers the <add> categories from the data. <add> """ <ide> return TextCategorizer(nlp.vocab, model, name, labels=labels) <ide> <ide>
1
Ruby
Ruby
check dependency order in on_system methods
d5f949e60b6d78aa50f0409a2dfb50a63eaa554e
<ide><path>Library/Homebrew/rubocops/components_order.rb <ide> module FormulaAudit <ide> class ComponentsOrder < FormulaCop <ide> extend AutoCorrector <ide> <del> def on_system_methods <del> @on_system_methods ||= [:intel, :arm, :macos, :linux, :system, *MacOSVersions::SYMBOLS.keys].map do |m| <del> :"on_#{m}" <del> end <del> end <del> <ide> def audit_formula(_node, _class_node, _parent_class_node, body_node) <ide> @present_components, @offensive_nodes = check_order(FORMULA_COMPONENT_PRECEDENCE_LIST, body_node) <ide> <ide><path>Library/Homebrew/rubocops/dependency_order.rb <ide> class DependencyOrder < FormulaCop <ide> def audit_formula(_node, _class_node, _parent_class_node, body_node) <ide> check_dependency_nodes_order(body_node) <ide> check_uses_from_macos_nodes_order(body_node) <del> [:head, :stable].each do |block_name| <add> ([:head, :stable] + on_system_methods).each do |block_name| <ide> block = find_block(body_node, block_name) <ide> next unless block <ide> <ide><path>Library/Homebrew/rubocops/extend/formula.rb <ide> def file_path_allowed? <ide> <ide> @file_path !~ Regexp.union(paths_to_exclude) <ide> end <add> <add> def on_system_methods <add> @on_system_methods ||= [:intel, :arm, :macos, :linux, :system, *MacOSVersions::SYMBOLS.keys].map do |m| <add> :"on_#{m}" <add> end <add> end <ide> end <ide> end <ide> end
3
PHP
PHP
update entry points to reflect new directories
8e1691d6df1eb1f2d4d6761f95f6ca600af7f25a
<ide><path>App/webroot/index.php <ide> if (php_sapi_name() === 'cli-server') { <ide> $_SERVER['PHP_SELF'] = '/' . basename(__FILE__); <ide> } <del>require dirname(__DIR__) . '/Config/bootstrap.php'; <add>require dirname(__DIR__) . '/App/Config/bootstrap.php'; <ide> <ide> use Cake\Core\Configure; <ide> use Cake\Network\Request; <ide><path>App/webroot/test.php <ide> set_time_limit(0); <ide> ini_set('display_errors', 1); <ide> <del>require dirname(__DIR__) . '/Config/bootstrap.php'; <add>require dirname(__DIR__) . '/App/Config/bootstrap.php'; <ide> <ide> use Cake\Core\Configure; <ide> use Cake\TestSuite\TestSuiteDispatcher;
2
Python
Python
remove dep on python_2_unicode_compatible
192201d5840f13c8b96f44fdce4645edeb653f0f
<ide><path>rest_framework/tests/test_description.py <ide> <ide> from __future__ import unicode_literals <ide> from django.test import TestCase <del>from django.utils.encoding import python_2_unicode_compatible <ide> from rest_framework.compat import apply_markdown, smart_text <ide> from rest_framework.views import APIView <ide> from rest_framework.tests.description import ViewWithNonASCIICharactersInDocstring <ide> class that can be converted to a string. <ide> """ <ide> # use a mock object instead of gettext_lazy to ensure that we can't end <ide> # up with a test case string in our l10n catalog <del> @python_2_unicode_compatible <ide> class MockLazyStr(object): <ide> def __init__(self, string): <ide> self.s = string <ide> def __str__(self): <ide> return self.s <add> def __unicode__(self): <add> return self.s <ide> <ide> class MockView(APIView): <del> __doc__ = MockLazyStr("a gettext string") <add> __doc__ = MockLazyStr(u"a gettext string") <ide> <del> self.assertEqual(MockView().get_view_description(), 'a gettext string') <add> self.assertEqual(MockView().get_view_description(), u'a gettext string') <ide> <ide> def test_markdown(self): <ide> """
1
PHP
PHP
set the url when in console context
10010f4ed208b7c46f5f871d54733fd4a4eb12d5
<ide><path>src/Illuminate/Foundation/Application.php <ide> protected function createRequest(Request $request = null) <ide> */ <ide> public function setRequestForConsoleEnvironment() <ide> { <del> $url = $this['config']['app.url']; <add> $url = $this['config']->get('app.url', 'http://localhost'); <ide> <ide> $this['request'] = Request::create($url, 'GET', array(), array(), array(), $_SERVER); <ide> } <ide><path>src/Illuminate/Foundation/start.php <ide> <ide> $app->instance('config', $config); <ide> <add>/* <add>|-------------------------------------------------------------------------- <add>| Set The Console Request If Necessary <add>|-------------------------------------------------------------------------- <add>| <add>| If we're running in a console context, we won't have a host on this <add>| request so we'll need to re-bind a new request with a URL from a <add>| configuration file. This will help the URL generator generate. <add>| <add>*/ <add> <add>if ($app->runningInConsole()) <add>{ <add> $app->setRequestForConsoleEnvironment(); <add>} <add> <ide> /* <ide> |-------------------------------------------------------------------------- <ide> | Set The Default Timezone
2
Ruby
Ruby
return output if json parsing is not desired
e1ce5c852dc68783ab4741173173824b1e79a266
<ide><path>Library/Homebrew/utils/github.rb <ide> def api_credentials_error_message(response_headers, needed_scopes) <ide> end <ide> end <ide> <del> def open_api(url, data: nil, request_method: nil, scopes: [].freeze) <add> def open_api(url, data: nil, request_method: nil, scopes: [].freeze, parse_json: true) <ide> # This is a no-op if the user is opting out of using the GitHub API. <ide> return block_given? ? yield({}) : {} if ENV["HOMEBREW_NO_GITHUB_API"] <ide> <ide> def open_api(url, data: nil, request_method: nil, scopes: [].freeze) <ide> <ide> return if http_code == "204" # No Content <ide> <del> json = JSON.parse output <add> output = JSON.parse output if parse_json <ide> if block_given? <del> yield json <add> yield output <ide> else <del> json <add> output <ide> end <ide> rescue JSON::ParserError => e <ide> raise Error, "Failed to parse JSON response\n#{e.message}", e.backtrace
1
Mixed
Javascript
support abortsignal in fork
73a21e4c06d5781dc37f3552dea93bb6a01e19f5
<ide><path>doc/api/child_process.md <ide> controller.abort(); <ide> <!-- YAML <ide> added: v0.5.0 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/36603 <add> description: AbortSignal support was added. <ide> - version: <ide> - v13.2.0 <ide> - v12.16.0 <ide> changes: <ide> * `execPath` {string} Executable used to create the child process. <ide> * `execArgv` {string[]} List of string arguments passed to the executable. <ide> **Default:** `process.execArgv`. <add> * `gid` {number} Sets the group identity of the process (see setgid(2)). <ide> * `serialization` {string} Specify the kind of serialization used for sending <ide> messages between processes. Possible values are `'json'` and `'advanced'`. <ide> See [Advanced serialization][] for more details. **Default:** `'json'`. <add> * `signal` {AbortSignal} Allows closing the subprocess using an AbortSignal. <ide> * `silent` {boolean} If `true`, stdin, stdout, and stderr of the child will be <ide> piped to the parent, otherwise they will be inherited from the parent, see <ide> the `'pipe'` and `'inherit'` options for [`child_process.spawn()`][]'s <ide> changes: <ide> When this option is provided, it overrides `silent`. If the array variant <ide> is used, it must contain exactly one item with value `'ipc'` or an error <ide> will be thrown. For instance `[0, 1, 2, 'ipc']`. <add> * `uid` {number} Sets the user identity of the process (see setuid(2)). <ide> * `windowsVerbatimArguments` {boolean} No quoting or escaping of arguments is <ide> done on Windows. Ignored on Unix. **Default:** `false`. <del> * `uid` {number} Sets the user identity of the process (see setuid(2)). <del> * `gid` {number} Sets the group identity of the process (see setgid(2)). <ide> * Returns: {ChildProcess} <ide> <ide> The `child_process.fork()` method is a special case of <ide> current process. <ide> The `shell` option available in [`child_process.spawn()`][] is not supported by <ide> `child_process.fork()` and will be ignored if set. <ide> <add>The `signal` option works exactly the same way it does in <add>[`child_process.spawn()`][]. <add> <ide> ### `child_process.spawn(command[, args][, options])` <ide> <!-- YAML <ide> added: v0.1.90 <ide><path>lib/child_process.js <ide> function fork(modulePath /* , args, options */) { <ide> options.execPath = options.execPath || process.execPath; <ide> options.shell = false; <ide> <del> return spawn(options.execPath, args, options); <add> return spawnWithSignal(options.execPath, args, options); <ide> } <ide> <ide> function _forkChild(fd, serializationMode) { <ide> function spawnWithSignal(file, args, options) { <ide> validateAbortSignal(options.signal, 'options.signal'); <ide> function kill() { <ide> if (child._handle) { <del> child._handle.kill('SIGTERM'); <add> child.kill('SIGTERM'); <ide> child.emit('error', new AbortError()); <ide> } <ide> } <ide><path>test/fixtures/child-process-stay-alive-forever.js <add>setInterval(() => { <add> // Starting an interval to stay alive. <add>}, 1000); <ide><path>test/parallel/test-child-process-fork-abort-signal.js <add>'use strict'; <add> <add>const { mustCall } = require('../common'); <add>const { strictEqual } = require('assert'); <add>const fixtures = require('../common/fixtures'); <add>const { fork } = require('child_process'); <add> <add>{ <add> // Test aborting a forked child_process after calling fork <add> const ac = new AbortController(); <add> const { signal } = ac; <add> const cp = fork(fixtures.path('child-process-stay-alive-forever.js'), { <add> signal <add> }); <add> cp.on('exit', mustCall()); <add> cp.on('error', mustCall((err) => { <add> strictEqual(err.name, 'AbortError'); <add> })); <add> process.nextTick(() => ac.abort()); <add>} <add>{ <add> // Test passing an already aborted signal to a forked child_process <add> const ac = new AbortController(); <add> const { signal } = ac; <add> ac.abort(); <add> const cp = fork(fixtures.path('child-process-stay-alive-forever.js'), { <add> signal <add> }); <add> cp.on('exit', mustCall()); <add> cp.on('error', mustCall((err) => { <add> strictEqual(err.name, 'AbortError'); <add> })); <add>}
4
Python
Python
remove unnecessary cpplint rules
3058f08e645bca41ee0f281ed83a697be1e3c8c4
<ide><path>tools/cpplint.py <ide> def CheckIncludeLine(filename, clean_lines, linenum, include_state, error): <ide> <ide> line = clean_lines.lines[linenum] <ide> <del> # "include" should use the new style "foo/bar.h" instead of just "bar.h" <del> if _RE_PATTERN_INCLUDE_NEW_STYLE.search(line): <del> error(filename, linenum, 'build/include', 4, <del> 'Include the directory when naming .h files') <del> <ide> # we shouldn't include a file more than once. actually, there are a <ide> # handful of instances where doing so is okay, but in general it's <ide> # not. <ide> def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error, <ide> if not line or line[0] == '#': <ide> continue <ide> <del> # String is special -- it is a non-templatized type in STL. <del> m = _RE_PATTERN_STRING.search(line) <del> if m: <del> # Don't warn about strings in non-STL namespaces: <del> # (We check only the first match per line; good enough.) <del> prefix = line[:m.start()] <del> if prefix.endswith('std::') or not prefix.endswith('::'): <del> required['<string>'] = (linenum, 'string') <del> <ide> for pattern, template, header in _re_pattern_algorithm_header: <ide> if pattern.search(line): <ide> required[header] = (linenum, template)
1
Python
Python
add tests for maximum_sctype
00e50a3a38d1f86e027dd1d77fd5491ade7d248a
<ide><path>numpy/core/tests/test_numerictypes.py <ide> import sys <ide> import itertools <ide> <add>import pytest <ide> import numpy as np <ide> from numpy.testing import assert_, assert_equal, assert_raises <ide> <ide> def TestSctypeDict(object): <ide> def test_longdouble(self): <ide> assert_(np.sctypeDict['f8'] is not np.longdouble) <ide> assert_(np.sctypeDict['c16'] is not np.clongdouble) <add> <add> <add>class TestMaximumSctype(object): <add> <add> # note that parametrizing with sctype['int'] and similar would skip types <add> # with the same size (gh-11923) <add> <add> @pytest.mark.parametrize('t', [np.byte, np.short, np.intc, np.int_, np.longlong]) <add> def test_int(self, t): <add> assert_equal(np.maximum_sctype(t), np.sctypes['int'][-1]) <add> <add> @pytest.mark.parametrize('t', [np.ubyte, np.ushort, np.uintc, np.uint, np.ulonglong]) <add> def test_uint(self, t): <add> assert_equal(np.maximum_sctype(t), np.sctypes['uint'][-1]) <add> <add> @pytest.mark.parametrize('t', [np.half, np.single, np.double, np.longdouble]) <add> def test_float(self, t): <add> assert_equal(np.maximum_sctype(t), np.sctypes['float'][-1]) <add> <add> @pytest.mark.parametrize('t', [np.csingle, np.cdouble, np.clongdouble]) <add> def test_complex(self, t): <add> assert_equal(np.maximum_sctype(t), np.sctypes['complex'][-1]) <add> <add> @pytest.mark.parametrize('t', [np.bool_, np.object_, np.unicode_, np.bytes_, np.void]) <add> def test_other(self, t): <add> assert_equal(np.maximum_sctype(t), t)
1
Text
Text
tweak the text a little
d79e597f301fdf42a0f441f35b48504a5b07eb8b
<ide><path>docs/sources/articles/https.md <ide> name) matches the hostname you will use to connect to Docker: <ide> <ide> Next, we're going to sign the public key with our CA: <ide> <del>Since tls connections can be made via IP address as well as dns name, <del>this extension allows for your client to connect via IP address. You will <del>need to replace $YOUR_IP_ADDRESS with your IP address. If there <del>is more than one simply continue to add them separated by commas. <add>Since TLS connections can be made via IP address as well as DNS name, they need <add>to be specified when creating the certificate. For example, to allow connections <add>using `10.10.10.20` and `127.0.0.1`: <ide> <del> $ echo subjectAltName = IP:$YOUR_PUBLIC_IP > extfile.cnf <add> $ echo subjectAltName = IP:10.10.10.20,IP:127.0.0.1 > extfile.cnf <ide> <ide> $ openssl x509 -req -days 365 -in server.csr -CA ca.pem -CAkey ca-key.pem \ <ide> -CAcreateserial -out server-cert.pem -extfile extfile.cnf
1
Java
Java
add appproperty to reactrootview
57b0039ce1c89423cd3038e411a12df7e572a46b
<ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManager.java <ide> private void attachMeasuredRootViewToInstance( <ide> UIManagerModule uiManagerModule = catalystInstance.getNativeModule(UIManagerModule.class); <ide> int rootTag = uiManagerModule.addMeasuredRootView(rootView); <ide> rootView.setRootViewTag(rootTag); <del> @Nullable Bundle launchOptions = rootView.getLaunchOptions(); <del> WritableMap initialProps = Arguments.makeNativeMap(launchOptions); <del> String jsAppModuleName = rootView.getJSModuleName(); <del> <del> WritableNativeMap appParams = new WritableNativeMap(); <del> appParams.putDouble("rootTag", rootTag); <del> appParams.putMap("initialProps", initialProps); <del> catalystInstance.getJSModule(AppRegistry.class).runApplication(jsAppModuleName, appParams); <add> rootView.runApplication(); <ide> UiThreadUtil.runOnUiThread(new Runnable() { <ide> @Override <ide> public void run() { <ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactRootView.java <ide> import com.facebook.common.logging.FLog; <ide> import com.facebook.infer.annotation.Assertions; <ide> import com.facebook.react.bridge.Arguments; <add>import com.facebook.react.bridge.CatalystInstance; <ide> import com.facebook.react.bridge.ReactContext; <ide> import com.facebook.react.bridge.UiThreadUtil; <ide> import com.facebook.react.bridge.WritableMap; <add>import com.facebook.react.bridge.WritableNativeMap; <ide> import com.facebook.react.common.ReactConstants; <ide> import com.facebook.react.common.annotations.VisibleForTesting; <add>import com.facebook.react.modules.appregistry.AppRegistry; <ide> import com.facebook.react.modules.core.DeviceEventManagerModule; <ide> import com.facebook.react.modules.deviceinfo.DeviceInfoModule; <ide> import com.facebook.react.uimanager.DisplayMetricsHolder; <ide> public interface ReactRootViewEventListener { <ide> <ide> private @Nullable ReactInstanceManager mReactInstanceManager; <ide> private @Nullable String mJSModuleName; <del> private @Nullable Bundle mLaunchOptions; <add> private @Nullable Bundle mAppProperties; <ide> private @Nullable CustomGlobalLayoutListener mCustomGlobalLayoutListener; <ide> private @Nullable ReactRootViewEventListener mRootViewEventListener; <ide> private int mRootViewTag; <ide> public void startReactApplication(ReactInstanceManager reactInstanceManager, Str <ide> public void startReactApplication( <ide> ReactInstanceManager reactInstanceManager, <ide> String moduleName, <del> @Nullable Bundle launchOptions) { <add> @Nullable Bundle initialProperties) { <ide> UiThreadUtil.assertOnUiThread(); <ide> <ide> // TODO(6788889): Use POJO instead of bundle here, apparently we can't just use WritableMap <ide> public void startReactApplication( <ide> <ide> mReactInstanceManager = reactInstanceManager; <ide> mJSModuleName = moduleName; <del> mLaunchOptions = launchOptions; <add> mAppProperties = initialProperties; <ide> <ide> if (!mReactInstanceManager.hasStartedCreatingInitialContext()) { <ide> mReactInstanceManager.createReactContextInBackground(); <ide> public void setEventListener(ReactRootViewEventListener eventListener) { <ide> return Assertions.assertNotNull(mJSModuleName); <ide> } <ide> <del> /* package */ @Nullable Bundle getLaunchOptions() { <del> return mLaunchOptions; <add> public @Nullable Bundle getAppProperties() { <add> return mAppProperties; <add> } <add> <add> public void setAppProperties(@Nullable Bundle appProperties) { <add> UiThreadUtil.assertOnUiThread(); <add> mAppProperties = appProperties; <add> runApplication(); <add> } <add> <add> /** <add> * Calls into JS to start the React application. Can be called multiple times with the <add> * same rootTag, which will re-render the application from the root. <add> */ <add> /* package */ void runApplication() { <add> if (mReactInstanceManager == null || !mIsAttachedToInstance) { <add> return; <add> } <add> <add> ReactContext reactContext = mReactInstanceManager.getCurrentReactContext(); <add> if (reactContext == null) { <add> return; <add> } <add> <add> CatalystInstance catalystInstance = reactContext.getCatalystInstance(); <add> <add> WritableNativeMap appParams = new WritableNativeMap(); <add> appParams.putDouble("rootTag", getRootViewTag()); <add> @Nullable Bundle appProperties = getAppProperties(); <add> if (appProperties != null) { <add> appParams.putMap("initialProps", Arguments.fromBundle(appProperties)); <add> } <add> <add> String jsAppModuleName = getJSModuleName(); <add> catalystInstance.getJSModule(AppRegistry.class).runApplication(jsAppModuleName, appParams); <ide> } <ide> <ide> /**
2
PHP
PHP
remove usage of prefix increment operator
1cca695360a522deb93bbfd1eef3820c43ff540a
<ide><path>src/Core/PluginCollection.php <ide> public function get($name) <ide> */ <ide> public function next() <ide> { <del> ++$this->position; <add> $this->position++; <ide> } <ide> <ide> /** <ide><path>src/Filesystem/Folder.php <ide> public function dirsize() <ide> $directory = Folder::slashTerm($this->path); <ide> $stack = [$directory]; <ide> $count = count($stack); <del> for ($i = 0, $j = $count; $i < $j; ++$i) { <add> for ($i = 0, $j = $count; $i < $j; $i++) { <ide> if (is_file($stack[$i])) { <ide> $size += filesize($stack[$i]); <ide> } elseif (is_dir($stack[$i])) { <ide><path>src/Utility/Text.php <ide> public static function tokenize($data, $separator = ',', $leftBound = '(', $righ <ide> } <ide> } <ide> } <del> $offset = ++$tmpOffset; <add> $offset = $tmpOffset++; <ide> } else { <ide> $results[] = $buffer . mb_substr($data, $offset); <ide> $offset = $length + 1; <ide><path>src/View/Helper/HtmlHelper.php <ide> protected function _renderCells($line, $useCount = false) <ide> } <ide> <ide> if ($useCount) { <add> $i += 1; <ide> if (isset($cellOptions['class'])) { <del> $cellOptions['class'] .= ' column-' . ++$i; <add> $cellOptions['class'] .= ' column-' . $i; <ide> } else { <del> $cellOptions['class'] = 'column-' . ++$i; <add> $cellOptions['class'] = 'column-' . $i; <ide> } <ide> } <ide>
4
Text
Text
fix typos in working_groups.md
a0c70808b306bfd1ec9dbcbe8b633c531b7b224c
<ide><path>WORKING_GROUPS.md <ide> content. <ide> ### [HTTP](https://github.com/nodejs/http) <ide> <ide> The HTTP working group is chartered for the support and improvement of the <del>HTTP implementation in Node. It's responsibilities are: <add>HTTP implementation in Node. Its responsibilities are: <ide> <ide> * Addressing HTTP issues on the Node.js issue tracker. <ide> * Authoring and editing HTTP documentation within the Node.js project. <ide> Its responsibilities are: <ide> The Node.js Testing Working Group's purpose is to extend and improve testing of <ide> the Node.js source code. <ide> <del>It's responsibilities are: <add>Its responsibilities are: <ide> <ide> * Coordinating an overall strategy for improving testing. <ide> * Documenting guidelines around tests.
1
Ruby
Ruby
prefer regexp#match? over regexp#===
ee669ab36fe93b8784416c408e84dee5c49d7427
<ide><path>activesupport/lib/active_support/inflector/inflections.rb <ide> require "concurrent/map" <ide> require "active_support/core_ext/array/prepend_and_append" <add>require "active_support/core_ext/regexp" <ide> require "active_support/i18n" <ide> <ide> module ActiveSupport <ide> def add(words) <ide> end <ide> <ide> def uncountable?(str) <del> @regex_array.any? { |regex| regex === str } <add> @regex_array.any? { |regex| regex.match? str } <ide> end <ide> <ide> private
1
Ruby
Ruby
use `env` utility instead of `with_env`
37f3a603cecb24799d3b1087b342c270b78dcc12
<ide><path>Library/Homebrew/cask/lib/hbc/system_command.rb <ide> def initialize(executable, args: [], sudo: false, input: [], print_stdout: false <ide> @must_succeed = must_succeed <ide> options.extend(HashValidator).assert_valid_keys(:chdir) <ide> @options = options <del> @env = { "PATH" => ENV["PATH"] }.merge(env) <add> @env = env <ide> <ide> @env.keys.grep_v(/^[\w&&\D]\w*$/) do |name| <ide> raise ArgumentError, "Invalid variable name: '#{name}'" <ide> end <ide> end <ide> <ide> def command <del> [*sudo_prefix, executable, *args] <add> [*sudo_prefix, *env_args, executable, *args] <ide> end <ide> <ide> private <ide> def command <ide> <ide> attr_predicate :sudo?, :print_stdout?, :print_stderr?, :must_succeed? <ide> <del> def sudo_prefix <del> return [] unless sudo? <del> askpass_flags = ENV.key?("SUDO_ASKPASS") ? ["-A"] : [] <del> prefix = ["/usr/bin/sudo", *askpass_flags, "-E"] <add> def env_args <add> return [] if env.empty? <ide> <del> env.each do |name, value| <add> variables = env.map do |name, value| <ide> sanitized_name = Shellwords.escape(name) <ide> sanitized_value = Shellwords.escape(value) <del> prefix << "#{sanitized_name}=#{sanitized_value}" <add> "#{sanitized_name}=#{sanitized_value}" <ide> end <ide> <del> prefix << "--" <add> ["env", *variables] <add> end <add> <add> def sudo_prefix <add> return [] unless sudo? <add> askpass_flags = ENV.key?("SUDO_ASKPASS") ? ["-A"] : [] <add> ["/usr/bin/sudo", *askpass_flags, "-E", "--"] <ide> end <ide> <ide> def assert_success <ide> def each_output_line(&b) <ide> executable, *args = expanded_command <ide> <ide> raw_stdin, raw_stdout, raw_stderr, raw_wait_thr = <del> # We need to specifically use `with_env` for `PATH`, otherwise <del> # Ruby itself will not look for the executable in `PATH`. <del> with_env "PATH" => env["PATH"] do <del> Open3.popen3(env, [executable, executable], *args, **options) <del> end <add> Open3.popen3([executable, executable], *args, **options) <ide> <ide> write_input_to(raw_stdin) <ide> raw_stdin.close_write <ide><path>Library/Homebrew/test/cask/system_command_spec.rb <ide> its("run!.stdout") { is_expected.to eq("123") } <ide> <ide> describe "the resulting command line" do <del> it "does not include the given variables" do <add> it "includes the given variables explicitly" do <ide> expect(Open3) <ide> .to receive(:popen3) <del> .with(a_hash_including("PATH"), ["env"] * 2, *env_args, {}) <add> .with(["env", "env"], "A=1", "B=2", "C=3", "env", *env_args, {}) <ide> .and_call_original <ide> <ide> subject.run! <ide> it "includes the given variables explicitly" do <ide> expect(Open3) <ide> .to receive(:popen3) <del> .with(an_instance_of(Hash), ["/usr/bin/sudo"] * 2, <del> "-E", a_string_starting_with("PATH="), <del> "A=1", "B=2", "C=3", "--", "env", *env_args, {}) <add> .with(["/usr/bin/sudo", "/usr/bin/sudo"], "-E", "--", <add> "env", "A=1", "B=2", "C=3", "env", *env_args, {}) <ide> .and_wrap_original do |original_popen3, *_, &block| <ide> original_popen3.call("/usr/bin/true", &block) <ide> end <ide> end <ide> end <ide> <del> it "looks for executables in custom PATH" do <add> it "looks for executables in a custom PATH" do <ide> mktmpdir do |path| <ide> (path/"tool").write <<~SH <ide> #!/bin/sh <ide><path>Library/Homebrew/test/support/helper/cask/fake_system_command.rb <ide> def sudo(*args) <del> ["/usr/bin/sudo", "-E", "PATH=#{ENV["PATH"]}", "--"] + args.flatten <add> ["/usr/bin/sudo", "-E", "--"] + args.flatten <ide> end <ide> <ide> module Hbc <ide><path>Library/Homebrew/test/support/helper/spec/shared_examples/hbc_staged.rb <ide> allow(staged).to receive(:Pathname).and_return(fake_pathname) <ide> <ide> Hbc::FakeSystemCommand.expects_command( <del> ["/usr/bin/sudo", "-E", "PATH=#{ENV["PATH"]}", "--", "/usr/sbin/chown", "-R", "--", "fake_user:staff", fake_pathname], <add> sudo("/usr/sbin/chown", "-R", "--", "fake_user:staff", fake_pathname), <ide> ) <ide> <ide> staged.set_ownership(fake_pathname.to_s) <ide> allow(staged).to receive(:Pathname).and_return(fake_pathname) <ide> <ide> Hbc::FakeSystemCommand.expects_command( <del> ["/usr/bin/sudo", "-E", "PATH=#{ENV["PATH"]}", "--", "/usr/sbin/chown", "-R", "--", "fake_user:staff", fake_pathname, fake_pathname], <add> sudo("/usr/sbin/chown", "-R", "--", "fake_user:staff", fake_pathname, fake_pathname), <ide> ) <ide> <ide> staged.set_ownership([fake_pathname.to_s, fake_pathname.to_s]) <ide> allow(staged).to receive(:Pathname).and_return(fake_pathname) <ide> <ide> Hbc::FakeSystemCommand.expects_command( <del> ["/usr/bin/sudo", "-E", "PATH=#{ENV["PATH"]}", "--", "/usr/sbin/chown", "-R", "--", "other_user:other_group", fake_pathname], <add> sudo("/usr/sbin/chown", "-R", "--", "other_user:other_group", fake_pathname), <ide> ) <ide> <ide> staged.set_ownership(fake_pathname.to_s, user: "other_user", group: "other_group")
4
Python
Python
skip hiddenfield from schema fields
d0ed482d7094e94b8cbfdc6c0f8335e02d79b765
<ide><path>rest_framework/schemas.py <ide> def get_serializer_fields(self, path, method, callback, view): <ide> <ide> fields = [] <ide> for field in serializer.fields.values(): <del> if field.read_only: <add> if field.read_only or isinstance(field, serializers.HiddenField): <ide> continue <add> <ide> required = field.required and method != 'PATCH' <ide> description = force_text(field.help_text) if field.help_text else '' <ide> field = coreapi.Field( <ide><path>tests/test_schemas.py <ide> class ExamplePagination(pagination.PageNumberPagination): <ide> class ExampleSerializer(serializers.Serializer): <ide> a = serializers.CharField(required=True, help_text='A field description') <ide> b = serializers.CharField(required=False) <add> read_only = serializers.CharField(read_only=True) <add> hidden = serializers.HiddenField(default='hello') <ide> <ide> <ide> class AnotherSerializer(serializers.Serializer):
2
Text
Text
fix code of getting-started-ja-jp
005b65c17bbc06215a2cf94a485382a2dc44cf87
<ide><path>docs/docs/getting-started.ja-JP.md <ide> React でのハッキングを始めるにあたり、一番簡単なものと <ide> </div> <ide> <ide> スターターキットのルートディレクトリに `helloworld.html` を作り、次のように書いてみましょう。 <add> <ide> ```html <ide> <!DOCTYPE html> <ide> <html>
1
Text
Text
add v3.21.0 to changelog
20bc7a6a09fda8ff415fccca01dd61c8fd28b2f1
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <del>### v3.21.0-beta.6 (August 17, 2020) <del> <del>- [#19087](https://github.com/emberjs/ember.js/pull/19087) [BUGFIX] Generated initializer tests no longer causes a deprecation warning <del>- [#19077](https://github.com/emberjs/ember.js/pull/19077) Simplify `get` and improve `computed` caching scheme. <del>- [#19082](https://github.com/emberjs/ember.js/pull/19082) Simplify mixin application <del>- [#19089](https://github.com/emberjs/ember.js/pull/19089) Update rendering engine to improve immediate encoding performance <del> <del>### v3.21.0-beta.5 (August 5, 2020) <del> <del>- [#19028](https://github.com/emberjs/ember.js/pull/19028) [BUGFIX] Ensure setter CP's with dependent keys on curly components can be two way bound <del> <del>### v3.21.0-beta.4 (August 3, 2020) <del> <del>- [#19059](https://github.com/emberjs/ember.js/pull/19059) [BUGFIX] Prevent `<base target="_parent">` from erroring in `HistoryLocation` <del>- [#19060](https://github.com/emberjs/ember.js/pull/19060) / [#19065](https://github.com/emberjs/ember.js/pull/19065) / [#19072](https://github.com/emberjs/ember.js/pull/19072) [BUGFIX] Update rendering engine to `@glimmer/*` 0.55.3 <del>- [#19063](https://github.com/emberjs/ember.js/pull/19063) [DOC] Fix missing docs for `{{#in-element}}` <del> <del>### v3.21.0-beta.3 (July 27, 2020) <del> <del>- [#19048](https://github.com/emberjs/ember.js/pull/19048) [BUGFIX] Update router.js to ensure transition.abort works for query param only transitions. <del>- [#19056](https://github.com/emberjs/ember.js/pull/19056) [BUGFIX] Update glimmer-vm to 0.54.2. <del> <del>### v3.21.0-beta.2 (July 20, 2020) <del> <del>- [#19040](https://github.com/emberjs/ember.js/pull/19040) [BUGFIX] Fix a memory leak that occurred when changing the array passed to `{{each}}` <del>- [#19047](https://github.com/emberjs/ember.js/pull/19047) [BUGFIX] Ensure `inject-babel-helpers` plugin can be parallelized <del> <del>### v3.21.0-beta.1 (July 13, 2020) <add>### v3.21.0 (August 24, 2020) <ide> <ide> - [#18993](https://github.com/emberjs/ember.js/pull/18993) [DEPRECATION] Deprecate `getWithDefault` per [RFC #554](https://github.com/emberjs/rfcs/blob/master/text/0554-deprecate-getwithdefault.md). <add>- [#19087](https://github.com/emberjs/ember.js/pull/19087) [BUGFIX] Generated initializer tests no longer causes a deprecation warning <ide> - [#17571](https://github.com/emberjs/ember.js/pull/17571) [BUGFIX] Avoid tampering `queryParam` argument in RouterService#isActive <ide> <ide> ### v3.20.4 (August 11, 2020)
1
PHP
PHP
fix phpdoc comment
12272dd2024795800c69b1643a4d3f0be056e28e
<ide><path>src/Illuminate/Database/Connection.php <ide> protected function getElapsedTime($start) <ide> * @param array $bindings <ide> * @param \Closure $callback <ide> * @return mixed <add> * @throws \Exception <ide> */ <ide> protected function handleQueryException($e, $query, $bindings, Closure $callback) <ide> { <ide><path>src/Illuminate/Foundation/Bootstrap/LoadConfiguration.php <ide> public function bootstrap(Application $app) <ide> * @param \Illuminate\Contracts\Foundation\Application $app <ide> * @param \Illuminate\Contracts\Config\Repository $repository <ide> * @return void <add> * @throws \Exception <ide> */ <ide> protected function loadConfigurationFiles(Application $app, RepositoryContract $repository) <ide> { <ide><path>src/Illuminate/Mail/Markdown.php <ide> class Markdown <ide> /** <ide> * Create a new Markdown renderer instance. <ide> * <del> * @param \Illuminate\View\Factory $view <add> * @param \Illuminate\Contracts\View\Factory $view <ide> * @param array $options <ide> * @return void <ide> */ <ide><path>src/Illuminate/View/Engines/CompilerEngine.php <ide> public function get($path, array $data = []) <ide> * @param int $obLevel <ide> * @return void <ide> * <del> * @throws $e <add> * @throws \Exception <ide> */ <ide> protected function handleViewException(Exception $e, $obLevel) <ide> { <ide><path>src/Illuminate/View/Engines/PhpEngine.php <ide> protected function evaluatePath($__path, $__data) <ide> * @param int $obLevel <ide> * @return void <ide> * <del> * @throws $e <add> * @throws \Exception <ide> */ <ide> protected function handleViewException(Exception $e, $obLevel) <ide> {
5
Python
Python
skip failing test on 2.5
76c2d75b64277acdacb345442fd8421645c4d187
<ide><path>celery/tests/worker/test_worker.py <ide> from __future__ import with_statement <ide> <ide> import socket <add>import sys <ide> <ide> from collections import deque <ide> from datetime import datetime, timedelta <ide> def test_apply_eta_task(self): <ide> self.assertIs(self.ready_queue.get_nowait(), task) <ide> <ide> def test_receieve_message_eta_isoformat(self): <add> if sys.version_info < (2, 6): <add> raise SkipTest('test broken on Python 2.5') <ide> l = MyKombuConsumer(self.ready_queue, timer=self.timer) <ide> m = create_message(Mock(), task=foo_task.name, <ide> eta=datetime.now().isoformat(),
1
PHP
PHP
add missing cookies property
52fd65dea65f8ccc43d5a22a781fe81d7f4b7d35
<ide><path>lib/Cake/Network/Request.php <ide> class Request implements \ArrayAccess { <ide> 'plugin' => null, <ide> 'controller' => null, <ide> 'action' => null, <del> 'pass' => array(), <add> 'pass' => [], <ide> ); <ide> <ide> /** <ide> class Request implements \ArrayAccess { <ide> * <ide> * @var array <ide> */ <del> public $data = array(); <add> public $data = []; <ide> <ide> /** <ide> * Array of querystring arguments <ide> * <ide> * @var array <ide> */ <del> public $query = array(); <add> public $query = []; <add> <add>/** <add> * Array of cookie data. <add> * <add> * @var array <add> */ <add> public $cookies = []; <ide> <ide> /** <ide> * The url string used for the request.
1
Python
Python
ignore past_key_values during gpt-neo inference
68b0baeedcf29fefe42b4bbfec04f309b03e63a6
<ide><path>src/transformers/models/gpt_neo/configuration_gpt_neo.py <ide> class GPTNeoConfig(PretrainedConfig): <ide> >>> configuration = model.config <ide> """ <ide> model_type = "gpt_neo" <add> keys_to_ignore_at_inference = ["past_key_values"] <ide> attribute_map = {"num_attention_heads": "num_heads", "num_hidden_layers": "num_layers"} <ide> <ide> def __init__(
1
Mixed
Ruby
delegate some additional methods in querying.rb
78ea4c598547c46cdfcf71aa484782ac903a3040
<ide><path>activerecord/CHANGELOG.md <add>* Delegate `empty?`, `none?` and `one?`. Now they can be invoked as model class methods. <add> <add> Example: <add> <add> # When no record is found on the table <add> Topic.empty? # => true <add> Topic.none? # => true <add> <add> # When only one record is found on the table <add> Topic.one? # => true <add> <add> *Kenta Shirai* <add> <ide> * The form builder now properly displays values when passing a proc form <ide> default to the attributes API. <ide> <ide><path>activerecord/lib/active_record/querying.rb <ide> module ActiveRecord <ide> module Querying <del> delegate :find, :take, :take!, :first, :first!, :last, :last!, :exists?, :any?, :many?, to: :all <add> delegate :find, :take, :take!, :first, :first!, :last, :last!, :exists?, :any?, :many?, :empty?, :none?, :one?, to: :all <ide> delegate :second, :second!, :third, :third!, :fourth, :fourth!, :fifth, :fifth!, :forty_two, :forty_two!, :third_to_last, :third_to_last!, :second_to_last, :second_to_last!, to: :all <ide> delegate :first_or_create, :first_or_create!, :first_or_initialize, to: :all <ide> delegate :find_or_create_by, :find_or_create_by!, :find_or_initialize_by, to: :all <ide><path>activerecord/test/cases/scoping/named_scoping_test.rb <ide> def test_subclass_merges_scopes_properly <ide> assert_equal 1, SpecialComment.where(body: 'go crazy').created.count <ide> end <ide> <add> def test_model_class_should_respond_to_empty <add> assert !Topic.empty? <add> Topic.delete_all <add> assert Topic.empty? <add> end <add> <add> def test_model_class_should_respond_to_none <add> assert !Topic.none? <add> Topic.delete_all <add> assert Topic.none? <add> end <add> <add> def test_model_class_should_respond_to_one <add> assert !Topic.one? <add> Topic.delete_all <add> assert !Topic.one? <add> Topic.create! <add> assert Topic.one? <add> end <add> <ide> end
3
Go
Go
add sandbox id to `service ls` output
50ec2d3a50fe84fff8d9132fb72c2f4b0628d065
<ide><path>libnetwork/client/service.go <ide> func (cli *NetworkCli) CmdServiceLs(chain string, args ...string) error { <ide> wr := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0) <ide> // unless quiet (-q) is specified, print field titles <ide> if !*quiet { <del> fmt.Fprintln(wr, "SERVICE ID\tNAME\tNETWORK\tCONTAINER") <add> fmt.Fprintln(wr, "SERVICE ID\tNAME\tNETWORK\tCONTAINER\tSANDBOX") <ide> } <ide> <ide> for _, sr := range serviceResources { <ide> ID := sr.ID <del> bkID, err := getBackendID(cli, ID) <add> bkID, sbID, err := getBackendID(cli, ID) <ide> if err != nil { <ide> return err <ide> } <ide> if !*noTrunc { <ide> ID = stringid.TruncateID(ID) <ide> bkID = stringid.TruncateID(bkID) <add> sbID = stringid.TruncateID(sbID) <ide> } <ide> if !*quiet { <del> fmt.Fprintf(wr, "%s\t%s\t%s\t%s\n", ID, sr.Name, sr.Network, bkID) <add> fmt.Fprintf(wr, "%s\t%s\t%s\t%s\t%s\n", ID, sr.Name, sr.Network, bkID, sbID) <ide> } else { <ide> fmt.Fprintln(wr, ID) <ide> } <ide> func (cli *NetworkCli) CmdServiceLs(chain string, args ...string) error { <ide> return nil <ide> } <ide> <del>func getBackendID(cli *NetworkCli, servID string) (string, error) { <add>func getBackendID(cli *NetworkCli, servID string) (string, string, error) { <ide> var ( <ide> obj []byte <ide> err error <ide> bk string <add> sb string <ide> ) <ide> <ide> if obj, _, err = readBody(cli.call("GET", "/services/"+servID+"/backend", nil, nil)); err == nil { <ide> var sr SandboxResource <ide> if err := json.NewDecoder(bytes.NewReader(obj)).Decode(&sr); err == nil { <ide> bk = sr.ContainerID <add> sb = sr.ID <ide> } else { <ide> // Only print a message, don't make the caller cli fail for this <ide> fmt.Fprintf(cli.out, "Failed to retrieve backend list for service %s (%v)\n", servID, err) <ide> } <ide> } <ide> <del> return bk, err <add> return bk, sb, err <ide> } <ide> <ide> // CmdServiceInfo handles service info UI
1
Mixed
Javascript
change the defaults maxbuffer size
652877e3a9eee3f863314382f64f8ac1e5b27186
<ide><path>doc/api/child_process.md <ide> changes: <ide> * `maxBuffer` {number} Largest amount of data in bytes allowed on stdout or <ide> stderr. If exceeded, the child process is terminated and any output is <ide> truncated. See caveat at [`maxBuffer` and Unicode][]. <del> **Default:** `200 * 1024`. <add> **Default:** `1024 * 1024`. <ide> * `killSignal` {string|integer} **Default:** `'SIGTERM'` <ide> * `uid` {number} Sets the user identity of the process (see setuid(2)). <ide> * `gid` {number} Sets the group identity of the process (see setgid(2)). <ide> changes: <ide> * `maxBuffer` {number} Largest amount of data in bytes allowed on stdout or <ide> stderr. If exceeded, the child process is terminated and any output is <ide> truncated. See caveat at [`maxBuffer` and Unicode][]. <del> **Default:** `200 * 1024`. <add> **Default:** `1024 * 1024`. <ide> * `killSignal` {string|integer} **Default:** `'SIGTERM'` <ide> * `uid` {number} Sets the user identity of the process (see setuid(2)). <ide> * `gid` {number} Sets the group identity of the process (see setgid(2)). <ide> changes: <ide> process will be killed. **Default:** `'SIGTERM'`. <ide> * `maxBuffer` {number} Largest amount of data in bytes allowed on stdout or <ide> stderr. If exceeded, the child process is terminated. See caveat at <del> [`maxBuffer` and Unicode][]. **Default:** `200 * 1024`. <add> [`maxBuffer` and Unicode][]. **Default:** `1024 * 1024`. <ide> * `encoding` {string} The encoding used for all stdio inputs and outputs. <ide> **Default:** `'buffer'`. <ide> * `windowsHide` {boolean} Hide the subprocess console window that would <ide> changes: <ide> * `maxBuffer` {number} Largest amount of data in bytes allowed on stdout or <ide> stderr. If exceeded, the child process is terminated and any output is <ide> truncated. See caveat at [`maxBuffer` and Unicode][]. <del> **Default:** `200 * 1024`. <add> **Default:** `1024 * 1024`. <ide> * `encoding` {string} The encoding used for all stdio inputs and outputs. <ide> **Default:** `'buffer'`. <ide> * `windowsHide` {boolean} Hide the subprocess console window that would <ide> changes: <ide> * `maxBuffer` {number} Largest amount of data in bytes allowed on stdout or <ide> stderr. If exceeded, the child process is terminated and any output is <ide> truncated. See caveat at [`maxBuffer` and Unicode][]. <del> **Default:** `200 * 1024`. <add> **Default:** `1024 * 1024`. <ide> * `encoding` {string} The encoding used for all stdio inputs and outputs. <ide> **Default:** `'buffer'`. <ide> * `shell` {boolean|string} If `true`, runs `command` inside of a shell. Uses <ide><path>lib/child_process.js <ide> const { <ide> ChildProcess <ide> } = child_process; <ide> <del>const MAX_BUFFER = 200 * 1024; <add>const MAX_BUFFER = 1024 * 1024; <ide> <ide> exports.ChildProcess = ChildProcess; <ide> <ide><path>test/parallel/test-child-process-exec-maxbuf.js <ide> function runChecks(err, stdio, streamName, expected) { <ide> <ide> // default value <ide> { <del> const cmd = `"${process.execPath}" -e "console.log('a'.repeat(200 * 1024))"`; <add> const cmd = <add> `"${process.execPath}" -e "console.log('a'.repeat(1024 * 1024))"`; <ide> <ide> cp.exec(cmd, common.mustCall((err) => { <ide> assert(err instanceof RangeError); <ide> function runChecks(err, stdio, streamName, expected) { <ide> // default value <ide> { <ide> const cmd = <del> `${process.execPath} -e "console.log('a'.repeat(200 * 1024 - 1))"`; <add> `${process.execPath} -e "console.log('a'.repeat(1024 * 1024 - 1))"`; <ide> <ide> cp.exec(cmd, common.mustCall((err, stdout, stderr) => { <ide> assert.ifError(err); <del> assert.strictEqual(stdout.trim(), 'a'.repeat(200 * 1024 - 1)); <add> assert.strictEqual(stdout.trim(), 'a'.repeat(1024 * 1024 - 1)); <ide> assert.strictEqual(stderr, ''); <ide> })); <ide> } <ide> function runChecks(err, stdio, streamName, expected) { <ide> <ide> // default value <ide> { <del> const cmd = `"${process.execPath}" -e "console.log('a'.repeat(200 * 1024))"`; <add> const cmd = <add> `"${process.execPath}" -e "console.log('a'.repeat(1024 * 1024))"`; <ide> <ide> cp.exec( <ide> cmd, <ide> common.mustCall((err, stdout, stderr) => { <del> runChecks(err, { stdout, stderr }, 'stdout', 'a'.repeat(200 * 1024)); <add> runChecks( <add> err, <add> { stdout, stderr }, <add> 'stdout', <add> 'a'.repeat(1024 * 1024) <add> ); <ide> }) <ide> ); <ide> } <ide> <ide> // default value <ide> { <ide> const cmd = <del> `"${process.execPath}" -e "console.log('a'.repeat(200 * 1024 - 1))"`; <add> `"${process.execPath}" -e "console.log('a'.repeat(1024 * 1024 - 1))"`; <ide> <ide> cp.exec(cmd, common.mustCall((err, stdout, stderr) => { <ide> assert.ifError(err); <del> assert.strictEqual(stdout.trim(), 'a'.repeat(200 * 1024 - 1)); <add> assert.strictEqual(stdout.trim(), 'a'.repeat(1024 * 1024 - 1)); <ide> assert.strictEqual(stderr, ''); <ide> })); <ide> } <ide><path>test/parallel/test-child-process-execfile-maxbuf.js <ide> function checkFactory(streamName) { <ide> { <ide> execFile( <ide> process.execPath, <del> ['-e', 'console.log("a".repeat(200 * 1024))'], <add> ['-e', 'console.log("a".repeat(1024 * 1024))'], <ide> checkFactory('stdout') <ide> ); <ide> } <ide> function checkFactory(streamName) { <ide> { <ide> execFile( <ide> process.execPath, <del> ['-e', 'console.log("a".repeat(200 * 1024 - 1))'], <add> ['-e', 'console.log("a".repeat(1024 * 1024 - 1))'], <ide> common.mustCall((err, stdout, stderr) => { <ide> assert.ifError(err); <del> assert.strictEqual(stdout.trim(), 'a'.repeat(200 * 1024 - 1)); <add> assert.strictEqual(stdout.trim(), 'a'.repeat(1024 * 1024 - 1)); <ide> assert.strictEqual(stderr, ''); <ide> }) <ide> ); <ide><path>test/parallel/test-child-process-execfilesync-maxBuffer.js <ide> const args = [ <ide> assert.deepStrictEqual(ret, msgOutBuf); <ide> } <ide> <del>// Default maxBuffer size is 200 * 1024. <add>// Default maxBuffer size is 1024 * 1024. <ide> { <ide> assert.throws(() => { <ide> execFileSync( <ide> process.execPath, <del> ['-e', "console.log('a'.repeat(200 * 1024))"] <add> ['-e', "console.log('a'.repeat(1024 * 1024))"] <ide> ); <ide> }, (e) => { <ide> assert.ok(e, 'maxBuffer should error'); <ide><path>test/parallel/test-child-process-execfilesync-maxbuf.js <ide> const args = [ <ide> assert.deepStrictEqual(ret, msgOutBuf); <ide> } <ide> <del>// maxBuffer size is 200 * 1024 at default. <add>// maxBuffer size is 1024 * 1024 at default. <ide> { <ide> assert.throws( <ide> () => { <ide> execFileSync( <ide> process.execPath, <del> ['-e', "console.log('a'.repeat(200 * 1024))"], <add> ['-e', "console.log('a'.repeat(1024 * 1024))"], <ide> { encoding: 'utf-8' } <ide> ); <ide> }, (e) => { <ide><path>test/parallel/test-child-process-execsync-maxbuf.js <ide> const args = [ <ide> assert.deepStrictEqual(ret, msgOutBuf); <ide> } <ide> <del>// Default maxBuffer size is 200 * 1024. <add>// Default maxBuffer size is 1024 * 1024. <ide> { <ide> assert.throws(() => { <del> execSync(`"${process.execPath}" -e "console.log('a'.repeat(200 * 1024))"`); <add> execSync( <add> `"${process.execPath}" -e "console.log('a'.repeat(1024 * 1024))"` <add> ); <ide> }, (e) => { <ide> assert.ok(e, 'maxBuffer should error'); <ide> assert.strictEqual(e.errno, 'ENOBUFS'); <ide> return true; <ide> }); <ide> } <ide> <del>// Default maxBuffer size is 200 * 1024. <add>// Default maxBuffer size is 1024 * 1024. <ide> { <ide> const ret = execSync( <del> `"${process.execPath}" -e "console.log('a'.repeat(200 * 1024 - 1))"` <add> `"${process.execPath}" -e "console.log('a'.repeat(1024 * 1024 - 1))"` <ide> ); <ide> <del> assert.deepStrictEqual(ret.toString().trim(), 'a'.repeat(200 * 1024 - 1)); <add> assert.deepStrictEqual( <add> ret.toString().trim(), <add> 'a'.repeat(1024 * 1024 - 1) <add> ); <ide> } <ide><path>test/parallel/test-child-process-spawnsync-maxbuf.js <ide> const args = [ <ide> assert.deepStrictEqual(ret.stdout, msgOutBuf); <ide> } <ide> <del>// Default maxBuffer size is 200 * 1024. <add>// Default maxBuffer size is 1024 * 1024. <ide> { <del> const args = ['-e', "console.log('a'.repeat(200 * 1024))"]; <add> const args = ['-e', "console.log('a'.repeat(1024 * 1024))"]; <ide> const ret = spawnSync(process.execPath, args); <ide> <ide> assert.ok(ret.error, 'maxBuffer should error'); <ide> assert.strictEqual(ret.error.errno, 'ENOBUFS'); <ide> } <ide> <del>// Default maxBuffer size is 200 * 1024. <add>// Default maxBuffer size is 1024 * 1024. <ide> { <del> const args = ['-e', "console.log('a'.repeat(200 * 1024 - 1))"]; <add> const args = ['-e', "console.log('a'.repeat(1024 * 1024 - 1))"]; <ide> const ret = spawnSync(process.execPath, args); <ide> <ide> assert.ifError(ret.error); <ide> assert.deepStrictEqual( <ide> ret.stdout.toString().trim(), <del> 'a'.repeat(200 * 1024 - 1) <add> 'a'.repeat(1024 * 1024 - 1) <ide> ); <ide> }
8
Mixed
Ruby
fix assignment for frozen value in hwia
584931d749bfdd8553740bdcc6e4fef2c18ec523
<ide><path>activesupport/CHANGELOG.md <add>* Duplicate frozen array when assigning it to a HashWithIndifferentAccess so <add> that it doesn't raise a `RuntimeError` when calling `map!` on it in `convert_value`. <add> <add> Fixes #18550. <add> <add> *Aditya Kapoor* <add> <ide> * Add missing time zone definitions for Russian Federation and sync them <ide> with `zone.tab` file from tzdata version 2014j (latest). <ide> <ide><path>activesupport/lib/active_support/hash_with_indifferent_access.rb <ide> def convert_value(value, options = {}) <ide> value.nested_under_indifferent_access <ide> end <ide> elsif value.is_a?(Array) <del> unless options[:for] == :assignment <add> if options[:for] != :assignment || value.frozen? <ide> value = value.dup <ide> end <ide> value.map! { |e| convert_value(e, options) } <ide><path>activesupport/test/hash_with_indifferent_access_test.rb <ide> def test_reverse_merge <ide> hash.reverse_merge! key: :new_value <ide> assert_equal :old_value, hash[:key] <ide> end <add> <add> def test_frozen_value <add> value = [1, 2, 3].freeze <add> hash = {}.with_indifferent_access <add> hash[:key] = value <add> assert_equal hash[:key], value <add> end <ide> end <ide>\ No newline at end of file
3
Ruby
Ruby
freeze rails when required
9b82fa159a4d1f4f1e4b2932f43d76d9fc74da21
<ide><path>railties/lib/generator/actions.rb <ide> def rake(command, options={}) <ide> # capify! <ide> # <ide> def capify! <del> log :capify <add> log :capify, "" <ide> in_root { run('capify .', false) } <ide> end <ide> <ide> def capify! <ide> # freeze! <ide> # <ide> def freeze!(args = {}) <del> log :freeze <add> log :vendor, "rails" <ide> in_root { run('rake rails:freeze:edge', false) } <ide> end <ide> <ide><path>railties/lib/generator/generators/app.rb <ide> class App < Base <ide> class_option :database, :type => :string, :aliases => "-d", :default => DEFAULT_DATABASE, <ide> :desc => "Preconfigure for selected database (options: #{DATABASES.join('/')})" <ide> <del> # TODO Make use of this option <ide> class_option :freeze, :type => :boolean, :aliases => "-f", :default => false, <ide> :desc => "Freeze Rails in vendor/rails from the gems" <ide> <ide> def create_vendor_files <ide> empty_directory "vendor/plugins" <ide> end <ide> <add> def freeze? <add> freeze! if options[:freeze] <add> end <add> <ide> protected <ide> <ide> def app_name
2
Javascript
Javascript
remove additional parameters of easings"
d6e99d9b5edd10170af913ae5fb7c71e2e802475
<ide><path>src/effects/Tween.js <ide> Tween.prototype = { <ide> Tween.propHooks._default.get( this ); <ide> }, <ide> run: function( percent ) { <del> var hooks = Tween.propHooks[ this.prop ]; <add> var eased, <add> hooks = Tween.propHooks[ this.prop ]; <ide> <del> this.pos = this.options.duration ? <del> jQuery.easing[ this.easing ]( percent ) : <del> percent; <del> this.now = ( this.end - this.start ) * this.pos + this.start; <add> if ( this.options.duration ) { <add> this.pos = eased = jQuery.easing[ this.easing ]( <add> percent, this.options.duration * percent, 0, 1, this.options.duration <add> ); <add> } else { <add> this.pos = eased = percent; <add> } <add> this.now = ( this.end - this.start ) * eased + this.start; <ide> <ide> if ( this.options.step ) { <ide> this.options.step.call( this.elem, this.now, this ); <ide><path>test/unit/tween.js <ide> QUnit.test( "jQuery.Tween - Plain Object", function( assert ) { <ide> <ide> assert.equal( tween.now, 90, "Calculated tween" ); <ide> <del> assert.ok( easingSpy.calledWith( 0.1 ), "...using jQuery.easing.linear" ); <add> assert.ok( easingSpy.calledWith( 0.1, 0.1 * testOptions.duration, 0, 1, testOptions.duration ), <add> "...using jQuery.easing.linear with back-compat arguments" ); <ide> assert.equal( testObject.test, 90, "Set value" ); <ide> <ide> tween.run( 1 ); <ide> QUnit.test( "jQuery.Tween - Element", function( assert ) { <ide> eased = 100 - ( jQuery.easing.swing( 0.1 ) * 100 ); <ide> assert.equal( tween.now, eased, "Calculated tween" ); <ide> <del> assert.ok( easingSpy.calledWith( 0.1 ), "...using jQuery.easing.linear" ); <add> assert.ok( <add> easingSpy.calledWith( 0.1, 0.1 * testOptions.duration, 0, 1, testOptions.duration ), <add> "...using jQuery.easing.linear with back-compat arguments" <add> ); <ide> assert.equal( <ide> parseFloat( testElement.style.height ).toFixed( 2 ), <ide> eased.toFixed( 2 ), "Set value"
2
Javascript
Javascript
fix typo in alert.js
beca25083a3a57a9e5d68577cbcb9e63521b1284
<ide><path>Libraries/Alert/Alert.js <ide> class Alert { <ide> ): void { <ide> if (Platform.OS === 'ios') { <ide> if (typeof type !== 'undefined') { <del> console.warn('Alert.alert() with a 4th "type" parameter is deprecated and will be removed. Use AlertIOS.prompt() instead.'); <add> console.warn('Alert.alert() with a 5th "type" parameter is deprecated and will be removed. Use AlertIOS.prompt() instead.'); <ide> AlertIOS.alert(title, message, buttons, type); <ide> return; <ide> }
1
Ruby
Ruby
fix variable name
d9108abcad66412f9e8604479cdcc7795a3262b1
<ide><path>actionpack/lib/action_dispatch/routing/route_set.rb <ide> class << self <ide> def url_options; {}; end <ide> end <ide> <del> route_methods = routes.named_routes.url_helpers_module <add> url_helpers = routes.named_routes.url_helpers_module <ide> <ide> # Make named_routes available in the module singleton <ide> # as well, so one can do: <ide> # Rails.application.routes.url_helpers.posts_path <del> extend route_methods <add> extend url_helpers <ide> <ide> # Any class that includes this module will get all <ide> # named routes... <del> include route_methods <add> include url_helpers <ide> <ide> if include_path_helpers <ide> path_helpers = routes.named_routes.path_helpers_module
1
PHP
PHP
fix typos in limiter builders
dd0f61ca160c1e349517145d0887786f8a6eba3d
<ide><path>src/Illuminate/Redis/Limiters/ConcurrencyLimiterBuilder.php <ide> public function block($timeout) <ide> } <ide> <ide> /** <del> * Execute the given callback if a lock is obtained, otherise call the failure callback. <add> * Execute the given callback if a lock is obtained, otherwise call the failure callback. <ide> * <ide> * @param callable $callback <ide> * @param callable|null $failure <ide><path>src/Illuminate/Redis/Limiters/DurationLimiterBuilder.php <ide> public function block($timeout) <ide> } <ide> <ide> /** <del> * Execute the given callback if a lock is obtained, otherise call the failure callback. <add> * Execute the given callback if a lock is obtained, otherwise call the failure callback. <ide> * <ide> * @param callable $callback <ide> * @param callable|null $failure
2
Java
Java
delay operator with reactive pull backpressure
0a229e42bd8ee5aee14f56869e121fe30cdd1d3f
<ide><path>src/main/java/rx/Observable.java <ide> public final Observable<T> defaultIfEmpty(T defaultValue) { <ide> public final <U, V> Observable<T> delay( <ide> Func0<? extends Observable<U>> subscriptionDelay, <ide> Func1<? super T, ? extends Observable<V>> itemDelay) { <del> return create(new OnSubscribeDelayWithSelector<T, U, V>(this, subscriptionDelay, itemDelay)); <add> return delaySubscription(subscriptionDelay).lift(new OperatorDelayWithSelector<T, V>(this, itemDelay)); <ide> } <ide> <ide> /** <ide> public final <U, V> Observable<T> delay( <ide> * @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.delay.aspx">MSDN: Observable.Delay</a> <ide> */ <ide> public final <U> Observable<T> delay(Func1<? super T, ? extends Observable<U>> itemDelay) { <del> return create(new OnSubscribeDelayWithSelector<T, U, U>(this, itemDelay)); <add> return lift(new OperatorDelayWithSelector<T, U>(this, itemDelay)); <ide> } <ide> <ide> /** <ide> public final Observable<T> delay(long delay, TimeUnit unit) { <ide> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229280.aspx">MSDN: Observable.Delay</a> <ide> */ <ide> public final Observable<T> delay(long delay, TimeUnit unit, Scheduler scheduler) { <del> return create(new OnSubscribeDelay<T>(this, delay, unit, scheduler)); <add> return lift(new OperatorDelay<T>(this, delay, unit, scheduler)); <ide> } <ide> <ide> /** <ide> public final Observable<T> delaySubscription(long delay, TimeUnit unit) { <ide> public final Observable<T> delaySubscription(long delay, TimeUnit unit, Scheduler scheduler) { <ide> return create(new OnSubscribeDelaySubscription<T>(this, delay, unit, scheduler)); <ide> } <add> <add> /** <add> * Returns an Observable that delays the subscription to the source Observable by a given amount of time. <add> * <p> <add> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/delaySubscription.png" alt=""> <add> * <dl> <add> * <dt><b>Scheduler:</b></dt> <add> * <dd>This version of {@code delay} operates by default on the {@code compuation} {@link Scheduler}.</dd> <add> * </dl> <add> * <add> * @param delay <add> * the time to delay the subscription <add> * @param unit <add> * the time unit of {@code delay} <add> * @return an Observable that delays the subscription to the source Observable by the given amount <add> * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Observable-Utility-Operators#delaysubscription">RxJava wiki: delaySubscription</a> <add> */ <add> public final <U> Observable<T> delaySubscription(Func0<? extends Observable<U>> subscriptionDelay) { <add> return create(new OnSubscribeDelaySubscriptionWithSelector<T, U>(this, subscriptionDelay)); <add> } <ide> <ide> /** <ide> * Returns an Observable that reverses the effect of {@link #materialize materialize} by transforming the <ide><path>src/main/java/rx/internal/operators/OnSubscribeDelay.java <del>/** <del> * Copyright 2014 Netflix, Inc. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del>package rx.internal.operators; <del> <del>import java.util.concurrent.TimeUnit; <del> <del>import rx.Observable; <del>import rx.Observable.OnSubscribe; <del>import rx.Scheduler; <del>import rx.Scheduler.Worker; <del>import rx.Subscriber; <del>import rx.functions.Action0; <del>import rx.functions.Func1; <del> <del>/** <del> * Delays the emission of onNext events by a given amount of time. <del> * @param <T> the value type <del> */ <del>public final class OnSubscribeDelay<T> implements OnSubscribe<T> { <del> <del> final Observable<? extends T> source; <del> final long delay; <del> final TimeUnit unit; <del> final Scheduler scheduler; <del> <del> public OnSubscribeDelay(Observable<? extends T> source, long delay, TimeUnit unit, Scheduler scheduler) { <del> this.source = source; <del> this.delay = delay; <del> this.unit = unit; <del> this.scheduler = scheduler; <del> } <del> <del> @Override <del> public void call(Subscriber<? super T> child) { <del> final Worker worker = scheduler.createWorker(); <del> child.add(worker); <del> <del> Observable.concat(source.map(new Func1<T, Observable<T>>() { <del> @Override <del> public Observable<T> call(T x) { <del> Emitter<T> e = new Emitter<T>(x); <del> worker.schedule(e, delay, unit); <del> return Observable.create(e); <del> } <del> })).unsafeSubscribe(child); <del> } <del> <del> /** <del> * Emits a value once the call() is invoked. <del> * Only one subscriber can wait for the emission. <del> * @param <T> the value type <del> */ <del> public static final class Emitter<T> implements OnSubscribe<T>, Action0 { <del> final T value; <del> <del> final Object guard; <del> /** Guarded by guard. */ <del> Subscriber<? super T> child; <del> /** Guarded by guard. */ <del> boolean done; <del> <del> public Emitter(T value) { <del> this.value = value; <del> this.guard = new Object(); <del> } <del> <del> @Override <del> public void call(Subscriber<? super T> s) { <del> synchronized (guard) { <del> if (!done) { <del> child = s; <del> return; <del> } <del> } <del> s.onNext(value); <del> s.onCompleted(); <del> } <del> <del> @Override <del> public void call() { <del> Subscriber<? super T> s; <del> synchronized (guard) { <del> done = true; <del> s = child; <del> child = null; <del> } <del> if (s != null) { <del> s.onNext(value); <del> s.onCompleted(); <del> } <del> } <del> } <del>} <ide><path>src/main/java/rx/internal/operators/OnSubscribeDelaySubscriptionWithSelector.java <add>/** <add> * Copyright 2014 Netflix, Inc. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not <add> * use this file except in compliance with the License. You may obtain a copy of <add> * the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT <add> * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the <add> * License for the specific language governing permissions and limitations under <add> * the License. <add> */ <add>package rx.internal.operators; <add> <add>import rx.Observable; <add>import rx.Observable.OnSubscribe; <add>import rx.Subscriber; <add>import rx.functions.Func0; <add> <add>/** <add> * Delays the subscription until the Observable<U> emits an event. <add> * <add> * @param <T> <add> * the value type <add> */ <add>public final class OnSubscribeDelaySubscriptionWithSelector<T, U> implements OnSubscribe<T> { <add> final Observable<? extends T> source; <add> final Func0<? extends Observable<U>> subscriptionDelay; <add> <add> public OnSubscribeDelaySubscriptionWithSelector(Observable<? extends T> source, Func0<? extends Observable<U>> subscriptionDelay) { <add> this.source = source; <add> this.subscriptionDelay = subscriptionDelay; <add> } <add> <add> @Override <add> public void call(final Subscriber<? super T> child) { <add> try { <add> subscriptionDelay.call().take(1).unsafeSubscribe(new Subscriber<U>() { <add> <add> @Override <add> public void onCompleted() { <add> // subscribe to actual source <add> source.unsafeSubscribe(child); <add> } <add> <add> @Override <add> public void onError(Throwable e) { <add> child.onError(e); <add> } <add> <add> @Override <add> public void onNext(U t) { <add> // ignore as we'll complete immediately because of take(1) <add> } <add> <add> }); <add> } catch (Throwable e) { <add> child.onError(e); <add> } <add> } <add> <add>} <ide><path>src/main/java/rx/internal/operators/OnSubscribeDelayWithSelector.java <del>/** <del> * Copyright 2014 Netflix, Inc. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); you may not <del> * use this file except in compliance with the License. You may obtain a copy of <del> * the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT <del> * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the <del> * License for the specific language governing permissions and limitations under <del> * the License. <del> */ <del>package rx.internal.operators; <del> <del>import rx.Observable; <del>import rx.Observable.OnSubscribe; <del>import rx.Subscriber; <del>import rx.functions.Func0; <del>import rx.functions.Func1; <del>import rx.internal.operators.OnSubscribeDelay.Emitter; <del>import rx.observers.SerializedSubscriber; <del>import rx.subscriptions.CompositeSubscription; <del> <del>/** <del> * Delay the subscription and emission of the source items by a per-item observable that fires its first element. <del> * @param <T> the item type <del> * @param <U> the value type of the subscription-delaying observable <del> * @param <V> the value type of the item-delaying observable <del> */ <del>public final class OnSubscribeDelayWithSelector<T, U, V> implements OnSubscribe<T> { <del> final Observable<? extends T> source; <del> final Func0<? extends Observable<U>> subscriptionDelay; <del> final Func1<? super T, ? extends Observable<V>> itemDelay; <del> <del> public OnSubscribeDelayWithSelector(Observable<? extends T> source, Func1<? super T, ? extends Observable<V>> itemDelay) { <del> this.source = source; <del> this.subscriptionDelay = new Func0<Observable<U>>() { <del> @Override <del> public Observable<U> call() { <del> return Observable.just(null); <del> } <del> }; <del> this.itemDelay = itemDelay; <del> } <del> <del> public OnSubscribeDelayWithSelector(Observable<? extends T> source, Func0<? extends Observable<U>> subscriptionDelay, Func1<? super T, ? extends Observable<V>> itemDelay) { <del> this.source = source; <del> this.subscriptionDelay = subscriptionDelay; <del> this.itemDelay = itemDelay; <del> } <del> <del> @Override <del> public void call(Subscriber<? super T> child) { <del> final SerializedSubscriber<T> s = new SerializedSubscriber<T>(child); <del> final CompositeSubscription csub = new CompositeSubscription(); <del> child.add(csub); <del> <del> Observable<U> osub; <del> try { <del> osub = subscriptionDelay.call(); <del> } catch (Throwable e) { <del> s.onError(e); <del> return; <del> } <del> <del> Observable<Observable<T>> seqs = source.map(new Func1<T, Observable<T>>() { <del> @Override <del> public Observable<T> call(final T x) { <del> final Emitter<T> e = new Emitter<T>(x); <del> Observable<V> itemObs = itemDelay.call(x); <del> <del> Subscriber<V> itemSub = new Subscriber<V>() { <del> boolean once = true; <del> @Override <del> public void onNext(V t) { <del> emit(); <del> } <del> <del> @Override <del> public void onError(Throwable e) { <del> s.onError(e); <del> s.unsubscribe(); <del> } <del> <del> @Override <del> public void onCompleted() { <del> emit(); <del> } <del> void emit() { <del> if (once) { <del> once = false; <del> e.call(); <del> csub.remove(this); <del> } <del> } <del> }; <del> csub.add(itemSub); <del> itemObs.unsafeSubscribe(itemSub); <del> <del> return Observable.create(e); <del> } <del> }); <del> final Observable<T> delayed = Observable.merge(seqs); <del> <del> Subscriber<U> osubSub = new Subscriber<U>(child) { <del> boolean subscribed; <del> @Override <del> public void onNext(U ignored) { <del> onCompleted(); <del> } <del> <del> @Override <del> public void onError(Throwable e) { <del> if (!subscribed) { <del> s.onError(e); <del> unsubscribe(); <del> } <del> } <del> <del> @Override <del> public void onCompleted() { <del> if (!subscribed) { <del> subscribed = true; <del> delayed.unsafeSubscribe(s); <del> } <del> } <del> }; <del> <del> osub.unsafeSubscribe(osubSub); <del> } <del>} <ide><path>src/main/java/rx/internal/operators/OperatorDelay.java <add>/** <add> * Copyright 2014 Netflix, Inc. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add>package rx.internal.operators; <add> <add>import java.util.concurrent.TimeUnit; <add> <add>import rx.Observable; <add>import rx.Observable.Operator; <add>import rx.Scheduler; <add>import rx.Scheduler.Worker; <add>import rx.Subscriber; <add>import rx.functions.Action0; <add> <add>/** <add> * Delays the emission of onNext events by a given amount of time. <add> * <add> * @param <T> <add> * the value type <add> */ <add>public final class OperatorDelay<T> implements Operator<T, T> { <add> <add> final Observable<? extends T> source; <add> final long delay; <add> final TimeUnit unit; <add> final Scheduler scheduler; <add> <add> public OperatorDelay(Observable<? extends T> source, long delay, TimeUnit unit, Scheduler scheduler) { <add> this.source = source; <add> this.delay = delay; <add> this.unit = unit; <add> this.scheduler = scheduler; <add> } <add> <add> @Override <add> public Subscriber<? super T> call(final Subscriber<? super T> child) { <add> final Worker worker = scheduler.createWorker(); <add> child.add(worker); <add> return new Subscriber<T>(child) { <add> <add> @Override <add> public void onCompleted() { <add> worker.schedule(new Action0() { <add> <add> @Override <add> public void call() { <add> child.onCompleted(); <add> } <add> <add> }, delay, unit); <add> } <add> <add> @Override <add> public void onError(Throwable e) { <add> child.onError(e); <add> } <add> <add> @Override <add> public void onNext(final T t) { <add> worker.schedule(new Action0() { <add> <add> @Override <add> public void call() { <add> child.onNext(t); <add> } <add> <add> }, delay, unit); <add> } <add> <add> }; <add> } <add> <add>} <ide><path>src/main/java/rx/internal/operators/OperatorDelayWithSelector.java <add>/** <add> * Copyright 2014 Netflix, Inc. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not <add> * use this file except in compliance with the License. You may obtain a copy of <add> * the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT <add> * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the <add> * License for the specific language governing permissions and limitations under <add> * the License. <add> */ <add>package rx.internal.operators; <add> <add>import rx.Observable; <add>import rx.Observable.Operator; <add>import rx.Subscriber; <add>import rx.functions.Func1; <add>import rx.observers.SerializedSubscriber; <add>import rx.subjects.PublishSubject; <add> <add>/** <add> * Delay the subscription and emission of the source items by a per-item observable that fires its first element. <add> * <add> * @param <T> <add> * the item type <add> * @param <V> <add> * the value type of the item-delaying observable <add> */ <add>public final class OperatorDelayWithSelector<T, V> implements Operator<T, T> { <add> final Observable<? extends T> source; <add> final Func1<? super T, ? extends Observable<V>> itemDelay; <add> <add> public OperatorDelayWithSelector(Observable<? extends T> source, Func1<? super T, ? extends Observable<V>> itemDelay) { <add> this.source = source; <add> this.itemDelay = itemDelay; <add> } <add> <add> @Override <add> public Subscriber<? super T> call(final Subscriber<? super T> _child) { <add> final SerializedSubscriber<T> child = new SerializedSubscriber<T>(_child); <add> final PublishSubject<Observable<T>> delayedEmissions = PublishSubject.create(); <add> <add> _child.add(Observable.merge(delayedEmissions).unsafeSubscribe(new Subscriber<T>() { <add> <add> @Override <add> public void onCompleted() { <add> child.onCompleted(); <add> } <add> <add> @Override <add> public void onError(Throwable e) { <add> child.onError(e); <add> } <add> <add> @Override <add> public void onNext(T t) { <add> child.onNext(t); <add> } <add> <add> })); <add> <add> return new Subscriber<T>(_child) { <add> <add> @Override <add> public void onCompleted() { <add> delayedEmissions.onCompleted(); <add> } <add> <add> @Override <add> public void onError(Throwable e) { <add> child.onError(e); <add> } <add> <add> @Override <add> public void onNext(final T t) { <add> try { <add> delayedEmissions.onNext(itemDelay.call(t).take(1).defaultIfEmpty(null).map(new Func1<V, T>() { <add> <add> @Override <add> public T call(V v) { <add> return t; <add> } <add> <add> })); <add> } catch (Throwable e) { <add> onError(e); <add> } <add> } <add> <add> }; <add> } <add>} <add><path>src/test/java/rx/internal/operators/OperatorDelayTest.java <del><path>src/test/java/rx/internal/operators/OnSubscribeDelayTest.java <ide> */ <ide> package rx.internal.operators; <ide> <add>import static org.junit.Assert.assertEquals; <ide> import static org.mockito.Matchers.any; <ide> import static org.mockito.Matchers.anyInt; <ide> import static org.mockito.Matchers.anyLong; <ide> import static org.mockito.MockitoAnnotations.initMocks; <ide> <ide> import java.util.ArrayList; <add>import java.util.Arrays; <ide> import java.util.List; <ide> import java.util.concurrent.TimeUnit; <ide> <ide> import org.mockito.InOrder; <ide> import org.mockito.Mock; <ide> <add>import rx.Notification; <ide> import rx.Observable; <ide> import rx.Observer; <ide> import rx.Subscription; <ide> import rx.exceptions.TestException; <add>import rx.functions.Action1; <ide> import rx.functions.Func0; <ide> import rx.functions.Func1; <add>import rx.internal.util.RxRingBuffer; <add>import rx.observers.TestObserver; <add>import rx.observers.TestSubscriber; <add>import rx.schedulers.Schedulers; <ide> import rx.schedulers.TestScheduler; <ide> import rx.subjects.PublishSubject; <ide> <del>public class OnSubscribeDelayTest { <add>public class OperatorDelayTest { <ide> @Mock <ide> private Observer<Long> observer; <ide> @Mock <ide> public Observable<Integer> call(Integer t1) { <ide> verify(o, never()).onError(any(Throwable.class)); <ide> verify(o, never()).onCompleted(); <ide> } <del> <add> <ide> @Test <ide> public void testDelayWithObservableAsTimed() { <ide> Observable<Long> source = Observable.interval(1L, TimeUnit.SECONDS, scheduler).take(3); <del> <add> <ide> final Observable<Long> delayer = Observable.timer(500L, TimeUnit.MILLISECONDS, scheduler); <del> <add> <ide> Func1<Long, Observable<Long>> delayFunc = new Func1<Long, Observable<Long>>() { <ide> @Override <ide> public Observable<Long> call(Long t1) { <ide> return delayer; <ide> } <ide> }; <del> <add> <ide> Observable<Long> delayed = source.delay(delayFunc); <ide> delayed.subscribe(observer); <ide> <ide> public Observable<Long> call(Long t1) { <ide> verify(observer, times(1)).onCompleted(); <ide> verify(observer, never()).onError(any(Throwable.class)); <ide> } <del> <add> <ide> @Test <ide> public void testDelayWithObservableReorder() { <ide> int n = 3; <ide> <ide> PublishSubject<Integer> source = PublishSubject.create(); <ide> final List<PublishSubject<Integer>> subjects = new ArrayList<PublishSubject<Integer>>(); <ide> for (int i = 0; i < n; i++) { <del> subjects.add(PublishSubject.<Integer>create()); <add> subjects.add(PublishSubject.<Integer> create()); <ide> } <del> <add> <ide> Observable<Integer> result = source.delay(new Func1<Integer, Observable<Integer>>() { <ide> <ide> @Override <ide> public Observable<Integer> call(Integer t1) { <ide> return subjects.get(t1); <ide> } <ide> }); <del> <add> <ide> @SuppressWarnings("unchecked") <ide> Observer<Integer> o = mock(Observer.class); <ide> InOrder inOrder = inOrder(o); <del> <add> <ide> result.subscribe(o); <del> <add> <ide> for (int i = 0; i < n; i++) { <ide> source.onNext(i); <ide> } <ide> source.onCompleted(); <del> <add> <ide> inOrder.verify(o, never()).onNext(anyInt()); <ide> inOrder.verify(o, never()).onCompleted(); <del> <add> <ide> for (int i = n - 1; i >= 0; i--) { <ide> subjects.get(i).onCompleted(); <ide> inOrder.verify(o).onNext(i); <ide> } <del> <add> <ide> inOrder.verify(o).onCompleted(); <del> <add> <ide> verify(o, never()).onError(any(Throwable.class)); <ide> } <add> <add> @Test <add> public void testDelayEmitsEverything() { <add> Observable<Integer> source = Observable.range(1, 5); <add> Observable<Integer> delayed = source.delay(500L, TimeUnit.MILLISECONDS, scheduler); <add> delayed = delayed.doOnEach(new Action1<Notification<? super Integer>>() { <add> <add> @Override <add> public void call(Notification<? super Integer> t1) { <add> System.out.println(t1); <add> } <add> <add> }); <add> TestObserver<Integer> observer = new TestObserver<Integer>(); <add> delayed.subscribe(observer); <add> // all will be delivered after 500ms since range does not delay between them <add> scheduler.advanceTimeBy(500L, TimeUnit.MILLISECONDS); <add> observer.assertReceivedOnNext(Arrays.asList(1, 2, 3, 4, 5)); <add> } <add> <add> @Test <add> public void testBackpressureWithTimedDelay() { <add> TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); <add> Observable.range(1, RxRingBuffer.SIZE * 2) <add> .delay(100, TimeUnit.MILLISECONDS) <add> .observeOn(Schedulers.computation()) <add> .map(new Func1<Integer, Integer>() { <add> <add> int c = 0; <add> <add> @Override <add> public Integer call(Integer t) { <add> if (c++ <= 0) { <add> try { <add> Thread.sleep(500); <add> } catch (InterruptedException e) { <add> } <add> } <add> return t; <add> } <add> <add> }).subscribe(ts); <add> <add> ts.awaitTerminalEvent(); <add> ts.assertNoErrors(); <add> assertEquals(RxRingBuffer.SIZE * 2, ts.getOnNextEvents().size()); <add> } <add> <add> @Test <add> public void testBackpressureWithSubscriptionTimedDelay() { <add> TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); <add> Observable.range(1, RxRingBuffer.SIZE * 2) <add> .delaySubscription(100, TimeUnit.MILLISECONDS) <add> .delay(100, TimeUnit.MILLISECONDS) <add> .observeOn(Schedulers.computation()) <add> .map(new Func1<Integer, Integer>() { <add> <add> int c = 0; <add> <add> @Override <add> public Integer call(Integer t) { <add> if (c++ <= 0) { <add> try { <add> Thread.sleep(500); <add> } catch (InterruptedException e) { <add> } <add> } <add> return t; <add> } <add> <add> }).subscribe(ts); <add> <add> ts.awaitTerminalEvent(); <add> ts.assertNoErrors(); <add> assertEquals(RxRingBuffer.SIZE * 2, ts.getOnNextEvents().size()); <add> } <add> <add> @Test <add> public void testBackpressureWithSelectorDelay() { <add> TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); <add> Observable.range(1, RxRingBuffer.SIZE * 2) <add> .delay(new Func1<Integer, Observable<Long>>() { <add> <add> @Override <add> public Observable<Long> call(Integer i) { <add> return Observable.timer(100, TimeUnit.MILLISECONDS); <add> } <add> <add> }) <add> .observeOn(Schedulers.computation()) <add> .map(new Func1<Integer, Integer>() { <add> <add> int c = 0; <add> <add> @Override <add> public Integer call(Integer t) { <add> if (c++ <= 0) { <add> try { <add> Thread.sleep(500); <add> } catch (InterruptedException e) { <add> } <add> } <add> return t; <add> } <add> <add> }).subscribe(ts); <add> <add> ts.awaitTerminalEvent(); <add> ts.assertNoErrors(); <add> assertEquals(RxRingBuffer.SIZE * 2, ts.getOnNextEvents().size()); <add> } <add> <add> @Test <add> public void testBackpressureWithSelectorDelayAndSubscriptionDelay() { <add> TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); <add> Observable.range(1, RxRingBuffer.SIZE * 2) <add> .delay(new Func0<Observable<Long>>() { <add> <add> @Override <add> public Observable<Long> call() { <add> return Observable.timer(500, TimeUnit.MILLISECONDS); <add> } <add> }, new Func1<Integer, Observable<Long>>() { <add> <add> @Override <add> public Observable<Long> call(Integer i) { <add> return Observable.timer(100, TimeUnit.MILLISECONDS); <add> } <add> <add> }) <add> .observeOn(Schedulers.computation()) <add> .map(new Func1<Integer, Integer>() { <add> <add> int c = 0; <add> <add> @Override <add> public Integer call(Integer t) { <add> if (c++ <= 0) { <add> try { <add> Thread.sleep(500); <add> } catch (InterruptedException e) { <add> } <add> } <add> return t; <add> } <add> <add> }).subscribe(ts); <add> <add> ts.awaitTerminalEvent(); <add> ts.assertNoErrors(); <add> assertEquals(RxRingBuffer.SIZE * 2, ts.getOnNextEvents().size()); <add> } <ide> }
7
Javascript
Javascript
fix the way of removeing a mesh
011770a86960e456bd64891f0e55149585181997
<ide><path>src/renderers/WebGLRenderer.js <ide> THREE.WebGLRenderer = function ( parameters ) { <ide> <ide> function removeInstancesWebglObjects( objlist, object ) { <ide> <del> delete objlist[object]; <add> delete objlist[object.id]; <ide> <ide> }; <ide>
1
Python
Python
add celeryd_force_hijack_root_logger option
6b8377d5b53407f02bab1d164b62d7d6aad704aa
<ide><path>celery/app/defaults.py <ide> def to_python(self, value): <ide> "CONCURRENCY": Option(0, type="int"), <ide> "ETA_SCHEDULER": Option("celery.utils.timer2.Timer"), <ide> "ETA_SCHEDULER_PRECISION": Option(1.0, type="float"), <add> "FORCE_HIJACK_ROOT_LOGGER": Option(False, type="bool"), <ide> "CONSUMER": Option("celery.worker.consumer.Consumer"), <ide> "LOG_FORMAT": Option(DEFAULT_PROCESS_LOG_FMT), <ide> "LOG_COLOR": Option(type="bool"), <ide> def to_python(self, value): <ide> "LOG_FILE": Option(), <ide> "LOG_FORMAT": Option(DEFAULT_LOG_FMT), <ide> }, <del> <ide> "EMAIL": { <ide> "HOST": Option("localhost"), <ide> "PORT": Option(25, type="int"), <ide><path>celery/log.py <ide> def setup_logging_subsystem(self, loglevel=None, logfile=None, <ide> colorize=colorize) <ide> if not receivers: <ide> root = logging.getLogger() <add> <add> if self.app.conf.CELERYD_FORCE_HIJACK_ROOT_LOGGER: <add> root.handlers = [] <add> <ide> mp = mputil.get_logger() <ide> for logger in (root, mp): <ide> self._setup_logger(logger, logfile, <ide> def setup_logger(self, loglevel=None, logfile=None, <ide> format = format or self.format <ide> colorize = self.app.either("CELERYD_LOG_COLOR", colorize) <ide> <del> if not root: <add> if not root or self.app.conf.CELERYD_FORCE_HIJACK_ROOT_LOGGER: <ide> return self._setup_logger(self.get_default_logger(loglevel, name), <ide> logfile, format, colorize, **kwargs) <ide> self.setup_logging_subsystem(loglevel, logfile,
2
Ruby
Ruby
reset the primary key for other tests
2d211c459d8274f13f7a0f84d48c3d61bff49aee
<ide><path>activerecord/test/cases/finder_test.rb <ide> def test_find_one_message_with_custom_primary_key <ide> rescue ActiveRecord::RecordNotFound => e <ide> assert_equal 'Couldn\'t find Toy with name=Hello World!', e.message <ide> end <add> ensure <add> Toy.reset_primary_key <ide> end <ide> <ide> def test_finder_with_offset_string
1
Ruby
Ruby
remove dependency on the filesystem
cc88ffed7a2e17ff53eb8796bc1fa2536ebca00d
<ide><path>activerecord/test/cases/migration/logger_test.rb <ide> module ActiveRecord <ide> class Migration <ide> class LoggerTest < ActiveRecord::TestCase <add> Migration = Struct.new(:version) do <add> def migrate direction <add> # do nothing <add> end <add> end <add> <ide> def test_migration_should_be_run_without_logger <ide> previous_logger = ActiveRecord::Base.logger <ide> ActiveRecord::Base.logger = nil <del> assert_nothing_raised do <del> ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid") <del> end <add> migrations = [Migration.new(1), Migration.new(2), Migration.new(3)] <add> ActiveRecord::Migrator.new(:up, migrations).migrate <ide> ensure <ide> ActiveRecord::Base.logger = previous_logger <ide> end
1
Ruby
Ruby
simulate target tag
bca9eb05d1c0b55176cc3659cadfe894467352fa
<ide><path>Library/Homebrew/dev-cmd/unbottled.rb <ide> def unbottled <ide> Utils::Bottles.tag <ide> end <ide> <add> Homebrew::SimulateSystem.os = @bottle_tag.system <add> Homebrew::SimulateSystem.arch = if Hardware::CPU::INTEL_ARCHS.include?(@bottle_tag.arch) <add> :intel <add> elsif Hardware::CPU::ARM_ARCHS.include?(@bottle_tag.arch) <add> :arm <add> else <add> raise "Unknown arch #{@bottle_tag.arch}." <add> end <add> <ide> all = args.eval_all? <ide> if args.total? <ide> if !all && !Homebrew::EnvConfig.eval_all? <ide> def unbottled <ide> end <ide> <ide> output_unbottled(formulae, deps_hash, noun, hash, args.named.present?) <add> ensure <add> Homebrew::SimulateSystem.clear <ide> end <ide> <ide> def formulae_all_installs_from_args(args, all) <ide><path>Library/Homebrew/hardware.rb <ide> module Hardware <ide> class CPU <ide> INTEL_32BIT_ARCHS = [:i386].freeze <ide> INTEL_64BIT_ARCHS = [:x86_64].freeze <add> INTEL_ARCHS = (INTEL_32BIT_ARCHS + INTEL_64BIT_ARCHS).freeze <ide> PPC_32BIT_ARCHS = [:ppc, :ppc32, :ppc7400, :ppc7450, :ppc970].freeze <ide> PPC_64BIT_ARCHS = [:ppc64, :ppc64le, :ppc970].freeze <add> PPC_ARCHS = (PPC_32BIT_ARCHS + PPC_64BIT_ARCHS).freeze <ide> ARM_64BIT_ARCHS = [:arm64, :aarch64].freeze <add> ARM_ARCHS = ARM_64BIT_ARCHS <ide> ALL_ARCHS = [ <del> *INTEL_32BIT_ARCHS, <del> *INTEL_64BIT_ARCHS, <del> *PPC_32BIT_ARCHS, <del> *PPC_64BIT_ARCHS, <del> *ARM_64BIT_ARCHS, <add> *INTEL_ARCHS, <add> *PPC_ARCHS, <add> *ARM_ARCHS, <ide> ].freeze <ide> <ide> INTEL_64BIT_OLDEST_CPU = :core2
2
Javascript
Javascript
use makeas in calendar too
93bcae3ebd2e84ef8a6bc83c5eab6edc985a9a4d
<ide><path>moment.js <ide> calendar : function () { <ide> // We want to compare the start of today, vs this. <ide> // Getting start-of-today depends on whether we're zone'd or not. <del> var sod = (this._isUTC ? moment().zone(this.zone()) : moment()).startOf('day'), <add> var sod = makeAs(moment(), this).startOf('day'), <ide> diff = this.diff(sod, 'days', true), <ide> format = diff < -6 ? 'sameElse' : <ide> diff < -1 ? 'lastWeek' :
1
Python
Python
use strerror attr as error message
6ee86a449049c5542a95aca33ef4e2514f17a8ef
<ide><path>libcloud/compute/drivers/vsphere.py <ide> def connect(self): <ide> except Exception: <ide> e = sys.exc_info()[1] <ide> message = e.message <add> if hasattr(e, 'strerror'): <add> message = e.strerror <ide> fault = getattr(e, 'fault', None) <ide> <ide> if fault == 'InvalidLoginFault': <ide> raise InvalidCredsError(message) <del> <ide> raise LibcloudError(value=message, driver=self.driver) <ide> <ide> atexit.register(self.disconnect)
1
Text
Text
buffer documentation improvements
f1dc5cd614b4eaa7a7f1466a317a06f543a58a71
<ide><path>doc/api/buffer.md <ide> <ide> <!-- source_link=lib/buffer.js --> <ide> <del>In Node.js, `Buffer` objects are used to represent binary data in the form <del>of a sequence of bytes. Many Node.js APIs, for example streams and file system <del>operations, support `Buffer`s, as interactions with the operating system or <del>other processes generally always happen in terms of binary data. <add>`Buffer` objects are used to represent a fixed-length sequence of bytes. Many <add>Node.js APIs support `Buffer`s. <ide> <del>The `Buffer` class is a subclass of the [`Uint8Array`][] class that is built <del>into the JavaScript language. A number of additional methods are supported <del>that cover additional use cases. Node.js APIs accept plain [`Uint8Array`][]s <del>wherever `Buffer`s are supported as well. <del> <del>Instances of `Buffer`, and instances of [`Uint8Array`][] in general, <del>are similar to arrays of integers from `0` to `255`, but correspond to <del>fixed-sized blocks of memory and cannot contain any other values. <del>The size of a `Buffer` is established when it is created and cannot be changed. <add>The `Buffer` class is a subclass of JavaScript's [`Uint8Array`][] class and <add>extends it with methods that cover additional use cases. Node.js APIs accept <add>plain [`Uint8Array`][]s wherever `Buffer`s are supported as well. <ide> <ide> The `Buffer` class is within the global scope, making it unlikely that one <ide> would need to ever use `require('buffer').Buffer`. <ide> changes: <ide> description: The `Buffer`s class now inherits from `Uint8Array`. <ide> --> <ide> <del>`Buffer` instances are also [`Uint8Array`][] instances, which is the language’s <del>built-in class for working with binary data. [`Uint8Array`][] in turn is a <del>subclass of [`TypedArray`][]. Therefore, all [`TypedArray`][] methods are also <del>available on `Buffer`s. However, there are subtle incompatibilities between <del>the `Buffer` API and the [`TypedArray`][] API. <add>`Buffer` instances are also JavaScript [`Uint8Array`][] and [`TypedArray`][] <add>instances. All [`TypedArray`][] methods are available on `Buffer`s. There are, <add>however, subtle incompatibilities between the `Buffer` API and the <add>[`TypedArray`][] API. <ide> <ide> In particular: <ide> <ide> In particular: <ide> * [`buf.toString()`][] is incompatible with its `TypedArray` equivalent. <ide> * A number of methods, e.g. [`buf.indexOf()`][], support additional arguments. <ide> <del>There are two ways to create new [`TypedArray`][] instances from a `Buffer`. <add>There are two ways to create new [`TypedArray`][] instances from a `Buffer`: <add> <add>* Passing a `Buffer` to a [`TypedArray`][] constructor will copy the `Buffer`s <add> contents, interpreted an array array of integers, and not as a byte sequence <add> of the target type. <add> <add>```js <add>const buf = Buffer.from([1, 2, 3, 4]); <add>const uint32array = new Uint32Array(buf); <add> <add>console.log(uint32array); <ide> <del>When passing a `Buffer` to a [`TypedArray`][] constructor, the `Buffer`’s <del>elements will be copied, interpreted as an array of integers, and not as a byte <del>array of the target type. For example, <del>`new Uint32Array(Buffer.from([1, 2, 3, 4]))` creates a 4-element <del>[`Uint32Array`][] with elements `[1, 2, 3, 4]`, rather than a <del>[`Uint32Array`][] with a single element `[0x1020304]` or `[0x4030201]`. <add>// Prints: Uint32Array(4) [ 1, 2, 3, 4 ] <add>``` <ide> <del>In order to create a [`TypedArray`][] that shares its memory with the `Buffer`, <del>the underlying [`ArrayBuffer`][] can be passed to the [`TypedArray`][] <del>constructor instead: <add>* Passing the `Buffer`s underlying [`ArrayBuffer`][] will create a <add> [`TypedArray`][] that shares its memory with the `Buffer`. <ide> <ide> ```js <ide> const buf = Buffer.from('hello', 'utf16le'); <ide> const uint16arr = new Uint16Array( <del> buf.buffer, buf.byteOffset, buf.length / Uint16Array.BYTES_PER_ELEMENT); <add> buf.buffer, <add> buf.byteOffset, <add> buf.length / Uint16Array.BYTES_PER_ELEMENT); <add> <add>console.log(uint16array); <add> <add>// Prints: Uint16Array(5) [ 104, 101, 108, 108, 111 ] <ide> ``` <ide> <del>It is also possible to create a new `Buffer` that shares the same allocated <add>It is possible to create a new `Buffer` that shares the same allocated <ide> memory as a [`TypedArray`][] instance by using the `TypedArray` object’s <ide> `.buffer` property in the same way. [`Buffer.from()`][`Buffer.from(arrayBuf)`] <ide> behaves like `new Uint8Array()` in this context. <ide> arr[1] = 4000; <ide> <ide> // Copies the contents of `arr`. <ide> const buf1 = Buffer.from(arr); <add> <ide> // Shares memory with `arr`. <ide> const buf2 = Buffer.from(arr.buffer); <ide> <ide> range is between `0x00` and `0xFF` (hex) or `0` and `255` (decimal). <ide> <ide> This operator is inherited from `Uint8Array`, so its behavior on out-of-bounds <ide> access is the same as `Uint8Array`. In other words, `buf[index]` returns <del>`undefined` when `index` is negative or `>= buf.length`, and <add>`undefined` when `index` is negative or greater or equal to `buf.length`, and <ide> `buf[index] = value` does not modify the buffer if `index` is negative or <ide> `>= buf.length`. <ide> <ide> console.log(buf.toString('utf8')); <ide> <ide> ### `buf.buffer` <ide> <del>* {ArrayBuffer} The underlying `ArrayBuffer` object based on <del> which this `Buffer` object is created. <add>* {ArrayBuffer} The underlying `ArrayBuffer` object based on which this `Buffer` <add> object is created. <ide> <ide> This `ArrayBuffer` is not guaranteed to correspond exactly to the original <ide> `Buffer`. See the notes on `buf.byteOffset` for details. <ide> console.log(buffer.buffer === arrayBuffer); <ide> <ide> ### `buf.byteOffset` <ide> <del>* {integer} The `byteOffset` on the underlying `ArrayBuffer` object based on <del> which this `Buffer` object is created. <add>* {integer} The `byteOffset` of the `Buffer`s underlying `ArrayBuffer` object. <ide> <ide> When setting `byteOffset` in `Buffer.from(ArrayBuffer, byteOffset, length)`, <del>or sometimes when allocating a buffer smaller than `Buffer.poolSize`, the <del>buffer doesn't start from a zero offset on the underlying `ArrayBuffer`. <add>or sometimes when allocating a `Buffer` smaller than `Buffer.poolSize`, the <add>buffer does not start from a zero offset on the underlying `ArrayBuffer`. <ide> <ide> This can cause problems when accessing the underlying `ArrayBuffer` directly <ide> using `buf.buffer`, as other parts of the `ArrayBuffer` may be unrelated <del>to the `buf` object itself. <add>to the `Buffer` object itself. <ide> <ide> A common issue when creating a `TypedArray` object that shares its memory with <ide> a `Buffer` is that in this case one needs to specify the `byteOffset` correctly: <ide> deprecated: v8.0.0 <ide> The `buf.parent` property is a deprecated alias for `buf.buffer`. <ide> <ide> ### `buf.readBigInt64BE([offset])` <add><!-- YAML <add>added: <add> - v12.0.0 <add> - v10.20.0 <add>--> <add> <add>* `offset` {integer} Number of bytes to skip before starting to read. Must <add> satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`. <add>* Returns: {bigint} <add> <add>Reads a signed, big-endian 64-bit integer from `buf` at the specified `offset`. <add> <add>Integers read from a `Buffer` are interpreted as two's complement signed <add>values. <add> <ide> ### `buf.readBigInt64LE([offset])` <ide> <!-- YAML <ide> added: <ide> added: <ide> satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`. <ide> * Returns: {bigint} <ide> <del>Reads a signed 64-bit integer from `buf` at the specified `offset` with <del>the specified [endianness][] (`readBigInt64BE()` reads as big endian, <del>`readBigInt64LE()` reads as little endian). <add>Reads a signed, little-endian 64-bit integer from `buf` at the specified <add>`offset`. <ide> <del>Integers read from a `Buffer` are interpreted as two's complement signed values. <add>Integers read from a `Buffer` are interpreted as two's complement signed <add>values. <ide> <ide> ### `buf.readBigUInt64BE([offset])` <del>### `buf.readBigUInt64LE([offset])` <ide> <!-- YAML <ide> added: <ide> - v12.0.0 <ide> added: <ide> satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`. <ide> * Returns: {bigint} <ide> <del>Reads an unsigned 64-bit integer from `buf` at the specified `offset` with <del>the specified [endianness][] (`readBigUInt64BE()` reads as big endian, <del>`readBigUInt64LE()` reads as little endian). <add>Reads an unsigned, big-endian 64-bit integer from `buf` at the specified <add>`offset`. <ide> <ide> ```js <ide> const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); <ide> <ide> console.log(buf.readBigUInt64BE(0)); <ide> // Prints: 4294967295n <add>``` <add> <add>### `buf.readBigUInt64LE([offset])` <add><!-- YAML <add>added: <add> - v12.0.0 <add> - v10.20.0 <add>--> <add> <add>* `offset` {integer} Number of bytes to skip before starting to read. Must <add> satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`. <add>* Returns: {bigint} <add> <add>Reads an unsigned, little-endian 64-bit integer from `buf` at the specified <add>`offset`. <add> <add>```js <add>const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); <ide> <ide> console.log(buf.readBigUInt64LE(0)); <ide> // Prints: 18446744069414584320n <ide> ``` <ide> <ide> ### `buf.readDoubleBE([offset])` <del>### `buf.readDoubleLE([offset])` <ide> <!-- YAML <ide> added: v0.11.15 <ide> changes: <ide> changes: <ide> satisfy `0 <= offset <= buf.length - 8`. **Default:** `0`. <ide> * Returns: {number} <ide> <del>Reads a 64-bit double from `buf` at the specified `offset` with the specified <del>[endianness][] (`readDoubleBE()` reads as big endian, `readDoubleLE()` reads as <del>little endian). <add>Reads a 64-bit, big-endian double from `buf` at the specified `offset`. <ide> <ide> ```js <ide> const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); <ide> <ide> console.log(buf.readDoubleBE(0)); <ide> // Prints: 8.20788039913184e-304 <add>``` <add> <add>### `buf.readDoubleLE([offset])` <add><!-- YAML <add>added: v0.11.15 <add>changes: <add> - version: v10.0.0 <add> pr-url: https://github.com/nodejs/node/pull/18395 <add> description: Removed `noAssert` and no implicit coercion of the offset <add> to `uint32` anymore. <add>--> <add> <add>* `offset` {integer} Number of bytes to skip before starting to read. Must <add> satisfy `0 <= offset <= buf.length - 8`. **Default:** `0`. <add>* Returns: {number} <add> <add>Reads a 64-bit, little-endian double from `buf` at the specified `offset`. <add> <add>```js <add>const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); <add> <ide> console.log(buf.readDoubleLE(0)); <ide> // Prints: 5.447603722011605e-270 <ide> console.log(buf.readDoubleLE(1)); <ide> // Throws ERR_OUT_OF_RANGE. <ide> ``` <ide> <ide> ### `buf.readFloatBE([offset])` <del>### `buf.readFloatLE([offset])` <ide> <!-- YAML <ide> added: v0.11.15 <ide> changes: <ide> changes: <ide> satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`. <ide> * Returns: {number} <ide> <del>Reads a 32-bit float from `buf` at the specified `offset` with the specified <del>[endianness][] (`readFloatBE()` reads as big endian, `readFloatLE()` reads as <del>little endian). <add>Reads a 32-bit, big-endian float from `buf` at the specified `offset`. <ide> <ide> ```js <ide> const buf = Buffer.from([1, 2, 3, 4]); <ide> <ide> console.log(buf.readFloatBE(0)); <ide> // Prints: 2.387939260590663e-38 <add>``` <add> <add>### `buf.readFloatLE([offset])` <add><!-- YAML <add>added: v0.11.15 <add>changes: <add> - version: v10.0.0 <add> pr-url: https://github.com/nodejs/node/pull/18395 <add> description: Removed `noAssert` and no implicit coercion of the offset <add> to `uint32` anymore. <add>--> <add> <add>* `offset` {integer} Number of bytes to skip before starting to read. Must <add> satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`. <add>* Returns: {number} <add> <add>Reads a 32-bit, little-endian float from `buf` at the specified `offset`. <add> <add>```js <add>const buf = Buffer.from([1, 2, 3, 4]); <add> <ide> console.log(buf.readFloatLE(0)); <ide> // Prints: 1.539989614439558e-36 <ide> console.log(buf.readFloatLE(1)); <ide> console.log(buf.readInt8(2)); <ide> ``` <ide> <ide> ### `buf.readInt16BE([offset])` <del>### `buf.readInt16LE([offset])` <ide> <!-- YAML <ide> added: v0.5.5 <ide> changes: <ide> changes: <ide> satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`. <ide> * Returns: {integer} <ide> <del>Reads a signed 16-bit integer from `buf` at the specified `offset` with <del>the specified [endianness][] (`readInt16BE()` reads as big endian, <del>`readInt16LE()` reads as little endian). <add>Reads a signed, big-endian 16-bit integer from `buf` at the specified `offset`. <ide> <ide> Integers read from a `Buffer` are interpreted as two's complement signed values. <ide> <ide> const buf = Buffer.from([0, 5]); <ide> <ide> console.log(buf.readInt16BE(0)); <ide> // Prints: 5 <add>``` <add> <add>### `buf.readInt16LE([offset])` <add><!-- YAML <add>added: v0.5.5 <add>changes: <add> - version: v10.0.0 <add> pr-url: https://github.com/nodejs/node/pull/18395 <add> description: Removed `noAssert` and no implicit coercion of the offset <add> to `uint32` anymore. <add>--> <add> <add>* `offset` {integer} Number of bytes to skip before starting to read. Must <add> satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`. <add>* Returns: {integer} <add> <add>Reads a signed, little-endian 16-bit integer from `buf` at the specified <add>`offset`. <add> <add>Integers read from a `Buffer` are interpreted as two's complement signed values. <add> <add>```js <add>const buf = Buffer.from([0, 5]); <add> <ide> console.log(buf.readInt16LE(0)); <ide> // Prints: 1280 <ide> console.log(buf.readInt16LE(1)); <ide> // Throws ERR_OUT_OF_RANGE. <ide> ``` <ide> <ide> ### `buf.readInt32BE([offset])` <del>### `buf.readInt32LE([offset])` <ide> <!-- YAML <ide> added: v0.5.5 <ide> changes: <ide> changes: <ide> satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`. <ide> * Returns: {integer} <ide> <del>Reads a signed 32-bit integer from `buf` at the specified `offset` with <del>the specified [endianness][] (`readInt32BE()` reads as big endian, <del>`readInt32LE()` reads as little endian). <add>Reads a signed, big-endian 32-bit integer from `buf` at the specified `offset`. <ide> <ide> Integers read from a `Buffer` are interpreted as two's complement signed values. <ide> <ide> const buf = Buffer.from([0, 0, 0, 5]); <ide> <ide> console.log(buf.readInt32BE(0)); <ide> // Prints: 5 <add>``` <add> <add>### `buf.readInt32LE([offset])` <add><!-- YAML <add>added: v0.5.5 <add>changes: <add> - version: v10.0.0 <add> pr-url: https://github.com/nodejs/node/pull/18395 <add> description: Removed `noAssert` and no implicit coercion of the offset <add> to `uint32` anymore. <add>--> <add> <add>* `offset` {integer} Number of bytes to skip before starting to read. Must <add> satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`. <add>* Returns: {integer} <add> <add>Reads a signed, little-endian 32-bit integer from `buf` at the specified <add>`offset`. <add> <add>Integers read from a `Buffer` are interpreted as two's complement signed values. <add> <add>```js <add>const buf = Buffer.from([0, 0, 0, 5]); <add> <ide> console.log(buf.readInt32LE(0)); <ide> // Prints: 83886080 <ide> console.log(buf.readInt32LE(1)); <ide> // Throws ERR_OUT_OF_RANGE. <ide> ``` <ide> <ide> ### `buf.readIntBE(offset, byteLength)` <del>### `buf.readIntLE(offset, byteLength)` <ide> <!-- YAML <ide> added: v0.11.15 <ide> changes: <ide> changes: <ide> * Returns: {integer} <ide> <ide> Reads `byteLength` number of bytes from `buf` at the specified `offset` <del>and interprets the result as a two's complement signed value. Supports up to 48 <del>bits of accuracy. <add>and interprets the result as a big-endian, two's complement signed value <add>supporting up to 48 bits of accuracy. <ide> <ide> ```js <ide> const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); <ide> <del>console.log(buf.readIntLE(0, 6).toString(16)); <del>// Prints: -546f87a9cbee <ide> console.log(buf.readIntBE(0, 6).toString(16)); <ide> // Prints: 1234567890ab <ide> console.log(buf.readIntBE(1, 6).toString(16)); <ide> console.log(buf.readIntBE(1, 0).toString(16)); <ide> // Throws ERR_OUT_OF_RANGE. <ide> ``` <ide> <add>### `buf.readIntLE(offset, byteLength)` <add><!-- YAML <add>added: v0.11.15 <add>changes: <add> - version: v10.0.0 <add> pr-url: https://github.com/nodejs/node/pull/18395 <add> description: Removed `noAssert` and no implicit coercion of the offset <add> and `byteLength` to `uint32` anymore. <add>--> <add> <add>* `offset` {integer} Number of bytes to skip before starting to read. Must <add> satisfy `0 <= offset <= buf.length - byteLength`. <add>* `byteLength` {integer} Number of bytes to read. Must satisfy <add> `0 < byteLength <= 6`. <add>* Returns: {integer} <add> <add>Reads `byteLength` number of bytes from `buf` at the specified `offset` <add>and interprets the result as a little-endian, two's complement signed value <add>supporting up to 48 bits of accuracy. <add> <add>```js <add>const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); <add> <add>console.log(buf.readIntLE(0, 6).toString(16)); <add>// Prints: -546f87a9cbee <add>``` <add> <ide> ### `buf.readUInt8([offset])` <ide> <!-- YAML <ide> added: v0.5.0 <ide> console.log(buf.readUInt8(2)); <ide> ``` <ide> <ide> ### `buf.readUInt16BE([offset])` <del>### `buf.readUInt16LE([offset])` <ide> <!-- YAML <ide> added: v0.5.5 <ide> changes: <ide> changes: <ide> satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`. <ide> * Returns: {integer} <ide> <del>Reads an unsigned 16-bit integer from `buf` at the specified `offset` with <del>the specified [endianness][] (`readUInt16BE()` reads as big endian, `readUInt16LE()` <del>reads as little endian). <add>Reads an unsigned, big-endian 16-bit integer from `buf` at the specified <add>`offset`. <ide> <ide> ```js <ide> const buf = Buffer.from([0x12, 0x34, 0x56]); <ide> <ide> console.log(buf.readUInt16BE(0).toString(16)); <ide> // Prints: 1234 <del>console.log(buf.readUInt16LE(0).toString(16)); <del>// Prints: 3412 <ide> console.log(buf.readUInt16BE(1).toString(16)); <ide> // Prints: 3456 <add>``` <add> <add>### `buf.readUInt16LE([offset])` <add><!-- YAML <add>added: v0.5.5 <add>changes: <add> - version: v10.0.0 <add> pr-url: https://github.com/nodejs/node/pull/18395 <add> description: Removed `noAssert` and no implicit coercion of the offset <add> to `uint32` anymore. <add>--> <add> <add>* `offset` {integer} Number of bytes to skip before starting to read. Must <add> satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`. <add>* Returns: {integer} <add> <add>Reads an unsigned, little-endian 16-bit integer from `buf` at the specified <add>`offset`. <add> <add>```js <add>const buf = Buffer.from([0x12, 0x34, 0x56]); <add> <add>console.log(buf.readUInt16LE(0).toString(16)); <add>// Prints: 3412 <ide> console.log(buf.readUInt16LE(1).toString(16)); <ide> // Prints: 5634 <ide> console.log(buf.readUInt16LE(2).toString(16)); <ide> // Throws ERR_OUT_OF_RANGE. <ide> ``` <ide> <ide> ### `buf.readUInt32BE([offset])` <del>### `buf.readUInt32LE([offset])` <ide> <!-- YAML <ide> added: v0.5.5 <ide> changes: <ide> changes: <ide> satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`. <ide> * Returns: {integer} <ide> <del>Reads an unsigned 32-bit integer from `buf` at the specified `offset` with <del>the specified [endianness][] (`readUInt32BE()` reads as big endian, <del>`readUInt32LE()` reads as little endian). <add>Reads an unsigned, big-endian 32-bit integer from `buf` at the specified <add>`offset`. <ide> <ide> ```js <ide> const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); <ide> <ide> console.log(buf.readUInt32BE(0).toString(16)); <ide> // Prints: 12345678 <add>``` <add> <add>### `buf.readUInt32LE([offset])` <add><!-- YAML <add>added: v0.5.5 <add>changes: <add> - version: v10.0.0 <add> pr-url: https://github.com/nodejs/node/pull/18395 <add> description: Removed `noAssert` and no implicit coercion of the offset <add> to `uint32` anymore. <add>--> <add> <add>* `offset` {integer} Number of bytes to skip before starting to read. Must <add> satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`. <add>* Returns: {integer} <add> <add>Reads an unsigned, little-endian 32-bit integer from `buf` at the specified <add>`offset`. <add> <add>```js <add>const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); <add> <ide> console.log(buf.readUInt32LE(0).toString(16)); <ide> // Prints: 78563412 <ide> console.log(buf.readUInt32LE(1).toString(16)); <ide> // Throws ERR_OUT_OF_RANGE. <ide> ``` <ide> <ide> ### `buf.readUIntBE(offset, byteLength)` <del>### `buf.readUIntLE(offset, byteLength)` <ide> <!-- YAML <ide> added: v0.11.15 <ide> changes: <ide> changes: <ide> * Returns: {integer} <ide> <ide> Reads `byteLength` number of bytes from `buf` at the specified `offset` <del>and interprets the result as an unsigned integer. Supports up to 48 <del>bits of accuracy. <add>and interprets the result as an unsigned big-endian integer supporting <add>up to 48 bits of accuracy. <ide> <ide> ```js <ide> const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); <ide> <ide> console.log(buf.readUIntBE(0, 6).toString(16)); <ide> // Prints: 1234567890ab <del>console.log(buf.readUIntLE(0, 6).toString(16)); <del>// Prints: ab9078563412 <ide> console.log(buf.readUIntBE(1, 6).toString(16)); <ide> // Throws ERR_OUT_OF_RANGE. <ide> ``` <ide> <add>### `buf.readUIntLE(offset, byteLength)` <add><!-- YAML <add>added: v0.11.15 <add>changes: <add> - version: v10.0.0 <add> pr-url: https://github.com/nodejs/node/pull/18395 <add> description: Removed `noAssert` and no implicit coercion of the offset <add> and `byteLength` to `uint32` anymore. <add>--> <add> <add>* `offset` {integer} Number of bytes to skip before starting to read. Must <add> satisfy `0 <= offset <= buf.length - byteLength`. <add>* `byteLength` {integer} Number of bytes to read. Must satisfy <add> `0 < byteLength <= 6`. <add>* Returns: {integer} <add> <add>Reads `byteLength` number of bytes from `buf` at the specified `offset` <add>and interprets the result as an unsigned, little-endian integer supporting <add>up to 48 bits of accuracy. <add> <add>```js <add>const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); <add> <add>console.log(buf.readUIntLE(0, 6).toString(16)); <add>// Prints: ab9078563412 <add>``` <add> <ide> ### `buf.subarray([start[, end]])` <ide> <!-- YAML <ide> added: v3.0.0 <ide> console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`); <ide> ``` <ide> <ide> ### `buf.writeBigInt64BE(value[, offset])` <del>### `buf.writeBigInt64LE(value[, offset])` <ide> <!-- YAML <ide> added: <ide> - v12.0.0 <ide> added: <ide> satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`. <ide> * Returns: {integer} `offset` plus the number of bytes written. <ide> <del>Writes `value` to `buf` at the specified `offset` with the specified <del>[endianness][] (`writeBigInt64BE()` writes as big endian, `writeBigInt64LE()` <del>writes as little endian). <add>Writes `value` to `buf` at the specified `offset` as big-endian. <ide> <ide> `value` is interpreted and written as a two's complement signed integer. <ide> <ide> console.log(buf); <ide> // Prints: <Buffer 01 02 03 04 05 06 07 08> <ide> ``` <ide> <add>### `buf.writeBigInt64LE(value[, offset])` <add><!-- YAML <add>added: <add> - v12.0.0 <add> - v10.20.0 <add>--> <add> <add>* `value` {bigint} Number to be written to `buf`. <add>* `offset` {integer} Number of bytes to skip before starting to write. Must <add> satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`. <add>* Returns: {integer} `offset` plus the number of bytes written. <add> <add>Writes `value` to `buf` at the specified `offset` as little-endian. <add> <add>`value` is interpreted and written as a two's complement signed integer. <add> <add>```js <add>const buf = Buffer.allocUnsafe(8); <add> <add>buf.writeBigInt64LE(0x0102030405060708n, 0); <add> <add>console.log(buf); <add>// Prints: <Buffer 08 07 06 05 04 03 02 01> <add>``` <add> <ide> ### `buf.writeBigUInt64BE(value[, offset])` <add><!-- YAML <add>added: <add> - v12.0.0 <add> - v10.20.0 <add>--> <add> <add>* `value` {bigint} Number to be written to `buf`. <add>* `offset` {integer} Number of bytes to skip before starting to write. Must <add> satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`. <add>* Returns: {integer} `offset` plus the number of bytes written. <add> <add>Writes `value` to `buf` at the specified `offset` as big-endian. <add> <add>```js <add>const buf = Buffer.allocUnsafe(8); <add> <add>buf.writeBigUInt64BE(0xdecafafecacefaden, 0); <add> <add>console.log(buf); <add>// Prints: <Buffer de ca fa fe ca ce fa de> <add>``` <add> <ide> ### `buf.writeBigUInt64LE(value[, offset])` <ide> <!-- YAML <ide> added: <ide> added: <ide> satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`. <ide> * Returns: {integer} `offset` plus the number of bytes written. <ide> <del>Writes `value` to `buf` at the specified `offset` with specified [endianness][] <del>(`writeBigUInt64BE()` writes as big endian, `writeBigUInt64LE()` writes as <del>little endian). <add>Writes `value` to `buf` at the specified `offset` as little-endian <ide> <ide> ```js <ide> const buf = Buffer.allocUnsafe(8); <ide> console.log(buf); <ide> ``` <ide> <ide> ### `buf.writeDoubleBE(value[, offset])` <del>### `buf.writeDoubleLE(value[, offset])` <ide> <!-- YAML <ide> added: v0.11.15 <ide> changes: <ide> changes: <ide> satisfy `0 <= offset <= buf.length - 8`. **Default:** `0`. <ide> * Returns: {integer} `offset` plus the number of bytes written. <ide> <del>Writes `value` to `buf` at the specified `offset` with the specified <del>[endianness][] (`writeDoubleBE()` writes as big endian, `writeDoubleLE()` writes <del>as little endian). `value` must be a JavaScript number. Behavior is undefined <del>when `value` is anything other than a JavaScript number. <add>Writes `value` to `buf` at the specified `offset` as big-endian. The `value` <add>must be a JavaScript number. Behavior is undefined when `value` is anything <add>other than a JavaScript number. <ide> <ide> ```js <ide> const buf = Buffer.allocUnsafe(8); <ide> buf.writeDoubleBE(123.456, 0); <ide> <ide> console.log(buf); <ide> // Prints: <Buffer 40 5e dd 2f 1a 9f be 77> <add>``` <add> <add>### `buf.writeDoubleLE(value[, offset])` <add><!-- YAML <add>added: v0.11.15 <add>changes: <add> - version: v10.0.0 <add> pr-url: https://github.com/nodejs/node/pull/18395 <add> description: Removed `noAssert` and no implicit coercion of the offset <add> to `uint32` anymore. <add>--> <add> <add>* `value` {number} Number to be written to `buf`. <add>* `offset` {integer} Number of bytes to skip before starting to write. Must <add> satisfy `0 <= offset <= buf.length - 8`. **Default:** `0`. <add>* Returns: {integer} `offset` plus the number of bytes written. <add> <add>Writes `value` to `buf` at the specified `offset` as little-endian. The `value` <add>must be a JavaScript number. Behavior is undefined when `value` is anything <add>other than a JavaScript number. <add> <add>```js <add>const buf = Buffer.allocUnsafe(8); <ide> <ide> buf.writeDoubleLE(123.456, 0); <ide> <ide> console.log(buf); <ide> ``` <ide> <ide> ### `buf.writeFloatBE(value[, offset])` <del>### `buf.writeFloatLE(value[, offset])` <ide> <!-- YAML <ide> added: v0.11.15 <ide> changes: <ide> changes: <ide> satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`. <ide> * Returns: {integer} `offset` plus the number of bytes written. <ide> <del>Writes `value` to `buf` at the specified `offset` with specified [endianness][] <del>(`writeFloatBE()` writes as big endian, `writeFloatLE()` writes as little <del>endian). `value` must be a JavaScript number. Behavior is undefined when <del>`value` is anything other than a JavaScript number. <add>Writes `value` to `buf` at the specified `offset` as big-endian. Behavior is <add>undefined when `value` is anything other than a JavaScript number. <ide> <ide> ```js <ide> const buf = Buffer.allocUnsafe(4); <ide> buf.writeFloatBE(0xcafebabe, 0); <ide> console.log(buf); <ide> // Prints: <Buffer 4f 4a fe bb> <ide> <add>``` <add> <add>### `buf.writeFloatLE(value[, offset])` <add><!-- YAML <add>added: v0.11.15 <add>changes: <add> - version: v10.0.0 <add> pr-url: https://github.com/nodejs/node/pull/18395 <add> description: Removed `noAssert` and no implicit coercion of the offset <add> to `uint32` anymore. <add>--> <add> <add>* `value` {number} Number to be written to `buf`. <add>* `offset` {integer} Number of bytes to skip before starting to write. Must <add> satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`. <add>* Returns: {integer} `offset` plus the number of bytes written. <add> <add>Writes `value` to `buf` at the specified `offset` as little-endian. Behavior is <add>undefined when `value` is anything other than a JavaScript number. <add> <add>```js <add>const buf = Buffer.allocUnsafe(4); <add> <ide> buf.writeFloatLE(0xcafebabe, 0); <ide> <ide> console.log(buf); <ide> console.log(buf); <ide> ``` <ide> <ide> ### `buf.writeInt16BE(value[, offset])` <del>### `buf.writeInt16LE(value[, offset])` <ide> <!-- YAML <ide> added: v0.5.5 <ide> changes: <ide> changes: <ide> satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`. <ide> * Returns: {integer} `offset` plus the number of bytes written. <ide> <del>Writes `value` to `buf` at the specified `offset` with the specified <del>[endianness][] (`writeInt16BE()` writes as big endian, `writeInt16LE()` writes <del>as little endian). `value` must be a valid signed 16-bit integer. Behavior is <del>undefined when `value` is anything other than a signed 16-bit integer. <add>Writes `value` to `buf` at the specified `offset` as big-endian. The `value` <add>must be a valid signed 16-bit integer. Behavior is undefined when `value` is <add>anything other than a signed 16-bit integer. <ide> <del>`value` is interpreted and written as a two's complement signed integer. <add>The `value` is interpreted and written as a two's complement signed integer. <ide> <ide> ```js <del>const buf = Buffer.allocUnsafe(4); <add>const buf = Buffer.allocUnsafe(2); <ide> <ide> buf.writeInt16BE(0x0102, 0); <del>buf.writeInt16LE(0x0304, 2); <ide> <ide> console.log(buf); <del>// Prints: <Buffer 01 02 04 03> <add>// Prints: <Buffer 01 02> <add>``` <add> <add>### `buf.writeInt16LE(value[, offset])` <add><!-- YAML <add>added: v0.5.5 <add>changes: <add> - version: v10.0.0 <add> pr-url: https://github.com/nodejs/node/pull/18395 <add> description: Removed `noAssert` and no implicit coercion of the offset <add> to `uint32` anymore. <add>--> <add> <add>* `value` {integer} Number to be written to `buf`. <add>* `offset` {integer} Number of bytes to skip before starting to write. Must <add> satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`. <add>* Returns: {integer} `offset` plus the number of bytes written. <add> <add>Writes `value` to `buf` at the specified `offset` as little-endian. The `value` <add>must be a valid signed 16-bit integer. Behavior is undefined when `value` is <add>anything other than a signed 16-bit integer. <add> <add>The `value` is interpreted and written as a two's complement signed integer. <add> <add>```js <add>const buf = Buffer.allocUnsafe(2); <add> <add>buf.writeInt16LE(0x0304, 0); <add> <add>console.log(buf); <add>// Prints: <Buffer 04 03> <ide> ``` <ide> <ide> ### `buf.writeInt32BE(value[, offset])` <del>### `buf.writeInt32LE(value[, offset])` <ide> <!-- YAML <ide> added: v0.5.5 <ide> changes: <ide> changes: <ide> satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`. <ide> * Returns: {integer} `offset` plus the number of bytes written. <ide> <del>Writes `value` to `buf` at the specified `offset` with the specified <del>[endianness][] (`writeInt32BE()` writes aS big endian, `writeInt32LE()` writes <del>as little endian). `value` must be a valid signed 32-bit integer. Behavior is <del>undefined when `value` is anything other than a signed 32-bit integer. <add>Writes `value` to `buf` at the specified `offset` as big-endian. The `value` <add>must be a valid signed 32-bit integer. Behavior is undefined when `value` is <add>anything other than a signed 32-bit integer. <ide> <del>`value` is interpreted and written as a two's complement signed integer. <add>The `value` is interpreted and written as a two's complement signed integer. <ide> <ide> ```js <del>const buf = Buffer.allocUnsafe(8); <add>const buf = Buffer.allocUnsafe(4); <ide> <ide> buf.writeInt32BE(0x01020304, 0); <del>buf.writeInt32LE(0x05060708, 4); <ide> <ide> console.log(buf); <del>// Prints: <Buffer 01 02 03 04 08 07 06 05> <add>// Prints: <Buffer 01 02 03 04> <add>``` <add> <add>### `buf.writeInt32LE(value[, offset])` <add><!-- YAML <add>added: v0.5.5 <add>changes: <add> - version: v10.0.0 <add> pr-url: https://github.com/nodejs/node/pull/18395 <add> description: Removed `noAssert` and no implicit coercion of the offset <add> to `uint32` anymore. <add>--> <add> <add>* `value` {integer} Number to be written to `buf`. <add>* `offset` {integer} Number of bytes to skip before starting to write. Must <add> satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`. <add>* Returns: {integer} `offset` plus the number of bytes written. <add> <add>Writes `value` to `buf` at the specified `offset` as little-endian. The `value` <add>must be a valid signed 32-bit integer. Behavior is undefined when `value` is <add>anything other than a signed 32-bit integer. <add> <add>The `value` is interpreted and written as a two's complement signed integer. <add> <add>```js <add>const buf = Buffer.allocUnsafe(4); <add> <add>buf.writeInt32LE(0x05060708, 0); <add> <add>console.log(buf); <add>// Prints: <Buffer 08 07 06 05> <ide> ``` <ide> <ide> ### `buf.writeIntBE(value, offset, byteLength)` <del>### `buf.writeIntLE(value, offset, byteLength)` <ide> <!-- YAML <ide> added: v0.11.15 <ide> changes: <ide> changes: <ide> `0 < byteLength <= 6`. <ide> * Returns: {integer} `offset` plus the number of bytes written. <ide> <del>Writes `byteLength` bytes of `value` to `buf` at the specified `offset`. <del>Supports up to 48 bits of accuracy. Behavior is undefined when `value` is <del>anything other than a signed integer. <add>Writes `byteLength` bytes of `value` to `buf` at the specified `offset` <add>as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when <add>`value` is anything other than a signed integer. <ide> <ide> ```js <ide> const buf = Buffer.allocUnsafe(6); <ide> buf.writeIntBE(0x1234567890ab, 0, 6); <ide> console.log(buf); <ide> // Prints: <Buffer 12 34 56 78 90 ab> <ide> <add>``` <add> <add>### `buf.writeIntLE(value, offset, byteLength)` <add><!-- YAML <add>added: v0.11.15 <add>changes: <add> - version: v10.0.0 <add> pr-url: https://github.com/nodejs/node/pull/18395 <add> description: Removed `noAssert` and no implicit coercion of the offset <add> and `byteLength` to `uint32` anymore. <add>--> <add> <add>* `value` {integer} Number to be written to `buf`. <add>* `offset` {integer} Number of bytes to skip before starting to write. Must <add> satisfy `0 <= offset <= buf.length - byteLength`. <add>* `byteLength` {integer} Number of bytes to write. Must satisfy <add> `0 < byteLength <= 6`. <add>* Returns: {integer} `offset` plus the number of bytes written. <add> <add>Writes `byteLength` bytes of `value` to `buf` at the specified `offset` <add>as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined <add>when `value` is anything other than a signed integer. <add> <add>```js <add>const buf = Buffer.allocUnsafe(6); <add> <ide> buf.writeIntLE(0x1234567890ab, 0, 6); <ide> <ide> console.log(buf); <ide> console.log(buf); <ide> ``` <ide> <ide> ### `buf.writeUInt16BE(value[, offset])` <del>### `buf.writeUInt16LE(value[, offset])` <ide> <!-- YAML <ide> added: v0.5.5 <ide> changes: <ide> changes: <ide> satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`. <ide> * Returns: {integer} `offset` plus the number of bytes written. <ide> <del>Writes `value` to `buf` at the specified `offset` with the specified <del>[endianness][] (`writeUInt16BE()` writes as big endian, `writeUInt16LE()` writes <del>as little endian). `value` must be a valid unsigned 16-bit integer. Behavior is <del>undefined when `value` is anything other than an unsigned 16-bit integer. <add>Writes `value` to `buf` at the specified `offset` as big-endian. The `value` <add>must be a valid unsigned 16-bit integer. Behavior is undefined when `value` <add>is anything other than an unsigned 16-bit integer. <ide> <ide> ```js <ide> const buf = Buffer.allocUnsafe(4); <ide> buf.writeUInt16BE(0xbeef, 2); <ide> <ide> console.log(buf); <ide> // Prints: <Buffer de ad be ef> <add>``` <add> <add>### `buf.writeUInt16LE(value[, offset])` <add><!-- YAML <add>added: v0.5.5 <add>changes: <add> - version: v10.0.0 <add> pr-url: https://github.com/nodejs/node/pull/18395 <add> description: Removed `noAssert` and no implicit coercion of the offset <add> to `uint32` anymore. <add>--> <add> <add>* `value` {integer} Number to be written to `buf`. <add>* `offset` {integer} Number of bytes to skip before starting to write. Must <add> satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`. <add>* Returns: {integer} `offset` plus the number of bytes written. <add> <add>Writes `value` to `buf` at the specified `offset` as little-endian. The `value` <add>must be a valid unsigned 16-bit integer. Behavior is undefined when `value` is <add>anything other than an unsigned 16-bit integer. <add> <add>```js <add>const buf = Buffer.allocUnsafe(4); <ide> <ide> buf.writeUInt16LE(0xdead, 0); <ide> buf.writeUInt16LE(0xbeef, 2); <ide> console.log(buf); <ide> ``` <ide> <ide> ### `buf.writeUInt32BE(value[, offset])` <del>### `buf.writeUInt32LE(value[, offset])` <ide> <!-- YAML <ide> added: v0.5.5 <ide> changes: <ide> changes: <ide> satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`. <ide> * Returns: {integer} `offset` plus the number of bytes written. <ide> <del>Writes `value` to `buf` at the specified `offset` with the specified <del>[endianness][] (`writeUInt32BE()` writes as big endian, `writeUInt32LE()` writes <del>as little endian). `value` must be a valid unsigned 32-bit integer. Behavior is <del>undefined when `value` is anything other than an unsigned 32-bit integer. <add>Writes `value` to `buf` at the specified `offset` as big-endian. The `value` <add>must be a valid unsigned 32-bit integer. Behavior is undefined when `value` <add>is anything other than an unsigned 32-bit integer. <ide> <ide> ```js <ide> const buf = Buffer.allocUnsafe(4); <ide> buf.writeUInt32BE(0xfeedface, 0); <ide> <ide> console.log(buf); <ide> // Prints: <Buffer fe ed fa ce> <add>``` <add> <add>### `buf.writeUInt32LE(value[, offset])` <add><!-- YAML <add>added: v0.5.5 <add>changes: <add> - version: v10.0.0 <add> pr-url: https://github.com/nodejs/node/pull/18395 <add> description: Removed `noAssert` and no implicit coercion of the offset <add> to `uint32` anymore. <add>--> <add> <add>* `value` {integer} Number to be written to `buf`. <add>* `offset` {integer} Number of bytes to skip before starting to write. Must <add> satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`. <add>* Returns: {integer} `offset` plus the number of bytes written. <add> <add>Writes `value` to `buf` at the specified `offset` as little-endian. The `value` <add>must be a valid unsigned 32-bit integer. Behavior is undefined when `value` is <add>anything other than an unsigned 32-bit integer. <add> <add>```js <add>const buf = Buffer.allocUnsafe(4); <ide> <ide> buf.writeUInt32LE(0xfeedface, 0); <ide> <ide> console.log(buf); <ide> ``` <ide> <ide> ### `buf.writeUIntBE(value, offset, byteLength)` <del>### `buf.writeUIntLE(value, offset, byteLength)` <ide> <!-- YAML <ide> added: v0.5.5 <ide> changes: <ide> changes: <ide> `0 < byteLength <= 6`. <ide> * Returns: {integer} `offset` plus the number of bytes written. <ide> <del>Writes `byteLength` bytes of `value` to `buf` at the specified `offset`. <del>Supports up to 48 bits of accuracy. Behavior is undefined when `value` is <del>anything other than an unsigned integer. <add>Writes `byteLength` bytes of `value` to `buf` at the specified `offset` <add>as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined <add>when `value` is anything other than an unsigned integer. <ide> <ide> ```js <ide> const buf = Buffer.allocUnsafe(6); <ide> buf.writeUIntBE(0x1234567890ab, 0, 6); <ide> <ide> console.log(buf); <ide> // Prints: <Buffer 12 34 56 78 90 ab> <add>``` <add> <add>### `buf.writeUIntLE(value, offset, byteLength)` <add><!-- YAML <add>added: v0.5.5 <add>changes: <add> - version: v10.0.0 <add> pr-url: https://github.com/nodejs/node/pull/18395 <add> description: Removed `noAssert` and no implicit coercion of the offset <add> and `byteLength` to `uint32` anymore. <add>--> <add> <add>* `value` {integer} Number to be written to `buf`. <add>* `offset` {integer} Number of bytes to skip before starting to write. Must <add> satisfy `0 <= offset <= buf.length - byteLength`. <add>* `byteLength` {integer} Number of bytes to write. Must satisfy <add> `0 < byteLength <= 6`. <add>* Returns: {integer} `offset` plus the number of bytes written. <add> <add>Writes `byteLength` bytes of `value` to `buf` at the specified `offset` <add>as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined <add>when `value` is anything other than an unsigned integer. <add> <add>```js <add>const buf = Buffer.allocUnsafe(6); <ide> <ide> buf.writeUIntLE(0x1234567890ab, 0, 6); <ide> <ide> changes: <ide> <ide> See [`Buffer.from(string[, encoding])`][`Buffer.from(string)`]. <ide> <del>## `buffer.INSPECT_MAX_BYTES` <add>## `buffer` module APIs <add> <add>While, the `Buffer` object is available as a global, there are additional <add>`Buffer`-related APIs that are available only via the `buffer` module <add>accessed using `require('buffer')`. <add> <add>### `buffer.INSPECT_MAX_BYTES` <ide> <!-- YAML <ide> added: v0.5.4 <ide> --> <ide> Returns the maximum number of bytes that will be returned when <ide> `buf.inspect()` is called. This can be overridden by user modules. See <ide> [`util.inspect()`][] for more details on `buf.inspect()` behavior. <ide> <del>This is a property on the `buffer` module returned by <del>`require('buffer')`, not on the `Buffer` global or a `Buffer` instance. <del> <del>## `buffer.kMaxLength` <add>### `buffer.kMaxLength` <ide> <!-- YAML <ide> added: v3.0.0 <ide> --> <ide> added: v3.0.0 <ide> <ide> An alias for [`buffer.constants.MAX_LENGTH`][]. <ide> <del>This is a property on the `buffer` module returned by <del>`require('buffer')`, not on the `Buffer` global or a `Buffer` instance. <del> <del>## `buffer.transcode(source, fromEnc, toEnc)` <add>### `buffer.transcode(source, fromEnc, toEnc)` <ide> <!-- YAML <ide> added: v7.1.0 <ide> changes: <ide> console.log(newBuf.toString('ascii')); <ide> Because the Euro (`€`) sign is not representable in US-ASCII, it is replaced <ide> with `?` in the transcoded `Buffer`. <ide> <del>This is a property on the `buffer` module returned by <del>`require('buffer')`, not on the `Buffer` global or a `Buffer` instance. <del> <del>## Class: `SlowBuffer` <add>### Class: `SlowBuffer` <ide> <!-- YAML <ide> deprecated: v6.0.0 <ide> --> <ide> See [`Buffer.allocUnsafeSlow()`][]. This was never a class in the sense that <ide> the constructor always returned a `Buffer` instance, rather than a `SlowBuffer` <ide> instance. <ide> <del>### `new SlowBuffer(size)` <add>#### `new SlowBuffer(size)` <ide> <!-- YAML <ide> deprecated: v6.0.0 <ide> --> <ide> deprecated: v6.0.0 <ide> <ide> See [`Buffer.allocUnsafeSlow()`][]. <ide> <del>## Buffer constants <add>### Buffer constants <ide> <!-- YAML <ide> added: v8.2.0 <ide> --> <ide> <del>`buffer.constants` is a property on the `buffer` module returned by <del>`require('buffer')`, not on the `Buffer` global or a `Buffer` instance. <del> <del>### `buffer.constants.MAX_LENGTH` <add>#### `buffer.constants.MAX_LENGTH` <ide> <!-- YAML <ide> added: v8.2.0 <ide> --> <ide> On 64-bit architectures, this value currently is `(2^31)-1` (~2GB). <ide> <ide> This value is also available as [`buffer.kMaxLength`][]. <ide> <del>### `buffer.constants.MAX_STRING_LENGTH` <add>#### `buffer.constants.MAX_STRING_LENGTH` <ide> <!-- YAML <ide> added: v8.2.0 <ide> --> <ide> introducing security vulnerabilities into an application. <ide> [`TypedArray#slice()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/slice <ide> [`TypedArray#subarray()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray <ide> [`TypedArray`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray <del>[`Uint32Array`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array <ide> [`Uint8Array`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array <ide> [`buf.buffer`]: #buffer_buf_buffer <ide> [`buf.compare()`]: #buffer_buf_compare_target_targetstart_targetend_sourcestart_sourceend
1
Javascript
Javascript
add missing file
9f8cdd28a9d1452894db8355b4f8c0504e0fd593
<ide><path>examples/scope-hoisting/webpack.config.js <add>var webpack = require("../../"); <add> <add>module.exports = { <add> plugins: [ <add> new webpack.optimize.ModuleConcatenationPlugin() <add> ] <add>};
1
Text
Text
fix punctuation issue in async_hooks.md
9a70b2725481ef17dc8a07d6e9d3dc9f72ad0907
<ide><path>doc/api/async_hooks.md <ide> The `TCPSERVERWRAP` is the server which receives the connections. <ide> The `TCPWRAP` is the new connection from the client. When a new <ide> connection is made, the `TCPWrap` instance is immediately constructed. This <ide> happens outside of any JavaScript stack. (An `executionAsyncId()` of `0` means <del>that it is being executed from C++ with no JavaScript stack above it). With only <add>that it is being executed from C++ with no JavaScript stack above it.) With only <ide> that information, it would be impossible to link resources together in <ide> terms of what caused them to be created, so `triggerAsyncId` is given the task <ide> of propagating what resource is responsible for the new resource's existence.
1
Java
Java
define behavior of null callable or deferredresult
11cf978394bda237203f223c933d726c4391a84e
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AsyncTaskMethodReturnValueHandler.java <ide> public void handleReturnValue(Object returnValue, <ide> NativeWebRequest webRequest) throws Exception { <ide> <ide> if (returnValue == null) { <add> mavContainer.setRequestHandled(true); <ide> return; <ide> } <ide> <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/CallableMethodReturnValueHandler.java <ide> public void handleReturnValue(Object returnValue, <ide> NativeWebRequest webRequest) throws Exception { <ide> <ide> if (returnValue == null) { <add> mavContainer.setRequestHandled(true); <ide> return; <ide> } <ide> <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/DeferredResultMethodReturnValueHandler.java <ide> public void handleReturnValue(Object returnValue, <ide> NativeWebRequest webRequest) throws Exception { <ide> <ide> if (returnValue == null) { <add> mavContainer.setRequestHandled(true); <ide> return; <ide> } <ide>
3
Javascript
Javascript
move charlengthleft() and charlengthat()
df1879ac20e0d16286bf3039a49e5fbd31286d1f
<ide><path>lib/internal/readline/utils.js <ide> CSI.kClearToLineEnd = CSI`0K`; <ide> CSI.kClearLine = CSI`2K`; <ide> CSI.kClearScreenDown = CSI`0J`; <ide> <add>// TODO(BridgeAR): Treat combined characters as single character, i.e, <add>// 'a\u0301' and '\u0301a' (both have the same visual output). <add>// Check Canonical_Combining_Class in <add>// http://userguide.icu-project.org/strings/properties <add>function charLengthLeft(str, i) { <add> if (i <= 0) <add> return 0; <add> if ((i > 1 && str.codePointAt(i - 2) >= kUTF16SurrogateThreshold) || <add> str.codePointAt(i - 1) >= kUTF16SurrogateThreshold) { <add> return 2; <add> } <add> return 1; <add>} <add> <add>function charLengthAt(str, i) { <add> if (str.length <= i) { <add> // Pretend to move to the right. This is necessary to autocomplete while <add> // moving to the right. <add> return 1; <add> } <add> return str.codePointAt(i) >= kUTF16SurrogateThreshold ? 2 : 1; <add>} <add> <ide> if (internalBinding('config').hasIntl) { <ide> const icu = internalBinding('icu'); <ide> // icu.getStringWidth(string, ambiguousAsFullWidth, expandEmojiSequence) <ide> function commonPrefix(strings) { <ide> } <ide> <ide> module.exports = { <add> charLengthAt, <add> charLengthLeft, <ide> commonPrefix, <ide> emitKeys, <ide> getStringWidth, <ide><path>lib/readline.js <ide> const { validateString } = require('internal/validators'); <ide> const { inspect } = require('internal/util/inspect'); <ide> const EventEmitter = require('events'); <ide> const { <add> charLengthAt, <add> charLengthLeft, <ide> commonPrefix, <ide> CSI, <ide> emitKeys, <ide> Interface.prototype._wordRight = function() { <ide> } <ide> }; <ide> <del>function charLengthLeft(str, i) { <del> if (i <= 0) <del> return 0; <del> if ((i > 1 && str.codePointAt(i - 2) >= kUTF16SurrogateThreshold) || <del> str.codePointAt(i - 1) >= kUTF16SurrogateThreshold) { <del> return 2; <del> } <del> return 1; <del>} <del> <del>function charLengthAt(str, i) { <del> if (str.length <= i) { <del> // Pretend to move to the right. This is necessary to autocomplete while <del> // moving to the right. <del> return 1; <del> } <del> return str.codePointAt(i) >= kUTF16SurrogateThreshold ? 2 : 1; <del>} <del> <ide> Interface.prototype._deleteLeft = function() { <ide> if (this.cursor > 0 && this.line.length > 0) { <ide> // The number of UTF-16 units comprising the character to the left
2
PHP
PHP
apply fixes from styleci
07a8cddf4e898c0d48ec14c37872047a418cc3e2
<ide><path>src/Illuminate/Routing/Router.php <ide> public function pushMiddlewareToGroup($group, $middleware) <ide> $this->middlewareGroups[$group] = []; <ide> } <ide> <del> if ( ! in_array($middleware, $this->middlewareGroups[$group])) { <add> if (! in_array($middleware, $this->middlewareGroups[$group])) { <ide> $this->middlewareGroups[$group][] = $middleware; <ide> } <ide>
1
Javascript
Javascript
remove instantiating entry when done
186a5912288acfff0ee59dae29af83c37c987921
<ide><path>src/auto/injector.js <ide> function createInjector(modulesToLoad) { <ide> path.unshift(serviceName); <ide> cache[serviceName] = INSTANTIATING; <ide> return cache[serviceName] = factory(serviceName); <add> } catch (err) { <add> if (cache[serviceName] === INSTANTIATING) { <add> delete cache[serviceName]; <add> } <add> throw err; <ide> } finally { <ide> path.shift(); <ide> }
1
Text
Text
update router.md to improve a11y
4de984ca232d63a59e320428719e13a7161aaf37
<ide><path>docs/api-reference/next/router.md <ide> import { useRouter } from 'next/router' <ide> export default function Page() { <ide> const router = useRouter() <ide> <del> return <span onClick={() => router.push('/post/abc')}>Click me</span> <add> return <button onClick={() => router.push('/post/abc')}>Click me</button> <ide> } <ide> ``` <ide> <ide> export default function ReadMore({ post }) { <ide> const router = useRouter() <ide> <ide> return ( <del> <span <add> <button <ide> onClick={() => { <ide> router.push({ <ide> pathname: '/post/[pid]', <ide> export default function ReadMore({ post }) { <ide> }} <ide> > <ide> Click here to read more <del> </span> <add> </button> <ide> ) <ide> } <ide> ``` <ide> import { useRouter } from 'next/router' <ide> export default function Page() { <ide> const router = useRouter() <ide> <del> return <span onClick={() => router.replace('/home')}>Click me</span> <add> return <button onClick={() => router.replace('/home')}>Click me</button> <ide> } <ide> ``` <ide> <ide> import { useRouter } from 'next/router' <ide> export default function Page() { <ide> const router = useRouter() <ide> <del> return <span onClick={() => router.back()}>Click here to go back</span> <add> return <button onClick={() => router.back()}>Click here to go back</button> <ide> } <ide> ``` <ide> <ide> import { useRouter } from 'next/router' <ide> export default function Page() { <ide> const router = useRouter() <ide> <del> return <span onClick={() => router.reload()}>Click here to reload</span> <add> return <button onClick={() => router.reload()}>Click here to reload</button> <ide> } <ide> ``` <ide>
1
Javascript
Javascript
add general purpose $cachefactory service
497839f583ca3dd75583fb996bb764cbd6d7c4ac
<ide><path>angularFiles.js <ide> angularFiles = { <ide> 'src/apis.js', <ide> 'src/service/autoScroll.js', <ide> 'src/service/browser.js', <add> 'src/service/cacheFactory.js', <ide> 'src/service/compiler.js', <ide> 'src/service/cookieStore.js', <ide> 'src/service/cookies.js', <ide><path>src/AngularPublic.js <ide> function ngModule($provide, $injector) { <ide> <ide> $provide.service('$autoScroll', $AutoScrollProvider); <ide> $provide.service('$browser', $BrowserProvider); <add> $provide.service('$cacheFactory', $CacheFactoryProvider); <ide> $provide.service('$compile', $CompileProvider); <ide> $provide.service('$cookies', $CookiesProvider); <ide> $provide.service('$cookieStore', $CookieStoreProvider); <ide><path>src/service/cacheFactory.js <add>/** <add> * @ngdoc object <add> * @name angular.module.ng.$cacheFactory <add> * <add> * @description <add> * Factory that constructs cache objects. <add> * <add> * <add> * @param {string} cacheId Name or id of the newly created cache. <add> * @param {object=} options Options object that specifies the cache behavior. Properties: <add> * <add> * - `{number=}` `capacity` — turns the cache into LRU cache. <add> * <add> * @returns {object} Newly created cache object with the following set of methods: <add> * <add> * - `{string}` `id()` — Returns id or name of the cache. <add> * - `{number}` `size()` — Returns number of items currently in the cache <add> * - `{void}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache <add> * - `{(*}} `get({string} key) — Returns cached value for `key` or undefined for cache miss. <add> * - `{void}` `remove{string} key) — Removes a key-value pair from the cache. <add> * - `{void}` `removeAll() — Removes all cached values. <add> * <add> */ <add>function $CacheFactoryProvider() { <add> <add> this.$get = function() { <add> var caches = {}; <add> <add> function cacheFactory(cacheId, options) { <add> if (cacheId in caches) { <add> throw Error('cacheId ' + cacheId + ' taken'); <add> } <add> <add> var size = 0, <add> stats = extend({}, options, {id: cacheId}), <add> data = {}, <add> capacity = (options && options.capacity) || Number.MAX_VALUE, <add> lruHash = {}, <add> freshEnd = null, <add> staleEnd = null; <add> <add> return caches[cacheId] = { <add> <add> put: function(key, value) { <add> var lruEntry = lruHash[key] || (lruHash[key] = {key: key}); <add> <add> refresh(lruEntry); <add> <add> if (isUndefined(value)) return; <add> if (!(key in data)) size++; <add> data[key] = value; <add> <add> if (size > capacity) { <add> this.remove(staleEnd.key); <add> } <add> }, <add> <add> <add> get: function(key) { <add> var lruEntry = lruHash[key]; <add> <add> if (!lruEntry) return; <add> <add> refresh(lruEntry); <add> <add> return data[key]; <add> }, <add> <add> <add> remove: function(key) { <add> var lruEntry = lruHash[key]; <add> <add> if (lruEntry == freshEnd) freshEnd = lruEntry.p; <add> if (lruEntry == staleEnd) staleEnd = lruEntry.n; <add> link(lruEntry.n,lruEntry.p); <add> <add> delete lruHash[key]; <add> delete data[key]; <add> size--; <add> }, <add> <add> <add> removeAll: function() { <add> data = {}; <add> size = 0; <add> lruHash = {}; <add> freshEnd = staleEnd = null; <add> }, <add> <add> <add> destroy: function() { <add> data = null; <add> stats = null; <add> lruHash = null; <add> delete caches[cacheId]; <add> }, <add> <add> <add> info: function() { <add> return extend({}, stats, {size: size}); <add> } <add> }; <add> <add> <add> /** <add> * makes the `entry` the freshEnd of the LRU linked list <add> */ <add> function refresh(entry) { <add> if (entry != freshEnd) { <add> if (!staleEnd) { <add> staleEnd = entry; <add> } else if (staleEnd == entry) { <add> staleEnd = entry.n; <add> } <add> <add> link(entry.n, entry.p); <add> link(entry, freshEnd); <add> freshEnd = entry; <add> freshEnd.n = null; <add> } <add> } <add> <add> <add> /** <add> * bidirectionally links two entries of the LRU linked list <add> */ <add> function link(nextEntry, prevEntry) { <add> if (nextEntry != prevEntry) { <add> if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify <add> if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify <add> } <add> } <add> } <add> <add> <add> cacheFactory.info = function() { <add> var info = {}; <add> forEach(caches, function(cache, cacheId) { <add> info[cacheId] = cache.info(); <add> }); <add> return info; <add> }; <add> <add> <add> cacheFactory.get = function(cacheId) { <add> return caches[cacheId]; <add> }; <add> <add> <add> return cacheFactory; <add> }; <add>} <ide><path>test/service/cacheFactorySpec.js <add>describe('$cacheFactory', function() { <add> <add> it('should be injected', inject(function($cacheFactory) { <add> expect($cacheFactory).toBeDefined(); <add> })); <add> <add> <add> it('should return a new cache whenever called', inject(function($cacheFactory) { <add> var cache1 = $cacheFactory('cache1'); <add> var cache2 = $cacheFactory('cache2'); <add> expect(cache1).not.toEqual(cache2); <add> })); <add> <add> <add> it('should complain if the cache id is being reused', inject(function($cacheFactory) { <add> $cacheFactory('cache1'); <add> expect(function() { $cacheFactory('cache1'); }). <add> toThrow('cacheId cache1 taken'); <add> })); <add> <add> <add> describe('info', function() { <add> <add> it('should provide info about all created caches', inject(function($cacheFactory) { <add> expect($cacheFactory.info()).toEqual({}); <add> <add> var cache1 = $cacheFactory('cache1'); <add> expect($cacheFactory.info()).toEqual({cache1: {id: 'cache1', size: 0}}); <add> <add> cache1.put('foo', 'bar'); <add> expect($cacheFactory.info()).toEqual({cache1: {id: 'cache1', size: 1}}); <add> })); <add> }); <add> <add> <add> describe('get', function() { <add> <add> it('should return a cache if looked up by id', inject(function($cacheFactory) { <add> var cache1 = $cacheFactory('cache1'), <add> cache2 = $cacheFactory('cache2'); <add> <add> expect(cache1).not.toBe(cache2); <add> expect(cache1).toBe($cacheFactory.get('cache1')); <add> expect(cache2).toBe($cacheFactory.get('cache2')); <add> })); <add> }); <add> <add> describe('cache', function() { <add> var cache; <add> <add> beforeEach(inject(function($cacheFactory) { <add> cache = $cacheFactory('test'); <add> })); <add> <add> <add> describe('put, get & remove', function() { <add> <add> it('should add cache entries via add and retrieve them via get', inject(function($cacheFactory) { <add> cache.put('key1', 'bar'); <add> cache.put('key2', {bar:'baz'}); <add> <add> expect(cache.get('key2')).toEqual({bar:'baz'}); <add> expect(cache.get('key1')).toBe('bar'); <add> })); <add> <add> <add> it('should ignore put if the value is undefined', inject(function($cacheFactory) { <add> cache.put(); <add> cache.put('key1'); <add> cache.put('key2', undefined); <add> <add> expect(cache.info().size).toBe(0); <add> })); <add> <add> <add> it('should remove entries via remove', inject(function($cacheFactory) { <add> cache.put('k1', 'foo'); <add> cache.put('k2', 'bar'); <add> <add> cache.remove('k2'); <add> <add> expect(cache.get('k1')).toBe('foo'); <add> expect(cache.get('k2')).toBeUndefined(); <add> <add> cache.remove('k1'); <add> <add> expect(cache.get('k1')).toBeUndefined(); <add> expect(cache.get('k2')).toBeUndefined(); <add> })); <add> <add> <add> it('should stringify keys', inject(function($cacheFactory) { <add> cache.put('123', 'foo'); <add> cache.put(123, 'bar'); <add> <add> expect(cache.get('123')).toBe('bar'); <add> expect(cache.info().size).toBe(1); <add> <add> cache.remove(123); <add> expect(cache.info().size).toBe(0); <add> })); <add> }); <add> <add> <add> describe('info', function() { <add> <add> it('should size increment with put and decrement with remove', inject(function($cacheFactory) { <add> expect(cache.info().size).toBe(0); <add> <add> cache.put('foo', 'bar'); <add> expect(cache.info().size).toBe(1); <add> <add> cache.put('baz', 'boo'); <add> expect(cache.info().size).toBe(2); <add> <add> cache.remove('baz'); <add> expect(cache.info().size).toBe(1); <add> <add> cache.remove('foo'); <add> expect(cache.info().size).toBe(0); <add> })); <add> <add> <add> it('should return cache id', inject(function($cacheFactory) { <add> expect(cache.info().id).toBe('test'); <add> })); <add> }); <add> <add> <add> describe('removeAll', function() { <add> <add> it('should blow away all data', inject(function($cacheFactory) { <add> cache.put('id1', 1); <add> cache.put('id2', 2); <add> cache.put('id3', 3); <add> expect(cache.info().size).toBe(3); <add> <add> cache.removeAll(); <add> <add> expect(cache.info().size).toBe(0); <add> expect(cache.get('id1')).toBeUndefined(); <add> expect(cache.get('id2')).toBeUndefined(); <add> expect(cache.get('id3')).toBeUndefined(); <add> })); <add> }); <add> <add> <add> describe('destroy', function() { <add> <add> it('should make the cache unusable and remove references to it from $cacheFactory', inject(function($cacheFactory) { <add> cache.put('foo', 'bar'); <add> cache.destroy(); <add> <add> expect(function() { cache.get('foo'); } ).toThrow(); <add> expect(function() { cache.get('neverexisted'); }).toThrow(); <add> expect(function() { cache.put('foo', 'bar'); }).toThrow(); <add> <add> expect($cacheFactory.get('test')).toBeUndefined(); <add> expect($cacheFactory.info()).toEqual({}); <add> })); <add> }); <add> }); <add> <add> <add> describe('LRU cache', function() { <add> <add> it('should create cache with defined capacity', inject(function($cacheFactory) { <add> cache = $cacheFactory('cache1', {capacity: 5}); <add> expect(cache.info().size).toBe(0); <add> <add> for (var i=0; i<5; i++) { <add> cache.put('id' + i, i); <add> } <add> <add> expect(cache.info().size).toBe(5); <add> <add> cache.put('id5', 5); <add> expect(cache.info().size).toBe(5); <add> cache.put('id6', 6); <add> expect(cache.info().size).toBe(5); <add> })); <add> <add> <add> describe('eviction', function() { <add> <add> beforeEach(inject(function($cacheFactory) { <add> cache = $cacheFactory('cache1', {capacity: 2}); <add> <add> cache.put('id0', 0); <add> cache.put('id1', 1); <add> })); <add> <add> <add> it('should kick out the first entry on put', inject(function($cacheFactory) { <add> cache.put('id2', 2); <add> expect(cache.get('id0')).toBeUndefined(); <add> expect(cache.get('id1')).toBe(1); <add> expect(cache.get('id2')).toBe(2); <add> })); <add> <add> <add> it('should refresh an entry via get', inject(function($cacheFactory) { <add> cache.get('id0'); <add> cache.put('id2', 2); <add> expect(cache.get('id0')).toBe(0); <add> expect(cache.get('id1')).toBeUndefined(); <add> expect(cache.get('id2')).toBe(2); <add> })); <add> <add> <add> it('should refresh an entry via put', inject(function($cacheFactory) { <add> cache.put('id0', '00'); <add> cache.put('id2', 2); <add> expect(cache.get('id0')).toBe('00'); <add> expect(cache.get('id1')).toBeUndefined(); <add> expect(cache.get('id2')).toBe(2); <add> })); <add> <add> <add> it('should not purge an entry if another one was removed', inject(function($cacheFactory) { <add> cache.remove('id1'); <add> cache.put('id2', 2); <add> expect(cache.get('id0')).toBe(0); <add> expect(cache.get('id1')).toBeUndefined(); <add> expect(cache.get('id2')).toBe(2); <add> })); <add> <add> <add> it('should purge the next entry if the stalest one was removed', inject(function($cacheFactory) { <add> cache.remove('id0'); <add> cache.put('id2', 2); <add> cache.put('id3', 3); <add> expect(cache.get('id0')).toBeUndefined(); <add> expect(cache.get('id1')).toBeUndefined(); <add> expect(cache.get('id2')).toBe(2); <add> expect(cache.get('id3')).toBe(3); <add> })); <add> <add> <add> it('should correctly recreate the linked list if all cache entries were removed', inject(function($cacheFactory) { <add> cache.remove('id0'); <add> cache.remove('id1'); <add> cache.put('id2', 2); <add> cache.put('id3', 3); <add> cache.put('id4', 4); <add> expect(cache.get('id0')).toBeUndefined(); <add> expect(cache.get('id1')).toBeUndefined(); <add> expect(cache.get('id2')).toBeUndefined(); <add> expect(cache.get('id3')).toBe(3); <add> expect(cache.get('id4')).toBe(4); <add> })); <add> <add> <add> it('should blow away the entire cache via removeAll and start evicting when full', inject(function($cacheFactory) { <add> cache.put('id0', 0); <add> cache.put('id1', 1); <add> cache.removeAll(); <add> <add> cache.put('id2', 2); <add> cache.put('id3', 3); <add> cache.put('id4', 4); <add> <add> expect(cache.info().size).toBe(2); <add> expect(cache.get('id0')).toBeUndefined(); <add> expect(cache.get('id1')).toBeUndefined(); <add> expect(cache.get('id2')).toBeUndefined(); <add> expect(cache.get('id3')).toBe(3); <add> expect(cache.get('id4')).toBe(4); <add> })); <add> <add> <add> it('should correctly refresh and evict items if operations are chained', inject(function($cacheFactory) { <add> cache = $cacheFactory('cache2', {capacity: 3}); <add> <add> cache.put('id0', 0); //0 <add> cache.put('id1', 1); //1,0 <add> cache.put('id2', 2); //2,1,0 <add> cache.get('id0'); //0,2,1 <add> cache.put('id3', 3); //3,0,2 <add> cache.put('id0', 9); //0,3,2 <add> cache.put('id4', 4); //4,0,3 <add> <add> expect(cache.get('id3')).toBe(3); <add> expect(cache.get('id0')).toBe(9); <add> expect(cache.get('id4')).toBe(4); <add> <add> cache.remove('id0'); //4,3 <add> cache.remove('id3'); //4 <add> cache.put('id5', 5); //5,4 <add> cache.put('id6', 6); //6,5,4 <add> cache.get('id4'); //4,6,5 <add> cache.put('id7', 7); //7,4,6 <add> <add> expect(cache.get('id0')).toBeUndefined(); <add> expect(cache.get('id1')).toBeUndefined(); <add> expect(cache.get('id2')).toBeUndefined(); <add> expect(cache.get('id3')).toBeUndefined(); <add> expect(cache.get('id4')).toBe(4); <add> expect(cache.get('id5')).toBeUndefined(); <add> expect(cache.get('id6')).toBe(6); <add> expect(cache.get('id7')).toBe(7); <add> <add> cache.removeAll(); <add> cache.put('id0', 0); //0 <add> cache.put('id1', 1); //1,0 <add> cache.put('id2', 2); //2,1,0 <add> cache.put('id3', 3); //3,2,1 <add> <add> expect(cache.info().size).toBe(3); <add> expect(cache.get('id0')).toBeUndefined(); <add> expect(cache.get('id1')).toBe(1); <add> expect(cache.get('id2')).toBe(2); <add> expect(cache.get('id3')).toBe(3); <add> })); <add> }); <add> }); <add>});
4
Python
Python
update example dag for ai platform operators
b2305660f0eb55ebd31fdc7fe4e8aeed8c1f8c00
<ide><path>airflow/providers/google/cloud/example_dags/example_mlengine.py <ide> from airflow import models <ide> from airflow.operators.bash import BashOperator <ide> from airflow.providers.google.cloud.operators.mlengine import ( <del> MLEngineCreateVersionOperator, MLEngineDeleteModelOperator, MLEngineDeleteVersionOperator, <del> MLEngineListVersionsOperator, MLEngineManageModelOperator, MLEngineSetDefaultVersionOperator, <del> MLEngineStartBatchPredictionJobOperator, MLEngineStartTrainingJobOperator, <add> MLEngineCreateModelOperator, MLEngineCreateVersionOperator, MLEngineDeleteModelOperator, <add> MLEngineDeleteVersionOperator, MLEngineGetModelOperator, MLEngineListVersionsOperator, <add> MLEngineSetDefaultVersionOperator, MLEngineStartBatchPredictionJobOperator, <add> MLEngineStartTrainingJobOperator, <ide> ) <ide> from airflow.providers.google.cloud.utils import mlengine_operator_utils <ide> from airflow.utils.dates import days_ago <ide> project_id=PROJECT_ID, <ide> region="us-central1", <ide> job_id="training-job-{{ ts_nodash }}-{{ params.model_name }}", <del> runtime_version="1.14", <del> python_version="3.5", <add> runtime_version="1.15", <add> python_version="3.7", <ide> job_dir=JOB_DIR, <ide> package_uris=[TRAINER_URI], <ide> training_python_module=TRAINER_PY_MODULE, <ide> training_args=[], <ide> ) <ide> <del> create_model = MLEngineManageModelOperator( <add> create_model = MLEngineCreateModelOperator( <ide> task_id="create-model", <ide> project_id=PROJECT_ID, <del> operation='create', <ide> model={ <ide> "name": MODEL_NAME, <ide> }, <ide> ) <ide> <del> get_model = MLEngineManageModelOperator( <add> get_model = MLEngineGetModelOperator( <ide> task_id="get-model", <ide> project_id=PROJECT_ID, <del> operation="get", <del> model={ <del> "name": MODEL_NAME, <del> } <add> model_name=MODEL_NAME, <ide> ) <ide> <ide> get_model_result = BashOperator( <ide> "name": "v1", <ide> "description": "First-version", <ide> "deployment_uri": '{}/keras_export/'.format(JOB_DIR), <del> "runtime_version": "1.14", <add> "runtime_version": "1.15", <ide> "machineType": "mls1-c1-m2", <ide> "framework": "TENSORFLOW", <del> "pythonVersion": "3.5" <add> "pythonVersion": "3.7" <ide> } <ide> ) <ide> <ide> "name": "v2", <ide> "description": "Second version", <ide> "deployment_uri": SAVED_MODEL_PATH, <del> "runtime_version": "1.14", <add> "runtime_version": "1.15", <ide> "machineType": "mls1-c1-m2", <ide> "framework": "TENSORFLOW", <del> "pythonVersion": "3.5" <add> "pythonVersion": "3.7" <ide> } <ide> ) <ide> <ide> prediction = MLEngineStartBatchPredictionJobOperator( <ide> task_id="prediction", <ide> project_id=PROJECT_ID, <del> job_id="prediciton-{{ ts_nodash }}-{{ params.model_name }}", <add> job_id="prediction-{{ ts_nodash }}-{{ params.model_name }}", <ide> region="us-central1", <ide> model_name=MODEL_NAME, <ide> data_format="TEXT", <ide> def validate_err_and_count(summary: Dict) -> Dict: <ide> return summary <ide> <ide> evaluate_prediction, evaluate_summary, evaluate_validation = mlengine_operator_utils.create_evaluate_ops( <del> task_prefix="evalueate-ops", # pylint: disable=too-many-arguments <add> task_prefix="evaluate-ops", <ide> data_format="TEXT", <ide> input_paths=[PREDICTION_INPUT], <ide> prediction_path=PREDICTION_OUTPUT, <ide> metric_fn_and_keys=get_metric_fn_and_keys(), <ide> validate_fn=validate_err_and_count, <del> batch_prediction_job_id="evalueate-ops-{{ ts_nodash }}-{{ params.model_name }}", <add> batch_prediction_job_id="evaluate-ops-{{ ts_nodash }}-{{ params.model_name }}", <ide> project_id=PROJECT_ID, <ide> region="us-central1", <ide> dataflow_options={
1
Text
Text
add the "line-31" to article
53e966c37c2d562b485c755a34696e15a7b7aaa1
<ide><path>guide/english/blockchain/smart-contracts/index.md <ide> There are many other blockchain projects offering (or promising) smart contract <ide> Smart contracts in Ethereum are written using Solidity. Solidity is a contract-oriented, high-level language for implementing Smart Contracts, and targets the Ethereum Virtual Machine. One can use Remix online IDE to try writing and deploying Smart Contracts. <ide> <ide> ### Smart Contracts in Hyperledger <del>Smart contracts in Hyperledger is called chaincode, and is written in Golang programming language. <add>A Smart Contract in Hyperledger is called chaincode and is written in Golang programming language. <add>A chaincode is typically used by administrators to group related smart contracts for deployment, but can also be used for low level system programming of Fabric. <ide> <ide> ## Hello World Smart Contract <ide> ```
1
Text
Text
fix the no convenient translation of return
f1c13b8b301ca8bd24aefb837406bfab89f9038a
<ide><path>curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/introducing-else-statements.spanish.md <ide> localeTitle: Introduciendo otras declaraciones <ide> --- <ide> <ide> ## Description <del><section id="description"> Cuando una condición para una sentencia <code>if</code> es verdadera, se ejecuta el bloque de código siguiente. ¿Qué pasa cuando esa condición es falsa? Normalmente no pasaría nada. Con una sentencia <code>else</code> , se puede ejecutar un bloque de código alternativo. <blockquote> if (num&gt; 10) { <br> devuelve &quot;Más grande que 10&quot;; <br> } else { <br> devuelve &quot;10 o menos&quot;; <br> } </blockquote></section> <add><section id="description"> Cuando una condición para una sentencia <code>if</code> es verdadera, se ejecuta el bloque de código siguiente. ¿Qué pasa cuando esa condición es falsa? Normalmente no pasaría nada. Con una sentencia <code>else</code> , se puede ejecutar un bloque de código alternativo. <blockquote> if (num&gt; 10) { <br> return &quot;Más grande que 10&quot;; <br> } else { <br> return &quot;10 o menos&quot;; <br> } </blockquote></section> <ide> <ide> ## Instructions <ide> <section id="instructions"> Combine las declaraciones <code>if</code> en una sola instrucción <code>if/else</code> . </section>
1
Go
Go
use spf13/cobra for docker unpause
8ea7733a6390a67d6981888b857ab78b11c4c076
<ide><path>api/client/commands.go <ide> func (cli *DockerCli) Command(name string) func(...string) error { <ide> "stats": cli.CmdStats, <ide> "tag": cli.CmdTag, <ide> "top": cli.CmdTop, <del> "unpause": cli.CmdUnpause, <ide> "update": cli.CmdUpdate, <ide> "version": cli.CmdVersion, <ide> "wait": cli.CmdWait, <ide><path>api/client/container/unpause.go <add>package container <add> <add>import ( <add> "fmt" <add> "strings" <add> <add> "golang.org/x/net/context" <add> <add> "github.com/docker/docker/api/client" <add> "github.com/docker/docker/cli" <add> "github.com/spf13/cobra" <add>) <add> <add>type unpauseOptions struct { <add> containers []string <add>} <add> <add>// NewUnpauseCommand creats a new cobra.Command for `docker unpause` <add>func NewUnpauseCommand(dockerCli *client.DockerCli) *cobra.Command { <add> var opts unpauseOptions <add> <add> cmd := &cobra.Command{ <add> Use: "unpause CONTAINER [CONTAINER...]", <add> Short: "Unpause all processes within one or more containers", <add> Args: cli.RequiresMinArgs(1), <add> RunE: func(cmd *cobra.Command, args []string) error { <add> opts.containers = args <add> return runUnpause(dockerCli, &opts) <add> }, <add> } <add> cmd.SetFlagErrorFunc(flagErrorFunc) <add> <add> return cmd <add>} <add> <add>func runUnpause(dockerCli *client.DockerCli, opts *unpauseOptions) error { <add> ctx := context.Background() <add> <add> var errs []string <add> for _, container := range opts.containers { <add> if err := dockerCli.Client().ContainerUnpause(ctx, container); err != nil { <add> errs = append(errs, err.Error()) <add> } else { <add> fmt.Fprintf(dockerCli.Out(), "%s\n", container) <add> } <add> } <add> if len(errs) > 0 { <add> return fmt.Errorf("%s", strings.Join(errs, "\n")) <add> } <add> return nil <add>} <ide><path>api/client/unpause.go <del>package client <del> <del>import ( <del> "fmt" <del> "strings" <del> <del> "golang.org/x/net/context" <del> <del> Cli "github.com/docker/docker/cli" <del> flag "github.com/docker/docker/pkg/mflag" <del>) <del> <del>// CmdUnpause unpauses all processes within a container, for one or more containers. <del>// <del>// Usage: docker unpause CONTAINER [CONTAINER...] <del>func (cli *DockerCli) CmdUnpause(args ...string) error { <del> cmd := Cli.Subcmd("unpause", []string{"CONTAINER [CONTAINER...]"}, Cli.DockerCommands["unpause"].Description, true) <del> cmd.Require(flag.Min, 1) <del> <del> cmd.ParseFlags(args, true) <del> <del> ctx := context.Background() <del> <del> var errs []string <del> for _, name := range cmd.Args() { <del> if err := cli.client.ContainerUnpause(ctx, name); err != nil { <del> errs = append(errs, err.Error()) <del> } else { <del> fmt.Fprintf(cli.out, "%s\n", name) <del> } <del> } <del> if len(errs) > 0 { <del> return fmt.Errorf("%s", strings.Join(errs, "\n")) <del> } <del> return nil <del>} <ide><path>cli/cobraadaptor/adaptor.go <ide> func NewCobraAdaptor(clientFlags *cliflags.ClientFlags) CobraAdaptor { <ide> container.NewExportCommand(dockerCli), <ide> container.NewRunCommand(dockerCli), <ide> container.NewStopCommand(dockerCli), <add> container.NewUnpauseCommand(dockerCli), <ide> image.NewRemoveCommand(dockerCli), <ide> image.NewSearchCommand(dockerCli), <ide> volume.NewVolumeCommand(dockerCli), <ide><path>cli/usage.go <ide> var DockerCommandUsage = []Command{ <ide> {"stats", "Display a live stream of container(s) resource usage statistics"}, <ide> {"tag", "Tag an image into a repository"}, <ide> {"top", "Display the running processes of a container"}, <del> {"unpause", "Unpause all processes within a container"}, <ide> {"update", "Update configuration of one or more containers"}, <ide> {"version", "Show the Docker version information"}, <ide> {"wait", "Block until a container stops, then print its exit code"},
5
Python
Python
add sqlite hook
4069c55013975c6b3903ce67dedd80090db9543b
<ide><path>airflow/hooks/__init__.py <ide> 'postgres_hook': ['PostgresHook'], <ide> 'presto_hook': ['PrestoHook'], <ide> 'samba_hook': ['SambaHook'], <add> 'sqlite_hook': ['SqliteHook'], <ide> 'S3_hook': ['S3Hook'], <ide> } <ide> <ide><path>airflow/hooks/sqlite_hook.py <add>import logging <add> <add>import sqlite3 <add> <add>from airflow.hooks.base_hook import BaseHook <add> <add> <add>class SqliteHook(BaseHook): <add> <add> ''' <add> Interact with SQLite. <add> ''' <add> <add> def __init__( <add> self, sqlite_conn_id='sqlite_default'): <add> self.sqlite_conn_id = sqlite_conn_id <add> <add> def get_conn(self): <add> """ <add> Returns a sqlite connection object <add> """ <add> conn = self.get_connection(self.sqlite_conn_id) <add> conn = sqlite3.connect(conn.host) <add> return conn <add> <add> def get_records(self, sql): <add> ''' <add> Executes the sql and returns a set of records. <add> ''' <add> conn = self.get_conn() <add> cur = conn.cursor() <add> cur.execute(sql) <add> rows = cur.fetchall() <add> cur.close() <add> conn.close() <add> return rows <add> <add> def get_pandas_df(self, sql): <add> ''' <add> Executes the sql and returns a pandas dataframe <add> ''' <add> import pandas.io.sql as psql <add> conn = self.get_conn() <add> df = psql.read_sql(sql, con=conn) <add> conn.close() <add> return df <add> <add> def run(self, sql): <add> conn = self.get_conn() <add> cur = conn.cursor() <add> cur.execute(sql) <add> conn.commit() <add> cur.close() <add> conn.close() <add> <add> def insert_rows(self, table, rows, target_fields=None): <add> """ <add> A generic way to insert a set of tuples into a table, <add> the whole set of inserts is treated as one transaction <add> """ <add> if target_fields: <add> target_fields = ", ".join(target_fields) <add> target_fields = "({})".format(target_fields) <add> else: <add> target_fields = '' <add> conn = self.get_conn() <add> cur = conn.cursor() <add> i = 0 <add> for row in rows: <add> i += 1 <add> l = [] <add> for cell in row: <add> if isinstance(cell, basestring): <add> l.append("'" + str(cell).replace("'", "''") + "'") <add> elif cell is None: <add> l.append('NULL') <add> else: <add> l.append(str(cell)) <add> values = tuple(l) <add> sql = "INSERT INTO {0} {1} VALUES ({2});".format( <add> table, <add> target_fields, <add> ",".join(values)) <add> cur.execute(sql) <add> conn.commit() <add> conn.commit() <add> cur.close() <add> conn.close() <add> logging.info( <add> "Done loading. Loaded a total of {i} rows".format(**locals()))
2
Java
Java
recognize wildcards in media types with a suffix
7718936158434e0f658233f74c33ab72bea5d440
<ide><path>spring-web/src/main/java/org/springframework/http/MediaType.java <ide> public String getSubtype() { <ide> } <ide> <ide> /** <del> * Indicates whether the {@linkplain #getSubtype() subtype} is the wildcard character <code>&#42;</code> or not. <add> * Indicates whether the {@linkplain #getSubtype() subtype} is the wildcard character <code>&#42;</code> <add> * or the wildcard character followed by a sufiix (e.g. <code>&#42;+xml</code>), or not. <ide> * @return whether the subtype is <code>&#42;</code> <ide> */ <ide> public boolean isWildcardSubtype() { <del> return WILDCARD_TYPE.equals(subtype); <add> return WILDCARD_TYPE.equals(subtype) || subtype.startsWith("*+"); <ide> } <ide> <ide> /** <ide><path>spring-web/src/test/java/org/springframework/http/MediaTypeTests.java <ide> public void specificityComparator() throws Exception { <ide> MediaType audio07 = new MediaType("audio", "*", 0.7); <ide> MediaType audioBasicLevel = new MediaType("audio", "basic", Collections.singletonMap("level", "1")); <ide> MediaType textHtml = new MediaType("text", "html"); <add> MediaType allXml = new MediaType("application", "*+xml"); <ide> MediaType all = MediaType.ALL; <ide> <ide> Comparator<MediaType> comp = MediaType.SPECIFICITY_COMPARATOR; <ide> public void specificityComparator() throws Exception { <ide> assertTrue("Invalid comparison result", comp.compare(audioBasic, audio) < 0); <ide> assertTrue("Invalid comparison result", comp.compare(audioBasic, all) < 0); <ide> assertTrue("Invalid comparison result", comp.compare(audio, all) < 0); <add> assertTrue("Invalid comparison result", comp.compare(MediaType.APPLICATION_XHTML_XML, allXml) < 0); <ide> <ide> // unspecific to specific <ide> assertTrue("Invalid comparison result", comp.compare(audio, audioBasic) > 0); <add> assertTrue("Invalid comparison result", comp.compare(allXml, MediaType.APPLICATION_XHTML_XML) > 0); <ide> assertTrue("Invalid comparison result", comp.compare(all, audioBasic) > 0); <ide> assertTrue("Invalid comparison result", comp.compare(all, audio) > 0); <ide> <ide> public void qualityComparator() throws Exception { <ide> MediaType audio07 = new MediaType("audio", "*", 0.7); <ide> MediaType audioBasicLevel = new MediaType("audio", "basic", Collections.singletonMap("level", "1")); <ide> MediaType textHtml = new MediaType("text", "html"); <add> MediaType allXml = new MediaType("application", "*+xml"); <ide> MediaType all = MediaType.ALL; <ide> <ide> Comparator<MediaType> comp = MediaType.QUALITY_VALUE_COMPARATOR; <ide> public void qualityComparator() throws Exception { <ide> assertTrue("Invalid comparison result", comp.compare(audioBasic, audio) < 0); <ide> assertTrue("Invalid comparison result", comp.compare(audioBasic, all) < 0); <ide> assertTrue("Invalid comparison result", comp.compare(audio, all) < 0); <add> assertTrue("Invalid comparison result", comp.compare(MediaType.APPLICATION_XHTML_XML, allXml) < 0); <ide> <ide> // unspecific to specific <ide> assertTrue("Invalid comparison result", comp.compare(audio, audioBasic) > 0); <ide> assertTrue("Invalid comparison result", comp.compare(all, audioBasic) > 0); <ide> assertTrue("Invalid comparison result", comp.compare(all, audio) > 0); <add> assertTrue("Invalid comparison result", comp.compare(allXml, MediaType.APPLICATION_XHTML_XML) > 0); <ide> <ide> // qualifiers <ide> assertTrue("Invalid comparison result", comp.compare(audio, audio07) < 0); <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessorMockTests.java <ide> public void handleReturnValueNotAcceptableProduces() throws Exception { <ide> processor.handleReturnValue("Foo", returnTypeStringProduces, mavContainer, webRequest); <ide> } <ide> <add> // SPR-9841 <add> <add> @Test <add> public void handleReturnValueMediaTypeSuffix() throws Exception { <add> String body = "Foo"; <add> MediaType accepted = MediaType.APPLICATION_XHTML_XML; <add> List<MediaType> supported = Collections.singletonList(MediaType.valueOf("application/*+xml")); <add> <add> servletRequest.addHeader("Accept", accepted); <add> <add> expect(messageConverter.canWrite(String.class, null)).andReturn(true); <add> expect(messageConverter.getSupportedMediaTypes()).andReturn(supported); <add> expect(messageConverter.canWrite(String.class, accepted)).andReturn(true); <add> messageConverter.write(eq(body), eq(accepted), isA(HttpOutputMessage.class)); <add> replay(messageConverter); <add> <add> processor.handleReturnValue(body, returnTypeStringProduces, mavContainer, webRequest); <add> <add> assertTrue(mavContainer.isRequestHandled()); <add> verify(messageConverter); <add> } <add> <ide> // SPR-9160 <ide> <ide> @Test <ide> public void handleReturnValueString() throws Exception { <ide> assertEquals("Foo", servletResponse.getContentAsString()); <ide> } <ide> <add> <ide> @ResponseBody <ide> public String handle1(@RequestBody String s, int i) { <ide> return s;
3
Java
Java
remove quality parameter from selected media type
75fd391fc716456bbd2448f60e691b8f588c70de
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/HandlerResultHandlerSupport.java <ide> else if (mediaType.isPresentIn(ALL_APPLICATION_MEDIA_TYPES)) { <ide> } <ide> <ide> if (selected != null) { <add> selected = selected.removeQualityValue(); <ide> if (logger.isDebugEnabled()) { <ide> logger.debug("Using '" + selected + "' given " + acceptableTypes + <ide> " and supported " + producibleTypes); <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/HandlerResultHandlerTests.java <ide> /* <del> * Copyright 2002-2019 the original author or authors. <add> * Copyright 2002-2020 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public class HandlerResultHandlerTests { <ide> <ide> <ide> @Test <del> public void usesContentTypeResolver() throws Exception { <add> void usesContentTypeResolver() { <ide> TestResultHandler resultHandler = new TestResultHandler(new FixedContentTypeResolver(IMAGE_GIF)); <ide> List<MediaType> mediaTypes = Arrays.asList(IMAGE_JPEG, IMAGE_GIF, IMAGE_PNG); <ide> MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/path")); <ide> public void usesContentTypeResolver() throws Exception { <ide> } <ide> <ide> @Test <del> public void producibleMediaTypesRequestAttribute() throws Exception { <add> void producibleMediaTypesRequestAttribute() { <ide> MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/path")); <ide> exchange.getAttributes().put(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, Collections.singleton(IMAGE_GIF)); <ide> <ide> public void producibleMediaTypesRequestAttribute() throws Exception { <ide> } <ide> <ide> @Test // SPR-9160 <del> public void sortsByQuality() throws Exception { <add> void sortsByQuality() { <ide> MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/path") <ide> .header("Accept", "text/plain; q=0.5, application/json")); <ide> <ide> public void sortsByQuality() throws Exception { <ide> } <ide> <ide> @Test <del> public void charsetFromAcceptHeader() throws Exception { <add> void charsetFromAcceptHeader() { <ide> MediaType text8859 = MediaType.parseMediaType("text/plain;charset=ISO-8859-1"); <ide> MediaType textUtf8 = MediaType.parseMediaType("text/plain;charset=UTF-8"); <ide> MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/path").accept(text8859)); <ide> public void charsetFromAcceptHeader() throws Exception { <ide> } <ide> <ide> @Test // SPR-12894 <del> public void noConcreteMediaType() throws Exception { <add> void noConcreteMediaType() { <ide> List<MediaType> producible = Collections.singletonList(ALL); <ide> MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/path")); <ide> MediaType actual = this.resultHandler.selectMediaType(exchange, () -> producible); <ide> <ide> assertThat(actual).isEqualTo(APPLICATION_OCTET_STREAM); <ide> } <ide> <add> @Test <add> void removeQualityParameter() { <add> MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/path") <add> .header("Accept", "text/plain; q=0.5")); <add> <add> List<MediaType> mediaTypes = Arrays.asList(APPLICATION_JSON, TEXT_PLAIN); <add> MediaType actual = this.resultHandler.selectMediaType(exchange, () -> mediaTypes); <add> <add> assertThat(actual).isEqualTo(TEXT_PLAIN); <add> } <add> <ide> <ide> @SuppressWarnings("WeakerAccess") <ide> private static class TestResultHandler extends HandlerResultHandlerSupport {
2
PHP
PHP
remove unused vars and assigments
936c6c7f711e7099ef2ed5f414622987c15b2765
<ide><path>src/Cache/CacheRegistry.php <ide> protected function _throwMissingClassError(string $class, ?string $plugin): void <ide> */ <ide> protected function _create($class, string $alias, array $config): CacheEngine <ide> { <del> $instance = null; <ide> if (is_object($class)) { <ide> $instance = $class; <ide> } else { <ide><path>src/Command/HelpCommand.php <ide> protected function asText(ConsoleIo $io, ArrayIterator $commands): void <ide> $invert[$class][] = $name; <ide> } <ide> $grouped = []; <del> $appNamespace = Configure::read('App.namespace'); <ide> $plugins = Plugin::loaded(); <ide> foreach ($invert as $class => $names) { <ide> preg_match('/^(.+)\\\\(Command|Shell)\\\\/', $class, $matches); <ide><path>src/Datasource/ModelAwareTrait.php <ide> public function loadModel(?string $modelClass = null, ?string $modelType = null) <ide> $modelType = $this->getModelType(); <ide> } <ide> <del> $alias = null; <ide> $options = []; <ide> if (strpos($modelClass, '\\') === false) { <ide> [, $alias] = pluginSplit($modelClass, true); <ide><path>src/Error/ExceptionRenderer.php <ide> protected function _getController(): Controller <ide> } <ide> <ide> $response = new Response(); <del> $controller = null; <ide> <ide> try { <ide> $class = null; <ide> protected function _getController(): Controller <ide> /** @var \Cake\Controller\Controller $controller */ <ide> $controller = new $class($request, $response); <ide> $controller->startupProcess(); <del> $startup = true; <ide> } catch (Throwable $e) { <del> $startup = false; <add> } <add> <add> if (!isset($controller)) { <add> return new Controller($request, $response); <ide> } <ide> <ide> // Retry RequestHandler, as another aspect of startupProcess() <ide> // could have failed. Ignore any exceptions out of startup, as <ide> // there could be userland input data parsers. <del> if ($startup === false && !empty($controller) && isset($controller->RequestHandler)) { <add> if (isset($controller->RequestHandler)) { <ide> try { <ide> $event = new Event('Controller.startup', $controller); <ide> $controller->RequestHandler->startup($event); <ide> } catch (Throwable $e) { <ide> } <ide> } <del> if (empty($controller)) { <del> $controller = new Controller($request, $response); <del> } <ide> <ide> return $controller; <ide> } <ide><path>src/Http/Client/Auth/Oauth.php <ide> public function authentication(Request $request, array $credentials): Request <ide> $credentials['method'] = 'hmac-sha1'; <ide> } <ide> <del> $value = ''; <ide> $credentials['method'] = strtoupper($credentials['method']); <ide> <del> $value = null; <ide> switch ($credentials['method']) { <ide> case 'HMAC-SHA1': <ide> $hasKeys = isset( <ide><path>src/I18n/DateFormatTrait.php <ide> public function i18nFormat($format = null, $timezone = null, $locale = null) <ide> */ <ide> protected function _formatObject($date, $format, ?string $locale): string <ide> { <del> $pattern = $dateFormat = $timeFormat = $calendar = null; <add> $pattern = $timeFormat = null; <ide> <ide> if (is_array($format)) { <ide> [$dateFormat, $timeFormat] = $format; <ide><path>src/Log/Engine/FileLog.php <ide> public function log($level, $message, array $context = []): void <ide> } <ide> <ide> $exists = file_exists($pathname); <del> $result = file_put_contents($pathname, $output, FILE_APPEND); <add> file_put_contents($pathname, $output, FILE_APPEND); <ide> static $selfError = false; <ide> <ide> if (!$selfError && !$exists && !chmod($pathname, (int)$mask)) { <ide><path>src/Mailer/TransportRegistry.php <ide> protected function _throwMissingClassError(string $class, ?string $plugin): void <ide> */ <ide> protected function _create($class, string $alias, array $config): AbstractTransport <ide> { <del> $instance = null; <ide> if (is_object($class)) { <ide> $instance = $class; <ide> } else { <ide><path>src/ORM/Association/Loader/SelectLoader.php <ide> protected function _addFilteringJoin(Query $query, $key, $subquery): Query <ide> } <ide> $subquery->select($filter, true); <ide> <del> $conditions = null; <ide> if (is_array($key)) { <ide> $conditions = $this->_createTupleCondition($query, $key, $filter, '='); <ide> } else { <ide><path>src/ORM/Marshaller.php <ide> protected function _belongsToMany(BelongsToMany $assoc, array $data, array $opti <ide> $primaryKey = array_flip((array)$target->getPrimaryKey()); <ide> $records = $conditions = []; <ide> $primaryCount = count($primaryKey); <del> $conditions = []; <ide> <ide> foreach ($data as $i => $row) { <ide> if (!is_array($row)) { <ide><path>src/Routing/Router.php <ide> public static function url($url = null, bool $full = false): string <ide> 'action' => 'index', <ide> '_ext' => null, <ide> ]; <del> $here = $output = $frag = null; <add> $here = $frag = null; <ide> <ide> $context = static::$_requestContext; <ide> // In 4.x this should be replaced with state injected via setRequestContext <ide><path>src/TestSuite/IntegrationTestTrait.php <ide> trait IntegrationTestTrait <ide> */ <ide> protected $_disableRouterReload = false; <ide> <del> /** <del> * Auto-detect if the HTTP middleware stack should be used. <del> * <del> * @before <del> * @return void <del> */ <del> public function setupServer(): void <del> { <del> $namespace = Configure::read('App.namespace'); <del> } <del> <ide> /** <ide> * Clears the state used for requests. <ide> * <ide><path>src/Validation/Validator.php <ide> public function getNotEmptyMessage(string $field): ?string <ide> $defaultMessage = __d('cake', 'This field cannot be left empty'); <ide> } <ide> <del> $notBlankMessage = null; <ide> foreach ($this->_fields[$field] as $rule) { <ide> if ($rule->get('rule') === 'notBlank' && $rule->get('message')) { <ide> return $rule->get('message'); <ide><path>src/View/Form/EntityContext.php <ide> protected function leafEntity($path = null) <ide> } <ide> <ide> $len = count($path); <del> $last = $len - 1; <ide> $leafEntity = $entity; <ide> for ($i = 0; $i < $len; $i++) { <ide> $prop = $path[$i]; <ide><path>src/View/View.php <ide> protected function _elementCache(string $name, array $data, array $options): arr <ide> return $cache; <ide> } <ide> <del> $plugin = null; <ide> [$plugin, $name] = $this->pluginSplit($name); <ide> <ide> $underscored = null;
15
Javascript
Javascript
use promises to track completion of decoding
683f64d54f7724d75ad919ed00db6306c557d90e
<ide><path>src/evaluator.js <ide> var PartialEvaluator = (function partialEvaluator() { <ide> } <ide> <ide> fn = 'paintImageXObject'; <del> var imageObj = new PDFImage(xref, resources, image, inline, handler); <ide> <del> imageObj.ready((function() { <del> return function(data) { <add> PDFImage.buildImage(function(imageObj) { <ide> var imgData = { <ide> width: w, <ide> height: h, <ide> var PartialEvaluator = (function partialEvaluator() { <ide> var pixels = imgData.data; <ide> imageObj.fillRgbaBuffer(pixels, imageObj.decode); <ide> handler.send('obj', [objId, 'Image', imgData]); <del> }; <del> })(objId)); <add> }, handler, xref, resources, image, inline); <ide> } <ide> <ide> uniquePrefix = uniquePrefix || ''; <ide><path>src/image.js <ide> 'use strict'; <ide> <ide> var PDFImage = (function pdfImage() { <del> function constructor(xref, res, image, inline, handler) { <add> /** <add> * Decode the image in the main thread if it supported. Resovles the promise <add> * when the image data is ready. <add> */ <add> function handleImageData(handler, xref, res, image, promise) { <add> if (image instanceof JpegStream && image.isNative) { <add> // For natively supported jpegs send them to the main thread for decoding. <add> var dict = image.dict; <add> var colorSpace = dict.get('ColorSpace', 'CS'); <add> colorSpace = ColorSpace.parse(colorSpace, xref, res); <add> var numComps = colorSpace.numComps; <add> handler.send('jpeg_decode', [image.getIR(), numComps], function(message) { <add> var data = message.data; <add> var stream = new Stream(data, 0, data.length, image.dict); <add> promise.resolve(stream); <add> }); <add> } else { <add> promise.resolve(image); <add> } <add> } <add> function constructor(xref, res, image, inline, smask) { <ide> this.image = image; <del> this.imageReady = true; <del> this.smaskReady = true; <del> this.callbacks = []; <ide> <ide> if (image.getParams) { <ide> // JPX/JPEG2000 streams directly contain bits per component <ide> var PDFImage = (function pdfImage() { <ide> this.decode = dict.get('Decode', 'D'); <ide> <ide> var mask = xref.fetchIfRef(dict.get('Mask')); <del> var smask = xref.fetchIfRef(dict.get('SMask')); <ide> <ide> if (mask) { <ide> TODO('masked images'); <ide> } else if (smask) { <del> this.smaskReady = false; <del> this.smask = new PDFImage(xref, res, smask, false, handler); <del> this.smask.ready(function() { <del> this.smaskReady = true; <del> if (this.isReady()) <del> this.fireReady(); <del> }.bind(this)); <del> } <del> <del> if (image instanceof JpegStream && image.isNative) { <del> this.imageReady = false; <del> handler.send('jpeg_decode', [image.getIR(), this.numComps], function(message) { <del> var data = message.data; <del> this.image = new Stream(data, 0, data.length); <del> this.imageReady = true; <del> if (this.isReady()) <del> this.fireReady(); <del> }.bind(this)); <add> this.smask = new PDFImage(xref, res, smask, false); <ide> } <ide> } <add> /** <add> * Handles processing of image data and calls the callback with an argument <add> * of a PDFImage when the image is ready to be used. <add> */ <add> constructor.buildImage = function buildImage(callback, handler, xref, res, <add> image, inline) { <add> var promise = new Promise(); <add> var smaskPromise = new Promise(); <add> var promises = [promise, smaskPromise]; <add> // The image data and smask data may not be ready yet, wait till both are <add> // resolved. <add> Promise.all(promises).then(function(results) { <add> var image = new PDFImage(xref, res, results[0], inline, results[1]); <add> callback(image); <add> }); <add> <add> handleImageData(handler, xref, res, image, promise); <add> <add> var smask = xref.fetchIfRef(image.dict.get('SMask')); <add> if (smask) <add> handleImageData(handler, xref, res, smask, smaskPromise); <add> else <add> smaskPromise.resolve(null); <add> }; <ide> <ide> constructor.prototype = { <ide> getComponents: function getComponents(buffer, decodeMap) { <ide> var PDFImage = (function pdfImage() { <ide> var buf = new Uint8Array(width * height); <ide> <ide> if (smask) { <del> if (!smask.isReady()) <del> error('Soft mask is not ready.'); <ide> var sw = smask.width; <ide> var sh = smask.height; <ide> if (sw != this.width || sh != this.height) <ide> var PDFImage = (function pdfImage() { <ide> buffer[i] = comps[i]; <ide> }, <ide> getImageBytes: function getImageBytes(length) { <del> if (!this.isReady()) <del> error('Image is not ready to be read.'); <ide> this.image.reset(); <ide> return this.image.getBytes(length); <del> }, <del> isReady: function isReady() { <del> return this.imageReady && this.smaskReady; <del> }, <del> fireReady: function fireReady() { <del> for (var i = 0; i < this.callbacks.length; ++i) <del> this.callbacks[i](); <del> this.callbacks = []; <del> }, <del> ready: function ready(callback) { <del> this.callbacks.push(callback); <del> if (this.isReady()) <del> this.fireReady(); <ide> } <ide> }; <ide> return constructor; <ide><path>src/util.js <ide> var Promise = (function promise() { <ide> } <ide> this.callbacks = []; <ide> }; <del> <add> /** <add> * Builds a promise that is resolved when all the passed in promises are <add> * resolved. <add> * @param Array promises <add> * @return Promise <add> */ <add> Promise.all = function(promises) { <add> var deferred = new Promise(); <add> var unresolved = promises.length; <add> var results = []; <add> if (unresolved === 0) { <add> deferred.resolve(results); <add> return deferred; <add> } <add> for (var i = 0; i < unresolved; ++i) { <add> var promise = promises[i]; <add> promise.then((function(i) { <add> return function(value) { <add> results[i] = value; <add> unresolved--; <add> if (unresolved === 0) <add> deferred.resolve(results); <add> }; <add> })(i)); <add> } <add> return deferred; <add> }; <ide> Promise.prototype = { <ide> hasData: false, <ide>
3
Javascript
Javascript
use isfinite in place of redundant isnumeric
3689963909880ed832ac17eabf7b9260927a68d8
<ide><path>src/css.js <ide> jQuery.extend( { <ide> // Make numeric if forced or a qualifier was provided and val looks numeric <ide> if ( extra === "" || extra ) { <ide> num = parseFloat( val ); <del> return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; <add> return extra === true || isFinite( num ) ? num || 0 : val; <ide> } <ide> return val; <ide> }
1
Javascript
Javascript
remove console.logs from previous commit again
6e9306afd2bedec0cb9f4a12c23ff4cb072653b8
<ide><path>fonts.js <ide> var FontLoader = { <ide> waitingStr: [], <ide> <ide> bind: function(fonts, callback) { <del> console.log("requesting fonts", fonts[0].properties.loadedName, fonts[0].name); <del> <ide> var rules = [], names = []; <ide> <ide> for (var i = 0; i < fonts.length; i++) { <ide><path>pdf.js <ide> var CanvasGraphics = (function() { <ide> // If the promise isn't resolved yet, add the continueCallback <ide> // to the promise and bail out. <ide> if (!promise.isResolved) { <del> console.log("depending on obj", depObjId); <ide> promise.then(continueCallback); <ide> return i; <ide> } <ide><path>worker.js <ide> var Promise = (function() { <ide> <ide> Promise.prototype = { <ide> resolve: function(data) { <del> console.log("resolve", this.name); <del> <ide> if (this.isResolved) { <ide> throw "A Promise can be resolved only once"; <ide> } <ide> var WorkerPDFDoc = (function() { <ide> var file = data[3]; <ide> var properties = data[4]; <ide> <del> console.log("got new font", name); <del> <ide> var font = { <ide> name: name, <ide> file: file,
3
Python
Python
add doc to osxbuild script
1006c2275077597ef9c510ccf8e0bee44ed93d71
<ide><path>tools/osxbuild/build.py <ide> <ide> This is a simple script, most of the heavy lifting is done in bdist_mpkg. <ide> <add>To run this script: 'python build.py' <add> <ide> Requires a svn version of numpy is installed, svn is used to revert <ide> file changes made to the docs for the end-user install. Installer is <ide> built using sudo so file permissions are correct when installed on
1
Ruby
Ruby
use a gentler disconnect
0ae187961c75c44ea418f44ce0c09f78cdf520ff
<ide><path>actioncable/test/client_test.rb <ide> def test_disappearing_client <ide> c.send_message command: 'subscribe', identifier: JSON.dump(channel: 'EchoChannel') <ide> assert_equal({"identifier"=>"{\"channel\":\"EchoChannel\"}", "type"=>"confirm_subscription"}, c.read_message) <ide> c.send_message command: 'message', identifier: JSON.dump(channel: 'EchoChannel'), data: JSON.dump(action: 'delay', message: 'hello') <del> c.close! # disappear before write <add> c.close # disappear before write <ide> <ide> c = faye_client(port) <ide> c.send_message command: 'subscribe', identifier: JSON.dump(channel: 'EchoChannel') <ide> assert_equal({"identifier"=>"{\"channel\":\"EchoChannel\"}", "type"=>"confirm_subscription"}, c.read_message) <ide> c.send_message command: 'message', identifier: JSON.dump(channel: 'EchoChannel'), data: JSON.dump(action: 'ding', message: 'hello') <ide> assert_equal({"identifier"=>'{"channel":"EchoChannel"}', "message"=>{"dong"=>"hello"}}, c.read_message) <del> c.close! # disappear before read <add> c.close # disappear before read <ide> end <ide> end <ide> end
1
Mixed
Ruby
log the sql that is actually sent to the database
6fb5f6f3d69662cc55a086f84f9caaca3eec1515
<ide><path>activerecord/CHANGELOG.md <add>* Log the sql that is actually sent to the database. <add> <add> If I have a query that produces sql <add> `WHERE "users"."name" = 'a b'` then in the log all the <add> whitespace is being squeezed. So the sql that is printed in the <add> log is `WHERE "users"."name" = 'a b'`. <add> <add> Do not squeeze whitespace out of sql queries. Fixes #10982. <add> <add> *Neeraj Singh* <add> <ide> * Do not load all child records for inverse case. <ide> <ide> currently `post.comments.find(Comment.first.id)` would load all <ide><path>activerecord/lib/active_record/log_subscriber.rb <ide> def sql(event) <ide> return if IGNORE_PAYLOAD_NAMES.include?(payload[:name]) <ide> <ide> name = "#{payload[:name]} (#{event.duration.round(1)}ms)" <del> sql = payload[:sql].squeeze(' ') <add> sql = payload[:sql] <ide> binds = nil <ide> <ide> unless (payload[:binds] || []).empty? <ide><path>activerecord/test/cases/log_subscriber_test.rb <ide> def test_schema_statements_are_ignored <ide> assert_equal 2, logger.debugs.length <ide> end <ide> <add> def test_sql_statements_are_not_squeezed <add> event = Struct.new(:duration, :payload) <add> logger = TestDebugLogSubscriber.new <add> logger.sql(event.new(0, sql: 'ruby rails')) <add> assert_match(/ruby rails/, logger.debugs.first) <add> end <add> <ide> def test_ignore_binds_payload_with_nil_column <ide> event = Struct.new(:duration, :payload) <ide>
3
Javascript
Javascript
put package name in qunit header
5b6b584068404b8cd230d88bf390d551ae717990
<ide><path>packages/qunit/lib/qunit-runner.js <ide> if (!packageName) { <ide> <ide> QUnit.config.autostart = false; <ide> QUnit.onload(); <add> $('h1 > a').text(packageName); <ide> <ide> QUnit.jsDump.setParser('object', function(obj) { <ide> return obj.toString();
1
Javascript
Javascript
improve test coverage
ebd1f5ddb0da7e3626b56614e2b5723debadd839
<ide><path>packages/react-events/src/dom/Press.js <ide> type PressEvent = {| <ide> shiftKey: boolean, <ide> |}; <ide> <add>const hasPointerEvents = <add> typeof window !== 'undefined' && window.PointerEvent !== undefined; <add> <ide> const isMac = <ide> typeof window !== 'undefined' && window.navigator != null <ide> ? /^Mac/.test(window.navigator.platform) <ide> : false; <add> <ide> const DEFAULT_PRESS_RETENTION_OFFSET = { <ide> bottom: 20, <ide> top: 20, <ide> left: 20, <ide> right: 20, <ide> }; <ide> <del>const targetEventTypes = [ <del> 'keydown_active', <del> // We need to preventDefault on pointerdown for mouse/pen events <del> // that are in hit target area but not the element area. <del> 'pointerdown_active', <del> 'click_active', <del>]; <del>const rootEventTypes = [ <del> 'click', <del> 'keyup', <del> 'pointerup', <del> 'pointermove', <del> 'scroll', <del> 'pointercancel', <del> // We listen to this here so stopPropagation can <del> // block other mouseup events used internally <del> 'mouseup_active', <del> 'touchend', <del>]; <del> <del>// If PointerEvents is not supported (e.g., Safari), also listen to touch and mouse events. <del>if (typeof window !== 'undefined' && window.PointerEvent === undefined) { <del> targetEventTypes.push('touchstart', 'mousedown'); <del> rootEventTypes.push( <del> 'mousemove', <del> 'touchmove', <del> 'touchcancel', <del> // Used as a 'cancel' signal for mouse interactions <del> 'dragstart', <del> ); <del>} <add>const targetEventTypes = hasPointerEvents <add> ? [ <add> 'keydown_active', <add> // We need to preventDefault on pointerdown for mouse/pen events <add> // that are in hit target area but not the element area. <add> 'pointerdown_active', <add> 'click_active', <add> ] <add> : ['keydown_active', 'touchstart', 'mousedown', 'click_active']; <add> <add>const rootEventTypes = hasPointerEvents <add> ? ['pointerup', 'pointermove', 'pointercancel', 'click', 'keyup', 'scroll'] <add> : [ <add> 'click', <add> 'keyup', <add> 'scroll', <add> 'mousemove', <add> 'touchmove', <add> 'touchcancel', <add> // Used as a 'cancel' signal for mouse interactions <add> 'dragstart', <add> // We listen to this here so stopPropagation can <add> // block other mouseup events used internally <add> 'mouseup_active', <add> 'touchend', <add> ]; <ide> <ide> function isFunction(obj): boolean { <ide> return typeof obj === 'function'; <ide> const pressResponderImpl = { <ide> } <ide> <ide> state.shouldPreventClick = false; <del> if (isPointerEvent || isTouchEvent) { <add> if (isTouchEvent) { <ide> state.ignoreEmulatedMouseEvents = true; <ide> } else if (isKeyboardEvent) { <ide> // Ignore unrelated key events <ide> const pressResponderImpl = { <ide> if (state.isPressWithinResponderRegion) { <ide> if (isPressed) { <ide> const onPressMove = props.onPressMove; <add> <ide> if (isFunction(onPressMove)) { <ide> dispatchEvent( <ide> event, <ide> const pressResponderImpl = { <ide> ); <ide> } <ide> } <add> <ide> if (state.isPressWithinResponderRegion && button !== 1) { <ide> dispatchEvent( <ide> event, <ide><path>packages/react-events/src/dom/__tests__/Focus-test.internal.js <ide> import { <ide> keydown, <ide> setPointerEvent, <ide> platform, <del> dispatchPointerPressDown, <del> dispatchPointerPressRelease, <add> dispatchPointerDown, <add> dispatchPointerUp, <ide> } from '../test-utils'; <ide> <ide> let React; <ide> describe.each(table)('Focus responder', hasPointerEvents => { <ide> <ide> it('is called with the correct pointerType: mouse', () => { <ide> const target = ref.current; <del> dispatchPointerPressDown(target, {pointerType: 'mouse'}); <del> dispatchPointerPressRelease(target, {pointerType: 'mouse'}); <add> dispatchPointerDown(target, {pointerType: 'mouse'}); <add> dispatchPointerUp(target, {pointerType: 'mouse'}); <ide> expect(onFocus).toHaveBeenCalledTimes(1); <ide> expect(onFocus).toHaveBeenCalledWith( <ide> expect.objectContaining({pointerType: 'mouse'}), <ide> describe.each(table)('Focus responder', hasPointerEvents => { <ide> <ide> it('is called with the correct pointerType: touch', () => { <ide> const target = ref.current; <del> dispatchPointerPressDown(target, {pointerType: 'touch'}); <del> dispatchPointerPressRelease(target, {pointerType: 'touch'}); <add> dispatchPointerDown(target, {pointerType: 'touch'}); <add> dispatchPointerUp(target, {pointerType: 'touch'}); <ide> expect(onFocus).toHaveBeenCalledTimes(1); <ide> expect(onFocus).toHaveBeenCalledWith( <ide> expect.objectContaining({pointerType: 'touch'}), <ide> describe.each(table)('Focus responder', hasPointerEvents => { <ide> if (hasPointerEvents) { <ide> it('is called with the correct pointerType: pen', () => { <ide> const target = ref.current; <del> dispatchPointerPressDown(target, {pointerType: 'pen'}); <del> dispatchPointerPressRelease(target, {pointerType: 'pen'}); <add> dispatchPointerDown(target, {pointerType: 'pen'}); <add> dispatchPointerUp(target, {pointerType: 'pen'}); <ide> expect(onFocus).toHaveBeenCalledTimes(1); <ide> expect(onFocus).toHaveBeenCalledWith( <ide> expect.objectContaining({pointerType: 'pen'}), <ide> describe.each(table)('Focus responder', hasPointerEvents => { <ide> expect(onFocusVisibleChange).toHaveBeenCalledTimes(1); <ide> expect(onFocusVisibleChange).toHaveBeenCalledWith(true); <ide> // then use pointer on the target, focus should no longer be visible <del> dispatchPointerPressDown(target); <add> dispatchPointerDown(target); <ide> expect(onFocusVisibleChange).toHaveBeenCalledTimes(2); <ide> expect(onFocusVisibleChange).toHaveBeenCalledWith(false); <ide> // onFocusVisibleChange should not be called again <ide> describe.each(table)('Focus responder', hasPointerEvents => { <ide> <ide> it('is not called after "focus" and "blur" events without keyboard', () => { <ide> const target = ref.current; <del> dispatchPointerPressDown(target); <del> dispatchPointerPressRelease(target); <del> dispatchPointerPressDown(container); <add> dispatchPointerDown(target); <add> dispatchPointerUp(target); <add> dispatchPointerDown(container); <ide> target.dispatchEvent(blur({relatedTarget: container})); <ide> expect(onFocusVisibleChange).toHaveBeenCalledTimes(0); <ide> }); <ide><path>packages/react-events/src/dom/__tests__/FocusWithin-test.internal.js <ide> import { <ide> focus, <ide> keydown, <ide> setPointerEvent, <del> dispatchPointerPressDown, <del> dispatchPointerPressRelease, <add> dispatchPointerDown, <add> dispatchPointerUp, <ide> } from '../test-utils'; <ide> <ide> let React; <ide> describe.each(table)('FocusWithin responder', hasPointerEvents => { <ide> expect(onFocusWithinVisibleChange).toHaveBeenCalledTimes(1); <ide> expect(onFocusWithinVisibleChange).toHaveBeenCalledWith(true); <ide> // then use pointer on the next target, focus should no longer be visible <del> dispatchPointerPressDown(innerTarget2); <add> dispatchPointerDown(innerTarget2); <ide> innerTarget1.dispatchEvent(blur({relatedTarget: innerTarget2})); <ide> innerTarget2.dispatchEvent(focus()); <ide> expect(onFocusWithinVisibleChange).toHaveBeenCalledTimes(2); <ide> describe.each(table)('FocusWithin responder', hasPointerEvents => { <ide> expect(onFocusWithinVisibleChange).toHaveBeenCalledTimes(3); <ide> expect(onFocusWithinVisibleChange).toHaveBeenCalledWith(true); <ide> // then use pointer on the target, focus should no longer be visible <del> dispatchPointerPressDown(innerTarget1); <add> dispatchPointerDown(innerTarget1); <ide> expect(onFocusWithinVisibleChange).toHaveBeenCalledTimes(4); <ide> expect(onFocusWithinVisibleChange).toHaveBeenCalledWith(false); <ide> // onFocusVisibleChange should not be called again <ide> describe.each(table)('FocusWithin responder', hasPointerEvents => { <ide> <ide> it('is not called after "focus" and "blur" events without keyboard', () => { <ide> const innerTarget = innerRef.current; <del> dispatchPointerPressDown(innerTarget); <del> dispatchPointerPressRelease(innerTarget); <add> dispatchPointerDown(innerTarget); <add> dispatchPointerUp(innerTarget); <ide> innerTarget.dispatchEvent(blur({relatedTarget: container})); <ide> expect(onFocusWithinVisibleChange).toHaveBeenCalledTimes(0); <ide> }); <ide><path>packages/react-events/src/dom/__tests__/Hover-test.internal.js <ide> describe.each(table)('Hover responder', hasPointerEvents => { <ide> <ide> const target = ref.current; <ide> dispatchPointerHoverEnter(target); <del> dispatchPointerHoverMove(target, {from: {x: 0, y: 0}, to: {x: 1, y: 1}}); <add> dispatchPointerHoverMove(target, {x: 0, y: 0}); <add> dispatchPointerHoverMove(target, {x: 1, y: 1}); <ide> expect(onHoverMove).toHaveBeenCalledTimes(2); <ide> expect(onHoverMove).toHaveBeenCalledWith( <ide> expect.objectContaining({type: 'hovermove'}), <ide> describe.each(table)('Hover responder', hasPointerEvents => { <ide> const target = ref.current; <ide> <ide> dispatchPointerHoverEnter(target, {x: 10, y: 10}); <del> dispatchPointerHoverMove(target, { <del> from: {x: 10, y: 10}, <del> to: {x: 20, y: 20}, <del> }); <add> dispatchPointerHoverMove(target, {x: 10, y: 10}); <add> dispatchPointerHoverMove(target, {x: 20, y: 20}); <ide> dispatchPointerHoverExit(target, {x: 20, y: 20}); <ide> <ide> expect(eventLog).toEqual([ <ide><path>packages/react-events/src/dom/__tests__/Press-test.internal.js <ide> <ide> 'use strict'; <ide> <add>import { <add> click, <add> dispatchPointerCancel, <add> dispatchPointerDown, <add> dispatchPointerUp, <add> dispatchPointerHoverMove, <add> dispatchPointerMove, <add> keydown, <add> keyup, <add> scroll, <add> pointerdown, <add> pointerup, <add> setPointerEvent, <add>} from '../test-utils'; <add> <ide> let React; <ide> let ReactFeatureFlags; <ide> let ReactDOM; <ide> let PressResponder; <ide> let usePressResponder; <ide> let Scheduler; <ide> <del>const createEvent = (type, data) => { <del> const event = document.createEvent('CustomEvent'); <del> event.initCustomEvent(type, true, true); <del> if (data != null) { <del> Object.entries(data).forEach(([key, value]) => { <del> event[key] = value; <del> }); <del> } <del> return event; <del>}; <del> <del>function createTouchEvent(type, id, data) { <del> return createEvent(type, { <del> changedTouches: [ <del> { <del> ...data, <del> identifier: id, <del> }, <del> ], <del> targetTouches: [ <del> { <del> ...data, <del> identifier: id, <del> }, <del> ], <del> }); <del>} <del> <del>const createKeyboardEvent = (type, data) => { <del> return createEvent(type, data); <del>}; <del> <del>function init() { <add>function initializeModules(hasPointerEvents) { <add> jest.resetModules(); <add> setPointerEvent(hasPointerEvents); <ide> ReactFeatureFlags = require('shared/ReactFeatureFlags'); <ide> ReactFeatureFlags.enableFlareAPI = true; <ide> React = require('react'); <ide> function init() { <ide> Scheduler = require('scheduler'); <ide> } <ide> <del>describe('Event responder: Press', () => { <add>function removePressMoveStrings(eventString) { <add> if (eventString === 'onPressMove') { <add> return false; <add> } <add> return true; <add>} <add> <add>const forcePointerEvents = true; <add>const environmentTable = [[forcePointerEvents], [!forcePointerEvents]]; <add> <add>const pointerTypesTable = [['mouse'], ['touch']]; <add> <add>describe.each(environmentTable)('Press responder', hasPointerEvents => { <ide> let container; <ide> <ide> beforeEach(() => { <del> jest.resetModules(); <del> init(); <add> initializeModules(hasPointerEvents); <ide> container = document.createElement('div'); <ide> document.body.appendChild(container); <ide> }); <ide> describe('Event responder: Press', () => { <ide> return <div ref={ref} listeners={listener} />; <ide> }; <ide> ReactDOM.render(<Component />, container); <add> document.elementFromPoint = () => ref.current; <ide> }); <ide> <del> it('prevents custom events being dispatched', () => { <del> ref.current.dispatchEvent(createEvent('pointerdown')); <del> ref.current.dispatchEvent(createEvent('pointerup')); <add> it('does not call callbacks', () => { <add> const target = ref.current; <add> dispatchPointerDown(target); <add> dispatchPointerUp(target); <ide> expect(onPressStart).not.toBeCalled(); <ide> expect(onPress).not.toBeCalled(); <ide> expect(onPressEnd).not.toBeCalled(); <ide> describe('Event responder: Press', () => { <ide> return <div ref={ref} listeners={listener} />; <ide> }; <ide> ReactDOM.render(<Component />, container); <add> document.elementFromPoint = () => ref.current; <ide> }); <ide> <del> it('is called after "pointerdown" event', () => { <del> ref.current.dispatchEvent( <del> createEvent('pointerdown', {pointerType: 'pen'}), <del> ); <del> ref.current.dispatchEvent( <del> createTouchEvent('touchstart', 0, { <del> target: ref.current, <del> }), <del> ); <del> expect(onPressStart).toHaveBeenCalledTimes(1); <del> expect(onPressStart).toHaveBeenCalledWith( <del> expect.objectContaining({pointerType: 'pen', type: 'pressstart'}), <del> ); <del> }); <add> it.each(pointerTypesTable)( <add> 'is called after pointer down: %s', <add> pointerType => { <add> dispatchPointerDown(ref.current, {pointerType}); <add> expect(onPressStart).toHaveBeenCalledTimes(1); <add> expect(onPressStart).toHaveBeenCalledWith( <add> expect.objectContaining({pointerType, type: 'pressstart'}), <add> ); <add> }, <add> ); <ide> <del> it('is called after auxillary-button "pointerdown" event', () => { <del> ref.current.dispatchEvent( <del> createEvent('pointerdown', {button: 1, pointerType: 'mouse'}), <del> ); <add> it('is called after auxillary-button pointer down', () => { <add> dispatchPointerDown(ref.current, {button: 1, pointerType: 'mouse'}); <ide> expect(onPressStart).toHaveBeenCalledTimes(1); <ide> expect(onPressStart).toHaveBeenCalledWith( <ide> expect.objectContaining({ <ide> describe('Event responder: Press', () => { <ide> }); <ide> <ide> it('is not called after "pointermove" following auxillary-button press', () => { <del> ref.current.getBoundingClientRect = () => ({ <add> const target = ref.current; <add> target.getBoundingClientRect = () => ({ <ide> top: 0, <ide> left: 0, <ide> bottom: 100, <ide> right: 100, <ide> }); <del> ref.current.dispatchEvent( <del> createEvent('pointerdown', { <del> button: 1, <del> pointerType: 'mouse', <del> clientX: 50, <del> clientY: 50, <del> }), <del> ); <del> ref.current.dispatchEvent( <del> createEvent('pointerup', { <del> button: 1, <del> pointerType: 'mouse', <del> clientX: 50, <del> clientY: 50, <del> }), <del> ); <del> container.dispatchEvent( <del> createEvent('pointermove', { <del> button: 1, <del> pointerType: 'mouse', <del> clientX: 110, <del> clientY: 110, <del> }), <del> ); <del> container.dispatchEvent( <del> createEvent('pointermove', { <del> button: 1, <del> pointerType: 'mouse', <del> clientX: 50, <del> clientY: 50, <del> }), <del> ); <del> expect(onPressStart).toHaveBeenCalledTimes(1); <del> }); <del> <del> it('ignores browser emulated events', () => { <del> ref.current.dispatchEvent(createEvent('pointerdown')); <del> ref.current.dispatchEvent(createEvent('touchstart')); <del> ref.current.dispatchEvent(createEvent('mousedown')); <add> dispatchPointerDown(target, { <add> button: 1, <add> pointerType: 'mouse', <add> }); <add> dispatchPointerUp(target, { <add> button: 1, <add> pointerType: 'mouse', <add> }); <add> dispatchPointerHoverMove(target, {x: 110, y: 110}); <add> dispatchPointerHoverMove(target, {x: 50, y: 50}); <ide> expect(onPressStart).toHaveBeenCalledTimes(1); <ide> }); <ide> <ide> it('ignores any events not caused by primary/auxillary-click or touch/pen contact', () => { <del> ref.current.dispatchEvent(createEvent('pointerdown', {button: 5})); <del> ref.current.dispatchEvent(createEvent('mousedown', {button: 2})); <add> const target = ref.current; <add> dispatchPointerDown(target, {button: 2}); <add> dispatchPointerDown(target, {button: 5}); <ide> expect(onPressStart).toHaveBeenCalledTimes(0); <ide> }); <ide> <ide> it('is called once after "keydown" events for Enter', () => { <del> ref.current.dispatchEvent(createKeyboardEvent('keydown', {key: 'Enter'})); <del> ref.current.dispatchEvent(createKeyboardEvent('keydown', {key: 'Enter'})); <del> ref.current.dispatchEvent(createKeyboardEvent('keydown', {key: 'Enter'})); <add> const target = ref.current; <add> target.dispatchEvent(keydown({key: 'Enter'})); <add> target.dispatchEvent(keydown({key: 'Enter'})); <add> target.dispatchEvent(keydown({key: 'Enter'})); <ide> expect(onPressStart).toHaveBeenCalledTimes(1); <ide> expect(onPressStart).toHaveBeenCalledWith( <ide> expect.objectContaining({pointerType: 'keyboard', type: 'pressstart'}), <ide> ); <ide> }); <ide> <ide> it('is called once after "keydown" events for Spacebar', () => { <add> const target = ref.current; <ide> const preventDefault = jest.fn(); <del> ref.current.dispatchEvent( <del> createKeyboardEvent('keydown', {key: ' ', preventDefault}), <del> ); <add> target.dispatchEvent(keydown({key: ' ', preventDefault})); <ide> expect(preventDefault).toBeCalled(); <del> ref.current.dispatchEvent(createKeyboardEvent('keypress', {key: ' '})); <del> ref.current.dispatchEvent(createKeyboardEvent('keydown', {key: ' '})); <del> ref.current.dispatchEvent(createKeyboardEvent('keypress', {key: ' '})); <add> target.dispatchEvent(keydown({key: ' ', preventDefault})); <ide> expect(onPressStart).toHaveBeenCalledTimes(1); <ide> expect(onPressStart).toHaveBeenCalledWith( <ide> expect.objectContaining({ <ide> describe('Event responder: Press', () => { <ide> }); <ide> <ide> it('is not called after "keydown" for other keys', () => { <del> ref.current.dispatchEvent(createKeyboardEvent('keydown', {key: 'a'})); <add> ref.current.dispatchEvent(keydown({key: 'a'})); <ide> expect(onPressStart).not.toBeCalled(); <ide> }); <del> <del> // No PointerEvent fallbacks <del> it('is called after "mousedown" event', () => { <del> ref.current.dispatchEvent( <del> createEvent('mousedown', { <del> button: 0, <del> }), <del> ); <del> expect(onPressStart).toHaveBeenCalledTimes(1); <del> expect(onPressStart).toHaveBeenCalledWith( <del> expect.objectContaining({pointerType: 'mouse', type: 'pressstart'}), <del> ); <del> }); <del> <del> it('is called after "touchstart" event', () => { <del> ref.current.dispatchEvent( <del> createTouchEvent('touchstart', 0, { <del> target: ref.current, <del> }), <del> ); <del> expect(onPressStart).toHaveBeenCalledTimes(1); <del> expect(onPressStart).toHaveBeenCalledWith( <del> expect.objectContaining({pointerType: 'touch', type: 'pressstart'}), <del> ); <del> }); <ide> }); <ide> <ide> describe('onPressEnd', () => { <ide> describe('Event responder: Press', () => { <ide> return <div ref={ref} listeners={listener} />; <ide> }; <ide> ReactDOM.render(<Component />, container); <add> document.elementFromPoint = () => ref.current; <ide> }); <ide> <del> it('is called after "pointerup" event', () => { <del> ref.current.dispatchEvent( <del> createEvent('pointerdown', {pointerType: 'pen'}), <del> ); <del> ref.current.dispatchEvent( <del> createTouchEvent('touchstart', 0, { <del> target: ref.current, <del> }), <del> ); <del> ref.current.dispatchEvent( <del> createTouchEvent('touchend', 0, { <del> target: ref.current, <del> }), <del> ); <del> ref.current.dispatchEvent(createEvent('pointerup', {pointerType: 'pen'})); <del> expect(onPressEnd).toHaveBeenCalledTimes(1); <del> expect(onPressEnd).toHaveBeenCalledWith( <del> expect.objectContaining({pointerType: 'pen', type: 'pressend'}), <del> ); <del> }); <add> it.each(pointerTypesTable)( <add> 'is called after pointer up: %s', <add> pointerType => { <add> const target = ref.current; <add> dispatchPointerDown(target, {pointerType}); <add> dispatchPointerUp(target, {pointerType}); <add> expect(onPressEnd).toHaveBeenCalledTimes(1); <add> expect(onPressEnd).toHaveBeenCalledWith( <add> expect.objectContaining({pointerType, type: 'pressend'}), <add> ); <add> }, <add> ); <ide> <del> it('is called after auxillary-button "pointerup" event', () => { <del> ref.current.dispatchEvent( <del> createEvent('pointerdown', {button: 1, pointerType: 'mouse'}), <del> ); <del> ref.current.dispatchEvent( <del> createEvent('pointerup', {button: 1, pointerType: 'mouse'}), <del> ); <add> it('is called after auxillary-button pointer up', () => { <add> const target = ref.current; <add> dispatchPointerDown(target, {button: 1, pointerType: 'mouse'}); <add> dispatchPointerUp(target, {button: 1, pointerType: 'mouse'}); <ide> expect(onPressEnd).toHaveBeenCalledTimes(1); <ide> expect(onPressEnd).toHaveBeenCalledWith( <ide> expect.objectContaining({ <ide> describe('Event responder: Press', () => { <ide> ); <ide> }); <ide> <del> it('ignores browser emulated events', () => { <del> ref.current.dispatchEvent( <del> createEvent('pointerdown', {pointerType: 'touch'}), <del> ); <del> ref.current.dispatchEvent( <del> createTouchEvent('touchstart', 0, { <del> target: ref.current, <del> }), <del> ); <del> ref.current.dispatchEvent( <del> createEvent('pointerup', {pointerType: 'touch'}), <del> ); <del> ref.current.dispatchEvent( <del> createTouchEvent('touchend', 0, { <del> target: ref.current, <del> }), <del> ); <del> ref.current.dispatchEvent(createEvent('mousedown')); <del> ref.current.dispatchEvent(createEvent('mouseup')); <del> ref.current.dispatchEvent(createEvent('click')); <del> expect(onPressEnd).toHaveBeenCalledTimes(1); <del> expect(onPressEnd).toHaveBeenCalledWith( <del> expect.objectContaining({pointerType: 'touch', type: 'pressend'}), <del> ); <del> }); <del> <ide> it('is called after "keyup" event for Enter', () => { <del> ref.current.dispatchEvent(createKeyboardEvent('keydown', {key: 'Enter'})); <add> const target = ref.current; <add> target.dispatchEvent(keydown({key: 'Enter'})); <ide> // click occurs before keyup <del> ref.current.dispatchEvent(createKeyboardEvent('click')); <del> ref.current.dispatchEvent(createKeyboardEvent('keyup', {key: 'Enter'})); <add> target.dispatchEvent(click()); <add> target.dispatchEvent(keyup({key: 'Enter'})); <ide> expect(onPressEnd).toHaveBeenCalledTimes(1); <ide> expect(onPressEnd).toHaveBeenCalledWith( <ide> expect.objectContaining({pointerType: 'keyboard', type: 'pressend'}), <ide> ); <ide> }); <ide> <ide> it('is called after "keyup" event for Spacebar', () => { <del> ref.current.dispatchEvent(createKeyboardEvent('keydown', {key: ' '})); <del> ref.current.dispatchEvent(createKeyboardEvent('keyup', {key: ' '})); <add> const target = ref.current; <add> target.dispatchEvent(keydown({key: ' '})); <add> target.dispatchEvent(keyup({key: ' '})); <ide> expect(onPressEnd).toHaveBeenCalledTimes(1); <ide> expect(onPressEnd).toHaveBeenCalledWith( <ide> expect.objectContaining({pointerType: 'keyboard', type: 'pressend'}), <ide> ); <ide> }); <ide> <ide> it('is not called after "keyup" event for other keys', () => { <del> ref.current.dispatchEvent(createKeyboardEvent('keydown', {key: 'Enter'})); <del> ref.current.dispatchEvent(createKeyboardEvent('keyup', {key: 'a'})); <add> const target = ref.current; <add> target.dispatchEvent(keydown({key: 'Enter'})); <add> target.dispatchEvent(keyup({key: 'a'})); <ide> expect(onPressEnd).not.toBeCalled(); <ide> }); <ide> <ide> it('is called with keyboard modifiers', () => { <del> ref.current.dispatchEvent(createKeyboardEvent('keydown', {key: 'Enter'})); <del> ref.current.dispatchEvent( <del> createKeyboardEvent('keyup', { <add> const target = ref.current; <add> target.dispatchEvent(keydown({key: 'Enter'})); <add> target.dispatchEvent( <add> keyup({ <ide> key: 'Enter', <ide> metaKey: true, <ide> ctrlKey: true, <ide> describe('Event responder: Press', () => { <ide> }), <ide> ); <ide> }); <del> <del> // No PointerEvent fallbacks <del> it('is called after "mouseup" event', () => { <del> ref.current.dispatchEvent( <del> createEvent('mousedown', { <del> button: 0, <del> }), <del> ); <del> ref.current.dispatchEvent( <del> createEvent('mouseup', { <del> button: 0, <del> }), <del> ); <del> expect(onPressEnd).toHaveBeenCalledTimes(1); <del> expect(onPressEnd).toHaveBeenCalledWith( <del> expect.objectContaining({pointerType: 'mouse', type: 'pressend'}), <del> ); <del> }); <del> it('is called after "touchend" event', () => { <del> document.elementFromPoint = () => ref.current; <del> ref.current.dispatchEvent( <del> createTouchEvent('touchstart', 0, { <del> target: ref.current, <del> }), <del> ); <del> ref.current.dispatchEvent( <del> createTouchEvent('touchend', 0, { <del> target: ref.current, <del> }), <del> ); <del> expect(onPressEnd).toHaveBeenCalledTimes(1); <del> expect(onPressEnd).toHaveBeenCalledWith( <del> expect.objectContaining({pointerType: 'touch', type: 'pressend'}), <del> ); <del> }); <ide> }); <ide> <ide> describe('onPressChange', () => { <ide> describe('Event responder: Press', () => { <ide> return <div ref={ref} listeners={listener} />; <ide> }; <ide> ReactDOM.render(<Component />, container); <add> document.elementFromPoint = () => ref.current; <ide> }); <ide> <del> it('is called after "pointerdown" and "pointerup" events', () => { <del> ref.current.dispatchEvent(createEvent('pointerdown')); <del> expect(onPressChange).toHaveBeenCalledTimes(1); <del> expect(onPressChange).toHaveBeenCalledWith(true); <del> ref.current.dispatchEvent(createEvent('pointerup')); <del> expect(onPressChange).toHaveBeenCalledTimes(2); <del> expect(onPressChange).toHaveBeenCalledWith(false); <del> }); <add> it.each(pointerTypesTable)( <add> 'is called after pointer down and up: %s', <add> pointerType => { <add> const target = ref.current; <add> dispatchPointerDown(target, {pointerType}); <add> expect(onPressChange).toHaveBeenCalledTimes(1); <add> expect(onPressChange).toHaveBeenCalledWith(true); <add> dispatchPointerUp(target, {pointerType}); <add> expect(onPressChange).toHaveBeenCalledTimes(2); <add> expect(onPressChange).toHaveBeenCalledWith(false); <add> }, <add> ); <ide> <ide> it('is called after valid "keydown" and "keyup" events', () => { <del> ref.current.dispatchEvent(createKeyboardEvent('keydown', {key: 'Enter'})); <add> ref.current.dispatchEvent(keydown({key: 'Enter'})); <ide> expect(onPressChange).toHaveBeenCalledTimes(1); <ide> expect(onPressChange).toHaveBeenCalledWith(true); <del> ref.current.dispatchEvent(createKeyboardEvent('keyup', {key: 'Enter'})); <add> ref.current.dispatchEvent(keyup({key: 'Enter'})); <ide> expect(onPressChange).toHaveBeenCalledTimes(2); <ide> expect(onPressChange).toHaveBeenCalledWith(false); <ide> }); <ide> describe('Event responder: Press', () => { <ide> bottom: 100, <ide> right: 100, <ide> }); <add> document.elementFromPoint = () => ref.current; <ide> }); <ide> <del> it('is called after "pointerup" event', () => { <del> ref.current.dispatchEvent( <del> createEvent('pointerdown', {pointerType: 'pen'}), <del> ); <del> ref.current.dispatchEvent( <del> createTouchEvent('touchstart', 0, { <del> target: ref.current, <del> clientX: 0, <del> clientY: 0, <del> }), <del> ); <del> ref.current.dispatchEvent( <del> createTouchEvent('touchend', 0, { <del> target: ref.current, <del> clientX: 0, <del> clientY: 0, <del> }), <del> ); <del> ref.current.dispatchEvent( <del> createEvent('pointerup', { <del> pointerType: 'pen', <del> clientX: 0, <del> clientY: 0, <del> }), <del> ); <del> expect(onPress).toHaveBeenCalledTimes(1); <del> expect(onPress).toHaveBeenCalledWith( <del> expect.objectContaining({pointerType: 'pen', type: 'press'}), <del> ); <del> }); <add> it.each(pointerTypesTable)( <add> 'is called after pointer up: %s', <add> pointerType => { <add> const target = ref.current; <add> dispatchPointerDown(target, {pointerType}); <add> dispatchPointerUp(target, {pointerType, x: 10, y: 10}); <add> expect(onPress).toHaveBeenCalledTimes(1); <add> expect(onPress).toHaveBeenCalledWith( <add> expect.objectContaining({pointerType, type: 'press'}), <add> ); <add> }, <add> ); <ide> <ide> it('is not called after auxillary-button press', () => { <del> const Component = () => { <del> const listener = usePressResponder({ <del> onPress, <del> }); <del> return <div ref={ref} listeners={listener} />; <del> }; <del> ReactDOM.render(<Component />, container); <del> <del> ref.current.dispatchEvent(createEvent('pointerdown', {button: 1})); <del> ref.current.dispatchEvent( <del> createEvent('pointerup', {button: 1, clientX: 10, clientY: 10}), <del> ); <add> const target = ref.current; <add> dispatchPointerDown(target, {button: 1, pointerType: 'mouse'}); <add> dispatchPointerUp(target, {button: 1, pointerType: 'mouse'}); <ide> expect(onPress).not.toHaveBeenCalled(); <ide> }); <ide> <ide> it('is called after valid "keyup" event', () => { <del> ref.current.dispatchEvent(createKeyboardEvent('keydown', {key: 'Enter'})); <del> ref.current.dispatchEvent(createKeyboardEvent('keyup', {key: 'Enter'})); <add> const target = ref.current; <add> target.dispatchEvent(keydown({key: 'Enter'})); <add> target.dispatchEvent(keyup({key: 'Enter'})); <ide> expect(onPress).toHaveBeenCalledTimes(1); <ide> expect(onPress).toHaveBeenCalledWith( <ide> expect.objectContaining({pointerType: 'keyboard', type: 'press'}), <ide> describe('Event responder: Press', () => { <ide> return <input ref={inputRef} listeners={listener} />; <ide> }; <ide> ReactDOM.render(<Component />, container); <del> inputRef.current.dispatchEvent( <del> createKeyboardEvent('keydown', {key: 'Enter'}), <del> ); <del> inputRef.current.dispatchEvent( <del> createKeyboardEvent('keyup', {key: 'Enter'}), <del> ); <del> inputRef.current.dispatchEvent( <del> createKeyboardEvent('keydown', {key: ' '}), <del> ); <del> inputRef.current.dispatchEvent(createKeyboardEvent('keyup', {key: ' '})); <add> const target = inputRef.current; <add> target.dispatchEvent(keydown({key: 'Enter'})); <add> target.dispatchEvent(keyup({key: 'Enter'})); <add> target.dispatchEvent(keydown({key: ' '})); <add> target.dispatchEvent(keyup({key: ' '})); <ide> expect(onPress).not.toBeCalled(); <ide> }); <ide> <ide> it('is called with modifier keys', () => { <del> ref.current.dispatchEvent( <del> createEvent('pointerdown', {metaKey: true, pointerType: 'mouse'}), <del> ); <del> ref.current.dispatchEvent( <del> createEvent('pointerup', {metaKey: true, pointerType: 'mouse'}), <del> ); <add> const target = ref.current; <add> dispatchPointerDown(target, {metaKey: true, pointerType: 'mouse'}); <add> dispatchPointerUp(target, { <add> metaKey: true, <add> pointerType: 'mouse', <add> }); <ide> expect(onPress).toHaveBeenCalledWith( <ide> expect.objectContaining({ <ide> pointerType: 'mouse', <ide> describe('Event responder: Press', () => { <ide> bottom: 0, <ide> top: 0, <ide> }); <del> buttonRef.current.dispatchEvent( <del> createEvent('pointerdown', {pointerType: 'mouse'}), <del> ); <del> buttonRef.current.dispatchEvent( <del> createEvent('pointerup', {pointerType: 'mouse'}), <del> ); <add> const target = buttonRef.current; <add> dispatchPointerDown(target, {pointerType: 'mouse'}); <add> dispatchPointerUp(target, {pointerType: 'mouse'}); <ide> expect(onPress).toBeCalled(); <ide> }); <del> <del> // No PointerEvent fallbacks <del> // TODO: jsdom missing APIs <del> // it('is called after "touchend" event', () => { <del> // ref.current.dispatchEvent(createEvent('touchstart')); <del> // ref.current.dispatchEvent(createEvent('touchend')); <del> // expect(onPress).toHaveBeenCalledTimes(1); <del> // }); <ide> }); <ide> <ide> describe('onPressMove', () => { <del> it('is called after "pointermove"', () => { <del> const onPressMove = jest.fn(); <del> const ref = React.createRef(); <add> let onPressMove, ref; <add> <add> beforeEach(() => { <add> onPressMove = jest.fn(); <add> ref = React.createRef(); <ide> const Component = () => { <ide> const listener = usePressResponder({ <ide> onPressMove, <ide> }); <ide> return <div ref={ref} listeners={listener} />; <ide> }; <ide> ReactDOM.render(<Component />, container); <del> <ide> ref.current.getBoundingClientRect = () => ({ <ide> top: 0, <ide> left: 0, <ide> bottom: 100, <ide> right: 100, <ide> }); <del> ref.current.dispatchEvent( <del> createEvent('pointerdown', {pointerType: 'mouse'}), <del> ); <del> ref.current.dispatchEvent( <del> createEvent('pointermove', { <del> pointerType: 'mouse', <del> clientX: 10, <del> clientY: 10, <del> }), <del> ); <del> expect(onPressMove).toHaveBeenCalledTimes(1); <del> expect(onPressMove).toHaveBeenCalledWith( <del> expect.objectContaining({pointerType: 'mouse', type: 'pressmove'}), <del> ); <add> document.elementFromPoint = () => ref.current; <ide> }); <ide> <del> it('is not called if "pointermove" occurs during keyboard press', () => { <del> const onPressMove = jest.fn(); <del> const ref = React.createRef(); <del> const Component = () => { <del> const listener = usePressResponder({ <del> onPressMove, <add> it.each(pointerTypesTable)( <add> 'is called after pointer move: %s', <add> pointerType => { <add> const target = ref.current; <add> target.getBoundingClientRect = () => ({ <add> top: 0, <add> left: 0, <add> bottom: 100, <add> right: 100, <ide> }); <del> return <div ref={ref} listeners={listener} />; <del> }; <del> ReactDOM.render(<Component />, container); <add> dispatchPointerDown(target, {pointerType}); <add> dispatchPointerMove(target, { <add> pointerType, <add> x: 10, <add> y: 10, <add> }); <add> dispatchPointerMove(target, { <add> pointerType, <add> x: 20, <add> y: 20, <add> }); <add> expect(onPressMove).toHaveBeenCalledTimes(2); <add> expect(onPressMove).toHaveBeenCalledWith( <add> expect.objectContaining({pointerType, type: 'pressmove'}), <add> ); <add> }, <add> ); <ide> <del> ref.current.getBoundingClientRect = () => ({ <add> it('is not called if pointer move occurs during keyboard press', () => { <add> const target = ref.current; <add> target.getBoundingClientRect = () => ({ <ide> top: 0, <ide> left: 0, <ide> bottom: 100, <ide> right: 100, <ide> }); <del> ref.current.dispatchEvent(createKeyboardEvent('keydown', {key: 'Enter'})); <del> ref.current.dispatchEvent( <del> createEvent('pointermove', { <del> pointerType: 'mouse', <del> clientX: 10, <del> clientY: 10, <del> }), <del> ); <add> target.dispatchEvent(keydown({key: 'Enter'})); <add> dispatchPointerMove(target, { <add> button: -1, <add> pointerType: 'mouse', <add> x: 10, <add> y: 10, <add> }); <ide> expect(onPressMove).not.toBeCalled(); <ide> }); <add> }); <ide> <del> it('ignores browser emulated events', () => { <del> const onPressMove = jest.fn(); <del> const ref = React.createRef(); <add> describe.each(pointerTypesTable)('press with movement: %s', pointerType => { <add> let events, ref, outerRef; <add> <add> beforeEach(() => { <add> events = []; <add> ref = React.createRef(); <add> outerRef = React.createRef(); <add> const createEventHandler = msg => () => { <add> events.push(msg); <add> }; <ide> const Component = () => { <ide> const listener = usePressResponder({ <del> onPressMove, <add> onPress: createEventHandler('onPress'), <add> onPressChange: createEventHandler('onPressChange'), <add> onPressMove: createEventHandler('onPressMove'), <add> onPressStart: createEventHandler('onPressStart'), <add> onPressEnd: createEventHandler('onPressEnd'), <ide> }); <del> return <div ref={ref} listeners={listener} />; <add> return ( <add> <div ref={outerRef}> <add> <div ref={ref} listeners={listener} /> <add> </div> <add> ); <ide> }; <ide> ReactDOM.render(<Component />, container); <del> <del> ref.current.getBoundingClientRect = () => ({ <del> top: 0, <del> left: 0, <del> bottom: 100, <del> right: 100, <del> }); <del> ref.current.dispatchEvent( <del> createEvent('pointerdown', {pointerType: 'touch'}), <del> ); <del> ref.current.dispatchEvent( <del> createTouchEvent('touchstart', 0, { <del> target: ref.current, <del> }), <del> ); <del> ref.current.dispatchEvent( <del> createEvent('pointermove', { <del> pointerType: 'touch', <del> clientX: 10, <del> clientY: 10, <del> }), <del> ); <del> ref.current.dispatchEvent( <del> createTouchEvent('touchmove', 0, { <del> target: ref.current, <del> clientX: 10, <del> clientY: 10, <del> }), <del> ); <del> ref.current.dispatchEvent(createEvent('mousemove')); <del> expect(onPressMove).toHaveBeenCalledTimes(1); <add> document.elementFromPoint = () => ref.current; <ide> }); <del> }); <ide> <del> describe('press with movement (pointer events)', () => { <ide> const rectMock = { <ide> width: 100, <ide> height: 100, <ide> describe('Event responder: Press', () => { <ide> const pressRectOffset = 20; <ide> const getBoundingClientRectMock = () => rectMock; <ide> const coordinatesInside = { <del> clientX: rectMock.left - pressRectOffset, <del> clientY: rectMock.top - pressRectOffset, <add> x: rectMock.left - pressRectOffset, <add> y: rectMock.top - pressRectOffset, <ide> }; <ide> const coordinatesOutside = { <del> clientX: rectMock.left - pressRectOffset - 1, <del> clientY: rectMock.top - pressRectOffset - 1, <add> x: rectMock.left - pressRectOffset - 1, <add> y: rectMock.top - pressRectOffset - 1, <ide> }; <ide> <ide> describe('within bounds of hit rect', () => { <ide> describe('Event responder: Press', () => { <ide> * └──────────────────┘ <ide> */ <ide> it('"onPress*" events are called immediately', () => { <del> let events = []; <del> const ref = React.createRef(); <del> const createEventHandler = msg => () => { <del> events.push(msg); <del> }; <del> <del> const Component = () => { <del> const listener = usePressResponder({ <del> onPress: createEventHandler('onPress'), <del> onPressChange: createEventHandler('onPressChange'), <del> onPressMove: createEventHandler('onPressMove'), <del> onPressStart: createEventHandler('onPressStart'), <del> onPressEnd: createEventHandler('onPressEnd'), <del> }); <del> return <div ref={ref} listeners={listener} />; <del> }; <del> ReactDOM.render(<Component />, container); <del> <del> ref.current.getBoundingClientRect = getBoundingClientRectMock; <del> ref.current.dispatchEvent(createEvent('pointerdown')); <del> ref.current.dispatchEvent( <del> createEvent('pointermove', coordinatesInside), <del> ); <del> ref.current.dispatchEvent(createEvent('pointerup', coordinatesInside)); <add> const target = ref.current; <add> target.getBoundingClientRect = getBoundingClientRectMock; <add> dispatchPointerDown(target, {pointerType}); <add> dispatchPointerMove(target, {pointerType, ...coordinatesInside}); <add> dispatchPointerUp(target, {pointerType, ...coordinatesInside}); <ide> jest.runAllTimers(); <del> <ide> expect(events).toEqual([ <ide> 'onPressStart', <ide> 'onPressChange', <ide> describe('Event responder: Press', () => { <ide> }); <ide> <ide> it('"onPress*" events are correctly called with target change', () => { <del> let events = []; <del> const outerRef = React.createRef(); <del> const innerRef = React.createRef(); <add> const target = ref.current; <add> const outer = outerRef.current; <add> target.getBoundingClientRect = getBoundingClientRectMock; <add> dispatchPointerDown(target, {pointerType}); <add> dispatchPointerMove(target, {pointerType, ...coordinatesInside}); <add> // TODO: this sequence may differ in the future between PointerEvent and mouse fallback when <add> // use 'setPointerCapture'. <add> if (pointerType === 'touch') { <add> dispatchPointerMove(target, {pointerType, ...coordinatesOutside}); <add> } else { <add> dispatchPointerMove(outer, {pointerType, ...coordinatesOutside}); <add> } <add> dispatchPointerMove(target, {pointerType, ...coordinatesInside}); <add> dispatchPointerUp(target, {pointerType, ...coordinatesInside}); <add> <add> expect(events.filter(removePressMoveStrings)).toEqual([ <add> 'onPressStart', <add> 'onPressChange', <add> 'onPressEnd', <add> 'onPressChange', <add> 'onPressStart', <add> 'onPressChange', <add> 'onPressEnd', <add> 'onPressChange', <add> 'onPress', <add> ]); <add> }); <add> <add> it('press retention offset can be configured', () => { <add> let localEvents = []; <add> const localRef = React.createRef(); <ide> const createEventHandler = msg => () => { <del> events.push(msg); <add> localEvents.push(msg); <ide> }; <add> const pressRetentionOffset = {top: 40, bottom: 40, left: 40, right: 40}; <ide> <ide> const Component = () => { <ide> const listener = usePressResponder({ <ide> describe('Event responder: Press', () => { <ide> onPressMove: createEventHandler('onPressMove'), <ide> onPressStart: createEventHandler('onPressStart'), <ide> onPressEnd: createEventHandler('onPressEnd'), <add> pressRetentionOffset, <ide> }); <del> return ( <del> <div ref={outerRef}> <del> <div ref={innerRef} listeners={listener} /> <del> </div> <del> ); <add> return <div ref={localRef} listeners={listener} />; <ide> }; <ide> ReactDOM.render(<Component />, container); <ide> <del> innerRef.current.getBoundingClientRect = getBoundingClientRectMock; <del> innerRef.current.dispatchEvent(createEvent('pointerdown')); <del> outerRef.current.dispatchEvent( <del> createEvent('pointermove', coordinatesOutside), <del> ); <del> innerRef.current.dispatchEvent( <del> createEvent('pointermove', coordinatesInside), <del> ); <del> innerRef.current.dispatchEvent( <del> createEvent('pointerup', coordinatesInside), <del> ); <del> jest.runAllTimers(); <del> <del> expect(events).toEqual([ <del> 'onPressStart', <del> 'onPressChange', <del> 'onPressEnd', <del> 'onPressChange', <del> 'onPressStart', <del> 'onPressChange', <del> 'onPressEnd', <del> 'onPressChange', <del> 'onPress', <del> ]); <del> }); <del> <del> it('press retention offset can be configured', () => { <del> let events = []; <del> const ref = React.createRef(); <del> const createEventHandler = msg => () => { <del> events.push(msg); <del> }; <del> const pressRetentionOffset = {top: 40, bottom: 40, left: 40, right: 40}; <del> <del> const Component = () => { <del> const listener = usePressResponder({ <del> onPress: createEventHandler('onPress'), <del> onPressChange: createEventHandler('onPressChange'), <del> onPressMove: createEventHandler('onPressMove'), <del> onPressStart: createEventHandler('onPressStart'), <del> onPressEnd: createEventHandler('onPressEnd'), <del> pressRetentionOffset, <del> }); <del> return <div ref={ref} listeners={listener} />; <del> }; <del> ReactDOM.render(<Component />, container); <del> <del> ref.current.getBoundingClientRect = getBoundingClientRectMock; <del> ref.current.dispatchEvent(createEvent('pointerdown')); <del> ref.current.dispatchEvent( <del> createEvent('pointermove', { <del> clientX: rectMock.left - pressRetentionOffset.left, <del> clientY: rectMock.top - pressRetentionOffset.top, <del> }), <del> ); <del> ref.current.dispatchEvent(createEvent('pointerup', coordinatesInside)); <del> expect(events).toEqual([ <add> const target = localRef.current; <add> target.getBoundingClientRect = getBoundingClientRectMock; <add> dispatchPointerDown(target, {pointerType}); <add> dispatchPointerMove(target, { <add> pointerType, <add> x: rectMock.left, <add> y: rectMock.top, <add> }); <add> dispatchPointerUp(target, {pointerType, ...coordinatesInside}); <add> expect(localEvents).toEqual([ <ide> 'onPressStart', <ide> 'onPressChange', <ide> 'onPressMove', <ide> describe('Event responder: Press', () => { <ide> }); <ide> <ide> it('responder region accounts for decrease in element dimensions', () => { <del> let events = []; <del> const ref = React.createRef(); <del> const createEventHandler = msg => () => { <del> events.push(msg); <del> }; <del> <del> const Component = () => { <del> const listener = usePressResponder({ <del> onPress: createEventHandler('onPress'), <del> onPressStart: createEventHandler('onPressStart'), <del> onPressEnd: createEventHandler('onPressEnd'), <del> }); <del> return <div ref={ref} listeners={listener} />; <del> }; <del> ReactDOM.render(<Component />, container); <del> <del> ref.current.getBoundingClientRect = getBoundingClientRectMock; <del> ref.current.dispatchEvent(createEvent('pointerdown')); <add> const target = ref.current; <add> target.getBoundingClientRect = getBoundingClientRectMock; <add> dispatchPointerDown(target, {pointerType}); <ide> // emulate smaller dimensions change on activation <del> ref.current.getBoundingClientRect = () => ({ <add> target.getBoundingClientRect = () => ({ <ide> width: 80, <ide> height: 80, <ide> top: 60, <ide> describe('Event responder: Press', () => { <ide> bottom: 490, <ide> }); <ide> const coordinates = { <del> clientX: rectMock.left, <del> clientY: rectMock.top, <add> x: rectMock.left, <add> y: rectMock.top, <ide> }; <ide> // move to an area within the pre-activation region <del> ref.current.dispatchEvent(createEvent('pointermove', coordinates)); <del> ref.current.dispatchEvent(createEvent('pointerup', coordinates)); <del> expect(events).toEqual(['onPressStart', 'onPressEnd', 'onPress']); <add> dispatchPointerMove(target, {pointerType, ...coordinates}); <add> dispatchPointerUp(target, {pointerType, ...coordinates}); <add> expect(events).toEqual([ <add> 'onPressStart', <add> 'onPressChange', <add> 'onPressMove', <add> 'onPressEnd', <add> 'onPressChange', <add> 'onPress', <add> ]); <ide> }); <ide> <ide> it('responder region accounts for increase in element dimensions', () => { <del> let events = []; <del> const ref = React.createRef(); <del> const createEventHandler = msg => () => { <del> events.push(msg); <del> }; <del> <del> const Component = () => { <del> const listener = usePressResponder({ <del> onPress: createEventHandler('onPress'), <del> onPressStart: createEventHandler('onPressStart'), <del> onPressEnd: createEventHandler('onPressEnd'), <del> }); <del> return <div ref={ref} listeners={listener} />; <del> }; <del> ReactDOM.render(<Component />, container); <del> <del> ref.current.getBoundingClientRect = getBoundingClientRectMock; <del> ref.current.dispatchEvent(createEvent('pointerdown')); <add> const target = ref.current; <add> target.getBoundingClientRect = getBoundingClientRectMock; <add> dispatchPointerDown(target, {pointerType}); <ide> // emulate larger dimensions change on activation <del> ref.current.getBoundingClientRect = () => ({ <add> target.getBoundingClientRect = () => ({ <ide> width: 200, <ide> height: 200, <ide> top: 0, <ide> describe('Event responder: Press', () => { <ide> bottom: 550, <ide> }); <ide> const coordinates = { <del> clientX: rectMock.left - 50, <del> clientY: rectMock.top - 50, <add> x: rectMock.left - 50, <add> y: rectMock.top - 50, <ide> }; <ide> // move to an area within the post-activation region <del> ref.current.dispatchEvent(createEvent('pointermove', coordinates)); <del> ref.current.dispatchEvent(createEvent('pointerup', coordinates)); <del> expect(events).toEqual(['onPressStart', 'onPressEnd', 'onPress']); <del> }); <del> }); <del> <del> describe('beyond bounds of hit rect', () => { <del> /** ┌──────────────────┐ <del> * │ ┌────────────┐ │ <del> * │ │ VisualRect │ │ <del> * │ └────────────┘ │ <del> * │ HitRect │ <del> * └──────────────────┘ <del> * X <= Move to X and release <del> */ <del> <del> it('"onPress" is not called on release', () => { <del> let events = []; <del> const ref = React.createRef(); <del> const createEventHandler = msg => () => { <del> events.push(msg); <del> }; <del> <del> const Component = () => { <del> const listener = usePressResponder({ <del> onPress: createEventHandler('onPress'), <del> onPressChange: createEventHandler('onPressChange'), <del> onPressMove: createEventHandler('onPressMove'), <del> onPressStart: createEventHandler('onPressStart'), <del> onPressEnd: createEventHandler('onPressEnd'), <del> }); <del> return <div ref={ref} listeners={listener} />; <del> }; <del> ReactDOM.render(<Component />, container); <del> <del> ref.current.getBoundingClientRect = getBoundingClientRectMock; <del> ref.current.dispatchEvent(createEvent('pointerdown')); <del> ref.current.dispatchEvent( <del> createEvent('pointermove', coordinatesInside), <del> ); <del> container.dispatchEvent(createEvent('pointermove', coordinatesOutside)); <del> container.dispatchEvent(createEvent('pointerup', coordinatesOutside)); <del> jest.runAllTimers(); <del> <del> expect(events).toEqual([ <del> 'onPressStart', <del> 'onPressChange', <del> 'onPressMove', <del> 'onPressEnd', <del> 'onPressChange', <del> ]); <del> }); <del> }); <del> <del> it('"onPress" is not called on release with mouse', () => { <del> let events = []; <del> const ref = React.createRef(); <del> const createEventHandler = msg => () => { <del> events.push(msg); <del> }; <del> <del> const Component = () => { <del> const listener = usePressResponder({ <del> onPress: createEventHandler('onPress'), <del> onPressChange: createEventHandler('onPressChange'), <del> onPressMove: createEventHandler('onPressMove'), <del> onPressStart: createEventHandler('onPressStart'), <del> onPressEnd: createEventHandler('onPressEnd'), <del> }); <del> return <div ref={ref} listeners={listener} />; <del> }; <del> ReactDOM.render(<Component />, container); <del> <del> ref.current.getBoundingClientRect = getBoundingClientRectMock; <del> ref.current.dispatchEvent( <del> createEvent('pointerdown', { <del> pointerType: 'mouse', <del> }), <del> ); <del> ref.current.dispatchEvent( <del> createEvent('pointermove', { <del> ...coordinatesInside, <del> pointerType: 'mouse', <del> }), <del> ); <del> container.dispatchEvent( <del> createEvent('pointermove', { <del> ...coordinatesOutside, <del> pointerType: 'mouse', <del> }), <del> ); <del> container.dispatchEvent( <del> createEvent('pointerup', { <del> ...coordinatesOutside, <del> pointerType: 'mouse', <del> }), <del> ); <del> jest.runAllTimers(); <del> <del> expect(events).toEqual([ <del> 'onPressStart', <del> 'onPressChange', <del> 'onPressMove', <del> 'onPressEnd', <del> 'onPressChange', <del> ]); <del> }); <del> <del> it('"onPress" is called on re-entry to hit rect for mouse', () => { <del> let events = []; <del> const ref = React.createRef(); <del> const createEventHandler = msg => () => { <del> events.push(msg); <del> }; <del> <del> const Component = () => { <del> const listener = usePressResponder({ <del> onPress: createEventHandler('onPress'), <del> onPressChange: createEventHandler('onPressChange'), <del> onPressMove: createEventHandler('onPressMove'), <del> onPressStart: createEventHandler('onPressStart'), <del> onPressEnd: createEventHandler('onPressEnd'), <del> }); <del> return <div ref={ref} listeners={listener} />; <del> }; <del> ReactDOM.render(<Component />, container); <del> <del> ref.current.getBoundingClientRect = getBoundingClientRectMock; <del> ref.current.dispatchEvent( <del> createEvent('pointerdown', { <del> pointerType: 'mouse', <del> }), <del> ); <del> ref.current.dispatchEvent( <del> createEvent('pointermove', { <del> ...coordinatesInside, <del> pointerType: 'mouse', <del> }), <del> ); <del> container.dispatchEvent( <del> createEvent('pointermove', { <del> ...coordinatesOutside, <del> pointerType: 'mouse', <del> }), <del> ); <del> container.dispatchEvent( <del> createEvent('pointermove', { <del> ...coordinatesInside, <del> pointerType: 'mouse', <del> }), <del> ); <del> container.dispatchEvent( <del> createEvent('pointerup', { <del> ...coordinatesInside, <del> pointerType: 'mouse', <del> }), <del> ); <del> jest.runAllTimers(); <del> <del> expect(events).toEqual([ <del> 'onPressStart', <del> 'onPressChange', <del> 'onPressMove', <del> 'onPressEnd', <del> 'onPressChange', <del> 'onPressStart', <del> 'onPressChange', <del> 'onPressEnd', <del> 'onPressChange', <del> 'onPress', <del> ]); <del> }); <del> <del> it('"onPress" is called on re-entry to hit rect for touch', () => { <del> let events = []; <del> const ref = React.createRef(); <del> const createEventHandler = msg => () => { <del> events.push(msg); <del> }; <del> <del> const Component = () => { <del> const listener = usePressResponder({ <del> onPress: createEventHandler('onPress'), <del> onPressChange: createEventHandler('onPressChange'), <del> onPressMove: createEventHandler('onPressMove'), <del> onPressStart: createEventHandler('onPressStart'), <del> onPressEnd: createEventHandler('onPressEnd'), <del> }); <del> return <div ref={ref} listeners={listener} />; <del> }; <del> ReactDOM.render(<Component />, container); <del> <del> ref.current.getBoundingClientRect = getBoundingClientRectMock; <del> ref.current.dispatchEvent( <del> createEvent('pointerdown', { <del> pointerType: 'touch', <del> }), <del> ); <del> ref.current.dispatchEvent( <del> createTouchEvent('touchstart', 0, { <del> target: ref.current, <del> }), <del> ); <del> ref.current.dispatchEvent( <del> createEvent('pointermove', { <del> ...coordinatesInside, <del> pointerType: 'touch', <del> }), <del> ); <del> ref.current.dispatchEvent( <del> createTouchEvent('touchmove', 0, { <del> ...coordinatesInside, <del> target: ref.current, <del> }), <del> ); <del> container.dispatchEvent( <del> createEvent('pointermove', { <del> ...coordinatesOutside, <del> pointerType: 'touch', <del> }), <del> ); <del> ref.current.dispatchEvent( <del> createTouchEvent('touchmove', 0, { <del> ...coordinatesOutside, <del> target: ref.current, <del> }), <del> ); <del> container.dispatchEvent( <del> createEvent('pointermove', { <del> ...coordinatesInside, <del> pointerType: 'touch', <del> }), <del> ); <del> ref.current.dispatchEvent( <del> createTouchEvent('touchmove', 0, { <del> ...coordinatesInside, <del> target: ref.current, <del> }), <del> ); <del> ref.current.dispatchEvent( <del> createTouchEvent('touchend', 0, { <del> ...coordinatesInside, <del> target: ref.current, <del> }), <del> ); <del> container.dispatchEvent( <del> createEvent('pointerup', { <del> ...coordinatesInside, <del> pointerType: 'touch', <del> }), <del> ); <del> jest.runAllTimers(); <del> <del> expect(events).toEqual([ <del> 'onPressStart', <del> 'onPressChange', <del> 'onPressMove', <del> 'onPressEnd', <del> 'onPressChange', <del> 'onPressStart', <del> 'onPressChange', <del> 'onPressEnd', <del> 'onPressChange', <del> 'onPress', <del> ]); <del> }); <del> }); <del> <del> describe('press with movement (touch events fallback)', () => { <del> const rectMock = { <del> width: 100, <del> height: 100, <del> top: 50, <del> left: 50, <del> right: 150, <del> bottom: 150, <del> }; <del> const pressRectOffset = 20; <del> const getBoundingClientRectMock = () => rectMock; <del> const coordinatesInside = { <del> clientX: rectMock.left - pressRectOffset, <del> clientY: rectMock.top - pressRectOffset, <del> }; <del> const coordinatesOutside = { <del> clientX: rectMock.left - pressRectOffset - 1, <del> clientY: rectMock.top - pressRectOffset - 1, <del> }; <del> <del> describe('within bounds of hit rect', () => { <del> /** ┌──────────────────┐ <del> * │ ┌────────────┐ │ <del> * │ │ VisualRect │ │ <del> * │ └────────────┘ │ <del> * │ HitRect X │ <= Move to X and release <del> * └──────────────────┘ <del> */ <del> it('"onPress*" events are called immediately', () => { <del> let events = []; <del> const ref = React.createRef(); <del> const createEventHandler = msg => () => { <del> events.push(msg); <del> }; <del> <del> const Component = () => { <del> const listener = usePressResponder({ <del> onPress: createEventHandler('onPress'), <del> onPressChange: createEventHandler('onPressChange'), <del> onPressMove: createEventHandler('onPressMove'), <del> onPressStart: createEventHandler('onPressStart'), <del> onPressEnd: createEventHandler('onPressEnd'), <del> }); <del> return <div ref={ref} listeners={listener} />; <del> }; <del> ReactDOM.render(<Component />, container); <del> <del> document.elementFromPoint = () => ref.current; <del> ref.current.getBoundingClientRect = getBoundingClientRectMock; <del> ref.current.dispatchEvent( <del> createTouchEvent('touchstart', 0, { <del> target: ref.current, <del> }), <del> ); <del> ref.current.dispatchEvent( <del> createTouchEvent('touchmove', 0, { <del> ...coordinatesInside, <del> target: ref.current, <del> }), <del> ); <del> ref.current.dispatchEvent( <del> createTouchEvent('touchend', 0, { <del> ...coordinatesInside, <del> target: ref.current, <del> }), <del> ); <del> jest.runAllTimers(); <del> <del> expect(events).toEqual([ <del> 'onPressStart', <del> 'onPressChange', <del> 'onPressMove', <del> 'onPressEnd', <del> 'onPressChange', <del> 'onPress', <del> ]); <del> }); <del> <del> it('press retention offset can be configured', () => { <del> let events = []; <del> const ref = React.createRef(); <del> const createEventHandler = msg => () => { <del> events.push(msg); <del> }; <del> const pressRetentionOffset = {top: 40, bottom: 40, left: 40, right: 40}; <del> <del> const Component = () => { <del> const listener = usePressResponder({ <del> onPress: createEventHandler('onPress'), <del> onPressChange: createEventHandler('onPressChange'), <del> onPressMove: createEventHandler('onPressMove'), <del> onPressStart: createEventHandler('onPressStart'), <del> onPressEnd: createEventHandler('onPressEnd'), <del> pressRetentionOffset, <del> }); <del> return <div ref={ref} listeners={listener} />; <del> }; <del> ReactDOM.render(<Component />, container); <del> <del> document.elementFromPoint = () => ref.current; <del> ref.current.getBoundingClientRect = getBoundingClientRectMock; <del> ref.current.dispatchEvent( <del> createTouchEvent('touchstart', 0, { <del> target: ref.current, <del> }), <del> ); <del> ref.current.dispatchEvent( <del> createTouchEvent('touchmove', 0, { <del> clientX: rectMock.left - pressRetentionOffset.left, <del> clientY: rectMock.top - pressRetentionOffset.top, <del> target: ref.current, <del> }), <del> ); <del> ref.current.dispatchEvent( <del> createTouchEvent('touchend', 0, { <del> ...coordinatesInside, <del> target: ref.current, <del> }), <del> ); <add> dispatchPointerMove(target, {pointerType, ...coordinates}); <add> dispatchPointerUp(target, {pointerType, ...coordinates}); <ide> expect(events).toEqual([ <ide> 'onPressStart', <ide> 'onPressChange', <ide> describe('Event responder: Press', () => { <ide> 'onPress', <ide> ]); <ide> }); <del> <del> it('responder region accounts for decrease in element dimensions', () => { <del> let events = []; <del> const ref = React.createRef(); <del> const createEventHandler = msg => () => { <del> events.push(msg); <del> }; <del> <del> const Component = () => { <del> const listener = usePressResponder({ <del> onPress: createEventHandler('onPress'), <del> onPressStart: createEventHandler('onPressStart'), <del> onPressEnd: createEventHandler('onPressEnd'), <del> }); <del> return <div ref={ref} listeners={listener} />; <del> }; <del> ReactDOM.render(<Component />, container); <del> <del> document.elementFromPoint = () => ref.current; <del> ref.current.getBoundingClientRect = getBoundingClientRectMock; <del> ref.current.dispatchEvent( <del> createTouchEvent('touchstart', 0, { <del> target: ref.current, <del> }), <del> ); <del> // emulate smaller dimensions change on activation <del> ref.current.getBoundingClientRect = () => ({ <del> width: 80, <del> height: 80, <del> top: 60, <del> left: 60, <del> right: 140, <del> bottom: 140, <del> }); <del> const coordinates = { <del> clientX: rectMock.left, <del> clientY: rectMock.top, <del> }; <del> // move to an area within the pre-activation region <del> ref.current.dispatchEvent( <del> createTouchEvent('touchmove', 0, { <del> ...coordinates, <del> target: ref.current, <del> }), <del> ); <del> ref.current.dispatchEvent( <del> createTouchEvent('touchend', 0, { <del> ...coordinates, <del> target: ref.current, <del> }), <del> ); <del> expect(events).toEqual(['onPressStart', 'onPressEnd', 'onPress']); <del> }); <del> <del> it('responder region accounts for increase in element dimensions', () => { <del> let events = []; <del> const ref = React.createRef(); <del> const createEventHandler = msg => () => { <del> events.push(msg); <del> }; <del> <del> const Component = () => { <del> const listener = usePressResponder({ <del> onPress: createEventHandler('onPress'), <del> onPressStart: createEventHandler('onPressStart'), <del> onPressEnd: createEventHandler('onPressEnd'), <del> }); <del> return <div ref={ref} listeners={listener} />; <del> }; <del> ReactDOM.render(<Component />, container); <del> <del> document.elementFromPoint = () => ref.current; <del> ref.current.getBoundingClientRect = getBoundingClientRectMock; <del> ref.current.dispatchEvent( <del> createTouchEvent('touchstart', 0, { <del> target: ref.current, <del> }), <del> ); <del> // emulate larger dimensions change on activation <del> ref.current.getBoundingClientRect = () => ({ <del> width: 200, <del> height: 200, <del> top: 0, <del> left: 0, <del> right: 200, <del> bottom: 200, <del> }); <del> const coordinates = { <del> clientX: rectMock.left - 50, <del> clientY: rectMock.top - 50, <del> }; <del> // move to an area within the post-activation region <del> ref.current.dispatchEvent( <del> createTouchEvent('touchmove', 0, { <del> ...coordinates, <del> target: ref.current, <del> }), <del> ); <del> ref.current.dispatchEvent( <del> createTouchEvent('touchend', 0, { <del> ...coordinates, <del> target: ref.current, <del> }), <del> ); <del> expect(events).toEqual(['onPressStart', 'onPressEnd', 'onPress']); <del> }); <ide> }); <ide> <ide> describe('beyond bounds of hit rect', () => { <ide> describe('Event responder: Press', () => { <ide> * └──────────────────┘ <ide> * X <= Move to X and release <ide> */ <del> <ide> it('"onPress" is not called on release', () => { <del> let events = []; <del> const ref = React.createRef(); <del> const createEventHandler = msg => () => { <del> events.push(msg); <del> }; <del> <del> const Component = () => { <del> const listener = usePressResponder({ <del> onPress: createEventHandler('onPress'), <del> onPressChange: createEventHandler('onPressChange'), <del> onPressMove: createEventHandler('onPressMove'), <del> onPressStart: createEventHandler('onPressStart'), <del> onPressEnd: createEventHandler('onPressEnd'), <del> }); <del> return <div ref={ref} listeners={listener} />; <del> }; <del> ReactDOM.render(<Component />, container); <del> <del> document.elementFromPoint = () => ref.current; <del> ref.current.getBoundingClientRect = getBoundingClientRectMock; <del> ref.current.dispatchEvent( <del> createTouchEvent('touchstart', 0, { <del> target: ref.current, <del> }), <del> ); <del> ref.current.dispatchEvent( <del> createTouchEvent('touchmove', 0, { <del> ...coordinatesInside, <del> target: ref.current, <del> }), <del> ); <del> document.elementFromPoint = () => container; <del> container.dispatchEvent( <del> createTouchEvent('touchmove', 0, { <del> ...coordinatesOutside, <del> target: container, <del> }), <del> ); <del> container.dispatchEvent( <del> createTouchEvent('touchend', 0, { <del> ...coordinatesOutside, <del> target: container, <del> }), <del> ); <del> jest.runAllTimers(); <del> <del> expect(events).toEqual([ <del> 'onPressStart', <del> 'onPressChange', <del> 'onPressMove', <del> 'onPressEnd', <del> 'onPressChange', <del> ]); <del> }); <del> }); <del> <del> it('"onPress" is called on re-entry to hit rect for touch', () => { <del> let events = []; <del> const ref = React.createRef(); <del> const createEventHandler = msg => () => { <del> events.push(msg); <del> }; <del> <del> const Component = () => { <del> const listener = usePressResponder({ <del> onPress: createEventHandler('onPress'), <del> onPressChange: createEventHandler('onPressChange'), <del> onPressMove: createEventHandler('onPressMove'), <del> onPressStart: createEventHandler('onPressStart'), <del> onPressEnd: createEventHandler('onPressEnd'), <del> }); <del> return <div ref={ref} listeners={listener} />; <del> }; <del> ReactDOM.render(<Component />, container); <del> <del> document.elementFromPoint = () => ref.current; <del> ref.current.getBoundingClientRect = getBoundingClientRectMock; <del> ref.current.dispatchEvent( <del> createTouchEvent('touchstart', 0, { <del> target: ref.current, <del> }), <del> ); <del> ref.current.dispatchEvent( <del> createTouchEvent('touchmove', 0, { <del> ...coordinatesInside, <del> target: ref.current, <del> }), <del> ); <del> document.elementFromPoint = () => container; <del> container.dispatchEvent( <del> createTouchEvent('touchmove', 0, { <del> ...coordinatesOutside, <del> target: container, <del> }), <del> ); <del> ref.current.dispatchEvent( <del> createTouchEvent('touchmove', 0, { <del> ...coordinatesInside, <del> target: ref.current, <del> }), <del> ); <del> document.elementFromPoint = () => ref.current; <del> ref.current.dispatchEvent( <del> createTouchEvent('touchend', 0, { <del> ...coordinatesInside, <del> target: ref.current, <del> }), <del> ); <del> jest.runAllTimers(); <add> const target = ref.current; <add> target.getBoundingClientRect = getBoundingClientRectMock; <add> dispatchPointerDown(target, {pointerType}); <add> dispatchPointerMove(target, {pointerType, ...coordinatesInside}); <add> if (pointerType === 'mouse') { <add> // TODO: use setPointerCapture so this is only true for fallback mouse events. <add> dispatchPointerMove(container, {pointerType, ...coordinatesOutside}); <add> } else { <add> dispatchPointerMove(target, {pointerType, ...coordinatesOutside}); <add> } <add> dispatchPointerUp(container, {pointerType, ...coordinatesOutside}); <add> expect(events.filter(removePressMoveStrings)).toEqual([ <add> 'onPressStart', <add> 'onPressChange', <add> 'onPressEnd', <add> 'onPressChange', <add> ]); <add> }); <add> }); <add> <add> it('"onPress" is called on re-entry to hit rect', () => { <add> const target = ref.current; <add> target.getBoundingClientRect = getBoundingClientRectMock; <add> dispatchPointerDown(target, {pointerType}); <add> dispatchPointerMove(target, {pointerType, ...coordinatesInside}); <add> if (pointerType === 'mouse') { <add> // TODO: use setPointerCapture so this is only true for fallback mouse events. <add> dispatchPointerMove(container, {pointerType, ...coordinatesOutside}); <add> } else { <add> dispatchPointerMove(target, {pointerType, ...coordinatesOutside}); <add> } <add> dispatchPointerMove(target, {pointerType, ...coordinatesInside}); <add> dispatchPointerUp(target, {pointerType, ...coordinatesInside}); <ide> <ide> expect(events).toEqual([ <ide> 'onPressStart', <ide> describe('Event responder: Press', () => { <ide> }); <ide> <ide> describe('nested responders', () => { <del> it('dispatch events in the correct order', () => { <del> const events = []; <del> const ref = React.createRef(); <del> const createEventHandler = msg => () => { <del> events.push(msg); <del> }; <add> if (hasPointerEvents) { <add> it('dispatch events in the correct order', () => { <add> const events = []; <add> const ref = React.createRef(); <add> const createEventHandler = msg => () => { <add> events.push(msg); <add> }; <ide> <del> const Inner = () => { <del> const listener = usePressResponder({ <del> onPress: createEventHandler('inner: onPress'), <del> onPressChange: createEventHandler('inner: onPressChange'), <del> onPressMove: createEventHandler('inner: onPressMove'), <del> onPressStart: createEventHandler('inner: onPressStart'), <del> onPressEnd: createEventHandler('inner: onPressEnd'), <del> stopPropagation: false, <del> }); <del> return ( <del> <div <del> ref={ref} <del> listeners={listener} <del> onPointerDown={createEventHandler('pointerdown')} <del> onPointerUp={createEventHandler('pointerup')} <del> onKeyDown={createEventHandler('keydown')} <del> onKeyUp={createEventHandler('keyup')} <del> /> <del> ); <del> }; <add> const Inner = () => { <add> const listener = usePressResponder({ <add> onPress: createEventHandler('inner: onPress'), <add> onPressChange: createEventHandler('inner: onPressChange'), <add> onPressMove: createEventHandler('inner: onPressMove'), <add> onPressStart: createEventHandler('inner: onPressStart'), <add> onPressEnd: createEventHandler('inner: onPressEnd'), <add> stopPropagation: false, <add> }); <add> return ( <add> <div <add> ref={ref} <add> listeners={listener} <add> onPointerDown={createEventHandler('pointerdown')} <add> onPointerUp={createEventHandler('pointerup')} <add> onKeyDown={createEventHandler('keydown')} <add> onKeyUp={createEventHandler('keyup')} <add> /> <add> ); <add> }; <ide> <del> const Outer = () => { <del> const listener = usePressResponder({ <del> onPress: createEventHandler('outer: onPress'), <del> onPressChange: createEventHandler('outer: onPressChange'), <del> onPressMove: createEventHandler('outer: onPressMove'), <del> onPressStart: createEventHandler('outer: onPressStart'), <del> onPressEnd: createEventHandler('outer: onPressEnd'), <del> }); <del> return ( <del> <div listeners={listener}> <del> <Inner /> <del> </div> <del> ); <del> }; <del> ReactDOM.render(<Outer />, container); <add> const Outer = () => { <add> const listener = usePressResponder({ <add> onPress: createEventHandler('outer: onPress'), <add> onPressChange: createEventHandler('outer: onPressChange'), <add> onPressMove: createEventHandler('outer: onPressMove'), <add> onPressStart: createEventHandler('outer: onPressStart'), <add> onPressEnd: createEventHandler('outer: onPressEnd'), <add> }); <add> return ( <add> <div listeners={listener}> <add> <Inner /> <add> </div> <add> ); <add> }; <add> ReactDOM.render(<Outer />, container); <ide> <del> ref.current.getBoundingClientRect = () => ({ <del> top: 0, <del> left: 0, <del> bottom: 100, <del> right: 100, <add> const target = ref.current; <add> target.getBoundingClientRect = () => ({ <add> top: 0, <add> left: 0, <add> bottom: 100, <add> right: 100, <add> }); <add> dispatchPointerDown(target); <add> dispatchPointerUp(target); <add> expect(events).toEqual([ <add> 'inner: onPressStart', <add> 'inner: onPressChange', <add> 'pointerdown', <add> 'inner: onPressEnd', <add> 'inner: onPressChange', <add> 'inner: onPress', <add> 'pointerup', <add> ]); <ide> }); <del> <del> ref.current.dispatchEvent(createEvent('pointerdown')); <del> ref.current.dispatchEvent( <del> createEvent('pointerup', {clientX: 10, clientY: 10}), <del> ); <del> expect(events).toEqual([ <del> 'inner: onPressStart', <del> 'inner: onPressChange', <del> 'pointerdown', <del> 'inner: onPressEnd', <del> 'inner: onPressChange', <del> 'inner: onPress', <del> 'pointerup', <del> ]); <del> }); <add> } <ide> <ide> describe('correctly not propagate', () => { <ide> it('for onPress', () => { <ide> describe('Event responder: Press', () => { <ide> }; <ide> ReactDOM.render(<Outer />, container); <ide> <del> ref.current.getBoundingClientRect = () => ({ <add> const target = ref.current; <add> target.getBoundingClientRect = () => ({ <ide> top: 0, <ide> left: 0, <ide> bottom: 100, <ide> right: 100, <ide> }); <del> <del> ref.current.dispatchEvent(createEvent('pointerdown')); <del> ref.current.dispatchEvent( <del> createEvent('pointerup', {clientX: 10, clientY: 10}), <del> ); <add> dispatchPointerDown(target); <add> dispatchPointerUp(target); <ide> expect(fn).toHaveBeenCalledTimes(1); <ide> }); <ide> <ide> describe('Event responder: Press', () => { <ide> }; <ide> ReactDOM.render(<Outer />, container); <ide> <del> ref.current.dispatchEvent(createEvent('pointerdown')); <add> const target = ref.current; <add> dispatchPointerDown(target); <ide> expect(fn).toHaveBeenCalledTimes(1); <ide> expect(fn2).toHaveBeenCalledTimes(0); <del> ref.current.dispatchEvent(createEvent('pointerup')); <add> dispatchPointerUp(target); <ide> expect(fn).toHaveBeenCalledTimes(1); <ide> expect(fn2).toHaveBeenCalledTimes(1); <ide> }); <ide> describe('Event responder: Press', () => { <ide> }; <ide> ReactDOM.render(<Outer />, container); <ide> <del> ref.current.dispatchEvent(createEvent('pointerdown')); <add> const target = ref.current; <add> dispatchPointerDown(target); <ide> expect(fn).toHaveBeenCalledTimes(1); <del> ref.current.dispatchEvent(createEvent('pointerup')); <add> dispatchPointerUp(target); <ide> expect(fn).toHaveBeenCalledTimes(2); <ide> }); <ide> }); <ide> }); <ide> <ide> describe('link components', () => { <del> it('prevents native behaviour for pointer events by default', () => { <add> it('prevents native behavior by default', () => { <ide> const onPress = jest.fn(); <ide> const preventDefault = jest.fn(); <ide> const ref = React.createRef(); <ide> describe('Event responder: Press', () => { <ide> }; <ide> ReactDOM.render(<Component />, container); <ide> <del> ref.current.dispatchEvent(createEvent('pointerdown')); <del> ref.current.dispatchEvent( <del> createEvent('pointerup', { <del> clientX: 0, <del> clientY: 0, <del> }), <del> ); <del> ref.current.dispatchEvent(createEvent('click', {preventDefault})); <add> const target = ref.current; <add> dispatchPointerDown(target); <add> dispatchPointerUp(target, {preventDefault}); <ide> expect(preventDefault).toBeCalled(); <ide> expect(onPress).toHaveBeenCalledWith( <ide> expect.objectContaining({defaultPrevented: true}), <ide> describe('Event responder: Press', () => { <ide> }; <ide> ReactDOM.render(<Component />, container); <ide> <del> ref.current.dispatchEvent(createEvent('keydown', {key: 'Enter'})); <del> ref.current.dispatchEvent(createEvent('click', {preventDefault})); <del> ref.current.dispatchEvent(createEvent('keyup', {key: 'Enter'})); <add> const target = ref.current; <add> target.dispatchEvent(keydown({key: 'Enter'})); <add> target.dispatchEvent(click({preventDefault})); <add> target.dispatchEvent(keyup({key: 'Enter'})); <ide> expect(preventDefault).toBeCalled(); <ide> expect(onPress).toHaveBeenCalledWith( <ide> expect.objectContaining({defaultPrevented: true}), <ide> describe('Event responder: Press', () => { <ide> }; <ide> ReactDOM.render(<Component />, container); <ide> <del> buttonRef.current.dispatchEvent(createEvent('pointerdown')); <del> buttonRef.current.dispatchEvent( <del> createEvent('pointerup', { <del> clientX: 0, <del> clientY: 0, <del> }), <del> ); <del> buttonRef.current.dispatchEvent(createEvent('click', {preventDefault})); <add> const target = buttonRef.current; <add> dispatchPointerDown(target); <add> dispatchPointerUp(target, {preventDefault}); <ide> expect(preventDefault).toBeCalled(); <ide> }); <ide> <ide> describe('Event responder: Press', () => { <ide> }; <ide> ReactDOM.render(<Component />, container); <ide> <del> ref.current.dispatchEvent(createEvent('pointerdown')); <del> ref.current.dispatchEvent( <del> createEvent('pointerup', { <del> clientX: 0, <del> clientY: 0, <del> }), <del> ); <del> ref.current.dispatchEvent(createEvent('click', {preventDefault})); <add> const target = ref.current; <add> dispatchPointerDown(target); <add> dispatchPointerUp(target, {preventDefault}); <ide> expect(preventDefault).toBeCalled(); <ide> expect(onPress).toHaveBeenCalledWith( <ide> expect.objectContaining({defaultPrevented: true}), <ide> describe('Event responder: Press', () => { <ide> ReactDOM.render(<Component />, container); <ide> <ide> ['metaKey', 'ctrlKey', 'shiftKey'].forEach(modifierKey => { <del> ref.current.dispatchEvent( <del> createEvent('pointerdown', {[modifierKey]: true}), <del> ); <del> ref.current.dispatchEvent( <del> createEvent('pointerup', { <del> [modifierKey]: true, <del> clientX: 0, <del> clientY: 0, <del> }), <del> ); <del> ref.current.dispatchEvent( <del> createEvent('click', {[modifierKey]: true, preventDefault}), <del> ); <add> const target = ref.current; <add> dispatchPointerDown(target, {[modifierKey]: true}); <add> dispatchPointerUp(target, {[modifierKey]: true, preventDefault}); <ide> expect(preventDefault).not.toBeCalled(); <ide> expect(onPress).toHaveBeenCalledWith( <ide> expect.objectContaining({defaultPrevented: false}), <ide> describe('Event responder: Press', () => { <ide> }; <ide> ReactDOM.render(<Component />, container); <ide> <del> ref.current.dispatchEvent(createEvent('pointerdown')); <del> ref.current.dispatchEvent( <del> createEvent('pointerup', { <del> clientX: 0, <del> clientY: 0, <del> }), <del> ); <del> ref.current.dispatchEvent(createEvent('click', {preventDefault})); <add> const target = ref.current; <add> dispatchPointerDown(target); <add> dispatchPointerUp(target, {preventDefault}); <ide> expect(preventDefault).not.toBeCalled(); <ide> expect(onPress).toHaveBeenCalledWith( <ide> expect.objectContaining({defaultPrevented: false}), <ide> describe('Event responder: Press', () => { <ide> }; <ide> ReactDOM.render(<Component />, container); <ide> <del> ref.current.dispatchEvent(createEvent('keydown', {key: 'Enter'})); <del> ref.current.dispatchEvent(createEvent('click', {preventDefault})); <del> ref.current.dispatchEvent(createEvent('keyup', {key: 'Enter'})); <add> const target = ref.current; <add> target.dispatchEvent(keydown({key: 'Enter'})); <add> target.dispatchEvent(click({preventDefault})); <add> target.dispatchEvent(keyup({key: 'Enter'})); <ide> expect(preventDefault).not.toBeCalled(); <ide> expect(onPress).toHaveBeenCalledWith( <ide> expect.objectContaining({defaultPrevented: false}), <ide> describe('Event responder: Press', () => { <ide> }); <ide> <ide> describe('responder cancellation', () => { <del> it('ends on "pointercancel", "touchcancel", "scroll", and "dragstart"', () => { <add> it.each(pointerTypesTable)('ends on pointer cancel', pointerType => { <ide> const onPressEnd = jest.fn(); <ide> const ref = React.createRef(); <ide> <ide> describe('Event responder: Press', () => { <ide> }; <ide> ReactDOM.render(<Component />, container); <ide> <del> // Should cancel for non-mouse events <del> ref.current.dispatchEvent( <del> createEvent('pointerdown', { <del> pointerType: 'touch', <del> }), <del> ); <del> ref.current.dispatchEvent(createEvent('scroll')); <del> expect(onPressEnd).toHaveBeenCalledTimes(1); <del> <del> onPressEnd.mockReset(); <del> <del> // Should not cancel for mouse events <del> ref.current.dispatchEvent( <del> createEvent('pointerdown', { <del> pointerType: 'mouse', <del> }), <del> ); <del> ref.current.dispatchEvent(createEvent('scroll')); <del> expect(onPressEnd).toHaveBeenCalledTimes(0); <del> <del> // When pointer events are supported <del> ref.current.dispatchEvent( <del> createEvent('pointerdown', { <del> pointerType: 'mouse', <del> }), <del> ); <del> ref.current.dispatchEvent( <del> createEvent('pointercancel', { <del> pointerType: 'mouse', <del> }), <del> ); <del> expect(onPressEnd).toHaveBeenCalledTimes(1); <del> <del> onPressEnd.mockReset(); <del> <del> // Touch fallback <del> ref.current.dispatchEvent( <del> createTouchEvent('touchstart', 0, { <del> target: ref.current, <del> }), <del> ); <del> ref.current.dispatchEvent( <del> createTouchEvent('touchcancel', 0, { <del> target: ref.current, <del> }), <del> ); <del> expect(onPressEnd).toHaveBeenCalledTimes(1); <del> <del> onPressEnd.mockReset(); <del> <del> // Mouse fallback <del> ref.current.dispatchEvent(createEvent('mousedown')); <del> ref.current.dispatchEvent(createEvent('dragstart')); <add> const target = ref.current; <add> dispatchPointerDown(target, {pointerType}); <add> dispatchPointerCancel(target, {pointerType}); <ide> expect(onPressEnd).toHaveBeenCalledTimes(1); <ide> }); <ide> }); <ide> <del> it('does end on "scroll" to document', () => { <add> it('does end on "scroll" to document (not mouse)', () => { <ide> const onPressEnd = jest.fn(); <ide> const ref = React.createRef(); <ide> <ide> describe('Event responder: Press', () => { <ide> }; <ide> ReactDOM.render(<Component />, container); <ide> <del> ref.current.dispatchEvent(createEvent('pointerdown')); <del> document.dispatchEvent(createEvent('scroll')); <add> const target = ref.current; <add> dispatchPointerDown(target, {pointerType: 'touch'}); <add> document.dispatchEvent(scroll()); <ide> expect(onPressEnd).toHaveBeenCalledTimes(1); <ide> }); <ide> <del> it('does end on "scroll" to a parent container', () => { <add> it('does end on "scroll" to a parent container (not mouse)', () => { <ide> const onPressEnd = jest.fn(); <ide> const ref = React.createRef(); <ide> const containerRef = React.createRef(); <ide> describe('Event responder: Press', () => { <ide> }; <ide> ReactDOM.render(<Component />, container); <ide> <del> ref.current.dispatchEvent(createEvent('pointerdown')); <del> containerRef.current.dispatchEvent(createEvent('scroll')); <add> dispatchPointerDown(ref.current, {pointerType: 'touch'}); <add> containerRef.current.dispatchEvent(scroll()); <ide> expect(onPressEnd).toHaveBeenCalledTimes(1); <ide> }); <ide> <ide> describe('Event responder: Press', () => { <ide> }; <ide> ReactDOM.render(<Component />, container); <ide> <del> ref.current.dispatchEvent(createEvent('pointerdown')); <del> outsideRef.current.dispatchEvent(createEvent('scroll')); <add> dispatchPointerDown(ref.current); <add> outsideRef.current.dispatchEvent(scroll()); <ide> expect(onPressEnd).not.toBeCalled(); <ide> }); <ide> <ide> describe('Event responder: Press', () => { <ide> }; <ide> ReactDOM.render(<Component />, container); <ide> <del> ref.current.dispatchEvent(createEvent('pointerdown')); <del> ref.current.dispatchEvent(createEvent('pointermove')); <del> ref.current.dispatchEvent(createEvent('pointerup')); <del> ref.current.dispatchEvent(createEvent('pointerdown')); <add> const target = ref.current; <add> dispatchPointerDown(target); <add> dispatchPointerMove(target); <add> dispatchPointerUp(target); <add> dispatchPointerDown(target); <ide> }); <ide> <ide> it('should correctly pass through event properties', () => { <ide> describe('Event responder: Press', () => { <ide> }; <ide> ReactDOM.render(<Component />, container); <ide> <del> ref.current.getBoundingClientRect = () => ({ <add> const target = ref.current; <add> target.getBoundingClientRect = () => ({ <ide> top: 10, <ide> left: 10, <ide> bottom: 110, <ide> right: 110, <ide> }); <del> <del> ref.current.dispatchEvent( <del> createEvent('pointerdown', { <del> pointerType: 'mouse', <del> pageX: 15, <del> pageY: 16, <del> screenX: 20, <del> screenY: 21, <del> clientX: 30, <del> clientY: 31, <del> }), <del> ); <del> ref.current.dispatchEvent( <del> createEvent('pointermove', { <del> pointerType: 'mouse', <del> pageX: 16, <del> pageY: 17, <del> screenX: 21, <del> screenY: 22, <del> clientX: 31, <del> clientY: 32, <del> }), <del> ); <del> ref.current.dispatchEvent( <del> createEvent('pointerup', { <del> pointerType: 'mouse', <del> pageX: 17, <del> pageY: 18, <del> screenX: 22, <del> screenY: 23, <del> clientX: 32, <del> clientY: 33, <del> }), <del> ); <del> ref.current.dispatchEvent( <del> createEvent('pointerdown', { <del> pointerType: 'mouse', <del> pageX: 18, <del> pageY: 19, <del> screenX: 23, <del> screenY: 24, <del> clientX: 33, <del> clientY: 34, <del> }), <del> ); <add> dispatchPointerDown(target, { <add> pointerType: 'mouse', <add> pageX: 15, <add> pageY: 16, <add> screenX: 20, <add> screenY: 21, <add> clientX: 30, <add> clientY: 31, <add> }); <add> dispatchPointerMove(target, { <add> pointerType: 'mouse', <add> pageX: 16, <add> pageY: 17, <add> screenX: 21, <add> screenY: 22, <add> clientX: 31, <add> clientY: 32, <add> }); <add> dispatchPointerUp(target, { <add> pointerType: 'mouse', <add> pageX: 17, <add> pageY: 18, <add> screenX: 22, <add> screenY: 23, <add> clientX: 32, <add> clientY: 33, <add> }); <add> dispatchPointerDown(target, { <add> pointerType: 'mouse', <add> pageX: 18, <add> pageY: 19, <add> screenX: 23, <add> screenY: 24, <add> clientX: 33, <add> clientY: 34, <add> }); <ide> expect(typeof timeStamps[0] === 'number').toBe(true); <ide> expect(eventLog).toEqual([ <ide> { <ide> describe('Event responder: Press', () => { <ide> ]); <ide> }); <ide> <del> function dispatchEventWithTimeStamp(elem, name, timeStamp) { <del> const event = createEvent(name, { <del> clientX: 0, <del> clientY: 0, <del> }); <del> Object.defineProperty(event, 'timeStamp', { <del> value: timeStamp, <del> }); <del> elem.dispatchEvent(event); <del> } <del> <del> it('should properly only flush sync once when the event systems are mixed', () => { <del> const ref = React.createRef(); <del> let renderCounts = 0; <del> <del> function MyComponent() { <del> const [, updateCounter] = React.useState(0); <del> renderCounts++; <del> <del> function handlePress() { <del> updateCounter(count => count + 1); <del> } <del> <del> const listener = usePressResponder({ <del> onPress: handlePress, <del> }); <del> <del> return ( <del> <div> <del> <button <del> ref={ref} <del> listeners={listener} <del> onClick={() => { <del> updateCounter(count => count + 1); <del> }}> <del> Press me <del> </button> <del> </div> <del> ); <del> } <del> <del> const newContainer = document.createElement('div'); <del> const root = ReactDOM.unstable_createRoot(newContainer); <del> document.body.appendChild(newContainer); <del> root.render(<MyComponent />); <del> Scheduler.unstable_flushAll(); <del> <del> dispatchEventWithTimeStamp(ref.current, 'pointerdown', 100); <del> dispatchEventWithTimeStamp(ref.current, 'pointerup', 100); <del> dispatchEventWithTimeStamp(ref.current, 'click', 100); <del> <del> if (__DEV__) { <del> expect(renderCounts).toBe(2); <del> } else { <del> expect(renderCounts).toBe(1); <del> } <del> Scheduler.unstable_flushAll(); <del> if (__DEV__) { <del> expect(renderCounts).toBe(4); <del> } else { <del> expect(renderCounts).toBe(2); <del> } <del> <del> dispatchEventWithTimeStamp(ref.current, 'pointerdown', 100); <del> dispatchEventWithTimeStamp(ref.current, 'pointerup', 100); <del> // Ensure the timeStamp logic works <del> dispatchEventWithTimeStamp(ref.current, 'click', 101); <del> <del> if (__DEV__) { <del> expect(renderCounts).toBe(6); <del> } else { <del> expect(renderCounts).toBe(3); <del> } <add> if (hasPointerEvents) { <add> it('should properly only flush sync once when the event systems are mixed', () => { <add> const ref = React.createRef(); <add> let renderCounts = 0; <ide> <del> Scheduler.unstable_flushAll(); <del> document.body.removeChild(newContainer); <del> }); <add> function MyComponent() { <add> const [, updateCounter] = React.useState(0); <add> renderCounts++; <ide> <del> it('should properly flush sync when the event systems are mixed with unstable_flushDiscreteUpdates', () => { <del> const ref = React.createRef(); <del> let renderCounts = 0; <add> function handlePress() { <add> updateCounter(count => count + 1); <add> } <ide> <del> function MyComponent() { <del> const [, updateCounter] = React.useState(0); <del> renderCounts++; <add> const listener = usePressResponder({ <add> onPress: handlePress, <add> }); <ide> <del> function handlePress() { <del> updateCounter(count => count + 1); <add> return ( <add> <div> <add> <button <add> ref={ref} <add> listeners={listener} <add> onClick={() => { <add> updateCounter(count => count + 1); <add> }}> <add> Press me <add> </button> <add> </div> <add> ); <ide> } <ide> <del> const listener = usePressResponder({ <del> onPress: handlePress, <del> }); <del> <del> return ( <del> <div> <del> <button <del> ref={ref} <del> listeners={listener} <del> onClick={() => { <del> // This should flush synchronously <del> ReactDOM.unstable_flushDiscreteUpdates(); <del> updateCounter(count => count + 1); <del> }}> <del> Press me <del> </button> <del> </div> <del> ); <del> } <del> <del> const newContainer = document.createElement('div'); <del> const root = ReactDOM.unstable_createRoot(newContainer); <del> document.body.appendChild(newContainer); <del> root.render(<MyComponent />); <del> Scheduler.unstable_flushAll(); <del> <del> dispatchEventWithTimeStamp(ref.current, 'pointerdown', 100); <del> dispatchEventWithTimeStamp(ref.current, 'pointerup', 100); <del> dispatchEventWithTimeStamp(ref.current, 'click', 100); <del> <del> if (__DEV__) { <del> expect(renderCounts).toBe(4); <del> } else { <del> expect(renderCounts).toBe(2); <del> } <del> Scheduler.unstable_flushAll(); <del> if (__DEV__) { <del> expect(renderCounts).toBe(6); <del> } else { <del> expect(renderCounts).toBe(3); <del> } <add> const newContainer = document.createElement('div'); <add> const root = ReactDOM.unstable_createRoot(newContainer); <add> document.body.appendChild(newContainer); <add> root.render(<MyComponent />); <add> Scheduler.unstable_flushAll(); <ide> <del> dispatchEventWithTimeStamp(ref.current, 'pointerdown', 100); <del> dispatchEventWithTimeStamp(ref.current, 'pointerup', 100); <del> // Ensure the timeStamp logic works <del> dispatchEventWithTimeStamp(ref.current, 'click', 101); <add> const target = ref.current; <add> target.dispatchEvent(pointerdown({timeStamp: 100})); <add> target.dispatchEvent(pointerup({timeStamp: 100})); <add> target.dispatchEvent(click({timeStamp: 100})); <ide> <del> if (__DEV__) { <del> expect(renderCounts).toBe(8); <del> } else { <del> expect(renderCounts).toBe(4); <del> } <add> if (__DEV__) { <add> expect(renderCounts).toBe(2); <add> } else { <add> expect(renderCounts).toBe(1); <add> } <add> Scheduler.unstable_flushAll(); <add> if (__DEV__) { <add> expect(renderCounts).toBe(4); <add> } else { <add> expect(renderCounts).toBe(2); <add> } <ide> <del> Scheduler.unstable_flushAll(); <del> document.body.removeChild(newContainer); <del> }); <add> target.dispatchEvent(pointerdown({timeStamp: 100})); <add> target.dispatchEvent(pointerup({timeStamp: 100})); <add> // Ensure the timeStamp logic works <add> target.dispatchEvent(click({timeStamp: 101})); <ide> <del> it( <del> 'should only flush before outermost discrete event handler when mixing ' + <del> 'event systems', <del> async () => { <del> const {useState} = React; <add> if (__DEV__) { <add> expect(renderCounts).toBe(6); <add> } else { <add> expect(renderCounts).toBe(3); <add> } <ide> <del> const button = React.createRef(); <add> Scheduler.unstable_flushAll(); <add> document.body.removeChild(newContainer); <add> }); <ide> <del> const ops = []; <add> it('should properly flush sync when the event systems are mixed with unstable_flushDiscreteUpdates', () => { <add> const ref = React.createRef(); <add> let renderCounts = 0; <ide> <ide> function MyComponent() { <del> const [pressesCount, updatePressesCount] = useState(0); <del> const [clicksCount, updateClicksCount] = useState(0); <add> const [, updateCounter] = React.useState(0); <add> renderCounts++; <ide> <ide> function handlePress() { <del> // This dispatches a synchronous, discrete event in the legacy event <del> // system. However, because it's nested inside the new event system, <del> // its updates should not flush until the end of the outer handler. <del> button.current.click(); <del> // Text context should not have changed <del> ops.push(newContainer.textContent); <del> updatePressesCount(pressesCount + 1); <add> updateCounter(count => count + 1); <ide> } <ide> <ide> const listener = usePressResponder({ <ide> describe('Event responder: Press', () => { <ide> return ( <ide> <div> <ide> <button <add> ref={ref} <ide> listeners={listener} <del> ref={button} <del> onClick={() => updateClicksCount(clicksCount + 1)}> <del> Presses: {pressesCount}, Clicks: {clicksCount} <add> onClick={() => { <add> // This should flush synchronously <add> ReactDOM.unstable_flushDiscreteUpdates(); <add> updateCounter(count => count + 1); <add> }}> <add> Press me <ide> </button> <ide> </div> <ide> ); <ide> } <ide> <ide> const newContainer = document.createElement('div'); <del> document.body.appendChild(newContainer); <ide> const root = ReactDOM.unstable_createRoot(newContainer); <del> <add> document.body.appendChild(newContainer); <ide> root.render(<MyComponent />); <ide> Scheduler.unstable_flushAll(); <del> expect(newContainer.textContent).toEqual('Presses: 0, Clicks: 0'); <ide> <del> dispatchEventWithTimeStamp(button.current, 'pointerdown', 100); <del> dispatchEventWithTimeStamp(button.current, 'pointerup', 100); <del> dispatchEventWithTimeStamp(button.current, 'click', 100); <add> const target = ref.current; <add> target.dispatchEvent(pointerdown({timeStamp: 100})); <add> target.dispatchEvent(pointerup({timeStamp: 100})); <add> target.dispatchEvent(click({timeStamp: 100})); <add> <add> if (__DEV__) { <add> expect(renderCounts).toBe(4); <add> } else { <add> expect(renderCounts).toBe(2); <add> } <ide> Scheduler.unstable_flushAll(); <del> expect(newContainer.textContent).toEqual('Presses: 1, Clicks: 1'); <add> if (__DEV__) { <add> expect(renderCounts).toBe(6); <add> } else { <add> expect(renderCounts).toBe(3); <add> } <ide> <del> expect(ops).toEqual(['Presses: 0, Clicks: 0']); <del> }, <del> ); <add> target.dispatchEvent(pointerdown({timeStamp: 100})); <add> target.dispatchEvent(pointerup({timeStamp: 100})); <add> // Ensure the timeStamp logic works <add> target.dispatchEvent(click({timeStamp: 101})); <ide> <del> it('should work correctly with stopPropagation set to true', () => { <del> const ref = React.createRef(); <del> const pointerDownEvent = jest.fn(); <add> if (__DEV__) { <add> expect(renderCounts).toBe(8); <add> } else { <add> expect(renderCounts).toBe(4); <add> } <ide> <del> const Component = () => { <del> const listener = usePressResponder({stopPropagation: true}); <add> Scheduler.unstable_flushAll(); <add> document.body.removeChild(newContainer); <add> }); <ide> <del> return <div ref={ref} listeners={listener} />; <del> }; <add> it( <add> 'should only flush before outermost discrete event handler when mixing ' + <add> 'event systems', <add> async () => { <add> const {useState} = React; <ide> <del> container.addEventListener('pointerdown', pointerDownEvent); <del> ReactDOM.render(<Component />, container); <add> const button = React.createRef(); <ide> <del> ref.current.dispatchEvent( <del> createEvent('pointerdown', {pointerType: 'mouse', button: 0}), <del> ); <del> container.removeEventListener('pointerdown', pointerDownEvent); <del> expect(pointerDownEvent).toHaveBeenCalledTimes(0); <del> }); <add> const ops = []; <ide> <del> it('has the correct press target when used with event hook', () => { <del> const ref = React.createRef(); <del> const onPress = jest.fn(); <del> const Component = () => { <del> const listener = usePressResponder({onPress}); <add> function MyComponent() { <add> const [pressesCount, updatePressesCount] = useState(0); <add> const [clicksCount, updateClicksCount] = useState(0); <ide> <del> return ( <del> <div> <del> <a href="#" ref={ref} listeners={listener} /> <del> </div> <del> ); <del> }; <del> ReactDOM.render(<Component />, container); <add> function handlePress() { <add> // This dispatches a synchronous, discrete event in the legacy event <add> // system. However, because it's nested inside the new event system, <add> // its updates should not flush until the end of the outer handler. <add> button.current.click(); <add> // Text context should not have changed <add> ops.push(newContainer.textContent); <add> updatePressesCount(pressesCount + 1); <add> } <ide> <del> ref.current.dispatchEvent( <del> createEvent('pointerdown', {pointerType: 'mouse', button: 0}), <del> ); <del> ref.current.dispatchEvent( <del> createEvent('pointerup', {pointerType: 'mouse', button: 0}), <del> ); <del> expect(onPress).toHaveBeenCalledTimes(1); <del> expect(onPress).toHaveBeenCalledWith( <del> expect.objectContaining({target: ref.current}), <add> const listener = usePressResponder({ <add> onPress: handlePress, <add> }); <add> <add> return ( <add> <div> <add> <button <add> listeners={listener} <add> ref={button} <add> onClick={() => updateClicksCount(clicksCount + 1)}> <add> Presses: {pressesCount}, Clicks: {clicksCount} <add> </button> <add> </div> <add> ); <add> } <add> <add> const newContainer = document.createElement('div'); <add> document.body.appendChild(newContainer); <add> const root = ReactDOM.unstable_createRoot(newContainer); <add> <add> root.render(<MyComponent />); <add> Scheduler.unstable_flushAll(); <add> expect(newContainer.textContent).toEqual('Presses: 0, Clicks: 0'); <add> <add> const target = button.current; <add> target.dispatchEvent(pointerdown({timeStamp: 100})); <add> target.dispatchEvent(pointerup({timeStamp: 100})); <add> target.dispatchEvent(click({timeStamp: 100})); <add> <add> Scheduler.unstable_flushAll(); <add> expect(newContainer.textContent).toEqual('Presses: 1, Clicks: 1'); <add> <add> expect(ops).toEqual(['Presses: 0, Clicks: 0']); <add> }, <ide> ); <del> }); <add> <add> it('should work correctly with stopPropagation set to true', () => { <add> const ref = React.createRef(); <add> const pointerDownEvent = jest.fn(); <add> <add> const Component = () => { <add> const listener = usePressResponder({stopPropagation: true}); <add> return <div ref={ref} listeners={listener} />; <add> }; <add> <add> container.addEventListener('pointerdown', pointerDownEvent); <add> ReactDOM.render(<Component />, container); <add> dispatchPointerDown(ref.current); <add> container.removeEventListener('pointerdown', pointerDownEvent); <add> expect(pointerDownEvent).toHaveBeenCalledTimes(0); <add> }); <add> } <ide> }); <ide><path>packages/react-events/src/dom/test-utils.js <ide> * Change environment support for PointerEvent. <ide> */ <ide> <del>function hasPointerEvent(bool) { <add>function hasPointerEvent() { <ide> return global != null && global.PointerEvent != null; <ide> } <ide> <ide> const platform = { <ide> * Mock native events <ide> */ <ide> <del>function createEvent(type, data) { <add>function createEvent(type, data = {}) { <ide> const event = document.createEvent('CustomEvent'); <ide> event.initCustomEvent(type, true, true); <add> event.clientX = data.x || 0; <add> event.clientY = data.y || 0; <add> event.x = data.x || 0; <add> event.y = data.y || 0; <ide> if (data != null) { <del> Object.entries(data).forEach(([key, value]) => { <del> event[key] = value; <add> Object.keys(data).forEach(key => { <add> const value = data[key]; <add> Object.defineProperty(event, key, {value}); <ide> }); <ide> } <ide> return event; <ide> } <ide> <del>function createTouchEvent(type, data, id) { <add>function createTouchEvent(type, data = {}, id) { <ide> return createEvent(type, { <ide> changedTouches: [ <ide> { <add> identifier: id, <add> clientX: data.x || 0, <add> clientY: data.y || 0, <ide> ...data, <add> }, <add> ], <add> targetTouches: [ <add> { <ide> identifier: id, <add> clientX: 0 || data.x, <add> clientY: 0 || data.y, <add> ...data, <ide> }, <ide> ], <ide> }); <ide> function gotpointercapture(data) { <ide> } <ide> <ide> function keydown(data) { <del> return createKeyboardEvent('keydown', data); <add> return createEvent('keydown', data); <ide> } <ide> <ide> function keyup(data) { <del> return createKeyboardEvent('keyup', data); <add> return createEvent('keyup', data); <ide> } <ide> <ide> function lostpointercapture(data) { <ide> return createEvent('lostpointercapture', data); <ide> } <ide> <add>function mousedown(data) { <add> return createEvent('mousedown', data); <add>} <add> <add>function mouseenter(data) { <add> return createEvent('mouseenter', data); <add>} <add> <add>function mouseleave(data) { <add> return createEvent('mouseleave', data); <add>} <add> <add>function mousemove(data) { <add> return createEvent('mousemove', data); <add>} <add> <add>function mouseout(data) { <add> return createEvent('mouseout', data); <add>} <add> <add>function mouseover(data) { <add> return createEvent('mouseover', data); <add>} <add> <add>function mouseup(data) { <add> return createEvent('mouseup', data); <add>} <add> <ide> function pointercancel(data) { <ide> return createEvent('pointercancel', data); <ide> } <ide> function pointerup(data) { <ide> return createEvent('pointerup', data); <ide> } <ide> <del>function mousedown(data) { <del> return createEvent('mousedown', data); <del>} <del> <del>function mouseenter(data) { <del> return createEvent('mouseenter', data); <del>} <del> <del>function mouseleave(data) { <del> return createEvent('mouseleave', data); <del>} <del> <del>function mousemove(data) { <del> return createEvent('mousemove', data); <del>} <del> <del>function mouseout(data) { <del> return createEvent('mouseout', data); <del>} <del> <del>function mouseover(data) { <del> return createEvent('mouseover', data); <del>} <del> <del>function mouseup(data) { <del> return createEvent('mouseup', data); <add>function scroll(data) { <add> return createEvent('scroll', data); <ide> } <ide> <ide> function touchcancel(data, id) { <ide> function dispatchPointerHoverEnter(target, {relatedTarget, x, y} = {}) { <ide> dispatch(pointerenter({pointerType, ...event})); <ide> } <ide> dispatch(mouseover(event)); <del> dispatch(mouseover(event)); <add> dispatch(mouseenter(event)); <ide> } <ide> <del>function dispatchPointerHoverMove(target, {from, to} = {}) { <add>function dispatchPointerHoverMove(target, {x, y} = {}) { <ide> const dispatch = arg => target.dispatchEvent(arg); <ide> const button = -1; <ide> const pointerId = 1; <ide> const pointerType = 'mouse'; <del> function dispatchMove({x, y}) { <add> function dispatchMove() { <ide> const event = { <ide> button, <ide> clientX: x, <ide> function dispatchPointerHoverMove(target, {from, to} = {}) { <ide> } <ide> dispatch(mousemove(event)); <ide> } <del> dispatchMove({x: from.x, y: from.y}); <del> dispatchMove({x: to.x, y: to.y}); <add> dispatchMove(); <ide> } <ide> <ide> function dispatchPointerHoverExit(target, {relatedTarget, x, y} = {}) { <ide> function dispatchPointerHoverExit(target, {relatedTarget, x, y} = {}) { <ide> dispatch(mouseleave(event)); <ide> } <ide> <del>function dispatchPointerCancel(target, options) { <add>function dispatchPointerCancel(target, {pointerType = 'mouse', ...rest} = {}) { <ide> const dispatchEvent = arg => target.dispatchEvent(arg); <del> dispatchEvent(pointercancel({pointerType: 'mouse'})); <del> dispatchEvent(dragstart({pointerType: 'mouse'})); <add> if (hasPointerEvent()) { <add> dispatchEvent(pointercancel({pointerType, ...rest})); <add> } else { <add> if (pointerType === 'mouse') { <add> dispatchEvent(dragstart({...rest})); <add> } else { <add> dispatchEvent(touchcancel({...rest})); <add> } <add> } <ide> } <ide> <del>function dispatchPointerPressDown( <add>function dispatchPointerDown( <ide> target, <del> {button = 0, pointerType = 'mouse'} = {}, <add> {button = 0, pointerType = 'mouse', ...rest} = {}, <ide> ) { <ide> const dispatch = arg => target.dispatchEvent(arg); <ide> const pointerId = 1; <del> if (pointerType !== 'mouse') { <add> const pointerEvent = {button, pointerId, pointerType, ...rest}; <add> const mouseEvent = {button, ...rest}; <add> const touch = {...rest}; <add> <add> if (pointerType === 'mouse') { <ide> if (hasPointerEvent()) { <del> dispatch(pointerover({button, pointerId, pointerType})); <del> dispatch(pointerenter({button, pointerId, pointerType})); <del> dispatch(pointerdown({button, pointerId, pointerType})); <add> dispatch(pointerover(pointerEvent)); <add> dispatch(pointerenter(pointerEvent)); <ide> } <del> dispatch(touchstart(null, pointerId)); <add> dispatch(mouseover(mouseEvent)); <add> dispatch(mouseenter(mouseEvent)); <ide> if (hasPointerEvent()) { <del> dispatch(gotpointercapture({button, pointerId, pointerType})); <add> dispatch(pointerdown(pointerEvent)); <add> } <add> dispatch(mousedown(mouseEvent)); <add> if (document.activeElement !== target) { <add> dispatch(focus()); <ide> } <ide> } else { <ide> if (hasPointerEvent()) { <del> dispatch(pointerdown({button, pointerId, pointerType})); <add> dispatch(pointerover(pointerEvent)); <add> dispatch(pointerenter(pointerEvent)); <add> dispatch(pointerdown(pointerEvent)); <ide> } <del> dispatch(mousedown({button})); <del> if (document.activeElement !== target) { <del> dispatch(focus({button})); <add> dispatch(touchstart(touch, pointerId)); <add> if (hasPointerEvent()) { <add> dispatch(gotpointercapture(pointerEvent)); <ide> } <ide> } <ide> } <ide> <del>function dispatchPointerPressRelease( <add>function dispatchPointerUp( <ide> target, <del> {button = 0, pointerType = 'mouse'} = {}, <add> {button = 0, pointerType = 'mouse', ...rest} = {}, <ide> ) { <ide> const dispatch = arg => target.dispatchEvent(arg); <ide> const pointerId = 1; <del> if (pointerType !== 'mouse') { <add> const pointerEvent = {button, pointerId, pointerType, ...rest}; <add> const mouseEvent = {button, ...rest}; <add> const touch = {...rest}; <add> <add> if (pointerType === 'mouse') { <ide> if (hasPointerEvent()) { <del> dispatch(pointerup({button, pointerId, pointerType})); <del> dispatch(lostpointercapture({button, pointerId, pointerType})); <del> dispatch(pointerout({button, pointerId, pointerType})); <del> dispatch(pointerleave({button, pointerId, pointerType})); <del> } <del> dispatch(touchend(null, pointerId)); <del> dispatch(mouseover({button})); <del> dispatch(mousemove({button})); <del> dispatch(mousedown({button})); <del> if (document.activeElement !== target) { <del> dispatch(focus({button})); <add> dispatch(pointerup(pointerEvent)); <ide> } <del> dispatch(mouseup({button})); <del> dispatch(click({button})); <add> dispatch(mouseup(mouseEvent)); <add> dispatch(click(mouseEvent)); <ide> } else { <ide> if (hasPointerEvent()) { <del> dispatch(pointerup({button, pointerId, pointerType})); <add> dispatch(pointerup(pointerEvent)); <add> dispatch(lostpointercapture(pointerEvent)); <add> dispatch(pointerout(pointerEvent)); <add> dispatch(pointerleave(pointerEvent)); <ide> } <del> dispatch(mouseup({button})); <del> dispatch(click({button})); <add> dispatch(touchend(touch, pointerId)); <add> dispatch(mouseover(mouseEvent)); <add> dispatch(mousemove(mouseEvent)); <add> dispatch(mousedown(mouseEvent)); <add> if (document.activeElement !== target) { <add> dispatch(focus()); <add> } <add> dispatch(mouseup(mouseEvent)); <add> dispatch(click(mouseEvent)); <add> } <add>} <add> <add>function dispatchPointerMove( <add> target, <add> {button = 0, pointerType = 'mouse', ...rest} = {}, <add>) { <add> const dispatch = arg => target.dispatchEvent(arg); <add> const pointerId = 1; <add> const pointerEvent = { <add> button, <add> pointerId, <add> pointerType, <add> ...rest, <add> }; <add> const mouseEvent = { <add> button, <add> ...rest, <add> }; <add> const touch = { <add> ...rest, <add> }; <add> <add> if (hasPointerEvent()) { <add> dispatch(pointermove(pointerEvent)); <add> } <add> if (pointerType === 'mouse') { <add> dispatch(mousemove(mouseEvent)); <add> } <add> if (pointerType === 'touch') { <add> dispatch(touchmove(touch, pointerId)); <ide> } <ide> } <ide> <ide> function dispatchTouchTap(target) { <del> dispatchPointerPressDown(target, {pointerType: 'touch'}); <del> dispatchPointerPressRelease(target, {pointerType: 'touch'}); <add> dispatchPointerDown(target, {pointerType: 'touch'}); <add> dispatchPointerUp(target, {pointerType: 'touch'}); <add>} <add> <add>function dispatchMouseTap(target) { <add> dispatchPointerDown(target, {pointerType: 'mouse'}); <add> dispatchPointerUp(target, {pointerType: 'mouse'}); <ide> } <ide> <ide> module.exports = { <ide> blur, <add> click, <ide> focus, <ide> createEvent, <ide> dispatchLongPressContextMenu, <ide> module.exports = { <ide> dispatchPointerHoverEnter, <ide> dispatchPointerHoverExit, <ide> dispatchPointerHoverMove, <del> dispatchPointerPressDown, <del> dispatchPointerPressRelease, <add> dispatchPointerMove, <add> dispatchPointerDown, <add> dispatchPointerUp, <ide> dispatchTouchTap, <add> dispatchMouseTap, <ide> keydown, <ide> keyup, <add> scroll, <add> pointerdown, <add> pointerup, <ide> platform, <ide> hasPointerEvent, <ide> setPointerEvent,
6
Go
Go
honor context cancellation when pruning
0dee69799eb467543dc2ae4cc3bb7b46bc7e21d4
<ide><path>api/server/router/container/backend.go <ide> type attachBackend interface { <ide> <ide> // systemBackend includes functions to implement to provide system wide containers functionality <ide> type systemBackend interface { <del> ContainersPrune(pruneFilters filters.Args) (*types.ContainersPruneReport, error) <add> ContainersPrune(ctx context.Context, pruneFilters filters.Args) (*types.ContainersPruneReport, error) <ide> } <ide> <ide> // Backend is all the methods that need to be implemented to provide container specific functionality. <ide><path>api/server/router/container/container.go <ide> func (r *containerRouter) initRoutes() { <ide> router.NewPostRoute("/exec/{name:.*}/resize", r.postContainerExecResize), <ide> router.NewPostRoute("/containers/{name:.*}/rename", r.postContainerRename), <ide> router.NewPostRoute("/containers/{name:.*}/update", r.postContainerUpdate), <del> router.NewPostRoute("/containers/prune", r.postContainersPrune), <add> router.NewPostRoute("/containers/prune", r.postContainersPrune, router.WithCancel), <ide> // PUT <ide> router.NewPutRoute("/containers/{name:.*}/archive", r.putContainersArchive), <ide> // DELETE <ide><path>api/server/router/container/container_routes.go <ide> func (s *containerRouter) postContainersPrune(ctx context.Context, w http.Respon <ide> return err <ide> } <ide> <del> pruneReport, err := s.backend.ContainersPrune(pruneFilters) <add> pruneReport, err := s.backend.ContainersPrune(ctx, pruneFilters) <ide> if err != nil { <ide> return err <ide> } <ide><path>api/server/router/image/backend.go <ide> type imageBackend interface { <ide> Images(imageFilters filters.Args, all bool, withExtraAttrs bool) ([]*types.ImageSummary, error) <ide> LookupImage(name string) (*types.ImageInspect, error) <ide> TagImage(imageName, repository, tag string) error <del> ImagesPrune(pruneFilters filters.Args) (*types.ImagesPruneReport, error) <add> ImagesPrune(ctx context.Context, pruneFilters filters.Args) (*types.ImagesPruneReport, error) <ide> } <ide> <ide> type importExportBackend interface { <ide><path>api/server/router/image/image.go <ide> func (r *imageRouter) initRoutes() { <ide> router.NewPostRoute("/images/create", r.postImagesCreate, router.WithCancel), <ide> router.NewPostRoute("/images/{name:.*}/push", r.postImagesPush, router.WithCancel), <ide> router.NewPostRoute("/images/{name:.*}/tag", r.postImagesTag), <del> router.NewPostRoute("/images/prune", r.postImagesPrune), <add> router.NewPostRoute("/images/prune", r.postImagesPrune, router.WithCancel), <ide> // DELETE <ide> router.NewDeleteRoute("/images/{name:.*}", r.deleteImages), <ide> } <ide><path>api/server/router/image/image_routes.go <ide> func (s *imageRouter) postImagesPrune(ctx context.Context, w http.ResponseWriter <ide> return err <ide> } <ide> <del> pruneReport, err := s.backend.ImagesPrune(pruneFilters) <add> pruneReport, err := s.backend.ImagesPrune(ctx, pruneFilters) <ide> if err != nil { <ide> return err <ide> } <ide><path>api/server/router/network/backend.go <ide> package network <ide> <ide> import ( <add> "golang.org/x/net/context" <add> <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/filters" <ide> "github.com/docker/docker/api/types/network" <ide> type Backend interface { <ide> ConnectContainerToNetwork(containerName, networkName string, endpointConfig *network.EndpointSettings) error <ide> DisconnectContainerFromNetwork(containerName string, networkName string, force bool) error <ide> DeleteNetwork(name string) error <del> NetworksPrune(pruneFilters filters.Args) (*types.NetworksPruneReport, error) <add> NetworksPrune(ctx context.Context, pruneFilters filters.Args) (*types.NetworksPruneReport, error) <ide> } <ide><path>api/server/router/network/network.go <ide> func (r *networkRouter) initRoutes() { <ide> router.NewPostRoute("/networks/create", r.postNetworkCreate), <ide> router.NewPostRoute("/networks/{id:.*}/connect", r.postNetworkConnect), <ide> router.NewPostRoute("/networks/{id:.*}/disconnect", r.postNetworkDisconnect), <del> router.NewPostRoute("/networks/prune", r.postNetworksPrune), <add> router.NewPostRoute("/networks/prune", r.postNetworksPrune, router.WithCancel), <ide> // DELETE <ide> router.NewDeleteRoute("/networks/{id:.*}", r.deleteNetwork), <ide> } <ide><path>api/server/router/network/network_routes.go <ide> func (n *networkRouter) postNetworksPrune(ctx context.Context, w http.ResponseWr <ide> return err <ide> } <ide> <del> pruneReport, err := n.backend.NetworksPrune(pruneFilters) <add> pruneReport, err := n.backend.NetworksPrune(ctx, pruneFilters) <ide> if err != nil { <ide> return err <ide> } <ide><path>api/server/router/volume/backend.go <ide> package volume <ide> <ide> import ( <add> "golang.org/x/net/context" <add> <ide> // TODO return types need to be refactored into pkg <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/filters" <ide> type Backend interface { <ide> VolumeInspect(name string) (*types.Volume, error) <ide> VolumeCreate(name, driverName string, opts, labels map[string]string) (*types.Volume, error) <ide> VolumeRm(name string, force bool) error <del> VolumesPrune(pruneFilters filters.Args) (*types.VolumesPruneReport, error) <add> VolumesPrune(ctx context.Context, pruneFilters filters.Args) (*types.VolumesPruneReport, error) <ide> } <ide><path>api/server/router/volume/volume.go <ide> func (r *volumeRouter) initRoutes() { <ide> router.NewGetRoute("/volumes/{name:.*}", r.getVolumeByName), <ide> // POST <ide> router.NewPostRoute("/volumes/create", r.postVolumesCreate), <del> router.NewPostRoute("/volumes/prune", r.postVolumesPrune), <add> router.NewPostRoute("/volumes/prune", r.postVolumesPrune, router.WithCancel), <ide> // DELETE <ide> router.NewDeleteRoute("/volumes/{name:.*}", r.deleteVolumes), <ide> } <ide><path>api/server/router/volume/volume_routes.go <ide> func (v *volumeRouter) postVolumesPrune(ctx context.Context, w http.ResponseWrit <ide> return err <ide> } <ide> <del> pruneReport, err := v.backend.VolumesPrune(pruneFilters) <add> pruneReport, err := v.backend.VolumesPrune(ctx, pruneFilters) <ide> if err != nil { <ide> return err <ide> } <ide><path>daemon/prune.go <ide> import ( <ide> "regexp" <ide> "time" <ide> <add> "golang.org/x/net/context" <add> <ide> "github.com/Sirupsen/logrus" <ide> "github.com/docker/distribution/reference" <ide> "github.com/docker/docker/api/types" <ide> import ( <ide> ) <ide> <ide> // ContainersPrune removes unused containers <del>func (daemon *Daemon) ContainersPrune(pruneFilters filters.Args) (*types.ContainersPruneReport, error) { <add>func (daemon *Daemon) ContainersPrune(ctx context.Context, pruneFilters filters.Args) (*types.ContainersPruneReport, error) { <ide> rep := &types.ContainersPruneReport{} <ide> <ide> until, err := getUntilFromPruneFilters(pruneFilters) <ide> func (daemon *Daemon) ContainersPrune(pruneFilters filters.Args) (*types.Contain <ide> <ide> allContainers := daemon.List() <ide> for _, c := range allContainers { <add> select { <add> case <-ctx.Done(): <add> logrus.Warnf("ContainersPrune operation cancelled: %#v", *rep) <add> return rep, ctx.Err() <add> default: <add> } <add> <ide> if !c.IsRunning() { <ide> if !until.IsZero() && c.Created.After(until) { <ide> continue <ide> func (daemon *Daemon) ContainersPrune(pruneFilters filters.Args) (*types.Contain <ide> } <ide> <ide> // VolumesPrune removes unused local volumes <del>func (daemon *Daemon) VolumesPrune(pruneFilters filters.Args) (*types.VolumesPruneReport, error) { <add>func (daemon *Daemon) VolumesPrune(ctx context.Context, pruneFilters filters.Args) (*types.VolumesPruneReport, error) { <ide> rep := &types.VolumesPruneReport{} <ide> <ide> pruneVols := func(v volume.Volume) error { <add> select { <add> case <-ctx.Done(): <add> logrus.Warnf("VolumesPrune operation cancelled: %#v", *rep) <add> return ctx.Err() <add> default: <add> } <add> <ide> name := v.Name() <ide> refs := daemon.volumes.Refs(v) <ide> <ide> func (daemon *Daemon) VolumesPrune(pruneFilters filters.Args) (*types.VolumesPru <ide> } <ide> <ide> // ImagesPrune removes unused images <del>func (daemon *Daemon) ImagesPrune(pruneFilters filters.Args) (*types.ImagesPruneReport, error) { <add>func (daemon *Daemon) ImagesPrune(ctx context.Context, pruneFilters filters.Args) (*types.ImagesPruneReport, error) { <ide> rep := &types.ImagesPruneReport{} <ide> <ide> danglingOnly := true <ide> func (daemon *Daemon) ImagesPrune(pruneFilters filters.Args) (*types.ImagesPrune <ide> allContainers := daemon.List() <ide> imageRefs := map[string]bool{} <ide> for _, c := range allContainers { <del> imageRefs[c.ID] = true <add> select { <add> case <-ctx.Done(): <add> return nil, ctx.Err() <add> default: <add> imageRefs[c.ID] = true <add> } <ide> } <ide> <ide> // Filter intermediary images and get their unique size <ide> allLayers := daemon.layerStore.Map() <ide> topImages := map[image.ID]*image.Image{} <ide> for id, img := range allImages { <del> dgst := digest.Digest(id) <del> if len(daemon.referenceStore.References(dgst)) == 0 && len(daemon.imageStore.Children(id)) != 0 { <del> continue <del> } <del> if !until.IsZero() && img.Created.After(until) { <del> continue <del> } <del> if !matchLabels(pruneFilters, img.Config.Labels) { <del> continue <add> select { <add> case <-ctx.Done(): <add> return nil, ctx.Err() <add> default: <add> dgst := digest.Digest(id) <add> if len(daemon.referenceStore.References(dgst)) == 0 && len(daemon.imageStore.Children(id)) != 0 { <add> continue <add> } <add> if !until.IsZero() && img.Created.After(until) { <add> continue <add> } <add> if !matchLabels(pruneFilters, img.Config.Labels) { <add> continue <add> } <add> topImages[id] = img <ide> } <del> topImages[id] = img <ide> } <ide> <add> canceled := false <add>deleteImagesLoop: <ide> for id := range topImages { <add> select { <add> case <-ctx.Done(): <add> // we still want to calculate freed size and return the data <add> canceled = true <add> break deleteImagesLoop <add> default: <add> } <add> <ide> dgst := digest.Digest(id) <ide> hex := dgst.Hex() <ide> if _, ok := imageRefs[hex]; ok { <ide> func (daemon *Daemon) ImagesPrune(pruneFilters filters.Args) (*types.ImagesPrune <ide> } <ide> } <ide> <add> if canceled { <add> logrus.Warnf("ImagesPrune operation cancelled: %#v", *rep) <add> return nil, ctx.Err() <add> } <add> <ide> return rep, nil <ide> } <ide> <ide> // localNetworksPrune removes unused local networks <del>func (daemon *Daemon) localNetworksPrune(pruneFilters filters.Args) *types.NetworksPruneReport { <add>func (daemon *Daemon) localNetworksPrune(ctx context.Context, pruneFilters filters.Args) *types.NetworksPruneReport { <ide> rep := &types.NetworksPruneReport{} <ide> <ide> until, _ := getUntilFromPruneFilters(pruneFilters) <ide> <ide> // When the function returns true, the walk will stop. <ide> l := func(nw libnetwork.Network) bool { <add> select { <add> case <-ctx.Done(): <add> return true <add> default: <add> } <ide> if !until.IsZero() && nw.Info().Created().After(until) { <ide> return false <ide> } <ide> func (daemon *Daemon) localNetworksPrune(pruneFilters filters.Args) *types.Netwo <ide> } <ide> <ide> // clusterNetworksPrune removes unused cluster networks <del>func (daemon *Daemon) clusterNetworksPrune(pruneFilters filters.Args) (*types.NetworksPruneReport, error) { <add>func (daemon *Daemon) clusterNetworksPrune(ctx context.Context, pruneFilters filters.Args) (*types.NetworksPruneReport, error) { <ide> rep := &types.NetworksPruneReport{} <ide> <ide> until, _ := getUntilFromPruneFilters(pruneFilters) <ide> func (daemon *Daemon) clusterNetworksPrune(pruneFilters filters.Args) (*types.Ne <ide> } <ide> networkIsInUse := regexp.MustCompile(`network ([[:alnum:]]+) is in use`) <ide> for _, nw := range networks { <del> if nw.Ingress { <del> // Routing-mesh network removal has to be explicitly invoked by user <del> continue <del> } <del> if !until.IsZero() && nw.Created.After(until) { <del> continue <del> } <del> if !matchLabels(pruneFilters, nw.Labels) { <del> continue <del> } <del> // https://github.com/docker/docker/issues/24186 <del> // `docker network inspect` unfortunately displays ONLY those containers that are local to that node. <del> // So we try to remove it anyway and check the error <del> err = cluster.RemoveNetwork(nw.ID) <del> if err != nil { <del> // we can safely ignore the "network .. is in use" error <del> match := networkIsInUse.FindStringSubmatch(err.Error()) <del> if len(match) != 2 || match[1] != nw.ID { <del> logrus.Warnf("could not remove cluster network %s: %v", nw.Name, err) <add> select { <add> case <-ctx.Done(): <add> return rep, ctx.Err() <add> default: <add> if nw.Ingress { <add> // Routing-mesh network removal has to be explicitly invoked by user <add> continue <ide> } <del> continue <add> if !until.IsZero() && nw.Created.After(until) { <add> continue <add> } <add> if !matchLabels(pruneFilters, nw.Labels) { <add> continue <add> } <add> // https://github.com/docker/docker/issues/24186 <add> // `docker network inspect` unfortunately displays ONLY those containers that are local to that node. <add> // So we try to remove it anyway and check the error <add> err = cluster.RemoveNetwork(nw.ID) <add> if err != nil { <add> // we can safely ignore the "network .. is in use" error <add> match := networkIsInUse.FindStringSubmatch(err.Error()) <add> if len(match) != 2 || match[1] != nw.ID { <add> logrus.Warnf("could not remove cluster network %s: %v", nw.Name, err) <add> } <add> continue <add> } <add> rep.NetworksDeleted = append(rep.NetworksDeleted, nw.Name) <ide> } <del> rep.NetworksDeleted = append(rep.NetworksDeleted, nw.Name) <ide> } <ide> return rep, nil <ide> } <ide> <ide> // NetworksPrune removes unused networks <del>func (daemon *Daemon) NetworksPrune(pruneFilters filters.Args) (*types.NetworksPruneReport, error) { <add>func (daemon *Daemon) NetworksPrune(ctx context.Context, pruneFilters filters.Args) (*types.NetworksPruneReport, error) { <ide> if _, err := getUntilFromPruneFilters(pruneFilters); err != nil { <ide> return nil, err <ide> } <ide> <ide> rep := &types.NetworksPruneReport{} <del> if clusterRep, err := daemon.clusterNetworksPrune(pruneFilters); err == nil { <add> if clusterRep, err := daemon.clusterNetworksPrune(ctx, pruneFilters); err == nil { <ide> rep.NetworksDeleted = append(rep.NetworksDeleted, clusterRep.NetworksDeleted...) <ide> } <ide> <del> localRep := daemon.localNetworksPrune(pruneFilters) <add> localRep := daemon.localNetworksPrune(ctx, pruneFilters) <ide> rep.NetworksDeleted = append(rep.NetworksDeleted, localRep.NetworksDeleted...) <add> <add> select { <add> case <-ctx.Done(): <add> logrus.Warnf("NetworksPrune operation cancelled: %#v", *rep) <add> return nil, ctx.Err() <add> default: <add> } <add> <ide> return rep, nil <ide> } <ide>
13
Text
Text
add link to airflow website in readme
51be6ec1c0f430d964c3f32895a9f909d3ff8300
<ide><path>README.md <ide> [![Twitter Follow](https://img.shields.io/twitter/follow/ApacheAirflow.svg?style=social&label=Follow)](https://twitter.com/ApacheAirflow) <ide> [![Slack Status](https://img.shields.io/badge/slack-join_chat-white.svg?logo=slack&style=social)](https://apache-airflow-slack.herokuapp.com/) <ide> <del>Apache Airflow (or simply Airflow) is a platform to programmatically author, schedule, and monitor workflows. <add>[Apache Airflow](https://airflow.apache.org/docs/stable/) (or simply Airflow) is a platform to programmatically author, schedule, and monitor <add> workflows. <ide> <ide> When workflows are defined as code, they become more maintainable, <ide> versionable, testable, and collaborative. <ide> Yes! Be sure to abide by the Apache Foundation [trademark policies](https://www. <ide> <ide> ## Links <ide> <del>- [Documentation](https://airflow.apache.org/) <add>- [Documentation](https://airflow.apache.org/docs/stable/) <ide> - [Chat](https://apache-airflow-slack.herokuapp.com/) <ide> - [More](https://cwiki.apache.org/confluence/display/AIRFLOW/Airflow+Links)
1
Text
Text
fix links to code of conduct [ci skip]
abc7b88e755b712727e37ba24187bf85404a9b74
<ide><path>guides/source/contributing_to_ruby_on_rails.md <ide> After reading this guide, you will know: <ide> Ruby on Rails is not "someone else's framework." Over the years, hundreds of people have contributed to Ruby on Rails ranging from a single character to massive architectural changes or significant documentation - all with the goal of making Ruby on Rails better for everyone. Even if you don't feel up to writing code or documentation yet, there are a variety of other ways that you can contribute, from reporting issues to testing patches. <ide> <ide> As mentioned in [Rails <del>README](https://github.com/rails/rails/blob/master/README.md), everyone interacting in Rails and its sub-projects' codebases, issue trackers, chat rooms, and mailing lists is expected to follow the Rails [code of conduct](https://github.com/rails/rails/blob/master/CODE_OF_CONDUCT.md). <add>README](https://github.com/rails/rails/blob/master/README.md), everyone interacting in Rails and its sub-projects' codebases, issue trackers, chat rooms, and mailing lists is expected to follow the Rails [code of conduct](http://rubyonrails.org/conduct/). <ide> <ide> -------------------------------------------------------------------------------- <ide>
1
Go
Go
remove bypid from execcommands
6f3e86e906a8955d3dc3ddc2a6be51b17e7a097f
<ide><path>daemon/exec.go <ide> func (d *Daemon) registerExecCommand(container *container.Container, config *exe <ide> d.execCommands.Add(config.ID, config) <ide> } <ide> <del>func (d *Daemon) registerExecPidUnlocked(container *container.Container, config *exec.Config) { <del> logrus.Debugf("registering pid %v for exec %v", config.Pid, config.ID) <del> // Storing execs in container in order to kill them gracefully whenever the container is stopped or removed. <del> container.ExecCommands.SetPidUnlocked(config.ID, config.Pid) <del> // Storing execs in daemon for easy access via Engine API. <del> d.execCommands.SetPidUnlocked(config.ID, config.Pid) <del>} <del> <ide> // ExecExists looks up the exec instance and returns a bool if it exists or not. <ide> // It will also return the error produced by `getConfig` <ide> func (d *Daemon) ExecExists(name string) (bool, error) { <ide> func (d *Daemon) ContainerExecStart(ctx context.Context, name string, stdin io.R <ide> return translateContainerdStartErr(ec.Entrypoint, ec.SetExitCode, err) <ide> } <ide> ec.Pid = systemPid <del> d.registerExecPidUnlocked(c, ec) <ide> c.ExecCommands.Unlock() <ide> ec.Unlock() <ide> <ide><path>daemon/exec/exec.go <ide> func (c *Config) SetExitCode(code int) { <ide> <ide> // Store keeps track of the exec configurations. <ide> type Store struct { <del> byID map[string]*Config <del> byPid map[int]*Config <add> byID map[string]*Config <ide> sync.RWMutex <ide> } <ide> <ide> // NewStore initializes a new exec store. <ide> func NewStore() *Store { <ide> return &Store{ <del> byID: make(map[string]*Config), <del> byPid: make(map[int]*Config), <add> byID: make(map[string]*Config), <ide> } <ide> } <ide> <ide> func (e *Store) Add(id string, Config *Config) { <ide> e.Unlock() <ide> } <ide> <del>// SetPidUnlocked adds an association between a Pid and a config, it does not <del>// synchronized with other operations. <del>func (e *Store) SetPidUnlocked(id string, pid int) { <del> if config, ok := e.byID[id]; ok { <del> e.byPid[pid] = config <del> } <del>} <del> <ide> // Get returns an exec configuration by its id. <ide> func (e *Store) Get(id string) *Config { <ide> e.RLock() <ide> func (e *Store) Get(id string) *Config { <ide> return res <ide> } <ide> <del>// ByPid returns an exec configuration by its pid. <del>func (e *Store) ByPid(pid int) *Config { <del> e.RLock() <del> res := e.byPid[pid] <del> e.RUnlock() <del> return res <del>} <del> <ide> // Delete removes an exec configuration from the store. <ide> func (e *Store) Delete(id string, pid int) { <ide> e.Lock() <del> delete(e.byPid, pid) <ide> delete(e.byID, id) <ide> e.Unlock() <ide> } <ide><path>daemon/monitor.go <ide> func (daemon *Daemon) ProcessEvent(id string, e libcontainerd.EventType, ei libc <ide> return daemon.postRunProcessing(c, ei) <ide> } <ide> <del> if execConfig := c.ExecCommands.ByPid(int(ei.Pid)); execConfig != nil { <add> if execConfig := c.ExecCommands.Get(ei.ProcessID); execConfig != nil { <ide> ec := int(ei.ExitCode) <ide> execConfig.Lock() <ide> defer execConfig.Unlock() <ide> func (daemon *Daemon) ProcessEvent(id string, e libcontainerd.EventType, ei libc <ide> } else { <ide> logrus.WithFields(logrus.Fields{ <ide> "container": c.ID, <add> "exec-id": ei.ProcessID, <ide> "exec-pid": ei.Pid, <ide> }).Warnf("Ignoring Exit Event, no such exec command found") <ide> }
3
Ruby
Ruby
cache the klass member of the reflection
743b67508e2027e1d086142ccbec47a19fc943f6
<ide><path>activerecord/lib/active_record/associations/join_dependency/join_association.rb <ide> def find_parent_in(other_join_dependency) <ide> <ide> def join_to(manager) <ide> tables = @tables.dup <add> <ide> foreign_table = parent_table <ide> foreign_klass = parent.base_klass <ide> <ide> def join_to(manager) <ide> # more sense in this context), so we reverse <ide> chain.reverse_each do |reflection| <ide> table = tables.shift <add> klass = reflection.klass <ide> <ide> case reflection.source_macro <ide> when :belongs_to <ide> def join_to(manager) <ide> foreign_key = reflection.active_record_primary_key <ide> end <ide> <del> constraint = build_constraint(reflection, table, key, foreign_table, foreign_key) <add> constraint = build_constraint(klass, table, key, foreign_table, foreign_key) <ide> <ide> scope_chain_items = scope_chain_iter.next.map do |item| <ide> if item.is_a?(Relation) <ide> item <ide> else <del> ActiveRecord::Relation.new(reflection.klass, table).instance_exec(self, &item) <add> ActiveRecord::Relation.new(klass, table).instance_exec(self, &item) <ide> end <ide> end <ide> <ide> if reflection.type <ide> scope_chain_items << <del> ActiveRecord::Relation.new(reflection.klass, table) <add> ActiveRecord::Relation.new(klass, table) <ide> .where(reflection.type => foreign_klass.base_class.name) <ide> end <ide> <del> scope_chain_items.concat [reflection.klass.send(:build_default_scope)].compact <add> scope_chain_items.concat [klass.send(:build_default_scope)].compact <ide> <ide> rel = scope_chain_items.inject(scope_chain_items.shift) do |left, right| <ide> left.merge right <ide> def join_to(manager) <ide> manager.from(join(table, constraint)) <ide> <ide> # The current table in this iteration becomes the foreign table in the next <del> foreign_table, foreign_klass = table, reflection.klass <add> foreign_table, foreign_klass = table, klass <ide> end <ide> <ide> manager <ide> def join_to(manager) <ide> # foreign_table #=> #<Arel::Table @name="physicians" ...> <ide> # foreign_key #=> id <ide> # <del> def build_constraint(reflection, table, key, foreign_table, foreign_key) <add> def build_constraint(klass, table, key, foreign_table, foreign_key) <ide> constraint = table[key].eq(foreign_table[foreign_key]) <ide> <del> if reflection.klass.finder_needs_type_condition? <add> if klass.finder_needs_type_condition? <ide> constraint = table.create_and([ <ide> constraint, <del> reflection.klass.send(:type_condition, table) <add> klass.send(:type_condition, table) <ide> ]) <ide> end <ide>
1
PHP
PHP
add intersect by keys method to collections
4fc0ea5389424876bdbd858bbb3df97e9adc0b28
<ide><path>src/Illuminate/Support/Collection.php <ide> public function intersect($items) <ide> return new static(array_intersect($this->items, $this->getArrayableItems($items))); <ide> } <ide> <add> /** <add> * Intersect the collection with the given items by key <add> * <add> * @param mixed $items <add> * @return static <add> */ <add> public function intersectByKeys($items) <add> { <add> return new static(array_intersect_key($this->items, $this->getArrayableItems($items))); <add> } <add> <ide> /** <ide> * Determine if the collection is empty or not. <ide> * <ide><path>tests/Support/SupportCollectionTest.php <ide> public function testIntersectCollection() <ide> $this->assertEquals(['first_word' => 'Hello'], $c->intersect(new Collection(['first_world' => 'Hello', 'last_word' => 'World']))->all()); <ide> } <ide> <add> public function testIntersectByKeysNull() <add> { <add> $c = new Collection(['name' => 'Mateus', 'age' => 18]); <add> $this->assertEquals([], $c->intersectByKeys(null)->all()); <add> } <add> <add> public function testIntersectByKeys() <add> { <add> $c = new Collection(['name' => 'Mateus', 'age' => 18]); <add> $this->assertEquals(['name' => 'Mateus'], $c->intersectByKeys(new Collection(['name' => 'Mateus', 'surname' => 'Guimaraes']))->all()); <add> } <add> <ide> public function testUnique() <ide> { <ide> $c = new Collection(['Hello', 'World', 'World']);
2
Java
Java
add marble diagram for single.repeatuntil operator
97ebd2c0ba3d1505631b844d2ff5000944be2ae6
<ide><path>src/main/java/io/reactivex/Single.java <ide> public final Flowable<T> repeatWhen(Function<? super Flowable<Object>, ? extends <ide> <ide> /** <ide> * Re-subscribes to the current Single until the given BooleanSupplier returns true. <add> * <p> <add> * <img width="640" height="463" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.repeatUntil.png" alt=""> <ide> * <dl> <ide> * <dt><b>Backpressure:</b></dt> <ide> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer.</dd>
1
Javascript
Javascript
add test for deprecation warnings
23deea0f02818823b6f3ac9bf94a5d051721c671
<ide><path>src/isomorphic/__tests__/React-test.js <add>/** <add> * Copyright 2013-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> * <add> * @emails react-core <add> */ <add> <add>'use strict'; <add> <add>describe('React', () => { <add> <add> var React; <add> <add> beforeEach(() => { <add> React = require('React'); <add> }); <add> <add> it('should log a deprecation warning once when using React.__spread', () => { <add> spyOn(console, 'error'); <add> React.__spread({}); <add> React.__spread({}); <add> expectDev(console.error.calls.count()).toBe(1); <add> expectDev(console.error.calls.argsFor(0)[0]).toContain( <add> 'React.__spread is deprecated and should not be used' <add> ); <add> }); <add> <add> it('should log a deprecation warning once when using React.createMixin', () => { <add> spyOn(console, 'error'); <add> React.createMixin(); <add> React.createMixin(); <add> expectDev(console.error.calls.count()).toBe(1); <add> expectDev(console.error.calls.argsFor(0)[0]).toContain( <add> 'React.createMixin is deprecated and should not be used' <add> ); <add> }); <add> <add>});
1
Python
Python
remove unused outdated file
e00680a33a511f4b99a16bf46a885fa1aa6e33c6
<ide><path>spacy/lang/entity_rules.py <del># coding: utf8 <del>from __future__ import unicode_literals <del> <del>from ..symbols import ORTH, ENT_TYPE, LOWER <del> <del> <del>ENT_ID = "ent_id" <del>ENTITY_RULES = [] <del> <del> <del>for name, tag, patterns in [ <del> ("Reddit", "PRODUCT", [[{LOWER: "reddit"}]]), <del> ("Linux", "PRODUCT", [[{LOWER: "linux"}]]), <del> ("Haskell", "PRODUCT", [[{LOWER: "haskell"}]]), <del> ("HaskellCurry", "PERSON", [[{LOWER: "haskell"}, {LOWER: "curry"}]]), <del> ("Javascript", "PRODUCT", [[{LOWER: "javascript"}]]), <del> ("CSS", "PRODUCT", [[{LOWER: "css"}], [{LOWER: "css3"}]]), <del> ("HTML", "PRODUCT", [[{LOWER: "html"}], [{LOWER: "html5"}]]), <del> ("Python", "PRODUCT", [[{ORTH: "Python"}]]), <del> ("Ruby", "PRODUCT", [[{ORTH: "Ruby"}]]), <del> ("spaCy", "PRODUCT", [[{LOWER: "spacy"}]]), <del> ("displaCy", "PRODUCT", [[{LOWER: "displacy"}]]), <del> ("Digg", "PRODUCT", [[{LOWER: "digg"}]]), <del> ("FoxNews", "ORG", [[{LOWER: "foxnews"}], [{LOWER: "fox"}, {LOWER: "news"}]]), <del> ("Google", "ORG", [[{LOWER: "google"}]]), <del> ("Mac", "PRODUCT", [[{LOWER: "mac"}]]), <del> ("Wikipedia", "PRODUCT", [[{LOWER: "wikipedia"}]]), <del> ("Windows", "PRODUCT", [[{LOWER: "windows"}]]), <del> ("Dell", "ORG", [[{LOWER: "dell"}]]), <del> ("Facebook", "ORG", [[{LOWER: "facebook"}]]), <del> ("Blizzard", "ORG", [[{LOWER: "blizzard"}]]), <del> ("Ubuntu", "ORG", [[{LOWER: "ubuntu"}]]), <del> ("YouTube", "PRODUCT", [[{LOWER: "youtube"}]]), <del>]: <del> ENTITY_RULES.append({ENT_ID: name, "attrs": {ENT_TYPE: tag}, "patterns": patterns}) <del> <del> <del>FALSE_POSITIVES = [ <del> [{ORTH: "Shit"}], <del> [{ORTH: "Weed"}], <del> [{ORTH: "Cool"}], <del> [{ORTH: "Btw"}], <del> [{ORTH: "Bah"}], <del> [{ORTH: "Bullshit"}], <del> [{ORTH: "Lol"}], <del> [{ORTH: "Yo"}, {LOWER: "dawg"}], <del> [{ORTH: "Yay"}], <del> [{ORTH: "Ahh"}], <del> [{ORTH: "Yea"}], <del> [{ORTH: "Bah"}], <del>]
1
PHP
PHP
apply fixes from styleci
cf9726d1d8f01884962d5d065d6c3b38cb13b29c
<ide><path>src/Illuminate/Queue/DatabaseQueue.php <ide> protected function getLockForPopping() <ide> { <ide> $databaseEngine = $this->database->getPdo()->getAttribute(PDO::ATTR_DRIVER_NAME); <ide> <del> $databaseVersion = $this->database->getConfig('version') ?? <add> $databaseVersion = $this->database->getConfig('version') ?? <ide> $this->database->getPdo()->getAttribute(PDO::ATTR_SERVER_VERSION); <ide> <ide> if (($databaseEngine === 'mysql' && version_compare($databaseVersion, '8.0.1', '>=')) ||
1
Go
Go
implement docker attach with standalone client lib
5e80ac9c8438252ebb16f6c4aef450e2861a2e5d
<ide><path>api/client/attach.go <ide> package client <ide> <ide> import ( <del> "encoding/json" <ide> "fmt" <ide> "io" <del> "net/url" <ide> <ide> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/api/types" <ide> func (cli *DockerCli) CmdAttach(args ...string) error { <ide> <ide> cmd.ParseFlags(args, true) <ide> <del> serverResp, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil, nil) <add> c, err := cli.client.ContainerInspect(cmd.Arg(0)) <ide> if err != nil { <ide> return err <ide> } <ide> <del> defer serverResp.body.Close() <del> <del> var c types.ContainerJSON <del> if err := json.NewDecoder(serverResp.body).Decode(&c); err != nil { <del> return err <del> } <del> <ide> if !c.State.Running { <ide> return fmt.Errorf("You cannot attach to a stopped container, start it first") <ide> } <ide> func (cli *DockerCli) CmdAttach(args ...string) error { <ide> } <ide> } <ide> <del> var in io.ReadCloser <add> options := types.ContainerAttachOptions{ <add> ContainerID: cmd.Arg(0), <add> Stream: true, <add> Stdin: !*noStdin && c.Config.OpenStdin, <add> Stdout: true, <add> Stderr: true, <add> } <ide> <del> v := url.Values{} <del> v.Set("stream", "1") <del> if !*noStdin && c.Config.OpenStdin { <del> v.Set("stdin", "1") <add> var in io.ReadCloser <add> if options.Stdin { <ide> in = cli.in <ide> } <ide> <del> v.Set("stdout", "1") <del> v.Set("stderr", "1") <del> <ide> if *proxy && !c.Config.Tty { <del> sigc := cli.forwardAllSignals(cmd.Arg(0)) <add> sigc := cli.forwardAllSignals(options.ContainerID) <ide> defer signal.StopCatch(sigc) <ide> } <ide> <del> if err := cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?"+v.Encode(), c.Config.Tty, in, cli.out, cli.err, nil, nil); err != nil { <add> resp, err := cli.client.ContainerAttach(options) <add> if err != nil { <add> return err <add> } <add> defer resp.Close() <add> <add> if err := cli.holdHijackedConnection(c.Config.Tty, in, cli.out, cli.err, resp); err != nil { <ide> return err <ide> } <ide> <del> _, status, err := getExitCode(cli, cmd.Arg(0)) <add> _, status, err := getExitCode(cli, options.ContainerID) <ide> if err != nil { <ide> return err <ide> } <ide><path>api/client/client.go <ide> import ( <ide> <ide> // apiClient is an interface that clients that talk with a docker server must implement. <ide> type apiClient interface { <add> ContainerAttach(options types.ContainerAttachOptions) (*types.HijackedResponse, error) <ide> ContainerCommit(options types.ContainerCommitOptions) (types.ContainerCommitResponse, error) <ide> ContainerCreate(config *runconfig.ContainerConfigWrapper, containerName string) (types.ContainerCreateResponse, error) <ide> ContainerDiff(containerID string) ([]types.ContainerChange, error) <ide><path>api/client/hijack.go <ide> import ( <ide> <ide> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/api" <add> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/dockerversion" <ide> "github.com/docker/docker/pkg/stdcopy" <ide> "github.com/docker/docker/pkg/term" <ide> ) <ide> <add>func (cli *DockerCli) holdHijackedConnection(setRawTerminal bool, inputStream io.ReadCloser, outputStream, errorStream io.Writer, resp *types.HijackedResponse) error { <add> var ( <add> err error <add> oldState *term.State <add> ) <add> if inputStream != nil && setRawTerminal && cli.isTerminalIn && os.Getenv("NORAW") == "" { <add> oldState, err = term.SetRawTerminal(cli.inFd) <add> if err != nil { <add> return err <add> } <add> defer term.RestoreTerminal(cli.inFd, oldState) <add> } <add> <add> receiveStdout := make(chan error, 1) <add> if outputStream != nil || errorStream != nil { <add> go func() { <add> defer func() { <add> if inputStream != nil { <add> if setRawTerminal && cli.isTerminalIn { <add> term.RestoreTerminal(cli.inFd, oldState) <add> } <add> inputStream.Close() <add> } <add> }() <add> <add> // When TTY is ON, use regular copy <add> if setRawTerminal && outputStream != nil { <add> _, err = io.Copy(outputStream, resp.Reader) <add> } else { <add> _, err = stdcopy.StdCopy(outputStream, errorStream, resp.Reader) <add> } <add> logrus.Debugf("[hijack] End of stdout") <add> receiveStdout <- err <add> }() <add> } <add> <add> stdinDone := make(chan struct{}) <add> go func() { <add> if inputStream != nil { <add> io.Copy(resp.Conn, inputStream) <add> logrus.Debugf("[hijack] End of stdin") <add> } <add> <add> if err := resp.CloseWrite(); err != nil { <add> logrus.Debugf("Couldn't send EOF: %s", err) <add> } <add> close(stdinDone) <add> }() <add> <add> select { <add> case err := <-receiveStdout: <add> if err != nil { <add> logrus.Debugf("Error receiveStdout: %s", err) <add> return err <add> } <add> case <-stdinDone: <add> if outputStream != nil || errorStream != nil { <add> if err := <-receiveStdout; err != nil { <add> logrus.Debugf("Error receiveStdout: %s", err) <add> return err <add> } <add> } <add> } <add> <add> return nil <add>} <add> <ide> type tlsClientCon struct { <ide> *tls.Conn <ide> rawConn net.Conn <ide> func (cli *DockerCli) hijackWithContentType(method, path, contentType string, se <ide> } <ide> <ide> var oldState *term.State <del> <ide> if in != nil && setRawTerminal && cli.isTerminalIn && os.Getenv("NORAW") == "" { <ide> oldState, err = term.SetRawTerminal(cli.inFd) <ide> if err != nil { <ide><path>api/client/lib/client.go <ide> type Client struct { <ide> BasePath string <ide> // scheme holds the scheme of the client i.e. https. <ide> Scheme string <add> // tlsConfig holds the tls configuration to use in hijacked requests. <add> tlsConfig *tls.Config <ide> // httpClient holds the client transport instance. Exported to keep the old code running. <ide> HTTPClient *http.Client <ide> // version of the server to talk to. <ide> func NewClientWithVersion(host string, version version.Version, tlsOptions *tlsc <ide> sockets.ConfigureTCPTransport(transport, proto, addr) <ide> <ide> return &Client{ <add> Proto: proto, <ide> Addr: addr, <ide> BasePath: basePath, <ide> Scheme: scheme, <add> tlsConfig: tlsConfig, <ide> HTTPClient: &http.Client{Transport: transport}, <ide> version: version, <ide> customHTTPHeaders: httpHeaders, <ide><path>api/client/lib/container_attach.go <add>package lib <add> <add>import ( <add> "net/url" <add> <add> "github.com/docker/docker/api/types" <add>) <add> <add>// ContainerAttach attaches a connection to a container in the server. <add>// It returns a types.HijackedConnection with the hijacked connection <add>// and the a reader to get output. It's up to the called to close <add>// the hijacked connection by calling types.HijackedResponse.Close. <add>func (cli *Client) ContainerAttach(options types.ContainerAttachOptions) (*types.HijackedResponse, error) { <add> query := url.Values{} <add> if options.Stream { <add> query.Set("stream", "1") <add> } <add> if options.Stdin { <add> query.Set("stdin", "1") <add> } <add> if options.Stdout { <add> query.Set("stdout", "1") <add> } <add> if options.Stderr { <add> query.Set("stderr", "1") <add> } <add> <add> headers := map[string][]string{"Content-Type": {"text/plain"}} <add> return cli.postHijacked("/containers/"+options.ContainerID+"/attach", query, nil, headers) <add>} <ide><path>api/client/lib/hijack.go <add>package lib <add> <add>import ( <add> "crypto/tls" <add> "errors" <add> "fmt" <add> "io" <add> "net" <add> "net/http/httputil" <add> "net/url" <add> "strings" <add> "time" <add> <add> "github.com/docker/docker/api/types" <add>) <add> <add>// tlsClientCon holds tls information and a dialed connection. <add>type tlsClientCon struct { <add> *tls.Conn <add> rawConn net.Conn <add>} <add> <add>func (c *tlsClientCon) CloseWrite() error { <add> // Go standard tls.Conn doesn't provide the CloseWrite() method so we do it <add> // on its underlying connection. <add> if conn, ok := c.rawConn.(types.CloseWriter); ok { <add> return conn.CloseWrite() <add> } <add> return nil <add>} <add> <add>// postHijacked sends a POST request and hijacks the connection. <add>func (cli *Client) postHijacked(path string, query url.Values, body io.Reader, headers map[string][]string) (*types.HijackedResponse, error) { <add> bodyEncoded, err := encodeData(body) <add> if err != nil { <add> return nil, err <add> } <add> <add> req, err := cli.newRequest("POST", path, query, bodyEncoded, headers) <add> if err != nil { <add> return nil, err <add> } <add> req.Host = cli.Addr <add> <add> req.Header.Set("Connection", "Upgrade") <add> req.Header.Set("Upgrade", "tcp") <add> <add> conn, err := dial(cli.Proto, cli.Addr, cli.tlsConfig) <add> if err != nil { <add> if strings.Contains(err.Error(), "connection refused") { <add> return nil, fmt.Errorf("Cannot connect to the Docker daemon. Is 'docker daemon' running on this host?") <add> } <add> return nil, err <add> } <add> <add> // When we set up a TCP connection for hijack, there could be long periods <add> // of inactivity (a long running command with no output) that in certain <add> // network setups may cause ECONNTIMEOUT, leaving the client in an unknown <add> // state. Setting TCP KeepAlive on the socket connection will prohibit <add> // ECONNTIMEOUT unless the socket connection truly is broken <add> if tcpConn, ok := conn.(*net.TCPConn); ok { <add> tcpConn.SetKeepAlive(true) <add> tcpConn.SetKeepAlivePeriod(30 * time.Second) <add> } <add> <add> clientconn := httputil.NewClientConn(conn, nil) <add> defer clientconn.Close() <add> <add> // Server hijacks the connection, error 'connection closed' expected <add> clientconn.Do(req) <add> <add> rwc, br := clientconn.Hijack() <add> <add> return &types.HijackedResponse{rwc, br}, nil <add>} <add> <add>func tlsDial(network, addr string, config *tls.Config) (net.Conn, error) { <add> return tlsDialWithDialer(new(net.Dialer), network, addr, config) <add>} <add> <add>// We need to copy Go's implementation of tls.Dial (pkg/cryptor/tls/tls.go) in <add>// order to return our custom tlsClientCon struct which holds both the tls.Conn <add>// object _and_ its underlying raw connection. The rationale for this is that <add>// we need to be able to close the write end of the connection when attaching, <add>// which tls.Conn does not provide. <add>func tlsDialWithDialer(dialer *net.Dialer, network, addr string, config *tls.Config) (net.Conn, error) { <add> // We want the Timeout and Deadline values from dialer to cover the <add> // whole process: TCP connection and TLS handshake. This means that we <add> // also need to start our own timers now. <add> timeout := dialer.Timeout <add> <add> if !dialer.Deadline.IsZero() { <add> deadlineTimeout := dialer.Deadline.Sub(time.Now()) <add> if timeout == 0 || deadlineTimeout < timeout { <add> timeout = deadlineTimeout <add> } <add> } <add> <add> var errChannel chan error <add> <add> if timeout != 0 { <add> errChannel = make(chan error, 2) <add> time.AfterFunc(timeout, func() { <add> errChannel <- errors.New("") <add> }) <add> } <add> <add> rawConn, err := dialer.Dial(network, addr) <add> if err != nil { <add> return nil, err <add> } <add> // When we set up a TCP connection for hijack, there could be long periods <add> // of inactivity (a long running command with no output) that in certain <add> // network setups may cause ECONNTIMEOUT, leaving the client in an unknown <add> // state. Setting TCP KeepAlive on the socket connection will prohibit <add> // ECONNTIMEOUT unless the socket connection truly is broken <add> if tcpConn, ok := rawConn.(*net.TCPConn); ok { <add> tcpConn.SetKeepAlive(true) <add> tcpConn.SetKeepAlivePeriod(30 * time.Second) <add> } <add> <add> colonPos := strings.LastIndex(addr, ":") <add> if colonPos == -1 { <add> colonPos = len(addr) <add> } <add> hostname := addr[:colonPos] <add> <add> // If no ServerName is set, infer the ServerName <add> // from the hostname we're connecting to. <add> if config.ServerName == "" { <add> // Make a copy to avoid polluting argument or default. <add> c := *config <add> c.ServerName = hostname <add> config = &c <add> } <add> <add> conn := tls.Client(rawConn, config) <add> <add> if timeout == 0 { <add> err = conn.Handshake() <add> } else { <add> go func() { <add> errChannel <- conn.Handshake() <add> }() <add> <add> err = <-errChannel <add> } <add> <add> if err != nil { <add> rawConn.Close() <add> return nil, err <add> } <add> <add> // This is Docker difference with standard's crypto/tls package: returned a <add> // wrapper which holds both the TLS and raw connections. <add> return &tlsClientCon{conn, rawConn}, nil <add>} <add> <add>func dial(proto, addr string, tlsConfig *tls.Config) (net.Conn, error) { <add> if tlsConfig != nil && proto != "unix" { <add> // Notice this isn't Go standard's tls.Dial function <add> return tlsDial(proto, addr, tlsConfig) <add> } <add> return net.Dial(proto, addr) <add>} <ide><path>api/client/lib/request.go <ide> func (cli *Client) sendRequest(method, path string, query url.Values, body inter <ide> return cli.sendClientRequest(method, path, query, params, headers) <ide> } <ide> <del>func (cli *Client) sendClientRequest(method, path string, query url.Values, in io.Reader, headers map[string][]string) (*serverResponse, error) { <add>func (cli *Client) sendClientRequest(method, path string, query url.Values, body io.Reader, headers map[string][]string) (*serverResponse, error) { <ide> serverResp := &serverResponse{ <ide> body: nil, <ide> statusCode: -1, <ide> } <ide> <ide> expectedPayload := (method == "POST" || method == "PUT") <del> if expectedPayload && in == nil { <del> in = bytes.NewReader([]byte{}) <del> } <del> <del> apiPath := cli.getAPIPath(path, query) <del> req, err := http.NewRequest(method, apiPath, in) <del> if err != nil { <del> return serverResp, err <del> } <del> <del> // Add CLI Config's HTTP Headers BEFORE we set the Docker headers <del> // then the user can't change OUR headers <del> for k, v := range cli.customHTTPHeaders { <del> req.Header.Set(k, v) <add> if expectedPayload && body == nil { <add> body = bytes.NewReader([]byte{}) <ide> } <ide> <add> req, err := cli.newRequest(method, path, query, body, headers) <ide> req.URL.Host = cli.Addr <ide> req.URL.Scheme = cli.Scheme <ide> <del> if headers != nil { <del> for k, v := range headers { <del> req.Header[k] = v <del> } <del> } <del> <ide> if expectedPayload && req.Header.Get("Content-Type") == "" { <ide> req.Header.Set("Content-Type", "text/plain") <ide> } <ide> func (cli *Client) sendClientRequest(method, path string, query url.Values, in i <ide> return serverResp, nil <ide> } <ide> <add>func (cli *Client) newRequest(method, path string, query url.Values, body io.Reader, headers map[string][]string) (*http.Request, error) { <add> apiPath := cli.getAPIPath(path, query) <add> req, err := http.NewRequest(method, apiPath, body) <add> if err != nil { <add> return nil, err <add> } <add> <add> // Add CLI Config's HTTP Headers BEFORE we set the Docker headers <add> // then the user can't change OUR headers <add> for k, v := range cli.customHTTPHeaders { <add> req.Header.Set(k, v) <add> } <add> <add> if headers != nil { <add> for k, v := range headers { <add> req.Header[k] = v <add> } <add> } <add> <add> return req, nil <add>} <add> <ide> func encodeData(data interface{}) (*bytes.Buffer, error) { <ide> params := bytes.NewBuffer(nil) <ide> if data != nil { <ide><path>api/types/client.go <ide> package types <ide> <ide> import ( <add> "bufio" <ide> "io" <add> "net" <ide> <ide> "github.com/docker/docker/cliconfig" <ide> "github.com/docker/docker/pkg/parsers/filters" <ide> "github.com/docker/docker/pkg/ulimit" <ide> ) <ide> <del>// ContainerCommitOptions hods parameters to commit changes into a container. <add>// ContainerAttachOptions holds parameters to attach to a container. <add>type ContainerAttachOptions struct { <add> ContainerID string <add> Stream bool <add> Stdin bool <add> Stdout bool <add> Stderr bool <add>} <add> <add>// ContainerCommitOptions holds parameters to commit changes into a container. <ide> type ContainerCommitOptions struct { <ide> ContainerID string <ide> RepositoryName string <ide> type EventsOptions struct { <ide> Filters filters.Args <ide> } <ide> <add>// HijackedResponse holds connection information for a hijacked request. <add>type HijackedResponse struct { <add> Conn net.Conn <add> Reader *bufio.Reader <add>} <add> <add>// Close closes the hijacked connection and reader. <add>func (h *HijackedResponse) Close() { <add> h.Conn.Close() <add>} <add> <add>// CloseWriter is an interface that implement structs <add>// that close input streams to prevent from writing. <add>type CloseWriter interface { <add> CloseWrite() error <add>} <add> <add>// CloseWrite closes a readWriter for writing. <add>func (h *HijackedResponse) CloseWrite() error { <add> if conn, ok := h.Conn.(CloseWriter); ok { <add> return conn.CloseWrite() <add> } <add> return nil <add>} <add> <ide> // ImageBuildOptions holds the information <ide> // necessary to build images. <ide> type ImageBuildOptions struct {
8
Text
Text
add missing api docs for hostconfig.pidmode
2c9b5addc5022dba33d5d0443b49b2e4c0041ef3
<ide><path>docs/reference/api/docker_remote_api.md <ide> This section lists each version from latest to oldest. Each listing includes a <ide> no longer expects a "Container" field to be present. This property was not used <ide> and is no longer sent by the docker client. <ide> * `POST /containers/create/` now validates the hostname (should be a valid RFC 1123 hostname). <add>* `POST /containers/create/` `HostConfig.PidMode` field now accepts `container:<name|id>`, <add> to have the container join the PID namespace of an existing container. <ide> <ide> ### v1.23 API changes <ide> <ide><path>docs/reference/api/docker_remote_api_v1.18.md <ide> Create a container <ide> "MemorySwap": 0, <ide> "CpuShares": 512, <ide> "CpusetCpus": "0,1", <add> "PidMode": "", <ide> "PortBindings": { "22/tcp": [{ "HostPort": "11022" }] }, <ide> "PublishAllPorts": false, <ide> "Privileged": false, <ide> Json Parameters: <ide> - **CpuShares** - An integer value containing the CPU Shares for container <ide> (ie. the relative weight vs other containers). <ide> - **CpusetCpus** - String value containing the cgroups CpusetCpus to use. <add> - **PidMode** - Set the PID (Process) Namespace mode for the container; <add> `"container:<name|id>"`: joins another container's PID namespace <add> `"host"`: use the host's PID namespace inside the container <ide> - **PortBindings** - A map of exposed container ports and the host port they <ide> should map to. It should be specified in the form <ide> `{ <port>/<protocol>: [{ "HostPort": "<port>" }] }` <ide> Return low-level information on the container `id` <ide> "Memory": 0, <ide> "MemorySwap": 0, <ide> "NetworkMode": "bridge", <add> "PidMode": "", <ide> "PortBindings": {}, <ide> "Privileged": false, <ide> "ReadonlyRootfs": false, <ide><path>docs/reference/api/docker_remote_api_v1.19.md <ide> Create a container <ide> "CpusetMems": "0,1", <ide> "BlkioWeight": 300, <ide> "OomKillDisable": false, <add> "PidMode": "", <ide> "PortBindings": { "22/tcp": [{ "HostPort": "11022" }] }, <ide> "PublishAllPorts": false, <ide> "Privileged": false, <ide> Json Parameters: <ide> - **CpusetMems** - Memory nodes (MEMs) in which to allow execution (0-3, 0,1). Only effective on NUMA systems. <ide> - **BlkioWeight** - Block IO weight (relative weight) accepts a weight value between 10 and 1000. <ide> - **OomKillDisable** - Boolean value, whether to disable OOM Killer for the container or not. <add> - **PidMode** - Set the PID (Process) Namespace mode for the container; <add> `"container:<name|id>"`: joins another container's PID namespace <add> `"host"`: use the host's PID namespace inside the container <ide> - **PortBindings** - A map of exposed container ports and the host port they <ide> should map to. A JSON object in the form <ide> `{ <port>/<protocol>: [{ "HostPort": "<port>" }] }` <ide> Return low-level information on the container `id` <ide> "MemorySwap": 0, <ide> "OomKillDisable": false, <ide> "NetworkMode": "bridge", <add> "PidMode": "", <ide> "PortBindings": {}, <ide> "Privileged": false, <ide> "ReadonlyRootfs": false, <ide><path>docs/reference/api/docker_remote_api_v1.20.md <ide> Create a container <ide> "BlkioWeight": 300, <ide> "MemorySwappiness": 60, <ide> "OomKillDisable": false, <add> "PidMode": "", <ide> "PortBindings": { "22/tcp": [{ "HostPort": "11022" }] }, <ide> "PublishAllPorts": false, <ide> "Privileged": false, <ide> Json Parameters: <ide> - **BlkioWeight** - Block IO weight (relative weight) accepts a weight value between 10 and 1000. <ide> - **MemorySwappiness** - Tune a container's memory swappiness behavior. Accepts an integer between 0 and 100. <ide> - **OomKillDisable** - Boolean value, whether to disable OOM Killer for the container or not. <add> - **PidMode** - Set the PID (Process) Namespace mode for the container; <add> `"container:<name|id>"`: joins another container's PID namespace <add> `"host"`: use the host's PID namespace inside the container <ide> - **PortBindings** - A map of exposed container ports and the host port they <ide> should map to. A JSON object in the form <ide> `{ <port>/<protocol>: [{ "HostPort": "<port>" }] }` <ide> Return low-level information on the container `id` <ide> "MemorySwap": 0, <ide> "OomKillDisable": false, <ide> "NetworkMode": "bridge", <add> "PidMode": "", <ide> "PortBindings": {}, <ide> "Privileged": false, <ide> "ReadonlyRootfs": false, <ide><path>docs/reference/api/docker_remote_api_v1.21.md <ide> Create a container <ide> "BlkioWeight": 300, <ide> "MemorySwappiness": 60, <ide> "OomKillDisable": false, <add> "PidMode": "", <ide> "PortBindings": { "22/tcp": [{ "HostPort": "11022" }] }, <ide> "PublishAllPorts": false, <ide> "Privileged": false, <ide> Json Parameters: <ide> - **BlkioWeight** - Block IO weight (relative weight) accepts a weight value between 10 and 1000. <ide> - **MemorySwappiness** - Tune a container's memory swappiness behavior. Accepts an integer between 0 and 100. <ide> - **OomKillDisable** - Boolean value, whether to disable OOM Killer for the container or not. <add> - **PidMode** - Set the PID (Process) Namespace mode for the container; <add> `"container:<name|id>"`: joins another container's PID namespace <add> `"host"`: use the host's PID namespace inside the container <ide> - **PortBindings** - A map of exposed container ports and the host port they <ide> should map to. A JSON object in the form <ide> `{ <port>/<protocol>: [{ "HostPort": "<port>" }] }` <ide> Return low-level information on the container `id` <ide> "KernelMemory": 0, <ide> "OomKillDisable": false, <ide> "NetworkMode": "bridge", <add> "PidMode": "", <ide> "PortBindings": {}, <ide> "Privileged": false, <ide> "ReadonlyRootfs": false, <ide><path>docs/reference/api/docker_remote_api_v1.22.md <ide> Create a container <ide> "MemorySwappiness": 60, <ide> "OomKillDisable": false, <ide> "OomScoreAdj": 500, <add> "PidMode": "", <ide> "PortBindings": { "22/tcp": [{ "HostPort": "11022" }] }, <ide> "PublishAllPorts": false, <ide> "Privileged": false, <ide> Json Parameters: <ide> - **MemorySwappiness** - Tune a container's memory swappiness behavior. Accepts an integer between 0 and 100. <ide> - **OomKillDisable** - Boolean value, whether to disable OOM Killer for the container or not. <ide> - **OomScoreAdj** - An integer value containing the score given to the container in order to tune OOM killer preferences. <add> - **PidMode** - Set the PID (Process) Namespace mode for the container; <add> `"container:<name|id>"`: joins another container's PID namespace <add> `"host"`: use the host's PID namespace inside the container <ide> - **PortBindings** - A map of exposed container ports and the host port they <ide> should map to. A JSON object in the form <ide> `{ <port>/<protocol>: [{ "HostPort": "<port>" }] }` <ide> Return low-level information on the container `id` <ide> "OomKillDisable": false, <ide> "OomScoreAdj": 500, <ide> "NetworkMode": "bridge", <add> "PidMode": "", <ide> "PortBindings": {}, <ide> "Privileged": false, <ide> "ReadonlyRootfs": false, <ide><path>docs/reference/api/docker_remote_api_v1.23.md <ide> Create a container <ide> "MemorySwappiness": 60, <ide> "OomKillDisable": false, <ide> "OomScoreAdj": 500, <add> "PidMode": "", <ide> "PidsLimit": -1, <ide> "PortBindings": { "22/tcp": [{ "HostPort": "11022" }] }, <ide> "PublishAllPorts": false, <ide> Json Parameters: <ide> - **MemorySwappiness** - Tune a container's memory swappiness behavior. Accepts an integer between 0 and 100. <ide> - **OomKillDisable** - Boolean value, whether to disable OOM Killer for the container or not. <ide> - **OomScoreAdj** - An integer value containing the score given to the container in order to tune OOM killer preferences. <add> - **PidMode** - Set the PID (Process) Namespace mode for the container; <add> `"container:<name|id>"`: joins another container's PID namespace <add> `"host"`: use the host's PID namespace inside the container <ide> - **PidsLimit** - Tune a container's pids limit. Set -1 for unlimited. <ide> - **PortBindings** - A map of exposed container ports and the host port they <ide> should map to. A JSON object in the form <ide> Return low-level information on the container `id` <ide> "OomKillDisable": false, <ide> "OomScoreAdj": 500, <ide> "NetworkMode": "bridge", <add> "PidMode": "", <ide> "PortBindings": {}, <ide> "Privileged": false, <ide> "ReadonlyRootfs": false, <ide><path>docs/reference/api/docker_remote_api_v1.24.md <ide> Create a container <ide> "MemorySwappiness": 60, <ide> "OomKillDisable": false, <ide> "OomScoreAdj": 500, <add> "PidMode": "", <ide> "PidsLimit": -1, <ide> "PortBindings": { "22/tcp": [{ "HostPort": "11022" }] }, <ide> "PublishAllPorts": false, <ide> Create a container <ide> - **MemorySwappiness** - Tune a container's memory swappiness behavior. Accepts an integer between 0 and 100. <ide> - **OomKillDisable** - Boolean value, whether to disable OOM Killer for the container or not. <ide> - **OomScoreAdj** - An integer value containing the score given to the container in order to tune OOM killer preferences. <add> - **PidMode** - Set the PID (Process) Namespace mode for the container; <add> `"container:<name|id>"`: joins another container's PID namespace <add> `"host"`: use the host's PID namespace inside the container <ide> - **PidsLimit** - Tune a container's pids limit. Set -1 for unlimited. <ide> - **PortBindings** - A map of exposed container ports and the host port they <ide> should map to. A JSON object in the form <ide> Return low-level information on the container `id` <ide> "OomKillDisable": false, <ide> "OomScoreAdj": 500, <ide> "NetworkMode": "bridge", <add> "PidMode": "", <ide> "PortBindings": {}, <ide> "Privileged": false, <ide> "ReadonlyRootfs": false, <ide><path>docs/reference/api/docker_remote_api_v1.25.md <ide> Create a container <ide> "MemorySwappiness": 60, <ide> "OomKillDisable": false, <ide> "OomScoreAdj": 500, <add> "PidMode": "", <ide> "PidsLimit": -1, <ide> "PortBindings": { "22/tcp": [{ "HostPort": "11022" }] }, <ide> "PublishAllPorts": false, <ide> Create a container <ide> - **MemorySwappiness** - Tune a container's memory swappiness behavior. Accepts an integer between 0 and 100. <ide> - **OomKillDisable** - Boolean value, whether to disable OOM Killer for the container or not. <ide> - **OomScoreAdj** - An integer value containing the score given to the container in order to tune OOM killer preferences. <add> - **PidMode** - Set the PID (Process) Namespace mode for the container; <add> `"container:<name|id>"`: joins another container's PID namespace <add> `"host"`: use the host's PID namespace inside the container <ide> - **PidsLimit** - Tune a container's pids limit. Set -1 for unlimited. <ide> - **PortBindings** - A map of exposed container ports and the host port they <ide> should map to. A JSON object in the form <ide> Return low-level information on the container `id` <ide> "OomKillDisable": false, <ide> "OomScoreAdj": 500, <ide> "NetworkMode": "bridge", <add> "PidMode": "", <ide> "PortBindings": {}, <ide> "Privileged": false, <ide> "ReadonlyRootfs": false,
9
Java
Java
add flush method to serverhttpresponse
3a2c15b0fd5d370f80964b8f4d62b353823e06cf
<ide><path>spring-web/src/main/java/org/springframework/http/server/AsyncServletServerHttpRequest.java <ide> public void completeAsync() { <ide> // Implementation of AsyncListener methods <ide> // --------------------------------------------------------------------- <ide> <add> @Override <ide> public void onStartAsync(AsyncEvent event) throws IOException { <ide> } <ide> <add> @Override <ide> public void onError(AsyncEvent event) throws IOException { <ide> } <ide> <add> @Override <ide> public void onTimeout(AsyncEvent event) throws IOException { <del> for (Runnable handler : this.timeoutHandlers) { <del> handler.run(); <add> try { <add> for (Runnable handler : this.timeoutHandlers) { <add> handler.run(); <add> } <add> } <add> catch (Throwable t) { <add> // ignore <ide> } <ide> } <ide> <add> @Override <ide> public void onComplete(AsyncEvent event) throws IOException { <del> for (Runnable handler : this.completionHandlers) { <del> handler.run(); <add> try { <add> for (Runnable handler : this.completionHandlers) { <add> handler.run(); <add> } <add> } <add> catch (Throwable t) { <add> // ignore <ide> } <ide> this.asyncContext = null; <ide> this.asyncCompleted.set(true); <ide><path>spring-web/src/main/java/org/springframework/http/server/ServerHttpResponse.java <ide> package org.springframework.http.server; <ide> <ide> import java.io.Closeable; <add>import java.io.IOException; <ide> <ide> import org.springframework.http.HttpOutputMessage; <ide> import org.springframework.http.HttpStatus; <ide> public interface ServerHttpResponse extends HttpOutputMessage, Closeable { <ide> */ <ide> void setStatusCode(HttpStatus status); <ide> <add> /** <add> * TODO <add> */ <add> void flush() throws IOException; <add> <ide> /** <ide> * Close this response, freeing any resources created. <ide> */ <ide><path>spring-web/src/main/java/org/springframework/http/server/ServletServerHttpResponse.java <ide> public OutputStream getBody() throws IOException { <ide> return this.servletResponse.getOutputStream(); <ide> } <ide> <add> @Override <add> public void flush() throws IOException { <add> writeCookies(); <add> writeHeaders(); <add> this.servletResponse.flushBuffer(); <add> } <add> <ide> public void close() { <ide> writeCookies(); <ide> writeHeaders(); <ide><path>spring-websocket/src/main/java/org/springframework/sockjs/SockJsSession.java <ide> <ide> package org.springframework.sockjs; <ide> <add>import java.io.IOException; <add> <ide> <ide> <ide> /** <ide> */ <ide> public interface SockJsSession { <ide> <del> void sendMessage(String text) throws Exception; <add> void sendMessage(String text) throws IOException; <ide> <ide> void close(); <ide> <ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/AbstractServerSession.java <ide> package org.springframework.sockjs.server; <ide> <ide> import java.io.EOFException; <add>import java.io.IOException; <add>import java.net.SocketException; <ide> import java.util.Date; <ide> import java.util.concurrent.ScheduledFuture; <ide> <ide> protected SockJsConfiguration getSockJsConfig() { <ide> return this.sockJsConfig; <ide> } <ide> <del> public final synchronized void sendMessage(String message) { <add> public final synchronized void sendMessage(String message) throws IOException { <ide> Assert.isTrue(!isClosed(), "Cannot send a message, session has been closed"); <ide> sendMessageInternal(message); <ide> } <ide> <del> protected abstract void sendMessageInternal(String message); <add> protected abstract void sendMessageInternal(String message) throws IOException; <ide> <ide> public final synchronized void close() { <ide> if (!isClosed()) { <ide> logger.debug("Closing session"); <ide> <ide> if (isActive()) { <ide> // deliver messages "in flight" before sending close frame <del> writeFrame(SockJsFrame.closeFrameGoAway()); <add> try { <add> writeFrame(SockJsFrame.closeFrameGoAway()); <add> } <add> catch (Exception e) { <add> // ignore <add> } <ide> } <ide> <ide> super.close(); <ide> public final synchronized void close() { <ide> * For internal use within a TransportHandler and the (TransportHandler-specific) <ide> * session sub-class. The frame is written only if the connection is active. <ide> */ <del> protected void writeFrame(SockJsFrame frame) { <add> protected void writeFrame(SockJsFrame frame) throws IOException { <ide> if (logger.isTraceEnabled()) { <ide> logger.trace("Preparing to write " + frame); <ide> } <ide> try { <ide> writeFrameInternal(frame); <ide> } <del> catch (EOFException ex) { <del> logger.warn("Client went away. Terminating connection abruptly"); <add> catch (IOException ex) { <add> if (ex instanceof EOFException || ex instanceof SocketException) { <add> logger.warn("Client went away. Terminating connection"); <add> } <add> else { <add> logger.warn("Failed to send message. Terminating connection: " + ex.getMessage()); <add> } <ide> deactivate(); <ide> close(); <add> throw ex; <ide> } <ide> catch (Throwable t) { <del> logger.warn("Failed to send message. Terminating connection abruptly: " + t.getMessage()); <add> logger.warn("Failed to send message. Terminating connection: " + t.getMessage()); <ide> deactivate(); <ide> close(); <add> throw new NestedSockJsRuntimeException("Failed to write frame " + frame, t); <ide> } <ide> } <ide> <del> protected abstract void writeFrameInternal(SockJsFrame frame) throws Exception; <add> protected abstract void writeFrameInternal(SockJsFrame frame) throws IOException; <ide> <ide> /** <ide> * Some {@link TransportHandler} types cannot detect if a client connection is closed <ide> protected void writeFrame(SockJsFrame frame) { <ide> */ <ide> protected abstract void deactivate(); <ide> <del> public synchronized void sendHeartbeat() { <add> public synchronized void sendHeartbeat() throws IOException { <ide> if (isActive()) { <ide> writeFrame(SockJsFrame.heartbeatFrame()); <ide> scheduleHeartbeat(); <ide> protected void scheduleHeartbeat() { <ide> Date time = new Date(System.currentTimeMillis() + getSockJsConfig().getHeartbeatTime()); <ide> this.heartbeatTask = getSockJsConfig().getHeartbeatScheduler().schedule(new Runnable() { <ide> public void run() { <del> sendHeartbeat(); <add> try { <add> sendHeartbeat(); <add> } <add> catch (IOException e) { <add> // ignore <add> } <ide> } <ide> }, time); <ide> if (logger.isTraceEnabled()) { <ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/AbstractSockJsService.java <ide> public final void handleRequest(ServerHttpRequest request, ServerHttpResponse re <ide> request.getHeaders(); <ide> } <ide> catch (IllegalArgumentException ex) { <del> // Ignore invalid Content-Type (TODO!!) <add> // Ignore invalid Content-Type (TODO) <ide> } <ide> <del> if (sockJsPath.equals("") || sockJsPath.equals("/")) { <del> response.getHeaders().setContentType(new MediaType("text", "plain", Charset.forName("UTF-8"))); <del> response.getBody().write("Welcome to SockJS!\n".getBytes("UTF-8")); <del> return; <del> } <del> else if (sockJsPath.equals("/info")) { <del> this.infoHandler.handle(request, response); <del> return; <del> } <del> else if (sockJsPath.matches("/iframe[0-9-.a-z_]*.html")) { <del> this.iframeHandler.handle(request, response); <del> return; <del> } <del> else if (sockJsPath.equals("/websocket")) { <del> handleRawWebSocket(request, response); <del> return; <del> } <del> <del> String[] pathSegments = StringUtils.tokenizeToStringArray(sockJsPath.substring(1), "/"); <del> if (pathSegments.length != 3) { <del> logger.debug("Expected /{server}/{session}/{transport} but got " + sockJsPath); <del> response.setStatusCode(HttpStatus.NOT_FOUND); <del> return; <del> } <add> try { <add> if (sockJsPath.equals("") || sockJsPath.equals("/")) { <add> response.getHeaders().setContentType(new MediaType("text", "plain", Charset.forName("UTF-8"))); <add> response.getBody().write("Welcome to SockJS!\n".getBytes("UTF-8")); <add> return; <add> } <add> else if (sockJsPath.equals("/info")) { <add> this.infoHandler.handle(request, response); <add> return; <add> } <add> else if (sockJsPath.matches("/iframe[0-9-.a-z_]*.html")) { <add> this.iframeHandler.handle(request, response); <add> return; <add> } <add> else if (sockJsPath.equals("/websocket")) { <add> handleRawWebSocket(request, response); <add> return; <add> } <ide> <del> String serverId = pathSegments[0]; <del> String sessionId = pathSegments[1]; <del> String transport = pathSegments[2]; <add> String[] pathSegments = StringUtils.tokenizeToStringArray(sockJsPath.substring(1), "/"); <add> if (pathSegments.length != 3) { <add> logger.debug("Expected /{server}/{session}/{transport} but got " + sockJsPath); <add> response.setStatusCode(HttpStatus.NOT_FOUND); <add> return; <add> } <ide> <del> if (!validateRequest(serverId, sessionId, transport)) { <del> response.setStatusCode(HttpStatus.NOT_FOUND); <del> return; <del> } <add> String serverId = pathSegments[0]; <add> String sessionId = pathSegments[1]; <add> String transport = pathSegments[2]; <ide> <del> handleRequestInternal(request, response, sessionId, TransportType.fromValue(transport)); <add> if (!validateRequest(serverId, sessionId, transport)) { <add> response.setStatusCode(HttpStatus.NOT_FOUND); <add> return; <add> } <ide> <add> handleTransportRequest(request, response, sessionId, TransportType.fromValue(transport)); <add> } <add> finally { <add> response.flush(); <add> } <ide> } <ide> <ide> protected abstract void handleRawWebSocket(ServerHttpRequest request, ServerHttpResponse response) <ide> throws Exception; <ide> <add> protected abstract void handleTransportRequest(ServerHttpRequest request, ServerHttpResponse response, <add> String sessionId, TransportType transportType) throws Exception; <add> <ide> protected boolean validateRequest(String serverId, String sessionId, String transport) { <ide> <ide> if (!StringUtils.hasText(serverId) || !StringUtils.hasText(sessionId) || !StringUtils.hasText(transport)) { <ide> protected boolean validateRequest(String serverId, String sessionId, String tran <ide> return true; <ide> } <ide> <del> protected abstract void handleRequestInternal(ServerHttpRequest request, ServerHttpResponse response, <del> String sessionId, TransportType transportType) throws Exception; <del> <ide> protected void addCorsHeaders(ServerHttpRequest request, ServerHttpResponse response, HttpMethod... httpMethods) { <ide> <ide> String origin = request.getHeaders().getFirst("origin"); <ide> protected void sendMethodNotAllowed(ServerHttpResponse response, List<HttpMethod <ide> logger.debug("Sending Method Not Allowed (405)"); <ide> response.setStatusCode(HttpStatus.METHOD_NOT_ALLOWED); <ide> response.getHeaders().setAllow(new HashSet<HttpMethod>(httpMethods)); <del> response.getBody(); // ensure headers are flushed (TODO!) <ide> } <ide> <ide> <ide> else if (HttpMethod.OPTIONS.equals(request.getMethod())) { <ide> <ide> addCorsHeaders(request, response, HttpMethod.GET, HttpMethod.OPTIONS); <ide> addCacheHeaders(response); <del> <del> response.getBody(); // ensure headers are flushed (TODO!) <ide> } <ide> else { <ide> sendMethodNotAllowed(response, Arrays.asList(HttpMethod.OPTIONS, HttpMethod.GET)); <ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/NestedSockJsRuntimeException.java <add>/* <add> * Copyright 2002-2013 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.sockjs.server; <add> <add>import org.springframework.core.NestedRuntimeException; <add> <add> <add>/** <add> * <add> * @author Rossen Stoyanchev <add> * @since 4.0 <add> */ <add>@SuppressWarnings("serial") <add>public class NestedSockJsRuntimeException extends NestedRuntimeException { <add> <add> <add> public NestedSockJsRuntimeException(String msg) { <add> super(msg); <add> } <add> <add> public NestedSockJsRuntimeException(String msg, Throwable cause) { <add> super(msg, cause); <add> } <add> <add>} <ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/SockJsFrame.java <ide> public byte[] getContentBytes() { <ide> } <ide> <ide> public String toString() { <del> String quoted = this.content.replace("\n", "\\n").replace("\r", "\\r"); <del> return "SockJsFrame content='" + quoted + "'"; <add> String result = this.content; <add> if (result.length() > 80) { <add> result = result.substring(0, 80) + "...(truncated)"; <add> } <add> return "SockJsFrame content='" + result.replace("\n", "\\n").replace("\r", "\\r") + "'"; <ide> } <ide> <ide> <ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/support/DefaultSockJsService.java <ide> protected void handleRawWebSocket(ServerHttpRequest request, ServerHttpResponse <ide> } <ide> <ide> @Override <del> protected void handleRequestInternal(ServerHttpRequest request, ServerHttpResponse response, <add> protected void handleTransportRequest(ServerHttpRequest request, ServerHttpResponse response, <ide> String sessionId, TransportType transportType) throws Exception { <ide> <ide> TransportHandler transportHandler = this.transportHandlers.get(transportType); <ide> protected void handleRequestInternal(ServerHttpRequest request, ServerHttpRespon <ide> response.setStatusCode(HttpStatus.NO_CONTENT); <ide> addCorsHeaders(request, response, supportedMethod, HttpMethod.OPTIONS); <ide> addCacheHeaders(response); <del> response.getBody(); // ensure headers are flushed (TODO!) <ide> } <ide> else { <ide> List<HttpMethod> supportedMethods = Arrays.asList(supportedMethod); <ide> protected void handleRequestInternal(ServerHttpRequest request, ServerHttpRespon <ide> if (isJsessionIdCookieNeeded()) { <ide> Cookie cookie = request.getCookies().getCookie("JSESSIONID"); <ide> String jsid = (cookie != null) ? cookie.getValue() : "dummy"; <del> // TODO: Jetty sets Expires header, so bypass Cookie object for now <add> // TODO: bypass use of Cookie object (causes Jetty to set Expires header) <ide> response.getHeaders().set("Set-Cookie", "JSESSIONID=" + jsid + ";path=/"); // TODO <ide> } <ide> <ide> protected void handleRequestInternal(ServerHttpRequest request, ServerHttpRespon <ide> } <ide> <ide> transportHandler.handleRequest(request, response, session); <del> <del> response.close(); // ensure headers are flushed (TODO !!) <ide> } <ide> <ide> public SockJsSessionSupport getSockJsSession(String sessionId, TransportHandler transportHandler) { <ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/transport/AbstractHttpSendingTransportHandler.java <ide> protected void handleRequestInternal(ServerHttpRequest request, ServerHttpRespon <ide> } <ide> else if (httpServerSession.isActive()) { <ide> logger.debug("another " + getTransportType() + " connection still open: " + httpServerSession); <del> httpServerSession.writeFrame(response.getBody(), SockJsFrame.closeFrameAnotherConnectionOpen()); <add> httpServerSession.writeFrame(response, SockJsFrame.closeFrameAnotherConnectionOpen()); <ide> } <ide> else { <ide> logger.debug("starting " + getTransportType() + " async request"); <ide> protected void handleNewSession(ServerHttpRequest request, ServerHttpResponse re <ide> <ide> logger.debug("Opening " + getTransportType() + " connection"); <ide> session.setFrameFormat(getFrameFormat(request)); <del> session.writeFrame(response.getBody(), SockJsFrame.openFrame()); <add> session.writeFrame(response, SockJsFrame.openFrame()); <ide> session.connectionInitialized(); <ide> } <ide> <ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/transport/AbstractHttpServerSession.java <ide> package org.springframework.sockjs.server.transport; <ide> <ide> import java.io.IOException; <del>import java.io.OutputStream; <ide> import java.util.concurrent.ArrayBlockingQueue; <ide> import java.util.concurrent.BlockingQueue; <ide> <ide> public abstract class AbstractHttpServerSession extends AbstractServerSession { <ide> <ide> private AsyncServerHttpRequest asyncRequest; <ide> <del> private OutputStream outputStream; <add> private ServerHttpResponse response; <ide> <ide> <ide> public AbstractHttpServerSession(String sessionId, SockJsConfiguration sockJsConfig) { <ide> public synchronized void setCurrentRequest(ServerHttpRequest request, ServerHttp <ide> <ide> if (isClosed()) { <ide> logger.debug("connection already closed"); <del> writeFrame(response.getBody(), SockJsFrame.closeFrameGoAway()); <add> writeFrame(response, SockJsFrame.closeFrameGoAway()); <ide> return; <ide> } <ide> <ide> public synchronized void setCurrentRequest(ServerHttpRequest request, ServerHttp <ide> this.asyncRequest.setTimeout(-1); <ide> this.asyncRequest.startAsync(); <ide> <del> this.outputStream = response.getBody(); <add> this.response = response; <ide> this.frameFormat = frameFormat; <ide> <ide> scheduleHeartbeat(); <del> tryFlush(); <add> tryFlushCache(); <ide> } <ide> <ide> public synchronized boolean isActive() { <ide> protected BlockingQueue<String> getMessageCache() { <ide> return this.messageCache; <ide> } <ide> <del> protected final synchronized void sendMessageInternal(String message) { <add> protected ServerHttpResponse getResponse() { <add> return this.response; <add> } <add> <add> protected final synchronized void sendMessageInternal(String message) throws IOException { <ide> // assert close() was not called <ide> // threads: TH-Session-Endpoint or any other thread <ide> this.messageCache.add(message); <del> tryFlush(); <add> tryFlushCache(); <ide> } <ide> <del> private void tryFlush() { <add> private void tryFlushCache() throws IOException { <ide> if (isActive() && !getMessageCache().isEmpty()) { <ide> logger.trace("Flushing messages"); <del> flush(); <add> flushCache(); <ide> } <ide> } <ide> <ide> /** <ide> * Only called if the connection is currently active <ide> */ <del> protected abstract void flush(); <add> protected abstract void flushCache() throws IOException; <ide> <ide> protected void closeInternal() { <ide> resetRequest(); <ide> } <ide> <ide> protected synchronized void writeFrameInternal(SockJsFrame frame) throws IOException { <ide> if (isActive()) { <del> writeFrame(this.outputStream, frame); <add> writeFrame(this.response, frame); <ide> } <ide> } <ide> <ide> protected synchronized void writeFrameInternal(SockJsFrame frame) throws IOExcep <ide> * even when the connection is not active, as long as a valid OutputStream <ide> * is provided. <ide> */ <del> public void writeFrame(OutputStream outputStream, SockJsFrame frame) throws IOException { <add> public void writeFrame(ServerHttpResponse response, SockJsFrame frame) throws IOException { <ide> frame = this.frameFormat.format(frame); <ide> if (logger.isTraceEnabled()) { <ide> logger.trace("Writing " + frame); <ide> } <del> outputStream.write(frame.getContentBytes()); <add> response.getBody().write(frame.getContentBytes()); <ide> } <ide> <ide> @Override <ide> protected void deactivate() { <del> this.outputStream = null; <ide> this.asyncRequest = null; <add> this.response = null; <ide> updateLastActiveTime(); <ide> } <ide> <ide> protected synchronized void resetRequest() { <ide> if (isActive()) { <ide> this.asyncRequest.completeAsync(); <ide> } <del> this.outputStream = null; <ide> this.asyncRequest = null; <add> this.response = null; <ide> updateLastActiveTime(); <ide> } <ide> <ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/transport/EventSourceTransportHandler.java <ide> protected MediaType getContentType() { <ide> protected void writePrelude(ServerHttpRequest request, ServerHttpResponse response) throws IOException { <ide> response.getBody().write('\r'); <ide> response.getBody().write('\n'); <del> response.getBody().flush(); <add> response.flush(); <ide> } <ide> <ide> @Override <ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/transport/HtmlFileTransportHandler.java <ide> protected void writePrelude(ServerHttpRequest request, ServerHttpResponse respon <ide> <ide> String html = String.format(PARTIAL_HTML_CONTENT, callback); <ide> response.getBody().write(html.getBytes("UTF-8")); <del> response.getBody().flush(); <add> response.flush(); <ide> } <ide> <ide> @Override <ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/transport/PollingHttpServerSession.java <ide> */ <ide> package org.springframework.sockjs.server.transport; <ide> <add>import java.io.IOException; <add> <ide> import org.springframework.sockjs.server.SockJsConfiguration; <ide> import org.springframework.sockjs.server.SockJsFrame; <ide> <ide> public PollingHttpServerSession(String sessionId, SockJsConfiguration sockJsConf <ide> } <ide> <ide> @Override <del> protected void flush() { <add> protected void flushCache() throws IOException { <ide> cancelHeartbeat(); <ide> String[] messages = getMessageCache().toArray(new String[getMessageCache().size()]); <ide> getMessageCache().clear(); <ide> writeFrame(SockJsFrame.messageFrame(messages)); <ide> } <ide> <ide> @Override <del> protected void writeFrame(SockJsFrame frame) { <add> protected void writeFrame(SockJsFrame frame) throws IOException { <ide> super.writeFrame(frame); <ide> resetRequest(); <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/transport/SockJsWebSocketHandler.java <ide> public boolean isActive() { <ide> } <ide> <ide> @Override <del> public void sendMessageInternal(String message) { <add> public void sendMessageInternal(String message) throws IOException { <ide> cancelHeartbeat(); <ide> writeFrame(SockJsFrame.messageFrame(message)); <ide> scheduleHeartbeat(); <ide> } <ide> <ide> @Override <del> protected void writeFrameInternal(SockJsFrame frame) throws Exception { <add> protected void writeFrameInternal(SockJsFrame frame) throws IOException { <ide> if (logger.isTraceEnabled()) { <ide> logger.trace("Write " + frame); <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/transport/StreamingHttpServerSession.java <ide> package org.springframework.sockjs.server.transport; <ide> <ide> import java.io.IOException; <del>import java.io.OutputStream; <ide> <add>import org.springframework.http.server.ServerHttpResponse; <ide> import org.springframework.sockjs.server.SockJsConfiguration; <ide> import org.springframework.sockjs.server.SockJsFrame; <ide> <ide> public StreamingHttpServerSession(String sessionId, SockJsConfiguration sockJsCo <ide> super(sessionId, sockJsConfig); <ide> } <ide> <del> protected void flush() { <add> protected void flushCache() throws IOException { <ide> <ide> cancelHeartbeat(); <ide> <ide> protected synchronized void resetRequest() { <ide> } <ide> <ide> @Override <del> public void writeFrame(OutputStream outputStream, SockJsFrame frame) throws IOException { <del> super.writeFrame(outputStream, frame); <del> outputStream.flush(); <add> public void writeFrame(ServerHttpResponse response, SockJsFrame frame) throws IOException { <add> super.writeFrame(response, frame); <add> response.flush(); <ide> } <ide> } <ide> <ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/transport/WebSocketSockJsHandlerAdapter.java <ide> <ide> package org.springframework.sockjs.server.transport; <ide> <add>import java.io.IOException; <add> <ide> import org.springframework.sockjs.SockJsHandler; <ide> import org.springframework.sockjs.SockJsSessionSupport; <ide> import org.springframework.sockjs.server.SockJsConfiguration; <ide> public boolean isActive() { <ide> } <ide> <ide> @Override <del> public void sendMessage(String message) throws Exception { <add> public void sendMessage(String message) throws IOException { <ide> this.wsSession.sendText(message); <ide> } <ide> <ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/transport/XhrStreamingTransportHandler.java <ide> protected void writePrelude(ServerHttpRequest request, ServerHttpResponse respon <ide> response.getBody().write('h'); <ide> } <ide> response.getBody().write('\n'); <del> response.getBody().flush(); <add> response.flush(); <ide> } <ide> <ide> @Override <ide><path>spring-websocket/src/main/java/org/springframework/websocket/WebSocketSession.java <ide> <ide> package org.springframework.websocket; <ide> <add>import java.io.IOException; <add> <ide> <ide> <ide> /** <ide> public interface WebSocketSession { <ide> <ide> boolean isOpen(); <ide> <del> void sendText(String text) throws Exception; <add> void sendText(String text) throws IOException; <ide> <ide> void close(); <ide> <ide><path>spring-websocket/src/main/java/org/springframework/websocket/endpoint/StandardWebSocketSession.java <ide> <ide> package org.springframework.websocket.endpoint; <ide> <add>import java.io.IOException; <add> <ide> import org.apache.commons.logging.Log; <ide> import org.apache.commons.logging.LogFactory; <ide> import org.springframework.websocket.WebSocketSession; <ide> public boolean isOpen() { <ide> } <ide> <ide> @Override <del> public void sendText(String text) throws Exception { <add> public void sendText(String text) throws IOException { <ide> logger.trace("Sending text message: " + text); <ide> // TODO: check closed <ide> this.session.getBasicRemote().sendText(text); <ide><path>spring-websocket/src/main/java/org/springframework/websocket/server/endpoint/EndpointRegistration.java <ide> import javax.websocket.server.HandshakeRequest; <ide> import javax.websocket.server.ServerEndpointConfig; <ide> <add>import org.apache.commons.logging.Log; <add>import org.apache.commons.logging.LogFactory; <ide> import org.springframework.beans.BeansException; <ide> import org.springframework.beans.factory.BeanFactory; <ide> import org.springframework.beans.factory.BeanFactoryAware; <ide> */ <ide> public class EndpointRegistration implements ServerEndpointConfig, BeanFactoryAware { <ide> <add> private static Log logger = LogFactory.getLog(EndpointRegistration.class); <add> <ide> private final String path; <ide> <ide> private final Class<? extends Endpoint> endpointClass; <ide> public Endpoint getEndpoint() { <ide> if (this.endpointClass != null) { <ide> WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext(); <ide> if (wac == null) { <del> throw new IllegalStateException("Failed to find WebApplicationContext. " <del> + "Was org.springframework.web.context.ContextLoader used to load the WebApplicationContext?"); <add> String message = "Failed to find the root WebApplicationContext. Was ContextLoaderListener not used?"; <add> logger.error(message); <add> throw new IllegalStateException(); <ide> } <ide> return wac.getAutowireCapableBeanFactory().createBean(this.endpointClass); <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/websocket/server/endpoint/handshake/EndpointHandshakeHandler.java <ide> import org.springframework.websocket.endpoint.WebSocketHandlerEndpoint; <ide> import org.springframework.websocket.server.AbstractHandshakeHandler; <ide> import org.springframework.websocket.server.HandshakeHandler; <del>import org.springframework.websocket.server.endpoint.EndpointRequestUpgradeStrategy; <ide> <ide> <ide> /** <ide> * A {@link HandshakeHandler} for use with standard Java WebSocket runtimes. A <del> * container-specific {@link EndpointRequestUpgradeStrategy} is required since standard <add> * container-specific {@link RequestUpgradeStrategy} is required since standard <ide> * Java WebSocket currently does not provide any means of integrating a WebSocket <ide> * handshake into an HTTP request processing pipeline. Currently available are <ide> * implementations for Tomcat and Glassfish. <ide> */ <ide> public class EndpointHandshakeHandler extends AbstractHandshakeHandler { <ide> <del> private static final boolean tomcatWebSocketPresent = ClassUtils.isPresent( <del> "org.apache.tomcat.websocket.server.WsHttpUpgradeHandler", EndpointHandshakeHandler.class.getClassLoader()); <del> <del> private static final boolean glassfishWebSocketPresent = ClassUtils.isPresent( <del> "org.glassfish.tyrus.servlet.TyrusHttpUpgradeHandler", EndpointHandshakeHandler.class.getClassLoader()); <del> <del> private final EndpointRequestUpgradeStrategy upgradeStrategy; <add> private final RequestUpgradeStrategy upgradeStrategy; <ide> <ide> <ide> public EndpointHandshakeHandler(Endpoint endpoint) { <ide> super(endpoint); <del> this.upgradeStrategy = createUpgradeStrategy(); <add> this.upgradeStrategy = createRequestUpgradeStrategy(); <ide> } <ide> <ide> public EndpointHandshakeHandler(WebSocketHandler webSocketHandler) { <ide> super(webSocketHandler); <del> this.upgradeStrategy = createUpgradeStrategy(); <add> this.upgradeStrategy = createRequestUpgradeStrategy(); <ide> } <ide> <ide> public EndpointHandshakeHandler(Class<?> handlerClass) { <ide> super(handlerClass); <del> this.upgradeStrategy = createUpgradeStrategy(); <add> this.upgradeStrategy = createRequestUpgradeStrategy(); <ide> } <ide> <del> private static EndpointRequestUpgradeStrategy createUpgradeStrategy() { <del> String className; <del> if (tomcatWebSocketPresent) { <del> className = "org.springframework.websocket.server.endpoint.support.TomcatRequestUpgradeStrategy"; <del> } <del> else if (glassfishWebSocketPresent) { <del> className = "org.springframework.websocket.server.endpoint.support.GlassfishRequestUpgradeStrategy"; <del> } <del> else { <del> throw new IllegalStateException("No suitable EndpointRequestUpgradeStrategy"); <del> } <del> try { <del> Class<?> clazz = ClassUtils.forName(className, EndpointHandshakeHandler.class.getClassLoader()); <del> return (EndpointRequestUpgradeStrategy) BeanUtils.instantiateClass(clazz.getConstructor()); <del> } <del> catch (Throwable t) { <del> throw new IllegalStateException("Failed to instantiate " + className, t); <del> } <add> protected RequestUpgradeStrategy createRequestUpgradeStrategy() { <add> return new RequestUpgradeStrategyFactory().create(); <ide> } <ide> <ide> @Override <ide> else if (webSocketHandler instanceof WebSocketHandler) { <ide> this.upgradeStrategy.upgrade(request, response, protocol, endpoint); <ide> } <ide> <add> <add> private static class RequestUpgradeStrategyFactory { <add> <add> private static final String packageName = EndpointHandshakeHandler.class.getPackage().getName(); <add> <add> private static final boolean tomcatWebSocketPresent = ClassUtils.isPresent( <add> "org.apache.tomcat.websocket.server.WsHttpUpgradeHandler", EndpointHandshakeHandler.class.getClassLoader()); <add> <add> private static final boolean glassfishWebSocketPresent = ClassUtils.isPresent( <add> "org.glassfish.tyrus.servlet.TyrusHttpUpgradeHandler", EndpointHandshakeHandler.class.getClassLoader()); <add> <add> <add> private RequestUpgradeStrategy create() { <add> String className; <add> if (tomcatWebSocketPresent) { <add> className = packageName + ".TomcatRequestUpgradeStrategy"; <add> } <add> else if (glassfishWebSocketPresent) { <add> className = packageName + ".GlassfishRequestUpgradeStrategy"; <add> } <add> else { <add> throw new IllegalStateException("No suitable " + RequestUpgradeStrategy.class.getSimpleName()); <add> } <add> try { <add> Class<?> clazz = ClassUtils.forName(className, EndpointHandshakeHandler.class.getClassLoader()); <add> return (RequestUpgradeStrategy) BeanUtils.instantiateClass(clazz.getConstructor()); <add> } <add> catch (Throwable t) { <add> throw new IllegalStateException("Failed to instantiate " + className, t); <add> } <add> } <add> } <add> <ide> } <ide>\ No newline at end of file <ide><path>spring-websocket/src/main/java/org/springframework/websocket/server/endpoint/handshake/GlassfishRequestUpgradeStrategy.java <ide> import org.springframework.util.ReflectionUtils; <ide> import org.springframework.util.StringUtils; <ide> import org.springframework.websocket.server.endpoint.EndpointRegistration; <del>import org.springframework.websocket.server.endpoint.EndpointRequestUpgradeStrategy; <ide> <ide> /** <ide> * Glassfish support for upgrading an {@link HttpServletRequest} during a WebSocket <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <del>public class GlassfishRequestUpgradeStrategy implements EndpointRequestUpgradeStrategy { <add>public class GlassfishRequestUpgradeStrategy implements RequestUpgradeStrategy { <ide> <ide> private final static Random random = new Random(); <ide> <ide> public void upgrade(ServerHttpRequest request, ServerHttpResponse response, Stri <ide> servletResponse = new AlreadyUpgradedResponseWrapper(servletResponse); <ide> <ide> TyrusEndpoint tyrusEndpoint = createTyrusEndpoint(servletRequest, endpoint); <del> WebSocketEngine.getEngine().register(tyrusEndpoint); <add> WebSocketEngine engine = WebSocketEngine.getEngine(); <add> engine.register(tyrusEndpoint); <ide> <ide> try { <ide> if (!performUpgrade(servletRequest, servletResponse, request.getHeaders(), tyrusEndpoint)) { <ide> throw new IllegalStateException("Failed to upgrade HttpServletRequest"); <ide> } <ide> } <ide> finally { <del> WebSocketEngine.getEngine().unregister(tyrusEndpoint); <add> engine.unregister(tyrusEndpoint); <ide> } <ide> } <ide> <add><path>spring-websocket/src/main/java/org/springframework/websocket/server/endpoint/handshake/RequestUpgradeStrategy.java <del><path>spring-websocket/src/main/java/org/springframework/websocket/server/endpoint/EndpointRequestUpgradeStrategy.java <ide> * limitations under the License. <ide> */ <ide> <del>package org.springframework.websocket.server.endpoint; <add>package org.springframework.websocket.server.endpoint.handshake; <ide> <ide> import javax.websocket.Endpoint; <ide> <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <del>public interface EndpointRequestUpgradeStrategy { <add>public interface RequestUpgradeStrategy { <ide> <ide> String[] getSupportedVersions(); <ide> <ide><path>spring-websocket/src/main/java/org/springframework/websocket/server/endpoint/handshake/TomcatRequestUpgradeStrategy.java <ide> <ide> package org.springframework.websocket.server.endpoint.handshake; <ide> <add>import java.io.IOException; <ide> import java.lang.reflect.Method; <ide> import java.util.Collections; <ide> <ide> import org.springframework.http.server.ServerHttpRequest; <ide> import org.springframework.http.server.ServerHttpResponse; <ide> import org.springframework.http.server.ServletServerHttpRequest; <add>import org.springframework.sockjs.server.NestedSockJsRuntimeException; <ide> import org.springframework.util.Assert; <ide> import org.springframework.util.ReflectionUtils; <ide> import org.springframework.websocket.server.endpoint.EndpointRegistration; <del>import org.springframework.websocket.server.endpoint.EndpointRequestUpgradeStrategy; <ide> <ide> <ide> /** <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <del>public class TomcatRequestUpgradeStrategy implements EndpointRequestUpgradeStrategy { <add>public class TomcatRequestUpgradeStrategy implements RequestUpgradeStrategy { <ide> <ide> <ide> @Override <ide> public String[] getSupportedVersions() { <ide> <ide> @Override <ide> public void upgrade(ServerHttpRequest request, ServerHttpResponse response, String protocol, <del> Endpoint endpoint) throws Exception { <add> Endpoint endpoint) throws IOException { <ide> <ide> Assert.isTrue(request instanceof ServletServerHttpRequest); <ide> HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest(); <ide> <ide> WsHttpUpgradeHandler upgradeHandler = servletRequest.upgrade(WsHttpUpgradeHandler.class); <ide> <ide> WsHandshakeRequest webSocketRequest = new WsHandshakeRequest(servletRequest); <del> Method method = ReflectionUtils.findMethod(WsHandshakeRequest.class, "finished"); <del> ReflectionUtils.makeAccessible(method); <del> method.invoke(webSocketRequest); <add> try { <add> Method method = ReflectionUtils.findMethod(WsHandshakeRequest.class, "finished"); <add> ReflectionUtils.makeAccessible(method); <add> method.invoke(webSocketRequest); <add> } <add> catch (Exception ex) { <add> throw new NestedSockJsRuntimeException("Failed to upgrade HttpServletRequest", ex); <add> } <ide> <ide> // TODO: use ServletContext attribute when Tomcat is updated <ide> WsServerContainer serverContainer = WsServerContainer.getServerContainer();
25
Go
Go
replace cancelled channel with net/context
f2401a0f6960734093be307a27bba85a3c2ecfcd
<ide><path>api/server/router/build/backend.go <ide> type Backend interface { <ide> // by the caller. <ide> // <ide> // TODO: make this return a reference instead of string <del> Build(clientCtx context.Context, config *types.ImageBuildOptions, context builder.Context, stdout io.Writer, stderr io.Writer, out io.Writer, clientGone <-chan bool) (string, error) <add> Build(clientCtx context.Context, config *types.ImageBuildOptions, context builder.Context, stdout io.Writer, stderr io.Writer, out io.Writer) (string, error) <ide> } <ide><path>api/server/router/build/build_routes.go <ide> func (br *buildRouter) postBuild(ctx context.Context, w http.ResponseWriter, r * <ide> return progress.NewProgressReader(in, progressOutput, r.ContentLength, "Downloading context", remoteURL) <ide> } <ide> <del> var ( <del> context builder.ModifiableContext <del> dockerfileName string <del> out io.Writer <del> ) <del> context, dockerfileName, err = builder.DetectContextFromRemoteURL(r.Body, remoteURL, createProgressReader) <add> buildContext, dockerfileName, err := builder.DetectContextFromRemoteURL(r.Body, remoteURL, createProgressReader) <ide> if err != nil { <ide> return errf(err) <ide> } <ide> defer func() { <del> if err := context.Close(); err != nil { <add> if err := buildContext.Close(); err != nil { <ide> logrus.Debugf("[BUILDER] failed to remove temporary context: %v", err) <ide> } <ide> }() <ide> func (br *buildRouter) postBuild(ctx context.Context, w http.ResponseWriter, r * <ide> <ide> buildOptions.AuthConfigs = authConfigs <ide> <del> out = output <add> var out io.Writer = output <ide> if buildOptions.SuppressOutput { <ide> out = notVerboseBuffer <ide> } <ide> out = &syncWriter{w: out} <ide> stdout := &streamformatter.StdoutFormatter{Writer: out, StreamFormatter: sf} <ide> stderr := &streamformatter.StderrFormatter{Writer: out, StreamFormatter: sf} <ide> <del> closeNotifier := make(<-chan bool) <add> finished := make(chan struct{}) <add> defer close(finished) <ide> if notifier, ok := w.(http.CloseNotifier); ok { <del> closeNotifier = notifier.CloseNotify() <add> notifyContext, cancel := context.WithCancel(ctx) <add> closeNotifier := notifier.CloseNotify() <add> go func() { <add> select { <add> case <-closeNotifier: <add> cancel() <add> case <-finished: <add> } <add> }() <add> ctx = notifyContext <ide> } <ide> <ide> imgID, err := br.backend.Build(ctx, buildOptions, <del> builder.DockerIgnoreContext{ModifiableContext: context}, <del> stdout, stderr, out, <del> closeNotifier) <add> builder.DockerIgnoreContext{ModifiableContext: buildContext}, <add> stdout, stderr, out) <ide> if err != nil { <ide> return errf(err) <ide> } <ide><path>builder/dockerfile/builder.go <ide> import ( <ide> "io/ioutil" <ide> "os" <ide> "strings" <del> "sync" <ide> <ide> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/builder" <ide> type Builder struct { <ide> docker builder.Backend <ide> context builder.Context <ide> clientCtx context.Context <add> cancel context.CancelFunc <ide> <ide> dockerfile *parser.Node <ide> runConfig *container.Config // runconfig for cmd, run, entrypoint etc. <ide> type Builder struct { <ide> cmdSet bool <ide> disableCommit bool <ide> cacheBusted bool <del> cancelled chan struct{} <del> cancelOnce sync.Once <ide> allowedBuildArgs map[string]bool // list of build-time args that are allowed for expansion/substitution and passing to commands in 'run'. <ide> <ide> // TODO: remove once docker.Commit can receive a tag <ide> func NewBuildManager(b builder.Backend) (bm *BuildManager) { <ide> // NewBuilder creates a new Dockerfile builder from an optional dockerfile and a Config. <ide> // If dockerfile is nil, the Dockerfile specified by Config.DockerfileName, <ide> // will be read from the Context passed to Build(). <del>func NewBuilder(clientCtx context.Context, config *types.ImageBuildOptions, backend builder.Backend, context builder.Context, dockerfile io.ReadCloser) (b *Builder, err error) { <add>func NewBuilder(clientCtx context.Context, config *types.ImageBuildOptions, backend builder.Backend, buildContext builder.Context, dockerfile io.ReadCloser) (b *Builder, err error) { <ide> if config == nil { <ide> config = new(types.ImageBuildOptions) <ide> } <ide> if config.BuildArgs == nil { <ide> config.BuildArgs = make(map[string]string) <ide> } <add> ctx, cancel := context.WithCancel(clientCtx) <ide> b = &Builder{ <del> clientCtx: clientCtx, <add> clientCtx: ctx, <add> cancel: cancel, <ide> options: config, <ide> Stdout: os.Stdout, <ide> Stderr: os.Stderr, <ide> docker: backend, <del> context: context, <add> context: buildContext, <ide> runConfig: new(container.Config), <ide> tmpContainers: map[string]struct{}{}, <del> cancelled: make(chan struct{}), <ide> id: stringid.GenerateNonCryptoID(), <ide> allowedBuildArgs: make(map[string]bool), <ide> } <ide> func sanitizeRepoAndTags(names []string) ([]reference.Named, error) { <ide> } <ide> <ide> // Build creates a NewBuilder, which builds the image. <del>func (bm *BuildManager) Build(clientCtx context.Context, config *types.ImageBuildOptions, context builder.Context, stdout io.Writer, stderr io.Writer, out io.Writer, clientGone <-chan bool) (string, error) { <add>func (bm *BuildManager) Build(clientCtx context.Context, config *types.ImageBuildOptions, context builder.Context, stdout io.Writer, stderr io.Writer, out io.Writer) (string, error) { <ide> b, err := NewBuilder(clientCtx, config, bm.backend, context, nil) <ide> if err != nil { <ide> return "", err <ide> } <del> img, err := b.build(config, context, stdout, stderr, out, clientGone) <add> img, err := b.build(config, context, stdout, stderr, out) <ide> return img, err <ide> <ide> } <ide> func (bm *BuildManager) Build(clientCtx context.Context, config *types.ImageBuil <ide> // * Tag image, if applicable. <ide> // * Print a happy message and return the image ID. <ide> // <del>func (b *Builder) build(config *types.ImageBuildOptions, context builder.Context, stdout io.Writer, stderr io.Writer, out io.Writer, clientGone <-chan bool) (string, error) { <add>func (b *Builder) build(config *types.ImageBuildOptions, context builder.Context, stdout io.Writer, stderr io.Writer, out io.Writer) (string, error) { <ide> b.options = config <ide> b.context = context <ide> b.Stdout = stdout <ide> func (b *Builder) build(config *types.ImageBuildOptions, context builder.Context <ide> } <ide> } <ide> <del> finished := make(chan struct{}) <del> defer close(finished) <del> go func() { <del> select { <del> case <-finished: <del> case <-clientGone: <del> b.cancelOnce.Do(func() { <del> close(b.cancelled) <del> }) <del> } <del> <del> }() <del> <ide> repoAndTags, err := sanitizeRepoAndTags(config.Tags) <ide> if err != nil { <ide> return "", err <ide> func (b *Builder) build(config *types.ImageBuildOptions, context builder.Context <ide> b.addLabels() <ide> } <ide> select { <del> case <-b.cancelled: <add> case <-b.clientCtx.Done(): <ide> logrus.Debug("Builder: build cancelled!") <ide> fmt.Fprintf(b.Stdout, "Build cancelled") <ide> return "", fmt.Errorf("Build cancelled") <ide> func (b *Builder) build(config *types.ImageBuildOptions, context builder.Context <ide> <ide> // Cancel cancels an ongoing Dockerfile build. <ide> func (b *Builder) Cancel() { <del> b.cancelOnce.Do(func() { <del> close(b.cancelled) <del> }) <add> b.cancel() <ide> } <ide> <ide> // BuildFromConfig builds directly from `changes`, treating it as if it were the contents of a Dockerfile <ide><path>builder/dockerfile/internals.go <ide> package dockerfile <ide> import ( <ide> "crypto/sha256" <ide> "encoding/hex" <add> "errors" <ide> "fmt" <ide> "io" <ide> "io/ioutil" <ide> import ( <ide> "runtime" <ide> "sort" <ide> "strings" <add> "sync" <ide> "time" <ide> <ide> "github.com/Sirupsen/logrus" <ide> func (b *Builder) create() (string, error) { <ide> return c.ID, nil <ide> } <ide> <add>var errCancelled = errors.New("build cancelled") <add> <ide> func (b *Builder) run(cID string) (err error) { <ide> errCh := make(chan error) <ide> go func() { <ide> errCh <- b.docker.ContainerAttachRaw(cID, nil, b.Stdout, b.Stderr, true) <ide> }() <ide> <ide> finished := make(chan struct{}) <del> defer close(finished) <add> var once sync.Once <add> finish := func() { close(finished) } <add> cancelErrCh := make(chan error, 1) <add> defer once.Do(finish) <ide> go func() { <ide> select { <del> case <-b.cancelled: <add> case <-b.clientCtx.Done(): <ide> logrus.Debugln("Build cancelled, killing and removing container:", cID) <ide> b.docker.ContainerKill(cID, 0) <ide> b.removeContainer(cID) <add> cancelErrCh <- errCancelled <ide> case <-finished: <add> cancelErrCh <- nil <ide> } <ide> }() <ide> <ide> func (b *Builder) run(cID string) (err error) { <ide> Code: ret, <ide> } <ide> } <del> <del> return nil <add> once.Do(finish) <add> return <-cancelErrCh <ide> } <ide> <ide> func (b *Builder) removeContainer(c string) error {
4
Ruby
Ruby
fix style violations
ee93787580752ff9246f052de801d90554754d41
<ide><path>actionpack/test/controller/parameters/parameters_permit_test.rb <ide> def walk_permitted(params) <ide> }, <ide> tabstops: [4, 8, 12, 16], <ide> suspicious: [true, Object.new, false, /yo!/], <del> dubious: [{a: :a, b: /wtf!/}, {c: :c}], <add> dubious: [{ a: :a, b: /wtf!/ }, { c: :c }], <ide> injected: Object.new <ide> }, <ide> hacked: 1 # not a hash <ide><path>activerecord/lib/active_record/define_callbacks.rb <ide> module ClassMethods # :nodoc: <ide> included do <ide> include ActiveModel::Validations::Callbacks <ide> <del> define_model_callbacks :initialize, :find, :touch, :only => :after <add> define_model_callbacks :initialize, :find, :touch, only: :after <ide> define_model_callbacks :save, :create, :update, :destroy <ide> end <ide> end
2
Javascript
Javascript
add spec for linking
99899d008f4a0540e3f5671b1f9c6c522c6105e3
<ide><path>Libraries/Linking/Linking.js <ide> <ide> const InteractionManager = require('../Interaction/InteractionManager'); <ide> const NativeEventEmitter = require('../EventEmitter/NativeEventEmitter'); <del>const NativeModules = require('../BatchedBridge/NativeModules'); <ide> const Platform = require('../Utilities/Platform'); <ide> <ide> const invariant = require('invariant'); <ide> <del>const LinkingManager = <del> Platform.OS === 'android' <del> ? NativeModules.IntentAndroid <del> : NativeModules.LinkingManager; <add>import NativeLinking from './NativeLinking'; <ide> <ide> /** <ide> * `Linking` gives you a general interface to interact with both incoming <ide> const LinkingManager = <ide> */ <ide> class Linking extends NativeEventEmitter { <ide> constructor() { <del> super(LinkingManager); <add> super(NativeLinking); <ide> } <ide> <ide> /** <ide> class Linking extends NativeEventEmitter { <ide> */ <ide> openURL(url: string): Promise<any> { <ide> this._validateURL(url); <del> return LinkingManager.openURL(url); <add> return NativeLinking.openURL(url); <ide> } <ide> <ide> /** <ide> class Linking extends NativeEventEmitter { <ide> */ <ide> canOpenURL(url: string): Promise<boolean> { <ide> this._validateURL(url); <del> return LinkingManager.canOpenURL(url); <add> return NativeLinking.canOpenURL(url); <ide> } <ide> <ide> /** <ide> class Linking extends NativeEventEmitter { <ide> * See https://facebook.github.io/react-native/docs/linking.html#opensettings <ide> */ <ide> openSettings(): Promise<any> { <del> return LinkingManager.openSettings(); <add> return NativeLinking.openSettings(); <ide> } <ide> <ide> /** <ide> class Linking extends NativeEventEmitter { <ide> getInitialURL(): Promise<?string> { <ide> return Platform.OS === 'android' <ide> ? InteractionManager.runAfterInteractions().then(() => <del> LinkingManager.getInitialURL(), <add> NativeLinking.getInitialURL(), <ide> ) <del> : LinkingManager.getInitialURL(); <add> : NativeLinking.getInitialURL(); <ide> } <ide> <ide> /* <ide> class Linking extends NativeEventEmitter { <ide> * See https://facebook.github.io/react-native/docs/linking.html#sendintent <ide> */ <ide> sendIntent( <del> action: String, <del> extras?: [{key: string, value: string | number | boolean}], <del> ) { <del> return LinkingManager.sendIntent(action, extras); <add> action: string, <add> extras?: Array<{key: string, value: string | number | boolean}>, <add> ): Promise<void> { <add> if (Platform.OS === 'android') { <add> return NativeLinking.sendIntent(action, extras); <add> } <add> return new Promise((resolve, reject) => reject(new Error('Unsupported'))); <ide> } <ide> <ide> _validateURL(url: string) { <ide><path>Libraries/Linking/NativeLinking.js <add>/** <add> * Copyright (c) Facebook, Inc. and its affiliates. <add> * <add> * This source code is licensed under the MIT license found in the <add> * LICENSE file in the root directory of this source tree. <add> * <add> * @flow <add> * @format <add> */ <add> <add>'use strict'; <add> <add>import type {TurboModule} from 'RCTExport'; <add>import * as TurboModuleRegistry from 'TurboModuleRegistry'; <add>import Platform from 'Platform'; <add> <add>export interface Spec extends TurboModule { <add> // Common interface <add> +getInitialURL: () => Promise<string>; <add> +canOpenURL: (url: string) => Promise<boolean>; <add> +openURL: (url: string) => Promise<void>; <add> +openSettings: () => Promise<void>; <add> <add> // Android only <add> +sendIntent: ( <add> action: string, <add> extras: ?Array<{key: string, value: string | number | boolean}>, <add> ) => Promise<void>; <add> <add> // Events <add> +addListener: (eventName: string) => void; <add> +removeListeners: (count: number) => void; <add>} <add> <add>export default (Platform.OS === 'ios' <add> ? TurboModuleRegistry.getEnforcing<Spec>('LinkingManager') <add> : TurboModuleRegistry.getEnforcing<Spec>('IntentAndroid'));
2
PHP
PHP
delete
736716781cc1856ebb12701fc95edebaa894d716
<ide><path>src/Illuminate/Filesystem/Filesystem.php <ide> public function prepend($path, $data) <ide> { <ide> if ($this->exists($path)) <ide> { <del> return $this->put($path, $data.$this->get($path)); <add> return $this->put($path, $data.$this->get($path)); <ide> } <ide> else <ide> { <ide> public function delete($paths) <ide> { <ide> $paths = is_array($paths) ? $paths : func_get_args(); <ide> <del> foreach ($paths as $path) { @unlink($path); } <add> $success = true; <add> <add> foreach ($paths as $path) { if ( ! @unlink($path)) $success = false; } <add> <add> return $success; <ide> } <ide> <ide> /** <ide> public function deleteDirectory($directory, $preserve = false) <ide> } <ide> <ide> if ( ! $preserve) @rmdir($directory); <del> <add> <ide> return true; <ide> } <ide>
1
Mixed
Ruby
add option to skip joins for associations
de6b4efa3e86727f3bd2f2e7982c0902efd19e1a
<ide><path>activerecord/CHANGELOG.md <add>* Add option to disable joins for associations. <add> <add> In a multiple database application, associations can't join across <add> databases. When set, this option instructs Rails to generate 2 or <add> more queries rather than generating joins for associations. <add> <add> Set the option on a has many through association: <add> <add> ```ruby <add> class Dog <add> has_many :treats, through: :humans, disable_joins: true <add> has_many :humans <add> end <add> ``` <add> <add> Then instead of generating join SQL, two queries are used for `@dog.treats`: <add> <add> ``` <add> SELECT "humans"."id" FROM "humans" WHERE "humans"."dog_id" = ? [["dog_id", 1]] <add> SELECT "treats".* FROM "treats" WHERE "treats"."human_id" IN (?, ?, ?) [["human_id", 1], ["human_id", 2], ["human_id", 3]] <add> ``` <add> <add> *Eileen M. Uchitelle*, *Aaron Patterson*, *Lee Quarella* <add> <ide> * Add setting for enumerating column names in SELECT statements. <ide> <ide> Adding a column to a PostgresSQL database, for example, while the application is running can <ide><path>activerecord/lib/active_record.rb <ide> module ActiveRecord <ide> <ide> autoload :Relation <ide> autoload :AssociationRelation <add> autoload :DisableJoinsAssociationRelation <ide> autoload :NullRelation <ide> <ide> autoload_under "relation" do <ide><path>activerecord/lib/active_record/associations.rb <ide> module Builder #:nodoc: <ide> autoload :Preloader <ide> autoload :JoinDependency <ide> autoload :AssociationScope <add> autoload :DisableJoinsAssociationScope <ide> autoload :AliasTracker <ide> end <ide> <ide> module ClassMethods <ide> # of association, including other <tt>:through</tt> associations. Options for <tt>:class_name</tt>, <ide> # <tt>:primary_key</tt> and <tt>:foreign_key</tt> are ignored, as the association uses the <ide> # source reflection. <add> # [:disable_joins] <add> # Specifies whether joins should be skipped for an association. If set to true, two or more queries <add> # will be generated. Note that in some cases, if order or limit is applied, it will be done in-memory <add> # due to database limitions. This option is only applicable on `has_many :through` associations as <add> # `has_many` alone do not perform a join. <ide> # <ide> # If the association on the join model is a #belongs_to, the collection can be modified <ide> # and the records on the <tt>:through</tt> model will be automatically created and removed <ide> module ClassMethods <ide> # has_many :tags, as: :taggable <ide> # has_many :reports, -> { readonly } <ide> # has_many :subscribers, through: :subscriptions, source: :user <add> # has_many :subscribers, through: :subscriptions, disable_joins: true <ide> # has_many :comments, strict_loading: true <ide> def has_many(name, scope = nil, **options, &extension) <ide> reflection = Builder::HasMany.build(self, name, scope, options, &extension) <ide><path>activerecord/lib/active_record/associations/association.rb <ide> module Associations <ide> # <tt>owner</tt>, the collection of its posts as <tt>target</tt>, and <ide> # the <tt>reflection</tt> object represents a <tt>:has_many</tt> macro. <ide> class Association #:nodoc: <del> attr_reader :owner, :target, :reflection <add> attr_reader :owner, :target, :reflection, :disable_joins <ide> <ide> delegate :options, to: :reflection <ide> <ide> def initialize(owner, reflection) <ide> reflection.check_validity! <ide> <ide> @owner, @reflection = owner, reflection <add> @disable_joins = @reflection.options[:disable_joins] || false <ide> <ide> reset <ide> reset_scope <ide> def target=(target) <ide> end <ide> <ide> def scope <del> if (scope = klass.current_scope) && scope.try(:proxy_association) == self <add> if disable_joins <add> DisableJoinsAssociationScope.create.scope(self) <add> elsif (scope = klass.current_scope) && scope.try(:proxy_association) == self <ide> scope.spawn <ide> elsif scope = klass.global_current_scope <ide> target_scope.merge!(association_scope).merge!(scope) <ide> def violates_strict_loading? <ide> # actually gets built. <ide> def association_scope <ide> if klass <del> @association_scope ||= AssociationScope.scope(self) <add> @association_scope ||= if disable_joins <add> DisableJoinsAssociationScope.scope(self) <add> else <add> AssociationScope.scope(self) <add> end <ide> end <ide> end <ide> <ide><path>activerecord/lib/active_record/associations/builder/has_many.rb <ide> def self.valid_options(options) <ide> valid += [:as, :foreign_type] if options[:as] <ide> valid += [:through, :source, :source_type] if options[:through] <ide> valid += [:ensuring_owner_was] if options[:dependent] == :destroy_async <add> valid += [:disable_joins] if options[:disable_joins] && options[:through] <ide> valid <ide> end <ide> <ide><path>activerecord/lib/active_record/associations/disable_joins_association_scope.rb <add># frozen_string_literal: true <add> <add>module ActiveRecord <add> module Associations <add> class DisableJoinsAssociationScope < AssociationScope # :nodoc: <add> def scope(association) <add> source_reflection = association.reflection <add> owner = association.owner <add> unscoped = association.klass.unscoped <add> reverse_chain = get_chain(source_reflection, association, unscoped.alias_tracker).reverse <add> <add> last_reflection, last_ordered, last_join_ids = last_scope_chain(reverse_chain, owner) <add> <add> add_constraints(last_reflection, last_reflection.join_primary_key, last_join_ids, owner, last_ordered) <add> end <add> <add> private <add> def last_scope_chain(reverse_chain, owner) <add> first_scope = [reverse_chain.shift, false, [owner.id]] <add> <add> reverse_chain.inject(first_scope) do |(reflection, ordered, join_ids), next_reflection| <add> key = reflection.join_primary_key <add> records = add_constraints(reflection, key, join_ids, owner, ordered) <add> foreign_key = next_reflection.join_foreign_key <add> record_ids = records.pluck(foreign_key) <add> records_ordered = records && records.order_values.any? <add> <add> [next_reflection, records_ordered, record_ids] <add> end <add> end <add> <add> def add_constraints(reflection, key, join_ids, owner, ordered) <add> scope = reflection.build_scope(reflection.aliased_table).where(key => join_ids) <add> scope = reflection.constraints.inject(scope) do |memo, scope_chain_item| <add> item = eval_scope(reflection, scope_chain_item, owner) <add> scope.unscope!(*item.unscope_values) <add> scope.where_clause += item.where_clause <add> scope.order_values = item.order_values | scope.order_values <add> scope <add> end <add> <add> if scope.order_values.empty? && ordered <add> split_scope = DisableJoinsAssociationRelation.create(scope.klass, key, join_ids) <add> split_scope.where_clause += scope.where_clause <add> split_scope <add> else <add> scope <add> end <add> end <add> end <add> end <add>end <ide><path>activerecord/lib/active_record/associations/has_many_through_association.rb <ide> def delete_through_records(records) <ide> <ide> def find_target <ide> return [] unless target_reflection_has_associated_record? <add> return scope.to_a if disable_joins <ide> super <ide> end <ide> <ide><path>activerecord/lib/active_record/associations/preloader/through_association.rb <ide> def through_scope <ide> scope = through_reflection.klass.unscoped <ide> options = reflection.options <ide> <add> return scope if options[:disable_joins] <add> <ide> values = reflection_scope.values <ide> if annotations = values[:annotate] <ide> scope.annotate!(*annotations) <ide><path>activerecord/lib/active_record/disable_joins_association_relation.rb <add># frozen_string_literal: true <add> <add>module ActiveRecord <add> class DisableJoinsAssociationRelation < Relation # :nodoc: <add> TOO_MANY_RECORDS = 5000 <add> <add> attr_reader :ids, :key <add> <add> def initialize(klass, key, ids) <add> @ids = ids.uniq <add> @key = key <add> super(klass) <add> end <add> <add> def limit(value) <add> records.take(value) <add> end <add> <add> def first(limit = nil) <add> if limit <add> records.limit(limit).first <add> else <add> records.first <add> end <add> end <add> <add> def load <add> super <add> records = @records <add> <add> records_by_id = records.group_by do |record| <add> record[key] <add> end <add> <add> records = ids.flat_map { |id| records_by_id[id.to_i] } <add> records.compact! <add> <add> @records = records <add> end <add> end <add>end <ide><path>activerecord/lib/active_record/relation/delegation.rb <ide> def initialize_relation_delegate_cache <ide> [ <ide> ActiveRecord::Relation, <ide> ActiveRecord::Associations::CollectionProxy, <del> ActiveRecord::AssociationRelation <add> ActiveRecord::AssociationRelation, <add> ActiveRecord::DisableJoinsAssociationRelation <ide> ].each do |klass| <ide> delegate = Class.new(klass) { <ide> include ClassSpecificRelation <ide><path>activerecord/test/cases/associations/has_many_through_disable_joins_associations_test.rb <add># frozen_string_literal: true <add> <add>require "cases/helper" <add> <add>require "models/post" <add>require "models/author" <add>require "models/comment" <add>require "models/rating" <add>require "models/member" <add>require "models/member_type" <add> <add>require "models/pirate" <add>require "models/treasure" <add> <add>require "models/hotel" <add>require "models/department" <add> <add>class HasManyThroughDisableJoinsAssociationsTest < ActiveRecord::TestCase <add> fixtures :posts, :authors, :comments, :pirates <add> <add> def setup <add> @author = authors(:mary) <add> @post = @author.posts.create(title: "title", body: "body") <add> @member_type = MemberType.create(name: "club") <add> @member = Member.create(member_type: @member_type) <add> @comment = @post.comments.create(body: "text", origin: @member) <add> @post2 = @author.posts.create(title: "title", body: "body") <add> @member2 = Member.create(member_type: @member_type) <add> @comment2 = @post2.comments.create(body: "text", origin: @member2) <add> @rating1 = @comment.ratings.create(value: 8) <add> @rating2 = @comment.ratings.create(value: 9) <add> end <add> <add> def test_counting_on_disable_joins_through <add> assert_equal @author.comments.count, @author.no_joins_comments.count <add> assert_queries(2) { @author.no_joins_comments.count } <add> assert_queries(1) { @author.comments.count } <add> end <add> <add> def test_counting_on_disable_joins_through_using_custom_foreign_key <add> assert_equal @author.comments_with_foreign_key.count, @author.no_joins_comments_with_foreign_key.count <add> assert_queries(2) { @author.no_joins_comments_with_foreign_key.count } <add> assert_queries(1) { @author.comments_with_foreign_key.count } <add> end <add> <add> def test_pluck_on_disable_joins_through <add> assert_equal @author.comments.pluck(:id), @author.no_joins_comments.pluck(:id) <add> assert_queries(2) { @author.no_joins_comments.pluck(:id) } <add> assert_queries(1) { @author.comments.pluck(:id) } <add> end <add> <add> def test_pluck_on_disable_joins_through_using_custom_foreign_key <add> assert_equal @author.comments_with_foreign_key.pluck(:id), @author.no_joins_comments_with_foreign_key.pluck(:id) <add> assert_queries(2) { @author.no_joins_comments_with_foreign_key.pluck(:id) } <add> assert_queries(1) { @author.comments_with_foreign_key.pluck(:id) } <add> end <add> <add> def test_fetching_on_disable_joins_through <add> assert_equal @author.comments.first.id, @author.no_joins_comments.first.id <add> assert_queries(2) { @author.no_joins_comments.first.id } <add> assert_queries(1) { @author.comments.first.id } <add> end <add> <add> def test_fetching_on_disable_joins_through_using_custom_foreign_key <add> assert_equal @author.comments_with_foreign_key.first.id, @author.no_joins_comments_with_foreign_key.first.id <add> assert_queries(2) { @author.no_joins_comments_with_foreign_key.first.id } <add> assert_queries(1) { @author.comments_with_foreign_key.first.id } <add> end <add> <add> def test_to_a_on_disable_joins_through <add> assert_equal @author.comments.to_a, @author.no_joins_comments.to_a <add> @author.reload <add> assert_queries(2) { @author.no_joins_comments.to_a } <add> assert_queries(1) { @author.comments.to_a } <add> end <add> <add> def test_appending_on_disable_joins_through <add> assert_difference(->() { @author.no_joins_comments.reload.size }) do <add> @post.comments.create(body: "text") <add> end <add> assert_queries(2) { @author.no_joins_comments.reload.size } <add> assert_queries(1) { @author.comments.reload.size } <add> end <add> <add> def test_appending_on_disable_joins_through_using_custom_foreign_key <add> assert_difference(->() { @author.no_joins_comments_with_foreign_key.reload.size }) do <add> @post.comments.create(body: "text") <add> end <add> assert_queries(2) { @author.no_joins_comments_with_foreign_key.reload.size } <add> assert_queries(1) { @author.comments_with_foreign_key.reload.size } <add> end <add> <add> def test_empty_on_disable_joins_through <add> empty_author = authors(:bob) <add> assert_equal [], assert_queries(0) { empty_author.comments.all } <add> assert_equal [], assert_queries(1) { empty_author.no_joins_comments.all } <add> end <add> <add> def test_empty_on_disable_joins_through_using_custom_foreign_key <add> empty_author = authors(:bob) <add> assert_equal [], assert_queries(0) { empty_author.comments_with_foreign_key.all } <add> assert_equal [], assert_queries(1) { empty_author.no_joins_comments_with_foreign_key.all } <add> end <add> <add> def test_pluck_on_disable_joins_through_a_through <add> rating_ids = Rating.where(comment: @comment).pluck(:id) <add> assert_equal rating_ids, assert_queries(1) { @author.ratings.pluck(:id) } <add> assert_equal rating_ids, assert_queries(3) { @author.no_joins_ratings.pluck(:id) } <add> end <add> <add> def test_count_on_disable_joins_through_a_through <add> ratings_count = Rating.where(comment: @comment).count <add> assert_equal ratings_count, assert_queries(1) { @author.ratings.count } <add> assert_equal ratings_count, assert_queries(3) { @author.no_joins_ratings.count } <add> end <add> <add> def test_count_on_disable_joins_using_relation_with_scope <add> assert_equal 2, assert_queries(1) { @author.good_ratings.count } <add> assert_equal 2, assert_queries(3) { @author.no_joins_good_ratings.count } <add> end <add> <add> def test_to_a_on_disable_joins_with_multiple_scopes <add> assert_equal [@rating1, @rating2], assert_queries(1) { @author.good_ratings.to_a } <add> assert_equal [@rating1, @rating2], assert_queries(3) { @author.no_joins_good_ratings.to_a } <add> end <add> <add> def test_preloading_has_many_through_disable_joins <add> assert_queries(3) { Author.all.preload(:good_ratings).map(&:good_ratings) } <add> assert_queries(4) { Author.all.preload(:no_joins_good_ratings).map(&:good_ratings) } <add> end <add> <add> def test_polymophic_disable_joins_through_counting <add> assert_equal 2, assert_queries(1) { @author.ordered_members.count } <add> assert_equal 2, assert_queries(3) { @author.no_joins_ordered_members.count } <add> end <add> <add> def test_polymophic_disable_joins_through_ordering <add> assert_equal [@member2, @member], assert_queries(1) { @author.ordered_members.to_a } <add> assert_equal [@member2, @member], assert_queries(3) { @author.no_joins_ordered_members.to_a } <add> end <add> <add> def test_polymorphic_disable_joins_through_reordering <add> assert_equal [@member, @member2], assert_queries(1) { @author.ordered_members.reorder(id: :asc).to_a } <add> assert_equal [@member, @member2], assert_queries(3) { @author.no_joins_ordered_members.reorder(id: :asc).to_a } <add> end <add> <add> def test_polymorphic_disable_joins_through_ordered_scopes <add> assert_equal [@member2, @member], assert_queries(1) { @author.ordered_members.unnamed.to_a } <add> assert_equal [@member2, @member], assert_queries(3) { @author.no_joins_ordered_members.unnamed.to_a } <add> end <add> <add> def test_polymorphic_disable_joins_through_ordered_chained_scopes <add> member3 = Member.create(member_type: @member_type) <add> member4 = Member.create(member_type: @member_type, name: "named") <add> @post2.comments.create(body: "text", origin: member3) <add> @post2.comments.create(body: "text", origin: member4) <add> <add> assert_equal [member3, @member2, @member], assert_queries(1) { @author.ordered_members.unnamed.with_member_type_id(@member_type.id).to_a } <add> assert_equal [member3, @member2, @member], assert_queries(3) { @author.no_joins_ordered_members.unnamed.with_member_type_id(@member_type.id).to_a } <add> end <add> <add> def test_polymorphic_disable_joins_through_ordered_scope_limits <add> assert_equal [@member2], assert_queries(1) { @author.ordered_members.unnamed.limit(1).to_a } <add> assert_equal [@member2], assert_queries(3) { @author.no_joins_ordered_members.unnamed.limit(1).to_a } <add> end <add> <add> def test_polymorphic_disable_joins_through_ordered_scope_first <add> assert_equal @member2, assert_queries(1) { @author.ordered_members.unnamed.first } <add> assert_equal @member2, assert_queries(3) { @author.no_joins_ordered_members.unnamed.first } <add> end <add> <add> def test_order_applied_in_double_join <add> assert_equal [@member2, @member], assert_queries(1) { @author.members.to_a } <add> assert_equal [@member2, @member], assert_queries(3) { @author.no_joins_members.to_a } <add> end <add> <add> def test_first_and_scope_applied_in_double_join <add> assert_equal @member2, assert_queries(1) { @author.members.unnamed.first } <add> assert_equal @member2, assert_queries(3) { @author.no_joins_members.unnamed.first } <add> end <add> <add> def test_first_and_scope_in_double_join_applies_order_in_memory <add> disable_joins_sql = capture_sql { @author.no_joins_members.unnamed.first } <add> assert_no_match(/ORDER BY/, disable_joins_sql.last) <add> end <add> <add> def test_limit_and_scope_applied_in_double_join <add> assert_equal [@member2], assert_queries(1) { @author.members.unnamed.limit(1).to_a } <add> assert_equal [@member2], assert_queries(3) { @author.no_joins_members.unnamed.limit(1) } <add> end <add> <add> def test_limit_and_scope_in_double_join_applies_limit_in_memory <add> disable_joins_sql = capture_sql { @author.no_joins_members.unnamed.first } <add> assert_no_match(/LIMIT 1/, disable_joins_sql.last) <add> end <add>end <ide><path>activerecord/test/models/author.rb <ide> def ratings <ide> Rating.joins(:comment).merge(self) <ide> end <ide> end <add> <add> has_many :comments_with_order, -> { ordered_by_post_id }, through: :posts, source: :comments <add> has_many :no_joins_comments, through: :posts, disable_joins: :true, source: :comments <add> <add> has_many :comments_with_foreign_key, through: :posts, source: :comments, foreign_key: :post_id <add> has_many :no_joins_comments_with_foreign_key, through: :posts, disable_joins: :true, source: :comments, foreign_key: :post_id <add> <add> has_many :members, <add> through: :comments_with_order, <add> source: :origin, <add> source_type: "Member" <add> <add> has_many :no_joins_members, <add> through: :comments_with_order, <add> source: :origin, <add> source_type: "Member", <add> disable_joins: true <add> <add> has_many :ordered_members, <add> -> { order(id: :desc) }, <add> through: :comments_with_order, <add> source: :origin, <add> source_type: "Member" <add> <add> has_many :no_joins_ordered_members, <add> -> { order(id: :desc) }, <add> through: :comments_with_order, <add> source: :origin, <add> source_type: "Member", <add> disable_joins: true <add> <add> has_many :ratings, through: :comments <add> has_many :good_ratings, <add> -> { where("ratings.value > 5") }, <add> through: :comments, <add> source: :ratings <add> <add> has_many :no_joins_ratings, through: :no_joins_comments, disable_joins: :true, source: :ratings <add> has_many :no_joins_good_ratings, <add> -> { where("ratings.value > 5") }, <add> through: :comments, <add> source: :ratings, <add> disable_joins: true <add> <ide> has_many :comments_containing_the_letter_e, through: :posts, source: :comments <ide> has_many :comments_with_order_and_conditions, -> { order("comments.body").where("comments.body like 'Thank%'") }, through: :posts, source: :comments <ide> has_many :comments_with_include, -> { includes(:post).where(posts: { type: "Post" }) }, through: :posts, source: :comments <ide><path>activerecord/test/models/comment.rb <ide> class Comment < ActiveRecord::Base <ide> scope :for_first_post, -> { where(post_id: 1) } <ide> scope :for_first_author, -> { joins(:post).where("posts.author_id" => 1) } <ide> scope :created, -> { all } <add> scope :ordered_by_post_id, -> { order("comments.post_id DESC") } <ide> <ide> belongs_to :post, counter_cache: true <ide> belongs_to :author, polymorphic: true <ide> belongs_to :resource, polymorphic: true <add> belongs_to :origin, polymorphic: true <ide> belongs_to :company, foreign_key: "company" <ide> <ide> has_many :ratings <ide><path>activerecord/test/models/member.rb <ide> class Member < ActiveRecord::Base <ide> <ide> belongs_to :admittable, polymorphic: true <ide> has_one :premium_club, through: :admittable <add> <add> scope :unnamed, -> { where(name: nil) } <add> scope :with_member_type_id, -> (id) { where(member_type_id: id) } <ide> end <ide> <ide> class SelfMember < ActiveRecord::Base <ide><path>activerecord/test/models/post.rb <ide> def greeting <ide> scope :containing_the_letter_a, -> { where("body LIKE '%a%'") } <ide> scope :titled_with_an_apostrophe, -> { where("title LIKE '%''%'") } <ide> scope :ranked_by_comments, -> { order(table[:comments_count].desc) } <add> scope :ordered_by_post_id, -> { order("posts.post_id ASC") } <ide> <ide> scope :limit_by, lambda { |l| limit(l) } <ide> scope :locked, -> { lock } <ide><path>activerecord/test/schema/schema.rb <ide> # See #14855. <ide> t.string :resource_id <ide> t.string :resource_type <add> t.integer :origin_id <add> t.string :origin_type <ide> t.integer :developer_id <ide> t.datetime :updated_at <ide> t.datetime :deleted_at <ide><path>guides/source/active_record_multiple_databases.md <ide> databases <ide> The following features are not (yet) supported: <ide> <ide> * Automatic swapping for horizontal sharding <del>* Joining across clusters <ide> * Load balancing replicas <ide> * Dumping schema caches for multiple databases <ide> <ide> end <ide> `ActiveRecord::Base.connected_to` maintains the ability to switch <ide> connections globally. <ide> <add>### Handling associations with joins across databases <add> <add>As of Rails 7.0+, Active Record has an option for handling associations that would perform <add>a join across multiple databases. If you have a has many through association that you want to <add>disable joining and perform 2 or more queries, pass the `disable_joins: true` option. <add> <add>For example: <add> <add>```ruby <add>class Dog < AnimalsRecord <add> has_many :treats, through: :humans, disable_joins: true <add> has_many :humans <add>end <add>``` <add> <add>Previously calling `@dog.treats` without `disable_joins` would raise an error because databases are unable <add>to handle joins across clusters. With the `disable_joins` option, Rails will generate multiple select queries <add>to avoid attempting joining across clusters. For the above association `@dog.treats` would generate the <add>following SQL: <add> <add>```sql <add>SELECT "humans"."id" FROM "humans" WHERE "humans"."dog_id" = ? [["dog_id", 1]] <add>SELECT "treats".* FROM "treats" WHERE "treats"."human_id" IN (?, ?, ?) [["human_id", 1], ["human_id", 2], ["human_id", 3]] <add>``` <add> <add>There are some important things to be aware of with this option: <add> <add>1) There may be performance implications since now two or more queries will be performed (depending <add>on the association) rather than a join. If the select for `humans` returned a high number of IDs <add>the select for `treats` may send too many IDs. <add>2) Since we are no longer performing joins a query with an order or limit is now sorted in-memory since <add>order from one table cannot be applied to another table. <add>3) This setting must be added to all associations that you want joining to be disabled. <add>Rails can't guess this for you because association loading is lazy, to load `treats` in `@dog.treats` <add>Rails already needs to know what SQL should be generated. <add> <ide> ## Caveats <ide> <ide> ### Automatic swapping for horizontal sharding <ide> dependent on your infrastructure. We may implement basic, primitive load balanci <ide> in the future, but for an application at scale this should be something your application <ide> handles outside of Rails. <ide> <del>### Joining Across Databases <del> <del>Applications cannot join across databases. At the moment applications will need to <del>manually write two selects and split the joins themselves. In a future version Rails <del>will split the joins for you. <del> <ide> ### Schema Cache <ide> <ide> If you use a schema cache and multiple databases, you'll need to write an initializer
17
Text
Text
remove trailing slashes
acc5c18ba375aa982e5b834a65d95db2f4bee36b
<ide><path>CONTRIBUTING.md <ide> in the proper package's repository. <ide> * Follow the [CoffeeScript](#coffeescript-styleguide), <ide> [JavaScript](https://github.com/styleguide/javascript), <ide> and [CSS](https://github.com/styleguide/css) styleguides <del> * Include thoughtfully worded [Jasmine](http://pivotal.github.com/jasmine/) <add> * Include thoughtfully worded [Jasmine](http://pivotal.github.com/jasmine) <ide> specs <ide> * Avoid placing files in `vendor`. 3rd-party packages should be added as a <ide> `package.json` dependency. <ide> in the proper package's repository. <ide> <ide> ## Documentation Styleguide <ide> <del>* Use [TomDoc](http://tomdoc.org/). <del>* Use [Markdown](https://daringfireball.net/projects/markdown/). <add>* Use [TomDoc](http://tomdoc.org). <add>* Use [Markdown](https://daringfireball.net/projects/markdown). <ide> * Reference classes with `{ClassName}` style notation. <ide> * Reference methods with `{ClassName.methodName}` style notation. <ide> * Delegate to comments elsewhere with `{Delegates to: ClassName.methodName}`
1
Text
Text
correct url to blog post
2a845a61b747b71adc4df84f9261391d12547733
<ide><path>examples/with-reasonml/README.md <ide> Run BuckleScript build system `bsb -w` and `next -w` separately. For the sake <ide> of simple convention, `npm run dev` run both `bsb` and `next` concurrently. <ide> However, this doesn't offer the full [colorful and very, very, veeeery nice <ide> error <del>output](https://reasonml.github.io/community/blog/#way-way-waaaay-nicer-error-messages) <add>output](https://reasonml.github.io/blog/2017/08/25/way-nicer-error-messages.html) <ide> experience that ReasonML can offer, don't miss it! <ide> <ide> ## The idea behind the example
1
PHP
PHP
add docs and missing property definition
edcef5b6a5ecc8bdef2a2c2f988823ae4420f092
<ide><path>src/Controller/Controller.php <ide> class Controller implements EventListener { <ide> /** <ide> * The name of this controller. Controller names are plural, named after the model they manipulate. <ide> * <add> * Set automatically using conventions in Controller::__construct(). <add> * <ide> * @var string <ide> * @link http://book.cakephp.org/2.0/en/controllers.html#controller-attributes <ide> */ <ide> class Controller implements EventListener { <ide> */ <ide> public $methods = array(); <ide> <add>/** <add> * The path to this controllers view templates. <add> * Example `Articles` <add> * <add> * Set automatically using conventions in Controller::__construct(). <add> * <add> * @var string <add> */ <add> public $viewPath; <add> <ide> /** <ide> * Constructor. <ide> * <add> * Sets a number of properties based on conventions if they are empty. To override the <add> * conventions CakePHP uses you can define properties in your class declaration. <add> * <ide> * @param \Cake\Network\Request $request Request object for this controller. Can be null for testing, <ide> * but expect that features that use the request parameters will not work. <ide> * @param \Cake\Network\Response $response Response object for this controller. <ide><path>src/Model/ModelAwareTrait.php <ide> trait ModelAwareTrait { <ide> * This object's primary model class name. Should be a plural form. <ide> * CakePHP will not inflect the name. <ide> * <del> * Example: For a object named 'Comments', the modelClass would be 'Comments' <add> * Example: For a object named 'Comments', the modelClass would be 'Comments'. <add> * Plugin classes should use `Plugin.Comments` style names to correctly load <add> * models from the correct plugin. <ide> * <ide> * @var string <ide> */
2
Javascript
Javascript
use callback arguments in getconnections test
7113d999dcb7e93ac1504f3ae622df61a9495a1c
<ide><path>test/parallel/test-child-process-fork-getconnections.js <ide> if (process.argv[2] === 'child') { <ide> const child = fork(process.argv[1], ['child']); <ide> <ide> child.on('exit', function(code, signal) { <del> if (!subprocessKilled) <del> throw new Error('subprocess died unexpectedly!'); <add> if (!subprocessKilled) { <add> assert.fail('subprocess died unexpectedly! ' + <add> `code: ${code} signal: ${signal}`); <add> } <ide> }); <ide> <ide> const server = net.createServer(); <ide> if (process.argv[2] === 'child') { <ide> child.once('message', function(m) { <ide> assert.strictEqual(m.status, 'closed'); <ide> server.getConnections(function(err, num) { <add> assert.ifError(err); <add> assert.strictEqual(num, count - (i + 1)); <ide> closeSockets(i + 1); <ide> }); <ide> });
1
Ruby
Ruby
add test for basename in `#extract_nestedly`
c6fa3fe8b416a41c698188269c3f587c3ad107d1
<ide><path>Library/Homebrew/test/unpack_strategy_spec.rb <ide> expect(Pathname.glob(unpack_dir/"**/*")).to include unpack_dir/directories <ide> end <ide> end <add> <add> context "when extracting a nested archive" do <add> let(:basename) { "file.xyz" } <add> let(:path) { <add> (mktmpdir/basename).tap do |path| <add> mktmpdir do |dir| <add> FileUtils.touch dir/"file.txt" <add> system "tar", "-c", "-f", path, "-C", dir, "file.txt" <add> end <add> end <add> } <add> <add> it "does not pass down the basename of the archive" do <add> strategy.extract_nestedly(to: unpack_dir) <add> expect(unpack_dir/"file.txt").to be_a_file <add> end <add> end <ide> end <ide> end <ide>
1