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 |
|---|---|---|---|---|---|
Text | Text | add render_layout.action_view asn to documentation | 9219fb314d75337f9c9d318a7971871e0b874fbc | <ide><path>guides/source/active_support_instrumentation.md
<ide> INFO. Additional keys may be added by the caller.
<ide> }
<ide> ```
<ide>
<add>#### render_layout.action_view
<add>
<add>| Key | Value |
<add>| ------------- | --------------------- |
<add>| `:identifier` | Full path to template |
<add>
<add>
<add>```ruby
<add>{
<add> identifier: "/Users/adam/projects/notifications/app/views/layouts/application.html.erb"
<add>}
<add>```
<add>
<ide> ### Active Record
<ide>
<ide> #### sql.active_record | 1 |
Mixed | Go | fix outdated docs and comments | e82989f8455721f4287bd501ee2d819924dd8026 | <ide><path>libnetwork/README.md
<ide> There are many networking solutions available to suit a broad range of use-cases
<ide> return
<ide> }
<ide>
<del> // Create the sandbox for the containr.
<add> // Create the sandbox for the container.
<add> // NewSandbox accepts Variadic optional arguments which libnetwork can use.
<ide> sbx, err := controller.NewSandbox("container1",
<ide> libnetwork.OptionHostname("test"),
<ide> libnetwork.OptionDomainname("docker.io"))
<ide>
<ide> // A sandbox can join the endpoint via the join api.
<del> // Join accepts Variadic arguments which libnetwork and Drivers can use.
<ide> err = ep.Join(sbx)
<ide> if err != nil {
<ide> return
<ide><path>libnetwork/controller.go
<ide> Package libnetwork provides the basic functionality and extension points to
<ide> create network namespaces and allocate interfaces for containers to use.
<ide>
<del> // Create a new controller instance
<del> controller, _err := libnetwork.New(nil)
<del>
<del> // Select and configure the network driver
<ide> networkType := "bridge"
<ide>
<add> // Create a new controller instance
<ide> driverOptions := options.Generic{}
<ide> genericOption := make(map[string]interface{})
<ide> genericOption[netlabel.GenericData] = driverOptions
<del> err := controller.ConfigureNetworkDriver(networkType, genericOption)
<add> controller, err := libnetwork.New(config.OptionDriverConfig(networkType, genericOption))
<ide> if err != nil {
<ide> return
<ide> }
<ide> create network namespaces and allocate interfaces for containers to use.
<ide> return
<ide> }
<ide>
<del> // A container can join the endpoint by providing the container ID to the join api.
<del> // Join accepts Variadic arguments which will be made use of by libnetwork and Drivers
<del> err = ep.Join("container1",
<del> libnetwork.JoinOptionHostname("test"),
<del> libnetwork.JoinOptionDomainname("docker.io"))
<add> // Create the sandbox for the container.
<add> // NewSandbox accepts Variadic optional arguments which libnetwork can use.
<add> sbx, err := controller.NewSandbox("container1",
<add> libnetwork.OptionHostname("test"),
<add> libnetwork.OptionDomainname("docker.io"))
<add>
<add> // A sandbox can join the endpoint via the join api.
<add> err = ep.Join(sbx)
<ide> if err != nil {
<ide> return
<ide> } | 2 |
Javascript | Javascript | remove var in libraries/emitter/* | cf70870caa2db3813647a1aab091758a81cab6e0 | <ide><path>Libraries/vendor/emitter/EventValidator.js
<ide> if (__DEV__) {
<ide> }
<ide> };
<ide>
<del> var closestTypeFor = function(type, allowedTypes) {
<add> const closestTypeFor = function(type, allowedTypes) {
<ide> const typeRecommendations = allowedTypes.map(
<ide> typeRecommendationFor.bind(this, type),
<ide> );
<ide> return typeRecommendations.sort(recommendationSort)[0];
<ide> };
<ide>
<del> var typeRecommendationFor = function(type, recommendedType) {
<add> const typeRecommendationFor = function(type, recommendedType) {
<ide> return {
<ide> type: recommendedType,
<ide> distance: damerauLevenshteinDistance(type, recommendedType),
<ide> };
<ide> };
<ide>
<del> var recommendationSort = function(recommendationA, recommendationB) {
<add> const recommendationSort = function(recommendationA, recommendationB) {
<ide> if (recommendationA.distance < recommendationB.distance) {
<ide> return -1;
<ide> } else if (recommendationA.distance > recommendationB.distance) {
<ide> if (__DEV__) {
<ide> }
<ide> };
<ide>
<del> var isCloseEnough = function(closestType, actualType) {
<add> const isCloseEnough = function(closestType, actualType) {
<ide> return closestType.distance / actualType.length < 0.334;
<ide> };
<ide>
<del> var damerauLevenshteinDistance = function(a, b) {
<add> const damerauLevenshteinDistance = function(a, b) {
<ide> let i, j;
<ide> const d = [];
<ide> | 1 |
Text | Text | add esm examples for assert | a8b5cdca352087bc5275cab1e4c31dd3f80d3121 | <ide><path>doc/api/assert.md
<ide> assertion mode, error messages for objects display the objects, often truncated.
<ide>
<ide> To use strict assertion mode:
<ide>
<del>```js
<add>```mjs
<add>import { strict as assert } from 'assert';
<add>```
<add>
<add>```cjs
<ide> const assert = require('assert').strict;
<ide> ```
<del>```js
<add>
<add>```mjs
<add>import assert from 'assert/strict';
<add>```
<add>
<add>```cjs
<ide> const assert = require('assert/strict');
<ide> ```
<ide>
<ide> Example error diff:
<ide>
<del>```js
<del>const assert = require('assert').strict;
<add>```mjs
<add>import { strict as assert } from 'assert';
<add>
<add>assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);
<add>// AssertionError: Expected inputs to be strictly deep-equal:
<add>// + actual - expected ... Lines skipped
<add>//
<add>// [
<add>// [
<add>// ...
<add>// 2,
<add>// + 3
<add>// - '3'
<add>// ],
<add>// ...
<add>// 5
<add>// ]
<add>```
<add>
<add>```cjs
<add>const assert = require('assert/strict');
<ide>
<ide> assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);
<ide> // AssertionError: Expected inputs to be strictly deep-equal:
<ide> Legacy assertion mode uses the [Abstract Equality Comparison][] in:
<ide>
<ide> To use legacy assertion mode:
<ide>
<del>```js
<add>```cjs
<add>import assert from 'assert';
<add>```
<add>
<add>```cjs
<ide> const assert = require('assert');
<ide> ```
<ide>
<ide> Whenever possible, use the [strict assertion mode][] instead. Otherwise, the
<ide> especially true for [`assert.deepEqual()`][], where the comparison rules are
<ide> lax:
<ide>
<del>```js
<add>```cjs
<ide> // WARNING: This does not throw an AssertionError!
<ide> assert.deepEqual(/a/gi, new Date());
<ide> ```
<ide> and:
<ide> assertion error.
<ide> * `operator` {string} Set to the passed in operator value.
<ide>
<del>```js
<add>```mjs
<add>import assert from 'assert';
<add>
<add>// Generate an AssertionError to compare the error message later:
<add>const { message } = new assert.AssertionError({
<add> actual: 1,
<add> expected: 2,
<add> operator: 'strictEqual'
<add>});
<add>
<add>// Verify error output:
<add>try {
<add> assert.strictEqual(1, 2);
<add>} catch (err) {
<add> assert(err instanceof assert.AssertionError);
<add> assert.strictEqual(err.message, message);
<add> assert.strictEqual(err.name, 'AssertionError');
<add> assert.strictEqual(err.actual, 1);
<add> assert.strictEqual(err.expected, 2);
<add> assert.strictEqual(err.code, 'ERR_ASSERTION');
<add> assert.strictEqual(err.operator, 'strictEqual');
<add> assert.strictEqual(err.generatedMessage, true);
<add>}
<add>```
<add>
<add>```cjs
<ide> const assert = require('assert');
<ide>
<ide> // Generate an AssertionError to compare the error message later:
<ide> were called a specific number of times. The `tracker.verify()` must be called
<ide> for the verification to take place. The usual pattern would be to call it in a
<ide> [`process.on('exit')`][] handler.
<ide>
<del>```js
<add>```mjs
<add>import assert from 'assert';
<add>
<add>const tracker = new assert.CallTracker();
<add>
<add>function func() {}
<add>
<add>// callsfunc() must be called exactly 1 time before tracker.verify().
<add>const callsfunc = tracker.calls(func, 1);
<add>
<add>callsfunc();
<add>
<add>// Calls tracker.verify() and verifies if all tracker.calls() functions have
<add>// been called exact times.
<add>process.on('exit', () => {
<add> tracker.verify();
<add>});
<add>```
<add>
<add>```cjs
<ide> const assert = require('assert');
<ide>
<ide> const tracker = new assert.CallTracker();
<ide> function has not been called exactly `exact` times when
<ide> [`tracker.verify()`][] is called, then [`tracker.verify()`][] will throw an
<ide> error.
<ide>
<del>```js
<add>```mjs
<add>import assert from 'assert';
<add>
<add>// Creates call tracker.
<add>const tracker = new assert.CallTracker();
<add>
<add>function func() {}
<add>
<add>// Returns a function that wraps func() that must be called exact times
<add>// before tracker.verify().
<add>const callsfunc = tracker.calls(func);
<add>```
<add>
<add>```cjs
<ide> const assert = require('assert');
<ide>
<ide> // Creates call tracker.
<ide> added:
<ide> The arrays contains information about the expected and actual number of calls of
<ide> the functions that have not been called the expected number of times.
<ide>
<del>```js
<add>```mjs
<add>import assert from 'assert';
<add>
<add>// Creates call tracker.
<add>const tracker = new assert.CallTracker();
<add>
<add>function func() {}
<add>
<add>function foo() {}
<add>
<add>// Returns a function that wraps func() that must be called exact times
<add>// before tracker.verify().
<add>const callsfunc = tracker.calls(func, 2);
<add>
<add>// Returns an array containing information on callsfunc()
<add>tracker.report();
<add>// [
<add>// {
<add>// message: 'Expected the func function to be executed 2 time(s) but was
<add>// executed 0 time(s).',
<add>// actual: 0,
<add>// expected: 2,
<add>// operator: 'func',
<add>// stack: stack trace
<add>// }
<add>// ]
<add>```
<add>
<add>```cjs
<ide> const assert = require('assert');
<ide>
<ide> // Creates call tracker.
<ide> Iterates through the list of functions passed to
<ide> [`tracker.calls()`][] and will throw an error for functions that
<ide> have not been called the expected number of times.
<ide>
<del>```js
<add>```mjs
<add>import assert from 'assert';
<add>
<add>// Creates call tracker.
<add>const tracker = new assert.CallTracker();
<add>
<add>function func() {}
<add>
<add>// Returns a function that wraps func() that must be called exact times
<add>// before tracker.verify().
<add>const callsfunc = tracker.calls(func, 2);
<add>
<add>callsfunc();
<add>
<add>// Will throw an error since callsfunc() was only called once.
<add>tracker.verify();
<add>```
<add>
<add>```cjs
<ide> const assert = require('assert');
<ide>
<ide> // Creates call tracker.
<ide> The following example does not throw an [`AssertionError`][] because the
<ide> primitives are considered equal by the [Abstract Equality Comparison][]
<ide> ( `==` ).
<ide>
<del>```js
<add>```mjs
<add>import assert from 'assert';
<add>// WARNING: This does not throw an AssertionError!
<add>
<add>assert.deepEqual('+00000000', false);
<add>```
<add>
<add>```cjs
<add>const assert = require('assert');
<ide> // WARNING: This does not throw an AssertionError!
<add>
<ide> assert.deepEqual('+00000000', false);
<ide> ```
<ide>
<ide> "Deep" equality means that the enumerable "own" properties of child objects
<ide> are evaluated also:
<ide>
<del>```js
<add>```mjs
<add>import assert from 'assert';
<add>
<add>const obj1 = {
<add> a: {
<add> b: 1
<add> }
<add>};
<add>const obj2 = {
<add> a: {
<add> b: 2
<add> }
<add>};
<add>const obj3 = {
<add> a: {
<add> b: 1
<add> }
<add>};
<add>const obj4 = Object.create(obj1);
<add>
<add>assert.deepEqual(obj1, obj1);
<add>// OK
<add>
<add>// Values of b are different:
<add>assert.deepEqual(obj1, obj2);
<add>// AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } }
<add>
<add>assert.deepEqual(obj1, obj3);
<add>// OK
<add>
<add>// Prototypes are ignored:
<add>assert.deepEqual(obj1, obj4);
<add>// AssertionError: { a: { b: 1 } } deepEqual {}
<add>```
<add>
<add>```cjs
<ide> const assert = require('assert');
<ide>
<ide> const obj1 = {
<ide> are recursively evaluated also by the following rules.
<ide> * [`WeakMap`][] and [`WeakSet`][] comparison does not rely on their values. See
<ide> below for further details.
<ide>
<del>```js
<del>const assert = require('assert').strict;
<add>```mjs
<add>import assert from 'assert/strict';
<add>
<add>// This fails because 1 !== '1'.
<add>deepStrictEqual({ a: 1 }, { a: '1' });
<add>// AssertionError: Expected inputs to be strictly deep-equal:
<add>// + actual - expected
<add>//
<add>// {
<add>// + a: 1
<add>// - a: '1'
<add>// }
<add>
<add>// The following objects don't have own properties
<add>const date = new Date();
<add>const object = {};
<add>const fakeDate = {};
<add>Object.setPrototypeOf(fakeDate, Date.prototype);
<add>
<add>// Different [[Prototype]]:
<add>assert.deepStrictEqual(object, fakeDate);
<add>// AssertionError: Expected inputs to be strictly deep-equal:
<add>// + actual - expected
<add>//
<add>// + {}
<add>// - Date {}
<add>
<add>// Different type tags:
<add>assert.deepStrictEqual(date, fakeDate);
<add>// AssertionError: Expected inputs to be strictly deep-equal:
<add>// + actual - expected
<add>//
<add>// + 2018-04-26T00:49:08.604Z
<add>// - Date {}
<add>
<add>assert.deepStrictEqual(NaN, NaN);
<add>// OK, because of the SameValue comparison
<add>
<add>// Different unwrapped numbers:
<add>assert.deepStrictEqual(new Number(1), new Number(2));
<add>// AssertionError: Expected inputs to be strictly deep-equal:
<add>// + actual - expected
<add>//
<add>// + [Number: 1]
<add>// - [Number: 2]
<add>
<add>assert.deepStrictEqual(new String('foo'), Object('foo'));
<add>// OK because the object and the string are identical when unwrapped.
<add>
<add>assert.deepStrictEqual(-0, -0);
<add>// OK
<add>
<add>// Different zeros using the SameValue Comparison:
<add>assert.deepStrictEqual(0, -0);
<add>// AssertionError: Expected inputs to be strictly deep-equal:
<add>// + actual - expected
<add>//
<add>// + 0
<add>// - -0
<add>
<add>const symbol1 = Symbol();
<add>const symbol2 = Symbol();
<add>assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol1]: 1 });
<add>// OK, because it is the same symbol on both objects.
<add>
<add>assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol2]: 1 });
<add>// AssertionError [ERR_ASSERTION]: Inputs identical but not reference equal:
<add>//
<add>// {
<add>// [Symbol()]: 1
<add>// }
<add>
<add>const weakMap1 = new WeakMap();
<add>const weakMap2 = new WeakMap([[{}, {}]]);
<add>const weakMap3 = new WeakMap();
<add>weakMap3.unequal = true;
<add>
<add>assert.deepStrictEqual(weakMap1, weakMap2);
<add>// OK, because it is impossible to compare the entries
<add>
<add>// Fails because weakMap3 has a property that weakMap1 does not contain:
<add>assert.deepStrictEqual(weakMap1, weakMap3);
<add>// AssertionError: Expected inputs to be strictly deep-equal:
<add>// + actual - expected
<add>//
<add>// WeakMap {
<add>// + [items unknown]
<add>// - [items unknown],
<add>// - unequal: true
<add>// }
<add>```
<add>
<add>```cjs
<add>const assert = require('assert/strict');
<ide>
<ide> // This fails because 1 !== '1'.
<ide> assert.deepStrictEqual({ a: 1 }, { a: '1' });
<ide> Expects the `string` input not to match the regular expression.
<ide> This feature is currently experimental and the name might change or it might be
<ide> completely removed again.
<ide>
<del>```js
<del>const assert = require('assert').strict;
<add>```mjs
<add>import assert from 'assert/strict';
<ide>
<ide> assert.doesNotMatch('I will fail', /fail/);
<ide> // AssertionError [ERR_ASSERTION]: The input was expected to not match the ...
<ide> assert.doesNotMatch('I will pass', /different/);
<ide> // OK
<ide> ```
<ide>
<del>If the values do match, or if the `string` argument is of another type than
<del>`string`, an [`AssertionError`][] is thrown with a `message` property set equal
<del>to the value of the `message` parameter. If the `message` parameter is
<del>undefined, a default error message is assigned. If the `message` parameter is an
<del>instance of an [`Error`][] then it will be thrown instead of the
<add>```cjs
<add>const assert = require('assert/strict');
<add>
<add>assert.doesNotMatch('I will fail', /fail/);
<add>// AssertionError [ERR_ASSERTION]: The input was expected to not match the ...
<add>
<add>assert.doesNotMatch(123, /pass/);
<add>// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.
<add>
<add>assert.doesNotMatch('I will pass', /different/);
<add>// OK
<add>```
<add>
<add>If the values do match, or if the `string` argument is of another type than
<add>`string`, an [`AssertionError`][] is thrown with a `message` property set equal
<add>to the value of the `message` parameter. If the `message` parameter is
<add>undefined, a default error message is assigned. If the `message` parameter is an
<add>instance of an [`Error`][] then it will be thrown instead of the
<ide> [`AssertionError`][].
<ide>
<ide> ## `assert.doesNotReject(asyncFn[, error][, message])`
<ide> Besides the async nature to await the completion behaves identically to
<ide> [`assert.doesNotThrow()`][].
<ide>
<ide> <!-- eslint-disable no-restricted-syntax -->
<del>```js
<add>```mjs
<add>import assert from 'assert/strict';
<add>
<add>await assert.doesNotReject(
<add> async () => {
<add> throw new TypeError('Wrong value');
<add> },
<add> SyntaxError
<add>);
<add>```
<add>
<add>```cjs
<add>const assert = require('assert/strict');
<add>
<ide> (async () => {
<ide> await assert.doesNotReject(
<ide> async () => {
<ide> Besides the async nature to await the completion behaves identically to
<ide> ```
<ide>
<ide> <!-- eslint-disable no-restricted-syntax -->
<del>```js
<add>```mjs
<add>import assert from 'assert/strict';
<add>
<add>assert.doesNotReject(Promise.reject(new TypeError('Wrong value')))
<add> .then(() => {
<add> // ...
<add> });
<add>```
<add>
<add><!-- eslint-disable no-restricted-syntax -->
<add>```cjs
<add>const assert = require('assert/strict');
<add>
<ide> assert.doesNotReject(Promise.reject(new TypeError('Wrong value')))
<ide> .then(() => {
<ide> // ...
<ide> The following, for instance, will throw the [`TypeError`][] because there is no
<ide> matching error type in the assertion:
<ide>
<ide> <!-- eslint-disable no-restricted-syntax -->
<del>```js
<add>```mjs
<add>import assert from 'assert/strict';
<add>
<add>assert.doesNotThrow(
<add> () => {
<add> throw new TypeError('Wrong value');
<add> },
<add> SyntaxError
<add>);
<add>```
<add>
<add><!-- eslint-disable no-restricted-syntax -->
<add>```cjs
<add>const assert = require('assert/strict');
<add>
<ide> assert.doesNotThrow(
<ide> () => {
<ide> throw new TypeError('Wrong value');
<ide> However, the following will result in an [`AssertionError`][] with the message
<ide> 'Got unwanted exception...':
<ide>
<ide> <!-- eslint-disable no-restricted-syntax -->
<del>```js
<add>```mjs
<add>import assert from 'assert/strict';
<add>
<add>assert.doesNotThrow(
<add> () => {
<add> throw new TypeError('Wrong value');
<add> },
<add> TypeError
<add>);
<add>```
<add>
<add><!-- eslint-disable no-restricted-syntax -->
<add>```cjs
<add>const assert = require('assert/strict');
<add>
<ide> assert.doesNotThrow(
<ide> () => {
<ide> throw new TypeError('Wrong value');
<ide> parameter, the value of `message` will be appended to the [`AssertionError`][]
<ide> message:
<ide>
<ide> <!-- eslint-disable no-restricted-syntax -->
<del>```js
<add>```mjs
<add>import assert from 'assert/strict';
<add>
<add>assert.doesNotThrow(
<add> () => {
<add> throw new TypeError('Wrong value');
<add> },
<add> /Wrong value/,
<add> 'Whoops'
<add>);
<add>// Throws: AssertionError: Got unwanted exception: Whoops
<add>```
<add>
<add><!-- eslint-disable no-restricted-syntax -->
<add>```cjs
<add>const assert = require('assert/strict');
<add>
<ide> assert.doesNotThrow(
<ide> () => {
<ide> throw new TypeError('Wrong value');
<ide> Tests shallow, coercive equality between the `actual` and `expected` parameters
<ide> using the [Abstract Equality Comparison][] ( `==` ). `NaN` is special handled
<ide> and treated as being identical in case both sides are `NaN`.
<ide>
<del>```js
<add>```mjs
<add>import assert from 'assert';
<add>
<add>assert.equal(1, 1);
<add>// OK, 1 == 1
<add>assert.equal(1, '1');
<add>// OK, 1 == '1'
<add>assert.equal(NaN, NaN);
<add>// OK
<add>
<add>assert.equal(1, 2);
<add>// AssertionError: 1 == 2
<add>assert.equal({ a: { b: 1 } }, { a: { b: 1 } });
<add>// AssertionError: { a: { b: 1 } } == { a: { b: 1 } }
<add>```
<add>
<add>```cjs
<ide> const assert = require('assert');
<ide>
<ide> assert.equal(1, 1);
<ide> Throws an [`AssertionError`][] with the provided error message or a default
<ide> error message. If the `message` parameter is an instance of an [`Error`][] then
<ide> it will be thrown instead of the [`AssertionError`][].
<ide>
<del>```js
<del>const assert = require('assert').strict;
<add>```mjs
<add>import assert from 'assert/strict';
<add>
<add>assert.fail();
<add>// AssertionError [ERR_ASSERTION]: Failed
<add>
<add>assert.fail('boom');
<add>// AssertionError [ERR_ASSERTION]: boom
<add>
<add>assert.fail(new TypeError('need array'));
<add>// TypeError: need array
<add>```
<add>
<add>```cjs
<add>const assert = require('assert/strict');
<ide>
<ide> assert.fail();
<ide> // AssertionError [ERR_ASSERTION]: Failed
<ide> the other arguments will be stored as properties on the thrown object. If
<ide> removed from stacktrace (see [`Error.captureStackTrace`][]). If no arguments are
<ide> given, the default message `Failed` will be used.
<ide>
<del>```js
<del>const assert = require('assert').strict;
<add>```mjs
<add>import assert from 'assert/strict';
<add>
<add>assert.fail('a', 'b');
<add>// AssertionError [ERR_ASSERTION]: 'a' != 'b'
<add>
<add>assert.fail(1, 2, undefined, '>');
<add>// AssertionError [ERR_ASSERTION]: 1 > 2
<add>
<add>assert.fail(1, 2, 'fail');
<add>// AssertionError [ERR_ASSERTION]: fail
<add>
<add>assert.fail(1, 2, 'whoops', '>');
<add>// AssertionError [ERR_ASSERTION]: whoops
<add>
<add>assert.fail(1, 2, new TypeError('need array'));
<add>// TypeError: need array
<add>```
<add>
<add>```cjs
<add>const assert = require('assert/strict');
<ide>
<ide> assert.fail('a', 'b');
<ide> // AssertionError [ERR_ASSERTION]: 'a' != 'b'
<ide> influence on the error message.
<ide>
<ide> Example use of `stackStartFn` for truncating the exception's stacktrace:
<ide>
<del>```js
<add>```mjs
<add>import assert from 'assert/strict';
<add>
<add>function suppressFrame() {
<add> assert.fail('a', 'b', undefined, '!==', suppressFrame);
<add>}
<add>suppressFrame();
<add>// AssertionError [ERR_ASSERTION]: 'a' !== 'b'
<add>// at repl:1:1
<add>// at ContextifyScript.Script.runInThisContext (vm.js:44:33)
<add>// ...
<add>```
<add>
<add>```cjs
<add>const assert = require('assert/strict');
<add>
<ide> function suppressFrame() {
<ide> assert.fail('a', 'b', undefined, '!==', suppressFrame);
<ide> }
<ide> testing the `error` argument in callbacks. The stack trace contains all frames
<ide> from the error passed to `ifError()` including the potential new frames for
<ide> `ifError()` itself.
<ide>
<del>```js
<del>const assert = require('assert').strict;
<add>```mjs
<add>import assert from 'assert/strict';
<add>
<add>assert.ifError(null);
<add>// OK
<add>assert.ifError(0);
<add>// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0
<add>assert.ifError('error');
<add>// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error'
<add>assert.ifError(new Error());
<add>// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error
<add>
<add>// Create some random error frames.
<add>let err;
<add>(function errorFrame() {
<add> err = new Error('test error');
<add>})();
<add>
<add>(function ifErrorFrame() {
<add> assert.ifError(err);
<add>})();
<add>// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error
<add>// at ifErrorFrame
<add>// at errorFrame
<add>```
<add>
<add>```cjs
<add>const assert = require('assert/strict');
<ide>
<ide> assert.ifError(null);
<ide> // OK
<ide> Expects the `string` input to match the regular expression.
<ide> This feature is currently experimental and the name might change or it might be
<ide> completely removed again.
<ide>
<del>```js
<del>const assert = require('assert').strict;
<add>```mjs
<add>import assert from 'assert/strict';
<add>
<add>assert.match('I will fail', /pass/);
<add>// AssertionError [ERR_ASSERTION]: The input did not match the regular ...
<add>
<add>assert.match(123, /pass/);
<add>// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.
<add>
<add>assert.match('I will pass', /pass/);
<add>// OK
<add>```
<add>
<add>```cjs
<add>const assert = require('assert/strict');
<ide>
<ide> assert.match('I will fail', /pass/);
<ide> // AssertionError [ERR_ASSERTION]: The input did not match the regular ...
<ide> An alias of [`assert.notDeepStrictEqual()`][].
<ide>
<ide> Tests for any deep inequality. Opposite of [`assert.deepEqual()`][].
<ide>
<del>```js
<add>```mjs
<add>import assert from 'assert';
<add>
<add>const obj1 = {
<add> a: {
<add> b: 1
<add> }
<add>};
<add>const obj2 = {
<add> a: {
<add> b: 2
<add> }
<add>};
<add>const obj3 = {
<add> a: {
<add> b: 1
<add> }
<add>};
<add>const obj4 = Object.create(obj1);
<add>
<add>assert.notDeepEqual(obj1, obj1);
<add>// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
<add>
<add>assert.notDeepEqual(obj1, obj2);
<add>// OK
<add>
<add>assert.notDeepEqual(obj1, obj3);
<add>// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
<add>
<add>assert.notDeepEqual(obj1, obj4);
<add>// OK
<add>```
<add>
<add>```cjs
<ide> const assert = require('assert');
<ide>
<ide> const obj1 = {
<ide> changes:
<ide>
<ide> Tests for deep strict inequality. Opposite of [`assert.deepStrictEqual()`][].
<ide>
<del>```js
<del>const assert = require('assert').strict;
<add>```mjs
<add>import assert from 'assert/strict';
<add>
<add>assert.notDeepStrictEqual({ a: 1 }, { a: '1' });
<add>// OK
<add>```
<add>
<add>```cjs
<add>const assert = require('assert/strict');
<ide>
<ide> assert.notDeepStrictEqual({ a: 1 }, { a: '1' });
<ide> // OK
<ide> Tests shallow, coercive inequality with the [Abstract Equality Comparison][]
<ide> (`!=` ). `NaN` is special handled and treated as being identical in case both
<ide> sides are `NaN`.
<ide>
<del>```js
<add>```mjs
<add>import assert from 'assert';
<add>
<add>assert.notEqual(1, 2);
<add>// OK
<add>
<add>assert.notEqual(1, 1);
<add>// AssertionError: 1 != 1
<add>
<add>assert.notEqual(1, '1');
<add>// AssertionError: 1 != '1'
<add>```
<add>
<add>```cjs
<ide> const assert = require('assert');
<ide>
<ide> assert.notEqual(1, 2);
<ide> changes:
<ide> Tests strict inequality between the `actual` and `expected` parameters as
<ide> determined by the [SameValue Comparison][].
<ide>
<del>```js
<del>const assert = require('assert').strict;
<add>```mjs
<add>import assert from 'assert/strict';
<add>
<add>assert.notStrictEqual(1, 2);
<add>// OK
<add>
<add>assert.notStrictEqual(1, 1);
<add>// AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to:
<add>//
<add>// 1
<add>
<add>assert.notStrictEqual(1, '1');
<add>// OK
<add>```
<add>
<add>```cjs
<add>const assert = require('assert/strict');
<ide>
<ide> assert.notStrictEqual(1, 2);
<ide> // OK
<ide> If no arguments are passed in at all `message` will be set to the string:
<ide> Be aware that in the `repl` the error message will be different to the one
<ide> thrown in a file! See below for further details.
<ide>
<del>```js
<del>const assert = require('assert').strict;
<add>```mjs
<add>import assert from 'assert/strict';
<ide>
<ide> assert.ok(true);
<ide> // OK
<ide> assert.ok(0);
<ide> // AssertionError: The expression evaluated to a falsy value:
<ide> //
<ide> // assert.ok(0)
<add>```
<add>
<add>```cjs
<add>const assert = require('assert/strict');
<add>
<add>assert.ok(true);
<add>// OK
<add>assert.ok(1);
<add>// OK
<add>
<add>assert.ok();
<add>// AssertionError: No value argument passed to `assert.ok()`
<add>
<add>assert.ok(false, 'it\'s false');
<add>// AssertionError: it's false
<add>
<add>// In the repl:
<add>assert.ok(typeof 123 === 'string');
<add>// AssertionError: false == true
<add>
<add>// In a file (e.g. test.js):
<add>assert.ok(typeof 123 === 'string');
<add>// AssertionError: The expression evaluated to a falsy value:
<add>//
<add>// assert.ok(typeof 123 === 'string')
<add>
<add>assert.ok(false);
<add>// AssertionError: The expression evaluated to a falsy value:
<add>//
<add>// assert.ok(false)
<add>
<add>assert.ok(0);
<add>// AssertionError: The expression evaluated to a falsy value:
<add>//
<add>// assert.ok(0)
<add>```
<add>
<add>```mjs
<add>import assert from 'assert/strict';
<add>
<add>// Using `assert()` works the same:
<add>assert(0);
<add>// AssertionError: The expression evaluated to a falsy value:
<add>//
<add>// assert(0)
<add>```
<add>
<add>```cjs
<add>const assert = require('assert');
<ide>
<ide> // Using `assert()` works the same:
<ide> assert(0);
<ide> each property will be tested for including the non-enumerable `message` and
<ide> If specified, `message` will be the message provided by the [`AssertionError`][]
<ide> if the `asyncFn` fails to reject.
<ide>
<del>```js
<add>```mjs
<add>import assert from 'assert/strict';
<add>
<add>await assert.rejects(
<add> async () => {
<add> throw new TypeError('Wrong value');
<add> },
<add> {
<add> name: 'TypeError',
<add> message: 'Wrong value'
<add> }
<add>);
<add>```
<add>
<add>```cjs
<add>const assert = require('assert/strict');
<add>
<ide> (async () => {
<ide> await assert.rejects(
<ide> async () => {
<ide> if the `asyncFn` fails to reject.
<ide> })();
<ide> ```
<ide>
<del>```js
<add>```mjs
<add>import assert from 'assert/strict';
<add>
<add>await assert.rejects(
<add> async () => {
<add> throw new TypeError('Wrong value');
<add> },
<add> (err) => {
<add> assert.strictEqual(err.name, 'TypeError');
<add> assert.strictEqual(err.message, 'Wrong value');
<add> return true;
<add> }
<add>);
<add>```
<add>
<add>```cjs
<add>const assert = require('assert/strict');
<add>
<ide> (async () => {
<ide> await assert.rejects(
<ide> async () => {
<ide> if the `asyncFn` fails to reject.
<ide> })();
<ide> ```
<ide>
<del>```js
<add>```mjs
<add>import assert from 'assert/strict';
<add>
<add>assert.rejects(
<add> Promise.reject(new Error('Wrong value')),
<add> Error
<add>).then(() => {
<add> // ...
<add>});
<add>```
<add>
<add>```cjs
<add>const asssert = require('assert/strict');
<add>
<ide> assert.rejects(
<ide> Promise.reject(new Error('Wrong value')),
<ide> Error
<ide> changes:
<ide> Tests strict equality between the `actual` and `expected` parameters as
<ide> determined by the [SameValue Comparison][].
<ide>
<del>```js
<del>const assert = require('assert').strict;
<add>```mjs
<add>import assert from 'assert/strict';
<add>
<add>assert.strictEqual(1, 2);
<add>// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
<add>//
<add>// 1 !== 2
<add>
<add>assert.strictEqual(1, 1);
<add>// OK
<add>
<add>assert.strictEqual('Hello foobar', 'Hello World!');
<add>// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
<add>// + actual - expected
<add>//
<add>// + 'Hello foobar'
<add>// - 'Hello World!'
<add>// ^
<add>
<add>const apples = 1;
<add>const oranges = 2;
<add>assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`);
<add>// AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2
<add>
<add>assert.strictEqual(1, '1', new TypeError('Inputs are not identical'));
<add>// TypeError: Inputs are not identical
<add>```
<add>
<add>```cjs
<add>const assert = require('assert/strict');
<ide>
<ide> assert.strictEqual(1, 2);
<ide> // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
<ide> fails.
<ide>
<ide> Custom validation object/error instance:
<ide>
<del>```js
<add>```mjs
<add>import assert from 'assert/strict';
<add>
<ide> const err = new TypeError('Wrong value');
<ide> err.code = 404;
<ide> err.foo = 'bar';
<ide> assert.throws(
<ide> );
<ide>
<ide> // Using regular expressions to validate error properties:
<del>assert.throws(
<add>throws(
<ide> () => {
<ide> throw err;
<ide> },
<ide> assert.throws(
<ide> );
<ide>
<ide> // Fails due to the different `message` and `name` properties:
<add>throws(
<add> () => {
<add> const otherErr = new Error('Not found');
<add> // Copy all enumerable properties from `err` to `otherErr`.
<add> for (const [key, value] of Object.entries(err)) {
<add> otherErr[key] = value;
<add> }
<add> throw otherErr;
<add> },
<add> // The error's `message` and `name` properties will also be checked when using
<add> // an error as validation object.
<add> err
<add>);
<add>```
<add>
<add>```cjs
<add>const assert = require('assert/strict');
<add>
<add>const err = new TypeError('Wrong value');
<add>err.code = 404;
<add>err.foo = 'bar';
<add>err.info = {
<add> nested: true,
<add> baz: 'text'
<add>};
<add>err.reg = /abc/i;
<add>
<ide> assert.throws(
<add> () => {
<add> throw err;
<add> },
<add> {
<add> name: 'TypeError',
<add> message: 'Wrong value',
<add> info: {
<add> nested: true,
<add> baz: 'text'
<add> }
<add> // Only properties on the validation object will be tested for.
<add> // Using nested objects requires all properties to be present. Otherwise
<add> // the validation is going to fail.
<add> }
<add>);
<add>
<add>// Using regular expressions to validate error properties:
<add>throws(
<add> () => {
<add> throw err;
<add> },
<add> {
<add> // The `name` and `message` properties are strings and using regular
<add> // expressions on those will match against the string. If they fail, an
<add> // error is thrown.
<add> name: /^TypeError$/,
<add> message: /Wrong/,
<add> foo: 'bar',
<add> info: {
<add> nested: true,
<add> // It is not possible to use regular expressions for nested properties!
<add> baz: 'text'
<add> },
<add> // The `reg` property contains a regular expression and only if the
<add> // validation object contains an identical regular expression, it is going
<add> // to pass.
<add> reg: /abc/i
<add> }
<add>);
<add>
<add>// Fails due to the different `message` and `name` properties:
<add>throws(
<ide> () => {
<ide> const otherErr = new Error('Not found');
<ide> // Copy all enumerable properties from `err` to `otherErr`.
<ide> assert.throws(
<ide>
<ide> Validate instanceof using constructor:
<ide>
<del>```js
<add>```mjs
<add>import assert from 'assert/strict';
<add>
<add>assert.throws(
<add> () => {
<add> throw new Error('Wrong value');
<add> },
<add> Error
<add>);
<add>```
<add>
<add>```cjs
<add>const assert = require('assert/strict');
<add>
<ide> assert.throws(
<ide> () => {
<ide> throw new Error('Wrong value');
<ide> Validate error message using [`RegExp`][]:
<ide> Using a regular expression runs `.toString` on the error object, and will
<ide> therefore also include the error name.
<ide>
<del>```js
<add>```mjs
<add>import assert from 'assert/strict';
<add>
<add>assert.throws(
<add> () => {
<add> throw new Error('Wrong value');
<add> },
<add> /^Error: Wrong value$/
<add>);
<add>```
<add>
<add>```cjs
<add>const assert = require('assert/strict');
<add>
<ide> assert.throws(
<ide> () => {
<ide> throw new Error('Wrong value');
<ide> Custom error validation:
<ide> The function must return `true` to indicate all internal validations passed.
<ide> It will otherwise fail with an [`AssertionError`][].
<ide>
<del>```js
<add>```mjs
<add>import assert from 'assert/strict';
<add>
<add>assert.throws(
<add> () => {
<add> throw new Error('Wrong value');
<add> },
<add> (err) => {
<add> assert(err instanceof Error);
<add> assert(/value/.test(err));
<add> // Avoid returning anything from validation functions besides `true`.
<add> // Otherwise, it's not clear what part of the validation failed. Instead,
<add> // throw an error about the specific validation that failed (as done in this
<add> // example) and add as much helpful debugging information to that error as
<add> // possible.
<add> return true;
<add> },
<add> 'unexpected error'
<add>);
<add>```
<add>
<add>```cjs
<add>const assert = require('assert/strict');
<add>
<ide> assert.throws(
<ide> () => {
<ide> throw new Error('Wrong value');
<ide> message as the thrown error message is going to result in an
<ide> a string as the second argument gets considered:
<ide>
<ide> <!-- eslint-disable no-restricted-syntax -->
<del>```js
<add>```mjs
<add>import assert from 'assert/strict';
<add>
<add>function throwingFirst() {
<add> throw new Error('First');
<add>}
<add>
<add>function throwingSecond() {
<add> throw new Error('Second');
<add>}
<add>
<add>function notThrowing() {}
<add>
<add>// The second argument is a string and the input function threw an Error.
<add>// The first case will not throw as it does not match for the error message
<add>// thrown by the input function!
<add>assert.throws(throwingFirst, 'Second');
<add>// In the next example the message has no benefit over the message from the
<add>// error and since it is not clear if the user intended to actually match
<add>// against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error.
<add>assert.throws(throwingSecond, 'Second');
<add>// TypeError [ERR_AMBIGUOUS_ARGUMENT]
<add>
<add>// The string is only used (as message) in case the function does not throw:
<add>assert.throws(notThrowing, 'Second');
<add>// AssertionError [ERR_ASSERTION]: Missing expected exception: Second
<add>
<add>// If it was intended to match for the error message do this instead:
<add>// It does not throw because the error messages match.
<add>assert.throws(throwingSecond, /Second$/);
<add>
<add>// If the error message does not match, an AssertionError is thrown.
<add>assert.throws(throwingFirst, /Second$/);
<add>// AssertionError [ERR_ASSERTION]
<add>```
<add>
<add><!-- eslint-disable no-restricted-syntax -->
<add>```cjs
<add>const assert = require('assert/strict');
<add>
<ide> function throwingFirst() {
<ide> throw new Error('First');
<ide> } | 1 |
Mixed | Python | add type hints for "strings" folder | 000cedc07f1065282acd7e25add4d2847fe08391 | <ide><path>DIRECTORY.md
<ide> * Problem 12
<ide> * [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_12/sol1.py)
<ide> * [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_12/sol2.py)
<add> * Problem 120
<add> * [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_120/sol1.py)
<ide> * Problem 13
<ide> * [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_13/sol1.py)
<ide> * Problem 14
<ide> * Problem 29
<ide> * [Solution](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_29/solution.py)
<ide> * Problem 30
<del> * [Soln](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_30/soln.py)
<add> * [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_30/sol1.py)
<ide> * Problem 31
<ide> * [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_31/sol1.py)
<ide> * [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_31/sol2.py)
<ide><path>strings/aho_corasick.py
<ide> from collections import deque
<add>from typing import Dict, List, Union
<ide>
<ide>
<ide> class Automaton:
<del> def __init__(self, keywords):
<add> def __init__(self, keywords: List[str]):
<ide> self.adlist = list()
<ide> self.adlist.append(
<ide> {"value": "", "next_states": [], "fail_state": 0, "output": []}
<ide> def __init__(self, keywords):
<ide> self.add_keyword(keyword)
<ide> self.set_fail_transitions()
<ide>
<del> def find_next_state(self, current_state, char):
<add> def find_next_state(self, current_state: int, char: str) -> Union[int, None]:
<ide> for state in self.adlist[current_state]["next_states"]:
<ide> if char == self.adlist[state]["value"]:
<ide> return state
<ide> return None
<ide>
<del> def add_keyword(self, keyword):
<add> def add_keyword(self, keyword: str) -> None:
<ide> current_state = 0
<ide> for character in keyword:
<ide> if self.find_next_state(current_state, character):
<ide> def add_keyword(self, keyword):
<ide> current_state = len(self.adlist) - 1
<ide> self.adlist[current_state]["output"].append(keyword)
<ide>
<del> def set_fail_transitions(self):
<add> def set_fail_transitions(self) -> None:
<ide> q = deque()
<ide> for node in self.adlist[0]["next_states"]:
<ide> q.append(node)
<ide> def set_fail_transitions(self):
<ide> + self.adlist[self.adlist[child]["fail_state"]]["output"]
<ide> )
<ide>
<del> def search_in(self, string):
<add> def search_in(self, string: str) -> Dict[str, List[int]]:
<ide> """
<ide> >>> A = Automaton(["what", "hat", "ver", "er"])
<ide> >>> A.search_in("whatever, err ... , wherever")
<ide><path>strings/boyer_moore_search.py
<ide> n=length of main string
<ide> m=length of pattern string
<ide> """
<add>from typing import List
<ide>
<ide>
<ide> class BoyerMooreSearch:
<del> def __init__(self, text, pattern):
<add> def __init__(self, text: str, pattern: str):
<ide> self.text, self.pattern = text, pattern
<ide> self.textLen, self.patLen = len(text), len(pattern)
<ide>
<del> def match_in_pattern(self, char):
<add> def match_in_pattern(self, char: str) -> int:
<ide> """finds the index of char in pattern in reverse order
<ide>
<ide> Parameters :
<ide> def match_in_pattern(self, char):
<ide> return i
<ide> return -1
<ide>
<del> def mismatch_in_text(self, currentPos):
<add> def mismatch_in_text(self, currentPos: int) -> int:
<ide> """
<ide> find the index of mis-matched character in text when compared with pattern
<ide> from last
<ide> def mismatch_in_text(self, currentPos):
<ide> return currentPos + i
<ide> return -1
<ide>
<del> def bad_character_heuristic(self):
<add> def bad_character_heuristic(self) -> List[int]:
<ide> # searches pattern in text and returns index positions
<ide> positions = []
<ide> for i in range(self.textLen - self.patLen + 1):
<ide><path>strings/knuth_morris_pratt.py
<del>def kmp(pattern, text):
<add>from typing import List
<add>
<add>
<add>def kmp(pattern: str, text: str) -> bool:
<ide> """
<ide> The Knuth-Morris-Pratt Algorithm for finding a pattern within a piece of text
<ide> with complexity O(n + m)
<ide> def kmp(pattern, text):
<ide> return False
<ide>
<ide>
<del>def get_failure_array(pattern):
<add>def get_failure_array(pattern: str) -> List[int]:
<ide> """
<ide> Calculates the new index we should go to if we fail a comparison
<ide> :param pattern:
<ide><path>strings/levenshtein_distance.py
<ide> """
<ide>
<ide>
<del>def levenshtein_distance(first_word, second_word):
<add>def levenshtein_distance(first_word: str, second_word: str) -> int:
<ide> """Implementation of the levenshtein distance in Python.
<ide> :param first_word: the first word to measure the difference.
<ide> :param second_word: the second word to measure the difference.
<ide><path>strings/manacher.py
<del>def palindromic_string(input_string):
<add>def palindromic_string(input_string: str) -> str:
<ide> """
<ide> >>> palindromic_string('abbbaba')
<ide> 'abbba'
<ide><path>strings/rabin_karp.py
<ide> modulus = 1000003
<ide>
<ide>
<del>def rabin_karp(pattern, text):
<add>def rabin_karp(pattern: str, text: str) -> bool:
<ide> """
<ide> The Rabin-Karp Algorithm for finding a pattern within a piece of text
<ide> with complexity O(nm), most efficient when it is used with multiple patterns
<ide> def rabin_karp(pattern, text):
<ide> return False
<ide>
<ide>
<del>def test_rabin_karp():
<add>def test_rabin_karp() -> None:
<ide> """
<ide> >>> test_rabin_karp()
<ide> Success. | 7 |
Python | Python | fix fmin examples | e3bca2cf026ae16926ef58d71b33afa2981c33c6 | <ide><path>numpy/core/code_generators/ufunc_docstrings.py
<ide> def add_newdoc(place, name, doc):
<ide> Examples
<ide> --------
<ide> >>> np.fmin([2, 3, 4], [1, 5, 2])
<del> array([2, 5, 4])
<add> array([1, 3, 2])
<ide>
<ide> >>> np.fmin(np.eye(2), [0.5, 2])
<del> array([[ 1. , 2. ],
<del> [ 0.5, 2. ]])
<add> array([[ 0.5, 0. ],
<add> [ 0. , 1. ]])
<ide>
<ide> >>> np.fmin([np.nan, 0, np.nan],[0, np.nan, np.nan])
<ide> array([ 0., 0., NaN]) | 1 |
Python | Python | fix pavement.py write_release_task | 375e90dccd32bf5d4308766d635d35734c627e76 | <ide><path>pavement.py
<ide> def write_release_task(options, filename='NOTES.txt'):
<ide> ~~~
<ide>
<ide> """)
<del> ftarget.writelines(['%s\n' % c for c in compute_md5(idirs)])
<del> ftarget.writelines("""
<add> ftarget.writelines(['%s\n' % c for c in compute_md5(idirs)])
<add> ftarget.writelines("""
<ide> SHA256
<ide> ~~~~~~
<ide>
<ide> """)
<del> ftarget.writelines(['%s\n' % c for c in compute_sha256(idirs)])
<add> ftarget.writelines(['%s\n' % c for c in compute_sha256(idirs)])
<ide>
<ide> # Sign release
<ide> cmd = ['gpg', '--clearsign', '--armor'] | 1 |
PHP | PHP | fix cs errors | 46c2b9e1f57433ecb4a8b605473ad3695549ff95 | <ide><path>src/Collection/CollectionInterface.php
<ide> public function each(callable $c);
<ide> * @param callable|null $c the method that will receive each of the elements and
<ide> * returns true whether or not they should be in the resulting collection.
<ide> * If left null, a callback that filters out falsey values will be used.
<del> * @return \Cake\Collection\CollectionInterface
<add> * @return self
<ide> */
<ide> public function filter(?callable $c = null): CollectionInterface;
<ide>
<ide> public function filter(?callable $c = null): CollectionInterface;
<ide> *
<ide> * @param callable $c the method that will receive each of the elements and
<ide> * returns true whether or not they should be out of the resulting collection.
<del> * @return \Cake\Collection\CollectionInterface
<add> * @return self
<ide> */
<ide> public function reject(callable $c): CollectionInterface;
<ide>
<ide> public function contains($value): bool;
<ide> *
<ide> * @param callable $c the method that will receive each of the elements and
<ide> * returns the new value for the key that is being iterated
<del> * @return \Cake\Collection\CollectionInterface
<add> * @return self
<ide> */
<ide> public function map(callable $c): CollectionInterface;
<ide>
<ide> public function reduce(callable $c, $zero = null);
<ide> * @param string|callable $matcher A dot separated path of column to follow
<ide> * so that the final one can be returned or a callable that will take care
<ide> * of doing that.
<del> * @return \Cake\Collection\CollectionInterface
<add> * @return self
<ide> */
<ide> public function extract($matcher): CollectionInterface;
<ide>
<ide> public function median($matcher = null);
<ide> * @param int $dir either SORT_DESC or SORT_ASC
<ide> * @param int $type the type of comparison to perform, either SORT_STRING
<ide> * SORT_NUMERIC or SORT_NATURAL
<del> * @return \Cake\Collection\CollectionInterface
<add> * @return self
<ide> */
<ide> public function sortBy($callback, int $dir = SORT_DESC, int $type = \SORT_NUMERIC): CollectionInterface;
<ide>
<ide> public function sortBy($callback, int $dir = SORT_DESC, int $type = \SORT_NUMERI
<ide> *
<ide> * @param callable|string $callback the callback or column name to use for grouping
<ide> * or a function returning the grouping key out of the provided element
<del> * @return \Cake\Collection\CollectionInterface
<add> * @return self
<ide> */
<ide> public function groupBy($callback): CollectionInterface;
<ide>
<ide> public function groupBy($callback): CollectionInterface;
<ide> *
<ide> * @param callable|string $callback the callback or column name to use for indexing
<ide> * or a function returning the indexing key out of the provided element
<del> * @return \Cake\Collection\CollectionInterface
<add> * @return self
<ide> */
<ide> public function indexBy($callback): CollectionInterface;
<ide>
<ide> public function indexBy($callback): CollectionInterface;
<ide> *
<ide> * @param callable|string $callback the callback or column name to use for indexing
<ide> * or a function returning the indexing key out of the provided element
<del> * @return \Cake\Collection\CollectionInterface
<add> * @return self
<ide> */
<ide> public function countBy($callback): CollectionInterface;
<ide>
<ide> public function sumOf($matcher = null);
<ide> * Returns a new collection with the elements placed in a random order,
<ide> * this function does not preserve the original keys in the collection.
<ide> *
<del> * @return \Cake\Collection\CollectionInterface
<add> * @return self
<ide> */
<ide> public function shuffle(): CollectionInterface;
<ide>
<ide> public function shuffle(): CollectionInterface;
<ide> *
<ide> * @param int $size the maximum number of elements to randomly
<ide> * take from this collection
<del> * @return \Cake\Collection\CollectionInterface
<add> * @return self
<ide> */
<ide> public function sample(int $size = 10): CollectionInterface;
<ide>
<ide> public function sample(int $size = 10): CollectionInterface;
<ide> * @param int $size the maximum number of elements to take from
<ide> * this collection
<ide> * @param int $from A positional offset from where to take the elements
<del> * @return \Cake\Collection\CollectionInterface
<add> * @return self
<ide> */
<ide> public function take(int $size = 1, int $from = 0): CollectionInterface;
<ide>
<ide> public function take(int $size = 1, int $from = 0): CollectionInterface;
<ide> * ```
<ide> *
<ide> * @param int $howMany The number of elements at the end of the collection
<del> * @return \Cake\Collection\CollectionInterface
<add> * @return self
<ide> */
<ide> public function takeLast(int $howMany): CollectionInterface;
<ide>
<ide> public function takeLast(int $howMany): CollectionInterface;
<ide> * at the beginning of the iteration.
<ide> *
<ide> * @param int $howMany The number of elements to skip.
<del> * @return \Cake\Collection\CollectionInterface
<add> * @return self
<ide> */
<ide> public function skip(int $howMany): CollectionInterface;
<ide>
<ide> public function skip(int $howMany): CollectionInterface;
<ide> * @param array $conditions a key-value list of conditions where
<ide> * the key is a property path as accepted by `Collection::extract,
<ide> * and the value the condition against with each element will be matched
<del> * @return \Cake\Collection\CollectionInterface
<add> * @return self
<ide> */
<ide> public function match(array $conditions): CollectionInterface;
<ide>
<ide> public function last();
<ide> * in this collection with the passed list of elements
<ide> *
<ide> * @param iterable $items Items list.
<del> * @return \Cake\Collection\CollectionInterface
<add> * @return self
<ide> */
<ide> public function append($items): CollectionInterface;
<ide>
<ide> public function append($items): CollectionInterface;
<ide> *
<ide> * @param mixed $item The item to append.
<ide> * @param mixed $key The key to append the item with. If null a key will be generated.
<del> * @return \Cake\Collection\CollectionInterface
<add> * @return self
<ide> */
<ide> public function appendItem($item, $key = null): CollectionInterface;
<ide>
<ide> /**
<ide> * Prepend a set of items to a collection creating a new collection
<ide> *
<ide> * @param mixed $items The items to prepend.
<del> * @return \Cake\Collection\CollectionInterface
<add> * @return self
<ide> */
<ide> public function prepend($items): CollectionInterface;
<ide>
<ide> public function prepend($items): CollectionInterface;
<ide> *
<ide> * @param mixed $item The item to prepend.
<ide> * @param mixed $key The key to prepend the item with. If null a key will be generated.
<del> * @return \Cake\Collection\CollectionInterface
<add> * @return self
<ide> */
<ide> public function prependItem($item, $key = null): CollectionInterface;
<ide>
<ide> public function prependItem($item, $key = null): CollectionInterface;
<ide> * or a function returning the value out of the provided element
<ide> * @param callable|string|null $groupPath the column name path to use as the parent
<ide> * grouping key or a function returning the key out of the provided element
<del> * @return \Cake\Collection\CollectionInterface
<add> * @return self
<ide> */
<ide> public function combine($keyPath, $valuePath, $groupPath = null): CollectionInterface;
<ide>
<ide> public function combine($keyPath, $valuePath, $groupPath = null): CollectionInte
<ide> * @param callable|string $parentPath the column name path to use for determining
<ide> * whether an element is child of another
<ide> * @param string $nestingKey The key name under which children are nested
<del> * @return \Cake\Collection\CollectionInterface
<add> * @return self
<ide> */
<ide> public function nest($idPath, $parentPath, string $nestingKey = 'children'): CollectionInterface;
<ide>
<ide> public function nest($idPath, $parentPath, string $nestingKey = 'children'): Col
<ide> * inside the hierarchy of each value so that the value can be inserted
<ide> * @param mixed $values The values to be inserted at the specified path,
<ide> * values are matched with the elements in this collection by its positional index.
<del> * @return \Cake\Collection\CollectionInterface
<add> * @return self
<ide> */
<ide> public function insert(string $path, $values): CollectionInterface;
<ide>
<ide> public function jsonSerialize(): array;
<ide> * collection as the array keys. Keep in mind that it is valid for iterators
<ide> * to return the same key for different elements, setting this value to false
<ide> * can help getting all items if keys are not important in the result.
<del> * @return \Cake\Collection\CollectionInterface
<add> * @return self
<ide> */
<ide> public function compile(bool $preserveKeys = true): CollectionInterface;
<ide>
<ide> public function compile(bool $preserveKeys = true): CollectionInterface;
<ide> *
<ide> * A lazy collection can only be iterated once. A second attempt results in an error.
<ide> *
<del> * @return \Cake\Collection\CollectionInterface
<add> * @return self
<ide> */
<ide> public function lazy(): CollectionInterface;
<ide>
<ide> public function lazy(): CollectionInterface;
<ide> *
<ide> * This can also be used to make any non-rewindable iterator rewindable.
<ide> *
<del> * @return \Cake\Collection\CollectionInterface
<add> * @return self
<ide> */
<ide> public function buffered(): CollectionInterface;
<ide>
<ide> public function buffered(): CollectionInterface;
<ide> * @param string|int $dir The direction in which to return the elements
<ide> * @param string|callable $nestingKey The key name under which children are nested
<ide> * or a callable function that will return the children list
<del> * @return \Cake\Collection\CollectionInterface
<add> * @return self
<ide> */
<ide> public function listNested($dir = 'desc', $nestingKey = 'children'): CollectionInterface;
<ide>
<ide> public function listNested($dir = 'desc', $nestingKey = 'children'): CollectionI
<ide> * If an array, it will be interpreted as a key-value list of conditions where
<ide> * the key is a property path as accepted by `Collection::extract`,
<ide> * and the value the condition against with each element will be matched.
<del> * @return \Cake\Collection\CollectionInterface
<add> * @return self
<ide> */
<ide> public function stopWhen($condition): CollectionInterface;
<ide>
<ide> public function stopWhen($condition): CollectionInterface;
<ide> *
<ide> * @param callable|null $transformer A callable function that will receive each of
<ide> * the items in the collection and should return an array or Traversable object
<del> * @return \Cake\Collection\CollectionInterface
<add> * @return self
<ide> */
<ide> public function unfold(?callable $transformer = null): CollectionInterface;
<ide>
<ide> public function unfold(?callable $transformer = null): CollectionInterface;
<ide> *
<ide> * @param callable $handler A callable function that will receive
<ide> * this collection as first argument.
<del> * @return \Cake\Collection\CollectionInterface
<add> * @return self
<ide> */
<ide> public function through(callable $handler): CollectionInterface;
<ide>
<ide> public function through(callable $handler): CollectionInterface;
<ide> * ```
<ide> *
<ide> * @param iterable ...$items The collections to zip.
<del> * @return \Cake\Collection\CollectionInterface
<add> * @return self
<ide> */
<ide> public function zip(iterable $items): CollectionInterface;
<ide>
<ide> public function zip(iterable $items): CollectionInterface;
<ide> *
<ide> * @param iterable ...$items The collections to zip.
<ide> * @param callable $callable The function to use for zipping the elements together.
<del> * @return \Cake\Collection\CollectionInterface
<add> * @return self
<ide> */
<ide> public function zipWith(iterable $items, $callable): CollectionInterface;
<ide>
<ide> public function zipWith(iterable $items, $callable): CollectionInterface;
<ide> * ```
<ide> *
<ide> * @param int $chunkSize The maximum size for each chunk
<del> * @return \Cake\Collection\CollectionInterface
<add> * @return self
<ide> */
<ide> public function chunk(int $chunkSize): CollectionInterface;
<ide>
<ide> public function chunk(int $chunkSize): CollectionInterface;
<ide> *
<ide> * @param int $chunkSize The maximum size for each chunk
<ide> * @param bool $preserveKeys If the keys of the array should be preserved
<del> * @return \Cake\Collection\CollectionInterface
<add> * @return self
<ide> */
<ide> public function chunkWithKeys(int $chunkSize, bool $preserveKeys = true): CollectionInterface;
<ide>
<ide> public function unwrap(): Traversable;
<ide> * // ]
<ide> * ```
<ide> *
<del> * @return \Cake\Collection\CollectionInterface
<add> * @return self
<ide> */
<ide> public function transpose(): CollectionInterface;
<ide>
<ide> public function countKeys(): int;
<ide> * @param callable|null $operation A callable that allows you to customize the product result.
<ide> * @param callable|null $filter A filtering callback that must return true for a result to be part
<ide> * of the final results.
<del> * @return \Cake\Collection\CollectionInterface
<add> * @return self
<ide> */
<ide> public function cartesianProduct(?callable $operation = null, ?callable $filter = null): CollectionInterface;
<ide> } | 1 |
Javascript | Javascript | update reactnativetypes from pr to react | c0029be95364008802505feb8ed2f28f5026abe1 | <ide><path>Libraries/Renderer/shims/ReactNativeTypes.js
<ide> * @flow
<ide> */
<ide>
<del>import * as React from 'react';
<add>import React, {type ElementRef, type AbstractComponent} from 'react';
<ide>
<ide> export type MeasureOnSuccessCallback = (
<ide> x: number,
<ide> class ReactNativeComponent<Props> extends React.Component<Props> {
<ide> measure(callback: MeasureOnSuccessCallback): void {}
<ide> measureInWindow(callback: MeasureInWindowOnSuccessCallback): void {}
<ide> measureLayout(
<del> relativeToNativeNode: number | React.ElementRef<HostComponent<mixed>>,
<add> relativeToNativeNode: number | ElementRef<HostComponent<mixed>>,
<ide> onSuccess: MeasureLayoutOnSuccessCallback,
<ide> onFail?: () => void,
<ide> ): void {}
<ide> export type ReactNativeComponentClass_ForTestsOnly<Props> = Class<
<ide> >;
<ide>
<ide> /**
<del> * This type keeps HostComponent and NativeMethodsMixin in sync.
<add> * This type keeps ReactNativeFiberHostComponent and NativeMethodsMixin in sync.
<ide> * It can also provide types for ReactNative applications that use NMM or refs.
<ide> */
<del>type NativeMethods = $ReadOnly<{|
<add>export type NativeMethods = {
<ide> blur(): void,
<ide> focus(): void,
<ide> measure(callback: MeasureOnSuccessCallback): void,
<ide> measureInWindow(callback: MeasureInWindowOnSuccessCallback): void,
<ide> measureLayout(
<del> relativeToNativeNode: number | React.ElementRef<HostComponent<mixed>>,
<add> relativeToNativeNode: number | ElementRef<HostComponent<mixed>>,
<ide> onSuccess: MeasureLayoutOnSuccessCallback,
<ide> onFail?: () => void,
<ide> ): void,
<ide> setNativeProps(nativeProps: Object): void,
<del>|}>;
<add>};
<ide>
<ide> export type NativeMethodsMixinType = NativeMethods;
<del>export type HostComponent<T> = React.AbstractComponent<T, NativeMethods>;
<add>export type HostComponent<T> = AbstractComponent<
<add> T,
<add> $ReadOnly<$Exact<NativeMethods>>,
<add>>;
<ide>
<ide> type SecretInternalsType = {
<ide> NativeMethodsMixin: NativeMethodsMixinType, | 1 |
Javascript | Javascript | use missing validator | 7a0a8efec183db31294369823cc5a66c3a54cc7b | <ide><path>lib/net.js
<ide> const {
<ide> const { isUint8Array } = require('internal/util/types');
<ide> const {
<ide> validateAbortSignal,
<add> validateFunction,
<ide> validateInt32,
<ide> validateNumber,
<ide> validatePort,
<ide> function lookupAndConnect(self, options) {
<ide> return;
<ide> }
<ide>
<del> if (options.lookup && typeof options.lookup !== 'function')
<del> throw new ERR_INVALID_ARG_TYPE('options.lookup',
<del> 'Function', options.lookup);
<del>
<add> if (options.lookup !== undefined)
<add> validateFunction(options.lookup, 'options.lookup');
<ide>
<ide> if (dns === undefined) dns = require('dns');
<ide> const dnsopts = { | 1 |
PHP | PHP | fix some type hints | 5d148e582381e95af77a43ae1c3cd68e477c8235 | <ide><path>src/Illuminate/Bus/Dispatcher.php
<ide> public function dispatchFromArray($command, array $array)
<ide> * Marshal a command and dispatch it to its appropriate handler.
<ide> *
<ide> * @param mixed $command
<del> * @param array $array
<add> * @param \ArrayAccess $array
<ide> * @return mixed
<ide> */
<ide> public function dispatchFrom($command, ArrayAccess $source, $extras = [])
<ide><path>src/Illuminate/Foundation/Bus/DispatchesCommands.php
<ide> protected function dispatchFromArray($command, array $array)
<ide> * Marshal a command and dispatch it to its appropriate handler.
<ide> *
<ide> * @param mixed $command
<del> * @param array $array
<add> * @param \ArrayAccess $array
<ide> * @return mixed
<ide> */
<ide> protected function dispatchFrom($command, ArrayAccess $source, $extras = []) | 2 |
Javascript | Javascript | fix incorrect babal alias for next/router. (#480) | aa7fccbbc4768a7971ad265f67a2f885e9c2a317 | <ide><path>server/build/babel/preset.js
<ide> module.exports = {
<ide> 'next/css': require.resolve('../../../lib/css'),
<ide> 'next/head': require.resolve('../../../lib/head'),
<ide> 'next/document': require.resolve('../../../server/document'),
<del> 'next/router': require.resolve('../../../server/router'),
<add> 'next/router': require.resolve('../../../lib/router'),
<ide> 'styled-jsx/style': require.resolve('styled-jsx/style')
<ide> }
<ide> } | 1 |
Mixed | Python | move device and hook to utils. fix device stuff | 2164c8dbbfdba1e0e27703f84bf5cf995b044d79 | <ide><path>tutorials/image/cifar10_estimator/README.md
<ide> $ python cifar10_main.py --data-dir=/prefix/to/downloaded/data/cifar-10-batches-
<ide> # Run the model on 2 GPUs using CPU as parameter server. After training, it runs the evaluation.
<ide> $ python cifar10_main.py --data-dir=/prefix/to/downloaded/data/cifar-10-batches-py \
<ide> --job-dir=/tmp/cifar10 \
<del> --force-gpu-compatible \
<ide> --num-gpus=2 \
<ide> --train-steps=1000
<ide>
<ide> $ python cifar10_main.py --data-dir=/prefix/to/downloaded/data/cifar-10-batches-
<ide> # a couple of times to perform evaluation.
<ide> $ python cifar10_main.py --data-dir=/prefix/to/downloaded/data/cifar-10-batches-bin \
<ide> --job-dir=/tmp/cifar10 \
<del> --avg-on-gpu \
<del> --force-gpu-compatible \
<add> --variable-strategy GPU \
<ide> --num-gpus=2 \
<ide>
<ide>
<ide> gcloud ml-engine jobs submit training cifarmultigpu \
<ide> --module-name cifar10_estimator.cifar10_main \
<ide> -- \
<ide> --data-dir=$MY_BUCKET/cifar-10-batches-py \
<del> --force-gpu-compatible \
<ide> --num-gpus=4 \
<ide> --train-steps=1000
<ide> ```
<ide> Once you have a `TF_CONFIG` configured properly on each host you're ready to run
<ide> # Make sure the model_dir is the same as defined on the TF_CONFIG.
<ide> $ python cifar10_main.py --data-dir=gs://path/cifar-10-batches-py \
<ide> --job-dir=gs://path/model_dir/ \
<del> --force-gpu-compatible \
<ide> --num-gpus=4 \
<ide> --train-steps=40000 \
<ide> --sync \
<del> \
<ide> --num-workers=2
<ide> ```
<ide>
<ide> INFO:tensorflow:Saving dict for global step 1: accuracy = 0.0994, global_step =
<ide> # Make sure the model_dir is the same as defined on the TF_CONFIG.
<ide> $ python cifar10_main.py --data-dir=gs://path/cifar-10-batches-py \
<ide> --job-dir=gs://path/model_dir/ \
<del> --force-gpu-compatible \
<ide> --num-gpus=4 \
<ide> --train-steps=40000 \
<ide> --sync
<ide><path>tutorials/image/cifar10_estimator/cifar10_main.py
<ide>
<ide> import argparse
<ide> import functools
<del>import operator
<add>import itertools
<ide> import os
<add>import six
<ide>
<ide> import numpy as np
<ide> from six.moves import xrange # pylint: disable=redefined-builtin
<ide> import tensorflow as tf
<del>from tensorflow.python.platform import tf_logging as logging
<del>from tensorflow.python.training import basic_session_run_hooks
<del>from tensorflow.python.training import session_run_hook
<del>from tensorflow.python.training import training_util
<ide>
<ide> import cifar10
<ide> import cifar10_model
<add>import cifar10_utils
<ide>
<del>tf.logging.set_verbosity(tf.logging.INFO)
<del>
<del>
<del>class ExamplesPerSecondHook(session_run_hook.SessionRunHook):
<del> """Hook to print out examples per second.
<ide>
<del> Total time is tracked and then divided by the total number of steps
<del> to get the average step time and then batch_size is used to determine
<del> the running average of examples per second. The examples per second for the
<del> most recent interval is also logged.
<del> """
<del>
<del> def __init__(
<del> self,
<del> batch_size,
<del> every_n_steps=100,
<del> every_n_secs=None,):
<del> """Initializer for ExamplesPerSecondHook.
<del>
<del> Args:
<del> batch_size: Total batch size used to calculate examples/second from
<del> global time.
<del> every_n_steps: Log stats every n steps.
<del> every_n_secs: Log stats every n seconds.
<del> """
<del> if (every_n_steps is None) == (every_n_secs is None):
<del> raise ValueError('exactly one of every_n_steps'
<del> ' and every_n_secs should be provided.')
<del> self._timer = basic_session_run_hooks.SecondOrStepTimer(
<del> every_steps=every_n_steps, every_secs=every_n_secs)
<del>
<del> self._step_train_time = 0
<del> self._total_steps = 0
<del> self._batch_size = batch_size
<del>
<del> def begin(self):
<del> self._global_step_tensor = training_util.get_global_step()
<del> if self._global_step_tensor is None:
<del> raise RuntimeError(
<del> 'Global step should be created to use StepCounterHook.')
<del>
<del> def before_run(self, run_context): # pylint: disable=unused-argument
<del> return basic_session_run_hooks.SessionRunArgs(self._global_step_tensor)
<del>
<del> def after_run(self, run_context, run_values):
<del> _ = run_context
<del>
<del> global_step = run_values.results
<del> if self._timer.should_trigger_for_step(global_step):
<del> elapsed_time, elapsed_steps = self._timer.update_last_triggered_step(
<del> global_step)
<del> if elapsed_time is not None:
<del> steps_per_sec = elapsed_steps / elapsed_time
<del> self._step_train_time += elapsed_time
<del> self._total_steps += elapsed_steps
<del>
<del> average_examples_per_sec = self._batch_size * (
<del> self._total_steps / self._step_train_time)
<del> current_examples_per_sec = steps_per_sec * self._batch_size
<del> # Average examples/sec followed by current examples/sec
<del> logging.info('%s: %g (%g), step = %g', 'Average examples/sec',
<del> average_examples_per_sec, current_examples_per_sec,
<del> self._total_steps)
<del>
<del>
<del>class GpuParamServerDeviceSetter(object):
<del> """Used with tf.device() to place variables on the least loaded GPU.
<del>
<del> A common use for this class is to pass a list of GPU devices, e.g. ['gpu:0',
<del> 'gpu:1','gpu:2'], as ps_devices. When each variable is placed, it will be
<del> placed on the least loaded gpu. All other Ops, which will be the computation
<del> Ops, will be placed on the worker_device.
<del> """
<add>tf.logging.set_verbosity(tf.logging.INFO)
<ide>
<del> def __init__(self, worker_device, ps_devices):
<del> """Initializer for GpuParamServerDeviceSetter.
<ide>
<del> Args:
<del> worker_device: the device to use for computation Ops.
<del> ps_devices: a list of devices to use for Variable Ops. Each variable is
<del> assigned to the least loaded device.
<del> """
<del> self.ps_devices = ps_devices
<del> self.worker_device = worker_device
<del> self.ps_sizes = [0] * len(self.ps_devices)
<del>
<del> def __call__(self, op):
<del> if op.device:
<del> return op.device
<del> if op.type not in ['Variable', 'VariableV2', 'VarHandleOp']:
<del> return self.worker_device
<del>
<del> # Gets the least loaded ps_device
<del> device_index, _ = min(enumerate(self.ps_sizes), key=operator.itemgetter(1))
<del> device_name = self.ps_devices[device_index]
<del> var_size = op.outputs[0].get_shape().num_elements()
<del> self.ps_sizes[device_index] += var_size
<del>
<del> return device_name
<del>
<del>
<del>def _create_device_setter(avg_on_gpu, worker, num_gpus):
<del> """Create device setter object."""
<del> if avg_on_gpu:
<del> gpus = ['/gpu:%d' % i for i in range(num_gpus)]
<del> return GpuParamServerDeviceSetter(worker, gpus)
<del> else:
<del> # tf.train.replica_device_setter supports placing variables on the CPU, all
<del> # on one GPU, or on ps_servers defined in a cluster_spec.
<del> return tf.train.replica_device_setter(
<del> worker_device=worker, ps_device='/cpu:0', ps_tasks=1)
<del>
<del>def get_model_fn(num_gpus, avg_on_gpu, num_workers):
<add>def get_model_fn(num_gpus, variable_strategy, num_workers):
<ide> def _resnet_model_fn(features, labels, mode, params):
<ide> """Resnet model body.
<ide>
<del> Support single host, one or more GPU training. Parameter distribution can be
<del> either one of the following scheme.
<add> Support single host, one or more GPU training. Parameter distribution can
<add> be either one of the following scheme.
<ide> 1. CPU is the parameter server and manages gradient updates.
<ide> 2. Parameters are distributed evenly across all GPUs, and the first GPU
<ide> manages gradient updates.
<ide> def _resnet_model_fn(features, labels, mode, params):
<ide>
<ide> if num_gpus != 0:
<ide> for i in range(num_gpus):
<del> worker = '/gpu:%d' % i
<del> device_setter = _create_device_setter(avg_on_gpu, worker, num_gpus)
<add> worker_device = '/gpu:{}'.format(i)
<add> if variable_strategy == 'CPU':
<add> device_setter = cifar10_utils.local_device_setter(
<add> worker_device=worker_device)
<add> elif variable_strategy == 'GPU':
<add> device_setter = cifar10_utils.local_device_setter(
<add> ps_device_type='gpu',
<add> worker_device=worker_device,
<add> ps_strategy=tf.contrib.training.GreedyLoadBalancingStrategy(
<add> num_gpus,
<add> tf.contrib.training.byte_size_load_fn
<add> )
<add> )
<ide> with tf.variable_scope('resnet', reuse=bool(i != 0)):
<ide> with tf.name_scope('tower_%d' % i) as name_scope:
<ide> with tf.device(device_setter):
<ide> def _resnet_model_fn(features, labels, mode, params):
<ide>
<ide> # Now compute global loss and gradients.
<ide> gradvars = []
<del> # Server that runs the ops to apply global gradient updates.
<del> avg_device = '/gpu:0' if avg_on_gpu else '/cpu:0'
<del> with tf.device(avg_device):
<del> with tf.name_scope('gradient_averaging'):
<del> loss = tf.reduce_mean(tower_losses, name='loss')
<del> for zipped_gradvars in zip(*tower_gradvars):
<del> # Averaging one var's gradients computed from multiple towers
<del> var = zipped_gradvars[0][1]
<del> grads = [gv[0] for gv in zipped_gradvars]
<del> with tf.device(var.device):
<del> if len(grads) == 1:
<del> avg_grad = grads[0]
<del> else:
<del> avg_grad = tf.multiply(tf.add_n(grads), 1. / len(grads))
<del> gradvars.append((avg_grad, var))
<del>
<add> with tf.name_scope('gradient_averaging'):
<add> all_grads = {}
<add> for grad, var in itertools.chain(*tower_gradvars):
<add> if grad is not None:
<add> all_grads.setdefault(var, []).append(grad)
<add> for var, grads in six.iteritems(all_grads):
<add> # Average gradients on the same device as the variables
<add> # to which they apply.
<add> with tf.device(var.device):
<add> if len(grads) == 1:
<add> avg_grad = grads[0]
<add> else:
<add> avg_grad = tf.multiply(tf.add_n(grads), 1. / len(grads))
<add> gradvars.append((avg_grad, var))
<add>
<add>
<add> # Device that runs the ops to apply global gradient updates.
<add> consolidation_device = '/gpu:0' if variable_strategy == 'GPU' else '/cpu:0'
<add> with tf.device(consolidation_device):
<ide> # Suggested learning rate scheduling from
<ide> # https://github.com/ppwwyyxx/tensorpack/blob/master/examples/ResNet/cifar10-resnet.py#L155
<ide> # users could apply other scheduling.
<ide> def _resnet_model_fn(features, labels, mode, params):
<ide> metrics = {
<ide> 'accuracy': tf.metrics.accuracy(stacked_labels, predictions['classes'])
<ide> }
<add> loss = tf.reduce_mean(tower_losses, name='loss')
<ide>
<ide> return tf.estimator.EstimatorSpec(
<ide> mode=mode,
<ide> def _tower_fn(is_training,
<ide>
<ide> tower_grad = tf.gradients(tower_loss, model_params)
<ide>
<del> return tower_loss, tower_grad, tower_pred
<add> return tower_loss, zip(tower_grad, model_params), tower_pred
<ide>
<ide>
<ide> def input_fn(data_dir, subset, num_shards, batch_size,
<ide> def _experiment_fn(run_config, hparams):
<ide>
<ide> train_steps = hparams.train_steps
<ide> eval_steps = num_eval_examples // hparams.eval_batch_size
<del> examples_sec_hook = ExamplesPerSecondHook(
<add> examples_sec_hook = cifar10_utils.ExamplesPerSecondHook(
<ide> hparams.train_batch_size, every_n_steps=10)
<ide>
<ide> tensors_to_log = {'learning_rate': 'learning_rate',
<del> 'loss': 'gradient_averaging/loss'}
<add> 'loss': 'loss'}
<ide>
<ide> logging_hook = tf.train.LoggingTensorHook(
<ide> tensors=tensors_to_log, every_n_iter=100)
<ide> def _experiment_fn(run_config, hparams):
<ide>
<ide> classifier = tf.estimator.Estimator(
<ide> model_fn=get_model_fn(
<del> num_gpus, is_gpu_ps, run_config.num_worker_replicas),
<add> num_gpus, is_gpu_ps, run_config.num_worker_replicas or 1),
<ide> config=run_config,
<ide> params=vars(hparams)
<ide> )
<ide> def _experiment_fn(run_config, hparams):
<ide> def main(job_dir,
<ide> data_dir,
<ide> num_gpus,
<del> avg_on_gpu,
<add> variable_strategy,
<ide> use_distortion_for_training,
<ide> log_device_placement,
<ide> num_intra_threads,
<del> force_gpu_compatible,
<ide> **hparams):
<ide> # The env variable is on deprecation path, default is set to off.
<ide> os.environ['TF_SYNC_ON_FINISH'] = '0'
<ide> def main(job_dir,
<ide> log_device_placement=log_device_placement,
<ide> intra_op_parallelism_threads=num_intra_threads,
<ide> gpu_options=tf.GPUOptions(
<del> force_gpu_compatible=force_gpu_compatible
<add> force_gpu_compatible=True
<ide> )
<ide> )
<ide>
<ide> def main(job_dir,
<ide> get_experiment_fn(
<ide> data_dir,
<ide> num_gpus,
<del> avg_on_gpu,
<add> variable_strategy,
<ide> use_distortion_for_training
<ide> ),
<ide> run_config=config,
<ide> def main(job_dir,
<ide> help='The directory where the model will be stored.'
<ide> )
<ide> parser.add_argument(
<del> '--avg-on-gpu',
<del> action='store_true',
<del> default=False,
<del> help='If present, use GPU to average gradients.'
<add> '--variable_strategy',
<add> choices=['CPU', 'GPU'],
<add> type=str,
<add> default='CPU',
<add> help='Where to locate variable operations'
<ide> )
<ide> parser.add_argument(
<ide> '--num-gpus',
<ide> def main(job_dir,
<ide> type=float,
<ide> default=2e-4,
<ide> help='Weight decay for convolutions.'
<del> )
<del>
<add> )
<ide> parser.add_argument(
<ide> '--learning-rate',
<ide> type=float,
<ide> def main(job_dir,
<ide> system will pick an appropriate number.\
<ide> """
<ide> )
<del> parser.add_argument(
<del> '--force-gpu-compatible',
<del> action='store_true',
<del> default=False,
<del> help="""\
<del> Whether to enable force_gpu_compatible in GPU_Options. Check
<del> tensorflow/core/protobuf/config.proto#L69 for details.\
<del> """
<del> )
<ide> parser.add_argument(
<ide> '--log-device-placement',
<ide> action='store_true',
<ide> def main(job_dir,
<ide> if args.num_gpus < 0:
<ide> raise ValueError(
<ide> 'Invalid GPU count: \"num_gpus\" must be 0 or a positive integer.')
<del> if args.num_gpus == 0 and args.avg_on_gpu:
<add> if args.num_gpus == 0 and args.variable_strategy == 'GPU':
<ide> raise ValueError(
<ide> 'No GPU available for use, must use CPU to average gradients.')
<ide> if (args.num_layers - 2) % 6 != 0:
<ide><path>tutorials/image/cifar10_estimator/cifar10_utils.py
<add>import six
<add>
<add>from tensorflow.python.platform import tf_logging as logging
<add>
<add>from tensorflow.core.framework import node_def_pb2
<add>from tensorflow.python.framework import device as pydev
<add>from tensorflow.python.training import basic_session_run_hooks
<add>from tensorflow.python.training import session_run_hook
<add>from tensorflow.python.training import training_util
<add>from tensorflow.python.training import device_setter
<add>
<add>class ExamplesPerSecondHook(session_run_hook.SessionRunHook):
<add> """Hook to print out examples per second.
<add>
<add> Total time is tracked and then divided by the total number of steps
<add> to get the average step time and then batch_size is used to determine
<add> the running average of examples per second. The examples per second for the
<add> most recent interval is also logged.
<add> """
<add>
<add> def __init__(
<add> self,
<add> batch_size,
<add> every_n_steps=100,
<add> every_n_secs=None,):
<add> """Initializer for ExamplesPerSecondHook.
<add>
<add> Args:
<add> batch_size: Total batch size used to calculate examples/second from
<add> global time.
<add> every_n_steps: Log stats every n steps.
<add> every_n_secs: Log stats every n seconds.
<add> """
<add> if (every_n_steps is None) == (every_n_secs is None):
<add> raise ValueError('exactly one of every_n_steps'
<add> ' and every_n_secs should be provided.')
<add> self._timer = basic_session_run_hooks.SecondOrStepTimer(
<add> every_steps=every_n_steps, every_secs=every_n_secs)
<add>
<add> self._step_train_time = 0
<add> self._total_steps = 0
<add> self._batch_size = batch_size
<add>
<add> def begin(self):
<add> self._global_step_tensor = training_util.get_global_step()
<add> if self._global_step_tensor is None:
<add> raise RuntimeError(
<add> 'Global step should be created to use StepCounterHook.')
<add>
<add> def before_run(self, run_context): # pylint: disable=unused-argument
<add> return basic_session_run_hooks.SessionRunArgs(self._global_step_tensor)
<add>
<add> def after_run(self, run_context, run_values):
<add> _ = run_context
<add>
<add> global_step = run_values.results
<add> if self._timer.should_trigger_for_step(global_step):
<add> elapsed_time, elapsed_steps = self._timer.update_last_triggered_step(
<add> global_step)
<add> if elapsed_time is not None:
<add> steps_per_sec = elapsed_steps / elapsed_time
<add> self._step_train_time += elapsed_time
<add> self._total_steps += elapsed_steps
<add>
<add> average_examples_per_sec = self._batch_size * (
<add> self._total_steps / self._step_train_time)
<add> current_examples_per_sec = steps_per_sec * self._batch_size
<add> # Average examples/sec followed by current examples/sec
<add> logging.info('%s: %g (%g), step = %g', 'Average examples/sec',
<add> average_examples_per_sec, current_examples_per_sec,
<add> self._total_steps)
<add>
<add>def local_device_setter(num_devices=1,
<add> ps_device_type='cpu',
<add> worker_device='/cpu:0',
<add> ps_ops=None,
<add> ps_strategy=None):
<add> if ps_ops == None:
<add> ps_ops = ['Variable', 'VariableV2', 'VarHandleOp']
<add>
<add> if ps_strategy is None:
<add> ps_strategy = device_setter._RoundRobinStrategy(num_devices)
<add> if not six.callable(ps_strategy):
<add> raise TypeError("ps_strategy must be callable")
<add>
<add> def _local_device_chooser(op):
<add> current_device = pydev.DeviceSpec.from_string(op.device or "")
<add>
<add> node_def = op if isinstance(op, node_def_pb2.NodeDef) else op.node_def
<add> if node_def.op in ps_ops:
<add> ps_device_spec = pydev.DeviceSpec.from_string(
<add> '/{}:{}'.format(ps_device_type, ps_strategy(op)))
<add>
<add> ps_device_spec.merge_from(current_device)
<add> return ps_device_spec.to_string()
<add> else:
<add> worker_device_spec = pydev.DeviceSpec.from_string(worker_device or "")
<add> worker_device_spec.merge_from(current_device)
<add> return worker_device_spec.to_string()
<add> return _local_device_chooser
<ide><path>tutorials/image/cifar10_estimator/generate_cifar10_tfrecords.py
<ide>
<ide> import tensorflow as tf
<ide>
<del>FLAGS = None
<del>
<del>
<del>
<ide>
<ide> def _int64_feature(value):
<ide> return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
<ide> def convert_to_tfrecord(input_files, output_file):
<ide> record_writer.write(example.SerializeToString())
<ide>
<ide>
<del>def main(unused_argv):
<add>def main(input_dir, output_dir):
<ide> file_names = _get_file_names()
<ide> for mode, files in file_names.items():
<ide> input_files = [
<del> os.path.join(FLAGS.input_dir, f) for f in files]
<del> output_file = os.path.join(FLAGS.output_dir, mode + '.tfrecords')
<add> os.path.join(input_dir, f) for f in files]
<add> output_file = os.path.join(output_dir, mode + '.tfrecords')
<ide> # Convert to Examples and write the result to TFRecords.
<ide> convert_to_tfrecord(input_files, output_file)
<ide> print('Done!')
<ide> def main(unused_argv):
<ide> if __name__ == '__main__':
<ide> parser = argparse.ArgumentParser()
<ide> parser.add_argument(
<del> '--input_dir',
<add> '--input-dir',
<ide> type=str,
<ide> default='',
<ide> help='Directory where CIFAR10 data is located.'
<ide> )
<ide> parser.add_argument(
<del> '--output_dir',
<add> '--output-dir',
<ide> type=str,
<ide> default='',
<ide> help="""\
<ide> Directory where TFRecords will be saved.The TFRecords will have the same
<ide> name as the CIFAR10 inputs + .tfrecords.\
<ide> """
<ide> )
<del> FLAGS = parser.parse_args()
<del>
<del> tf.app.run(main)
<add> args = parser.parse_args()
<add> main(args.input_dir, args.output_dir) | 4 |
Mixed | Go | fix network name masking network id on delete | e52001c56e12e4fc63fb5d89ef919295d6ddd5d5 | <ide><path>daemon/network.go
<ide> func (daemon *Daemon) NetworkControllerEnabled() bool {
<ide>
<ide> // FindNetwork function finds a network for a given string that can represent network name or id
<ide> func (daemon *Daemon) FindNetwork(idName string) (libnetwork.Network, error) {
<del> // Find by Name
<del> n, err := daemon.GetNetworkByName(idName)
<del> if err != nil && !isNoSuchNetworkError(err) {
<del> return nil, err
<add> // 1. match by full ID.
<add> n, err := daemon.GetNetworkByID(idName)
<add> if err == nil || !isNoSuchNetworkError(err) {
<add> return n, err
<ide> }
<ide>
<del> if n != nil {
<del> return n, nil
<add> // 2. match by full name
<add> n, err = daemon.GetNetworkByName(idName)
<add> if err == nil || !isNoSuchNetworkError(err) {
<add> return n, err
<ide> }
<ide>
<del> // Find by id
<del> return daemon.GetNetworkByID(idName)
<add> // 3. match by ID prefix
<add> list := daemon.GetNetworksByIDPrefix(idName)
<add> if len(list) == 0 {
<add> return nil, errors.WithStack(networkNotFound(idName))
<add> }
<add> if len(list) > 1 {
<add> return nil, errors.WithStack(invalidIdentifier(idName))
<add> }
<add> return list[0], nil
<ide> }
<ide>
<ide> func isNoSuchNetworkError(err error) bool {
<ide> _, ok := err.(libnetwork.ErrNoSuchNetwork)
<ide> return ok
<ide> }
<ide>
<del>// GetNetworkByID function returns a network whose ID begins with the given prefix.
<del>// It fails with an error if no matching, or more than one matching, networks are found.
<del>func (daemon *Daemon) GetNetworkByID(partialID string) (libnetwork.Network, error) {
<del> list := daemon.GetNetworksByID(partialID)
<del>
<del> if len(list) == 0 {
<del> return nil, errors.WithStack(networkNotFound(partialID))
<del> }
<del> if len(list) > 1 {
<del> return nil, errors.WithStack(invalidIdentifier(partialID))
<add>// GetNetworkByID function returns a network whose ID matches the given ID.
<add>// It fails with an error if no matching network is found.
<add>func (daemon *Daemon) GetNetworkByID(id string) (libnetwork.Network, error) {
<add> c := daemon.netController
<add> if c == nil {
<add> return nil, libnetwork.ErrNoSuchNetwork(id)
<ide> }
<del> return list[0], nil
<add> return c.NetworkByID(id)
<ide> }
<ide>
<ide> // GetNetworkByName function returns a network for a given network name.
<ide> func (daemon *Daemon) GetNetworkByName(name string) (libnetwork.Network, error)
<ide> return c.NetworkByName(name)
<ide> }
<ide>
<del>// GetNetworksByID returns a list of networks whose ID partially matches zero or more networks
<del>func (daemon *Daemon) GetNetworksByID(partialID string) []libnetwork.Network {
<add>// GetNetworksByIDPrefix returns a list of networks whose ID partially matches zero or more networks
<add>func (daemon *Daemon) GetNetworksByIDPrefix(partialID string) []libnetwork.Network {
<ide> c := daemon.netController
<ide> if c == nil {
<ide> return nil
<ide><path>docs/api/version-history.md
<ide> keywords: "API, Docker, rcli, REST, documentation"
<ide> * `POST /containers/create` now accepts additional values for the
<ide> `HostConfig.IpcMode` property. New values are `private`, `shareable`,
<ide> and `none`.
<add>* `DELETE /networks/{id or name}` fixed issue where a `name` equal to another
<add> network's name was able to mask that `id`. If both a network with the given
<add> _name_ exists, and a network with the given _id_, the network with the given
<add> _id_ is now deleted. This change is not versioned, and affects all API versions
<add> if the daemon has this patch.
<ide>
<ide> ## v1.31 API changes
<ide>
<ide><path>integration/network/delete_test.go
<add>package network
<add>
<add>import (
<add> "context"
<add> "testing"
<add>
<add> "github.com/docker/docker/api/types"
<add> "github.com/docker/docker/integration/util/request"
<add> "github.com/stretchr/testify/assert"
<add> "github.com/stretchr/testify/require"
<add>)
<add>
<add>func containsNetwork(nws []types.NetworkResource, nw types.NetworkCreateResponse) bool {
<add> for _, n := range nws {
<add> if n.ID == nw.ID {
<add> return true
<add> }
<add> }
<add> return false
<add>}
<add>
<add>// createAmbiguousNetworks creates three networks, of which the second network
<add>// uses a prefix of the first network's ID as name. The third network uses the
<add>// first network's ID as name.
<add>//
<add>// After successful creation, properties of all three networks is returned
<add>func createAmbiguousNetworks(t *testing.T) (types.NetworkCreateResponse, types.NetworkCreateResponse, types.NetworkCreateResponse) {
<add> client := request.NewAPIClient(t)
<add> ctx := context.Background()
<add>
<add> testNet, err := client.NetworkCreate(ctx, "testNet", types.NetworkCreate{})
<add> require.NoError(t, err)
<add> idPrefixNet, err := client.NetworkCreate(ctx, testNet.ID[:12], types.NetworkCreate{})
<add> require.NoError(t, err)
<add> fullIDNet, err := client.NetworkCreate(ctx, testNet.ID, types.NetworkCreate{})
<add> require.NoError(t, err)
<add>
<add> nws, err := client.NetworkList(ctx, types.NetworkListOptions{})
<add> require.NoError(t, err)
<add>
<add> assert.Equal(t, true, containsNetwork(nws, testNet), "failed to create network testNet")
<add> assert.Equal(t, true, containsNetwork(nws, idPrefixNet), "failed to create network idPrefixNet")
<add> assert.Equal(t, true, containsNetwork(nws, fullIDNet), "failed to create network fullIDNet")
<add> return testNet, idPrefixNet, fullIDNet
<add>}
<add>
<add>// TestDockerNetworkDeletePreferID tests that if a network with a name
<add>// equal to another network's ID exists, the Network with the given
<add>// ID is removed, and not the network with the given name.
<add>func TestDockerNetworkDeletePreferID(t *testing.T) {
<add> defer setupTest(t)()
<add> client := request.NewAPIClient(t)
<add> ctx := context.Background()
<add> testNet, idPrefixNet, fullIDNet := createAmbiguousNetworks(t)
<add>
<add> // Delete the network using a prefix of the first network's ID as name.
<add> // This should the network name with the id-prefix, not the original network.
<add> err := client.NetworkRemove(ctx, testNet.ID[:12])
<add> require.NoError(t, err)
<add>
<add> // Delete the network using networkID. This should remove the original
<add> // network, not the network with the name equal to the networkID
<add> err = client.NetworkRemove(ctx, testNet.ID)
<add> require.NoError(t, err)
<add>
<add> // networks "testNet" and "idPrefixNet" should be removed, but "fullIDNet" should still exist
<add> nws, err := client.NetworkList(ctx, types.NetworkListOptions{})
<add> require.NoError(t, err)
<add> assert.Equal(t, false, containsNetwork(nws, testNet), "Network testNet not removed")
<add> assert.Equal(t, false, containsNetwork(nws, idPrefixNet), "Network idPrefixNet not removed")
<add> assert.Equal(t, true, containsNetwork(nws, fullIDNet), "Network fullIDNet not found")
<add>}
<ide><path>integration/network/main_test.go
<add>package network
<add>
<add>import (
<add> "fmt"
<add> "os"
<add> "testing"
<add>
<add> "github.com/docker/docker/internal/test/environment"
<add>)
<add>
<add>var testEnv *environment.Execution
<add>
<add>func TestMain(m *testing.M) {
<add> var err error
<add> testEnv, err = environment.New()
<add> if err != nil {
<add> fmt.Println(err)
<add> os.Exit(1)
<add> }
<add>
<add> testEnv.Print()
<add> os.Exit(m.Run())
<add>}
<add>
<add>func setupTest(t *testing.T) func() {
<add> environment.ProtectAll(t, testEnv)
<add> return func() { testEnv.Clean(t) }
<add>} | 4 |
Python | Python | celerybeat persistent scheduler shelve fix | cc1a67ebb4612284ce65c36639da06e6d408a4d5 | <ide><path>celery/beat.py
<ide> def setup_schedule(self):
<ide> def get_schedule(self):
<ide> return self._store
<ide>
<add> def merge_inplace(self, b):
<add> A, B = set(self._store.keys()), set(b.keys())
<add>
<add> # Remove items from disk not in the schedule anymore.
<add> for key in A ^ B:
<add> self._store.pop(key, None)
<add>
<add> # Update and add new items in the schedule
<add> for key in B:
<add> entry = self.Entry(**dict(b[key]))
<add> if self._store.get(key):
<add> self._store[key].update(entry)
<add> else:
<add> self._store[key] = entry
<add>
<add> def update_from_dict(self, dict_):
<add> self._store.update(dict((name, self._maybe_entry(name, entry))
<add> for name, entry in dict_.items()))
<ide> def sync(self):
<ide> if self._store is not None:
<ide> self.logger.debug("CeleryBeat: Syncing schedule to disk...") | 1 |
Ruby | Ruby | use fetch for better error handling | e1f31e85ff6d6dab052049c2a4465659a791d844 | <ide><path>activesupport/lib/active_support/core_ext/date_and_time/calculations.rb
<ide> def last_year
<ide> # Week is assumed to start on +start_day+, default is
<ide> # +Date.beginning_of_week+ or +config.beginning_of_week+ when set.
<ide> def days_to_week_start(start_day = Date.beginning_of_week)
<del> start_day_number = DAYS_INTO_WEEK[start_day]
<add> start_day_number = DAYS_INTO_WEEK.fetch(start_day)
<ide> (wday - start_day_number) % 7
<ide> end
<ide>
<ide> def last_hour(date_or_time)
<ide> end
<ide>
<ide> def days_span(day)
<del> (DAYS_INTO_WEEK[day] - DAYS_INTO_WEEK[Date.beginning_of_week]) % 7
<add> (DAYS_INTO_WEEK.fetch(day) - DAYS_INTO_WEEK.fetch(Date.beginning_of_week)) % 7
<ide> end
<ide>
<ide> def copy_time_to(other) | 1 |
Go | Go | fix spelling of benchmark test | 5583774e29911bbd42181e8db2ece08761677cf3 | <ide><path>integration/container_test.go
<ide> func TestEntrypointNoCmd(t *testing.T) {
<ide> }
<ide> }
<ide>
<del>func BenchmarkRunSequencial(b *testing.B) {
<add>func BenchmarkRunSequential(b *testing.B) {
<ide> runtime := mkRuntime(b)
<ide> defer nuke(runtime)
<ide> for i := 0; i < b.N; i++ { | 1 |
Javascript | Javascript | use domhelper to extract url protocol | 50bc8bedba68549b7d3c7565ca14d1d126e37276 | <ide><path>packages/ember-htmlbars/lib/hooks/attribute.js
<ide> export default function attribute(env, morph, element, attrName, attrValue) {
<ide> if (isStream(attrValue)) {
<ide> throw new EmberError('Bound attributes are not yet supported in Ember.js');
<ide> } else {
<del> var sanitizedValue = sanitizeAttributeValue(element, attrName, attrValue);
<add> var sanitizedValue = sanitizeAttributeValue(env.dom, element, attrName, attrValue);
<ide> env.dom.setProperty(element, attrName, sanitizedValue);
<ide> }
<ide> }
<ide><path>packages/ember-views/lib/system/sanitize_attribute_value.js
<ide> export var badAttributes = {
<ide> 'background': true
<ide> };
<ide>
<del>export default function sanitizeAttributeValue(element, attribute, value) {
<add>export default function sanitizeAttributeValue(dom, element, attribute, value) {
<ide> var tagName;
<ide>
<del> if (!parsingNode) {
<del> parsingNode = document.createElement('a');
<del> }
<del>
<ide> if (!element) {
<ide> tagName = null;
<ide> } else {
<ide> export default function sanitizeAttributeValue(element, attribute, value) {
<ide> }
<ide>
<ide> if ((tagName === null || badTags[tagName]) && badAttributes[attribute]) {
<del> parsingNode.href = value;
<del>
<del> if (badProtocols[parsingNode.protocol] === true) {
<add> // Previously, we relied on creating a new `<a>` element and setting
<add> // its `href` in order to get the DOM to parse and extract its protocol.
<add> // Naive approaches to URL parsing are susceptible to all sorts of XSS
<add> // attacks.
<add> //
<add> // However, this approach does not work in environments without a DOM,
<add> // such as Node & FastBoot. We have extracted the logic for parsing to
<add> // the DOM helper, so that in locations without DOM, we can substitute
<add> // our own robust URL parsing.
<add> //
<add> // This will also allow us to use the new `URL` API in browsers that
<add> // support it, and skip the process of creating an element entirely.
<add> var protocol = dom.protocolForURL(value);
<add> if (badProtocols[protocol] === true) {
<ide> return 'unsafe:' + value;
<ide> }
<ide> }
<ide><path>packages/ember-views/lib/views/view.js
<ide> var View = CoreView.extend({
<ide> // Determine the current value and add it to the render buffer
<ide> // if necessary.
<ide> attributeValue = get(this, property);
<del> View.applyAttributeBindings(buffer, attributeName, attributeValue);
<add> View.applyAttributeBindings(this.renderer._dom, buffer, attributeName, attributeValue);
<ide> } else {
<ide> unspecifiedAttributeBindings[property] = attributeName;
<ide> }
<ide> var View = CoreView.extend({
<ide>
<ide> attributeValue = get(this, property);
<ide>
<del> View.applyAttributeBindings(elem, attributeName, attributeValue);
<add> View.applyAttributeBindings(this.renderer._dom, elem, attributeName, attributeValue);
<ide> };
<ide>
<ide> this.registerObserver(this, property, observer);
<ide> View.views = {};
<ide> View.childViewsProperty = childViewsProperty;
<ide>
<ide> // Used by Handlebars helpers, view element attributes
<del>View.applyAttributeBindings = function(elem, name, initialValue) {
<del> var value = sanitizeAttributeValue(elem[0], name, initialValue);
<add>View.applyAttributeBindings = function(dom, elem, name, initialValue) {
<add> var value = sanitizeAttributeValue(dom, elem[0], name, initialValue);
<ide> var type = typeOf(value);
<ide>
<ide> // if this changes, also change the logic in ember-handlebars/lib/helpers/binding.js
<ide><path>packages/ember-views/tests/system/sanitize_attribute_value_test.js
<ide> import sanitizeAttributeValue from "ember-views/system/sanitize_attribute_value";
<ide> import { SafeString } from "ember-htmlbars/utils/string";
<add>import { DOMHelper } from "morph";
<ide>
<ide> QUnit.module('ember-views: sanitizeAttributeValue(null, "href")');
<ide>
<ide> var goodProtocols = ['https', 'http', 'ftp', 'tel', 'file'];
<add>var dom = new DOMHelper();
<ide>
<ide> for (var i = 0, l = goodProtocols.length; i < l; i++) {
<ide> buildProtocolTest(goodProtocols[i]);
<ide> function buildProtocolTest(protocol) {
<ide> expect(1);
<ide>
<ide> var expected = protocol + '://foo.com';
<del> var actual = sanitizeAttributeValue(null, 'href', expected);
<add> var actual = sanitizeAttributeValue(dom, null, 'href', expected);
<ide>
<ide> equal(actual, expected, 'protocol not escaped');
<ide> });
<ide> test('blocks javascript: protocol', function() {
<ide> expect(1);
<ide>
<ide> var expected = 'javascript:alert("foo")';
<del> var actual = sanitizeAttributeValue(null, 'href', expected);
<add> var actual = sanitizeAttributeValue(dom, null, 'href', expected);
<ide>
<ide> equal(actual, 'unsafe:' + expected, 'protocol escaped');
<ide> });
<ide> test('blocks blacklisted protocols', function() {
<ide> expect(1);
<ide>
<ide> var expected = 'javascript:alert("foo")';
<del> var actual = sanitizeAttributeValue(null, 'href', expected);
<add> var actual = sanitizeAttributeValue(dom, null, 'href', expected);
<ide>
<ide> equal(actual, 'unsafe:' + expected, 'protocol escaped');
<ide> });
<ide> test('does not block SafeStrings', function() {
<ide> expect(1);
<ide>
<ide> var expected = 'javascript:alert("foo")';
<del> var actual = sanitizeAttributeValue(null, 'href', new SafeString(expected));
<add> var actual = sanitizeAttributeValue(dom, null, 'href', new SafeString(expected));
<ide>
<ide> equal(actual, expected, 'protocol unescaped');
<ide> }); | 4 |
PHP | PHP | implement protocolversion methods | a1e5181fe16fa0cdbd751728c6b5f3cfd14a24cc | <ide><path>src/Network/Request.php
<ide> class Request implements ArrayAccess
<ide> */
<ide> protected $uploadedFiles = [];
<ide>
<add> /**
<add> * The HTTP protocol version used.
<add> *
<add> * @var string|null
<add> */
<add> protected $protocol;
<add>
<ide> /**
<ide> * Wrapper method to create a new request from PHP superglobals.
<ide> *
<ide> public function withParsedBody($data)
<ide> return $new;
<ide> }
<ide>
<add> /**
<add> * Retrieves the HTTP protocol version as a string.
<add> *
<add> * @return string HTTP protocol version.
<add> */
<add> public function getProtocolVersion()
<add> {
<add> if ($this->protocol) {
<add> return $this->protocol;
<add> }
<add> // Lazily populate this data as it is generally not used.
<add> preg_match('/^HTTP\/([\d.]+)$/', $this->env('SERVER_PROTOCOL'), $match);
<add> $protocol = '1.1';
<add> if (isset($match[1])) {
<add> $protocol = $match[1];
<add> }
<add> $this->protocol = $protocol;
<add> return $this->protocol;
<add> }
<add>
<add> /**
<add> * Return an instance with the specified HTTP protocol version.
<add> *
<add> * The version string MUST contain only the HTTP version number (e.g.,
<add> * "1.1", "1.0").
<add> *
<add> * @param string $version HTTP protocol version
<add> * @return static
<add> */
<add> public function withProtocolVersion($version)
<add> {
<add> if (!preg_match('/^(1\.[01]|2)$/', $version)) {
<add> throw new InvalidArgumentException("Unsupported protocol version '{$version}' provided");
<add> }
<add> $new = clone $this;
<add> $new->protocol = $version;
<add> return $new;
<add> }
<add>
<ide> /**
<ide> * Get/Set value from the request's environment data.
<ide> * Fallback to using env() if key not set in $environment property.
<ide><path>tests/TestCase/Network/RequestTest.php
<ide> public function testWithMethodInvalid()
<ide> $request->withMethod('no good');
<ide> }
<ide>
<add> /**
<add> * Test getProtocolVersion()
<add> *
<add> * @return void
<add> */
<add> public function testGetProtocolVersion()
<add> {
<add> $request = new Request();
<add> $this->assertEquals('1.1', $request->getProtocolVersion());
<add>
<add> // SERVER var.
<add> $request = new Request([
<add> 'environment' => ['SERVER_PROTOCOL' => 'HTTP/1.0']
<add> ]);
<add> $this->assertEquals('1.0', $request->getProtocolVersion());
<add> }
<add>
<add> /**
<add> * Test withProtocolVersion()
<add> *
<add> * @return void
<add> */
<add> public function testWithProtocolVersion()
<add> {
<add> $request = new Request();
<add> $new = $request->withProtocolVersion('1.0');
<add> $this->assertNotSame($new, $request);
<add> $this->assertEquals('1.1', $request->getProtocolVersion());
<add> $this->assertEquals('1.0', $new->getProtocolVersion());
<add> }
<add>
<add> /**
<add> * Test withProtocolVersion() and invalid data
<add> *
<add> * @expectedException InvalidArgumentException
<add> * @expectedExceptionMessage Unsupported protocol version 'no good' provided
<add> * @return void
<add> */
<add> public function testWithProtocolVersionInvalid()
<add> {
<add> $request = new Request();
<add> $request->withProtocolVersion('no good');
<add> }
<add>
<ide> /**
<ide> * Test host retrieval.
<ide> * | 2 |
Java | Java | remove timeouts from react instance loading | 29238eb3eba0c4d73e4a0e67f2d7de72bf0a1b83 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/CatalystInstanceImpl.java
<ide> import java.util.Collection;
<ide> import java.util.concurrent.Callable;
<ide> import java.util.concurrent.CopyOnWriteArrayList;
<del>import java.util.concurrent.TimeUnit;
<ide> import java.util.concurrent.atomic.AtomicInteger;
<ide>
<ide> import com.facebook.common.logging.FLog;
<add>import com.facebook.infer.annotation.Assertions;
<add>import com.facebook.proguard.annotations.DoNotStrip;
<ide> import com.facebook.react.bridge.queue.CatalystQueueConfiguration;
<ide> import com.facebook.react.bridge.queue.CatalystQueueConfigurationImpl;
<ide> import com.facebook.react.bridge.queue.CatalystQueueConfigurationSpec;
<ide> import com.facebook.react.bridge.queue.QueueThreadExceptionHandler;
<del>import com.facebook.proguard.annotations.DoNotStrip;
<ide> import com.facebook.react.common.ReactConstants;
<ide> import com.facebook.react.common.annotations.VisibleForTesting;
<del>import com.facebook.infer.annotation.Assertions;
<ide> import com.facebook.systrace.Systrace;
<ide> import com.facebook.systrace.TraceListener;
<ide>
<ide> @DoNotStrip
<ide> public class CatalystInstanceImpl implements CatalystInstance {
<ide>
<del> private static final int BRIDGE_SETUP_TIMEOUT_MS = 30000;
<del> private static final int LOAD_JS_BUNDLE_TIMEOUT_MS = 30000;
<del>
<ide> private static final AtomicInteger sNextInstanceIdForTrace = new AtomicInteger(1);
<ide>
<ide> // Access from any thread
<ide> public ReactBridge call() throws Exception {
<ide> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE);
<ide> }
<ide> }
<del> }).get(BRIDGE_SETUP_TIMEOUT_MS, TimeUnit.MILLISECONDS);
<add> }).get();
<ide> } catch (Exception t) {
<ide> throw new RuntimeException("Failed to initialize bridge", t);
<ide> }
<ide> public Boolean call() throws Exception {
<ide>
<ide> return true;
<ide> }
<del> }).get(LOAD_JS_BUNDLE_TIMEOUT_MS, TimeUnit.MILLISECONDS);
<add> }).get();
<ide> } catch (Exception t) {
<ide> throw new RuntimeException(t);
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/common/futures/SimpleSettableFuture.java
<ide> public void set(T result) {
<ide> }
<ide>
<ide> /**
<del> * Sets the eception. If another thread has called {@link #get}, they will immediately receive the
<del> * exception. set or setException must only be called once.
<add> * Sets the exception. If another thread has called {@link #get}, they will immediately receive
<add> * the exception. set or setException must only be called once.
<ide> */
<ide> public void setException(Exception exception) {
<ide> checkNotSet();
<ide> public boolean isDone() {
<ide> return mReadyLatch.getCount() == 0;
<ide> }
<ide>
<del> @Deprecated
<ide> @Override
<del> public T get() throws InterruptedException, ExecutionException {
<del> throw new UnsupportedOperationException("Must use a timeout");
<add> public @Nullable T get() throws InterruptedException, ExecutionException {
<add> mReadyLatch.await();
<add> if (mException != null) {
<add> throw new ExecutionException(mException);
<add> }
<add>
<add> return mResult;
<ide> }
<ide>
<ide> /**
<ide> public T get() throws InterruptedException, ExecutionException {
<ide> @Override
<ide> public @Nullable T get(long timeout, TimeUnit unit) throws
<ide> InterruptedException, ExecutionException, TimeoutException {
<del> try {
<del> if (!mReadyLatch.await(timeout, unit)) {
<del> throw new TimeoutException("Timed out waiting for result");
<del> }
<del> } catch (InterruptedException e) {
<del> throw new RuntimeException(e);
<add> if (!mReadyLatch.await(timeout, unit)) {
<add> throw new TimeoutException("Timed out waiting for result");
<ide> }
<ide> if (mException != null) {
<ide> throw new ExecutionException(mException); | 2 |
PHP | PHP | apply fixes from styleci | 6ee81be055a0b7fc6d5c2c5c3566a897707c8250 | <ide><path>tests/Integration/Routing/UrlSigningTest.php
<ide> public function testSignedMiddlewareIgnoringParameter()
<ide>
<ide> protected function createValidateSignatureMiddleware(array $ignore)
<ide> {
<del> return new class ($ignore) extends ValidateSignature {
<add> return new class($ignore) extends ValidateSignature
<add> {
<ide> public function __construct(array $ignore)
<ide> {
<ide> $this->ignore = $ignore; | 1 |
Javascript | Javascript | consolidate assertions in ipv6only test | c37b39282bf6ad26a9505f311277303e18e4968f | <ide><path>test/parallel/test-cluster-net-listen-ipv6only-rr.js
<ide> if (cluster.isMaster) {
<ide> if (!address) {
<ide> address = workerAddress;
<ide> } else {
<del> assert.strictEqual(address.addressType, workerAddress.addressType);
<del> assert.strictEqual(address.host, workerAddress.host);
<del> assert.strictEqual(address.port, workerAddress.port);
<add> assert.deepStrictEqual(workerAddress, address);
<ide> }
<ide> countdown.dec();
<ide> })); | 1 |
Javascript | Javascript | escape all 24 mixed pieces, not only first 12 | be2468e571ba4cfd723e27c128831d843d1bbac6 | <ide><path>src/lib/units/month.js
<ide> function computeMonthsParse () {
<ide> longPieces[i] = regexEscape(longPieces[i]);
<ide> mixedPieces[i] = regexEscape(mixedPieces[i]);
<ide> }
<add> for (; i < 24; i++) {
<add> mixedPieces[i] = regexEscape(mixedPieces[i]);
<add> }
<ide>
<ide> this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
<ide> this._monthsShortRegex = this._monthsRegex; | 1 |
Java | Java | fix modals when using nodes | f8d623ca3a4c8ccbfa34fbe3d0a03c3935619dd3 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/FlatReactModalShadowNode.java
<add>/**
<add> * Copyright (c) 2015-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>
<add>package com.facebook.react.flat;
<add>
<add>import android.annotation.TargetApi;
<add>import android.content.Context;
<add>import android.graphics.Point;
<add>import android.view.Display;
<add>import android.view.Surface;
<add>import android.view.WindowManager;
<add>
<add>import com.facebook.csslayout.CSSNode;
<add>
<add>/**
<add> * FlatReactModalShadowNode
<add> *
<add> * This is a Nodes specific shadow node for modals. This is required because we wrap any
<add> * non-FlatShadowNode node in a NativeViewWrapper. In the case of a modal shadow node, we need
<add> * to treat it as its own node so that we can add the custom measurement behavior that is there
<add> * in the non-Nodes version when we add a child.
<add> *
<add> * {@see {@link com.facebook.react.views.modal.ModalHostShadowNode}}
<add> */
<add>class FlatReactModalShadowNode extends FlatShadowNode implements AndroidView {
<add>
<add> private final Point mMinPoint = new Point();
<add> private final Point mMaxPoint = new Point();
<add> private boolean mPaddingChanged;
<add>
<add> FlatReactModalShadowNode() {
<add> forceMountToView();
<add> forceMountChildrenToView();
<add> }
<add>
<add> /**
<add> * We need to set the styleWidth and styleHeight of the one child (represented by the <View/>
<add> * within the <RCTModalHostView/> in Modal.js. This needs to fill the entire window.
<add> */
<add> @Override
<add> @TargetApi(16)
<add> public void addChildAt(CSSNode child, int i) {
<add> super.addChildAt(child, i);
<add>
<add> Context context = getThemedContext();
<add> WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
<add> Display display = wm.getDefaultDisplay();
<add> // getCurrentSizeRange will return the min and max width and height that the window can be
<add> display.getCurrentSizeRange(mMinPoint, mMaxPoint);
<add>
<add> int width, height;
<add> int rotation = display.getRotation();
<add> if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) {
<add> // If we are vertical the width value comes from min width and height comes from max height
<add> width = mMinPoint.x;
<add> height = mMaxPoint.y;
<add> } else {
<add> // If we are horizontal the width value comes from max width and height comes from min height
<add> width = mMaxPoint.x;
<add> height = mMinPoint.y;
<add> }
<add> child.setStyleWidth(width);
<add> child.setStyleHeight(height);
<add> }
<add>
<add> @Override
<add> public boolean needsCustomLayoutForChildren() {
<add> return false;
<add> }
<add>
<add> @Override
<add> public boolean isPaddingChanged() {
<add> return mPaddingChanged;
<add> }
<add>
<add> @Override
<add> public void resetPaddingChanged() {
<add> mPaddingChanged = false;
<add> }
<add>
<add> @Override
<add> public void setPadding(int spacingType, float padding) {
<add> if (getPadding().set(spacingType, padding)) {
<add> mPaddingChanged = true;
<add> dirty();
<add> }
<add> }
<add>}
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/FlatUIImplementation.java
<ide> public static FlatUIImplementation createInstance(
<ide> viewManagers.add(new RCTTextInlineImageManager());
<ide> viewManagers.add(new RCTImageViewManager());
<ide> viewManagers.add(new RCTTextInputManager());
<add> viewManagers.add(new RCTModalHostManager(reactContext));
<ide>
<ide> ViewManagerRegistry viewManagerRegistry = new ViewManagerRegistry(viewManagers);
<ide> FlatNativeViewHierarchyManager nativeViewHierarchyManager = new FlatNativeViewHierarchyManager(
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/RCTModalHostManager.java
<add>/**
<add> * Copyright (c) 2015-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>
<add>package com.facebook.react.flat;
<add>
<add>import com.facebook.react.bridge.ReactApplicationContext;
<add>import com.facebook.react.uimanager.LayoutShadowNode;
<add>import com.facebook.react.views.modal.ReactModalHostManager;
<add>
<add>/* package */ class RCTModalHostManager extends ReactModalHostManager {
<add>
<add> /* package */ RCTModalHostManager(ReactApplicationContext context) {
<add> super(context);
<add> }
<add>
<add> @Override
<add> public LayoutShadowNode createShadowNodeInstance() {
<add> return new FlatReactModalShadowNode();
<add> }
<add>
<add> @Override
<add> public Class<? extends LayoutShadowNode> getShadowNodeClass() {
<add> return FlatReactModalShadowNode.class;
<add> }
<add>} | 3 |
PHP | PHP | add fulltablename tests with empty schemaname | b1aae5b5ab92e0f77b629b488aa6db209c9858c8 | <ide><path>lib/Cake/Test/Case/Model/Datasource/DboSourceTest.php
<ide> public function testFullTablePermutations() {
<ide> $Article->tablePrefix = '';
<ide> $result = $this->testDb->fullTableName($Article, true, false);
<ide> $this->assertEquals($result, '`with spaces`');
<add>
<add> $this->loadFixtures('Article');
<add> $Article->useTable = $Article->table = 'articles';
<add> $Article->setDataSource('test');
<add> $testdb = $Article->getDataSource();
<add> $result = $testdb->fullTableName($Article, false, true);
<add> $this->assertEquals($testdb->getSchemaName() . '.articles', $result);
<add>
<add> // tests for empty schemaName
<add> $noschema = ConnectionManager::create('noschema', array(
<add> 'datasource' => 'DboTestSource'
<add> ));
<add> $Article->setDataSource('noschema');
<add> $Article->schemaName = null;
<add> $result = $noschema->fullTableName($Article, false, true);
<add> $this->assertEquals('articles', $result);
<ide> }
<ide>
<ide> /** | 1 |
Javascript | Javascript | handle boolean attributes in `@` bindings | db5e0ffe124ac588f01ef0fe79efebfa72f5eec7 | <ide><path>src/ng/compile.js
<ide> function $CompileProvider($provide, $$sanitizeUriProvider) {
<ide> }
<ide> });
<ide> attrs.$$observers[attrName].$$scope = scope;
<del> if (isString(attrs[attrName])) {
<add> lastValue = attrs[attrName];
<add> if (isString(lastValue)) {
<ide> // If the attribute has been provided then we trigger an interpolation to ensure
<ide> // the value is there for use in the link fn
<del> destination[scopeName] = $interpolate(attrs[attrName])(scope);
<add> destination[scopeName] = $interpolate(lastValue)(scope);
<add> } else if (isBoolean(lastValue)) {
<add> // If the attributes is one of the BOOLEAN_ATTR then Angular will have converted
<add> // the value to boolean rather than a string, so we special case this situation
<add> destination[scopeName] = lastValue;
<ide> }
<ide> break;
<ide>
<ide><path>test/ng/compileSpec.js
<ide> describe('$compile', function() {
<ide> expect(element.isolateScope()['watch']).toBe('watch');
<ide> })
<ide> );
<add>
<add> it('should handle @ bindings on BOOLEAN attributes', function() {
<add> var checkedVal;
<add> module(function($compileProvider) {
<add> $compileProvider.directive('test', function() {
<add> return {
<add> scope: { checked: '@' },
<add> link: function(scope, element, attrs) {
<add> checkedVal = scope.checked;
<add> }
<add> };
<add> });
<add> });
<add> inject(function($compile, $rootScope) {
<add> $compile('<input test checked="checked">')($rootScope);
<add> expect(checkedVal).toEqual(true);
<add> });
<add> });
<ide> });
<ide>
<ide> | 2 |
Javascript | Javascript | clarify trie utils | e38739ce58770525bd93356e0a619f47e9b601f7 | <ide><path>dist/Immutable.dev.js
<ide> var $Sequence = Sequence;
<ide> return this.slice(0, -1);
<ide> },
<ide> has: function(searchKey) {
<del> return this.get(searchKey, SENTINEL) !== SENTINEL;
<add> return this.get(searchKey, NOTHING) !== NOTHING;
<ide> },
<ide> get: function(searchKey, notFoundValue) {
<ide> return this.find((function(_, key) {
<ide> var $Sequence = Sequence;
<ide> contains: function(searchValue) {
<ide> return this.find((function(value) {
<ide> return is(value, searchValue);
<del> }), null, SENTINEL) !== SENTINEL;
<add> }), null, NOTHING) !== NOTHING;
<ide> },
<ide> find: function(predicate, thisArg, notFoundValue) {
<ide> var foundValue = notFoundValue;
<ide> var $Sequence = Sequence;
<ide> var groups = OrderedMap.empty().withMutations((function(map) {
<ide> seq.forEach((function(value, key, collection) {
<ide> var groupKey = mapper(value, key, collection);
<del> var group = map.get(groupKey, SENTINEL);
<del> if (group === SENTINEL) {
<add> var group = map.get(groupKey, NOTHING);
<add> if (group === NOTHING) {
<ide> group = [];
<ide> map.set(groupKey, group);
<ide> }
<ide> var $IndexedSequence = IndexedSequence;
<ide> var groups = OrderedMap.empty().withMutations((function(map) {
<ide> seq.forEach((function(value, index, collection) {
<ide> var groupKey = mapper(value, index, collection);
<del> var group = map.get(groupKey, SENTINEL);
<del> if (group === SENTINEL) {
<add> var group = map.get(groupKey, NOTHING);
<add> if (group === NOTHING) {
<ide> group = new Array(maintainIndices ? seq.length : 0);
<ide> map.set(groupKey, group);
<ide> }
<ide> function makeIndexedSequence(parent) {
<ide> return newSequence;
<ide> }
<ide> function getInDeepSequence(seq, keyPath, notFoundValue, pathOffset) {
<del> var nested = seq.get ? seq.get(keyPath[pathOffset], SENTINEL) : SENTINEL;
<del> if (nested === SENTINEL) {
<add> var nested = seq.get ? seq.get(keyPath[pathOffset], NOTHING) : NOTHING;
<add> if (nested === NOTHING) {
<ide> return notFoundValue;
<ide> }
<ide> if (++pathOffset === keyPath.length) {
<ide> function _updateCursor(cursor, changeFn, changeKey) {
<ide> var SHIFT = 5;
<ide> var SIZE = 1 << SHIFT;
<ide> var MASK = SIZE - 1;
<del>var SENTINEL = {};
<add>var NOTHING = {};
<ide> function OwnerID() {}
<ide> var Map = function Map(sequence) {
<ide> if (sequence && sequence.constructor === $Map) {
<ide> var $Map = Map;
<ide> __deepEqual: function(other) {
<ide> var self = this;
<ide> return other.every((function(v, k) {
<del> return is(self.get(k, SENTINEL), v);
<add> return is(self.get(k, NOTHING), v);
<ide> }));
<ide> },
<ide> __ensureOwner: function(ownerID) {
<ide> function mergeIntoCollectionWith(collection, merger, seqs) {
<ide> }
<ide> return collection.withMutations((function(collection) {
<ide> var mergeIntoMap = merger ? (function(value, key) {
<del> var existing = collection.get(key, SENTINEL);
<del> collection.set(key, existing === SENTINEL ? value : merger(existing, value));
<add> var existing = collection.get(key, NOTHING);
<add> collection.set(key, existing === NOTHING ? value : merger(existing, value));
<ide> }) : (function(value, key) {
<ide> collection.set(key, value);
<ide> });
<ide> function mergeIntoCollectionWith(collection, merger, seqs) {
<ide> }
<ide> function updateInDeepMap(collection, keyPath, updater, pathOffset) {
<ide> var key = keyPath[pathOffset];
<del> var nested = collection.get ? collection.get(key, SENTINEL) : SENTINEL;
<del> if (nested === SENTINEL) {
<add> var nested = collection.get ? collection.get(key, NOTHING) : NOTHING;
<add> if (nested === NOTHING) {
<ide> nested = Map.empty();
<ide> }
<ide> invariant(collection.set, 'updateIn with invalid keyPath');
<ide> var $Vector = Vector;
<ide> return setVectorBounds(vect, 0, index + 1).set(index, value);
<ide> }));
<ide> }
<del> if (this.get(index, SENTINEL) === value) {
<add> if (this.get(index, NOTHING) === value) {
<ide> return this;
<ide> }
<ide> index = rawIndex(index, this._origin);
<ide><path>src/Map.js
<ide> import "invariant"
<ide> import "Cursor"
<ide> import "TrieUtils"
<ide> /* global Sequence, is, invariant, Cursor,
<del> SHIFT, MASK, SENTINEL, OwnerID */
<add> SHIFT, MASK, NOTHING, OwnerID */
<ide> /* exported Map, MapPrototype */
<ide>
<ide>
<ide> class Map extends Sequence {
<ide> // Using Sentinel here ensures that a missing key is not interpretted as an
<ide> // existing key set to be null.
<ide> var self = this;
<del> return other.every((v, k) => is(self.get(k, SENTINEL), v));
<add> return other.every((v, k) => is(self.get(k, NOTHING), v));
<ide> }
<ide>
<ide> __ensureOwner(ownerID) {
<ide> function mergeIntoCollectionWith(collection, merger, seqs) {
<ide> return collection.withMutations(collection => {
<ide> var mergeIntoMap = merger ?
<ide> (value, key) => {
<del> var existing = collection.get(key, SENTINEL);
<add> var existing = collection.get(key, NOTHING);
<ide> collection.set(
<del> key, existing === SENTINEL ? value : merger(existing, value)
<add> key, existing === NOTHING ? value : merger(existing, value)
<ide> );
<ide> } :
<ide> (value, key) => {
<ide> function mergeIntoCollectionWith(collection, merger, seqs) {
<ide>
<ide> function updateInDeepMap(collection, keyPath, updater, pathOffset) {
<ide> var key = keyPath[pathOffset];
<del> var nested = collection.get ? collection.get(key, SENTINEL) : SENTINEL;
<del> if (nested === SENTINEL) {
<add> var nested = collection.get ? collection.get(key, NOTHING) : NOTHING;
<add> if (nested === NOTHING) {
<ide> nested = Map.empty();
<ide> }
<ide> invariant(collection.set, 'updateIn with invalid keyPath');
<ide><path>src/Sequence.js
<ide> */
<ide>
<ide> /* Sequence has implicit lazy dependencies */
<del>/* global is, Map, OrderedMap, Vector, Set, SENTINEL, invariant */
<add>/* global is, Map, OrderedMap, Vector, Set, NOTHING, invariant */
<ide> /* exported Sequence, IndexedSequence */
<ide>
<ide>
<ide> class Sequence {
<ide> }
<ide>
<ide> has(searchKey) {
<del> return this.get(searchKey, SENTINEL) !== SENTINEL;
<add> return this.get(searchKey, NOTHING) !== NOTHING;
<ide> }
<ide>
<ide> get(searchKey, notFoundValue) {
<ide> class Sequence {
<ide> }
<ide>
<ide> contains(searchValue) {
<del> return this.find(value => is(value, searchValue), null, SENTINEL) !== SENTINEL;
<add> return this.find(value => is(value, searchValue), null, NOTHING) !== NOTHING;
<ide> }
<ide>
<ide> find(predicate, thisArg, notFoundValue) {
<ide> class Sequence {
<ide> var groups = OrderedMap.empty().withMutations(map => {
<ide> seq.forEach((value, key, collection) => {
<ide> var groupKey = mapper(value, key, collection);
<del> var group = map.get(groupKey, SENTINEL);
<del> if (group === SENTINEL) {
<add> var group = map.get(groupKey, NOTHING);
<add> if (group === NOTHING) {
<ide> group = [];
<ide> map.set(groupKey, group);
<ide> }
<ide> class IndexedSequence extends Sequence {
<ide> var groups = OrderedMap.empty().withMutations(map => {
<ide> seq.forEach((value, index, collection) => {
<ide> var groupKey = mapper(value, index, collection);
<del> var group = map.get(groupKey, SENTINEL);
<del> if (group === SENTINEL) {
<add> var group = map.get(groupKey, NOTHING);
<add> if (group === NOTHING) {
<ide> group = new Array(maintainIndices ? seq.length : 0);
<ide> map.set(groupKey, group);
<ide> }
<ide> function makeIndexedSequence(parent) {
<ide> }
<ide>
<ide> function getInDeepSequence(seq, keyPath, notFoundValue, pathOffset) {
<del> var nested = seq.get ? seq.get(keyPath[pathOffset], SENTINEL) : SENTINEL;
<del> if (nested === SENTINEL) {
<add> var nested = seq.get ? seq.get(keyPath[pathOffset], NOTHING) : NOTHING;
<add> if (nested === NOTHING) {
<ide> return notFoundValue;
<ide> }
<ide> if (++pathOffset === keyPath.length) {
<ide><path>src/TrieUtils.js
<ide> * of patent rights can be found in the PATENTS file in the same directory.
<ide> */
<ide>
<del>/* exported SHIFT, SIZE, MASK, SENTINEL, OwnerID */
<add>/* exported SHIFT, SIZE, MASK, NOTHING, OwnerID */
<ide>
<add>// Constants describing the size of trie nodes.
<ide> var SHIFT = 5; // Resulted in best performance after ______?
<ide> var SIZE = 1 << SHIFT;
<ide> var MASK = SIZE - 1;
<del>var SENTINEL = {};
<add>
<add>// A consistent shared value representing "not set" which equals nothing other
<add>// than itself, and nothing that could be provided externally.
<add>var NOTHING = {};
<add>
<add>// A function which returns a value representing an "owner" for transient writes
<add>// to tries. The return value will only ever equal itself, and will not equal
<add>// the return of any subsequent call of this function.
<ide> function OwnerID() {}
<ide><path>src/Vector.js
<ide> import "Map"
<ide> import "TrieUtils"
<ide> /* global Sequence, IndexedSequence, is, invariant,
<ide> MapPrototype, mergeIntoCollectionWith, deepMerger,
<del> SHIFT, SIZE, MASK, SENTINEL, OwnerID */
<add> SHIFT, SIZE, MASK, NOTHING, OwnerID */
<ide> /* exported Vector, VectorPrototype */
<ide>
<ide>
<ide> class Vector extends IndexedSequence {
<ide> );
<ide> }
<ide>
<del> if (this.get(index, SENTINEL) === value) {
<add> if (this.get(index, NOTHING) === value) {
<ide> return this;
<ide> }
<ide> | 5 |
Javascript | Javascript | use round() instead of parseint() to be consistent | 571f9baf99a1493db43b038fb4db2afbf44c513d | <ide><path>moment.js
<ide> },
<ide>
<ide> unixValueOf : function () {
<del> return parseInt(this.valueOf() / 1000, 10);
<add> return round(this.valueOf() / 1000);
<ide> },
<ide>
<ide> local : function () { | 1 |
Mixed | Javascript | add local family | d4423d63cd8821d4d8013bd8a862063ac2b32fa7 | <ide><path>doc/api/net.md
<ide> TCP server, the argument is as follows, otherwise the argument is `undefined`.
<ide> * `data` {Object} The argument passed to event listener.
<ide> * `localAddress` {string} Local address.
<ide> * `localPort` {number} Local port.
<add> * `localFamily` {string} Local family.
<ide> * `remoteAddress` {string} Remote address.
<ide> * `remotePort` {number} Remote port.
<ide> * `remoteFamily` {string} Remote IP family. `'IPv4'` or `'IPv6'`.
<ide> added: v0.9.6
<ide>
<ide> The numeric representation of the local port. For example, `80` or `21`.
<ide>
<add>### `socket.localFamily`
<add>
<add><!-- YAML
<add>added: REPLACEME
<add>-->
<add>
<add>* {string}
<add>
<add>The string representation of the local IP family. `'IPv4'` or `'IPv6'`.
<add>
<ide> ### `socket.pause()`
<ide>
<ide> * Returns: {net.Socket} The socket itself.
<ide><path>lib/net.js
<ide> protoGetter('localPort', function localPort() {
<ide> return this._getsockname().port;
<ide> });
<ide>
<add>protoGetter('localFamily', function localFamily() {
<add> return this._getsockname().family;
<add>});
<ide>
<ide> Socket.prototype[kAfterAsyncWrite] = function() {
<ide> this[kLastWriteQueueSize] = 0;
<ide> function onconnection(err, clientHandle) {
<ide> clientHandle.getsockname(localInfo);
<ide> data.localAddress = localInfo.address;
<ide> data.localPort = localInfo.port;
<add> data.localFamily = localInfo.family;
<ide> }
<ide> if (clientHandle.getpeername) {
<ide> const remoteInfo = ObjectCreate(null);
<ide><path>test/parallel/test-net-local-address-port.js
<ide> const net = require('net');
<ide> const server = net.createServer(common.mustCall(function(socket) {
<ide> assert.strictEqual(socket.localAddress, common.localhostIPv4);
<ide> assert.strictEqual(socket.localPort, this.address().port);
<add> assert.strictEqual(socket.localFamily, this.address().family);
<ide> socket.on('end', function() {
<ide> server.close();
<ide> }); | 3 |
Ruby | Ruby | give a message to `#test_duplicable` assertion | 2aac4e4392821e72bd7a2626e78b3797c74de9c2 | <ide><path>activesupport/test/core_ext/object/duplicable_test.rb
<ide> def test_duplicable
<ide> "* https://github.com/rubinius/rubinius/issues/3089"
<ide>
<ide> RAISE_DUP.each do |v|
<del> assert !v.duplicable?
<add> assert !v.duplicable?, "#{ v.inspect } should not be duplicable"
<ide> assert_raises(TypeError, v.class.name) { v.dup }
<ide> end
<ide> | 1 |
Ruby | Ruby | add a desc field to formula | 86365470e6a2a02c1a54f75fae818b779375b079 | <ide><path>Library/Homebrew/formula.rb
<ide> def bottle
<ide> Bottle.new(self, bottle_specification) if bottled?
<ide> end
<ide>
<add> # The description of the software.
<add> # @see .desc
<add> def desc
<add> self.class.desc
<add> end
<add>
<ide> # The homepage for the software.
<ide> # @see .homepage
<ide> def homepage
<ide> def recursive_requirements(&block)
<ide> def to_hash
<ide> hsh = {
<ide> "name" => name,
<add> "desc" => desc,
<ide> "homepage" => homepage,
<ide> "versions" => {
<ide> "stable" => (stable.version.to_s if stable),
<ide> class << self
<ide> # @private
<ide> attr_reader :keg_only_reason
<ide>
<add> # @!attribute [w]
<add> # A one-line description of the software. Used by users to get an overview
<add> # of the software and Homebrew maintainers.
<add> # Shows when running `brew info`.
<add> attr_rw :desc
<add>
<ide> # @!attribute [w]
<ide> # The homepage for the software. Used by users to get more information
<ide> # about the software and Homebrew maintainers as a point of contact for | 1 |
Go | Go | remove jobs from stats | 65a056345cec1b85bd41ed70ee814894709ee6c0 | <ide><path>api/server/server.go
<ide> func getContainersStats(eng *engine.Engine, version version.Version, w http.Resp
<ide> if vars == nil {
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<del> name := vars["name"]
<del> job := eng.Job("container_stats", name)
<del> streamJSON(job, w, true)
<del> return job.Run()
<add>
<add> d := getDaemon(eng)
<add>
<add> return d.ContainerStats(vars["name"], utils.NewWriteFlusher(w))
<ide> }
<ide>
<ide> func getContainersLogs(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide><path>daemon/daemon.go
<ide> func (daemon *Daemon) Install(eng *engine.Engine) error {
<ide> for name, method := range map[string]engine.Handler{
<ide> "commit": daemon.ContainerCommit,
<ide> "container_inspect": daemon.ContainerInspect,
<del> "container_stats": daemon.ContainerStats,
<ide> "create": daemon.ContainerCreate,
<ide> "export": daemon.ContainerExport,
<ide> "info": daemon.CmdInfo,
<ide><path>daemon/stats.go
<ide> package daemon
<ide>
<ide> import (
<ide> "encoding/json"
<add> "io"
<ide>
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/daemon/execdriver"
<del> "github.com/docker/docker/engine"
<ide> "github.com/docker/libcontainer"
<ide> "github.com/docker/libcontainer/cgroups"
<ide> )
<ide>
<del>func (daemon *Daemon) ContainerStats(job *engine.Job) error {
<del> updates, err := daemon.SubscribeToContainerStats(job.Args[0])
<add>func (daemon *Daemon) ContainerStats(name string, out io.Writer) error {
<add> updates, err := daemon.SubscribeToContainerStats(name)
<ide> if err != nil {
<ide> return err
<ide> }
<del> enc := json.NewEncoder(job.Stdout)
<add> enc := json.NewEncoder(out)
<ide> for v := range updates {
<ide> update := v.(*execdriver.ResourceStats)
<ide> ss := convertToAPITypes(update.Stats)
<ide> func (daemon *Daemon) ContainerStats(job *engine.Job) error {
<ide> ss.CpuStats.SystemUsage = update.SystemUsage
<ide> if err := enc.Encode(ss); err != nil {
<ide> // TODO: handle the specific broken pipe
<del> daemon.UnsubscribeToContainerStats(job.Args[0], updates)
<add> daemon.UnsubscribeToContainerStats(name, updates)
<ide> return err
<ide> }
<ide> } | 3 |
Javascript | Javascript | change the way we test this | 026782921145e492bfb1660f1d5cee763fa0ca78 | <ide><path>spec/main-process/atom-application.test.js
<ide> import dedent from 'dedent'
<ide> import electron from 'electron'
<ide> import fs from 'fs-plus'
<ide> import path from 'path'
<add>import sinon from 'sinon'
<ide> import AtomApplication from '../../src/main-process/atom-application'
<ide> import parseCommandLine from '../../src/main-process/parse-command-line'
<ide> import {timeoutPromise, conditionPromise, emitterEventPromise} from '../async-spec-helpers'
<ide> describe('AtomApplication', function () {
<ide> await focusWindow(window2)
<ide>
<ide> const fileA = path.join(dirAPath, 'file-a')
<add> const uriA = `atom://core/open/file?filename=${fileA}`
<ide> const fileB = path.join(dirBPath, 'file-b')
<add> const uriB = `atom://core/open/file?filename=${fileB}`
<ide>
<del> atomApplication.launch(parseCommandLine(['--uri-handler', `atom://core/open/file?filename=${fileA}`]))
<del> await conditionPromise(() => atomApplication.getLastFocusedWindow() === window1, `window1 to be focused from ${fileA}`)
<add> sinon.spy(window1, 'sendURIMessage')
<add> sinon.spy(window2, 'sendURIMessage')
<ide>
<del> atomApplication.launch(parseCommandLine(['--uri-handler', `atom://core/open/file?filename=${fileB}`]))
<del> await conditionPromise(() => atomApplication.getLastFocusedWindow() === window2, `window2 to be focused from ${fileB}`)
<add> atomApplication.launch(parseCommandLine(['--uri-handler', uriA]))
<add> await conditionPromise(() => window1.sendURIMessage.calledWith(uriA), `window1 to be focused from ${fileA}`)
<add>
<add> atomApplication.launch(parseCommandLine(['--uri-handler', uriB]))
<add> await conditionPromise(() => window2.sendURIMessage.calledWith(uriB), `window2 to be focused from ${fileB}`)
<ide> })
<ide> })
<ide> }) | 1 |
PHP | PHP | add a formal interface for fixture state managers | 651d050ed1a39e80b4b7a7588342d314a79f7abf | <ide><path>src/TestSuite/Fixture/StateResetStrategyInterface.php
<add><?php
<add>declare(strict_types=1);
<add>
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * For full copyright and license information, please see the LICENSE.txt
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> * @link https://cakephp.org CakePHP(tm) Project
<add> * @since 4.3.0
<add> * @license https://opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\TestSuite\Fixture;
<add>
<add>/**
<add> * Interface for fixture state management.
<add> *
<add> * This interface exposes hooks that run before and
<add> * after tests. This allows test database state to be 'prepared'
<add> * and 'cleaned up'.
<add> */
<add>interface StateResetStrategyInterface
<add>{
<add> /**
<add> * Before test hook
<add> *
<add> * Fired before each test is started.
<add> *
<add> * @param string $test The test that is going to run.
<add> * @return void
<add> */
<add> public function beforeTest(string $test): void;
<add>
<add> /**
<add> * After test hook
<add> *
<add> * Fired after each test is complete.
<add> *
<add> * @param string $test The test that was completed.
<add> * @return void
<add> */
<add> public function afterTest(string $test): void;
<add>}
<ide><path>src/TestSuite/Fixture/TransactionStrategy.php
<ide> * This strategy aims to gives good performance at the cost
<ide> * of not being able to query data in fixtures from another
<ide> * process.
<del> *
<del> * @TODO create a strategy interface
<ide> */
<del>class TransactionStrategy
<add>class TransactionStrategy implements StateResetStrategyInterface
<ide> {
<ide> /**
<ide> * Constructor.
<ide> protected function aliasConnections(bool $enableLogging): void
<ide> /**
<ide> * Before each test start a transaction.
<ide> *
<add> * @param string $test The test that was completed.
<ide> * @return void
<ide> */
<del> public function beforeTest(): void
<add> public function beforeTest(string $test): void
<ide> {
<ide> $connections = ConnectionManager::configured();
<ide> foreach ($connections as $connection) {
<ide> public function beforeTest(): void
<ide> * operations we should end up at a transaction depth of 0
<ide> * and we will rollback the root transaction started in beforeTest()
<ide> *
<add> * @param string $test The test that was completed.
<ide> * @return void
<ide> */
<del> public function afterTest(): void
<add> public function afterTest(string $test): void
<ide> {
<ide> $connections = ConnectionManager::configured();
<ide> foreach ($connections as $connection) {
<ide><path>src/TestSuite/Fixture/TruncationStrategy.php
<ide> * This mode also offers 'backwards compatible' behavior
<ide> * with the schema + data fixture system.
<ide> */
<del>class TruncationStrategy
<add>class TruncationStrategy implements StateResetStrategyInterface
<ide> {
<ide> /**
<ide> * Constructor.
<ide> protected function aliasConnections(bool $enableLogging): void
<ide> /**
<ide> * Before each test start a transaction.
<ide> *
<add> * @param string $test The test that was completed.
<ide> * @return void
<ide> */
<del> public function beforeTest(): void
<add> public function beforeTest(string $test): void
<ide> {
<ide> $connections = ConnectionManager::configured();
<ide> foreach ($connections as $connection) {
<ide> public function beforeTest(): void
<ide> *
<ide> * Implemented to satisfy the interface.
<ide> *
<add> * @param string $test The test that was completed.
<ide> * @return void
<ide> */
<del> public function afterTest(): void
<add> public function afterTest(string $test): void
<ide> {
<ide> // Do nothing
<ide> }
<ide><path>src/TestSuite/FixtureSchemaExtension.php
<ide>
<ide> use Cake\TestSuite\Fixture\FixtureDataManager;
<ide> use Cake\TestSuite\Fixture\FixtureLoader;
<add>use Cake\TestSuite\Fixture\StateResetStrategyInterface;
<ide> use Cake\TestSuite\Fixture\TransactionStrategy;
<add>use InvalidArgumentException;
<ide> use PHPUnit\Runner\AfterTestHook;
<ide> use PHPUnit\Runner\BeforeTestHook;
<add>use ReflectionClass;
<ide>
<ide> /**
<ide> * PHPUnit extension to integrate CakePHP's data-only fixtures.
<ide> class FixtureSchemaExtension implements
<ide> BeforeTestHook
<ide> {
<ide> /**
<del> * @var object
<add> * @var \Cake\TestSuite\Fixture\StateResetStrategyInterface
<ide> */
<ide> protected $state;
<ide>
<ide> /**
<ide> * Constructor.
<ide> *
<ide> * @param string $stateStrategy The state management strategy to use.
<add> * @psalm-param class-string<\Cake\TestSuite\Fixture\StateResetStrategyInterface> $stateStrategy
<ide> */
<ide> public function __construct(string $stateStrategy = TransactionStrategy::class)
<ide> {
<ide> $enableLogging = in_array('--debug', $_SERVER['argv'] ?? [], true);
<add> $class = new ReflectionClass($stateStrategy);
<add> if (!$class->implementsInterface(StateResetStrategyInterface::class)) {
<add> throw new InvalidArgumentException(sprintf(
<add> 'Invalid stateStrategy provided. State strategies must implement `%s`. Got `%s`.',
<add> StateResetStrategyInterface::class,
<add> $stateStrategy
<add> ));
<add> }
<ide> $this->state = new $stateStrategy($enableLogging);
<ide>
<ide> FixtureLoader::setInstance(new FixtureDataManager());
<ide> public function __construct(string $stateStrategy = TransactionStrategy::class)
<ide> */
<ide> public function executeBeforeTest(string $test): void
<ide> {
<del> $this->state->beforeTest();
<add> $this->state->beforeTest($test);
<ide> }
<ide>
<ide> /**
<ide> public function executeBeforeTest(string $test): void
<ide> */
<ide> public function executeAfterTest(string $test, float $time): void
<ide> {
<del> $this->state->afterTest();
<add> $this->state->afterTest($test);
<ide> }
<ide> }
<ide><path>tests/TestCase/TestSuite/Fixture/TransactionStrategyTest.php
<ide> public function testTransactionWrapping()
<ide> $users = TableRegistry::get('Users');
<ide>
<ide> $strategy = new TransactionStrategy();
<del> $strategy->beforeTest();
<add> $strategy->beforeTest(__METHOD__);
<ide> $user = $users->newEntity(['username' => 'testing', 'password' => 'secrets']);
<ide>
<ide> $users->save($user, ['atomic' => true]);
<ide> $this->assertNotEmpty($users->get($user->id), 'User should exist.');
<ide>
<ide> // Rollback and the user should be gone.
<del> $strategy->afterTest();
<add> $strategy->afterTest(__METHOD__);
<ide> $this->assertNull($users->findById($user->id)->first(), 'No user expected.');
<ide> }
<ide> }
<ide><path>tests/TestCase/TestSuite/Fixture/TruncationStrategyTest.php
<ide> public function testBeforeTestSimple()
<ide> $this->assertGreaterThan(0, $rowCount);
<ide>
<ide> $strategy = new TruncationStrategy();
<del> $strategy->beforeTest();
<add> $strategy->beforeTest(__METHOD__);
<ide>
<ide> $rowCount = $articles->find()->count();
<ide> $this->assertEquals(0, $rowCount); | 6 |
PHP | PHP | replace contents of service manifest atomically | 563e7d4e16d73eaafaf927fba2a29f5fbe783ede | <ide><path>src/Illuminate/Foundation/ProviderRepository.php
<ide> public function writeManifest($manifest)
<ide> throw new Exception('The bootstrap/cache directory must be present and writable.');
<ide> }
<ide>
<del> $this->files->put(
<add> $this->files->replace(
<ide> $this->manifestPath, '<?php return '.var_export($manifest, true).';'
<ide> );
<ide> | 1 |
Javascript | Javascript | use bind instead of apply in logger | 8a895e1b9559dfd846bdeb332dea12cb8279aa87 | <ide><path>packages/ember-metal/lib/logger.js
<ide> function consoleMethod(name) {
<ide> var method = typeof consoleObj === 'object' ? consoleObj[name] : null;
<ide>
<ide> if (method) {
<del> // Older IE doesn't support apply, but Chrome needs it
<del> if (typeof method.apply === 'function') {
<del> logToConsole = function() {
<del> method.apply(consoleObj, arguments);
<del> };
<add> // Older IE doesn't support bind, but Chrome needs it
<add> if (typeof method.bind === 'function') {
<add> logToConsole = method.bind(consoleObj);
<ide> logToConsole.displayName = 'console.' + name;
<ide> return logToConsole;
<ide> } else { | 1 |
Javascript | Javascript | add lao locale (lo) | 08dc83c7e1f29c4eb1b1df0b5215bdae9d287f79 | <ide><path>src/locale/lo.js
<add>//! moment.js locale configuration
<add>//! locale : lao (lo)
<add>//! author : Ryan Hart : https://github.com/ryanhart2
<add>
<add>import moment from '../moment';
<add>
<add>export default moment.defineLocale('lo', {
<add> months : 'ມັງກອນ_ກຸມພາ_ມີນາ_ເມສາ_ພຶດສະພາ_ມິຖຸນາ_ກໍລະກົດ_ສິງຫາ_ກັນຍາ_ຕຸລາ_ພະຈິກ_ທັນວາ'.split('_'),
<add> monthsShort : 'ມັງກອນ_ກຸມພາ_ມີນາ_ເມສາ_ພຶດສະພາ_ມິຖຸນາ_ກໍລະກົດ_ສິງຫາ_ກັນຍາ_ຕຸລາ_ພະຈິກ_ທັນວາ'.split('_'),
<add> weekdays : 'ອາທິດ_ຈັນ_ອັງຄານ_ພຸດ_ພະຫັດ_ສຸກ_ເສົາ'.split('_'),
<add> weekdaysShort : 'ທິດ_ຈັນ_ອັງຄານ_ພຸດ_ພະຫັດ_ສຸກ_ເສົາ'.split('_'),
<add> weekdaysMin : 'ທ_ຈ_ອຄ_ພ_ພຫ_ສກ_ສ'.split('_'),
<add> longDateFormat : {
<add> LT : 'HH:mm',
<add> LTS : 'HH:mm:ss',
<add> L : 'DD/MM/YYYY',
<add> LL : 'D MMMM YYYY',
<add> LLL : 'D MMMM YYYY HH:mm',
<add> LLLL : 'ວັນdddd D MMMM YYYY HH:mm'
<add> },
<add> meridiemParse: /ຕອນເຊົ້າ|ຕອນແລງ/,
<add> isPM: function (input) {
<add> return input === 'ຕອນແລງ';
<add> },
<add> meridiem : function (hour, minute, isLower) {
<add> if (hour < 12) {
<add> return 'ຕອນເຊົ້າ';
<add> } else {
<add> return 'ຕອນແລງ';
<add> }
<add> },
<add> calendar : {
<add> sameDay : '[ມື້ນີ້ເວລາ] LT',
<add> nextDay : '[ມື້ອື່ນເວລາ] LT',
<add> nextWeek : '[ວັນ]dddd[ໜ້າເວລາ] LT',
<add> lastDay : '[ມື້ວານນີ້ເວລາ] LT',
<add> lastWeek : '[ວັນ]dddd[ແລ້ວນີ້ເວລາ] LT',
<add> sameElse : 'L'
<add> },
<add> relativeTime : {
<add> future : 'ອີກ %s',
<add> past : '%sຜ່ານມາ',
<add> s : 'ບໍ່ເທົ່າໃດວິນາທີ',
<add> m : '1 ນາທີ',
<add> mm : '%d ນາທີ',
<add> h : '1 ຊົ່ວໂມງ',
<add> hh : '%d ຊົ່ວໂມງ',
<add> d : '1 ມື້',
<add> dd : '%d ມື້',
<add> M : '1 ເດືອນ',
<add> MM : '%d ເດືອນ',
<add> y : '1 ປີ',
<add> yy : '%d ປີ'
<add> },
<add> ordinalParse: /(ທີ່)\d{1,2}/,
<add> ordinal : function (number) {
<add> return 'ທີ່' + number;
<add> }
<add>});
<add>
<ide><path>src/test/locale/lo.js
<add>import {localeModule, test} from '../qunit';
<add>import moment from '../../moment';
<add>localeModule('lo');
<add>
<add>test('parse', function (assert) {
<add> var tests = 'ມັງກອນ ມັງກອນ_ກຸມພາ ກຸມພາ_ມີນາ ມີນາ_ເມສາ ເມສາ_ພຶດສະພາ ພຶດສະພາ_ມິຖຸນາ ມິຖຸນາ_ກໍລະກົດ ກໍລະກົດ_ສິງຫາ ສິງຫາ_ກັນຍາ ກັນຍາ_ຕຸລາ ຕຸລາ_ພະຈິກ ພະຈິກ_ທັນວາ ທັນວາ'.split('_'), i;
<add> function equalTest(input, mmm, i) {
<add> assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1));
<add> }
<add> for (i = 0; i < 12; i++) {
<add> tests[i] = tests[i].split(' ');
<add> equalTest(tests[i][0], 'MMM', i);
<add> equalTest(tests[i][1], 'MMM', i);
<add> equalTest(tests[i][0], 'MMMM', i);
<add> equalTest(tests[i][1], 'MMMM', i);
<add> equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i);
<add> equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i);
<add> equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i);
<add> equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i);
<add> }
<add>});
<add>
<add>test('format', function (assert) {
<add> var a = [
<add> ['dddd, MMMM Do YYYY, h:mm:ss a', 'ອາທິດ, ກຸມພາ ທີ່14 2010, 3:25:50 ຕອນແລງ'],
<add> ['ddd, hA', 'ທິດ, 3ຕອນແລງ'],
<add> ['M Mo MM MMMM MMM', '2 ທີ່2 02 ກຸມພາ ກຸມພາ'],
<add> ['YYYY YY', '2010 10'],
<add> ['D Do DD', '14 ທີ່14 14'],
<add> ['d do dddd ddd dd', '0 ທີ່0 ອາທິດ ທິດ ທ'],
<add> ['DDD DDDo DDDD', '45 ທີ່45 045'],
<add> ['w wo ww', '8 ທີ່8 08'],
<add> ['h hh', '3 03'],
<add> ['H HH', '15 15'],
<add> ['m mm', '25 25'],
<add> ['s ss', '50 50'],
<add> ['a A', 'ຕອນແລງ ຕອນແລງ'],
<add> ['[ວັນ]DDDo [ຂອງປີ]', 'ວັນທີ່45 ຂອງປີ'],
<add> ['LTS', '15:25:50'],
<add> ['L', '14/02/2010'],
<add> ['LL', '14 ກຸມພາ 2010'],
<add> ['LLL', '14 ກຸມພາ 2010 15:25'],
<add> ['LLLL', 'ວັນອາທິດ 14 ກຸມພາ 2010 15:25'],
<add> ['l', '14/2/2010'],
<add> ['ll', '14 ກຸມພາ 2010'],
<add> ['lll', '14 ກຸມພາ 2010 15:25'],
<add> ['llll', 'ວັນທິດ 14 ກຸມພາ 2010 15:25']
<add> ],
<add> b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)),
<add> i;
<add> for (i = 0; i < a.length; i++) {
<add> assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]);
<add> }
<add>});
<add>
<add>test('format ordinal', function (assert) {
<add> assert.equal(moment([2011, 0, 1]).format('DDDo'), 'ທີ່1', 'ທີ່1');
<add> assert.equal(moment([2011, 0, 2]).format('DDDo'), 'ທີ່2', 'ທີ່2');
<add> assert.equal(moment([2011, 0, 3]).format('DDDo'), 'ທີ່3', 'ທີ່3');
<add> assert.equal(moment([2011, 0, 4]).format('DDDo'), 'ທີ່4', 'ທີ່4');
<add> assert.equal(moment([2011, 0, 5]).format('DDDo'), 'ທີ່5', 'ທີ່5');
<add> assert.equal(moment([2011, 0, 6]).format('DDDo'), 'ທີ່6', 'ທີ່6');
<add> assert.equal(moment([2011, 0, 7]).format('DDDo'), 'ທີ່7', 'ທີ່7');
<add> assert.equal(moment([2011, 0, 8]).format('DDDo'), 'ທີ່8', 'ທີ່8');
<add> assert.equal(moment([2011, 0, 9]).format('DDDo'), 'ທີ່9', 'ທີ່9');
<add> assert.equal(moment([2011, 0, 10]).format('DDDo'), 'ທີ່10', 'ທີ່10');
<add>
<add> assert.equal(moment([2011, 0, 11]).format('DDDo'), 'ທີ່11', 'ທີ່11');
<add> assert.equal(moment([2011, 0, 12]).format('DDDo'), 'ທີ່12', 'ທີ່12');
<add> assert.equal(moment([2011, 0, 13]).format('DDDo'), 'ທີ່13', 'ທີ່13');
<add> assert.equal(moment([2011, 0, 14]).format('DDDo'), 'ທີ່14', 'ທີ່14');
<add> assert.equal(moment([2011, 0, 15]).format('DDDo'), 'ທີ່15', 'ທີ່15');
<add> assert.equal(moment([2011, 0, 16]).format('DDDo'), 'ທີ່16', 'ທີ່16');
<add> assert.equal(moment([2011, 0, 17]).format('DDDo'), 'ທີ່17', 'ທີ່17');
<add> assert.equal(moment([2011, 0, 18]).format('DDDo'), 'ທີ່18', 'ທີ່18');
<add> assert.equal(moment([2011, 0, 19]).format('DDDo'), 'ທີ່19', 'ທີ່19');
<add> assert.equal(moment([2011, 0, 20]).format('DDDo'), 'ທີ່20', 'ທີ່20');
<add>
<add> assert.equal(moment([2011, 0, 21]).format('DDDo'), 'ທີ່21', 'ທີ່21');
<add> assert.equal(moment([2011, 0, 22]).format('DDDo'), 'ທີ່22', 'ທີ່22');
<add> assert.equal(moment([2011, 0, 23]).format('DDDo'), 'ທີ່23', 'ທີ່23');
<add> assert.equal(moment([2011, 0, 24]).format('DDDo'), 'ທີ່24', 'ທີ່24');
<add> assert.equal(moment([2011, 0, 25]).format('DDDo'), 'ທີ່25', 'ທີ່25');
<add> assert.equal(moment([2011, 0, 26]).format('DDDo'), 'ທີ່26', 'ທີ່26');
<add> assert.equal(moment([2011, 0, 27]).format('DDDo'), 'ທີ່27', 'ທີ່27');
<add> assert.equal(moment([2011, 0, 28]).format('DDDo'), 'ທີ່28', 'ທີ່28');
<add> assert.equal(moment([2011, 0, 29]).format('DDDo'), 'ທີ່29', 'ທີ່29');
<add> assert.equal(moment([2011, 0, 30]).format('DDDo'), 'ທີ່30', 'ທີ່30');
<add>
<add> assert.equal(moment([2011, 0, 31]).format('DDDo'), 'ທີ່31', 'ທີ່31');
<add>});
<add>
<add>test('format month', function (assert) {
<add> var expected = 'ມັງກອນ ມັງກອນ_ກຸມພາ ກຸມພາ_ມີນາ ມີນາ_ເມສາ ເມສາ_ພຶດສະພາ ພຶດສະພາ_ມິຖຸນາ ມິຖຸນາ_ກໍລະກົດ ກໍລະກົດ_ສິງຫາ ສິງຫາ_ກັນຍາ ກັນຍາ_ຕຸລາ ຕຸລາ_ພະຈິກ ພະຈິກ_ທັນວາ ທັນວາ'.split('_'), i;
<add> for (i = 0; i < expected.length; i++) {
<add> assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]);
<add> }
<add>});
<add>
<add>test('format week', function (assert) {
<add> var expected = 'ອາທິດ ທິດ ທ_ຈັນ ຈັນ ຈ_ອັງຄານ ອັງຄານ ອຄ_ພຸດ ພຸດ ພ_ພະຫັດ ພະຫັດ ພຫ_ສຸກ ສຸກ ສກ_ເສົາ ເສົາ ສ'.split('_'), i;
<add> for (i = 0; i < expected.length; i++) {
<add> assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]);
<add> }
<add>});
<add>
<add>test('from', function (assert) {
<add> var start = moment([2007, 1, 28]);
<add> assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'ບໍ່ເທົ່າໃດວິນາທີ', '44 seconds = a few seconds');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), '1 ນາທີ', '45 seconds = a minute');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), '1 ນາທີ', '89 seconds = a minute');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 ນາທີ', '90 seconds = 2 minutes');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 ນາທີ', '44 minutes = 44 minutes');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), '1 ຊົ່ວໂມງ', '45 minutes = an hour');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), '1 ຊົ່ວໂມງ', '89 minutes = an hour');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 ຊົ່ວໂມງ', '90 minutes = 2 hours');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 ຊົ່ວໂມງ', '5 hours = 5 hours');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 ຊົ່ວໂມງ', '21 hours = 21 hours');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), '1 ມື້', '22 hours = a day');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), '1 ມື້', '35 hours = a day');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 ມື້', '36 hours = 2 days');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), '1 ມື້', '1 day = a day');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 ມື້', '5 days = 5 days');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 ມື້', '25 days = 25 days');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), '1 ເດືອນ', '26 days = a month');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), '1 ເດືອນ', '30 days = a month');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), '1 ເດືອນ', '43 days = a month');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 ເດືອນ', '46 days = 2 months');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 ເດືອນ', '75 days = 2 months');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 ເດືອນ', '76 days = 3 months');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), '1 ເດືອນ', '1 month = a month');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 ເດືອນ', '5 months = 5 months');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), '1 ປີ', '345 days = a year');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 ປີ', '548 days = 2 years');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), '1 ປີ', '1 year = a year');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 ປີ', '5 years = 5 years');
<add>});
<add>
<add>test('suffix', function (assert) {
<add> assert.equal(moment(30000).from(0), 'ອີກ ບໍ່ເທົ່າໃດວິນາທີ', 'prefix');
<add> assert.equal(moment(0).from(30000), 'ບໍ່ເທົ່າໃດວິນາທີຜ່ານມາ', 'suffix');
<add>});
<add>
<add>test('now from now', function (assert) {
<add> assert.equal(moment().fromNow(), 'ບໍ່ເທົ່າໃດວິນາທີຜ່ານມາ', 'now from now should display as in the past');
<add>});
<add>
<add>test('fromNow', function (assert) {
<add> assert.equal(moment().add({s: 30}).fromNow(), 'ອີກ ບໍ່ເທົ່າໃດວິນາທີ', 'in a few seconds');
<add> assert.equal(moment().add({d: 5}).fromNow(), 'ອີກ 5 ມື້', 'in 5 days');
<add>});
<add>
<add>test('calendar day', function (assert) {
<add> var a = moment().hours(2).minutes(0).seconds(0);
<add>
<add> assert.equal(moment(a).calendar(), 'ມື້ນີ້ເວລາ 02:00', 'today at the same time');
<add> assert.equal(moment(a).add({m: 25}).calendar(), 'ມື້ນີ້ເວລາ 02:25', 'Now plus 25 min');
<add> assert.equal(moment(a).add({h: 1}).calendar(), 'ມື້ນີ້ເວລາ 03:00', 'Now plus 1 hour');
<add> assert.equal(moment(a).add({d: 1}).calendar(), 'ມື້ອື່ນເວລາ 02:00', 'tomorrow at the same time');
<add> assert.equal(moment(a).subtract({h: 1}).calendar(), 'ມື້ນີ້ເວລາ 01:00', 'Now minus 1 hour');
<add> assert.equal(moment(a).subtract({d: 1}).calendar(), 'ມື້ວານນີ້ເວລາ 02:00', 'yesterday at the same time');
<add>});
<add>
<add>test('calendar next week', function (assert) {
<add> var i, m;
<add> for (i = 2; i < 7; i++) {
<add> m = moment().add({d: i});
<add> assert.equal(m.calendar(), m.format('[ວັນ]dddd[ໜ້າເວລາ] LT'), 'Today + ' + i + ' days current time');
<add> m.hours(0).minutes(0).seconds(0).milliseconds(0);
<add> assert.equal(m.calendar(), m.format('[ວັນ]dddd[ໜ້າເວລາ] LT'), 'Today + ' + i + ' days beginning of day');
<add> m.hours(23).minutes(59).seconds(59).milliseconds(999);
<add> assert.equal(m.calendar(), m.format('[ວັນ]dddd[ໜ້າເວລາ] LT'), 'Today + ' + i + ' days end of day');
<add> }
<add>});
<add>
<add>test('calendar last week', function (assert) {
<add> var i, m;
<add>
<add> for (i = 2; i < 7; i++) {
<add> m = moment().subtract({d: i});
<add> assert.equal(m.calendar(), m.format('[ວັນ]dddd[ແລ້ວນີ້ເວລາ] LT'), 'Today - ' + i + ' days current time');
<add> m.hours(0).minutes(0).seconds(0).milliseconds(0);
<add> assert.equal(m.calendar(), m.format('[ວັນ]dddd[ແລ້ວນີ້ເວລາ] LT'), 'Today - ' + i + ' days beginning of day');
<add> m.hours(23).minutes(59).seconds(59).milliseconds(999);
<add> assert.equal(m.calendar(), m.format('[ວັນ]dddd[ແລ້ວນີ້ເວລາ] LT'), 'Today - ' + i + ' days end of day');
<add> }
<add>});
<add>
<add>test('calendar all else', function (assert) {
<add> var weeksAgo = moment().subtract({w: 1}),
<add> weeksFromNow = moment().add({w: 1});
<add>
<add> assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago');
<add> assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week');
<add>
<add> weeksAgo = moment().subtract({w: 2});
<add> weeksFromNow = moment().add({w: 2});
<add>
<add> assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago');
<add> assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks');
<add>});
<add>
<add>test('weeks year starting sunday', function (assert) {
<add> assert.equal(moment([2012, 0, 1]).week(), 1, 'Jan 1 2012 should be week 1');
<add> assert.equal(moment([2012, 0, 7]).week(), 1, 'Jan 7 2012 should be week 1');
<add> assert.equal(moment([2012, 0, 8]).week(), 2, 'Jan 8 2012 should be week 2');
<add> assert.equal(moment([2012, 0, 14]).week(), 2, 'Jan 14 2012 should be week 2');
<add> assert.equal(moment([2012, 0, 15]).week(), 3, 'Jan 15 2012 should be week 3');
<add>});
<add>
<add>test('weeks year starting monday', function (assert) {
<add> assert.equal(moment([2006, 11, 31]).week(), 1, 'Dec 31 2006 should be week 1');
<add> assert.equal(moment([2007, 0, 1]).week(), 1, 'Jan 1 2007 should be week 1');
<add> assert.equal(moment([2007, 0, 6]).week(), 1, 'Jan 6 2007 should be week 1');
<add> assert.equal(moment([2007, 0, 7]).week(), 2, 'Jan 7 2007 should be week 2');
<add> assert.equal(moment([2007, 0, 13]).week(), 2, 'Jan 13 2007 should be week 2');
<add> assert.equal(moment([2007, 0, 14]).week(), 3, 'Jan 14 2007 should be week 3');
<add>});
<add>
<add>test('weeks year starting tuesday', function (assert) {
<add> assert.equal(moment([2007, 11, 29]).week(), 52, 'Dec 29 2007 should be week 52');
<add> assert.equal(moment([2008, 0, 1]).week(), 1, 'Jan 1 2008 should be week 1');
<add> assert.equal(moment([2008, 0, 5]).week(), 1, 'Jan 5 2008 should be week 1');
<add> assert.equal(moment([2008, 0, 6]).week(), 2, 'Jan 6 2008 should be week 2');
<add> assert.equal(moment([2008, 0, 12]).week(), 2, 'Jan 12 2008 should be week 2');
<add> assert.equal(moment([2008, 0, 13]).week(), 3, 'Jan 13 2008 should be week 3');
<add>});
<add>
<add>test('weeks year starting wednesday', function (assert) {
<add> assert.equal(moment([2002, 11, 29]).week(), 1, 'Dec 29 2002 should be week 1');
<add> assert.equal(moment([2003, 0, 1]).week(), 1, 'Jan 1 2003 should be week 1');
<add> assert.equal(moment([2003, 0, 4]).week(), 1, 'Jan 4 2003 should be week 1');
<add> assert.equal(moment([2003, 0, 5]).week(), 2, 'Jan 5 2003 should be week 2');
<add> assert.equal(moment([2003, 0, 11]).week(), 2, 'Jan 11 2003 should be week 2');
<add> assert.equal(moment([2003, 0, 12]).week(), 3, 'Jan 12 2003 should be week 3');
<add>});
<add>
<add>test('weeks year starting thursday', function (assert) {
<add> assert.equal(moment([2008, 11, 28]).week(), 1, 'Dec 28 2008 should be week 1');
<add> assert.equal(moment([2009, 0, 1]).week(), 1, 'Jan 1 2009 should be week 1');
<add> assert.equal(moment([2009, 0, 3]).week(), 1, 'Jan 3 2009 should be week 1');
<add> assert.equal(moment([2009, 0, 4]).week(), 2, 'Jan 4 2009 should be week 2');
<add> assert.equal(moment([2009, 0, 10]).week(), 2, 'Jan 10 2009 should be week 2');
<add> assert.equal(moment([2009, 0, 11]).week(), 3, 'Jan 11 2009 should be week 3');
<add>});
<add>
<add>test('weeks year starting friday', function (assert) {
<add> assert.equal(moment([2009, 11, 27]).week(), 1, 'Dec 27 2009 should be week 1');
<add> assert.equal(moment([2010, 0, 1]).week(), 1, 'Jan 1 2010 should be week 1');
<add> assert.equal(moment([2010, 0, 2]).week(), 1, 'Jan 2 2010 should be week 1');
<add> assert.equal(moment([2010, 0, 3]).week(), 2, 'Jan 3 2010 should be week 2');
<add> assert.equal(moment([2010, 0, 9]).week(), 2, 'Jan 9 2010 should be week 2');
<add> assert.equal(moment([2010, 0, 10]).week(), 3, 'Jan 10 2010 should be week 3');
<add>});
<add>
<add>test('weeks year starting saturday', function (assert) {
<add> assert.equal(moment([2010, 11, 26]).week(), 1, 'Dec 26 2010 should be week 1');
<add> assert.equal(moment([2011, 0, 1]).week(), 1, 'Jan 1 2011 should be week 1');
<add> assert.equal(moment([2011, 0, 2]).week(), 2, 'Jan 2 2011 should be week 2');
<add> assert.equal(moment([2011, 0, 8]).week(), 2, 'Jan 8 2011 should be week 2');
<add> assert.equal(moment([2011, 0, 9]).week(), 3, 'Jan 9 2011 should be week 3');
<add>});
<add>
<add>test('weeks year starting sunday format', function (assert) {
<add> assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 ທີ່1', 'Jan 1 2012 should be week 1');
<add> assert.equal(moment([2012, 0, 7]).format('w ww wo'), '1 01 ທີ່1', 'Jan 7 2012 should be week 1');
<add> assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 ທີ່2', 'Jan 8 2012 should be week 2');
<add> assert.equal(moment([2012, 0, 14]).format('w ww wo'), '2 02 ທີ່2', 'Jan 14 2012 should be week 2');
<add> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 ທີ່3', 'Jan 15 2012 should be week 3');
<add>});
<add>
<add>test('lenient ordinal parsing', function (assert) {
<add> var i, ordinalStr, testMoment;
<add> for (i = 1; i <= 31; ++i) {
<add> ordinalStr = moment([2014, 0, i]).format('YYYY MM Do');
<add> testMoment = moment(ordinalStr, 'YYYY MM Do');
<add> assert.equal(testMoment.year(), 2014,
<add> 'lenient ordinal parsing ' + i + ' year check');
<add> assert.equal(testMoment.month(), 0,
<add> 'lenient ordinal parsing ' + i + ' month check');
<add> assert.equal(testMoment.date(), i,
<add> 'lenient ordinal parsing ' + i + ' date check');
<add> }
<add>});
<add>
<add>test('lenient ordinal parsing of number', function (assert) {
<add> var i, testMoment;
<add> for (i = 1; i <= 31; ++i) {
<add> testMoment = moment('2014 01 ' + i, 'YYYY MM Do');
<add> assert.equal(testMoment.year(), 2014,
<add> 'lenient ordinal parsing of number ' + i + ' year check');
<add> assert.equal(testMoment.month(), 0,
<add> 'lenient ordinal parsing of number ' + i + ' month check');
<add> assert.equal(testMoment.date(), i,
<add> 'lenient ordinal parsing of number ' + i + ' date check');
<add> }
<add>});
<add>
<add>test('strict ordinal parsing', function (assert) {
<add> var i, ordinalStr, testMoment;
<add> for (i = 1; i <= 31; ++i) {
<add> ordinalStr = moment([2014, 0, i]).format('YYYY MM Do');
<add> testMoment = moment(ordinalStr, 'YYYY MM Do', true);
<add> assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i);
<add> }
<add>}); | 2 |
Text | Text | replace the reserved word `input` with `inputs` | 52592d45a5fb15c76445d7c7f2e14e33168ad3fd | <ide><path>docs/templates/backend.md
<ide> from keras import backend as K
<ide> The code below instantiates an input placeholder. It's equivalent to `tf.placeholder()` or `th.tensor.matrix()`, `th.tensor.tensor3()`, etc.
<ide>
<ide> ```python
<del>input = K.placeholder(shape=(2, 4, 5))
<add>inputs = K.placeholder(shape=(2, 4, 5))
<ide> # also works:
<del>input = K.placeholder(shape=(None, 4, 5))
<add>inputs = K.placeholder(shape=(None, 4, 5))
<ide> # also works:
<del>input = K.placeholder(ndim=3)
<add>inputs = K.placeholder(ndim=3)
<ide> ```
<ide>
<ide> The code below instantiates a shared variable. It's equivalent to `tf.Variable()` or `th.shared()`. | 1 |
Text | Text | fix a typo | 5494b267d9c945251c6b04cc1a835e1cfcdc0314 | <ide><path>docs/_posts/2016-07-13-mixins-considered-harmful.md
<ide> Multiple components may be sharing `RowMixin` to render the header, and each of
<ide>
<ide> If you see rendering logic inside a mixin, it’s time to extract a component!
<ide>
<del>Instead of `RowMixin`, we will define a `<Row>` component. We will also replace the convention of defining a `getHeaderText()` method with the standard mechanism of top-data flow in React: passing props.
<add>Instead of `RowMixin`, we will define a `<RowHeader>` component. We will also replace the convention of defining a `getHeaderText()` method with the standard mechanism of top-data flow in React: passing props.
<ide>
<ide> Finally, since neither of those components currently need lifecycle hooks or state, we can declare them as simple functions:
<ide> | 1 |
PHP | PHP | update exception type to a class that exists | f0164ddfe74deb36398c3261a93fd65e93fd8d48 | <ide><path>Cake/Test/TestCase/Utility/HashTest.php
<ide> public function testCombine() {
<ide> /**
<ide> * test combine() giving errors on key/value length mismatches.
<ide> *
<del> * @expectedException CakeException
<add> * @expectedException RuntimeException
<ide> * @return void
<ide> */
<ide> public function testCombineErrorMissingValue() {
<ide> public function testCombineErrorMissingValue() {
<ide> /**
<ide> * test combine() giving errors on key/value length mismatches.
<ide> *
<del> * @expectedException CakeException
<add> * @expectedException RuntimeException
<ide> * @return void
<ide> */
<ide> public function testCombineErrorMissingKey() {
<ide><path>Cake/Utility/Hash.php
<ide> public static function remove(array $data, $path) {
<ide> * @param string $groupPath A dot-separated string.
<ide> * @return array Combined array
<ide> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::combine
<del> * @throws CakeException CakeException When keys and values count is unequal.
<add> * @throws \RuntimeException When keys and values count is unequal.
<ide> */
<ide> public static function combine(array $data, $keyPath, $valuePath = null, $groupPath = null) {
<ide> if (empty($data)) {
<ide> public static function combine(array $data, $keyPath, $valuePath = null, $groupP
<ide> }
<ide>
<ide> if (count($keys) !== count($vals)) {
<del> throw new CakeException(__d(
<add> throw new \RuntimeException(__d(
<ide> 'cake_dev',
<ide> 'Hash::combine() needs an equal number of keys + values.'
<ide> )); | 2 |
Javascript | Javascript | remove duplicate documentation of register method | 0f3ea45d738ca6d09c4ceedf2e06fdf344054b5a | <ide><path>src/ng/filter.js
<ide> * For more information about how angular filters work, and how to create your own filters, see
<ide> * {@link guide/filter Filters} in the Angular Developer Guide.
<ide> */
<del>/**
<del> * @ngdoc method
<del> * @name $filterProvider#register
<del> * @description
<del> * Register filter factory function.
<del> *
<del> * @param {String} name Name of the filter.
<del> * @param {Function} fn The filter factory function which is injectable.
<del> */
<del>
<ide>
<ide> /**
<ide> * @ngdoc service
<ide> function $FilterProvider($provide) {
<ide>
<ide> /**
<ide> * @ngdoc method
<del> * @name $controllerProvider#register
<add> * @name $filterProvider#register
<ide> * @param {string|Object} name Name of the filter function, or an object map of filters where
<ide> * the keys are the filter names and the values are the filter factories.
<ide> * @returns {Object} Registered filter instance, or if a map of filters was provided then a map | 1 |
Javascript | Javascript | delete existing users before seeding db | 0e96d2604ea88b9f65b1d6155467dc37267b4a72 | <ide><path>tools/scripts/seed/seedAuthUser.js
<ide> MongoClient.connect(MONGOHQ_URL, { useNewUrlParser: true }, (err, client) => {
<ide> const user = db.collection('user');
<ide>
<ide> if (process.argv[2] === 'certUser') {
<del> user.deleteOne({ _id: ObjectId('5fa2db00a25c1c1fa49ce067') }, err => {
<del> handleError(err, client);
<add> user.deleteMany(
<add> {
<add> _id: {
<add> $in: [
<add> ObjectId('5fa2db00a25c1c1fa49ce067'),
<add> ObjectId('5bd30e0f1caf6ac3ddddddb5'),
<add> ObjectId('5bd30e0f1caf6ac3ddddddb9')
<add> ]
<add> }
<add> },
<add> err => {
<add> handleError(err, client);
<ide>
<del> try {
<del> user.insertOne(fullyCertifiedUser);
<del> } catch (e) {
<del> handleError(e, client);
<del> } finally {
<del> log('local auth user seed complete');
<del> client.close();
<add> try {
<add> user.insertOne(fullyCertifiedUser);
<add> user.insertOne(blankUser);
<add> } catch (e) {
<add> handleError(e, client);
<add> } finally {
<add> log('local auth user seed complete');
<add> client.close();
<add> }
<ide> }
<del> });
<add> );
<ide> } else {
<ide> user.deleteMany(
<ide> {
<ide> _id: {
<ide> $in: [
<add> ObjectId('5fa2db00a25c1c1fa49ce067'),
<ide> ObjectId('5bd30e0f1caf6ac3ddddddb5'),
<ide> ObjectId('5bd30e0f1caf6ac3ddddddb9')
<ide> ] | 1 |
Go | Go | add service create and update integration tests | 76b33fdb99a6395670b8b466a5ef65a8b928be94 | <ide><path>integration-cli/docker_cli_service_create_test.go
<ide> package main
<ide>
<ide> import (
<ide> "encoding/json"
<add> "fmt"
<ide> "strings"
<ide>
<ide> "github.com/docker/docker/api/types"
<ide> func (s *DockerSwarmSuite) TestServiceCreateMountVolume(c *check.C) {
<ide> c.Assert(mounts[0].Destination, checker.Equals, "/foo")
<ide> c.Assert(mounts[0].RW, checker.Equals, true)
<ide> }
<add>
<add>func (s *DockerSwarmSuite) TestServiceCreateWithSecret(c *check.C) {
<add> d := s.AddDaemon(c, true, true)
<add>
<add> serviceName := "test-service-secret"
<add> testName := "test_secret"
<add> id := d.createSecret(c, swarm.SecretSpec{
<add> swarm.Annotations{
<add> Name: testName,
<add> },
<add> []byte("TESTINGDATA"),
<add> })
<add> c.Assert(id, checker.Not(checker.Equals), "", check.Commentf("secrets: %s", id))
<add> testTarget := "testing"
<add>
<add> out, err := d.Cmd("service", "create", "--name", serviceName, "--secret", fmt.Sprintf("%s:%s", testName, testTarget), "busybox", "top")
<add> c.Assert(err, checker.IsNil, check.Commentf(out))
<add>
<add> out, err = d.Cmd("service", "inspect", "--format", "{{ json .Spec.TaskTemplate.ContainerSpec.Secrets }}", serviceName)
<add> c.Assert(err, checker.IsNil)
<add>
<add> var refs []swarm.SecretReference
<add> c.Assert(json.Unmarshal([]byte(out), &refs), checker.IsNil)
<add> c.Assert(refs, checker.HasLen, 1)
<add>
<add> c.Assert(refs[0].SecretName, checker.Equals, testName)
<add> c.Assert(refs[0].Target, checker.Equals, testTarget)
<add>}
<ide><path>integration-cli/docker_cli_service_update_test.go
<ide> package main
<ide>
<ide> import (
<ide> "encoding/json"
<add> "fmt"
<ide>
<ide> "github.com/docker/docker/api/types/swarm"
<ide> "github.com/docker/docker/pkg/integration/checker"
<ide> func (s *DockerSwarmSuite) TestServiceUpdateLabel(c *check.C) {
<ide> c.Assert(service.Spec.Labels, checker.HasLen, 1)
<ide> c.Assert(service.Spec.Labels["foo"], checker.Equals, "bar")
<ide> }
<add>
<add>func (s *DockerSwarmSuite) TestServiceUpdateSecrets(c *check.C) {
<add> d := s.AddDaemon(c, true, true)
<add> testName := "test_secret"
<add> id := d.createSecret(c, swarm.SecretSpec{
<add> swarm.Annotations{
<add> Name: testName,
<add> },
<add> []byte("TESTINGDATA"),
<add> })
<add> c.Assert(id, checker.Not(checker.Equals), "", check.Commentf("secrets: %s", id))
<add> testTarget := "testing"
<add> serviceName := "test"
<add>
<add> out, err := d.Cmd("service", "create", "--name", serviceName, "busybox", "top")
<add> c.Assert(err, checker.IsNil, check.Commentf(out))
<add>
<add> // add secret
<add> out, err = d.Cmd("service", "update", "test", "--secret-add", fmt.Sprintf("%s:%s", testName, testTarget))
<add> c.Assert(err, checker.IsNil, check.Commentf(out))
<add>
<add> out, err = d.Cmd("service", "inspect", "--format", "{{ json .Spec.TaskTemplate.ContainerSpec.Secrets }}", serviceName)
<add> c.Assert(err, checker.IsNil)
<add>
<add> var refs []swarm.SecretReference
<add> c.Assert(json.Unmarshal([]byte(out), &refs), checker.IsNil)
<add> c.Assert(refs, checker.HasLen, 1)
<add>
<add> c.Assert(refs[0].SecretName, checker.Equals, testName)
<add> c.Assert(refs[0].Target, checker.Equals, testTarget)
<add>
<add> // remove
<add> out, err = d.Cmd("service", "update", "test", "--secret-rm", testName)
<add> c.Assert(err, checker.IsNil, check.Commentf(out))
<add>
<add> out, err = d.Cmd("service", "inspect", "--format", "{{ json .Spec.TaskTemplate.ContainerSpec.Secrets }}", serviceName)
<add> c.Assert(err, checker.IsNil)
<add>
<add> c.Assert(json.Unmarshal([]byte(out), &refs), checker.IsNil)
<add> c.Assert(refs, checker.HasLen, 0)
<add>} | 2 |
Text | Text | add a webpack usage guide | 230743ecb1c79977bfa308ce90c039377dfdf524 | <ide><path>docs/guides/faq.md
<ide> Yes! Please [submit an issue or open a pull request][pr-issue-question] if this
<ide>
<ide> Yes! Please [submit an issue or open a pull request][pr-issue-question] if this does not work.
<ide>
<del>Be sure to use `require('!style-loader!css-loader!video.js/dist/video-js.css')` to inject video.js CSS.
<add>We have a short guide that deals with small configurations that you will need to do. [Webpack and Videojs Configuration][webpack-guide].
<ide>
<ide> ## Q: Does video.js work with react?
<ide>
<ide> Yes! See [ReactJS integration example][react-guide].
<ide>
<del>[reduced-test-case]: https://css-tricks.com/reduced-test-cases/
<del>
<del>[react-guide]: /docs/guides/react.md
<add>[ads]: https://github.com/videojs/videojs-contrib-ads
<ide>
<del>[plugin-guide]: /docs/guides/plugins.md
<add>[audio-tracks]: /docs/guides/audio-tracks.md
<ide>
<del>[install-guide]: http://videojs.com/getting-started/
<add>[contributing-issues]: http://github.com/videojs/video.js/blob/master/CONTRIBUTING.md#filing-issues
<ide>
<del>[troubleshooting]: /docs/guides/troubleshooting.md
<add>[contributing-prs]: http://github.com/videojs/video.js/blob/master/CONTRIBUTING.md#contributing-code
<ide>
<del>[video-tracks]: /docs/guides/video-tracks.md
<add>[dash]: http://github.com/videojs/videojs-contrib-dash
<ide>
<del>[audio-tracks]: /docs/guides/audio-tracks.md
<add>[debug-guide]: /docs/guides/debugging.md
<ide>
<del>[text-tracks]: /docs/guides/text-tracks.md
<add>[eme]: https://github.com/videojs/videojs-contrib-eme
<ide>
<del>[debug-guide]: /docs/guides/debugging.md
<add>[flash]: https://github.com/videojs/videojs-flash
<ide>
<del>[pr-issue-question]: #q-i-think-i-found-a-bug-with-videojs-or-i-want-to-add-a-feature-what-should-i-do
<add>[generator]: https://github.com/videojs/generator-videojs-plugin
<ide>
<ide> [hls]: http://github.com/videojs/videojs-contrib-hls
<ide>
<del>[flash]: https://github.com/videojs/videojs-flash
<del>
<del>[dash]: http://github.com/videojs/videojs-contrib-dash
<add>[install-guide]: http://videojs.com/getting-started/
<ide>
<del>[eme]: https://github.com/videojs/videojs-contrib-eme
<add>[issue-template]: http://github.com/videojs/video.js/blob/master/.github/ISSUE_TEMPLATE.md
<ide>
<del>[generator]: https://github.com/videojs/generator-videojs-plugin
<add>[npm-keywords]: https://docs.npmjs.com/files/package.json#keywords
<ide>
<del>[youtube]: https://github.com/videojs/videojs-youtube
<add>[plugin-guide]: /docs/guides/plugins.md
<ide>
<del>[vimeo]: https://github.com/videojs/videojs-vimeo
<add>[plugin-list]: http://videojs.com/plugins
<ide>
<del>[ads]: https://github.com/videojs/videojs-contrib-ads
<add>[pr-issue-question]: #q-i-think-i-found-a-bug-with-videojs-or-i-want-to-add-a-feature-what-should-i-do
<ide>
<ide> [pr-template]: http://github.com/videojs/video.js/blob/master/.github/PULL_REQUEST_TEMPLATE.md
<ide>
<del>[issue-template]: http://github.com/videojs/video.js/blob/master/.github/ISSUE_TEMPLATE.md
<add>[react-guide]: /docs/guides/react.md
<ide>
<del>[plugin-list]: http://videojs.com/plugins
<add>[reduced-test-case]: https://css-tricks.com/reduced-test-cases/
<add>
<add>[semver]: http://semver.org/
<ide>
<ide> [skins-list]: https://github.com/videojs/video.js/wiki/Skins
<ide>
<del>[contributing-issues]: http://github.com/videojs/video.js/blob/master/CONTRIBUTING.md#filing-issues
<add>[starter-example]: http://jsbin.com/axedog/edit?html,output
<ide>
<del>[contributing-prs]: http://github.com/videojs/video.js/blob/master/CONTRIBUTING.md#contributing-code
<add>[text-tracks]: /docs/guides/text-tracks.md
<ide>
<del>[vjs-issues]: https://github.com/videojs/video.js/issues
<add>[troubleshooting]: /docs/guides/troubleshooting.md
<ide>
<del>[vjs-prs]: https://github.com/videojs/video.js/pulls
<add>[video-tracks]: /docs/guides/video-tracks.md
<ide>
<del>[npm-keywords]: https://docs.npmjs.com/files/package.json#keywords
<add>[vimeo]: https://github.com/videojs/videojs-vimeo
<ide>
<del>[semver]: http://semver.org/
<add>[vjs-issues]: https://github.com/videojs/video.js/issues
<ide>
<del>[starter-example]: http://jsbin.com/axedog/edit?html,output
<add>[vjs-prs]: https://github.com/videojs/video.js/pulls
<add>
<add>[webpack-guide]: /docs/guides/webpack.md
<ide>
<add>[youtube]: https://github.com/videojs/videojs-youtube
<ide><path>docs/guides/webpack.md
<add># Using Webpack with Video.js
<add>
<add>video.js, and the playback technologies such as videojs-contrib-hls all work in a Webpack based build environment. Here are several configuration changes specific to Webpack that will get you up and running.
<add>
<add>## Video.js CSS:
<add>To add the CSS that the player requires, simply add
<add>`require('!style-loader!css-loader!video.js/dist/video-js.css')` to the file where the player is also included or initialized.
<add>
<add>## Handling .eot files in Webpack
<add>In addition to this, you may run into a problem where Webpack does not know how to load .eot files required for IE8 support by default. This can be solved by installing the file-loader and url-loader packages. Install them by running:
<add>`npm install --save-dev file-loader url-loader`
<add>
<add>With both packages installed, simply add the following to you webpack.config file in the 'loaders' section:
<add>```
<add>{
<add> loader: 'url-loader?limit=100000',
<add> test: /\.(png|woff|woff2|eot|ttf|svg)$/
<add>}
<add>```
<add>
<add>## Using Webpack with videojs-contrib-hls
<add>Import the HLS library with a line such as:
<add>`import * as HLS from 'videojs-contrib-hls';`
<add>
<add>In order to use the tech, we must also introduce webworkers with the package 'webworkify-webpack-dropin', run:
<add>`npm install --save-dev webworkify-webpack-dropin`
<add>
<add>To utilize this in your page, simply create an alias in your webpack.config.js file with:
<add>```
<add>resolve: {
<add> alias: {
<add> webworkify: 'webworkify-webpack-dropin'
<add> }
<add>}
<add>```
<add>
<add>Source maps that use the 'eval' tag are not compatible with webworkify, so this may need to be changed also. Source maps such as 'cheap-eval-module-source-map' should be changed to 'cheap-source-map' or anything else that fits your build without using 'eval' source maps. | 2 |
PHP | PHP | add dispatchnow to dispatchable trait | ab526b7d8fc565314f20c840c7398096b9ec9b94 | <ide><path>src/Illuminate/Foundation/Bus/Dispatchable.php
<ide>
<ide> namespace Illuminate\Foundation\Bus;
<ide>
<add>use Illuminate\Contracts\Bus\Dispatcher;
<add>
<ide> trait Dispatchable
<ide> {
<ide> /**
<ide> public static function dispatch()
<ide> return new PendingDispatch(new static(...func_get_args()));
<ide> }
<ide>
<add> /**
<add> * Dispatch a command to its appropriate handler in the current process.
<add> *
<add> * @return mixed
<add> */
<add> public static function dispatchNow()
<add> {
<add> return app(Dispatcher::class)->dispatchNow(new static(...func_get_args()));
<add> }
<add>
<ide> /**
<ide> * Set the jobs that should run if this job is successful.
<ide> * | 1 |
Text | Text | improve translation for russion locale | a82badaa222caac3d81adbe40ad69cee7d9e314c | <ide><path>curriculum/challenges/russian/02-javascript-algorithms-and-data-structures/functional-programming/add-elements-to-the-end-of-an-array-using-concat-instead-of-push.russian.md
<ide> id: 587d7da9367417b2b2512b67
<ide> title: Add Elements to the End of an Array Using concat Instead of push
<ide> challengeType: 1
<ide> videoUrl: ''
<del>localeTitle: Добавление элементов в конец массива Использование concat Вместо push
<add>localeTitle: Добавление элементов в конец массива используя concat вместо push
<ide> ---
<ide>
<del>## Description
<del><section id="description"> Функциональное программирование - это создание и использование не мутирующих функций. Последняя проблема ввела метод <code>concat</code> как способ объединить массивы в новую, не изменяя исходные массивы. Сравните <code>concat</code> с методом <code>push</code> . <code>Push</code> добавляет элемент в конец того же самого массива, на который он вызывается, который мутирует этот массив. Вот пример: <blockquote> var arr = [1, 2, 3]; <br> arr.push ([4, 5, 6]); <br> // arr изменяется на [1, 2, 3, [4, 5, 6]] <br> // Не функциональный способ программирования </blockquote> <code>Concat</code> предлагает способ добавления новых элементов в конец массива без каких-либо мутирующих побочных эффектов. </section>
<add>## Описание
<add><section id="description"> Функциональное программирование - это создание и использование не мутирующих функций. Предыдущая проблема ввела метод <code>concat</code> как способ объединить массивы, не изменяя исходные. Сравните <code>concat</code> с методом <code>push</code> . <code>Push</code> добавляет элемент в конец того же самого массива, на котором он вызывается, изменяя этот массив. Вот пример: <blockquote> var arr = [1, 2, 3]; <br> arr.push ([4, 5, 6]); <br> // arr изменяется на [1, 2, 3, [4, 5, 6]] <br> // Не функциональный способ программирования </blockquote> <code>Concat</code> предлагает способ добавления новых элементов в конец массива без каких-либо мутирующих побочных эффектов. </section>
<ide>
<del>## Instructions
<add>## Указания
<ide> <section id="instructions"> Измените функцию <code>nonMutatingPush</code> чтобы она использовала <code>concat</code> для добавления <code>newItem</code> в конец <code>original</code> вместо <code>push</code> . Функция должна возвращать массив. </section>
<ide>
<del>## Tests
<add>## Тесты
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> nonMutatingPush(first, second);
<ide>
<ide> </section>
<ide>
<del>## Solution
<add>## Решение
<ide> <section id='solution'>
<ide>
<ide> ```js | 1 |
Javascript | Javascript | fix warning in doc parsing | 05f17db8b2c57ae86d1043ca8009a34c3cd2f611 | <ide><path>tools/doc/json.js
<ide> function parseSignature(text, sig) {
<ide> // [foo] -> optional
<ide> if (p.charAt(p.length - 1) === ']') {
<ide> optional = true;
<del> p = p.substr(0, p.length - 1);
<add> p = p.replace(/\]/g, '');
<ide> p = p.trim();
<ide> }
<ide> var eq = p.indexOf('='); | 1 |
Ruby | Ruby | allow tapping non-github repositories | 965e2f50c3e8490ffb799ed01d6b1e8b1a7c98cc | <ide><path>Library/Homebrew/cmd/tap.rb
<ide> def tap
<ide> elsif ARGV.first == "--repair"
<ide> migrate_taps :force => true
<ide> else
<del> opoo "Already tapped!" unless install_tap(*tap_args)
<add> user, repo = tap_args
<add> clone_target = ARGV.named[1]
<add> opoo "Already tapped!" unless install_tap(user, repo, clone_target)
<ide> end
<ide> end
<ide>
<del> def install_tap user, repo
<add> def install_tap user, repo, clone_target=nil
<ide> # we special case homebrew so users don't have to shift in a terminal
<ide> repouser = if user == "homebrew" then "Homebrew" else user end
<ide> user = "homebrew" if user == "Homebrew"
<ide> def install_tap user, repo
<ide> tapd = HOMEBREW_LIBRARY/"Taps/#{user.downcase}/homebrew-#{repo.downcase}"
<ide> return false if tapd.directory?
<ide> ohai "Tapping #{repouser}/#{repo}"
<del> args = %W[clone https://github.com/#{repouser}/homebrew-#{repo} #{tapd}]
<add> if clone_target
<add> args = %W[clone #{clone_target} #{tapd}]
<add> else
<add> args = %W[clone https://github.com/#{repouser}/homebrew-#{repo} #{tapd}]
<add> end
<ide> args << "--depth=1" unless ARGV.include?("--full")
<ide> safe_system "git", *args
<ide>
<ide> files = []
<ide> tapd.find_formula { |file| files << file }
<ide> puts "Tapped #{files.length} formula#{plural(files.length, 'e')} (#{tapd.abv})"
<ide>
<del> if private_tap?(repouser, repo) then puts <<-EOS.undent
<del> It looks like you tapped a private repository. To avoid entering your
<del> credentials each time you update, you can use git HTTP credential caching
<del> or issue the following command:
<add> if check_private?(clone_target, repouser, repo)
<add> puts <<-EOS.undent
<add> It looks like you tapped a private repository. To avoid entering your
<add> credentials each time you update, you can use git HTTP credential
<add> caching or issue the following command:
<ide>
<del> cd #{tapd}
<del> git remote set-url origin git@github.com:#{repouser}/homebrew-#{repo}.git
<del> EOS
<add> cd #{tapd}
<add> git remote set-url origin git@github.com:#{repouser}/homebrew-#{repo}.git
<add> EOS
<ide> end
<ide>
<ide> true
<ide> def private_tap?(user, repo)
<ide> rescue GitHub::Error
<ide> false
<ide> end
<add>
<add> def check_private?(clone_target, user, repo)
<add> not clone_target && private_tap?(user, repo)
<add> end
<ide> end
<ide><path>Library/Homebrew/cmd/untap.rb
<ide> def untap
<ide> ARGV.each do |tapname|
<ide> user, repo = tap_args(tapname)
<ide>
<del> # we consistently downcase in tap to ensure we are not bitten by case-insensive
<del> # filesystem issues. Which is the default on mac. The problem being the
<del> # filesystem cares, but our regexps don't. So unless we resolve *every* path
<del> # we will get bitten.
<add> # We consistently downcase in tap to ensure we are not bitten by
<add> # case-insensitive filesystem issues, which is the default on mac. The
<add> # problem being the filesystem cares, but our regexps don't. So unless we
<add> # resolve *every* path we will get bitten.
<ide> user.downcase!
<ide> repo.downcase!
<ide> | 2 |
Text | Text | add missing url types in fs promise api | ac829f0135b02e0c130e2433e028235c2bed2059 | <ide><path>doc/api/fs.md
<ide> the error raised if the file is not accessible.
<ide> added: REPLACEME
<ide> -->
<ide>
<del>* `file` {string|Buffer|[FileHandle][]} filename or `FileHandle`
<add>* `file` {string|Buffer|URL|[FileHandle][]} filename or `FileHandle`
<ide> * `data` {string|Buffer}
<ide> * `options` {Object|string}
<ide> * `encoding` {string|null} **Default:** `'utf8'`
<ide> This function does not work on AIX versions before 7.1, it will resolve the
<ide> deprecated: REPLACEME
<ide> -->
<ide>
<del>* `path` {string|Buffer}
<add>* `path` {string|Buffer|URL}
<ide> * `mode` {integer}
<ide> * Returns: {Promise}
<ide>
<ide> no arguments upon success. This method is only implemented on macOS.
<ide> deprecated: REPLACEME
<ide> -->
<ide>
<del>* `path` {string|Buffer}
<add>* `path` {string|Buffer|URL}
<ide> * `uid` {integer}
<ide> * `gid` {integer}
<ide> * Returns: {Promise}
<ide> the `target` argument will automatically be normalized to absolute path.
<ide> added: REPLACEME
<ide> -->
<ide>
<del>* `path` {string|Buffer}
<add>* `path` {string|Buffer|URL}
<ide> * `len` {integer} **Default:** `0`
<ide> * Returns: {Promise}
<ide>
<ide> the end of the file.
<ide> added: REPLACEME
<ide> -->
<ide>
<del>* `file` {string|Buffer|[FileHandle][]} filename or `FileHandle`
<add>* `file` {string|Buffer|URL|[FileHandle][]} filename or `FileHandle`
<ide> * `data` {string|Buffer|Uint8Array}
<ide> * `options` {Object|string}
<ide> * `encoding` {string|null} **Default:** `'utf8'` | 1 |
Python | Python | fix import in th | 3d5046c499d6e61492820293865c6b7af0e26fd0 | <ide><path>spacy/lang/th/__init__.py
<ide> from .stop_words import STOP_WORDS
<ide>
<ide> from ..tokenizer_exceptions import BASE_EXCEPTIONS
<del>from ..tokens import Doc
<add>from ...tokens import Doc
<ide> from ..norm_exceptions import BASE_NORMS
<ide> from ...language import Language
<ide> from ...attrs import LANG, NORM | 1 |
Go | Go | show error message when todisk failed | af7f81878f561ecdab32936d4bea72f0ab26ce0e | <ide><path>daemon/create.go
<ide> import (
<ide> "path/filepath"
<ide> "strings"
<ide>
<add> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/graph"
<ide> "github.com/docker/docker/image"
<ide> "github.com/docker/docker/pkg/parsers"
<ide> func (daemon *Daemon) Create(config *runconfig.Config, hostConfig *runconfig.Hos
<ide> container.addMountPointWithVolume(destination, v, true)
<ide> }
<ide> if err := container.ToDisk(); err != nil {
<add> logrus.Errorf("Error saving new container to disk: %v", err)
<ide> return nil, nil, err
<ide> }
<ide> container.LogEvent("create")
<ide><path>daemon/daemon.go
<ide> func (daemon *Daemon) register(container *Container, updateSuffixarray bool) err
<ide> logrus.Debugf("unmount error %s", err)
<ide> }
<ide> if err := container.ToDisk(); err != nil {
<del> logrus.Debugf("saving stopped state to disk %s", err)
<add> logrus.Errorf("Error saving stopped state to disk: %v", err)
<ide> }
<ide> }
<ide>
<ide> func (daemon *Daemon) ensureName(container *Container) error {
<ide> container.Name = name
<ide>
<ide> if err := container.ToDisk(); err != nil {
<del> logrus.Debugf("Error saving container name %s", err)
<add> logrus.Errorf("Error saving container name to disk: %v", err)
<ide> }
<ide> }
<ide> return nil
<ide><path>daemon/delete.go
<ide> func (daemon *Daemon) rm(container *Container, forceRemove bool) (err error) {
<ide> // Save container state to disk. So that if error happens before
<ide> // container meta file got removed from disk, then a restart of
<ide> // docker should not make a dead container alive.
<del> container.ToDisk()
<add> if err := container.ToDisk(); err != nil {
<add> logrus.Errorf("Error saving dying container to disk: %v", err)
<add> }
<ide>
<ide> // If force removal is required, delete container from various
<ide> // indexes even if removal failed.
<ide><path>daemon/monitor.go
<ide> func (m *containerMonitor) callback(processConfig *execdriver.ProcessConfig, pid
<ide> }
<ide>
<ide> if err := m.container.ToDisk(); err != nil {
<del> logrus.Debugf("%s", err)
<add> logrus.Errorf("Error saving container to disk: %v", err)
<ide> }
<ide> }
<ide> | 4 |
Text | Text | add text to "upgrading to rails 5.1" | 3b5a6dfb18f33c373a89760c60d741f34206f23b | <ide><path>guides/source/5_1_release_notes.md
<ide> repository on GitHub.
<ide> Upgrading to Rails 5.1
<ide> ----------------------
<ide>
<del>ToDo
<add>If you're upgrading an existing application, it's a great idea to have good test
<add>coverage before going in. You should also first upgrade to Rails 5.0 in case you
<add>haven't and make sure your application still runs as expected before attempting
<add>an update to Rails 5.1. A list of things to watch out for when upgrading is
<add>available in the
<add>[Upgrading Ruby on Rails](upgrading_ruby_on_rails.html#upgrading-from-rails-5-0-to-rails-5-1)
<add>guide.
<add>
<ide>
<ide> Major Features
<ide> -------------- | 1 |
Javascript | Javascript | free the parser before emitting 'upgrade' | 93f1d9e10bbc922d6c8862e30efaee8975712633 | <ide><path>lib/_http_client.js
<ide> function socketOnData(d) {
<ide> socket.removeListener('data', socketOnData);
<ide> socket.removeListener('end', socketOnEnd);
<ide> parser.finish();
<add> freeParser(parser, req, socket);
<ide>
<ide> var bodyHead = d.slice(bytesParsed, d.length);
<ide>
<ide> function socketOnData(d) {
<ide> // Got Upgrade header or CONNECT method, but have no handler.
<ide> socket.destroy();
<ide> }
<del> freeParser(parser, req, socket);
<ide> } else if (parser.incoming && parser.incoming.complete &&
<ide> // When the status code is 100 (Continue), the server will
<ide> // send a final response after this client sends a request
<ide><path>test/parallel/test-http-parser-freed-before-upgrade.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const http = require('http');
<add>
<add>const server = http.createServer();
<add>
<add>server.on('upgrade', common.mustCall((request, socket) => {
<add> assert.strictEqual(socket.parser, null);
<add> socket.write([
<add> 'HTTP/1.1 101 Switching Protocols',
<add> 'Connection: Upgrade',
<add> 'Upgrade: WebSocket',
<add> '\r\n'
<add> ].join('\r\n'));
<add>}));
<add>
<add>server.listen(common.mustCall(() => {
<add> const request = http.get({
<add> port: server.address().port,
<add> headers: {
<add> Connection: 'Upgrade',
<add> Upgrade: 'WebSocket'
<add> }
<add> });
<add>
<add> request.on('upgrade', common.mustCall((response, socket) => {
<add> assert.strictEqual(socket.parser, null);
<add> socket.destroy();
<add> server.close();
<add> }));
<add>})); | 2 |
Ruby | Ruby | add test for safe_join | 31560955907b764d9951ff9b188cff722473ed26 | <ide><path>actionview/test/template/output_safety_helper_test.rb
<ide> def setup
<ide> assert_equal ""a" <br/> <b> <br/> <c>", joined
<ide> end
<ide>
<add> test "safe_join should return the safe string separated by $, when second argument is not passed" do
<add> joined = safe_join(["a", "b"])
<add> assert_equal "a#{$,}b", joined
<add> end
<add>
<ide> test "to_sentence should escape non-html_safe values" do
<ide> actual = to_sentence(%w(< > & ' "))
<ide> assert actual.html_safe? | 1 |
Ruby | Ruby | pass the mixin in to the code generation methods | c856d895bd054d0c474f1a3876257400db529590 | <ide><path>activerecord/lib/active_record/associations/builder/association.rb
<ide> def mixin
<ide> end
<ide>
<ide> def build
<del> define_accessors
<add> define_accessors(mixin)
<ide> configure_dependency if options[:dependent]
<ide> reflection = ActiveRecord::Reflection.create(macro, name, scope, options, model)
<ide> Association.extensions.each do |extension|
<ide> def validate_options
<ide> #
<ide> # Post.first.comments and Post.first.comments= methods are defined by this method...
<ide>
<del> def define_accessors
<del> define_readers
<del> define_writers
<add> def define_accessors(mixin)
<add> define_readers(mixin)
<add> define_writers(mixin)
<ide> end
<ide>
<del> def define_readers
<add> def define_readers(mixin)
<ide> mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
<ide> def #{name}(*args)
<ide> association(:#{name}).reader(*args)
<ide> end
<ide> CODE
<ide> end
<ide>
<del> def define_writers
<add> def define_writers(mixin)
<ide> mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
<ide> def #{name}=(value)
<ide> association(:#{name}).writer(value)
<ide><path>activerecord/lib/active_record/associations/builder/collection_association.rb
<ide> def define_callback(callback_name)
<ide>
<ide> # Defines the setter and getter methods for the collection_singular_ids.
<ide>
<del> def define_readers
<add> def define_readers(mixin)
<ide> super
<ide>
<ide> mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
<ide> def #{name.to_s.singularize}_ids
<ide> CODE
<ide> end
<ide>
<del> def define_writers
<add> def define_writers(mixin)
<ide> super
<ide>
<ide> mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
<ide><path>activerecord/lib/active_record/associations/builder/singular_association.rb
<ide> def constructable?
<ide> true
<ide> end
<ide>
<del> def define_accessors
<add> def define_accessors(mixin)
<ide> super
<del> define_constructors if constructable?
<add> define_constructors(mixin) if constructable?
<ide> end
<ide>
<ide> # Defines the (build|create)_association methods for belongs_to or has_one association
<ide>
<del> def define_constructors
<add> def define_constructors(mixin)
<ide> mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
<ide> def build_#{name}(*args, &block)
<ide> association(:#{name}).build(*args, &block) | 3 |
Javascript | Javascript | handle data visibility per chart | 29115c9d2c94f5f52a22fa5e9d39244726a7d9d2 | <ide><path>src/controllers/controller.doughnut.js
<ide> module.exports = function(Chart) {
<ide> var data = chart.data;
<ide> if (data.labels.length && data.datasets.length) {
<ide> return data.labels.map(function(label, i) {
<add> var meta = chart.getDatasetMeta(0);
<ide> var ds = data.datasets[0];
<del> var arc = chart.getDatasetMeta(0).data[i];
<add> var arc = meta.data[i];
<ide> var fill = arc.custom && arc.custom.backgroundColor ? arc.custom.backgroundColor : helpers.getValueAtIndexOrDefault(ds.backgroundColor, i, this.chart.options.elements.arc.backgroundColor);
<ide> var stroke = arc.custom && arc.custom.borderColor ? arc.custom.borderColor : helpers.getValueAtIndexOrDefault(ds.borderColor, i, this.chart.options.elements.arc.borderColor);
<ide> var bw = arc.custom && arc.custom.borderWidth ? arc.custom.borderWidth : helpers.getValueAtIndexOrDefault(ds.borderWidth, i, this.chart.options.elements.arc.borderWidth);
<ide> module.exports = function(Chart) {
<ide> fillStyle: fill,
<ide> strokeStyle: stroke,
<ide> lineWidth: bw,
<del> hidden: isNaN(data.datasets[0].data[i]),
<add> hidden: isNaN(ds.data[i]) || meta.data[i].hidden,
<ide>
<ide> // Extra data used for toggling the correct item
<ide> index: i
<ide> module.exports = function(Chart) {
<ide> }
<ide> }
<ide> },
<add>
<ide> onClick: function(e, legendItem) {
<del> helpers.each(this.chart.data.datasets, function(dataset, datasetIndex) {
<del> var meta = this.chart.getDatasetMeta(datasetIndex);
<del> var idx = legendItem.index;
<del>
<del> if (!isNaN(dataset.data[idx])) {
<del> meta.hiddenData[idx] = dataset.data[idx];
<del> dataset.data[idx] = NaN;
<del> } else if (!isNaN(meta.hiddenData[idx])) {
<del> dataset.data[idx] = meta.hiddenData[idx];
<del> }
<del> }, this);
<add> var index = legendItem.index;
<add> var chart = this.chart;
<add> var i, ilen, meta;
<add>
<add> for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
<add> meta = chart.getDatasetMeta(i);
<add> meta.data[index].hidden = !meta.data[index].hidden;
<add> }
<ide>
<del> this.chart.update();
<add> chart.update();
<ide> }
<ide> },
<ide>
<ide> module.exports = function(Chart) {
<ide> this.chart.offsetX = offset.x * this.chart.outerRadius;
<ide> this.chart.offsetY = offset.y * this.chart.outerRadius;
<ide>
<del> this.getDataset().total = 0;
<del> helpers.each(this.getDataset().data, function(value) {
<del> if (!isNaN(value)) {
<del> this.getDataset().total += Math.abs(value);
<del> }
<del> }, this);
<add> this.getMeta().total = this.calculateTotal();
<ide>
<ide> this.outerRadius = this.chart.outerRadius - (this.chart.radiusLength * this.getRingIndex(this.index));
<ide> this.innerRadius = this.outerRadius - this.chart.radiusLength;
<ide> module.exports = function(Chart) {
<ide> this.updateElement(arc, index, reset);
<ide> }, this);
<ide> },
<add>
<ide> updateElement: function(arc, index, reset) {
<ide> var centerX = (this.chart.chartArea.left + this.chart.chartArea.right) / 2;
<ide> var centerY = (this.chart.chartArea.top + this.chart.chartArea.bottom) / 2;
<ide> var startAngle = this.chart.options.rotation; // non reset case handled later
<ide> var endAngle = this.chart.options.rotation; // non reset case handled later
<del> var circumference = reset && this.chart.options.animation.animateRotate ? 0 : this.calculateCircumference(this.getDataset().data[index]) * (this.chart.options.circumference / (2.0 * Math.PI));
<add> var circumference = reset && this.chart.options.animation.animateRotate ? 0 : arc.hidden? 0 : this.calculateCircumference(this.getDataset().data[index]) * (this.chart.options.circumference / (2.0 * Math.PI));
<ide> var innerRadius = reset && this.chart.options.animation.animateScale ? 0 : this.innerRadius;
<ide> var outerRadius = reset && this.chart.options.animation.animateScale ? 0 : this.outerRadius;
<ide>
<ide> module.exports = function(Chart) {
<ide> arc._model.borderWidth = arc.custom && arc.custom.borderWidth ? arc.custom.borderWidth : helpers.getValueAtIndexOrDefault(this.getDataset().borderWidth, index, this.chart.options.elements.arc.borderWidth);
<ide> },
<ide>
<add> calculateTotal: function() {
<add> var meta = this.getMeta();
<add> var total = 0;
<add>
<add> this.getDataset().data.forEach(function(value, index) {
<add> if (!isNaN(value) && !meta.data[index].hidden) {
<add> total += Math.abs(value);
<add> }
<add> });
<add>
<add> return total;
<add> },
<add>
<ide> calculateCircumference: function(value) {
<del> if (this.getDataset().total > 0 && !isNaN(value)) {
<del> return (Math.PI * 2.0) * (value / this.getDataset().total);
<add> var total = this.getMeta().total;
<add> if (total > 0 && !isNaN(value)) {
<add> return (Math.PI * 2.0) * (value / total);
<ide> } else {
<ide> return 0;
<ide> }
<ide><path>src/controllers/controller.polarArea.js
<ide> module.exports = function(Chart) {
<ide> var data = chart.data;
<ide> if (data.labels.length && data.datasets.length) {
<ide> return data.labels.map(function(label, i) {
<add> var meta = chart.getDatasetMeta(0);
<ide> var ds = data.datasets[0];
<del> var arc = chart.getDatasetMeta(0).data[i];
<add> var arc = meta.data[i];
<ide> var fill = arc.custom && arc.custom.backgroundColor ? arc.custom.backgroundColor : helpers.getValueAtIndexOrDefault(ds.backgroundColor, i, this.chart.options.elements.arc.backgroundColor);
<ide> var stroke = arc.custom && arc.custom.borderColor ? arc.custom.borderColor : helpers.getValueAtIndexOrDefault(ds.borderColor, i, this.chart.options.elements.arc.borderColor);
<ide> var bw = arc.custom && arc.custom.borderWidth ? arc.custom.borderWidth : helpers.getValueAtIndexOrDefault(ds.borderWidth, i, this.chart.options.elements.arc.borderWidth);
<ide> module.exports = function(Chart) {
<ide> fillStyle: fill,
<ide> strokeStyle: stroke,
<ide> lineWidth: bw,
<del> hidden: isNaN(data.datasets[0].data[i]),
<add> hidden: isNaN(ds.data[i]) || meta.data[i].hidden,
<ide>
<ide> // Extra data used for toggling the correct item
<ide> index: i
<ide> module.exports = function(Chart) {
<ide> }
<ide> }
<ide> },
<add>
<ide> onClick: function(e, legendItem) {
<del> helpers.each(this.chart.data.datasets, function(dataset, datasetIndex) {
<del> var meta = this.chart.getDatasetMeta(datasetIndex);
<del> var idx = legendItem.index;
<del>
<del> if (!isNaN(dataset.data[idx])) {
<del> meta.hiddenData[idx] = dataset.data[idx];
<del> dataset.data[idx] = NaN;
<del> } else if (!isNaN(meta.hiddenData[idx])) {
<del> dataset.data[idx] = meta.hiddenData[idx];
<del> }
<del> }, this);
<add> var index = legendItem.index;
<add> var chart = this.chart;
<add> var i, ilen, meta;
<add>
<add> for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
<add> meta = chart.getDatasetMeta(i);
<add> meta.data[index].hidden = !meta.data[index].hidden;
<add> }
<ide>
<del> this.chart.update();
<add> chart.update();
<ide> }
<ide> },
<ide>
<ide> module.exports = function(Chart) {
<ide> this.chart.innerRadius = Math.max(this.chart.options.cutoutPercentage ? (this.chart.outerRadius / 100) * (this.chart.options.cutoutPercentage) : 1, 0);
<ide> this.chart.radiusLength = (this.chart.outerRadius - this.chart.innerRadius) / this.chart.getVisibleDatasetCount();
<ide>
<del> this.getDataset().total = 0;
<del> helpers.each(this.getDataset().data, function(value) {
<del> this.getDataset().total += Math.abs(value);
<del> }, this);
<del>
<ide> this.outerRadius = this.chart.outerRadius - (this.chart.radiusLength * this.index);
<ide> this.innerRadius = this.outerRadius - this.chart.radiusLength;
<ide>
<ide> module.exports = function(Chart) {
<ide>
<ide> // If there is NaN data before us, we need to calculate the starting angle correctly.
<ide> // We could be way more efficient here, but its unlikely that the polar area chart will have a lot of data
<del> var notNullIndex = 0;
<add> var visibleCount = 0;
<add> var meta = this.getMeta();
<ide> for (var i = 0; i < index; ++i) {
<del> if (!isNaN(this.getDataset().data[i])) {
<del> ++notNullIndex;
<add> if (!isNaN(this.getDataset().data[i]) && !meta.data[i].hidden) {
<add> ++visibleCount;
<ide> }
<ide> }
<ide>
<del> var startAngle = (-0.5 * Math.PI) + (circumference * notNullIndex);
<del> var endAngle = startAngle + circumference;
<add> var distance = arc.hidden? 0 : this.chart.scale.getDistanceFromCenterForValue(this.getDataset().data[index]);
<add> var startAngle = (-0.5 * Math.PI) + (circumference * visibleCount);
<add> var endAngle = startAngle + (arc.hidden? 0 : circumference);
<ide>
<ide> var resetModel = {
<ide> x: centerX,
<ide> y: centerY,
<ide> innerRadius: 0,
<del> outerRadius: this.chart.options.animateScale ? 0 : this.chart.scale.getDistanceFromCenterForValue(this.getDataset().data[index]),
<add> outerRadius: this.chart.options.animateScale ? 0 : distance,
<ide> startAngle: this.chart.options.animateRotate ? Math.PI * -0.5 : startAngle,
<ide> endAngle: this.chart.options.animateRotate ? Math.PI * -0.5 : endAngle,
<ide>
<ide> module.exports = function(Chart) {
<ide> x: centerX,
<ide> y: centerY,
<ide> innerRadius: 0,
<del> outerRadius: this.chart.scale.getDistanceFromCenterForValue(this.getDataset().data[index]),
<add> outerRadius: distance,
<ide> startAngle: startAngle,
<ide> endAngle: endAngle,
<ide>
<ide> module.exports = function(Chart) {
<ide> calculateCircumference: function(value) {
<ide> if (isNaN(value)) {
<ide> return 0;
<del> } else {
<del> // Count the number of NaN values
<del> var numNaN = helpers.where(this.getDataset().data, function(data) {
<del> return isNaN(data);
<del> }).length;
<del>
<del> return (2 * Math.PI) / (this.getDataset().data.length - numNaN);
<ide> }
<add>
<add> // Count the number of "visible"" values
<add> var meta = this.getMeta();
<add> var count = 0;
<add>
<add> this.getDataset().data.forEach(function(value, index) {
<add> if (!isNaN(value) && !meta.data[index].hidden) {
<add> count++;
<add> }
<add> });
<add>
<add> return (2 * Math.PI) / count;
<ide> }
<ide> });
<ide>
<del>};
<ide>\ No newline at end of file
<add>};
<ide><path>src/core/core.controller.js
<ide> module.exports = function(Chart) {
<ide> data: [],
<ide> dataset: null,
<ide> controller: null,
<del> hiddenData: {},
<ide> hidden: null, // See isDatasetVisible() comment
<ide> xAxisID: null,
<ide> yAxisID: null
<ide><path>src/core/core.element.js
<ide> module.exports = function(Chart) {
<ide> this.initialize.apply(this, arguments);
<ide> };
<ide> helpers.extend(Chart.Element.prototype, {
<del> initialize: function() {},
<add> initialize: function() {
<add> this.hidden = false;
<add> },
<ide> pivot: function() {
<ide> if (!this._view) {
<ide> this._view = helpers.clone(this._model);
<ide><path>src/scales/scale.linear.js
<ide> module.exports = function(Chart) {
<ide>
<ide> if (this.chart.isDatasetVisible(datasetIndex) && (this.isHorizontal() ? meta.xAxisID === this.id : meta.yAxisID === this.id)) {
<ide> helpers.each(dataset.data, function(rawValue, index) {
<del>
<ide> var value = +this.getRightValue(rawValue);
<del> if (isNaN(value)) {
<add> if (isNaN(value) || meta.data[index].hidden) {
<ide> return;
<ide> }
<ide>
<ide> module.exports = function(Chart) {
<ide> if (this.chart.isDatasetVisible(datasetIndex) && (this.isHorizontal() ? meta.xAxisID === this.id : meta.yAxisID === this.id)) {
<ide> helpers.each(dataset.data, function(rawValue, index) {
<ide> var value = +this.getRightValue(rawValue);
<del> if (isNaN(value)) {
<add> if (isNaN(value) || meta.data[index].hidden) {
<ide> return;
<ide> }
<ide>
<ide><path>src/scales/scale.logarithmic.js
<ide> module.exports = function(Chart) {
<ide> helpers.each(dataset.data, function(rawValue, index) {
<ide> var values = valuesPerType[meta.type];
<ide> var value = +this.getRightValue(rawValue);
<del> if (isNaN(value)) {
<add> if (isNaN(value) || meta.data[index].hidden) {
<ide> return;
<ide> }
<ide>
<ide> module.exports = function(Chart) {
<ide> } else {
<ide> helpers.each(this.chart.data.datasets, function(dataset, datasetIndex) {
<ide> var meta = this.chart.getDatasetMeta(datasetIndex);
<del> if (this.chart.isDatasetVisible(dataset, datasetIndex) && (this.isHorizontal() ? meta.xAxisID === this.id : meta.yAxisID === this.id)) {
<add> if (this.chart.isDatasetVisible(datasetIndex) && (this.isHorizontal() ? meta.xAxisID === this.id : meta.yAxisID === this.id)) {
<ide> helpers.each(dataset.data, function(rawValue, index) {
<ide> var value = +this.getRightValue(rawValue);
<del> if (isNaN(value)) {
<add> if (isNaN(value) || meta.data[index].hidden) {
<ide> return;
<ide> }
<ide>
<ide><path>src/scales/scale.radialLinear.js
<ide> module.exports = function(Chart) {
<ide>
<ide> helpers.each(this.chart.data.datasets, function(dataset, datasetIndex) {
<ide> if (this.chart.isDatasetVisible(datasetIndex)) {
<add> var meta = this.chart.getDatasetMeta(datasetIndex);
<ide> helpers.each(dataset.data, function(rawValue, index) {
<ide> var value = +this.getRightValue(rawValue);
<del> if (isNaN(value)) {
<add> if (isNaN(value) || meta.data[index].hidden) {
<ide> return;
<ide> }
<ide> | 7 |
Javascript | Javascript | fix syntax error for node older than 10 | 5339e5d528b07718fc69a6ca12da5acb09b81a7d | <ide><path>script/lib/verify-machine-requirements.js
<ide> function verifyPython() {
<ide> env: process.env,
<ide> stdio: ['ignore', 'pipe', 'ignore']
<ide> });
<del> } catch {}
<add> } catch (e) {}
<ide>
<ide> if (stdout) {
<ide> if (stdout.indexOf('+') !== -1) | 1 |
Javascript | Javascript | apply minor refactoring | 4fe081df44fdab28d241e73902f63390c5012772 | <ide><path>lib/assert.js
<del>// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
<del>//
<del>// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
<del>//
<ide> // Originally from narwhal.js (http://narwhaljs.org)
<ide> // Copyright (c) 2009 Thomas Robinson <280north.com>
<ide> //
<ide> function _deepEqual(actual, expected, strict, memos) {
<ide> }
<ide>
<ide> function isArguments(object) {
<del> return Object.prototype.toString.call(object) == '[object Arguments]';
<add> return Object.prototype.toString.call(object) === '[object Arguments]';
<ide> }
<ide>
<ide> function objEquiv(a, b, strict, actualVisitedObjects) {
<ide> function expectedException(actual, expected) {
<ide> return false;
<ide> }
<ide>
<del> if (Object.prototype.toString.call(expected) == '[object RegExp]') {
<add> if (Object.prototype.toString.call(expected) === '[object RegExp]') {
<ide> return expected.test(actual);
<ide> }
<ide> | 1 |
PHP | PHP | simplify validation on register stuff | 7a7e366da539d834279c1c9f1805bfbf8e9fe1ed | <ide><path>app/Http/Controllers/Auth/AuthController.php
<ide> <?php namespace App\Http\Controllers\Auth;
<ide>
<ide> use App\User;
<add>use Illuminate\Http\Request;
<ide> use App\Http\Controllers\Controller;
<ide> use Illuminate\Contracts\Auth\Guard;
<del>use App\Http\Requests\Auth\LoginRequest;
<del>use App\Http\Requests\Auth\RegisterRequest;
<ide>
<ide> class AuthController extends Controller {
<ide>
<ide> public function getRegister()
<ide> /**
<ide> * Handle a registration request for the application.
<ide> *
<del> * @param RegisterRequest $request
<add> * @param Request $request
<ide> * @return Response
<ide> */
<del> public function postRegister(RegisterRequest $request)
<add> public function postRegister(Request $request)
<ide> {
<add> $this->validate($request, [
<add> 'name' => 'required|max:255',
<add> 'email' => 'required|email|max:255|unique:users',
<add> 'password' => 'required|min:6|confirmed',
<add> ]);
<add>
<ide> $user = User::forceCreate([
<ide> 'name' => $request->name,
<ide> 'email' => $request->email,
<ide> public function getLogin()
<ide> /**
<ide> * Handle a login request to the application.
<ide> *
<del> * @param LoginRequest $request
<add> * @param Request $request
<ide> * @return Response
<ide> */
<del> public function postLogin(LoginRequest $request)
<add> public function postLogin(Request $request)
<ide> {
<add> $this->validate($request, [
<add> 'email' => 'required', 'password' => 'required'
<add> ]);
<add>
<ide> $credentials = $request->only('email', 'password');
<ide>
<ide> if ($this->auth->attempt($credentials, $request->has('remember')))
<ide><path>app/Http/Requests/Auth/LoginRequest.php
<del><?php namespace App\Http\Requests\Auth;
<del>
<del>use App\Http\Requests\Request;
<del>
<del>class LoginRequest extends Request {
<del>
<del> /**
<del> * Get the validation rules that apply to the request.
<del> *
<del> * @return array
<del> */
<del> public function rules()
<del> {
<del> return [
<del> 'email' => 'required', 'password' => 'required',
<del> ];
<del> }
<del>
<del> /**
<del> * Determine if the user is authorized to make this request.
<del> *
<del> * @return bool
<del> */
<del> public function authorize()
<del> {
<del> return true;
<del> }
<del>
<del>}
<ide><path>app/Http/Requests/Auth/RegisterRequest.php
<del><?php namespace App\Http\Requests\Auth;
<del>
<del>use App\Http\Requests\Request;
<del>
<del>class RegisterRequest extends Request {
<del>
<del> /**
<del> * Get the validation rules that apply to the request.
<del> *
<del> * @return array
<del> */
<del> public function rules()
<del> {
<del> return [
<del> 'name' => 'required|max:255',
<del> 'email' => 'required|max:255|email|unique:users',
<del> 'password' => 'required|confirmed|min:8',
<del> ];
<del> }
<del>
<del> /**
<del> * Determine if the user is authorized to make this request.
<del> *
<del> * @return bool
<del> */
<del> public function authorize()
<del> {
<del> return true;
<del> }
<del>
<del>} | 3 |
Javascript | Javascript | improve the code in test-process-cpuusage | c963094f3cf3d42af5255f1a340cb97884c641d8 | <ide><path>test/parallel/test-process-cpuUsage.js
<ide> for (let i = 0; i < 10; i++) {
<ide> assert(diffUsage.system >= 0);
<ide> }
<ide>
<add>const invalidUserArgument =
<add> /^TypeError: value of user property of argument is invalid$/;
<add>const invalidSystemArgument =
<add> /^TypeError: value of system property of argument is invalid$/;
<add>
<ide> // Ensure that an invalid shape for the previous value argument throws an error.
<del>assert.throws(function() { process.cpuUsage(1); });
<del>assert.throws(function() { process.cpuUsage({}); });
<del>assert.throws(function() { process.cpuUsage({ user: 'a' }); });
<del>assert.throws(function() { process.cpuUsage({ system: 'b' }); });
<del>assert.throws(function() { process.cpuUsage({ user: null, system: 'c' }); });
<del>assert.throws(function() { process.cpuUsage({ user: 'd', system: null }); });
<del>assert.throws(function() { process.cpuUsage({ user: -1, system: 2 }); });
<del>assert.throws(function() { process.cpuUsage({ user: 3, system: -2 }); });
<del>assert.throws(function() {
<add>assert.throws(() => {
<add> process.cpuUsage(1);
<add>}, invalidUserArgument);
<add>
<add>assert.throws(() => {
<add> process.cpuUsage({});
<add>}, invalidUserArgument);
<add>
<add>assert.throws(() => {
<add> process.cpuUsage({ user: 'a' });
<add>}, invalidUserArgument);
<add>
<add>assert.throws(() => {
<add> process.cpuUsage({ system: 'b' });
<add>}, invalidUserArgument);
<add>
<add>assert.throws(() => {
<add> process.cpuUsage({ user: null, system: 'c' });
<add>}, invalidUserArgument);
<add>
<add>assert.throws(() => {
<add> process.cpuUsage({ user: 'd', system: null });
<add>}, invalidUserArgument);
<add>
<add>assert.throws(() => {
<add> process.cpuUsage({ user: -1, system: 2 });
<add>}, invalidUserArgument);
<add>
<add>assert.throws(() => {
<add> process.cpuUsage({ user: 3, system: -2 });
<add>}, invalidSystemArgument);
<add>
<add>assert.throws(() => {
<ide> process.cpuUsage({
<ide> user: Number.POSITIVE_INFINITY,
<ide> system: 4
<ide> });
<del>});
<del>assert.throws(function() {
<add>}, invalidUserArgument);
<add>
<add>assert.throws(() => {
<ide> process.cpuUsage({
<ide> user: 5,
<ide> system: Number.NEGATIVE_INFINITY
<ide> });
<del>});
<add>}, invalidSystemArgument);
<ide>
<ide> // Ensure that the return value is the expected shape.
<ide> function validateResult(result) { | 1 |
Go | Go | fix race in logevent | a1b7a35c90f05b113b7c3aa474b74d1d2afbf7b6 | <ide><path>server/server.go
<ide> func (srv *Server) LogEvent(action, id, from string) *utils.JSONMessage {
<ide> now := time.Now().UTC().Unix()
<ide> jm := utils.JSONMessage{Status: action, ID: id, From: from, Time: now}
<ide> srv.AddEvent(jm)
<add> srv.Lock()
<ide> for _, c := range srv.listeners {
<ide> select { // non blocking channel
<ide> case c <- jm:
<ide> default:
<ide> }
<ide> }
<add> srv.Unlock()
<ide> return &jm
<ide> }
<ide> | 1 |
Javascript | Javascript | move player id generation | 1cab78347d244996eb8b0c2a49f541c0283e9d3d | <ide><path>src/js/player.js
<ide> vjs.Player = vjs.Component.extend({
<ide> init: function(tag, options, ready){
<ide> this.tag = tag; // Store the original tag used to set options
<ide>
<add> // Make sure tag ID exists
<add> tag.id = tag.id || 'vjs_video_' + vjs.guid++;
<add>
<ide> // Set Options
<ide> // The options argument overrides options set in the video tag
<ide> // which overrides globally set options.
<ide> vjs.Player.prototype.createEl = function(){
<ide> }
<ide> }
<ide>
<del> // Make sure tag ID exists
<del> tag.id = tag.id || 'vjs_video_' + vjs.guid++;
<del>
<ide> // Give video tag ID and class to player div
<ide> // ID will now reference player box, not the video tag
<ide> el.id = tag.id;
<ide><path>test/unit/player.js
<ide> test('should use custom message when encountering an unsupported video type',
<ide>
<ide> player.dispose();
<ide> });
<add>
<add>test('should register players with generated ids', function(){
<add> var fixture, video, player, id;
<add> fixture = document.getElementById('qunit-fixture');
<add>
<add> video = document.createElement('video');
<add> video.className = 'vjs-default-skin video-js';
<add> fixture.appendChild(video);
<add>
<add> player = new vjs.Player(video);
<add> id = player.el().id;
<add>
<add> equal(player.el().id, player.id(), 'the player and element ids are equal');
<add> ok(vjs.players[id], 'the generated id is registered');
<add>}); | 2 |
PHP | PHP | remove asset.x configure values | bd3428e45659078e29938cf20198ff7e6ef0869e | <ide><path>lib/Cake/Test/Case/View/Helper/FormHelperTest.php
<ide> public function setUp() {
<ide> parent::setUp();
<ide>
<ide> Configure::write('App.base', '');
<add> Configure::delete('Asset');
<ide> $this->Controller = new ContactTestController();
<ide> $this->View = new View($this->Controller);
<ide> | 1 |
Javascript | Javascript | rewrite issymbol to be simpler | 4239f8ac3bf3dcbcc8554e3b821f562831eeb663 | <ide><path>src/isomorphic/classic/types/ReactPropTypes.js
<ide> function isNode(propValue) {
<ide> }
<ide>
<ide> function isSymbol(propType, propValue) {
<add> // Native Symbol.
<ide> if (propType === 'symbol') {
<del> return true; // This is a native Symbol.
<add> return true;
<ide> }
<ide>
<del> if (typeof Symbol === 'undefined') {
<del> // No Symbol is available in the global namespace.
<del> // We need to check if it has some spec-defined method (duck typing).
<del>
<del> if (propValue['@@toStringTag'] === 'Symbol') {
<del> return true;
<del> }
<add> // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'
<add> if (propValue['@@toStringTag'] === 'Symbol') {
<add> return true;
<add> }
<ide>
<del> if (propValue.__key__ && propValue.prototype.__key__ === undefined) {
<del> return propValue.toString() === 'Symbol'
<del> }
<del> } else {
<del> return propValue instanceof Symbol; // This is a polyfilled Symbol.
<add> // Fallback for non-spec compliant Symbols which are polyfilled.
<add> if (typeof Symbol !== 'undefined' && propValue instanceof Symbol) {
<add> return true;
<ide> }
<ide>
<ide> return false; | 1 |
Python | Python | fix exception marshalling with json serializer | 33e72fdbc7b07fc26d13bcdc36fb6f42c8291b66 | <ide><path>celery/backends/amqp.py
<ide> def drain_events(self, connection, consumer,
<ide>
<ide> def callback(meta, message):
<ide> if meta['status'] in states.READY_STATES:
<del> results[meta['task_id']] = meta
<add> results[meta['task_id']] = self.meta_from_decoded(meta)
<ide>
<ide> consumer.callbacks[:] = [callback]
<ide> time_start = now() | 1 |
Text | Text | remove unclear text from fs.write() | a55c4fdeb13b63029c4e4960be4baadbda8279b0 | <ide><path>doc/api/fs.md
<ide> The callback will receive the arguments `(err, written, string)` where `written`
<ide> specifies how many _bytes_ the passed string required to be written. Note that
<ide> bytes written is not the same as string characters. See [`Buffer.byteLength`][].
<ide>
<del>Unlike when writing `buffer`, the entire string must be written. No substring
<del>may be specified. This is because the byte offset of the resulting data may not
<del>be the same as the string offset.
<del>
<ide> Note that it is unsafe to use `fs.write` multiple times on the same file
<ide> without waiting for the callback. For this scenario,
<ide> `fs.createWriteStream` is strongly recommended. | 1 |
Python | Python | fix bug with graph sample_weights | 56ae624f1238c293e2633677aa721bf548ac0186 | <ide><path>keras/models.py
<ide> def _fit(self, f, ins, out_labels=[], batch_size=128, nb_epoch=100, verbose=1, c
<ide> try:
<ide> ins_batch = slice_X(ins, batch_ids)
<ide> except TypeError as err:
<del> print('TypeError while preparing batch. \
<add> raise Exception('TypeError while preparing batch. \
<ide> If using HDF5 input data, pass shuffle="batch".\n')
<del> raise
<ide>
<ide> batch_logs = {}
<ide> batch_logs['batch'] = batch_index
<ide> def fit(self, data, batch_size=128, nb_epoch=100, verbose=1, callbacks=[],
<ide> validation_split=0., validation_data=None, shuffle=True, class_weight={}, sample_weight={}):
<ide> X = [data[name] for name in self.input_order]
<ide> y = [standardize_y(data[name]) for name in self.output_order]
<del> sample_weight_list = [standardize_weights(data[name],
<del> sample_weight=sample_weight.get(name)) for name in self.output_order]
<add>
<add> sample_weight_list = [standardize_weights(y[i],
<add> sample_weight=sample_weight.get(self.output_order[i])) for i in range(len(self.output_order))]
<ide> class_weight_list = [class_weight.get(name) for name in self.output_order]
<ide>
<ide> val_f = None
<ide> def fit(self, data, batch_size=128, nb_epoch=100, verbose=1, callbacks=[],
<ide> sample_weight=sample_weight_list[i],
<ide> class_weight=class_weight_list[i]) for i in range(len(self.output_order))]
<ide> ins = X + y + sample_weight_list
<del>
<ide> history = self._fit(f, ins, out_labels=out_labels, batch_size=batch_size, nb_epoch=nb_epoch,
<ide> verbose=verbose, callbacks=callbacks,
<ide> val_f=val_f, val_ins=val_ins, | 1 |
Text | Text | move the comment on line 71 to its own line | d824c770123bf626e2930303ffaed7d09bab299d | <ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-pass-an-object-as-a-functions-parameters.english.md
<ide> const stats = {
<ide> average: 35.85
<ide> };
<ide>
<add>// use function argument destructuring
<ide> // change code below this line
<del>const half = (stats) => (stats.max + stats.min) / 2.0; // use function argument destructuring
<add>const half = (stats) => (stats.max + stats.min) / 2.0;
<ide> // change code above this line
<ide>
<ide> console.log(stats); // should be object | 1 |
Javascript | Javascript | optimize a loop in buffergeometry.merge() | 8e49e00734b261e67c781b5b152f0bf2a9f3853c | <ide><path>src/core/BufferGeometry.js
<ide> BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototy
<ide> var attribute2 = geometry.attributes[ key ];
<ide> var attributeArray2 = attribute2.array;
<ide>
<del> var attributeSize = attribute2.itemSize;
<add> var attributeOffset = attribute2.itemSize * offset;
<add> var length = Math.min( attributeArray2.length, attributeArray1.length - attributeOffset );
<ide>
<del> for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length && j < attributeArray1.length; i ++, j ++ ) {
<add> for ( var i = 0, j = attributeOffset; i < length; i ++, j ++ ) {
<ide>
<ide> attributeArray1[ j ] = attributeArray2[ i ];
<ide> | 1 |
Javascript | Javascript | remove custom manager test | 52c48d08158857329e8bdd52873fefca32780057 | <ide><path>packages/ember-glimmer/tests/integration/custom-component-manager-test.js
<del>import { moduleFor, RenderingTest } from '../utils/test-case';
<del>import {
<del> GLIMMER_CUSTOM_COMPONENT_MANAGER
<del>} from 'ember/features';
<del>import { AbstractComponentManager } from 'ember-glimmer';
<del>
<del>if (GLIMMER_CUSTOM_COMPONENT_MANAGER) {
<del> /*
<del> Implementation of custom component manager, `ComponentManager` interface
<del> */
<del> class TestComponentManager extends AbstractComponentManager {
<del> create(env, definition) {
<del> return definition.ComponentClass.create();
<del> }
<del>
<del> getDestructor(component) {
<del> return component;
<del> }
<del>
<del> getSelf() {
<del> return null;
<del> }
<del> }
<del>
<del> moduleFor('Components test: curly components with custom manager', class extends RenderingTest {
<del> ['@skip it can render a basic component with custom component manager'](assert) {
<del> let managerId = 'test';
<del> this.owner.register(`component-manager:${managerId}`, new TestComponentManager());
<del> this.registerComponent('foo-bar', {
<del> template: `{{use-component-manager "${managerId}"}}hello`,
<del> managerId
<del> });
<del>
<del> this.render('{{foo-bar}}');
<del>
<del> assert.equal(this.firstChild.className, 'hey-oh-lets-go', 'class name was set correctly');
<del> assert.equal(this.firstChild.tagName, 'P', 'tag name was set correctly');
<del> assert.equal(this.firstChild.getAttribute('manager-id'), managerId, 'custom attribute was set correctly');
<del> }
<del> });
<del>} | 1 |
PHP | PHP | use short array syntax | 14fca9b0fc6fee01c08018995c2a343cecc7058d | <ide><path>src/View/Helper/SessionHelper.php
<ide> public function error() {
<ide> * @return string
<ide> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/session.html#SessionHelper::flash
<ide> */
<del> public function flash($key = 'flash', $attrs = array()) {
<del>
<add> public function flash($key = 'flash', $attrs = []) {
<ide> if (!Session::check('Message.' . $key)) {
<ide> return '';
<ide> } | 1 |
Go | Go | use default port range in unit tests | fcf8e85a35cddfd1f75f652a513015bb6f169257 | <ide><path>daemon/networkdriver/portallocator/portallocator_test.go
<ide> import (
<ide>
<ide> func init() {
<ide> beginPortRange = DefaultPortRangeStart
<del> endPortRange = DefaultPortRangeStart + 500
<add> endPortRange = DefaultPortRangeEnd
<ide> }
<ide>
<ide> func reset() { | 1 |
Javascript | Javascript | add more description of `controller as` syntax | 462eefc1e45236bf451fce851ec58169915b71cd | <ide><path>src/ng/directive/ngController.js
<ide> * @example
<ide> * Here is a simple form for editing user contact information. Adding, removing, clearing, and
<ide> * greeting are methods declared on the controller (see source tab). These methods can
<del> * easily be called from the angular markup. Notice that the scope becomes the `this` for the
<del> * controller's instance. This allows for easy access to the view data from the controller. Also
<del> * notice that any changes to the data are automatically reflected in the View without the need
<del> * for a manual update. The example is shown in two different declaration styles you may use
<del> * according to preference.
<add> * easily be called from the angular markup. Any changes to the data are automatically reflected
<add> * in the View without the need for a manual update.
<add> *
<add> * Two different declaration styles are included below: one which injects `scope` into the
<add> * controller, and another which instead binds methods and properties directly onto the controller
<add> * using `this`. The first option is more common in the Angular community, and is generally used
<add> * in boilerplates and in this guide. However, there are advantages to binding properties directly
<add> * to the controller and avoiding scope. Using `controller as` makes it obvious which controller
<add> * you are accessing in the template when multiple controllers apply to an element. Since there
<add> * is always a `.` in the bindings, you don't have to worry about prototypal inheritance masking
<add> * primitives.
<ide> <example>
<ide> <file name="index.html">
<ide> <script> | 1 |
Text | Text | fix a link in dgram.md | bbd95554c0d8bc3511a6a118e7e42458e5044a39 | <ide><path>doc/api/dgram.md
<ide> and `udp6` sockets). The bound address and port can be retrieved using
<ide> [`socket.bind()`]: #dgram_socket_bind_port_address_callback
<ide> [`System Error`]: errors.html#errors_class_systemerror
<ide> [byte length]: buffer.html#buffer_class_method_buffer_bytelength_string_encoding
<del>[IPv6 Zone Indices]: https://en.wikipedia.org/wiki/IPv6_address#Link-local_addresses_and_zone_indices
<add>[IPv6 Zone Indices]: https://en.wikipedia.org/wiki/IPv6_address#Scoped_literal_IPv6_addresses
<ide> [RFC 4007]: https://tools.ietf.org/html/rfc4007 | 1 |
Javascript | Javascript | update removehash handling for stats-app | 864d5c6bd82339b4895ae496b865a4ee1a4ab290 | <ide><path>.github/actions/next-stats-action/src/run/index.js
<ide> async function runConfigs(
<ide> const results = await glob(rename.srcGlob, { cwd: statsAppDir })
<ide> for (const result of results) {
<ide> let dest = rename.removeHash
<del> ? result.replace(/(\.|-)[0-9a-f]{20}(\.|-)/g, '$1HASH$2')
<add> ? result.replace(/(\.|-)[0-9a-f]{16}(\.|-)/g, '$1HASH$2')
<ide> : rename.dest
<ide> if (result === dest) continue
<ide> await fs.move( | 1 |
Javascript | Javascript | handle interceptors with `undefined` expressions | 4473b81cdaf16c5509ac53d80b9bdfb0a7ac5f30 | <ide><path>src/ng/parse.js
<ide> function $ParseProvider() {
<ide> return addInterceptor(exp, interceptorFn);
<ide>
<ide> default:
<del> return noop;
<add> return addInterceptor(noop, interceptorFn);
<ide> }
<ide> };
<ide>
<ide><path>test/ng/parseSpec.js
<ide> describe('parser', function() {
<ide> expect(called).toBe(true);
<ide> }));
<ide>
<add> it('should invoke interceptors when the expression is `undefined`', inject(function($parse) {
<add> var called = false;
<add> function interceptor(v) {
<add> called = true;
<add> return v;
<add> }
<add> scope.$watch($parse(undefined, interceptor));
<add> scope.$digest();
<add> expect(called).toBe(true);
<add> }));
<add>
<ide> it('should treat filters with constant input as constants', inject(function($parse) {
<ide> var filterCalls = 0;
<ide> $filterProvider.register('foo', valueFn(function(input) { | 2 |
Text | Text | add a readme to the client's package… | a00106f9a5cf58cced011c93e98fbe1d7f65c4e7 | <ide><path>client/README.md
<add>## Client
<add>
<add>The client package implements a fully featured http client to interact with the Docker engine. It's modeled after the requirements of the Docker engine CLI, but it can also serve other purposes.
<add>
<add>### Usage
<add>
<add>You can use this client package in your applications by creating a new client object. Then use that object to execute operations against the remote server. Follow the example below to see how to list all the containers running in a Docker engine host:
<add>
<add>```go
<add>package main
<add>
<add>import (
<add> "fmt"
<add>
<add> "github.com/docker/docker/client"
<add> "github.com/docker/docker/api/types"
<add> "golang.org/x/net/context"
<add>)
<add>
<add>func main() {
<add> defaultHeaders := map[string]string{"User-Agent": "engine-api-cli-1.0"}
<add> cli, err := client.NewClient("unix:///var/run/docker.sock", "v1.22", nil, defaultHeaders)
<add> if err != nil {
<add> panic(err)
<add> }
<add>
<add> options := types.ContainerListOptions{All: true}
<add> containers, err := cli.ContainerList(context.Background(), options)
<add> if err != nil {
<add> panic(err)
<add> }
<add>
<add> for _, c := range containers {
<add> fmt.Println(c.ID)
<add> }
<add>}
<add>``` | 1 |
Javascript | Javascript | remove the comment of base64 validation | d5c383706130638d9772c5fdc18545a90424bff3 | <ide><path>lib/internal/validators.js
<ide> function validateEncoding(data, encoding) {
<ide> throw new ERR_INVALID_ARG_VALUE('encoding', encoding,
<ide> `is invalid for data of length ${length}`);
<ide> }
<del>
<del> // TODO(bnoordhuis) Add BASE64 check?
<ide> }
<ide>
<ide> module.exports = { | 1 |
Javascript | Javascript | fix incomplete json produced by doctool | 05d0e9e6a3ae7ed293ea46d0e978eb35a2b5107f | <ide><path>tools/doc/json.js
<ide> function processList(section) {
<ide> // event: each item is an argument.
<ide> section.params = values;
<ide> break;
<add>
<add> default:
<add> if (section.list.length > 0) {
<add> section.desc = section.desc || [];
<add> for (var i = 0; i < section.list.length; i++) {
<add> section.desc.push(section.list[i]);
<add> }
<add> }
<ide> }
<ide>
<ide> // section.listParsed = values; | 1 |
PHP | PHP | use arrow functions | b94a68253d77944d68ba22f3391c83df479e1617 | <ide><path>src/Illuminate/Bus/DatabaseBatchRepository.php
<ide> public function pruneUnfinished(DateTimeInterface $before)
<ide> */
<ide> public function transaction(Closure $callback)
<ide> {
<del> return $this->connection->transaction(function () use ($callback) {
<del> return $callback();
<del> });
<add> return $this->connection->transaction(fn () => $callback());
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Container/ContextualBindingBuilder.php
<ide> public function giveTagged($tag)
<ide> */
<ide> public function giveConfig($key, $default = null)
<ide> {
<del> $this->give(function ($container) use ($key, $default) {
<del> return $container->get('config')->get($key, $default);
<del> });
<add> $this->give(fn ($container) => $container->get('config')->get($key, $default));
<ide> }
<ide> }
<ide><path>src/Illuminate/Database/Eloquent/Factories/Factory.php
<ide> public function createQuietly($attributes = [], ?Model $parent = null)
<ide> */
<ide> public function lazy(array $attributes = [], ?Model $parent = null)
<ide> {
<del> return function () use ($attributes, $parent) {
<del> return $this->create($attributes, $parent);
<del> };
<add> return fn () => $this->create($attributes, $parent);
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Http/Request.php
<ide> public function __isset($key)
<ide> */
<ide> public function __get($key)
<ide> {
<del> return Arr::get($this->all(), $key, function () use ($key) {
<del> return $this->route($key);
<del> });
<add> return Arr::get($this->all(), $key, fn () => $this->route($key));
<ide> }
<ide> }
<ide><path>src/Illuminate/Pagination/PaginationState.php
<ide> class PaginationState
<ide> */
<ide> public static function resolveUsing($app)
<ide> {
<del> Paginator::viewFactoryResolver(function () use ($app) {
<del> return $app['view'];
<del> });
<add> Paginator::viewFactoryResolver(fn () => $app['view']);
<ide>
<del> Paginator::currentPathResolver(function () use ($app) {
<del> return $app['request']->url();
<del> });
<add> Paginator::currentPathResolver(fn () => $app['request']->url());
<ide>
<ide> Paginator::currentPageResolver(function ($pageName = 'page') use ($app) {
<ide> $page = $app['request']->input($pageName);
<ide> public static function resolveUsing($app)
<ide> return 1;
<ide> });
<ide>
<del> Paginator::queryStringResolver(function () use ($app) {
<del> return $app['request']->query();
<del> });
<add> Paginator::queryStringResolver(fn () => $app['request']->query());
<ide>
<ide> CursorPaginator::currentCursorResolver(function ($cursorName = 'cursor') use ($app) {
<ide> return Cursor::fromEncoded($app['request']->input($cursorName));
<ide><path>src/Illuminate/Support/Env.php
<ide> public static function get($key, $default = null)
<ide>
<ide> return $value;
<ide> })
<del> ->getOrCall(function () use ($default) {
<del> return value($default);
<del> });
<add> ->getOrCall(fn () => value($default));
<ide> }
<ide> }
<ide><path>src/Illuminate/Testing/ParallelRunner.php
<ide> protected function forEachProcess($callback)
<ide> {
<ide> collect(range(1, $this->options->processes()))->each(function ($token) use ($callback) {
<ide> tap($this->createApplication(), function ($app) use ($callback, $token) {
<del> ParallelTesting::resolveTokenUsing(function () use ($token) {
<del> return $token;
<del> });
<add> ParallelTesting::resolveTokenUsing(fn () => $token);
<ide>
<ide> $callback($app);
<ide> })->flush();
<ide><path>src/Illuminate/Validation/Validator.php
<ide> protected function replacePlaceholderInString(string $value)
<ide> */
<ide> public function after($callback)
<ide> {
<del> $this->after[] = function () use ($callback) {
<del> return $callback($this);
<del> };
<add> $this->after[] = fn () => $callback($this);
<ide>
<ide> return $this;
<ide> } | 8 |
Python | Python | prepare data, train, and eval on py3 | 26c96542c573f390daf447b38df50968b2649922 | <ide><path>research/deeplab/datasets/build_cityscapes_data.py
<ide> def _convert_dataset(dataset_split):
<ide> i + 1, num_images, shard_id))
<ide> sys.stdout.flush()
<ide> # Read the image.
<del> image_data = tf.gfile.FastGFile(image_files[i], 'r').read()
<add> image_data = tf.gfile.FastGFile(image_files[i], 'rb').read()
<ide> height, width = image_reader.read_image_dims(image_data)
<ide> # Read the semantic segmentation annotation.
<del> seg_data = tf.gfile.FastGFile(label_files[i], 'r').read()
<add> seg_data = tf.gfile.FastGFile(label_files[i], 'rb').read()
<ide> seg_height, seg_width = label_reader.read_image_dims(seg_data)
<ide> if height != seg_height or width != seg_width:
<ide> raise RuntimeError('Shape mismatched between image and label.')
<ide><path>research/deeplab/datasets/build_data.py
<ide> def _bytes_list_feature(values):
<ide> Returns:
<ide> A TF-Feature.
<ide> """
<del> return tf.train.Feature(bytes_list=tf.train.BytesList(value=[values]))
<add> def norm2bytes(value):
<add> return value.encode() if isinstance(value, str) else value
<add>
<add> return tf.train.Feature(bytes_list=tf.train.BytesList(value=[norm2bytes(values)]))
<ide>
<ide>
<ide> def image_seg_to_tfexample(image_data, filename, height, width, seg_data):
<ide><path>research/deeplab/datasets/build_voc2012_data.py
<ide> def _convert_dataset(dataset_split):
<ide> # Read the image.
<ide> image_filename = os.path.join(
<ide> FLAGS.image_folder, filenames[i] + '.' + FLAGS.image_format)
<del> image_data = tf.gfile.FastGFile(image_filename, 'r').read()
<add> image_data = tf.gfile.FastGFile(image_filename, 'rb').read()
<ide> height, width = image_reader.read_image_dims(image_data)
<ide> # Read the semantic segmentation annotation.
<ide> seg_filename = os.path.join(
<ide> FLAGS.semantic_segmentation_folder,
<ide> filenames[i] + '.' + FLAGS.label_format)
<del> seg_data = tf.gfile.FastGFile(seg_filename, 'r').read()
<add> seg_data = tf.gfile.FastGFile(seg_filename, 'rb').read()
<ide> seg_height, seg_width = label_reader.read_image_dims(seg_data)
<ide> if height != seg_height or width != seg_width:
<ide> raise RuntimeError('Shape mismatched between image and label.')
<ide><path>research/deeplab/eval.py
<ide> See model.py for more details and usage.
<ide> """
<ide>
<add>import six
<ide> import math
<ide> import tensorflow as tf
<ide> from deeplab import common
<ide> def main(unused_argv):
<ide> metrics_to_values, metrics_to_updates = (
<ide> tf.contrib.metrics.aggregate_metric_map(metric_map))
<ide>
<del> for metric_name, metric_value in metrics_to_values.iteritems():
<add> for metric_name, metric_value in six.iteritems(metrics_to_values):
<ide> slim.summaries.add_scalar_summary(
<ide> metric_value, metric_name, print_summary=True)
<ide>
<ide> def main(unused_argv):
<ide> checkpoint_dir=FLAGS.checkpoint_dir,
<ide> logdir=FLAGS.eval_logdir,
<ide> num_evals=num_batches,
<del> eval_op=metrics_to_updates.values(),
<add> eval_op=list(metrics_to_updates.values()),
<ide> max_number_of_evaluations=num_eval_iters,
<ide> eval_interval_secs=FLAGS.eval_interval_secs)
<ide>
<ide><path>research/deeplab/train.py
<ide> See model.py for more details and usage.
<ide> """
<ide>
<add>import six
<ide> import tensorflow as tf
<ide> from deeplab import common
<ide> from deeplab import model
<ide> def _build_deeplab(inputs_queue, outputs_to_num_classes, ignore_label):
<ide> is_training=True,
<ide> fine_tune_batch_norm=FLAGS.fine_tune_batch_norm)
<ide>
<del> for output, num_classes in outputs_to_num_classes.iteritems():
<add> for output, num_classes in six.iteritems(outputs_to_num_classes):
<ide> train_utils.add_softmax_cross_entropy_loss_for_each_scale(
<ide> outputs_to_scales_to_logits[output],
<ide> samples[common.LABEL],
<ide> def main(unused_argv):
<ide> assert FLAGS.train_batch_size % config.num_clones == 0, (
<ide> 'Training batch size not divisble by number of clones (GPUs).')
<ide>
<del> clone_batch_size = FLAGS.train_batch_size / config.num_clones
<add> clone_batch_size = int(FLAGS.train_batch_size / config.num_clones)
<ide>
<ide> # Get dataset-dependent information.
<ide> dataset = segmentation_dataset.get_dataset(
<ide><path>research/deeplab/utils/train_utils.py
<ide> # ==============================================================================
<ide> """Utility functions for training."""
<ide>
<add>import six
<add>
<ide> import tensorflow as tf
<ide>
<ide> slim = tf.contrib.slim
<ide> def add_softmax_cross_entropy_loss_for_each_scale(scales_to_logits,
<ide> if labels is None:
<ide> raise ValueError('No label for softmax cross entropy loss.')
<ide>
<del> for scale, logits in scales_to_logits.iteritems():
<add> for scale, logits in six.iteritems(scales_to_logits):
<ide> loss_scope = None
<ide> if scope:
<ide> loss_scope = '%s_%s' % (scope, scale) | 6 |
Python | Python | remove duplicate test in `tests/test_utils.py` | 60bcc932022c623aaad427e38464727484774aa2 | <ide><path>tests/test_utils.py
<ide> class UrlsRemoveQueryParamTests(TestCase):
<ide> """
<ide> Tests the remove_query_param functionality.
<ide> """
<del> def test_valid_unicode_preserved(self):
<del> q = '/?q=%E6%9F%A5%E8%AF%A2'
<del> new_key = 'page'
<del> new_value = 2
<del> value = '%E6%9F%A5%E8%AF%A2'
<del>
<del> assert new_key in replace_query_param(q, new_key, new_value)
<del> assert value in replace_query_param(q, new_key, new_value)
<del>
<ide> def test_valid_unicode_removed(self):
<ide> q = '/?page=2345&q=%E6%9F%A5%E8%AF%A2'
<ide> key = 'page' | 1 |
Go | Go | fix use of cap in multireadseeker | 158bb9bbd588aa03a3567f40b367025ccbd81fb3 | <ide><path>pkg/ioutils/multireader.go
<ide> func (r *multiReadSeeker) Read(b []byte) (int, error) {
<ide> r.pos = &pos{0, 0}
<ide> }
<ide>
<del> bCap := int64(cap(b))
<add> bCap := int64(len(b))
<ide> buf := bytes.NewBuffer(nil)
<ide> var rdr io.ReadSeeker
<ide>
<ide><path>pkg/ioutils/multireader_test.go
<ide> package ioutils
<ide>
<ide> import (
<ide> "bytes"
<add> "encoding/binary"
<ide> "fmt"
<ide> "io"
<ide> "io/ioutil"
<ide> func TestMultiReadSeekerCurAfterSet(t *testing.T) {
<ide> t.Fatalf("reader size does not match, got %d, expected %d", size, mid+18)
<ide> }
<ide> }
<add>
<add>func TestMultiReadSeekerSmallReads(t *testing.T) {
<add> readers := []io.ReadSeeker{}
<add> for i := 0; i < 10; i++ {
<add> integer := make([]byte, 4, 4)
<add> binary.BigEndian.PutUint32(integer, uint32(i))
<add> readers = append(readers, bytes.NewReader(integer))
<add> }
<add>
<add> reader := MultiReadSeeker(readers...)
<add> for i := 0; i < 10; i++ {
<add> var integer uint32
<add> if err := binary.Read(reader, binary.BigEndian, &integer); err != nil {
<add> t.Fatalf("Read from NewMultiReadSeeker failed: %v", err)
<add> }
<add> if uint32(i) != integer {
<add> t.Fatalf("Read wrong value from NewMultiReadSeeker: %d != %d", i, integer)
<add> }
<add> }
<add>} | 2 |
Ruby | Ruby | remove superfluous cgi require | c585e263ab40101eb0fd71a1d24d0d704f4ce026 | <ide><path>activeresource/lib/active_resource/base.rb
<ide> require 'active_resource/connection'
<del>require 'cgi'
<ide> require 'set'
<ide>
<ide> module ActiveResource | 1 |
Javascript | Javascript | remove unnecessary $scope.apply wrapping | e970df8554877f0d7aa87a8ee5cdd647f6f4b771 | <ide><path>src/ng/q.js
<ide> * var deferred = $q.defer();
<ide> *
<ide> * setTimeout(function() {
<del> * // since this fn executes async in a future turn of the event loop, we need to wrap
<del> * // our code into an $apply call so that the model changes are properly observed.
<del> * scope.$apply(function() {
<del> * deferred.notify('About to greet ' + name + '.');
<del> *
<del> * if (okToGreet(name)) {
<del> * deferred.resolve('Hello, ' + name + '!');
<del> * } else {
<del> * deferred.reject('Greeting ' + name + ' is not allowed.');
<del> * }
<del> * });
<add> * deferred.notify('About to greet ' + name + '.');
<add> *
<add> * if (okToGreet(name)) {
<add> * deferred.resolve('Hello, ' + name + '!');
<add> * } else {
<add> * deferred.reject('Greeting ' + name + ' is not allowed.');
<add> * }
<ide> * }, 1000);
<ide> *
<ide> * return deferred.promise; | 1 |
Ruby | Ruby | pull tap list into a constant | e0fba99699e168d863dd7bcb57190766d612c95b | <ide><path>Library/Homebrew/cmd/search.rb
<ide> def search
<ide> if query
<ide> found = search_results.length
<ide>
<del> threads = []
<ide> results = []
<del> threads << Thread.new { search_tap "josegonzalez", "php", rx }
<del> threads << Thread.new { search_tap "samueljohn", "python", rx }
<del> threads << Thread.new { search_tap "Homebrew", "apache", rx }
<del> threads << Thread.new { search_tap "Homebrew", "versions", rx }
<del> threads << Thread.new { search_tap "Homebrew", "dupes", rx }
<del> threads << Thread.new { search_tap "Homebrew", "games", rx }
<del> threads << Thread.new { search_tap "Homebrew", "science", rx }
<del> threads << Thread.new { search_tap "Homebrew", "completions", rx }
<del> threads << Thread.new { search_tap "Homebrew", "x11", rx }
<ide>
<del> threads.each do |t|
<add> SEARCHABLE_TAPS.map do |user, repo|
<add> Thread.new { search_tap(user, repo, rx) }
<add> end.each do |t|
<ide> results.concat(t.value)
<ide> end
<ide>
<ide> def search
<ide> end
<ide> end
<ide>
<add> SEARCHABLE_TAPS = [
<add> %w{josegonzalez php},
<add> %w{samueljohn python},
<add> %w{Homebrew apache},
<add> %w{Homebrew versions},
<add> %w{Homebrew dupes},
<add> %w{Homebrew games},
<add> %w{Homebrew science},
<add> %w{Homebrew completions},
<add> %w{Homebrew x11},
<add> ]
<add>
<ide> def query_regexp(query)
<ide> case query
<ide> when nil then "" | 1 |
Text | Text | add description for "--cpu-shares=0" | b7249569e27e1962c69eef2b8f547fb6fb7ad367 | <ide><path>docs/reference/run.md
<ide> can be modified by changing the container's CPU share weighting relative
<ide> to the weighting of all other running containers.
<ide>
<ide> To modify the proportion from the default of 1024, use the `-c` or `--cpu-shares`
<del>flag to set the weighting to 2 or higher.
<add>flag to set the weighting to 2 or higher. If 0 is set, the system will ignore the
<add>value and use the default of 1024.
<ide>
<ide> The proportion will only apply when CPU-intensive processes are running.
<ide> When tasks in one container are idle, other containers can use the | 1 |
Ruby | Ruby | add cop for shell metacharacters in `exec` | 6e2f194e0933c82246eb84aa0fd7283832bc435e | <ide><path>Library/Homebrew/rubocops/shared/helper_functions.rb
<ide> def source_buffer(node)
<ide> end
<ide>
<ide> # Returns the string representation if node is of type str(plain) or dstr(interpolated) or const.
<del> def string_content(node)
<add> def string_content(node, strip_dynamic: false)
<ide> case node.type
<ide> when :str
<ide> node.str_content
<ide> when :dstr
<ide> content = ""
<ide> node.each_child_node(:str, :begin) do |child|
<ide> content += if child.begin_type?
<del> child.source
<add> strip_dynamic ? "" : child.source
<ide> else
<ide> child.str_content
<ide> end
<ide><path>Library/Homebrew/rubocops/shell_commands.rb
<ide> module RuboCop
<ide> module Cop
<ide> module Style
<add> # https://github.com/ruby/ruby/blob/v2_6_3/process.c#L2430-L2460
<add> SHELL_BUILTINS = %w[
<add> !
<add> .
<add> :
<add> break
<add> case
<add> continue
<add> do
<add> done
<add> elif
<add> else
<add> esac
<add> eval
<add> exec
<add> exit
<add> export
<add> fi
<add> for
<add> if
<add> in
<add> readonly
<add> return
<add> set
<add> shift
<add> then
<add> times
<add> trap
<add> unset
<add> until
<add> while
<add> ].freeze
<add>
<add> # https://github.com/ruby/ruby/blob/v2_6_3/process.c#L2495
<add> SHELL_METACHARACTERS = %W[* ? { } [ ] < > ( ) ~ & | \\ $ ; ' ` " \n #].freeze
<add>
<ide> # This cop makes sure that shell command arguments are separated.
<ide> #
<ide> # @api private
<ide> class ShellCommands < Base
<ide> ].freeze
<ide> RESTRICT_ON_SEND = TARGET_METHODS.map(&:second).uniq.freeze
<ide>
<del> SHELL_METACHARACTERS = %w[> < < | ; : & * $ ? : ~ + @ ! ` ( ) [ ]].freeze
<del>
<ide> def on_send(node)
<ide> TARGET_METHODS.each do |target_class, target_method|
<ide> next unless node.method_name == target_method
<ide> def on_send(node)
<ide> next if first_arg.nil? || arg_count >= 2
<ide>
<ide> first_arg_str = string_content(first_arg)
<del>
<del> # Only separate when no shell metacharacters are present
<del> next if SHELL_METACHARACTERS.any? { |meta| first_arg_str.include?(meta) }
<add> stripped_first_arg_str = string_content(first_arg, strip_dynamic: true)
<ide>
<ide> split_args = first_arg_str.shellsplit
<ide> next if split_args.count <= 1
<ide>
<add> # Only separate when no shell metacharacters are present
<add> command = split_args.first
<add> next if SHELL_BUILTINS.any?(command)
<add> next if command&.include?("=")
<add> next if SHELL_METACHARACTERS.any? { |meta| stripped_first_arg_str.include?(meta) }
<add>
<ide> good_args = split_args.map { |arg| "\"#{arg}\"" }.join(", ")
<ide> method_string = if target_class
<ide> "#{target_class}.#{target_method}"
<ide> def on_send(node)
<ide> end
<ide> end
<ide> end
<add>
<add> # This cop disallows shell metacharacters in `exec` calls.
<add> #
<add> # @api private
<add> class ExecShellMetacharacters < Base
<add> include HelperFunctions
<add>
<add> MSG = "Don't use shell metacharacters in `exec`. "\
<add> "Implement the logic in Ruby instead, using methods like `$stdout.reopen`."
<add>
<add> RESTRICT_ON_SEND = [:exec].freeze
<add>
<add> def on_send(node)
<add> return if node.receiver.present? && node.receiver != s(:const, nil, :Kernel)
<add> return if node.arguments.count != 1
<add>
<add> stripped_arg_str = string_content(node.arguments.first, strip_dynamic: true)
<add> command = string_content(node.arguments.first).shellsplit.first
<add>
<add> return if SHELL_BUILTINS.none?(command) &&
<add> !command&.include?("=") &&
<add> SHELL_METACHARACTERS.none? { |meta| stripped_arg_str.include?(meta) }
<add>
<add> add_offense(node.arguments.first, message: MSG)
<add> end
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>Library/Homebrew/test/rubocops/shell_commands_spec.rb
<ide>
<ide> require "rubocops/shell_commands"
<ide>
<del>describe RuboCop::Cop::Style::ShellCommands do
<del> subject(:cop) { described_class.new }
<del>
<del> context "when auditing shell commands" do
<del> it "reports and corrects an offense when `system` arguments should be separated" do
<del> expect_offense(<<~RUBY)
<del> class Foo < Formula
<del> def install
<del> system "foo bar"
<del> ^^^^^^^^^ Separate `system` commands into `\"foo\", \"bar\"`
<del> end
<del> end
<del> RUBY
<del>
<del> expect_correction(<<~RUBY)
<del> class Foo < Formula
<del> def install
<del> system "foo", "bar"
<del> end
<del> end
<del> RUBY
<del> end
<del>
<del> it "reports and corrects an offense when `system` arguments with string interpolation should be separated" do
<del> expect_offense(<<~RUBY)
<del> class Foo < Formula
<del> def install
<del> system "\#{bin}/foo bar"
<del> ^^^^^^^^^^^^^^^^ Separate `system` commands into `\"\#{bin}/foo\", \"bar\"`
<del> end
<del> end
<del> RUBY
<del>
<del> expect_correction(<<~RUBY)
<del> class Foo < Formula
<del> def install
<del> system "\#{bin}/foo", "bar"
<del> end
<del> end
<del> RUBY
<del> end
<del>
<del> it "reports no offenses when `system` with metacharacter arguments are called" do
<del> expect_no_offenses(<<~RUBY)
<del> class Foo < Formula
<del> def install
<del> system "foo bar > baz"
<del> end
<del> end
<del> RUBY
<del> end
<del>
<del> it "reports no offenses when trailing arguments to `system` are unseparated" do
<del> expect_no_offenses(<<~RUBY)
<del> class Foo < Formula
<del> def install
<del> system "foo", "bar baz"
<del> end
<del> end
<del> RUBY
<del> end
<del>
<del> it "reports no offenses when `Utils.popen` arguments are unseparated" do
<del> expect_no_offenses(<<~RUBY)
<del> class Foo < Formula
<del> def install
<del> Utils.popen("foo bar")
<del> end
<del> end
<del> RUBY
<del> end
<del>
<del> it "reports and corrects an offense when `Utils.popen_read` arguments are unseparated" do
<del> expect_offense(<<~RUBY)
<del> class Foo < Formula
<del> def install
<del> Utils.popen_read("foo bar")
<del> ^^^^^^^^^ Separate `Utils.popen_read` commands into `\"foo\", \"bar\"`
<del> end
<del> end
<del> RUBY
<del>
<del> expect_correction(<<~RUBY)
<del> class Foo < Formula
<del> def install
<del> Utils.popen_read("foo", "bar")
<del> end
<del> end
<del> RUBY
<del> end
<del>
<del> it "reports and corrects an offense when `Utils.safe_popen_read` arguments are unseparated" do
<del> expect_offense(<<~RUBY)
<del> class Foo < Formula
<del> def install
<del> Utils.safe_popen_read("foo bar")
<del> ^^^^^^^^^ Separate `Utils.safe_popen_read` commands into `\"foo\", \"bar\"`
<del> end
<del> end
<del> RUBY
<del>
<del> expect_correction(<<~RUBY)
<del> class Foo < Formula
<del> def install
<del> Utils.safe_popen_read("foo", "bar")
<del> end
<del> end
<del> RUBY
<del> end
<del>
<del> it "reports and corrects an offense when `Utils.popen_write` arguments are unseparated" do
<del> expect_offense(<<~RUBY)
<del> class Foo < Formula
<del> def install
<del> Utils.popen_write("foo bar")
<del> ^^^^^^^^^ Separate `Utils.popen_write` commands into `\"foo\", \"bar\"`
<del> end
<del> end
<del> RUBY
<del>
<del> expect_correction(<<~RUBY)
<del> class Foo < Formula
<del> def install
<del> Utils.popen_write("foo", "bar")
<del> end
<del> end
<del> RUBY
<del> end
<del>
<del> it "reports and corrects an offense when `Utils.safe_popen_write` arguments are unseparated" do
<del> expect_offense(<<~RUBY)
<del> class Foo < Formula
<del> def install
<del> Utils.safe_popen_write("foo bar")
<del> ^^^^^^^^^ Separate `Utils.safe_popen_write` commands into `\"foo\", \"bar\"`
<del> end
<del> end
<del> RUBY
<del>
<del> expect_correction(<<~RUBY)
<del> class Foo < Formula
<del> def install
<del> Utils.safe_popen_write("foo", "bar")
<del> end
<del> end
<del> RUBY
<del> end
<del>
<del> it "reports and corrects an offense when `Utils.popen_read` arguments with interpolation are unseparated" do
<del> expect_offense(<<~RUBY)
<del> class Foo < Formula
<del> def install
<del> Utils.popen_read("\#{bin}/foo bar")
<del> ^^^^^^^^^^^^^^^^ Separate `Utils.popen_read` commands into `\"\#{bin}/foo\", \"bar\"`
<del> end
<del> end
<del> RUBY
<del>
<del> expect_correction(<<~RUBY)
<del> class Foo < Formula
<del> def install
<del> Utils.popen_read("\#{bin}/foo", "bar")
<del> end
<del> end
<del> RUBY
<del> end
<del>
<del> it "reports no offenses when `Utils.popen_read` arguments with metacharacters are unseparated" do
<del> expect_no_offenses(<<~RUBY)
<del> class Foo < Formula
<del> def install
<del> Utils.popen_read("foo bar > baz")
<del> end
<del> end
<del> RUBY
<del> end
<del>
<del> it "reports no offenses when trailing arguments to `Utils.popen_read` are unseparated" do
<del> expect_no_offenses(<<~RUBY)
<del> class Foo < Formula
<del> def install
<del> Utils.popen_read("foo", "bar baz")
<del> end
<del> end
<del> RUBY
<del> end
<del>
<del> it "reports and corrects an offense when `Utils.popen_read` arguments are unseparated after a shell variable" do
<del> expect_offense(<<~RUBY)
<del> class Foo < Formula
<del> def install
<del> Utils.popen_read({ "SHELL" => "bash"}, "foo bar")
<del> ^^^^^^^^^ Separate `Utils.popen_read` commands into `\"foo\", \"bar\"`
<del> end
<del> end
<del> RUBY
<del>
<del> expect_correction(<<~RUBY)
<del> class Foo < Formula
<del> def install
<del> Utils.popen_read({ "SHELL" => "bash"}, "foo", "bar")
<del> end
<del> end
<del> RUBY
<add>module RuboCop
<add> module Cop
<add> module Style
<add> describe ShellCommands do
<add> subject(:cop) { described_class.new }
<add>
<add> context "when auditing shell commands" do
<add> it "reports and corrects an offense when `system` arguments should be separated" do
<add> expect_offense(<<~RUBY)
<add> class Foo < Formula
<add> def install
<add> system "foo bar"
<add> ^^^^^^^^^ Separate `system` commands into `\"foo\", \"bar\"`
<add> end
<add> end
<add> RUBY
<add>
<add> expect_correction(<<~RUBY)
<add> class Foo < Formula
<add> def install
<add> system "foo", "bar"
<add> end
<add> end
<add> RUBY
<add> end
<add>
<add> it "reports and corrects an offense when `system` arguments involving interpolation should be separated" do
<add> expect_offense(<<~RUBY)
<add> class Foo < Formula
<add> def install
<add> system "\#{bin}/foo bar"
<add> ^^^^^^^^^^^^^^^^ Separate `system` commands into `\"\#{bin}/foo\", \"bar\"`
<add> end
<add> end
<add> RUBY
<add>
<add> expect_correction(<<~RUBY)
<add> class Foo < Formula
<add> def install
<add> system "\#{bin}/foo", "bar"
<add> end
<add> end
<add> RUBY
<add> end
<add>
<add> it "reports no offenses when `system` with metacharacter arguments are called" do
<add> expect_no_offenses(<<~RUBY)
<add> class Foo < Formula
<add> def install
<add> system "foo bar > baz"
<add> end
<add> end
<add> RUBY
<add> end
<add>
<add> it "reports no offenses when trailing arguments to `system` are unseparated" do
<add> expect_no_offenses(<<~RUBY)
<add> class Foo < Formula
<add> def install
<add> system "foo", "bar baz"
<add> end
<add> end
<add> RUBY
<add> end
<add>
<add> it "reports no offenses when `Utils.popen` arguments are unseparated" do
<add> expect_no_offenses(<<~RUBY)
<add> class Foo < Formula
<add> def install
<add> Utils.popen("foo bar")
<add> end
<add> end
<add> RUBY
<add> end
<add>
<add> it "reports and corrects an offense when `Utils.popen_read` arguments are unseparated" do
<add> expect_offense(<<~RUBY)
<add> class Foo < Formula
<add> def install
<add> Utils.popen_read("foo bar")
<add> ^^^^^^^^^ Separate `Utils.popen_read` commands into `\"foo\", \"bar\"`
<add> end
<add> end
<add> RUBY
<add>
<add> expect_correction(<<~RUBY)
<add> class Foo < Formula
<add> def install
<add> Utils.popen_read("foo", "bar")
<add> end
<add> end
<add> RUBY
<add> end
<add>
<add> it "reports and corrects an offense when `Utils.safe_popen_read` arguments are unseparated" do
<add> expect_offense(<<~RUBY)
<add> class Foo < Formula
<add> def install
<add> Utils.safe_popen_read("foo bar")
<add> ^^^^^^^^^ Separate `Utils.safe_popen_read` commands into `\"foo\", \"bar\"`
<add> end
<add> end
<add> RUBY
<add>
<add> expect_correction(<<~RUBY)
<add> class Foo < Formula
<add> def install
<add> Utils.safe_popen_read("foo", "bar")
<add> end
<add> end
<add> RUBY
<add> end
<add>
<add> it "reports and corrects an offense when `Utils.popen_write` arguments are unseparated" do
<add> expect_offense(<<~RUBY)
<add> class Foo < Formula
<add> def install
<add> Utils.popen_write("foo bar")
<add> ^^^^^^^^^ Separate `Utils.popen_write` commands into `\"foo\", \"bar\"`
<add> end
<add> end
<add> RUBY
<add>
<add> expect_correction(<<~RUBY)
<add> class Foo < Formula
<add> def install
<add> Utils.popen_write("foo", "bar")
<add> end
<add> end
<add> RUBY
<add> end
<add>
<add> it "reports and corrects an offense when `Utils.safe_popen_write` arguments are unseparated" do
<add> expect_offense(<<~RUBY)
<add> class Foo < Formula
<add> def install
<add> Utils.safe_popen_write("foo bar")
<add> ^^^^^^^^^ Separate `Utils.safe_popen_write` commands into `\"foo\", \"bar\"`
<add> end
<add> end
<add> RUBY
<add>
<add> expect_correction(<<~RUBY)
<add> class Foo < Formula
<add> def install
<add> Utils.safe_popen_write("foo", "bar")
<add> end
<add> end
<add> RUBY
<add> end
<add>
<add> it "reports and corrects an offense when `Utils.popen_read` arguments with interpolation are unseparated" do
<add> expect_offense(<<~RUBY)
<add> class Foo < Formula
<add> def install
<add> Utils.popen_read("\#{bin}/foo bar")
<add> ^^^^^^^^^^^^^^^^ Separate `Utils.popen_read` commands into `\"\#{bin}/foo\", \"bar\"`
<add> end
<add> end
<add> RUBY
<add>
<add> expect_correction(<<~RUBY)
<add> class Foo < Formula
<add> def install
<add> Utils.popen_read("\#{bin}/foo", "bar")
<add> end
<add> end
<add> RUBY
<add> end
<add>
<add> it "reports no offenses when `Utils.popen_read` arguments with metacharacters are unseparated" do
<add> expect_no_offenses(<<~RUBY)
<add> class Foo < Formula
<add> def install
<add> Utils.popen_read("foo bar > baz")
<add> end
<add> end
<add> RUBY
<add> end
<add>
<add> it "reports no offenses when trailing arguments to `Utils.popen_read` are unseparated" do
<add> expect_no_offenses(<<~RUBY)
<add> class Foo < Formula
<add> def install
<add> Utils.popen_read("foo", "bar baz")
<add> end
<add> end
<add> RUBY
<add> end
<add>
<add> it "reports and corrects an offense when `Utils.popen_read` arguments are unseparated after a shell env" do
<add> expect_offense(<<~RUBY)
<add> class Foo < Formula
<add> def install
<add> Utils.popen_read({ "SHELL" => "bash"}, "foo bar")
<add> ^^^^^^^^^ Separate `Utils.popen_read` commands into `\"foo\", \"bar\"`
<add> end
<add> end
<add> RUBY
<add>
<add> expect_correction(<<~RUBY)
<add> class Foo < Formula
<add> def install
<add> Utils.popen_read({ "SHELL" => "bash"}, "foo", "bar")
<add> end
<add> end
<add> RUBY
<add> end
<add> end
<add> end
<add>
<add> describe ExecShellMetacharacters do
<add> subject(:cop) { described_class.new }
<add>
<add> context "when auditing exec calls" do
<add> it "reports aan offense when output piping is used" do
<add> expect_offense(<<~RUBY)
<add> fork do
<add> exec "foo bar > output"
<add> ^^^^^^^^^^^^^^^^^^ Don\'t use shell metacharacters in `exec`. Implement the logic in Ruby instead, using methods like `$stdout.reopen`.
<add> end
<add> RUBY
<add> end
<add>
<add> it "reports no offenses when no metacharacters are used" do
<add> expect_no_offenses(<<~RUBY)
<add> fork do
<add> exec "foo bar"
<add> end
<add> RUBY
<add> end
<add> end
<add> end
<ide> end
<ide> end
<ide> end | 3 |
PHP | PHP | add dutch language | ce3721a7a131bd3a1aac04ac046a3427e9a233e2 | <ide><path>application/language/nl/pagination.php
<add><?php
<add>
<add>return array(
<add>
<add> 'previous' => '« Vorige',
<add> 'next' => 'Volgende »',
<add>
<add>);
<ide>\ No newline at end of file
<ide><path>application/language/nl/validation.php
<add><?php
<add>
<add>return array(
<add>
<add> /*
<add> |--------------------------------------------------------------------------
<add> | Dutch validation language file
<add> |--------------------------------------------------------------------------
<add> |
<add> */
<add>
<add> "accepted" => "Het :attribute moet geaccepteerd zijn.",
<add> "active_url" => "Het :attribute is geen geldig URL.",
<add> "after" => "Het :attribute moet een datum na :date zijn.",
<add> "alpha" => "Het :attribute mag alleen letters bevatten.",
<add> "alpha_dash" => "Het :attribute mag alleen letters, nummers, onderstreep(_) en strepen(-) bevatten.",
<add> "alpha_num" => "Het :attribute mag alleen letters en nummers",
<add> "before" => "Het :attribute moet een datum voor :date zijn.",
<add> "between" => array(
<add> "numeric" => "Het :attribute moet tussen :min en :max zijn.",
<add> "file" => "Het :attribute moet tussen :min en :max kilobytes zijn.",
<add> "string" => "Het :attribute moet tussen :min en :max tekens zijn.",
<add> ),
<add> "confirmed" => "Het :attribute bevestiging komt niet overeen.",
<add> "different" => "Het :attribute en :other moeten verschillend zijn.",
<add> "email" => "Het :attribute formaat is ongeldig.",
<add> "exists" => "Het gekozen :attribute is al ingebruik.",
<add> "image" => "Het :attribute moet een afbeelding zijn.",
<add> "in" => "Het gekozen :attribute is ongeldig.",
<add> "integer" => "Het :attribute moet een getal zijn.",
<add> "ip" => "Het :attribute moet een geldig IP adres bevatten.",
<add> "match" => "Het :attribute formaat is ongeldig.",
<add> "max" => array(
<add> "numeric" => "Het :attribute moet minder dan :max zijn.",
<add> "file" => "Het :attribute moet minder dan :max kilobytes zijn.",
<add> "string" => "Het :attribute moet minder dan :max tekens zijn.",
<add> ),
<add> "mimes" => "Het :attribute moet een bestand zijn van het bestandstype :values.",
<add> "min" => array(
<add> "numeric" => "Het :attribute moet minimaal :min zijn.",
<add> "file" => "Het :attribute moet minimaal :min kilobytes zijn.",
<add> "string" => "Het :attribute moet minimaal :min characters zijn.",
<add> ),
<add> "not_in" => "Het :attribute formaat is ongeldig.",
<add> "numeric" => "Het :attribute moet een nummer zijn.",
<add> "required" => "Het :attribute veld is verplicht.",
<add> "same" => "Het :attribute en :other moeten overeenkomen.",
<add> "size" => array(
<add> "numeric" => "Het :attribute moet :size zijn.",
<add> "file" => "Het :attribute moet :size kilobyte zijn.",
<add> "string" => "Het :attribute moet :size characters zijn.",
<add> ),
<add> "unique" => "Het :attribute is al in gebruik.",
<add> "url" => "Het :attribute formaat is ongeldig.",
<add>
<add> /*
<add> |--------------------------------------------------------------------------
<add> | Custom Validation Language Lines
<add> |--------------------------------------------------------------------------
<add> |
<add> | Here you may specify custom validation messages for attributes using the
<add> | convention "attribute_rule" to name the lines. This helps keep your
<add> | custom validation clean and tidy.
<add> |
<add> | So, say you want to use a custom validation message when validating that
<add> | the "email" attribute is unique. Just add "email_unique" to this array
<add> | with your custom message. The Validator will handle the rest!
<add> |
<add> */
<add>
<add> 'custom' => array(),
<add>
<add> /*
<add> |--------------------------------------------------------------------------
<add> | Validation Attributes
<add> |--------------------------------------------------------------------------
<add> |
<add> | The following language lines are used to swap attribute place-holders
<add> | with something more reader friendly such as "E-Mail Address" instead
<add> | of "email". Your users will thank you.
<add> |
<add> | The Validator class will automatically search this array of lines it
<add> | is attempting to replace the :attribute place-holder in messages.
<add> | It's pretty slick. We think you'll like it.
<add> |
<add> */
<add>
<add> 'attributes' => array(),
<add>
<add>);
<ide>\ No newline at end of file | 2 |
Go | Go | improve perf by avoiding buffer growth | 277aa9c67415b9b76ab17daea583b51f8560a6a5 | <ide><path>pkg/stdcopy/stdcopy.go
<ide> type StdWriter struct {
<ide> }
<ide>
<ide> func (w *StdWriter) Write(buf []byte) (n int, err error) {
<add> var n1, n2 int
<ide> if w == nil || w.Writer == nil {
<ide> return 0, errors.New("Writer not instanciated")
<ide> }
<ide> binary.BigEndian.PutUint32(w.prefix[4:], uint32(len(buf)))
<del> buf = append(w.prefix[:], buf...)
<del>
<del> n, err = w.Writer.Write(buf)
<del> return n - StdWriterPrefixLen, err
<add> n1, err = w.Writer.Write(w.prefix[:])
<add> if err != nil {
<add> n = n1 - StdWriterPrefixLen
<add> } else {
<add> n2, err = w.Writer.Write(buf)
<add> n = n1 + n2 - StdWriterPrefixLen
<add> }
<add> if n < 0 {
<add> n = 0
<add> }
<add> return
<ide> }
<ide>
<ide> // NewStdWriter instanciates a new Writer. | 1 |
PHP | PHP | remove use of file from stringcomparetrait | d9eda250198b3b4799ad78e8e9c40f24d06f1d8a | <ide><path>src/TestSuite/StringCompareTrait.php
<ide> */
<ide> namespace Cake\TestSuite;
<ide>
<del>use Cake\Filesystem\File;
<del>
<ide> /**
<ide> * Compare a string to the contents of a file
<ide> *
<ide> public function assertSameAsFile(string $path, string $result): void
<ide> }
<ide>
<ide> if ($this->_updateComparisons) {
<del> $file = new File($path, true);
<del> $file->write($result);
<add> file_put_contents($result);
<ide> }
<ide>
<ide> $expected = file_get_contents($path); | 1 |
Ruby | Ruby | fix url generation for mounted engine | 177a4bd5b7f903030a100f9b5092b1fa62c7c748 | <ide><path>railties/lib/rails/application.rb
<ide> def load_console(sandbox=false)
<ide> alias :build_middleware_stack :app
<ide>
<ide> def call(env)
<add> if Rails.application == self
<add> env["ORIGINAL_SCRIPT_NAME"] = env["SCRIPT_NAME"]
<add> env["action_dispatch.parent_routes"] = routes
<add> end
<add>
<add> env["action_dispatch.routes"] = routes
<ide> app.call(env.reverse_merge!(env_defaults))
<ide> end
<ide>
<ide> def env_defaults
<del> @env_defaults ||= super.merge({
<add> @env_defaults ||= {
<ide> "action_dispatch.parameter_filter" => config.filter_parameters,
<ide> "action_dispatch.secret_token" => config.secret_token
<del> })
<add> }
<ide> end
<ide>
<ide> def initializers
<ide><path>railties/lib/rails/engine.rb
<ide> def endpoint
<ide> end
<ide>
<ide> def call(env)
<del> app.call(env.reverse_merge!(env_defaults))
<del> end
<del>
<del> def env_defaults
<del> @env_defaults ||= {
<del> "action_dispatch.routes" => routes
<del> }
<add> env["action_dispatch.routes"] = routes
<add> app.call(env)
<ide> end
<ide>
<ide> def routes
<ide><path>railties/test/railties/mounted_engine_routes_test.rb
<add>require 'isolation/abstract_unit'
<add>
<add>module ApplicationTests
<add> class ApplicationRoutingTest < Test::Unit::TestCase
<add> require 'rack/test'
<add> include Rack::Test::Methods
<add> include ActiveSupport::Testing::Isolation
<add>
<add> def setup
<add> build_app
<add>
<add> add_to_config("config.action_dispatch.show_exceptions = false")
<add>
<add> @plugin = engine "blog"
<add>
<add> app_file 'config/routes.rb', <<-RUBY
<add> AppTemplate::Application.routes.draw do |map|
<add> match "/engine_route" => "application_generating#engine_route"
<add> match "/url_for_engine_route" => "application_generating#url_for_engine_route"
<add> scope "/:user", :user => "anonymous" do
<add> mount Blog::Engine => "/blog"
<add> end
<add> root :to => 'main#index'
<add> end
<add> RUBY
<add>
<add> @plugin.write "lib/blog.rb", <<-RUBY
<add> module Blog
<add> class Engine < ::Rails::Engine
<add> end
<add> end
<add> RUBY
<add>
<add> app_file "config/initializers/bla.rb", <<-RUBY
<add> Blog::Engine.eager_load!
<add> RUBY
<add>
<add> @plugin.write "config/routes.rb", <<-RUBY
<add> Blog::Engine.routes.draw do
<add> resources :posts do
<add> get :generate_application_route
<add> end
<add> end
<add> RUBY
<add>
<add> @plugin.write "app/controllers/posts_controller.rb", <<-RUBY
<add> class PostsController < ActionController::Base
<add> include Blog::Engine.routes.url_helpers
<add>
<add> def index
<add> render :text => post_path(1)
<add> end
<add>
<add> def generate_application_route
<add> path = url_for( :routes => Rails.application.routes,
<add> :controller => "main",
<add> :action => "index",
<add> :only_path => true)
<add> render :text => path
<add> end
<add> end
<add> RUBY
<add>
<add> app_file "app/controllers/application_generating_controller.rb", <<-RUBY
<add> class ApplicationGeneratingController < ActionController::Base
<add> include Blog::Engine.routes.url_helpers
<add>
<add> def engine_route
<add> render :text => posts_path
<add> end
<add>
<add> def url_for_engine_route
<add> render :text => url_for(:controller => "posts", :action => "index", :user => "john", :only_path => true)
<add> end
<add> end
<add> RUBY
<add>
<add> boot_rails
<add> end
<add>
<add> def app
<add> @app ||= begin
<add> require "#{app_path}/config/environment"
<add> Rails.application
<add> end
<add> end
<add>
<add> test "routes generation in engine and application" do
<add> # test generating engine's route from engine
<add> get "/john/blog/posts"
<add> assert_equal "/john/blog/posts/1", last_response.body
<add>
<add> # test generating engine's route from application
<add> get "/engine_route"
<add> assert_equal "/anonymous/blog/posts", last_response.body
<add> get "/url_for_engine_route"
<add> assert_equal "/john/blog/posts", last_response.body
<add>
<add> # test generating application's route from engine
<add> get "/someone/blog/generate_application_route"
<add> assert_equal "/", last_response.body
<add> get "/someone/blog/generate_application_route", {}, "SCRIPT_NAME" => "/foo"
<add> assert_equal "/foo/", last_response.body
<add> end
<add> end
<add>end
<add> | 3 |
Javascript | Javascript | fix typo in validatescema.js | 4bc647d700c9028cf20823b0975318a1992fe275 | <ide><path>lib/validateSchema.js
<ide> const DID_YOU_MEAN = {
<ide>
<ide> const REMOVED = {
<ide> concord:
<del> "BREAKING CHANGE: resolve.concord has been removed and is no longer avaiable.",
<add> "BREAKING CHANGE: resolve.concord has been removed and is no longer available.",
<ide> devtoolLineToLine:
<del> "BREAKING CHANGE: output.devtoolLineToLine has been removed and is no longer avaiable."
<add> "BREAKING CHANGE: output.devtoolLineToLine has been removed and is no longer available."
<ide> };
<ide> /* cSpell:enable */
<ide> | 1 |
Python | Python | fix longformer and led | 3f77c26d74e1282955fefa8dfff2451e44f6d4a9 | <ide><path>src/transformers/models/led/modeling_tf_led.py
<ide> def call(
<ide> def compute_hidden_states(self, hidden_states, padding_len):
<ide> return hidden_states[:, :-padding_len] if padding_len > 0 else hidden_states
<ide>
<del> @tf.function
<ide> def _pad_to_window_size(
<ide> self,
<ide> input_ids,
<ide> def _pad_to_window_size(
<ide> batch_size, seq_len = input_shape[:2]
<ide> padding_len = (attention_window - seq_len % attention_window) % attention_window
<ide>
<del> if padding_len > 0:
<add> if tf.math.greater(padding_len, 0):
<ide> logger.info(
<ide> "Input ids are automatically padded from {} to {} to be a multiple of `config.attention_window`: {}".format(
<ide> seq_len, seq_len + padding_len, attention_window
<ide> )
<ide> )
<ide>
<del> paddings = tf.convert_to_tensor([[0, 0], [0, padding_len]])
<add> paddings = tf.convert_to_tensor([[0, 0], [0, padding_len]])
<add>
<add> if input_ids is not None:
<add> input_ids = tf.pad(input_ids, paddings, constant_values=pad_token_id)
<ide>
<del> if input_ids is not None:
<del> input_ids = tf.pad(input_ids, paddings, constant_values=pad_token_id)
<add> if inputs_embeds is not None:
<ide>
<del> if inputs_embeds is not None:
<add> def pad_embeddings():
<ide> input_ids_padding = tf.fill((batch_size, padding_len), pad_token_id)
<ide> inputs_embeds_padding = self.embed_tokens(input_ids_padding)
<del> inputs_embeds = tf.concat([inputs_embeds, inputs_embeds_padding], axis=-2)
<add> return tf.concat([inputs_embeds, inputs_embeds_padding], axis=-2)
<add>
<add> inputs_embeds = tf.cond(tf.math.greater(padding_len, 0), pad_embeddings, lambda: inputs_embeds)
<ide>
<del> attention_mask = tf.pad(
<del> attention_mask, paddings, constant_values=False
<del> ) # no attention on the padding tokens
<add> attention_mask = tf.pad(attention_mask, paddings, constant_values=False) # no attention on the padding tokens
<ide>
<ide> return (
<ide> padding_len,
<ide><path>src/transformers/models/longformer/modeling_tf_longformer.py
<ide> def _pad_to_window_size(
<ide> batch_size, seq_len = input_shape[:2]
<ide> padding_len = (attention_window - seq_len % attention_window) % attention_window
<ide>
<del> if padding_len > 0:
<add> if tf.math.greater(padding_len, 0):
<ide> logger.info(
<ide> "Input ids are automatically padded from {} to {} to be a multiple of `config.attention_window`: {}".format(
<ide> seq_len, seq_len + padding_len, attention_window
<ide> def pad_embeddings():
<ide> inputs_embeds_padding = self.embeddings(input_ids_padding)
<ide> return tf.concat([inputs_embeds, inputs_embeds_padding], axis=-2)
<ide>
<del> inputs_embeds = tf.cond(padding_len > 0, pad_embeddings, lambda: inputs_embeds)
<add> inputs_embeds = tf.cond(tf.math.greater(padding_len, 0), pad_embeddings, lambda: inputs_embeds)
<ide>
<ide> attention_mask = tf.pad(attention_mask, paddings, constant_values=False) # no attention on the padding tokens
<ide> token_type_ids = tf.pad(token_type_ids, paddings, constant_values=0) # pad with token_type_id = 0
<ide><path>tests/test_modeling_tf_common.py
<ide> def test_inputs_embeds(self):
<ide>
<ide> model(inputs)
<ide>
<add> def test_graph_mode_with_inputs_embeds(self):
<add> config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
<add>
<add> for model_class in self.all_model_classes:
<add> model = model_class(config)
<add>
<add> inputs = copy.deepcopy(self._prepare_for_class(inputs_dict, model_class))
<add> if not self.is_encoder_decoder:
<add> input_ids = inputs["input_ids"]
<add> del inputs["input_ids"]
<add> else:
<add> encoder_input_ids = inputs["input_ids"]
<add> decoder_input_ids = inputs.get("decoder_input_ids", encoder_input_ids)
<add> del inputs["input_ids"]
<add> inputs.pop("decoder_input_ids", None)
<add>
<add> if not self.is_encoder_decoder:
<add> inputs["inputs_embeds"] = model.get_input_embeddings()(input_ids)
<add> else:
<add> inputs["inputs_embeds"] = model.get_input_embeddings()(encoder_input_ids)
<add> inputs["decoder_inputs_embeds"] = model.get_input_embeddings()(decoder_input_ids)
<add>
<add> @tf.function
<add> def run_in_graph_mode():
<add> return model(inputs)
<add>
<add> outputs = run_in_graph_mode()
<add> self.assertIsNotNone(outputs)
<add>
<ide> def test_numpy_arrays_inputs(self):
<ide> config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
<ide> | 3 |
PHP | PHP | use cache get default value | b6407420475599f997cd0102f588de3a22a1dc7b | <ide><path>src/Illuminate/Session/CacheBasedSessionHandler.php
<ide> public function close()
<ide> */
<ide> public function read($sessionId)
<ide> {
<del> return $this->cache->get($sessionId) ?: '';
<add> return $this->cache->get($sessionId, '');
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Session/CookieSessionHandler.php
<ide> public function close()
<ide> */
<ide> public function read($sessionId)
<ide> {
<del> return $this->request->cookies->get($sessionId) ?: '';
<add> return $this->request->cookies->get($sessionId, '');
<ide> }
<ide>
<ide> /** | 2 |
Go | Go | improve error message for unsupported capabilities | fc3f98848a9f5043ec2b1c9a76b93a04fe1868cf | <ide><path>oci/caps/utils.go
<ide> func init() {
<ide> allCaps = make([]string, min(int(last+1), len(rawCaps)))
<ide> capabilityList = make(Capabilities, min(int(last+1), len(rawCaps)))
<ide> for i, c := range rawCaps {
<add> capName := "CAP_" + strings.ToUpper(c.String())
<ide> if c > last {
<add> capabilityList[capName] = nil
<ide> continue
<ide> }
<del> capName := "CAP_" + strings.ToUpper(c.String())
<ide> allCaps[i] = capName
<ide> capabilityList[capName] = &CapabilityMapping{
<ide> Key: capName,
<ide> func NormalizeLegacyCapabilities(caps []string) ([]string, error) {
<ide> if !strings.HasPrefix(c, "CAP_") {
<ide> c = "CAP_" + c
<ide> }
<del> if _, ok := capabilityList[c]; !ok {
<add> if v, ok := capabilityList[c]; !ok {
<ide> return nil, errdefs.InvalidParameter(fmt.Errorf("unknown capability: %q", c))
<add> } else if v == nil {
<add> return nil, errdefs.InvalidParameter(fmt.Errorf("capability not supported by your kernel: %q", c))
<ide> }
<ide> normalized = append(normalized, c)
<ide> } | 1 |
Javascript | Javascript | remove unnecessary arguments | cfbdc178174b24e27001d358bec61962a6e21097 | <ide><path>examples/todomvc/test/actions/todos.spec.js
<ide> describe('todo actions', () => {
<ide> })
<ide>
<ide> it('clearCompleted should create CLEAR_COMPLETED action', () => {
<del> expect(actions.clearCompleted('Use Redux')).toEqual({
<add> expect(actions.clearCompleted()).toEqual({
<ide> type: types.CLEAR_COMPLETED
<ide> })
<ide> }) | 1 |
Text | Text | add changelog entry for constantize - closes | 329a5a43227be48b408b702438b355c087fd2866 | <ide><path>activesupport/CHANGELOG.md
<ide> ## Rails 4.0.0 (unreleased) ##
<ide>
<add>* `constantize` now looks in the ancestor chain. *Marc-Andre Lafortune & Andrew White*
<add>
<ide> * `Object#try` can't call private methods. *Vasiliy Ermolovich*
<ide>
<ide> * `AS::Callbacks#run_callbacks` remove `key` argument. *Francesco Rodriguez* | 1 |
Ruby | Ruby | hide install receipt key names | 7266ecd4e3799006d0482708a3331bfac4e1e0d1 | <ide><path>Library/Homebrew/cmd/reinstall.rb
<ide> def reinstall_formula f
<ide>
<ide> fi = FormulaInstaller.new(f)
<ide> fi.options = options
<del> fi.build_bottle = ARGV.build_bottle?
<del> fi.build_bottle ||= tab.built_as_bottle && !tab.poured_from_bottle
<add> fi.build_bottle = ARGV.build_bottle? || tab.build_bottle?
<ide> fi.build_from_source = ARGV.build_from_source?
<ide> fi.force_bottle = ARGV.force_bottle?
<ide> fi.verbose = ARGV.verbose?
<ide><path>Library/Homebrew/cmd/upgrade.rb
<ide> def upgrade_formula f
<ide>
<ide> fi = FormulaInstaller.new(f)
<ide> fi.options = tab.used_options
<del> fi.build_bottle = ARGV.build_bottle?
<del> fi.build_bottle ||= tab.built_as_bottle && !tab.poured_from_bottle
<add> fi.build_bottle = ARGV.build_bottle? || tab.build_bottle?
<ide> fi.build_from_source = ARGV.build_from_source?
<ide> fi.verbose = ARGV.verbose?
<ide> fi.verbose &&= :quieter if ARGV.quieter?
<ide><path>Library/Homebrew/tab.rb
<ide> def cxxstdlib
<ide> CxxStdlib.create(lib, cc.to_sym)
<ide> end
<ide>
<add> def build_bottle?
<add> built_as_bottle && !poured_from_bottle
<add> end
<add>
<ide> def to_json
<ide> Utils::JSON.dump({
<ide> :used_options => used_options.as_flags, | 3 |
Javascript | Javascript | remove duplicate check | 7635b7cc27305dbe11112771d6f7c52b3c401db8 | <ide><path>lib/_http_server.js
<ide> function connectionListenerInternal(server, socket) {
<ide> socket._paused = false;
<ide> }
<ide>
<del>
<ide> function updateOutgoingData(socket, state, delta) {
<ide> state.outgoingData += delta;
<del> if (socket._paused &&
<del> state.outgoingData < socket.writableHighWaterMark) {
<del> return socketOnDrain(socket, state);
<del> }
<add> socketOnDrain(socket, state);
<ide> }
<ide>
<ide> function socketOnDrain(socket, state) { | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.