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
Ruby
Ruby
remove unused attribute
0f57f75008242d1739326fec38791c01852c9aa7
<ide><path>activestorage/lib/active_storage/attached.rb <ide> module ActiveStorage <ide> # Abstract base class for the concrete ActiveStorage::Attached::One and ActiveStorage::Attached::Many <ide> # classes that both provide proxy access to the blob association for a record. <ide> class Attached <del> attr_reader :name, :record, :dependent <add> attr_reader :name, :record <ide> <del> def initialize(name, record, dependent:) <del> @name, @record, @dependent = name, record, dependent <add> def initialize(name, record) <add> @name, @record = name, record <ide> end <ide> <ide> private <ide><path>activestorage/lib/active_storage/attached/model.rb <ide> module Attached::Model <ide> def has_one_attached(name, dependent: :purge_later) <ide> generated_association_methods.class_eval <<-CODE, __FILE__, __LINE__ + 1 <ide> def #{name} <del> @active_storage_attached_#{name} ||= ActiveStorage::Attached::One.new("#{name}", self, dependent: #{dependent == :purge_later ? ":purge_later" : "false"}) <add> @active_storage_attached_#{name} ||= ActiveStorage::Attached::One.new("#{name}", self) <ide> end <ide> <ide> def #{name}=(attachable) <ide> def #{name}=(attachable) <ide> def has_many_attached(name, dependent: :purge_later) <ide> generated_association_methods.class_eval <<-CODE, __FILE__, __LINE__ + 1 <ide> def #{name} <del> @active_storage_attached_#{name} ||= ActiveStorage::Attached::Many.new("#{name}", self, dependent: #{dependent == :purge_later ? ":purge_later" : "false"}) <add> @active_storage_attached_#{name} ||= ActiveStorage::Attached::Many.new("#{name}", self) <ide> end <ide> <ide> def #{name}=(attachables)
2
Text
Text
add install of virtual kernel extras for aufs
e715ca506f41b22cde21187328fcb416cec5e6a2
<ide><path>docs/installation/linux/ubuntulinux.md <ide> packages from the new repository: <ide> - Ubuntu Trusty 14.04 (LTS) <ide> <ide> For Ubuntu Trusty, Wily, and Xenial, it's recommended to install the <del>`linux-image-extra` kernel package. The `linux-image-extra` package <add>`linux-image-extra-*` kernel packages. The `linux-image-extra-*` packages <ide> allows you use the `aufs` storage driver. <ide> <del>To install the `linux-image-extra` package for your kernel version: <add>To install the `linux-image-extra-*` packages: <ide> <ide> 1. Open a terminal on your Ubuntu host. <ide> <ide> 2. Update your package manager. <ide> <ide> $ sudo apt-get update <ide> <del>3. Install the recommended package. <add>3. Install the recommended packages. <ide> <del> $ sudo apt-get install linux-image-extra-$(uname -r) <add> $ sudo apt-get install linux-image-extra-$(uname -r) linux-image-extra-virtual <ide> <ide> 4. Go ahead and install Docker. <ide> <del>If you are installing on Ubuntu 14.04 or 12.04, `apparmor` is required. You can install it using: `apt-get install apparmor` <del> <ide> #### Ubuntu Precise 12.04 (LTS) <ide> <ide> For Ubuntu Precise, Docker requires the 3.13 kernel version. If your kernel
1
Go
Go
increase the maxjsondecoderetry in json log reader
a82f9ac81956c6b63772c9c720878d377dd9ee02
<ide><path>daemon/logger/jsonfilelog/jsonfilelog.go <ide> import ( <ide> const ( <ide> // Name is the name of the file that the jsonlogger logs to. <ide> Name = "json-file" <del> maxJSONDecodeRetry = 10 <add> maxJSONDecodeRetry = 20000 <ide> ) <ide> <ide> // JSONFileLogger is Logger implementation for default Docker logging.
1
Javascript
Javascript
replace entries with keys
a1f827a859654ee4781dd0ef215907cf859d58c8
<ide><path>lib/internal/policy/manifest.js <ide> class DependencyMapperInstance { <ide> this.#patternDependencies = undefined; <ide> } else { <ide> const patterns = []; <del> for (const { 0: key } of ObjectEntries(dependencies)) { <add> const keys = ObjectKeys(dependencies); <add> for (let i = 0; i < keys.length; i++) { <add> const key = keys[i]; <ide> if (StringPrototypeEndsWith(key, '*')) { <ide> const target = RegExpPrototypeExec(/^([^*]*)\*([^*]*)$/); <ide> if (!target) {
1
Python
Python
add default `conf` parameter to spark jdbc hook
7506c73f1721151e9c50ef8bdb70d2136a16190b
<ide><path>airflow/providers/apache/spark/example_dags/example_spark_dag.py <ide> jdbc_to_spark_job = SparkJDBCOperator( <ide> cmd_type='jdbc_to_spark', <ide> jdbc_table="foo", <del> spark_conf={}, <ide> spark_jars="${SPARK_HOME}/jars/postgresql-42.2.12.jar", <ide> jdbc_driver="org.postgresql.Driver", <ide> metastore_table="bar", <ide> spark_to_jdbc_job = SparkJDBCOperator( <ide> cmd_type='spark_to_jdbc', <ide> jdbc_table="foo", <del> spark_conf={}, <ide> spark_jars="${SPARK_HOME}/jars/postgresql-42.2.12.jar", <ide> jdbc_driver="org.postgresql.Driver", <ide> metastore_table="bar", <ide><path>airflow/providers/apache/spark/hooks/spark_jdbc.py <ide> def __init__(self, <ide> super().__init__(*args, **kwargs) <ide> self._name = spark_app_name <ide> self._conn_id = spark_conn_id <del> self._conf = spark_conf <add> self._conf = spark_conf or {} <ide> self._py_files = spark_py_files <ide> self._files = spark_files <ide> self._jars = spark_jars
2
PHP
PHP
add finder options to paginator->paginate method
4d5d3e1fb253100270ac2278b8300a6e33f1f773
<ide><path>src/Controller/Component/PaginatorComponent.php <ide> public function paginate($object, array $settings = []) { <ide> unset($options['finder'], $options['maxLimit']); <ide> <ide> if (empty($query)) { <del> $query = $object->find($type); <add> $query = $object->find($type, isset($options['finderOptions']) ? $options['finderOptions'] : []); <ide> } <ide> <ide> $query->applyOptions($options);
1
Javascript
Javascript
check noassert option in buf.write*()
084acc819db956cc7fd83c90c55188092d3d5b41
<ide><path>test/parallel/test-buffer-write-noassert.js <add>'use strict'; <add>require('../common'); <add>const assert = require('assert'); <add> <add>// testing buffer write functions <add> <add>function write(funx, args, result, res) { <add> { <add> const buf = Buffer.alloc(9); <add> assert.strictEqual(buf[funx](...args), result); <add> assert.deepStrictEqual(buf, res); <add> } <add> <add> { <add> const invalidArgs = Array.from(args); <add> invalidArgs[1] = -1; <add> assert.throws( <add> () => Buffer.alloc(9)[funx](...invalidArgs), <add> /^RangeError: (?:Index )?out of range(?: index)?$/ <add> ); <add> } <add> <add> { <add> const buf2 = Buffer.alloc(9); <add> assert.strictEqual(buf2[funx](...args, true), result); <add> assert.deepStrictEqual(buf2, res); <add> } <add> <add>} <add> <add>write('writeInt8', [1, 0], 1, Buffer.from([1, 0, 0, 0, 0, 0, 0, 0, 0])); <add>write('writeIntBE', [1, 1, 4], 5, Buffer.from([0, 0, 0, 0, 1, 0, 0, 0, 0])); <add>write('writeIntLE', [1, 1, 4], 5, Buffer.from([0, 1, 0, 0, 0, 0, 0, 0, 0])); <add>write('writeInt16LE', [1, 1], 3, Buffer.from([0, 1, 0, 0, 0, 0, 0, 0, 0])); <add>write('writeInt16BE', [1, 1], 3, Buffer.from([0, 0, 1, 0, 0, 0, 0, 0, 0])); <add>write('writeInt32LE', [1, 1], 5, Buffer.from([0, 1, 0, 0, 0, 0, 0, 0, 0])); <add>write('writeInt32BE', [1, 1], 5, Buffer.from([0, 0, 0, 0, 1, 0, 0, 0, 0])); <add>write('writeUInt8', [1, 0], 1, Buffer.from([1, 0, 0, 0, 0, 0, 0, 0, 0])); <add>write('writeUIntLE', [1, 1, 4], 5, Buffer.from([0, 1, 0, 0, 0, 0, 0, 0, 0])); <add>write('writeUIntBE', [1, 1, 4], 5, Buffer.from([0, 0, 0, 0, 1, 0, 0, 0, 0])); <add>write('writeUInt16LE', [1, 1], 3, Buffer.from([0, 1, 0, 0, 0, 0, 0, 0, 0])); <add>write('writeUInt16BE', [1, 1], 3, Buffer.from([0, 0, 1, 0, 0, 0, 0, 0, 0])); <add>write('writeUInt32LE', [1, 1], 5, Buffer.from([0, 1, 0, 0, 0, 0, 0, 0, 0])); <add>write('writeUInt32BE', [1, 1], 5, Buffer.from([0, 0, 0, 0, 1, 0, 0, 0, 0])); <add>write('writeDoubleBE', [1, 1], 9, Buffer.from([0, 63, 240, 0, 0, 0, 0, 0, 0])); <add>write('writeDoubleLE', [1, 1], 9, Buffer.from([0, 0, 0, 0, 0, 0, 0, 240, 63])); <add>write('writeFloatBE', [1, 1], 5, Buffer.from([0, 63, 128, 0, 0, 0, 0, 0, 0])); <add>write('writeFloatLE', [1, 1], 5, Buffer.from([0, 0, 0, 128, 63, 0, 0, 0, 0]));
1
Go
Go
add the link of "the documentation"
1a67e9572e95507791465e78e503ec21a4a32781
<ide><path>cmd/dockerd/daemon.go <ide> func (cli *DaemonCli) start(opts *daemonOptions) (err error) { <ide> <ide> // return human-friendly error before creating files <ide> if runtime.GOOS == "linux" && os.Geteuid() != 0 { <del> return fmt.Errorf("dockerd needs to be started with root. To see how to run dockerd in rootless mode with unprivileged user, see the documentation") <add> return fmt.Errorf("dockerd needs to be started with root privileges. To run dockerd in rootless mode as an unprivileged user, see https://docs.docker.com/go/rootless/") <ide> } <ide> <ide> if err := setDefaultUmask(); err != nil {
1
Python
Python
remove extra space
2068d20bc5f71415e6980ecabc02f8785b2aaca4
<ide><path>libcloud/common/openstack.py <ide> def _populate_hosts_and_request_paths(self): <ide> if self._ex_force_auth_url != None: <ide> aurl = self._ex_force_auth_url <ide> <del> if aurl == None : <add> if aurl == None: <ide> raise LibcloudError('OpenStack instance must have auth_url set') <ide> <ide> osa = OpenStackAuthConnection(self, aurl, self._auth_version, self.user_id, self.key)
1
Mixed
Javascript
add reactor support
9e135accbb045d52eb65de602c81b5090daae1c4
<ide><path>doc/api/wasi.md <ide> Attempt to begin execution of `instance` as a WASI command by invoking its <ide> <ide> If `start()` is called more than once, an exception is thrown. <ide> <add>### `wasi.initialize(instance)` <add><!-- YAML <add>added: <add> - REPLACEME <add>--> <add> <add>* `instance` {WebAssembly.Instance} <add> <add>Attempt to initialize `instance` as a WASI reactor by invoking its <add>`_initialize()` export, if it is present. If `instance` contains a `_start()` <add>export, then an exception is thrown. <add> <add>`initialize()` requires that `instance` exports a [`WebAssembly.Memory`][] named <add>`memory`. If `instance` does not have a `memory` export an exception is thrown. <add> <add>If `initialize()` is called more than once, an exception is thrown. <add> <ide> ### `wasi.wasiImport` <ide> <!-- YAML <ide> added: <ide><path>lib/wasi.js <ide> const { <ide> validateObject, <ide> } = require('internal/validators'); <ide> const { WASI: _WASI } = internalBinding('wasi'); <del>const kExitCode = Symbol('exitCode'); <del>const kSetMemory = Symbol('setMemory'); <del>const kStarted = Symbol('started'); <add>const kExitCode = Symbol('kExitCode'); <add>const kSetMemory = Symbol('kSetMemory'); <add>const kStarted = Symbol('kStarted'); <add>const kInstance = Symbol('kInstance'); <ide> <ide> emitExperimentalWarning('WASI'); <ide> <ide> <add>function setupInstance(self, instance) { <add> validateObject(instance, 'instance'); <add> validateObject(instance.exports, 'instance.exports'); <add> <add> // WASI::_SetMemory() in src/node_wasi.cc only expects that |memory| is <add> // an object. It will try to look up the .buffer property when needed <add> // and fail with UVWASI_EINVAL when the property is missing or is not <add> // an ArrayBuffer. Long story short, we don't need much validation here <add> // but we type-check anyway because it helps catch bugs in the user's <add> // code early. <add> validateObject(instance.exports.memory, 'instance.exports.memory'); <add> if (!isArrayBuffer(instance.exports.memory.buffer)) { <add> throw new ERR_INVALID_ARG_TYPE( <add> 'instance.exports.memory.buffer', <add> ['WebAssembly.Memory'], <add> instance.exports.memory.buffer); <add> } <add> <add> self[kInstance] = instance; <add> self[kSetMemory](instance.exports.memory); <add>} <add> <ide> class WASI { <ide> constructor(options = {}) { <ide> validateObject(options, 'options'); <ide> class WASI { <ide> this.wasiImport = wrap; <ide> this[kStarted] = false; <ide> this[kExitCode] = 0; <add> this[kInstance] = undefined; <ide> } <ide> <add> // Must not export _initialize, must export _start <ide> start(instance) { <del> validateObject(instance, 'instance'); <del> <del> const exports = instance.exports; <add> if (this[kStarted]) { <add> throw new ERR_WASI_ALREADY_STARTED(); <add> } <add> this[kStarted] = true; <ide> <del> validateObject(exports, 'instance.exports'); <add> setupInstance(this, instance); <ide> <del> const { _initialize, _start, memory } = exports; <add> const { _start, _initialize } = this[kInstance].exports; <ide> <ide> if (typeof _start !== 'function') { <ide> throw new ERR_INVALID_ARG_TYPE( <ide> 'instance.exports._start', 'function', _start); <ide> } <del> <ide> if (_initialize !== undefined) { <ide> throw new ERR_INVALID_ARG_TYPE( <ide> 'instance.exports._initialize', 'undefined', _initialize); <ide> } <ide> <del> // WASI::_SetMemory() in src/node_wasi.cc only expects that |memory| is <del> // an object. It will try to look up the .buffer property when needed <del> // and fail with UVWASI_EINVAL when the property is missing or is not <del> // an ArrayBuffer. Long story short, we don't need much validation here <del> // but we type-check anyway because it helps catch bugs in the user's <del> // code early. <del> validateObject(memory, 'instance.exports.memory'); <del> <del> if (!isArrayBuffer(memory.buffer)) { <del> throw new ERR_INVALID_ARG_TYPE( <del> 'instance.exports.memory.buffer', <del> ['WebAssembly.Memory'], <del> memory.buffer); <add> try { <add> _start(); <add> } catch (err) { <add> if (err !== kExitCode) { <add> throw err; <add> } <ide> } <ide> <add> return this[kExitCode]; <add> } <add> <add> // Must not export _start, may optionally export _initialize <add> initialize(instance) { <ide> if (this[kStarted]) { <ide> throw new ERR_WASI_ALREADY_STARTED(); <ide> } <del> <ide> this[kStarted] = true; <del> this[kSetMemory](memory); <ide> <del> try { <del> exports._start(); <del> } catch (err) { <del> if (err !== kExitCode) { <del> throw err; <del> } <add> setupInstance(this, instance); <add> <add> const { _start, _initialize } = this[kInstance].exports; <add> <add> if (typeof _initialize !== 'function' && _initialize !== undefined) { <add> throw new ERR_INVALID_ARG_TYPE( <add> 'instance.exports._initialize', 'function', _initialize); <add> } <add> if (_start !== undefined) { <add> throw new ERR_INVALID_ARG_TYPE( <add> 'instance.exports._start', 'undefined', _initialize); <ide> } <ide> <del> return this[kExitCode]; <add> if (_initialize !== undefined) { <add> _initialize(); <add> } <ide> } <ide> } <ide> <ide><path>test/wasi/test-wasi-initialize-validation.js <add>// Flags: --experimental-wasi-unstable-preview1 <add>'use strict'; <add> <add>const common = require('../common'); <add>const assert = require('assert'); <add>const vm = require('vm'); <add>const { WASI } = require('wasi'); <add> <add>const fixtures = require('../common/fixtures'); <add>const bufferSource = fixtures.readSync('simple.wasm'); <add> <add>(async () => { <add> { <add> // Verify that a WebAssembly.Instance is passed in. <add> const wasi = new WASI(); <add> <add> assert.throws( <add> () => { wasi.initialize(); }, <add> { <add> code: 'ERR_INVALID_ARG_TYPE', <add> message: /"instance" argument must be of type object/ <add> } <add> ); <add> } <add> <add> { <add> // Verify that the passed instance has an exports objects. <add> const wasi = new WASI({}); <add> const wasm = await WebAssembly.compile(bufferSource); <add> const instance = await WebAssembly.instantiate(wasm); <add> <add> Object.defineProperty(instance, 'exports', { get() { return null; } }); <add> assert.throws( <add> () => { wasi.initialize(instance); }, <add> { <add> code: 'ERR_INVALID_ARG_TYPE', <add> message: /"instance\.exports" property must be of type object/ <add> } <add> ); <add> } <add> <add> { <add> // Verify that a _initialize() export was passed. <add> const wasi = new WASI({}); <add> const wasm = await WebAssembly.compile(bufferSource); <add> const instance = await WebAssembly.instantiate(wasm); <add> <add> Object.defineProperty(instance, 'exports', { <add> get() { <add> return { _initialize: 5, memory: new Uint8Array() }; <add> }, <add> }); <add> assert.throws( <add> () => { wasi.initialize(instance); }, <add> { <add> code: 'ERR_INVALID_ARG_TYPE', <add> message: /"instance\.exports\._initialize" property must be of type function/ <add> } <add> ); <add> } <add> <add> { <add> // Verify that a _start export was not passed. <add> const wasi = new WASI({}); <add> const wasm = await WebAssembly.compile(bufferSource); <add> const instance = await WebAssembly.instantiate(wasm); <add> <add> Object.defineProperty(instance, 'exports', { <add> get() { <add> return { <add> _start() {}, <add> _initialize() {}, <add> memory: new Uint8Array(), <add> }; <add> } <add> }); <add> assert.throws( <add> () => { wasi.initialize(instance); }, <add> { <add> code: 'ERR_INVALID_ARG_TYPE', <add> message: /"instance\.exports\._start" property must be undefined/ <add> } <add> ); <add> } <add> <add> { <add> // Verify that a memory export was passed. <add> const wasi = new WASI({}); <add> const wasm = await WebAssembly.compile(bufferSource); <add> const instance = await WebAssembly.instantiate(wasm); <add> <add> Object.defineProperty(instance, 'exports', { <add> get() { return { _initialize() {} }; } <add> }); <add> assert.throws( <add> () => { wasi.initialize(instance); }, <add> { <add> code: 'ERR_INVALID_ARG_TYPE', <add> message: /"instance\.exports\.memory" property must be of type object/ <add> } <add> ); <add> } <add> <add> { <add> // Verify that a non-ArrayBuffer memory.buffer is rejected. <add> const wasi = new WASI({}); <add> const wasm = await WebAssembly.compile(bufferSource); <add> const instance = await WebAssembly.instantiate(wasm); <add> <add> Object.defineProperty(instance, 'exports', { <add> get() { <add> return { <add> _initialize() {}, <add> memory: {}, <add> }; <add> } <add> }); <add> // The error message is a little white lie because any object <add> // with a .buffer property of type ArrayBuffer is accepted, <add> // but 99% of the time a WebAssembly.Memory object is used. <add> assert.throws( <add> () => { wasi.initialize(instance); }, <add> { <add> code: 'ERR_INVALID_ARG_TYPE', <add> message: /"instance\.exports\.memory\.buffer" property must be an WebAssembly\.Memory/ <add> } <add> ); <add> } <add> <add> { <add> // Verify that an argument that duck-types as a WebAssembly.Instance <add> // is accepted. <add> const wasi = new WASI({}); <add> const wasm = await WebAssembly.compile(bufferSource); <add> const instance = await WebAssembly.instantiate(wasm); <add> <add> Object.defineProperty(instance, 'exports', { <add> get() { <add> return { <add> _initialize() {}, <add> memory: { buffer: new ArrayBuffer(0) }, <add> }; <add> } <add> }); <add> wasi.initialize(instance); <add> } <add> <add> { <add> // Verify that a WebAssembly.Instance from another VM context is accepted. <add> const wasi = new WASI({}); <add> const instance = await vm.runInNewContext(` <add> (async () => { <add> const wasm = await WebAssembly.compile(bufferSource); <add> const instance = await WebAssembly.instantiate(wasm); <add> <add> Object.defineProperty(instance, 'exports', { <add> get() { <add> return { <add> _initialize() {}, <add> memory: new WebAssembly.Memory({ initial: 1 }) <add> }; <add> } <add> }); <add> <add> return instance; <add> })() <add> `, { bufferSource }); <add> <add> wasi.initialize(instance); <add> } <add> <add> { <add> // Verify that initialize() can only be called once. <add> const wasi = new WASI({}); <add> const wasm = await WebAssembly.compile(bufferSource); <add> const instance = await WebAssembly.instantiate(wasm); <add> <add> Object.defineProperty(instance, 'exports', { <add> get() { <add> return { <add> _initialize() {}, <add> memory: new WebAssembly.Memory({ initial: 1 }) <add> }; <add> } <add> }); <add> wasi.initialize(instance); <add> assert.throws( <add> () => { wasi.initialize(instance); }, <add> { <add> code: 'ERR_WASI_ALREADY_STARTED', <add> message: /^WASI instance has already started$/ <add> } <add> ); <add> } <add>})().then(common.mustCall()); <ide><path>test/wasi/test-wasi-start-validation.js <ide> const bufferSource = fixtures.readSync('simple.wasm'); <ide> const wasm = await WebAssembly.compile(bufferSource); <ide> const instance = await WebAssembly.instantiate(wasm); <ide> <del> Object.defineProperty(instance, 'exports', { get() { return {}; } }); <add> Object.defineProperty(instance, 'exports', { <add> get() { <add> return { memory: new Uint8Array() }; <add> }, <add> }); <ide> assert.throws( <ide> () => { wasi.start(instance); }, <ide> { <ide> const bufferSource = fixtures.readSync('simple.wasm'); <ide> get() { <ide> return { <ide> _start() {}, <del> _initialize() {} <add> _initialize() {}, <add> memory: new Uint8Array(), <ide> }; <ide> } <ide> });
4
Python
Python
replace deprecated functions
705acc35d6661c6b9cb19dfdb247d75f13574843
<ide><path>im2txt/im2txt/ops/image_processing.py <ide> def image_summary(name, image): <ide> image_summary("final_image", image) <ide> <ide> # Rescale to [-1,1] instead of [0, 1] <del> image = tf.sub(image, 0.5) <del> image = tf.mul(image, 2.0) <add> image = tf.subtract(image, 0.5) <add> image = tf.multiply(image, 2.0) <ide> return image <ide><path>im2txt/im2txt/ops/inputs.py <ide> def batch_with_dynamic_pad(images_and_captions, <ide> enqueue_list = [] <ide> for image, caption in images_and_captions: <ide> caption_length = tf.shape(caption)[0] <del> input_length = tf.expand_dims(tf.sub(caption_length, 1), 0) <add> input_length = tf.expand_dims(tf.subtract(caption_length, 1), 0) <ide> <ide> input_seq = tf.slice(caption, [0], input_length) <ide> target_seq = tf.slice(caption, [1], input_length) <ide><path>im2txt/im2txt/show_and_tell_model.py <ide> def build_model(self): <ide> # This LSTM cell has biases and outputs tanh(new_c) * sigmoid(o), but the <ide> # modified LSTM in the "Show and Tell" paper has no biases and outputs <ide> # new_c * sigmoid(o). <del> lstm_cell = tf.nn.rnn_cell.BasicLSTMCell( <add> lstm_cell = tf.contrib.rnn.BasicLSTMCell( <ide> num_units=self.config.num_lstm_units, state_is_tuple=True) <ide> if self.mode == "train": <del> lstm_cell = tf.nn.rnn_cell.DropoutWrapper( <add> lstm_cell = tf.contrib.rnn.DropoutWrapper( <ide> lstm_cell, <ide> input_keep_prob=self.config.lstm_dropout_keep_prob, <ide> output_keep_prob=self.config.lstm_dropout_keep_prob) <ide> def build_model(self): <ide> if self.mode == "inference": <ide> # In inference mode, use concatenated states for convenient feeding and <ide> # fetching. <del> tf.concat(1, initial_state, name="initial_state") <add> tf.concat_v2(initial_state, 1, name="initial_state") <ide> <ide> # Placeholder for feeding a batch of concatenated states. <ide> state_feed = tf.placeholder(dtype=tf.float32, <ide> shape=[None, sum(lstm_cell.state_size)], <ide> name="state_feed") <del> state_tuple = tf.split(1, 2, state_feed) <add> state_tuple = tf.split(value=state_feed, num_or_size_splits=2, axis=1) <ide> <ide> # Run a single LSTM step. <ide> lstm_outputs, state_tuple = lstm_cell( <ide> inputs=tf.squeeze(self.seq_embeddings, squeeze_dims=[1]), <ide> state=state_tuple) <ide> <ide> # Concatentate the resulting state. <del> tf.concat(1, state_tuple, name="state") <add> tf.concat_v2(state_tuple, 1, name="state") <ide> else: <ide> # Run the batch of sequence embeddings through the LSTM. <ide> sequence_length = tf.reduce_sum(self.input_mask, 1) <ide> def build_model(self): <ide> weights = tf.to_float(tf.reshape(self.input_mask, [-1])) <ide> <ide> # Compute losses. <del> losses = tf.nn.sparse_softmax_cross_entropy_with_logits(logits, targets) <del> batch_loss = tf.div(tf.reduce_sum(tf.mul(losses, weights)), <add> losses = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=targets, <add> logits=logits) <add> batch_loss = tf.div(tf.reduce_sum(tf.multiply(losses, weights)), <ide> tf.reduce_sum(weights), <ide> name="batch_loss") <ide> tf.losses.add_loss(batch_loss)
3
PHP
PHP
return instance from more eloquent methods
99ba29aeeb210f33e24c7dbeedda6cce9ec916dd
<ide><path>src/Illuminate/Database/Eloquent/Model.php <ide> public function getObservableEvents() <ide> * Set the observable event names. <ide> * <ide> * @param array $observables <del> * @return void <add> * @return $this <ide> */ <ide> public function setObservableEvents(array $observables) <ide> { <ide> $this->observables = $observables; <add> <add> return $this; <ide> } <ide> <ide> /** <ide> protected function updateTimestamps() <ide> * Set the value of the "created at" attribute. <ide> * <ide> * @param mixed $value <del> * @return void <add> * @return $this <ide> */ <ide> public function setCreatedAt($value) <ide> { <ide> $this->{static::CREATED_AT} = $value; <add> <add> return $this; <ide> } <ide> <ide> /** <ide> * Set the value of the "updated at" attribute. <ide> * <ide> * @param mixed $value <del> * @return void <add> * @return $this <ide> */ <ide> public function setUpdatedAt($value) <ide> { <ide> $this->{static::UPDATED_AT} = $value; <add> <add> return $this; <ide> } <ide> <ide> /** <ide> public function getTable() <ide> * Set the table associated with the model. <ide> * <ide> * @param string $table <del> * @return void <add> * @return $this <ide> */ <ide> public function setTable($table) <ide> { <ide> $this->table = $table; <add> <add> return $this; <ide> } <ide> <ide> /** <ide> public function getKeyName() <ide> * Set the primary key for the model. <ide> * <ide> * @param string $key <del> * @return void <add> * @return $this <ide> */ <ide> public function setKeyName($key) <ide> { <ide> $this->primaryKey = $key; <add> <add> return $this; <ide> } <ide> <ide> /** <ide> public function getPerPage() <ide> * Set the number of models to return per page. <ide> * <ide> * @param int $perPage <del> * @return void <add> * @return $this <ide> */ <ide> public function setPerPage($perPage) <ide> { <ide> $this->perPage = $perPage; <add> <add> return $this; <ide> } <ide> <ide> /** <ide> public function getTouchedRelations() <ide> * Set the relationships that are touched on save. <ide> * <ide> * @param array $touches <del> * @return void <add> * @return $this <ide> */ <ide> public function setTouchedRelations(array $touches) <ide> { <ide> $this->touches = $touches; <add> <add> return $this; <ide> } <ide> <ide> /** <ide> public function getIncrementing() <ide> * Set whether IDs are incrementing. <ide> * <ide> * @param bool $value <del> * @return void <add> * @return $this <ide> */ <ide> public function setIncrementing($value) <ide> { <ide> $this->incrementing = $value; <add> <add> return $this; <ide> } <ide> <ide> /** <ide> protected function castAttribute($key, $value) <ide> * <ide> * @param string $key <ide> * @param mixed $value <del> * @return void <add> * @return $this <ide> */ <ide> public function setAttribute($key, $value) <ide> { <ide> public function setAttribute($key, $value) <ide> } <ide> <ide> $this->attributes[$key] = $value; <add> <add> return $this; <ide> } <ide> <ide> /** <ide> public function getAttributes() <ide> * <ide> * @param array $attributes <ide> * @param bool $sync <del> * @return void <add> * @return $this <ide> */ <ide> public function setRawAttributes(array $attributes, $sync = false) <ide> { <ide> public function setRawAttributes(array $attributes, $sync = false) <ide> if ($sync) { <ide> $this->syncOriginal(); <ide> } <add> <add> return $this; <ide> } <ide> <ide> /**
1
Javascript
Javascript
remove duplicate line
21ce27161d1961b48c660b7524b59d154f510e99
<ide><path>flow/react-native-host-hooks.js <ide> declare module 'UIManager' { <ide> declare function removeSubviewsFromContainerWithID() : void; <ide> declare function replaceExistingNonRootView() : void; <ide> declare function setChildren() : void; <del> declare function setChildren() : void; <ide> declare function updateView() : void; <ide> } <ide> declare module 'View' { }
1
Javascript
Javascript
fix listener leak in stream.pipe()
2a65d2962578db2cc841c6679a1762a17ac8dfb2
<ide><path>lib/stream.js <ide> Stream.prototype.pipe = function(dest, options) { <ide> source.on('end', onend); <ide> } <ide> <del> dest.on('close', function() { <del> source.removeListener('data', ondata); <del> dest.removeListener('drain', ondrain); <del> source.removeListener('end', onend); <del> }); <del> <del> <ide> /* <ide> * Questionable: <ide> */ <ide> Stream.prototype.pipe = function(dest, options) { <ide> source.emit('resume'); <ide> }; <ide> } <del> <del> dest.on('pause', function() { <add> <add> var onpause = function() { <ide> source.pause(); <del> }); <add> } <ide> <del> dest.on('resume', function() { <add> dest.on('pause', onpause); <add> <add> var onresume = function() { <ide> if (source.readable) source.resume(); <del> }); <add> }; <add> <add> dest.on('resume', onresume); <add> <add> var cleanup = function () { <add> source.removeListener('data', ondata); <add> dest.removeListener('drain', ondrain); <add> source.removeListener('end', onend); <add> <add> dest.removeListener('pause', onpause); <add> dest.removeListener('resume', onresume); <add> <add> source.removeListener('end', cleanup); <add> source.removeListener('close', cleanup); <add> <add> dest.removeListener('end', cleanup); <add> dest.removeListener('close', cleanup); <add> } <add> <add> source.on('end', cleanup); <add> source.on('close', cleanup); <add> <add> dest.on('end', cleanup); <add> dest.on('close', cleanup); <ide> <ide> dest.emit('pipe', source); <ide> }; <ide><path>test/simple/test-stream-pipe-cleanup.js <add>// Copyright Joyent, Inc. and other Node contributors. <add>// <add>// Permission is hereby granted, free of charge, to any person obtaining a <add>// copy of this software and associated documentation files (the <add>// "Software"), to deal in the Software without restriction, including <add>// without limitation the rights to use, copy, modify, merge, publish, <add>// distribute, sublicense, and/or sell copies of the Software, and to permit <add>// persons to whom the Software is furnished to do so, subject to the <add>// following conditions: <add>// <add>// The above copyright notice and this permission notice shall be included <add>// in all copies or substantial portions of the Software. <add>// <add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS <add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF <add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN <add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, <add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR <add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE <add>// USE OR OTHER DEALINGS IN THE SOFTWARE. <add> <add>// This test asserts that Stream.prototype.pipe does not leave listeners <add>// hanging on the source or dest. <add> <add>var stream = require('stream'); <add>var assert = require('assert'); <add>var util = require('util'); <add> <add>function Writable () { <add> this.writable = true; <add> stream.Stream.call(this); <add>} <add>util.inherits(Writable, stream.Stream); <add>Writable.prototype.end = function () {} <add> <add>function Readable () { <add> this.readable = true; <add> stream.Stream.call(this); <add>} <add>util.inherits(Readable, stream.Stream); <add> <add>var i = 0; <add>var limit = 100; <add> <add>var w = new Writable(); <add> <add>console.error = function (text) { <add> throw new Error(text); <add>} <add> <add>var r; <add> <add>for (i = 0; i < limit; i++) { <add> r = new Readable() <add> r.pipe(w) <add> r.emit('end') <add>} <add>assert.equal(0, r.listeners('end').length); <add> <add>for (i = 0; i < limit; i++) { <add> r = new Readable() <add> r.pipe(w) <add> r.emit('close') <add>} <add>assert.equal(0, r.listeners('close').length); <add> <add>r = new Readable(); <add> <add>for (i = 0; i < limit; i++) { <add> w = new Writable(); <add> r.pipe(w); <add> w.emit('end'); <add>} <add>assert.equal(0, w.listeners('end').length); <add> <add>for (i = 0; i < limit; i++) { <add> w = new Writable(); <add> r.pipe(w); <add> w.emit('close'); <add>} <add>assert.equal(0, w.listeners('close').length); <add>
2
PHP
PHP
apply fixes from styleci
7bd4e6dc547526d072374eb4846e31369987d66f
<ide><path>src/Illuminate/Testing/TestResponse.php <ide> use Illuminate\Testing\Assert as PHPUnit; <ide> use Illuminate\Testing\Constraints\SeeInOrder; <ide> use Illuminate\Testing\Fluent\AssertableJson; <del>use Illuminate\Validation\ValidationException; <ide> use LogicException; <ide> use Symfony\Component\HttpFoundation\StreamedResponse; <ide>
1
Text
Text
remove reference to unmaintained plugin/gem
a2df57c991b844a9b963bc452fa517cc53560686
<ide><path>guides/source/security.md <ide> The most effective countermeasure is to _issue a new session identifier_ and dec <ide> reset_session <ide> ``` <ide> <del>If you use the popular RestfulAuthentication plugin for user management, add reset_session to the SessionsController#create action. Note that this removes any value from the session, _you have to transfer them to the new session_. <add>If you use the popular [Devise](https://rubygems.org/gems/devise) gem for user management, it will automatically expire sessions on sign in and sign out for you. If you roll your own, remember to expire the session after your sign in action (when the session is created). This will remove values from the session, therefore _you will have to transfer them to the new session_. <ide> <ide> Another countermeasure is to _save user-specific properties in the session_, verify them every time a request comes in, and deny access, if the information does not match. Such properties could be the remote IP address or the user agent (the web browser name), though the latter is less user-specific. When saving the IP address, you have to bear in mind that there are Internet service providers or large organizations that put their users behind proxies. _These might change over the course of a session_, so these users will not be able to use your application, or only in a limited way. <ide>
1
PHP
PHP
apply fixes from styleci
7a74817c91be61676deafe3a84a758a71350d9f2
<ide><path>src/Illuminate/Database/Eloquent/Model.php <ide> use Illuminate\Support\Str; <ide> use Illuminate\Support\Traits\ForwardsCalls; <ide> use JsonSerializable; <del>use LogicException; <ide> <ide> abstract class Model implements Arrayable, ArrayAccess, Jsonable, JsonSerializable, QueueableEntity, UrlRoutable <ide> {
1
Python
Python
add key control on mac os x
3198e3d7a32979207431625a1001d4eab65b8faf
<ide><path>glances/glances.py <ide> def displayProcess(self, processcount, processlist, sortedby='', log_count=0): <ide> # CPU% <ide> cpu_percent = processlist[processes]['cpu_percent'] <ide> if psutil_get_cpu_percent_tag: <del> self.term_window.addnstr( <del> self.process_y + 3 + processes, process_x + 12, <del> format(cpu_percent, '>5.1f'), 5, <del> self.__getProcessCpuColor2(cpu_percent)) <add> try: <add> self.term_window.addnstr( <add> self.process_y + 3 + processes, process_x + 12, <add> format(cpu_percent, '>5.1f'), 5, <add> self.__getProcessCpuColor2(cpu_percent)) <add> except: <add> self.term_window.addnstr( <add> self.process_y + 3 + processes, process_x, "N/A", 8) <ide> else: <ide> self.term_window.addnstr( <ide> self.process_y + 3 + processes, process_x, "N/A", 8) <ide> # MEM% <del> memory_percent = processlist[processes]['memory_percent'] <del> self.term_window.addnstr( <del> self.process_y + 3 + processes, process_x + 18, <del> format(memory_percent, '>5.1f'), 5, <del> self.__getProcessMemColor2(memory_percent)) <add> if (processlist[processes]['memory_percent'] != {}): <add> memory_percent = processlist[processes]['memory_percent'] <add> self.term_window.addnstr( <add> self.process_y + 3 + processes, process_x + 18, <add> format(memory_percent, '>5.1f'), 5, <add> self.__getProcessMemColor2(memory_percent)) <add> else: <add> self.term_window.addnstr( <add> self.process_y + 3 + processes, process_x + 18, "N/A", 8) <ide> # If screen space (X) is available then: <ide> # PID <ide> if tag_pid:
1
PHP
PHP
fix failing tests
cfb6ed4cdab1aaac63cfa153f3020dc5b27c5b96
<ide><path>lib/Cake/Test/Case/Model/Datasource/Database/MysqlTest.php <ide> public function testExceptionOnBrokenConnection() { <ide> public function testUpdateStatements() { <ide> $this->loadFixtures('Article', 'User'); <ide> $test = ConnectionManager::getDatasource('test'); <add> $db = $test->config['database']; <ide> <ide> $this->Dbo = $this->getMock('Mysql', array('execute'), array($test->config)); <ide> <ide> $this->Dbo->expects($this->at(0))->method('execute') <del> ->with("UPDATE `articles` SET `field1` = 'value1' WHERE 1 = 1"); <add> ->with("UPDATE `$db`.`articles` SET `field1` = 'value1' WHERE 1 = 1"); <ide> <ide> $this->Dbo->expects($this->at(1))->method('execute') <del> ->with("UPDATE `articles` AS `Article` LEFT JOIN `users` AS `User` ON (`Article`.`user_id` = `User`.`id`)" . <add> ->with("UPDATE `$db`.`articles` AS `Article` LEFT JOIN `$db`.`users` AS `User` ON " . <add> "(`Article`.`user_id` = `User`.`id`)" . <ide> " SET `Article`.`field1` = 2 WHERE 2=2"); <ide> <ide> $this->Dbo->expects($this->at(2))->method('execute') <del> ->with("UPDATE `articles` AS `Article` LEFT JOIN `users` AS `User` ON (`Article`.`user_id` = `User`.`id`)" . <add> ->with("UPDATE `$db`.`articles` AS `Article` LEFT JOIN `$db`.`users` AS `User` ON " . <add> "(`Article`.`user_id` = `User`.`id`)" . <ide> " SET `Article`.`field1` = 'value' WHERE `index` = 'val'"); <ide> <ide> $Article = new Article(); <ide> public function testUpdateStatements() { <ide> public function testDeleteStatements() { <ide> $this->loadFixtures('Article', 'User'); <ide> $test = ConnectionManager::getDatasource('test'); <add> $db = $test->config['database']; <ide> <ide> $this->Dbo = $this->getMock('Mysql', array('execute'), array($test->config)); <ide> <ide> $this->Dbo->expects($this->at(0))->method('execute') <del> ->with("DELETE FROM `articles` WHERE 1 = 1"); <add> ->with("DELETE FROM `$db`.`articles` WHERE 1 = 1"); <ide> <ide> $this->Dbo->expects($this->at(1))->method('execute') <del> ->with("DELETE `Article` FROM `articles` AS `Article` LEFT JOIN `users` AS `User` ON (`Article`.`user_id` = `User`.`id`)" . <add> ->with("DELETE `Article` FROM `$db`.`articles` AS `Article` LEFT JOIN `$db`.`users` AS `User` " . <add> "ON (`Article`.`user_id` = `User`.`id`)" . <ide> " WHERE 1 = 1"); <ide> <ide> $this->Dbo->expects($this->at(2))->method('execute') <del> ->with("DELETE `Article` FROM `articles` AS `Article` LEFT JOIN `users` AS `User` ON (`Article`.`user_id` = `User`.`id`)" . <add> ->with("DELETE `Article` FROM `$db`.`articles` AS `Article` LEFT JOIN `$db`.`users` AS `User` " . <add> "ON (`Article`.`user_id` = `User`.`id`)" . <ide> " WHERE 2=2"); <ide> $Article = new Article(); <ide>
1
Ruby
Ruby
handle cases where logger is not a tagged logger
43c6c7787954d959347a1f90d71b11ba0cb7a8c7
<ide><path>lib/action_cable/connection/base.rb <ide> class Base <ide> def initialize(server, env) <ide> @server, @env = server, env <ide> <del> @logger = new_tagged_logger || server.logger <add> @logger = new_tagged_logger <ide> <ide> @websocket = ActionCable::Connection::WebSocket.new(env) <ide> @subscriptions = ActionCable::Connection::Subscriptions.new(self) <ide> def respond_to_invalid_request <ide> <ide> # Tags are declared in the server but computed in the connection. This allows us per-connection tailored tags. <ide> def new_tagged_logger <del> if server.logger.respond_to?(:tagged) <del> TaggedLoggerProxy.new server.logger, <del> tags: server.config.log_tags.map { |tag| tag.respond_to?(:call) ? tag.call(request) : tag.to_s.camelize } <del> end <add> TaggedLoggerProxy.new server.logger, <add> tags: server.config.log_tags.map { |tag| tag.respond_to?(:call) ? tag.call(request) : tag.to_s.camelize } <ide> end <ide> <ide> def started_request_message <ide><path>lib/action_cable/connection/tagged_logger_proxy.rb <ide> def add_tags(*tags) <ide> @tags = @tags.uniq <ide> end <ide> <add> def tag(logger) <add> if logger.respond_to?(:tagged) <add> current_tags = tags - logger.formatter.current_tags <add> logger.tagged(*current_tags) { yield } <add> else <add> yield <add> end <add> end <add> <ide> %i( debug info warn error fatal unknown ).each do |severity| <ide> define_method(severity) do |message| <ide> log severity, message <ide> def add_tags(*tags) <ide> <ide> protected <ide> def log(type, message) <del> current_tags = tags - @logger.formatter.current_tags <del> @logger.tagged(*current_tags) { @logger.send type, message } <add> tag(@logger) { @logger.send type, message } <ide> end <ide> end <ide> end <ide><path>lib/action_cable/server/worker/active_record_connection_management.rb <ide> module ActiveRecordConnectionManagement <ide> end <ide> <ide> def with_database_connections <del> ActiveRecord::Base.logger.tagged(*connection.logger.tags) { yield } <add> connection.logger.tag(ActiveRecord::Base.logger) { yield } <ide> ensure <ide> ActiveRecord::Base.clear_active_connections! <ide> end
3
Javascript
Javascript
use correct server path since main was changed
de6d394d7365d2651614ac3517d51a91c63e3f1c
<ide><path>packages/next-server/index.js <add>// This file is used for when users run `require('next-server')` <ide> const Server = require('./dist/server/next-server').default <del>module.exports = function (opts) { <del> return new Server(opts) <add>module.exports = function (options) { <add> return new Server(options) <ide> } <ide><path>packages/next/server/next-dev-server.js <del>import Server from 'next-server' <add>import Server from 'next-server/dist/server/next-server' <ide> import { join } from 'path' <ide> import HotReloader from './hot-reloader' <ide> import {route} from 'next-server/dist/server/router' <ide><path>packages/next/server/next.js <ide> // This file is used for when users run `require('next')` <del>module.exports = (opts) => { <del> const Server = opts.dev ? require('./next-dev-server').default : require('next-server').default <del> return new Server(opts) <add>module.exports = (options) => { <add> if (options.dev) { <add> const Server = require('./next-dev-server').default <add> return new Server(options) <add> } <add> <add> const next = require('next-server') <add> return next(options) <ide> }
3
PHP
PHP
fix phpunit getmock warnings in 3.next
618457e8a6c07c7c1247b4bee6f0acd6fc5bd270
<ide><path>tests/TestCase/Console/ShellTest.php <ide> public function testRunCommandInvokeTask() <ide> { <ide> $parser = new ConsoleOptionParser('knife'); <ide> $parser->addSubcommand('slice'); <del> $io = $this->getMock('Cake\Console\ConsoleIo'); <add> $io = $this->getMockBuilder('Cake\Console\ConsoleIo')->getMock(); <ide> <del> $shell = $this->getMock('Cake\Console\Shell', ['hasTask', 'getOptionParser'], [$io]); <del> $task = $this->getMock('Cake\Console\Shell', ['main', '_welcome'], [$io]); <add> $shell = $this->getMockBuilder('Cake\Console\Shell') <add> ->setMethods(['hasTask', 'getOptionParser']) <add> ->setConstructorArgs([$io]) <add> ->getMock(); <add> $task = $this->getMockBuilder('Cake\Console\Shell') <add> ->setMethods(['main', '_welcome']) <add> ->setConstructorArgs([$io]) <add> ->getMock(); <ide> <ide> $shell->expects($this->once()) <ide> ->method('getOptionParser') <ide><path>tests/TestCase/Controller/Component/AuthComponentTest.php <ide> public function testIdentify() <ide> */ <ide> public function testIdentifyArrayAccess() <ide> { <del> $AuthLoginFormAuthenticate = $this->getMock( <del> 'Cake\Controller\Component\Auth\FormAuthenticate', <del> ['authenticate'], <del> [], <del> '', <del> false <del> ); <add> $AuthLoginFormAuthenticate = $this->getMockBuilder('Cake\Controller\Component\Auth\FormAuthenticate') <add> ->setMethods(['authenticate']) <add> ->disableOriginalConstructor() <add> ->getMock(); <ide> $this->Auth->authenticate = [ <ide> 'AuthLoginForm' => [ <ide> 'userModel' => 'AuthUsers' <ide> public function testIsAuthorizedDelegation() <ide> */ <ide> public function testIsAuthorizedWithArrayObject() <ide> { <del> $AuthMockOneAuthorize = $this->getMock( <del> 'Cake\Controller\Component\BaseAuthorize', <del> ['authorize'], <del> [], <del> '', <del> false <del> ); <add> $AuthMockOneAuthorize = $this->getMockBuilder('Cake\Controller\Component\BaseAuthorize') <add> ->setMethods(['authorize']) <add> ->disableOriginalConstructor() <add> ->getMock(); <ide> <ide> $this->Auth->setAuthorizeObject(0, $AuthMockOneAuthorize); <ide> $request = $this->Auth->request; <ide><path>tests/TestCase/Database/Schema/MysqlSchemaTest.php <ide> public function testCreateSql() <ide> public function testCreateSqlJson() <ide> { <ide> $driver = $this->_getMockedDriver(); <del> $connection = $this->getMock('Cake\Database\Connection', [], [], '', false); <add> $connection = $this->getMockBuilder('Cake\Database\Connection') <add> ->disableOriginalConstructor() <add> ->getMock(); <ide> $connection->expects($this->any()) <ide> ->method('driver') <ide> ->will($this->returnValue($driver)); <ide><path>tests/TestCase/Database/Type/JsonTypeTest.php <ide> public function setUp() <ide> { <ide> parent::setUp(); <ide> $this->type = Type::build('json'); <del> $this->driver = $this->getMock('Cake\Database\Driver'); <add> $this->driver = $this->getMockBuilder('Cake\Database\Driver')->getMock(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Error/Middleware/ErrorHandlerMiddlewareTest.php <ide> public function testRendererFactory() <ide> $factory = function ($exception) { <ide> $this->assertInstanceOf('LogicException', $exception); <ide> $cakeResponse = new CakeResponse; <del> $mock = $this->getMock('StdClass', ['render']); <add> $mock = $this->getMockBuilder('StdClass') <add> ->setMethods(['render']) <add> ->getMock(); <ide> $mock->expects($this->once()) <ide> ->method('render') <ide> ->will($this->returnValue($cakeResponse)); <ide> public function testHandleExceptionRenderingFails() <ide> $response = new Response(); <ide> <ide> $factory = function ($exception) { <del> $mock = $this->getMock('StdClass', ['render']); <add> $mock = $this->getMockBuilder('StdClass') <add> ->setMethods(['render']) <add> ->getMock(); <ide> $mock->expects($this->once()) <ide> ->method('render') <ide> ->will($this->throwException(new LogicException('Rendering failed'))); <ide><path>tests/TestCase/Http/ActionDispatcherTest.php <ide> public function setUp() <ide> */ <ide> public function testConstructorArgs() <ide> { <del> $factory = $this->getMock('Cake\Http\ControllerFactory'); <del> $events = $this->getMock('Cake\Event\EventManager'); <add> $factory = $this->getMockBuilder('Cake\Http\ControllerFactory')->getMock(); <add> $events = $this->getMockBuilder('Cake\Event\EventManager')->getMock(); <ide> $dispatcher = new ActionDispatcher($factory, $events); <ide> <ide> $this->assertAttributeSame($events, '_eventManager', $dispatcher); <ide> public function testAddFilter() <ide> $this->assertCount(1, $events->listeners('Dispatcher.beforeDispatch')); <ide> $this->assertCount(1, $events->listeners('Dispatcher.afterDispatch')); <ide> <del> $filter = $this->getMock( <del> 'Cake\Routing\DispatcherFilter', <del> ['beforeDispatch', 'afterDispatch'] <del> ); <add> $filter = $this->getMockBuilder('Cake\Routing\DispatcherFilter') <add> ->setMethods(['beforeDispatch', 'afterDispatch']) <add> ->getMock(); <ide> $this->dispatcher->addFilter($filter); <ide> <ide> $this->assertCount(2, $this->dispatcher->getFilters()); <ide> public function testBeforeDispatchEventAbort() <ide> { <ide> $response = new Response(); <ide> $dispatcher = new ActionDispatcher(); <del> $filter = $this->getMock( <del> 'Cake\Routing\DispatcherFilter', <del> ['beforeDispatch', 'afterDispatch'] <del> ); <add> $filter = $this->getMockBuilder('Cake\Routing\DispatcherFilter') <add> ->setMethods(['beforeDispatch', 'afterDispatch']) <add> ->getMock(); <ide> $filter->expects($this->once()) <ide> ->method('beforeDispatch') <ide> ->will($this->returnValue($response)); <ide> public function testBeforeDispatchEventAbort() <ide> */ <ide> public function testDispatchAfterDispatchEventModifyResponse() <ide> { <del> $filter = $this->getMock( <del> 'Cake\Routing\DispatcherFilter', <del> ['beforeDispatch', 'afterDispatch'] <del> ); <add> $filter = $this->getMockBuilder('Cake\Routing\DispatcherFilter') <add> ->setMethods(['beforeDispatch', 'afterDispatch']) <add> ->getMock(); <ide> $filter->expects($this->once()) <ide> ->method('afterDispatch') <ide> ->will($this->returnCallback(function ($event) { <ide> public function testDispatchAfterDispatchEventModifyResponse() <ide> */ <ide> public function testDispatchActionReturnResponseNoAfterDispatch() <ide> { <del> $filter = $this->getMock( <del> 'Cake\Routing\DispatcherFilter', <del> ['beforeDispatch', 'afterDispatch'] <del> ); <add> $filter = $this->getMockBuilder('Cake\Routing\DispatcherFilter') <add> ->setMethods(['beforeDispatch', 'afterDispatch']) <add> ->getMock(); <ide> $filter->expects($this->never()) <ide> ->method('afterDispatch'); <ide> <ide> public function testMissingController() <ide> 'action' => 'home', <ide> ] <ide> ]); <del> $response = $this->getMock('Cake\Network\Response'); <add> $response = $this->getMockBuilder('Cake\Network\Response')->getMock(); <ide> $this->dispatcher->dispatch($request, $response); <ide> } <ide> <ide> public function testMissingControllerInterface() <ide> 'action' => 'index', <ide> ] <ide> ]); <del> $response = $this->getMock('Cake\Network\Response'); <add> $response = $this->getMockBuilder('Cake\Network\Response')->getMock(); <ide> $this->dispatcher->dispatch($request, $response); <ide> } <ide> <ide> public function testMissingControllerAbstract() <ide> 'action' => 'index', <ide> ] <ide> ]); <del> $response = $this->getMock('Cake\Network\Response'); <add> $response = $this->getMockBuilder('Cake\Network\Response')->getMock(); <ide> $this->dispatcher->dispatch($request, $response); <ide> } <ide> <ide> public function testMissingControllerLowercase() <ide> 'pass' => ['home'], <ide> ] <ide> ]); <del> $response = $this->getMock('Cake\Network\Response'); <add> $response = $this->getMockBuilder('Cake\Network\Response')->getMock(); <ide> $this->dispatcher->dispatch($request, $response); <ide> } <ide> <ide><path>tests/TestCase/Http/ControllerFactoryTest.php <ide> public function setUp() <ide> parent::setUp(); <ide> Configure::write('App.namespace', 'TestApp'); <ide> $this->factory = new ControllerFactory(); <del> $this->response = $this->getMock('Cake\Network\Response'); <add> $this->response = $this->getMockBuilder('Cake\Network\Response')->getMock(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Http/ResponseTransformerTest.php <ide> public function testToPsrBodyCallable() <ide> */ <ide> public function testToPsrBodyFileResponse() <ide> { <del> $cake = $this->getMock('Cake\Network\Response', ['_clearBuffer']); <add> $cake = $this->getMockBuilder('Cake\Network\Response') <add> ->setMethods(['_clearBuffer']) <add> ->getMock(); <ide> $cake->file(__FILE__, ['name' => 'some-file.php', 'download' => true]); <ide> <ide> $result = ResponseTransformer::toPsr($cake); <ide> public function testToPsrBodyFileResponse() <ide> public function testToPsrBodyFileResponseFileRange() <ide> { <ide> $_SERVER['HTTP_RANGE'] = 'bytes=10-20'; <del> $cake = $this->getMock('Cake\Network\Response', ['_clearBuffer']); <add> $cake = $this->getMockBuilder('Cake\Network\Response') <add> ->setMethods(['_clearBuffer']) <add> ->getMock(); <ide> $path = TEST_APP . 'webroot/css/cake.generic.css'; <ide> $cake->file($path, ['name' => 'test-asset.css', 'download' => true]); <ide> <ide><path>tests/TestCase/Http/RunnerTest.php <ide> public function setUp() <ide> public function testRunSingle() <ide> { <ide> $this->stack->push($this->ok); <del> $req = $this->getMock('Psr\Http\Message\ServerRequestInterface'); <del> $res = $this->getMock('Psr\Http\Message\ResponseInterface'); <add> $req = $this->getMockBuilder('Psr\Http\Message\ServerRequestInterface')->getMock(); <add> $res = $this->getMockBuilder('Psr\Http\Message\ResponseInterface')->getMock(); <ide> <ide> $runner = new Runner(); <ide> $result = $runner->run($this->stack, $req, $res); <ide> public function testRunSingle() <ide> public function testRunResponseReplace() <ide> { <ide> $one = function ($req, $res, $next) { <del> $res = $this->getMock('Psr\Http\Message\ResponseInterface'); <add> $res = $this->getMockBuilder('Psr\Http\Message\ResponseInterface')->getMock(); <ide> return $next($req, $res); <ide> }; <ide> $this->stack->push($one); <ide> $runner = new Runner(); <ide> <del> $req = $this->getMock('Psr\Http\Message\ServerRequestInterface'); <del> $res = $this->getMock('Psr\Http\Message\ResponseInterface'); <add> $req = $this->getMockBuilder('Psr\Http\Message\ServerRequestInterface')->getMock(); <add> $res = $this->getMockBuilder('Psr\Http\Message\ResponseInterface')->getMock(); <ide> $result = $runner->run($this->stack, $req, $res); <ide> <ide> $this->assertNotSame($res, $result, 'Response was not replaced'); <ide> public function testRunSequencing() <ide> $this->stack->push($one)->push($two)->push($three); <ide> $runner = new Runner(); <ide> <del> $req = $this->getMock('Psr\Http\Message\ServerRequestInterface'); <del> $res = $this->getMock('Psr\Http\Message\ResponseInterface'); <add> $req = $this->getMockBuilder('Psr\Http\Message\ServerRequestInterface')->getMock(); <add> $res = $this->getMockBuilder('Psr\Http\Message\ResponseInterface')->getMock(); <ide> $result = $runner->run($this->stack, $req, $res); <ide> <ide> $this->assertSame($res, $result, 'Response is not correct'); <ide> public function testRunSequencing() <ide> public function testRunExceptionInMiddleware() <ide> { <ide> $this->stack->push($this->ok)->push($this->fail); <del> $req = $this->getMock('Psr\Http\Message\ServerRequestInterface'); <del> $res = $this->getMock('Psr\Http\Message\ResponseInterface'); <add> $req = $this->getMockBuilder('Psr\Http\Message\ServerRequestInterface')->getMock(); <add> $res = $this->getMockBuilder('Psr\Http\Message\ResponseInterface')->getMock(); <ide> <ide> $runner = new Runner(); <ide> $runner->run($this->stack, $req, $res); <ide> public function testRunExceptionInMiddleware() <ide> public function testRunNextNotCalled() <ide> { <ide> $this->stack->push($this->noNext); <del> $req = $this->getMock('Psr\Http\Message\ServerRequestInterface'); <del> $res = $this->getMock('Psr\Http\Message\ResponseInterface'); <add> $req = $this->getMockBuilder('Psr\Http\Message\ServerRequestInterface')->getMock(); <add> $res = $this->getMockBuilder('Psr\Http\Message\ResponseInterface')->getMock(); <ide> <ide> $runner = new Runner(); <ide> $result = $runner->run($this->stack, $req, $res); <ide><path>tests/TestCase/Http/ServerTest.php <ide> public function tearDown() <ide> */ <ide> public function testAppGetSet() <ide> { <del> $app = $this->getMock('Cake\Http\BaseApplication', [], [$this->config]); <add> $app = $this->getMockBuilder('Cake\Http\BaseApplication') <add> ->setConstructorArgs([$this->config]) <add> ->getMock(); <ide> $server = new Server($app); <ide> $this->assertSame($app, $server->getApp($app)); <ide> } <ide> public function testEmit() <ide> ->withHeader('X-First', 'first') <ide> ->withHeader('X-Second', 'second'); <ide> <del> $emitter = $this->getMock('Zend\Diactoros\Response\EmitterInterface'); <add> $emitter = $this->getMockBuilder('Zend\Diactoros\Response\EmitterInterface')->getMock(); <ide> $emitter->expects($this->once()) <ide> ->method('emit') <ide> ->with($final); <ide><path>tests/TestCase/ORM/EntityTest.php <ide> public function testJsonSerialize() <ide> */ <ide> public function testJsonSerializeRecursive() <ide> { <del> $phone = $this->getMock(Entity::class, ['jsonSerialize']); <add> $phone = $this->getMockBuilder(Entity::class) <add> ->setMethods(['jsonSerialize']) <add> ->getMock(); <ide> $phone->expects($this->once())->method('jsonSerialize')->will($this->returnValue('12345')); <ide> $data = ['name' => 'James', 'age' => 20, 'phone' => $phone]; <ide> $entity = new Entity($data); <ide><path>tests/TestCase/Shell/CacheShellTest.php <ide> class CacheShellTest extends TestCase <ide> public function setUp() <ide> { <ide> parent::setUp(); <del> $this->io = $this->getMock('Cake\Console\ConsoleIo'); <add> $this->io = $this->getMockBuilder('Cake\Console\ConsoleIo')->getMock(); <ide> $this->shell = new CacheShell($this->io); <ide> Cache::config('test', ['engine' => 'File', 'path' => TMP]); <ide> }
12
Ruby
Ruby
remove cors initializer from rails app
9917c0c255e1c1005b85885a15cc9a28bb8e4275
<ide><path>railties/lib/rails/generators/rails/app/app_generator.rb <ide> def delete_non_api_initializers_if_api_option <ide> end <ide> end <ide> <add> def delete_api_initializers <add> unless options[:api] <add> remove_file 'config/initializers/cors.rb' <add> end <add> end <add> <ide> def finish_template <ide> build(:leftovers) <ide> end <ide><path>railties/test/generators/app_generator_test.rb <ide> def test_new_application_use_json_serialzier <ide> assert_file("config/initializers/cookies_serializer.rb", /Rails\.application\.config\.action_dispatch\.cookies_serializer = :json/) <ide> end <ide> <add> def test_new_application_not_include_api_initializers <add> run_generator <add> <add> assert_no_file 'config/initializers/cors.rb' <add> end <add> <ide> def test_rails_update_keep_the_cookie_serializer_if_it_is_already_configured <ide> app_root = File.join(destination_root, 'myapp') <ide> run_generator [app_root]
2
PHP
PHP
add missing cell option
178f2cfb8715dfeae6535c0845087108b770805f
<ide><path>src/Shell/Task/TestTask.php <ide> public function getOptionParser() { <ide> 'Entity', 'entity', <ide> 'Helper', 'helper', <ide> 'Component', 'component', <del> 'Behavior', 'behavior' <add> 'Behavior', 'behavior', <add> 'Cell', 'cell', <ide> ] <ide> ])->addArgument('name', [ <ide> 'help' => 'An existing class to bake tests for.'
1
Python
Python
add metavar to cli arguments
7f02e56c9cb8b548624d13e9c2c2b89d753f996b
<ide><path>airflow/cli/cli_parser.py <ide> def positive_int(value): <ide> "Output table format. The specified value is passed to " <ide> "the tabulate module (https://pypi.org/project/tabulate/). " <ide> ), <add> metavar="FORMAT", <ide> choices=tabulate_formats, <ide> default="plain") <ide> ARG_COLOR = Arg( <ide> class AirflowHelpFormatter(argparse.HelpFormatter): <ide> """ <ide> def _format_action(self, action: Action): <ide> if isinstance(action, argparse._SubParsersAction): # pylint: disable=protected-access <add> <ide> parts = [] <add> action_header = self._format_action_invocation(action) <add> action_header = '%*s%s\n' % (self._current_indent, '', action_header) <add> parts.append(action_header) <add> <add> self._indent() <ide> subactions = action._get_subactions() # pylint: disable=protected-access <ide> action_subcommnads, group_subcommnands = partition( <ide> lambda d: isinstance(ALL_COMMANDS_DICT[d.dest], GroupCommand), subactions <ide> def _format_action(self, action: Action): <ide> for subaction in action_subcommnads: <ide> parts.append(self._format_action(subaction)) <ide> self._dedent() <add> self._dedent() <ide> <ide> # return a single string <ide> return self._join_parts(parts) <ide> def _format_action(self, action: Action): <ide> def get_parser(dag_parser: bool = False) -> argparse.ArgumentParser: <ide> """Creates and returns command line argument parser""" <ide> parser = DefaultHelpParser(prog="airflow", formatter_class=AirflowHelpFormatter) <del> subparsers = parser.add_subparsers(dest='subcommand') <add> subparsers = parser.add_subparsers(dest='subcommand', metavar="GROUP_OR_COMMAND") <ide> subparsers.required = True <ide> <ide> subparser_list = DAG_CLI_COMMANDS if dag_parser else ALL_COMMANDS_DICT.keys() <ide> def _add_action_command(sub: ActionCommand, sub_proc: argparse.ArgumentParser) - <ide> <ide> def _add_group_command(sub: GroupCommand, sub_proc: argparse.ArgumentParser) -> None: <ide> subcommands = sub.subcommands <del> sub_subparsers = sub_proc.add_subparsers(dest="subcommand") <add> sub_subparsers = sub_proc.add_subparsers(dest="subcommand", metavar="COMMAND") <ide> sub_subparsers.required = True <ide> <ide> for command in sorted(subcommands, key=lambda x: x.name):
1
Python
Python
add tests for ninefold
2475916e0d17e4b03bb93970b88555a229a5f3c0
<ide><path>libcloud/test/storage/test_ninefold.py <add># Licensed to the Apache Software Foundation (ASF) under one or more <add># contributor license agreements. See the NOTICE file distributed with <add># this work for additional information regarding copyright ownership. <add># The ASF licenses this file to You under the Apache License, Version 2.0 <add># (the "License"); you may not use this file except in compliance with <add># the License. You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, software <add># distributed under the License is distributed on an "AS IS" BASIS, <add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add># See the License for the specific language governing permissions and <add># limitations under the License. <add> <add>import unittest <add>import base64 <add> <add>from libcloud.utils.py3 import b <add>from libcloud.storage.drivers.ninefold import NinefoldStorageDriver <add>from libcloud.test.storage.test_atmos import AtmosMockHttp, AtmosTests <add> <add> <add>class NinefoldTests(AtmosTests, unittest.TestCase): <add> <add> def setUp(self): <add> NinefoldStorageDriver.connectionCls.conn_class = AtmosMockHttp <add> NinefoldStorageDriver.path = '' <add> AtmosMockHttp.type = None <add> AtmosMockHttp.upload_created = False <add> self.driver = NinefoldStorageDriver('dummy', base64.b64encode(b('dummy'))) <add> self._remove_test_file()
1
Text
Text
fix epic typo
5be91d5f23ef96403134973ad5130293a16bd6d6
<ide><path>docs/api/applyMiddleware.md <ide> import sandwiches from './reducers'; <ide> let createStoreWithMiddleware = applyMiddleware(thunk)(createStore); <ide> <ide> // We can use it exactly like “vanilla” createStore. <del>let store = createStoreWithMiddleware(sandhiches); <add>let store = createStoreWithMiddleware(sandwiches); <ide> <ide> function fetchSecretSauce() { <ide> return fetch('https://www.google.com/search?q=secret+sauce');
1
Javascript
Javascript
reduce usage of require('util')
51256e5d78d8cbb4c532c9d7226ae5ad08d09020
<ide><path>lib/internal/fs/utils.js <ide> const { <ide> }, <ide> hideStackFrames <ide> } = require('internal/errors'); <del>const { isUint8Array, isArrayBufferView } = require('internal/util/types'); <add>const { <add> isUint8Array, <add> isArrayBufferView, <add> isDate <add>} = require('internal/util/types'); <ide> const { once } = require('internal/util'); <ide> const pathModule = require('path'); <del>const util = require('util'); <ide> const kType = Symbol('type'); <ide> const kStats = Symbol('stats'); <ide> <ide> function toUnixTimestamp(time, name = 'time') { <ide> } <ide> return time; <ide> } <del> if (util.isDate(time)) { <add> if (isDate(time)) { <ide> // Convert to 123.456 UNIX timestamp <ide> return time.getTime() / 1000; <ide> }
1
Text
Text
add full stop to the release note items
99423defd826b09d9bf37bf942c2682b90ea8b42
<ide><path>docs/topics/release-notes.md <ide> You can determine your currently installed version using `pip freeze`: <ide> <ide> ### 3.0.1 <ide> <del>**Date**: [December 2014][3.0.1-milestone] <add>**Date**: [December 2014][3.0.1][3.0.1-milestone]: <ide> <del>* More helpful error message when the default Serializer `create()` fails ([#2013](https://github.com/tomchristie/django-rest-framework/issues/2013)) <add>* More helpful error message when the default Serializer `create()` fails. ([#2013](https://github.com/tomchristie/django-rest-framework/issues/2013)) <ide> * Raise error when attempting to save serializer if data is not valid. ([#2098](https://github.com/tomchristie/django-rest-framework/issues/2098)) <del>* Fix `FileUploadParser` breaks with empty file names and multiple upload handlers ([#2109](https://github.com/tomchristie/django-rest-framework/issues/2109)) <del>* Improve BindingDict` to support standard dict-functions ([#2135](https://github.com/tomchristie/django-rest-framework/issues/2135), [#2163](https://github.com/tomchristie/django-rest-framework/issues/2163)) <del>* Add `validate()` to `ListSerializer` ([#2168](https://github.com/tomchristie/django-rest-framework/issues/2168), [#2225](https://github.com/tomchristie/django-rest-framework/issues/2225), [#2232](https://github.com/tomchristie/django-rest-framework/issues/2232)) <del>* Fix JSONP renderer failing to escape some characters ([#2169](https://github.com/tomchristie/django-rest-framework/issues/2169), [#2195](https://github.com/tomchristie/django-rest-framework/issues/2195)) <del>* Add missing default style for `FileField` ([#2172](https://github.com/tomchristie/django-rest-framework/issues/2172)) <del>* Actions are required when calling `ViewSet.as_view()` ([#2175](https://github.com/tomchristie/django-rest-framework/issues/2175)) <del>* Add `allow_blank` to `ChoiceField ([#2184](https://github.com/tomchristie/django-rest-framework/issues/2184), [#2239](https://github.com/tomchristie/django-rest-framework/issues/2239)) <del>* Cosmetic fixes in the HTML renderer ([#2187](https://github.com/tomchristie/django-rest-framework/issues/2187)) <add>* Fix `FileUploadParser` breaks with empty file names and multiple upload handlers. ([#2109](https://github.com/tomchristie/django-rest-framework/issues/2109)) <add>* Improve BindingDict` to support standard dict-functions. ([#2135](https://github.com/tomchristie/django-rest-framework/issues/2135), [#2163](https://github.com/tomchristie/django-rest-framework/issues/2163)) <add>* Add `validate()` to `ListSerializer`. ([#2168](https://github.com/tomchristie/django-rest-framework/issues/2168), [#2225](https://github.com/tomchristie/django-rest-framework/issues/2225), [#2232](https://github.com/tomchristie/django-rest-framework/issues/2232)) <add>* Fix JSONP renderer failing to escape some characters. ([#2169](https://github.com/tomchristie/django-rest-framework/issues/2169), [#2195](https://github.com/tomchristie/django-rest-framework/issues/2195)) <add>* Add missing default style for `FileField`. ([#2172](https://github.com/tomchristie/django-rest-framework/issues/2172)) <add>* Actions are required when calling `ViewSet.as_view()`. ([#2175](https://github.com/tomchristie/django-rest-framework/issues/2175)) <add>* Add `allow_blank` to `ChoiceField`. ([#2184](https://github.com/tomchristie/django-rest-framework/issues/2184), [#2239](https://github.com/tomchristie/django-rest-framework/issues/2239)) <add>* Cosmetic fixes in the HTML renderer. ([#2187](https://github.com/tomchristie/django-rest-framework/issues/2187)) <ide> * Raise error if `fields` on serializer is not a list of strings. ([#2193](https://github.com/tomchristie/django-rest-framework/issues/2193), [#2213](https://github.com/tomchristie/django-rest-framework/issues/2213)) <ide> * Improve checks for nested creates and updates. ([#2194](https://github.com/tomchristie/django-rest-framework/issues/2194), [#2196](https://github.com/tomchristie/django-rest-framework/issues/2196)) <del>* `validated_attrs` argument renamed to `validated_data` in `Serializer` `create()`/`update()` ([#2197](https://github.com/tomchristie/django-rest-framework/issues/2197)) <del>* Remove deprecated code to reflect the droped Django versions ([#2200](https://github.com/tomchristie/django-rest-framework/issues/2200)) <add>* `validated_attrs` argument renamed to `validated_data` in `Serializer` `create()`/`update()`. ([#2197](https://github.com/tomchristie/django-rest-framework/issues/2197)) <add>* Remove deprecated code to reflect the droped Django versions. ([#2200](https://github.com/tomchristie/django-rest-framework/issues/2200)) <ide> * Better serializer errors for nested writes. ([#2202](https://github.com/tomchristie/django-rest-framework/issues/2202), [#2215](https://github.com/tomchristie/django-rest-framework/issues/2215)) <del>* Fix pagination and custom permissions incompatibility ([#2205](https://github.com/tomchristie/django-rest-framework/issues/2205)) <add>* Fix pagination and custom permissions incompatibility. ([#2205](https://github.com/tomchristie/django-rest-framework/issues/2205)) <ide> * Raise error if `fields` on serializer is not a list of strings. ([#2213](https://github.com/tomchristie/django-rest-framework/issues/2213)) <ide> * Add missing translation markers for relational fields. ([#2231](https://github.com/tomchristie/django-rest-framework/issues/2231)) <ide> * Improve field lookup behavior for dicts/mappings. ([#2244](https://github.com/tomchristie/django-rest-framework/issues/2244), [#2243](https://github.com/tomchristie/django-rest-framework/issues/2243)) <del>* Optimized hyperlinked PK ([#2242](https://github.com/tomchristie/django-rest-framework/issues/2242)) <add>* Optimized hyperlinked PK. ([#2242](https://github.com/tomchristie/django-rest-framework/issues/2242)) <ide> <ide> ### 3.0.0 <ide>
1
PHP
PHP
add arrayaccess test for request object
4e0754d3b9d869c0fd23574ee725c67ac834b2dd
<ide><path>tests/Http/HttpRequestTest.php <ide> public function testInputMethod() <ide> $this->assertInstanceOf('Symfony\Component\HttpFoundation\File\UploadedFile', $request['file']); <ide> } <ide> <add> public function testArrayAccess() <add> { <add> $request = Request::create('/', 'GET', ['name' => null, 'foo' => ['bar' => null, 'baz' => '']]); <add> $request->setRouteResolver(function () use ($request) { <add> $route = new Route('GET', '/foo/bar/{id}/{name}', []); <add> $route->bind($request); <add> $route->setParameter('id', 'foo'); <add> $route->setParameter('name', 'Taylor'); <add> <add> return $route; <add> }); <add> <add> $this->assertFalse(isset($request['non-existant'])); <add> $this->assertNull($request['non-existant']); <add> <add> $this->assertTrue(isset($request['name'])); <add> $this->assertEquals(null, $request['name']); <add> $this->assertNotEquals('Taylor', $request['name']); <add> <add> $this->assertTrue(isset($request['foo.bar'])); <add> $this->assertEquals(null, $request['foo.bar']); <add> $this->assertTrue(isset($request['foo.baz'])); <add> $this->assertEquals('', $request['foo.baz']); <add> <add> $this->assertTrue(isset($request['id'])); <add> $this->assertEquals('foo', $request['id']); <add> } <add> <ide> public function testAllMethod() <ide> { <ide> $request = Request::create('/', 'GET', ['name' => 'Taylor', 'age' => null]);
1
Ruby
Ruby
deprecate unused method
3688a2e01a471acacd13b54eddf57e97d24466f8
<ide><path>activerecord/lib/active_record/tasks/database_tasks.rb <ide> def dump_schema(db_config, format = ActiveRecord::Base.schema_format) # :nodoc: <ide> def schema_file(format = ActiveRecord::Base.schema_format) <ide> File.join(db_dir, schema_file_type(format)) <ide> end <add> deprecate :schema_file <ide> <ide> def schema_file_type(format = ActiveRecord::Base.schema_format) <ide> case format <ide><path>activerecord/test/cases/tasks/database_tasks_test.rb <ide> def test_check_schema_file <ide> end <ide> end <ide> <del> class DatabaseTasksCheckSchemaFileDefaultsTest < ActiveRecord::TestCase <add> class DatabaseTasksCheckSchemaFileMethods < ActiveRecord::TestCase <ide> def test_check_schema_file_defaults <ide> ActiveRecord::Tasks::DatabaseTasks.stub(:db_dir, "/tmp") do <del> assert_equal "/tmp/schema.rb", ActiveRecord::Tasks::DatabaseTasks.schema_file <add> assert_deprecated do <add> assert_equal "/tmp/schema.rb", ActiveRecord::Tasks::DatabaseTasks.schema_file <add> end <ide> end <ide> end <del> end <ide> <del> class DatabaseTasksCheckSchemaFileSpecifiedFormatsTest < ActiveRecord::TestCase <ide> { ruby: "schema.rb", sql: "structure.sql" }.each_pair do |fmt, filename| <ide> define_method("test_check_schema_file_for_#{fmt}_format") do <ide> ActiveRecord::Tasks::DatabaseTasks.stub(:db_dir, "/tmp") do <del> assert_equal "/tmp/#{filename}", ActiveRecord::Tasks::DatabaseTasks.schema_file(fmt) <add> assert_deprecated do <add> assert_equal "/tmp/#{filename}", ActiveRecord::Tasks::DatabaseTasks.schema_file(fmt) <add> end <ide> end <ide> end <ide> end
2
PHP
PHP
correct doc block
6002d6913d7bfbd0fa2b69ce79964b36ee985342
<ide><path>lib/Cake/Network/Email/CakeEmail.php <ide> protected function _attachInlineFiles($boundary = null) { <ide> /** <ide> * Render the body of the email. <ide> * <del> * @param string $content Content to render <add> * @param array $content Content to render <ide> * @return array Email body ready to be sent <ide> */ <ide> protected function _render($content) {
1
Python
Python
fix mypy errors for sftp provider
756b1207a96ff65f7e0f83864a7ad0386df9fa9d
<ide><path>airflow/providers/sftp/sensors/sftp.py <ide> """This module contains SFTP sensor.""" <ide> from typing import Optional <ide> <del>from paramiko import SFTP_NO_SUCH_FILE <add>from paramiko.sftp import SFTP_NO_SUCH_FILE <ide> <ide> from airflow.providers.sftp.hooks.sftp import SFTPHook <ide> from airflow.sensors.base import BaseSensorOperator <ide><path>tests/providers/sftp/sensors/test_sftp.py <ide> from unittest.mock import patch <ide> <ide> import pytest <del>from paramiko import SFTP_FAILURE, SFTP_NO_SUCH_FILE <add>from paramiko.sftp import SFTP_FAILURE, SFTP_NO_SUCH_FILE <ide> <ide> from airflow.providers.sftp.sensors.sftp import SFTPSensor <ide>
2
Text
Text
improve perf_hooks docs
d58b83d61f011fd3d6d9461dc5493d016d96c3a3
<ide><path>doc/api/perf_hooks.md <ide> added: v8.5.0 <ide> Returns a list of `PerformanceEntry` objects in chronological order <ide> with respect to `performanceEntry.startTime`. <ide> <add>```js <add>const { <add> performance, <add> PerformanceObserver <add>} = require('perf_hooks'); <add> <add>const obs = new PerformanceObserver((perfObserverList, observer) => { <add> console.log(perfObserverList.getEntries()); <add> /** <add> * [ <add> * PerformanceEntry { <add> * name: 'test', <add> * entryType: 'mark', <add> * startTime: 81.465639, <add> * duration: 0 <add> * }, <add> * PerformanceEntry { <add> * name: 'meow', <add> * entryType: 'mark', <add> * startTime: 81.860064, <add> * duration: 0 <add> * } <add> * ] <add> */ <add> observer.disconnect(); <add>}); <add>obs.observe({ entryTypes: ['mark'], buffered: true }); <add> <add>performance.mark('test'); <add>performance.mark('meow'); <add>``` <add> <ide> ### `performanceObserverEntryList.getEntriesByName(name[, type])` <ide> <!-- YAML <ide> added: v8.5.0 <ide> with respect to `performanceEntry.startTime` whose `performanceEntry.name` is <ide> equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to <ide> `type`. <ide> <add>```js <add>const { <add> performance, <add> PerformanceObserver <add>} = require('perf_hooks'); <add> <add>const obs = new PerformanceObserver((perfObserverList, observer) => { <add> console.log(perfObserverList.getEntriesByName('meow')); <add> /** <add> * [ <add> * PerformanceEntry { <add> * name: 'meow', <add> * entryType: 'mark', <add> * startTime: 98.545991, <add> * duration: 0 <add> * } <add> * ] <add> */ <add> console.log(perfObserverList.getEntriesByName('nope')); // [] <add> <add> console.log(perfObserverList.getEntriesByName('test', 'mark')); <add> /** <add> * [ <add> * PerformanceEntry { <add> * name: 'test', <add> * entryType: 'mark', <add> * startTime: 63.518931, <add> * duration: 0 <add> * } <add> * ] <add> */ <add> console.log(perfObserverList.getEntriesByName('test', 'measure')); // [] <add> observer.disconnect(); <add>}); <add>obs.observe({ entryTypes: ['mark', 'measure'], buffered: true }); <add> <add>performance.mark('test'); <add>performance.mark('meow'); <add>``` <add> <ide> ### `performanceObserverEntryList.getEntriesByType(type)` <ide> <!-- YAML <ide> added: v8.5.0 <ide> Returns a list of `PerformanceEntry` objects in chronological order <ide> with respect to `performanceEntry.startTime` whose `performanceEntry.entryType` <ide> is equal to `type`. <ide> <add>```js <add>const { <add> performance, <add> PerformanceObserver <add>} = require('perf_hooks'); <add> <add>const obs = new PerformanceObserver((perfObserverList, observer) => { <add> console.log(perfObserverList.getEntriesByType('mark')); <add> /** <add> * [ <add> * PerformanceEntry { <add> * name: 'test', <add> * entryType: 'mark', <add> * startTime: 55.897834, <add> * duration: 0 <add> * }, <add> * PerformanceEntry { <add> * name: 'meow', <add> * entryType: 'mark', <add> * startTime: 56.350146, <add> * duration: 0 <add> * } <add> * ] <add> */ <add> observer.disconnect(); <add>}); <add>obs.observe({ entryTypes: ['mark'], buffered: true }); <add> <add>performance.mark('test'); <add>performance.mark('meow'); <add>``` <add> <ide> ## `perf_hooks.monitorEventLoopDelay([options])` <ide> <!-- YAML <ide> added: v11.10.0
1
PHP
PHP
remove redundant test logic
c943d94e1b458b298b88b954050db0f50a8a7e26
<ide><path>tests/TestCase/TestSuite/FixtureManagerTest.php <ide> public function testFixturizeCoreConstraint() <ide> ]; <ide> $this->assertSame($expectedConstraint, $schema->getConstraint('tag_id_fk')); <ide> $this->manager->unload($test); <del> <del> $this->manager->load($test); <del> $table = $this->getTableLocator()->get('ArticlesTags'); <del> $schema = $table->getSchema(); <del> $expectedConstraint = [ <del> 'type' => 'foreign', <del> 'columns' => [ <del> 'tag_id', <del> ], <del> 'references' => [ <del> 'tags', <del> 'id', <del> ], <del> 'update' => 'cascade', <del> 'delete' => 'cascade', <del> 'length' => [], <del> ]; <del> $this->assertSame($expectedConstraint, $schema->getConstraint('tag_id_fk')); <del> <del> $this->manager->unload($test); <ide> } <ide> <ide> /** <ide> public function testLoadSingle() <ide> { <ide> $test = $this->getMockBuilder('Cake\TestSuite\TestCase')->getMock(); <ide> $test->autoFixtures = false; <del> $test->fixtures = ['core.Articles', 'core.ArticlesTags', 'core.Tags']; <add> $test->fixtures = ['core.Articles', 'core.Tags']; <ide> $this->manager->fixturize($test); <ide> $this->manager->loadSingle('Articles'); <ide> $this->manager->loadSingle('Tags'); <del> $this->manager->loadSingle('ArticlesTags'); <ide> <ide> $table = $this->getTableLocator()->get('ArticlesTags'); <ide> $results = $table->find('all')->toArray(); <ide> public function testLoadSingle() <ide> $this->assertCount(4, $results); <ide> <ide> $this->manager->unload($test); <del> <del> $this->manager->loadSingle('Articles'); <del> $this->manager->loadSingle('Tags'); <del> $this->manager->loadSingle('ArticlesTags'); <del> <del> $table = $this->getTableLocator()->get('ArticlesTags'); <del> $results = $table->find('all')->toArray(); <del> $schema = $table->getSchema(); <del> $expectedConstraint = [ <del> 'type' => 'foreign', <del> 'columns' => [ <del> 'tag_id', <del> ], <del> 'references' => [ <del> 'tags', <del> 'id', <del> ], <del> 'update' => 'cascade', <del> 'delete' => 'cascade', <del> 'length' => [], <del> ]; <del> $this->assertSame($expectedConstraint, $schema->getConstraint('tag_id_fk')); <del> $this->assertCount(4, $results); <del> $this->manager->unload($test); <ide> } <ide> <ide> /**
1
Javascript
Javascript
add alpnprotocols option to clientoptions
b4749014385e77268152d25c62f39791aed955a4
<ide><path>test/parallel/test-http2-connect.js <ide> const { connect: tlsConnect } = require('tls'); <ide> }; <ide> <ide> const clientOptions = { <add> ALPNProtocols: ['h2'], <ide> port, <ide> rejectUnauthorized: false <ide> };
1
Javascript
Javascript
enable log_view_lookups for {{outlet}} keyword
89cf0a916c8cd436c5370392d8890130d712a97a
<ide><path>packages/ember-application/tests/system/logging_test.js <ide> QUnit.test("do not log when template and view are missing when flag is not true" <ide> }); <ide> }); <ide> <del>QUnit.skip("log which view is used with a template", function() { <add>QUnit.test("log which view is used with a template", function() { <ide> if (EmberDev && EmberDev.runningProdBuild) { <ide> ok(true, 'Logging does not occur in production builds'); <ide> return; <ide> QUnit.skip("log which view is used with a template", function() { <ide> run(App, 'advanceReadiness'); <ide> <ide> visit('/posts').then(function() { <del> equal(logs['view:application'], 1, 'expected: Should log use of default view'); <add> equal(logs['view:application'], undefined, 'expected: Should not use a view when only a template is defined'); <ide> equal(logs['view:index'], undefined, 'expected: Should not log when index is not present.'); <ide> equal(logs['view:posts'], 1, 'expected: Rendering posts with PostsView.'); <ide> }); <ide><path>packages/ember-htmlbars/lib/keywords/outlet.js <ide> */ <ide> <ide> import merge from "ember-metal/merge"; <add>import { get } from "ember-metal/property_get"; <ide> import ComponentNode from "ember-htmlbars/system/component-node"; <ide> <ide> import topLevelViewTemplate from "ember-htmlbars/templates/top-level-view"; <ide> export default { <ide> var parentView = env.view; <ide> var outletState = state.outletState; <ide> var toRender = outletState.render; <add> var namespace = env.container.lookup('application:main'); <add> var LOG_VIEW_LOOKUPS = get(namespace, 'LOG_VIEW_LOOKUPS'); <ide> <ide> var ViewClass = outletState.render.ViewClass; <ide> <ide> export default { <ide> isOutlet: true <ide> }; <ide> <add> if (LOG_VIEW_LOOKUPS && ViewClass) { <add> Ember.Logger.info("Rendering " + toRender.name + " with " + ViewClass, { fullName: 'view:' + toRender.name }); <add> } <add> <ide> var componentNode = ComponentNode.create(renderNode, env, {}, options, parentView, null, null, template); <ide> state.componentNode = componentNode; <ide>
2
PHP
PHP
apply suggestions from code review
09f79790b71d2d0588511480f4cdc3179ac98777
<ide><path>src/Cache/Engine/MemcachedEngine.php <ide> public function init(array $config = []): bool <ide> $this->_setOptions(); <ide> <ide> $serverList = $this->_Memcached->getServerList(); <del> if (count($serverList)) { <add> if ($serverList) { <ide> if ($this->_config['persistent'] !== false) { <del> $actualServers = []; <ide> foreach ($serverList as $server) { <del> $actualServers[] = $server['host'] . ':' . $server['port']; <del> } <del> unset($server); <del> sort($actualServers); <del> $configuredServers = $this->_config['servers']; <del> sort($configuredServers); <del> if ($actualServers !== $configuredServers) { <del> $message = 'Invalid cache configuration. Multiple persistent cache configurations are detected' . <del> ' with different `servers` values. `servers` values for persistent cache configurations' . <del> ' must be the same when using the same persistence id.'; <del> throw new InvalidArgumentException($message); <add> if (!in_array($server['host'] . ':' . $server['port'], $this->_config['server'], true)) { <add> throw new InvalidArgumentException( <add> 'Invalid cache configuration. Multiple persistent cache configurations are detected' . <add> ' with different `servers` values. `servers` values for persistent cache configurations' . <add> ' must be the same when using the same persistence id.' <add> ); <add> } <ide> } <ide> } <ide>
1
PHP
PHP
fix ticket #825. related with session set to cache
66de46cd5b8bc9d144b4389211585c2aa56fc512
<ide><path>cake/libs/cache.php <ide> function settings($name = null) { <ide> } <ide> return array(); <ide> } <add> <add> function __destruct() { <add> if (Configure::read('Session.save') == 'cache' && function_exists('session_write_close')) { <add> session_write_close(); <add> } <add> } <ide> } <ide> <ide> /**
1
Javascript
Javascript
use const to define constants
804e7aa9ab0b34fa88709ef0980b960abca5e059
<ide><path>lib/_debug_agent.js <ide> 'use strict'; <ide> <del>var assert = require('assert'); <del>var net = require('net'); <del>var util = require('util'); <del>var Buffer = require('buffer').Buffer; <del> <del>var Transform = require('stream').Transform; <add>const assert = require('assert'); <add>const net = require('net'); <add>const util = require('util'); <add>const Buffer = require('buffer').Buffer; <add>const Transform = require('stream').Transform; <ide> <ide> exports.start = function start() { <ide> var agent = new Agent(); <ide> <ide> // Do not let `agent.listen()` request listening from cluster master <del> var cluster = require('cluster'); <add> const cluster = require('cluster'); <ide> cluster.isWorker = false; <ide> cluster.isMaster = true; <ide> <ide><path>lib/_debugger.js <ide> 'use strict'; <ide> <del>var util = require('util'), <del> path = require('path'), <del> net = require('net'), <del> vm = require('vm'), <del> module = require('module'), <del> repl = module.requireRepl(), <del> inherits = util.inherits, <del> assert = require('assert'), <del> spawn = require('child_process').spawn; <add>const util = require('util'); <add>const path = require('path'); <add>const net = require('net'); <add>const vm = require('vm'); <add>const module = require('module'); <add>const repl = module.requireRepl(); <add>const inherits = util.inherits; <add>const assert = require('assert'); <add>const spawn = require('child_process').spawn; <ide> <ide> exports.start = function(argv, stdin, stdout) { <ide> argv || (argv = process.argv.slice(2)); <ide> Protocol.prototype.serialize = function(req) { <ide> }; <ide> <ide> <del>var NO_FRAME = -1; <add>const NO_FRAME = -1; <ide> <ide> function Client() { <ide> net.Stream.call(this); <ide> Client.prototype._addHandle = function(desc) { <ide> }; <ide> <ide> <del>var natives = process.binding('natives'); <add>const natives = process.binding('natives'); <ide> <ide> <ide> Client.prototype._addScript = function(desc) { <ide> Client.prototype.fullTrace = function(cb) { <ide> <ide> <ide> <del>var commands = [ <add>const commands = [ <ide> [ <ide> 'run (r)', <ide> 'cont (c)', <ide> function Interface(stdin, stdout, args) { <ide> process.once('SIGTERM', process.exit.bind(process, 0)); <ide> process.once('SIGHUP', process.exit.bind(process, 0)); <ide> <del> var proto = Interface.prototype, <del> ignored = ['pause', 'resume', 'exitRepl', 'handleBreak', <del> 'requireConnection', 'killChild', 'trySpawn', <del> 'controlEval', 'debugEval', 'print', 'childPrint', <del> 'clearline'], <del> shortcut = { <del> 'run': 'r', <del> 'cont': 'c', <del> 'next': 'n', <del> 'step': 's', <del> 'out': 'o', <del> 'backtrace': 'bt', <del> 'setBreakpoint': 'sb', <del> 'clearBreakpoint': 'cb', <del> 'pause_': 'pause' <del> }; <add> var proto = Interface.prototype; <add> const ignored = ['pause', 'resume', 'exitRepl', 'handleBreak', <add> 'requireConnection', 'killChild', 'trySpawn', <add> 'controlEval', 'debugEval', 'print', 'childPrint', <add> 'clearline']; <add> const shortcut = { <add> 'run': 'r', <add> 'cont': 'c', <add> 'next': 'n', <add> 'step': 's', <add> 'out': 'o', <add> 'backtrace': 'bt', <add> 'setBreakpoint': 'sb', <add> 'clearBreakpoint': 'cb', <add> 'pause_': 'pause' <add> }; <ide> <ide> function defineProperty(key, protoKey) { <ide> // Check arity <ide><path>lib/_http_agent.js <ide> 'use strict'; <ide> <del>var net = require('net'); <del>var util = require('util'); <del>var EventEmitter = require('events').EventEmitter; <del>var debug = util.debuglog('http'); <add>const net = require('net'); <add>const util = require('util'); <add>const EventEmitter = require('events').EventEmitter; <add>const debug = util.debuglog('http'); <ide> <ide> // New Agent code. <ide> <ide><path>lib/_http_client.js <ide> 'use strict'; <ide> <del>var util = require('util'); <del>var net = require('net'); <del>var url = require('url'); <del>var EventEmitter = require('events').EventEmitter; <del>var HTTPParser = process.binding('http_parser').HTTPParser; <del>var assert = require('assert').ok; <del> <del>var common = require('_http_common'); <del> <del>var httpSocketSetup = common.httpSocketSetup; <del>var parsers = common.parsers; <del>var freeParser = common.freeParser; <del>var debug = common.debug; <del> <del>var OutgoingMessage = require('_http_outgoing').OutgoingMessage; <del> <del>var Agent = require('_http_agent'); <add>const util = require('util'); <add>const net = require('net'); <add>const url = require('url'); <add>const EventEmitter = require('events').EventEmitter; <add>const HTTPParser = process.binding('http_parser').HTTPParser; <add>const assert = require('assert').ok; <add>const common = require('_http_common'); <add>const httpSocketSetup = common.httpSocketSetup; <add>const parsers = common.parsers; <add>const freeParser = common.freeParser; <add>const debug = common.debug; <add>const OutgoingMessage = require('_http_outgoing').OutgoingMessage; <add>const Agent = require('_http_agent'); <ide> <ide> <ide> function ClientRequest(options, cb) { <ide> function ClientRequest(options, cb) { <ide> 'Expected "' + expectedProtocol + '".'); <ide> } <ide> <del> var defaultPort = options.defaultPort || self.agent && self.agent.defaultPort; <add> const defaultPort = options.defaultPort || <add> self.agent && self.agent.defaultPort; <ide> <ide> var port = options.port = options.port || defaultPort || 80; <ide> var host = options.host = options.hostname || options.host || 'localhost'; <ide><path>lib/_http_common.js <ide> 'use strict'; <ide> <del>var FreeList = require('freelist').FreeList; <del>var HTTPParser = process.binding('http_parser').HTTPParser; <add>const FreeList = require('freelist').FreeList; <add>const HTTPParser = process.binding('http_parser').HTTPParser; <ide> <del>var incoming = require('_http_incoming'); <del>var IncomingMessage = incoming.IncomingMessage; <del>var readStart = incoming.readStart; <del>var readStop = incoming.readStop; <add>const incoming = require('_http_incoming'); <add>const IncomingMessage = incoming.IncomingMessage; <add>const readStart = incoming.readStart; <add>const readStop = incoming.readStop; <ide> <del>var isNumber = require('util').isNumber; <del>var debug = require('util').debuglog('http'); <add>const isNumber = require('util').isNumber; <add>const debug = require('util').debuglog('http'); <ide> exports.debug = debug; <ide> <ide> exports.CRLF = '\r\n'; <ide> exports.chunkExpression = /chunk/i; <ide> exports.continueExpression = /100-continue/i; <ide> exports.methods = HTTPParser.methods; <ide> <del>var kOnHeaders = HTTPParser.kOnHeaders | 0; <del>var kOnHeadersComplete = HTTPParser.kOnHeadersComplete | 0; <del>var kOnBody = HTTPParser.kOnBody | 0; <del>var kOnMessageComplete = HTTPParser.kOnMessageComplete | 0; <add>const kOnHeaders = HTTPParser.kOnHeaders | 0; <add>const kOnHeadersComplete = HTTPParser.kOnHeadersComplete | 0; <add>const kOnBody = HTTPParser.kOnBody | 0; <add>const kOnMessageComplete = HTTPParser.kOnMessageComplete | 0; <ide> <ide> // Only called in the slow case where slow means <ide> // that the request headers were either fragmented <ide><path>lib/_http_incoming.js <ide> 'use strict'; <ide> <del>var util = require('util'); <del>var Stream = require('stream'); <add>const util = require('util'); <add>const Stream = require('stream'); <ide> <ide> function readStart(socket) { <ide> if (socket && !socket._paused && socket.readable) <ide><path>lib/_http_outgoing.js <ide> 'use strict'; <ide> <del>var assert = require('assert').ok; <del>var Stream = require('stream'); <del>var timers = require('timers'); <del>var util = require('util'); <del> <del>var common = require('_http_common'); <del> <del>var CRLF = common.CRLF; <del>var chunkExpression = common.chunkExpression; <del>var debug = common.debug; <del> <del> <del>var connectionExpression = /Connection/i; <del>var transferEncodingExpression = /Transfer-Encoding/i; <del>var closeExpression = /close/i; <del>var contentLengthExpression = /Content-Length/i; <del>var dateExpression = /Date/i; <del>var expectExpression = /Expect/i; <del> <del>var automaticHeaders = { <add>const assert = require('assert').ok; <add>const Stream = require('stream'); <add>const timers = require('timers'); <add>const util = require('util'); <add>const common = require('_http_common'); <add> <add>const CRLF = common.CRLF; <add>const chunkExpression = common.chunkExpression; <add>const debug = common.debug; <add> <add>const connectionExpression = /Connection/i; <add>const transferEncodingExpression = /Transfer-Encoding/i; <add>const closeExpression = /close/i; <add>const contentLengthExpression = /Content-Length/i; <add>const dateExpression = /Date/i; <add>const expectExpression = /Expect/i; <add> <add>const automaticHeaders = { <ide> connection: true, <ide> 'content-length': true, <ide> 'transfer-encoding': true, <ide> OutgoingMessage.prototype.addTrailers = function(headers) { <ide> }; <ide> <ide> <del>var crlf_buf = new Buffer('\r\n'); <add>const crlf_buf = new Buffer('\r\n'); <ide> <ide> <ide> OutgoingMessage.prototype.end = function(data, encoding, callback) { <ide><path>lib/_http_server.js <ide> 'use strict'; <ide> <del>var util = require('util'); <del>var net = require('net'); <del>var EventEmitter = require('events').EventEmitter; <del>var HTTPParser = process.binding('http_parser').HTTPParser; <del>var assert = require('assert').ok; <del> <del>var common = require('_http_common'); <del>var parsers = common.parsers; <del>var freeParser = common.freeParser; <del>var debug = common.debug; <del>var CRLF = common.CRLF; <del>var continueExpression = common.continueExpression; <del>var chunkExpression = common.chunkExpression; <del>var httpSocketSetup = common.httpSocketSetup; <del> <del>var OutgoingMessage = require('_http_outgoing').OutgoingMessage; <del> <del> <del>var STATUS_CODES = exports.STATUS_CODES = { <add>const util = require('util'); <add>const net = require('net'); <add>const EventEmitter = require('events').EventEmitter; <add>const HTTPParser = process.binding('http_parser').HTTPParser; <add>const assert = require('assert').ok; <add>const common = require('_http_common'); <add>const parsers = common.parsers; <add>const freeParser = common.freeParser; <add>const debug = common.debug; <add>const CRLF = common.CRLF; <add>const continueExpression = common.continueExpression; <add>const chunkExpression = common.chunkExpression; <add>const httpSocketSetup = common.httpSocketSetup; <add>const OutgoingMessage = require('_http_outgoing').OutgoingMessage; <add> <add>const STATUS_CODES = exports.STATUS_CODES = { <ide> 100 : 'Continue', <ide> 101 : 'Switching Protocols', <ide> 102 : 'Processing', // RFC 2518, obsoleted by RFC 4918 <ide><path>lib/_stream_duplex.js <ide> 'use strict'; <ide> <ide> module.exports = Duplex; <del>var util = require('util'); <del>var Readable = require('_stream_readable'); <del>var Writable = require('_stream_writable'); <add> <add>const util = require('util'); <add>const Readable = require('_stream_readable'); <add>const Writable = require('_stream_writable'); <ide> <ide> util.inherits(Duplex, Readable); <ide> <ide><path>lib/_stream_passthrough.js <ide> <ide> module.exports = PassThrough; <ide> <del>var Transform = require('_stream_transform'); <del>var util = require('util'); <add>const Transform = require('_stream_transform'); <add>const util = require('util'); <ide> util.inherits(PassThrough, Transform); <ide> <ide> function PassThrough(options) { <ide><path>lib/_stream_readable.js <ide> module.exports = Readable; <ide> Readable.ReadableState = ReadableState; <ide> <del>var EE = require('events').EventEmitter; <del>var Stream = require('stream'); <del>var util = require('util'); <add>const EE = require('events').EventEmitter; <add>const Stream = require('stream'); <add>const util = require('util'); <add>const debug = util.debuglog('stream'); <ide> var StringDecoder; <del>var debug = util.debuglog('stream'); <ide> <ide> util.inherits(Readable, Stream); <ide> <ide> Readable.prototype.setEncoding = function(enc) { <ide> }; <ide> <ide> // Don't raise the hwm > 128MB <del>var MAX_HWM = 0x800000; <add>const MAX_HWM = 0x800000; <ide> function roundUpToNextPowerOf2(n) { <ide> if (n >= MAX_HWM) { <ide> n = MAX_HWM; <ide> Readable.prototype.wrap = function(stream) { <ide> } <ide> <ide> // proxy certain important events. <del> var events = ['error', 'close', 'destroy', 'pause', 'resume']; <add> const events = ['error', 'close', 'destroy', 'pause', 'resume']; <ide> events.forEach(function(ev) { <ide> stream.on(ev, self.emit.bind(self, ev)); <ide> }); <ide><path>lib/_stream_transform.js <ide> <ide> module.exports = Transform; <ide> <del>var Duplex = require('_stream_duplex'); <del>var util = require('util'); <add>const Duplex = require('_stream_duplex'); <add>const util = require('util'); <ide> util.inherits(Transform, Duplex); <ide> <ide> <ide><path>lib/_stream_writable.js <ide> module.exports = Writable; <ide> Writable.WritableState = WritableState; <ide> <del>var util = require('util'); <del>var Stream = require('stream'); <del>var debug = util.debuglog('stream'); <add>const util = require('util'); <add>const Stream = require('stream'); <add>const debug = util.debuglog('stream'); <ide> <ide> util.inherits(Writable, Stream); <ide> <ide> function clearBuffer(stream, state) { <ide> <ide> Writable.prototype._write = function(chunk, encoding, cb) { <ide> cb(new Error('not implemented')); <del> <ide> }; <ide> <ide> Writable.prototype._writev = null; <ide><path>lib/_tls_common.js <ide> 'use strict'; <ide> <del>var util = require('util'); <del>var constants = require('constants'); <del>var tls = require('tls'); <add>const util = require('util'); <add>const constants = require('constants'); <add>const tls = require('tls'); <ide> <ide> // Lazily loaded <ide> var crypto = null; <ide> <del>var binding = process.binding('crypto'); <del>var NativeSecureContext = binding.SecureContext; <add>const binding = process.binding('crypto'); <add>const NativeSecureContext = binding.SecureContext; <ide> <ide> function SecureContext(secureProtocol, flags, context) { <ide> if (!(this instanceof SecureContext)) { <ide><path>lib/_tls_legacy.js <ide> 'use strict'; <ide> <del>var assert = require('assert'); <del>var events = require('events'); <del>var stream = require('stream'); <del>var tls = require('tls'); <del>var util = require('util'); <del>var common = require('_tls_common'); <del> <del>var Timer = process.binding('timer_wrap').Timer; <add>const assert = require('assert'); <add>const events = require('events'); <add>const stream = require('stream'); <add>const tls = require('tls'); <add>const util = require('util'); <add>const common = require('_tls_common'); <add>const debug = util.debuglog('tls-legacy'); <add>const Timer = process.binding('timer_wrap').Timer; <ide> var Connection = null; <ide> try { <ide> Connection = process.binding('crypto').Connection; <ide> } catch (e) { <ide> throw new Error('node.js not compiled with openssl crypto support.'); <ide> } <ide> <del>var debug = util.debuglog('tls-legacy'); <del> <ide> function SlabBuffer() { <ide> this.create(); <ide> } <ide><path>lib/_tls_wrap.js <ide> 'use strict'; <ide> <del>var assert = require('assert'); <del>var crypto = require('crypto'); <del>var net = require('net'); <del>var tls = require('tls'); <del>var util = require('util'); <del>var listenerCount = require('events').listenerCount; <del>var common = require('_tls_common'); <del> <del>var Timer = process.binding('timer_wrap').Timer; <del>var tls_wrap = process.binding('tls_wrap'); <add>const assert = require('assert'); <add>const crypto = require('crypto'); <add>const net = require('net'); <add>const tls = require('tls'); <add>const util = require('util'); <add>const listenerCount = require('events').listenerCount; <add>const common = require('_tls_common'); <add>const debug = util.debuglog('tls'); <add>const Timer = process.binding('timer_wrap').Timer; <add>const tls_wrap = process.binding('tls_wrap'); <ide> <ide> // Lazy load <ide> var tls_legacy; <ide> <del>var debug = util.debuglog('tls'); <del> <ide> function onhandshakestart() { <ide> debug('onhandshakestart'); <ide> <ide><path>lib/assert.js <ide> 'use strict'; <ide> <ide> // UTILITY <del>var util = require('util'); <del>var pSlice = Array.prototype.slice; <add>const util = require('util'); <add>const pSlice = Array.prototype.slice; <ide> <ide> // 1. The assert module provides functions that throw <ide> // AssertionError's when particular conditions are not met. The <ide> // assert module must conform to the following interface. <ide> <del>var assert = module.exports = ok; <add>const assert = module.exports = ok; <ide> <ide> // 2. The AssertionError is defined in assert. <ide> // new assert.AssertionError({ message: message, <ide><path>lib/buffer.js <ide> 'use strict'; <ide> <del>var buffer = process.binding('buffer'); <del>var smalloc = process.binding('smalloc'); <del>var util = require('util'); <del>var alloc = smalloc.alloc; <del>var truncate = smalloc.truncate; <del>var sliceOnto = smalloc.sliceOnto; <del>var kMaxLength = smalloc.kMaxLength; <add>const buffer = process.binding('buffer'); <add>const smalloc = process.binding('smalloc'); <add>const util = require('util'); <add>const alloc = smalloc.alloc; <add>const truncate = smalloc.truncate; <add>const sliceOnto = smalloc.sliceOnto; <add>const kMaxLength = smalloc.kMaxLength; <ide> var internal = {}; <ide> <ide> exports.Buffer = Buffer; <ide> Buffer.prototype.set = util.deprecate(function set(offset, v) { <ide> // TODO(trevnorris): fix these checks to follow new standard <ide> // write(string, offset = 0, length = buffer.length, encoding = 'utf8') <ide> var writeWarned = false; <del>var writeMsg = '.write(string, encoding, offset, length) is deprecated.' + <del> ' Use write(string[, offset[, length]][, encoding]) instead.'; <add>const writeMsg = '.write(string, encoding, offset, length) is deprecated.' + <add> ' Use write(string[, offset[, length]][, encoding]) instead.'; <ide> Buffer.prototype.write = function(string, offset, length, encoding) { <ide> // Buffer#write(string); <ide> if (util.isUndefined(offset)) { <ide><path>lib/child_process.js <ide> 'use strict'; <ide> <del>var StringDecoder = require('string_decoder').StringDecoder; <del>var EventEmitter = require('events').EventEmitter; <del>var net = require('net'); <del>var dgram = require('dgram'); <del>var assert = require('assert'); <del>var util = require('util'); <add>const StringDecoder = require('string_decoder').StringDecoder; <add>const EventEmitter = require('events').EventEmitter; <add>const net = require('net'); <add>const dgram = require('dgram'); <add>const assert = require('assert'); <add>const util = require('util'); <ide> <del>var Process = process.binding('process_wrap').Process; <del>var WriteWrap = process.binding('stream_wrap').WriteWrap; <del>var uv = process.binding('uv'); <add>const Process = process.binding('process_wrap').Process; <add>const WriteWrap = process.binding('stream_wrap').WriteWrap; <add>const uv = process.binding('uv'); <ide> <ide> var spawn_sync; // Lazy-loaded process.binding('spawn_sync') <ide> var constants; // Lazy-loaded process.binding('constants') <ide> <del>var errnoException = util._errnoException; <add>const errnoException = util._errnoException; <ide> var handleWraps = {}; <ide> <ide> function handleWrapGetter(name, callback) { <ide> function createSocket(pipe, readable) { <ide> <ide> // this object contain function to convert TCP objects to native handle objects <ide> // and back again. <del>var handleConversion = { <add>const handleConversion = { <ide> 'net.Native': { <ide> simultaneousAccepts: true, <ide> <ide> function getSocketList(type, slave, key) { <ide> return socketList; <ide> } <ide> <del>var INTERNAL_PREFIX = 'NODE_'; <add>const INTERNAL_PREFIX = 'NODE_'; <ide> function handleMessage(target, message, handle) { <ide> var eventName = 'message'; <ide> if (!util.isNull(message) && <ide><path>lib/cluster.js <ide> 'use strict'; <ide> <del>var EventEmitter = require('events').EventEmitter; <del>var assert = require('assert'); <del>var dgram = require('dgram'); <del>var fork = require('child_process').fork; <del>var net = require('net'); <del>var util = require('util'); <del>var SCHED_NONE = 1; <del>var SCHED_RR = 2; <del> <del>var cluster = new EventEmitter; <add>const EventEmitter = require('events').EventEmitter; <add>const assert = require('assert'); <add>const dgram = require('dgram'); <add>const fork = require('child_process').fork; <add>const net = require('net'); <add>const util = require('util'); <add>const SCHED_NONE = 1; <add>const SCHED_RR = 2; <add> <add>const cluster = new EventEmitter; <ide> module.exports = cluster; <ide> cluster.Worker = Worker; <ide> cluster.isWorker = ('NODE_UNIQUE_ID' in process.env); <ide> function masterInit() { <ide> <ide> cluster.fork = function(env) { <ide> cluster.setupMaster(); <del> var id = ++ids; <del> var workerProcess = createWorkerProcess(id, env); <del> var worker = new Worker({ <add> const id = ++ids; <add> const workerProcess = createWorkerProcess(id, env); <add> const worker = new Worker({ <ide> id: id, <ide> process: workerProcess <ide> }); <ide><path>lib/console.js <ide> 'use strict'; <ide> <del>var util = require('util'); <add>const util = require('util'); <ide> <ide> function Console(stdout, stderr) { <ide> if (!(this instanceof Console)) { <ide><path>lib/crypto.js <ide> try { <ide> throw new Error('node.js not compiled with openssl crypto support.'); <ide> } <ide> <del>var constants = require('constants'); <del>var stream = require('stream'); <del>var util = require('util'); <add>const constants = require('constants'); <add>const stream = require('stream'); <add>const util = require('util'); <ide> <del>var DH_GENERATOR = 2; <add>const DH_GENERATOR = 2; <ide> <ide> // This is here because many functions accepted binary strings without <ide> // any explicit encoding in older versions of node, and we don't want <ide> function toBuf(str, encoding) { <ide> exports._toBuf = toBuf; <ide> <ide> <del>var assert = require('assert'); <del>var StringDecoder = require('string_decoder').StringDecoder; <add>const assert = require('assert'); <add>const StringDecoder = require('string_decoder').StringDecoder; <ide> <ide> <ide> function LazyTransform(options) { <ide><path>lib/dgram.js <ide> 'use strict'; <ide> <del>var assert = require('assert'); <del>var util = require('util'); <del>var events = require('events'); <del>var constants = require('constants'); <add>const assert = require('assert'); <add>const util = require('util'); <add>const events = require('events'); <add>const constants = require('constants'); <ide> <del>var UDP = process.binding('udp_wrap').UDP; <del>var SendWrap = process.binding('udp_wrap').SendWrap; <add>const UDP = process.binding('udp_wrap').UDP; <add>const SendWrap = process.binding('udp_wrap').SendWrap; <ide> <del>var BIND_STATE_UNBOUND = 0; <del>var BIND_STATE_BINDING = 1; <del>var BIND_STATE_BOUND = 2; <add>const BIND_STATE_UNBOUND = 0; <add>const BIND_STATE_BINDING = 1; <add>const BIND_STATE_BOUND = 2; <ide> <ide> // lazily loaded <ide> var cluster = null; <ide> var dns = null; <ide> <del>var errnoException = util._errnoException; <del>var exceptionWithHostPort = util._exceptionWithHostPort; <add>const errnoException = util._errnoException; <add>const exceptionWithHostPort = util._exceptionWithHostPort; <ide> <ide> function lookup(address, family, callback) { <ide> if (!dns) <ide> Socket.prototype.bind = function(port /*, address, callback*/) { <ide> if (util.isFunction(arguments[arguments.length - 1])) <ide> self.once('listening', arguments[arguments.length - 1]); <ide> <del> var UDP = process.binding('udp_wrap').UDP; <add> const UDP = process.binding('udp_wrap').UDP; <ide> if (port instanceof UDP) { <ide> replaceHandle(self, port); <ide> startListening(self); <ide><path>lib/dns.js <ide> 'use strict'; <ide> <del>var net = require('net'); <del>var util = require('util'); <add>const net = require('net'); <add>const util = require('util'); <ide> <del>var cares = process.binding('cares_wrap'); <del>var uv = process.binding('uv'); <add>const cares = process.binding('cares_wrap'); <add>const uv = process.binding('uv'); <ide> <del>var GetAddrInfoReqWrap = cares.GetAddrInfoReqWrap; <del>var GetNameInfoReqWrap = cares.GetNameInfoReqWrap; <add>const GetAddrInfoReqWrap = cares.GetAddrInfoReqWrap; <add>const GetNameInfoReqWrap = cares.GetNameInfoReqWrap; <ide> <del>var isIp = net.isIP; <add>const isIp = net.isIP; <ide> <ide> <ide> function errnoException(err, syscall, hostname) { <ide><path>lib/domain.js <ide> // No new pull requests targeting this module will be accepted <ide> // unless they address existing, critical bugs. <ide> <del>var util = require('util'); <del>var EventEmitter = require('events'); <del>var inherits = util.inherits; <add>const util = require('util'); <add>const EventEmitter = require('events'); <add>const inherits = util.inherits; <ide> <ide> // communicate with events module, but don't require that <ide> // module to have to load this one, since this module has <ide><path>lib/events.js <ide> 'use strict'; <ide> <ide> var domain; <del>var util = require('util'); <add>const util = require('util'); <ide> <ide> function EventEmitter() { <ide> EventEmitter.init.call(this); <ide><path>lib/fs.js <ide> <ide> 'use strict'; <ide> <del>var util = require('util'); <del>var pathModule = require('path'); <add>const util = require('util'); <add>const pathModule = require('path'); <ide> <del>var binding = process.binding('fs'); <del>var constants = process.binding('constants'); <del>var fs = exports; <del>var Stream = require('stream').Stream; <del>var EventEmitter = require('events').EventEmitter; <del>var FSReqWrap = binding.FSReqWrap; <add>const binding = process.binding('fs'); <add>const constants = process.binding('constants'); <add>const fs = exports; <add>const Stream = require('stream').Stream; <add>const EventEmitter = require('events').EventEmitter; <add>const FSReqWrap = binding.FSReqWrap; <ide> <del>var Readable = Stream.Readable; <del>var Writable = Stream.Writable; <add>const Readable = Stream.Readable; <add>const Writable = Stream.Writable; <ide> <ide> const kMinPoolSpace = 128; <ide> const kMaxLength = require('smalloc').kMaxLength; <ide> const R_OK = constants.R_OK || 0; <ide> const W_OK = constants.W_OK || 0; <ide> const X_OK = constants.X_OK || 0; <ide> <del>var isWindows = process.platform === 'win32'; <add>const isWindows = process.platform === 'win32'; <ide> <del>var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); <del>var errnoException = util._errnoException; <add>const DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); <add>const errnoException = util._errnoException; <ide> <ide> <ide> function rethrow() { <ide><path>lib/http.js <ide> 'use strict'; <ide> <del>var util = require('util'); <del>var EventEmitter = require('events').EventEmitter; <add>const util = require('util'); <add>const EventEmitter = require('events').EventEmitter; <ide> <ide> <ide> exports.IncomingMessage = require('_http_incoming').IncomingMessage; <ide> <ide> <del>var common = require('_http_common'); <add>const common = require('_http_common'); <ide> exports.METHODS = util._extend([], common.methods).sort(); <ide> <ide> <ide> exports.OutgoingMessage = require('_http_outgoing').OutgoingMessage; <ide> <ide> <del>var server = require('_http_server'); <add>const server = require('_http_server'); <ide> exports.ServerResponse = server.ServerResponse; <ide> exports.STATUS_CODES = server.STATUS_CODES; <ide> <ide> <del>var agent = require('_http_agent'); <del>var Agent = exports.Agent = agent.Agent; <add>const agent = require('_http_agent'); <add>const Agent = exports.Agent = agent.Agent; <ide> exports.globalAgent = agent.globalAgent; <ide> <del>var client = require('_http_client'); <del>var ClientRequest = exports.ClientRequest = client.ClientRequest; <add>const client = require('_http_client'); <add>const ClientRequest = exports.ClientRequest = client.ClientRequest; <ide> <ide> exports.request = function(options, cb) { <ide> return new ClientRequest(options, cb); <ide> exports.get = function(options, cb) { <ide> }; <ide> <ide> exports._connectionListener = server._connectionListener; <del>var Server = exports.Server = server.Server; <add>const Server = exports.Server = server.Server; <ide> <ide> exports.createServer = function(requestListener) { <ide> return new Server(requestListener); <ide><path>lib/https.js <ide> 'use strict'; <ide> <del>var tls = require('tls'); <del>var url = require('url'); <del>var http = require('http'); <del>var util = require('util'); <del>var inherits = require('util').inherits; <del>var debug = util.debuglog('https'); <add>const tls = require('tls'); <add>const url = require('url'); <add>const http = require('http'); <add>const util = require('util'); <add>const inherits = require('util').inherits; <add>const debug = util.debuglog('https'); <ide> <ide> function Server(opts, requestListener) { <ide> if (!(this instanceof Server)) return new Server(opts, requestListener); <ide> Agent.prototype.getName = function(options) { <ide> return name; <ide> }; <ide> <del>var globalAgent = new Agent(); <add>const globalAgent = new Agent(); <ide> <ide> exports.globalAgent = globalAgent; <ide> exports.Agent = Agent; <ide><path>lib/module.js <ide> 'use strict'; <ide> <del>var NativeModule = require('native_module'); <del>var util = NativeModule.require('util'); <del>var runInThisContext = require('vm').runInThisContext; <del>var runInNewContext = require('vm').runInNewContext; <del>var assert = require('assert').ok; <del>var fs = NativeModule.require('fs'); <add>const NativeModule = require('native_module'); <add>const util = NativeModule.require('util'); <add>const runInThisContext = require('vm').runInThisContext; <add>const runInNewContext = require('vm').runInNewContext; <add>const assert = require('assert').ok; <add>const fs = NativeModule.require('fs'); <ide> <ide> <ide> // If obj.hasOwnProperty has been overridden, then calling <ide> Module.globalPaths = []; <ide> Module.wrapper = NativeModule.wrapper; <ide> Module.wrap = NativeModule.wrap; <ide> <del>var path = NativeModule.require('path'); <add>const path = NativeModule.require('path'); <ide> <ide> Module._debug = util.debuglog('module'); <ide> <ide> <ide> // We use this alias for the preprocessor that filters it out <del>var debug = Module._debug; <add>const debug = Module._debug; <ide> <ide> <ide> // given a module name, and a list of paths to test, returns the first <ide> function statPath(path) { <ide> } <ide> <ide> // check if the directory is a package.json dir <del>var packageMainCache = {}; <add>const packageMainCache = {}; <ide> <ide> function readPackage(requestPath) { <ide> if (hasOwnProperty(packageMainCache, requestPath)) { <ide> Module.runMain = function() { <ide> }; <ide> <ide> Module._initPaths = function() { <del> var isWindows = process.platform === 'win32'; <add> const isWindows = process.platform === 'win32'; <ide> <ide> if (isWindows) { <ide> var homeDir = process.env.USERPROFILE; <ide><path>lib/net.js <ide> 'use strict'; <ide> <del>var events = require('events'); <del>var stream = require('stream'); <del>var timers = require('timers'); <del>var util = require('util'); <del>var assert = require('assert'); <del>var cares = process.binding('cares_wrap'); <del>var uv = process.binding('uv'); <del>var Pipe = process.binding('pipe_wrap').Pipe; <add>const events = require('events'); <add>const stream = require('stream'); <add>const timers = require('timers'); <add>const util = require('util'); <add>const assert = require('assert'); <add>const cares = process.binding('cares_wrap'); <add>const uv = process.binding('uv'); <add>const Pipe = process.binding('pipe_wrap').Pipe; <ide> <del>var TCPConnectWrap = process.binding('tcp_wrap').TCPConnectWrap; <del>var PipeConnectWrap = process.binding('pipe_wrap').PipeConnectWrap; <del>var ShutdownWrap = process.binding('stream_wrap').ShutdownWrap; <del>var WriteWrap = process.binding('stream_wrap').WriteWrap; <add>const TCPConnectWrap = process.binding('tcp_wrap').TCPConnectWrap; <add>const PipeConnectWrap = process.binding('pipe_wrap').PipeConnectWrap; <add>const ShutdownWrap = process.binding('stream_wrap').ShutdownWrap; <add>const WriteWrap = process.binding('stream_wrap').WriteWrap; <ide> <ide> <ide> var cluster; <del>var errnoException = util._errnoException; <del>var exceptionWithHostPort = util._exceptionWithHostPort; <add>const errnoException = util._errnoException; <add>const exceptionWithHostPort = util._exceptionWithHostPort; <ide> <ide> function noop() {} <ide> <ide> function createHandle(fd) { <ide> } <ide> <ide> <del>var debug = util.debuglog('net'); <add>const debug = util.debuglog('net'); <ide> <ide> function isPipeName(s) { <ide> return util.isString(s) && toNumber(s) === false; <ide> Socket.prototype.connect = function(options, cb) { <ide> connect(self, options.path); <ide> <ide> } else { <del> var dns = require('dns'); <add> const dns = require('dns'); <ide> var host = options.host || 'localhost'; <ide> var port = options.port | 0; <ide> var localAddress = options.localAddress; <ide> Server.prototype.listen = function() { <ide> // When the ip is omitted it can be the second argument. <ide> var backlog = toNumber(arguments[1]) || toNumber(arguments[2]); <ide> <del> var TCP = process.binding('tcp_wrap').TCP; <add> const TCP = process.binding('tcp_wrap').TCP; <ide> <ide> if (arguments.length === 0 || util.isFunction(arguments[0])) { <ide> // Bind to a random port. <ide><path>lib/os.js <ide> 'use strict'; <ide> <del>var binding = process.binding('os'); <del>var util = require('util'); <del>var isWindows = process.platform === 'win32'; <add>const binding = process.binding('os'); <add>const util = require('util'); <add>const isWindows = process.platform === 'win32'; <ide> <ide> exports.hostname = binding.getHostname; <ide> exports.loadavg = binding.getLoadAvg; <ide><path>lib/path.js <ide> 'use strict'; <ide> <del>var isWindows = process.platform === 'win32'; <del>var util = require('util'); <add>const isWindows = process.platform === 'win32'; <add>const util = require('util'); <ide> <ide> <ide> // resolves . and .. elements in a path array with directory names there <ide> function normalizeArray(parts, allowAboveRoot) { <ide> <ide> // Regex to split a windows path into three parts: [*, device, slash, <ide> // tail] windows-only <del>var splitDeviceRe = <add>const splitDeviceRe = <ide> /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; <ide> <ide> // Regex to split the tail part of the above into [*, dir, basename, ext] <del>var splitTailRe = <add>const splitTailRe = <ide> /^([\s\S]*?)((?:\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))(?:[\\\/]*)$/; <ide> <ide> var win32 = {}; <ide> win32.delimiter = ';'; <ide> <ide> // Split a filename into [root, dir, basename, ext], unix version <ide> // 'root' is just a slash, or nothing. <del>var splitPathRe = <add>const splitPathRe = <ide> /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; <ide> var posix = {}; <ide> <ide><path>lib/querystring.js <ide> <ide> 'use strict'; <ide> <del>var QueryString = exports; <del>var util = require('util'); <add>const QueryString = exports; <add>const util = require('util'); <ide> <ide> <ide> // If obj.hasOwnProperty has been overridden, then calling <ide><path>lib/readline.js <ide> <ide> 'use strict'; <ide> <del>var kHistorySize = 30; <add>const kHistorySize = 30; <ide> <del>var util = require('util'); <del>var inherits = require('util').inherits; <del>var EventEmitter = require('events').EventEmitter; <add>const util = require('util'); <add>const inherits = util.inherits; <add>const EventEmitter = require('events').EventEmitter; <ide> <ide> <ide> exports.createInterface = function(input, output, completer, terminal) { <ide> Interface.prototype.write = function(d, key) { <ide> }; <ide> <ide> // \r\n, \n, or \r followed by something other than \n <del>var lineEnding = /\r?\n|\r(?!\n)/; <add>const lineEnding = /\r?\n|\r(?!\n)/; <ide> Interface.prototype._normalWrite = function(b) { <ide> if (util.isUndefined(b)) { <ide> return; <ide> exports.emitKeypressEvents = emitKeypressEvents; <ide> */ <ide> <ide> // Regexes used for ansi escape code splitting <del>var metaKeyCodeReAnywhere = /(?:\x1b)([a-zA-Z0-9])/; <del>var metaKeyCodeRe = new RegExp('^' + metaKeyCodeReAnywhere.source + '$'); <del>var functionKeyCodeReAnywhere = new RegExp('(?:\x1b+)(O|N|\\[|\\[\\[)(?:' + [ <add>const metaKeyCodeReAnywhere = /(?:\x1b)([a-zA-Z0-9])/; <add>const metaKeyCodeRe = new RegExp('^' + metaKeyCodeReAnywhere.source + '$'); <add>const functionKeyCodeReAnywhere = new RegExp('(?:\x1b+)(O|N|\\[|\\[\\[)(?:' + [ <ide> '(\\d+)(?:;(\\d+))?([~^$])', <ide> '(?:M([@ #!a`])(.)(.))', // mouse <ide> '(?:1;)?(\\d+)?([a-zA-Z])' <ide> ].join('|') + ')'); <del>var functionKeyCodeRe = new RegExp('^' + functionKeyCodeReAnywhere.source); <del>var escapeCodeReAnywhere = new RegExp([ <add>const functionKeyCodeRe = new RegExp('^' + functionKeyCodeReAnywhere.source); <add>const escapeCodeReAnywhere = new RegExp([ <ide> functionKeyCodeReAnywhere.source, metaKeyCodeReAnywhere.source, /\x1b./.source <ide> ].join('|')); <ide> <ide><path>lib/repl.js <ide> <ide> 'use strict'; <ide> <del>var util = require('util'); <del>var inherits = require('util').inherits; <del>var Stream = require('stream'); <del>var vm = require('vm'); <del>var path = require('path'); <del>var fs = require('fs'); <del>var rl = require('readline'); <del>var Console = require('console').Console; <del>var domain = require('domain'); <del>var debug = util.debuglog('repl'); <add>const util = require('util'); <add>const inherits = util.inherits; <add>const Stream = require('stream'); <add>const vm = require('vm'); <add>const path = require('path'); <add>const fs = require('fs'); <add>const rl = require('readline'); <add>const Console = require('console').Console; <add>const domain = require('domain'); <add>const debug = util.debuglog('repl'); <ide> <ide> // If obj.hasOwnProperty has been overridden, then calling <ide> // obj.hasOwnProperty(prop) will break. <ide> ArrayStream.prototype.writable = true; <ide> ArrayStream.prototype.resume = function() {}; <ide> ArrayStream.prototype.write = function() {}; <ide> <del>var requireRE = /\brequire\s*\(['"](([\w\.\/-]+\/)?([\w\.\/-]*))/; <del>var simpleExpressionRE = <add>const requireRE = /\brequire\s*\(['"](([\w\.\/-]+\/)?([\w\.\/-]*))/; <add>const simpleExpressionRE = <ide> /(([a-zA-Z_$](?:\w|\$)*)\.)*([a-zA-Z_$](?:\w|\$)*)\.?$/; <ide> <ide> <ide> function defineDefaultCommands(repl) { <ide> <ide> <ide> function trimWhitespace(cmd) { <del> var trimmer = /^\s*(.+)\s*$/m, <del> matches = trimmer.exec(cmd); <add> const trimmer = /^\s*(.+)\s*$/m; <add> var matches = trimmer.exec(cmd); <ide> <ide> if (matches && matches.length === 2) { <ide> return matches[1]; <ide> function regexpEscape(s) { <ide> * @return {String} The converted command. <ide> */ <ide> REPLServer.prototype.convertToContext = function(cmd) { <del> var self = this, matches, <del> scopeVar = /^\s*var\s*([_\w\$]+)(.*)$/m, <del> scopeFunc = /^\s*function\s*([_\w\$]+)/; <add> const scopeVar = /^\s*var\s*([_\w\$]+)(.*)$/m; <add> const scopeFunc = /^\s*function\s*([_\w\$]+)/; <add> var self = this, matches; <ide> <ide> // Replaces: var foo = "bar"; with: self.context.foo = bar; <ide> matches = scopeVar.exec(cmd); <ide><path>lib/smalloc.js <ide> 'use strict'; <ide> <del>var smalloc = process.binding('smalloc'); <del>var kMaxLength = smalloc.kMaxLength; <del>var util = require('util'); <add>const smalloc = process.binding('smalloc'); <add>const kMaxLength = smalloc.kMaxLength; <add>const util = require('util'); <ide> <ide> exports.alloc = alloc; <ide> exports.copyOnto = smalloc.copyOnto; <ide><path>lib/stream.js <ide> <ide> module.exports = Stream; <ide> <del>var EE = require('events').EventEmitter; <del>var util = require('util'); <add>const EE = require('events').EventEmitter; <add>const util = require('util'); <ide> <ide> util.inherits(Stream, EE); <ide> Stream.Readable = require('_stream_readable'); <ide><path>lib/string_decoder.js <ide> function assertEncoding(encoding) { <ide> // to reason about this code, so it should be split up in the future. <ide> // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code <ide> // points as used by CESU-8. <del>var StringDecoder = exports.StringDecoder = function(encoding) { <add>const StringDecoder = exports.StringDecoder = function(encoding) { <ide> this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); <ide> assertEncoding(encoding); <ide> switch (this.encoding) { <ide><path>lib/sys.js <ide> 'use strict'; <ide> <del>var util = require('util'); <add>const util = require('util'); <ide> <ide> // the sys module was renamed to 'util'. <ide> // this shim remains to keep old programs working. <ide> // sys is deprecated and shouldn't be used <ide> <del>var setExports = util.deprecate(function() { <add>const setExports = util.deprecate(function() { <ide> module.exports = util; <ide> }, 'sys is deprecated. Use util instead.'); <ide> <ide><path>lib/timers.js <ide> 'use strict'; <ide> <del>var Timer = process.binding('timer_wrap').Timer; <del>var L = require('_linklist'); <del>var assert = require('assert').ok; <add>const Timer = process.binding('timer_wrap').Timer; <add>const L = require('_linklist'); <add>const assert = require('assert').ok; <ide> <del>var kOnTimeout = Timer.kOnTimeout | 0; <add>const kOnTimeout = Timer.kOnTimeout | 0; <ide> <ide> // Timeout values > TIMEOUT_MAX are set to 1. <del>var TIMEOUT_MAX = 2147483647; // 2^31-1 <add>const TIMEOUT_MAX = 2147483647; // 2^31-1 <ide> <del>var debug = require('util').debuglog('timer'); <add>const debug = require('util').debuglog('timer'); <ide> <ide> <ide> // IDLE TIMEOUTS <ide> function listOnTimeout() { <ide> } <ide> <ide> <del>var unenroll = exports.unenroll = function(item) { <add>const unenroll = exports.unenroll = function(item) { <ide> L.remove(item); <ide> <ide> var list = lists[item._idleTimeout]; <ide> exports.clearInterval = function(timer) { <ide> }; <ide> <ide> <del>var Timeout = function(after) { <add>const Timeout = function(after) { <ide> this._idleTimeout = after; <ide> this._idlePrev = this; <ide> this._idleNext = this; <ide><path>lib/tls.js <ide> 'use strict'; <ide> <del>var net = require('net'); <del>var url = require('url'); <del>var util = require('util'); <add>const net = require('net'); <add>const url = require('url'); <add>const util = require('util'); <ide> <ide> // Allow {CLIENT_RENEG_LIMIT} client-initiated session renegotiations <ide> // every {CLIENT_RENEG_WINDOW} seconds. An error event is emitted if more <ide> exports.DEFAULT_CIPHERS = <ide> exports.DEFAULT_ECDH_CURVE = 'prime256v1'; <ide> <ide> exports.getCiphers = function() { <del> var names = process.binding('crypto').getSSLCiphers(); <add> const names = process.binding('crypto').getSSLCiphers(); <ide> // Drop all-caps names in favor of their lowercase aliases, <ide> var ctx = {}; <ide> names.forEach(function(name) { <ide><path>lib/tty.js <ide> 'use strict'; <ide> <del>var inherits = require('util').inherits; <del>var net = require('net'); <del>var TTY = process.binding('tty_wrap').TTY; <del>var isTTY = process.binding('tty_wrap').isTTY; <del>var util = require('util'); <add>const inherits = require('util').inherits; <add>const net = require('net'); <add>const TTY = process.binding('tty_wrap').TTY; <add>const isTTY = process.binding('tty_wrap').isTTY; <add>const util = require('util'); <ide> <del>var errnoException = util._errnoException; <add>const errnoException = util._errnoException; <ide> <ide> <ide> exports.isatty = function(fd) { <ide><path>lib/url.js <ide> 'use strict'; <ide> <del>var punycode = require('punycode'); <del>var util = require('util'); <add>const punycode = require('punycode'); <add>const util = require('util'); <ide> <ide> exports.parse = urlParse; <ide> exports.resolve = urlResolve; <ide> function Url() { <ide> <ide> // define these here so at least they only have to be <ide> // compiled once on the first module load. <del>var protocolPattern = /^([a-z0-9.+-]+:)/i, <del> portPattern = /:[0-9]*$/, <del> <del> // Special case for a simple path URL <del> simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, <del> <del> // RFC 2396: characters reserved for delimiting URLs. <del> // We actually just auto-escape these. <del> delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], <del> <del> // RFC 2396: characters not allowed for various reasons. <del> unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), <del> <del> // Allowed by RFCs, but cause of XSS attacks. Always escape these. <del> autoEscape = ['\''].concat(unwise), <del> // Characters that are never ever allowed in a hostname. <del> // Note that any invalid chars are also handled, but these <del> // are the ones that are *expected* to be seen, so we fast-path <del> // them. <del> nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), <del> hostEndingChars = ['/', '?', '#'], <del> hostnameMaxLen = 255, <del> hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, <del> hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, <del> // protocols that can allow "unsafe" and "unwise" chars. <del> unsafeProtocol = { <del> 'javascript': true, <del> 'javascript:': true <del> }, <del> // protocols that never have a hostname. <del> hostlessProtocol = { <del> 'javascript': true, <del> 'javascript:': true <del> }, <del> // protocols that always contain a // bit. <del> slashedProtocol = { <del> 'http': true, <del> 'https': true, <del> 'ftp': true, <del> 'gopher': true, <del> 'file': true, <del> 'http:': true, <del> 'https:': true, <del> 'ftp:': true, <del> 'gopher:': true, <del> 'file:': true <del> }, <del> querystring = require('querystring'); <add>const protocolPattern = /^([a-z0-9.+-]+:)/i; <add>const portPattern = /:[0-9]*$/; <add> <add>// Special case for a simple path URL <add>const simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/; <add> <add>// RFC 2396: characters reserved for delimiting URLs. <add>// We actually just auto-escape these. <add>const delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t']; <add> <add>// RFC 2396: characters not allowed for various reasons. <add>const unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims); <add> <add>// Allowed by RFCs, but cause of XSS attacks. Always escape these. <add>const autoEscape = ['\''].concat(unwise); <add> <add>// Characters that are never ever allowed in a hostname. <add>// Note that any invalid chars are also handled, but these <add>// are the ones that are *expected* to be seen, so we fast-path them. <add>const nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape); <add>const hostEndingChars = ['/', '?', '#']; <add>const hostnameMaxLen = 255; <add>const hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/; <add>const hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/; <add>// protocols that can allow "unsafe" and "unwise" chars. <add>const unsafeProtocol = { <add> 'javascript': true, <add> 'javascript:': true <add>}; <add>// protocols that never have a hostname. <add>const hostlessProtocol = { <add> 'javascript': true, <add> 'javascript:': true <add>}; <add>// protocols that always contain a // bit. <add>const slashedProtocol = { <add> 'http': true, <add> 'https': true, <add> 'ftp': true, <add> 'gopher': true, <add> 'file': true, <add> 'http:': true, <add> 'https:': true, <add> 'ftp:': true, <add> 'gopher:': true, <add> 'file:': true <add>}; <add>const querystring = require('querystring'); <ide> <ide> function urlParse(url, parseQueryString, slashesDenoteHost) { <ide> if (url && util.isObject(url) && url instanceof Url) return url; <ide><path>lib/util.js <ide> 'use strict'; <ide> <del>var formatRegExp = /%[sdj%]/g; <add>const formatRegExp = /%[sdj%]/g; <ide> exports.format = function(f) { <ide> if (!isString(f)) { <ide> var objects = []; <ide> function reduceToSingleString(output, base, braces) { <ide> <ide> // NOTE: These type checking functions intentionally don't use `instanceof` <ide> // because it is fragile and can be easily faked with `Object.create()`. <del>var isArray = exports.isArray = Array.isArray; <add>const isArray = exports.isArray = Array.isArray; <ide> <ide> function isBoolean(arg) { <ide> return typeof arg === 'boolean'; <ide> function pad(n) { <ide> } <ide> <ide> <del>var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', <del> 'Oct', 'Nov', 'Dec']; <add>const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', <add> 'Oct', 'Nov', 'Dec']; <ide> <ide> // 26 Feb 16:19:34 <ide> function timestamp() { <ide><path>lib/v8.js <ide> <ide> 'use strict'; <ide> <del>var v8binding = process.binding('v8'); <del>var smalloc = require('smalloc'); <del> <del>var heapStatisticsBuffer = smalloc.alloc(v8binding.kHeapStatisticsBufferLength, <del> v8binding.kHeapStatisticsBufferType); <del> <del>var kTotalHeapSizeIndex = v8binding.kTotalHeapSizeIndex; <del>var kTotalHeapSizeExecutableIndex = v8binding.kTotalHeapSizeExecutableIndex; <del>var kTotalPhysicalSizeIndex = v8binding.kTotalPhysicalSizeIndex; <del>var kUsedHeapSizeIndex = v8binding.kUsedHeapSizeIndex; <del>var kHeapSizeLimitIndex = v8binding.kHeapSizeLimitIndex; <add>const v8binding = process.binding('v8'); <add>const smalloc = require('smalloc'); <add> <add>const heapStatisticsBuffer = <add> smalloc.alloc(v8binding.kHeapStatisticsBufferLength, <add> v8binding.kHeapStatisticsBufferType); <add> <add>const kTotalHeapSizeIndex = v8binding.kTotalHeapSizeIndex; <add>const kTotalHeapSizeExecutableIndex = v8binding.kTotalHeapSizeExecutableIndex; <add>const kTotalPhysicalSizeIndex = v8binding.kTotalPhysicalSizeIndex; <add>const kUsedHeapSizeIndex = v8binding.kUsedHeapSizeIndex; <add>const kHeapSizeLimitIndex = v8binding.kHeapSizeLimitIndex; <ide> <ide> exports.getHeapStatistics = function() { <ide> var buffer = heapStatisticsBuffer; <ide><path>lib/vm.js <ide> 'use strict'; <ide> <del>var binding = process.binding('contextify'); <del>var Script = binding.ContextifyScript; <del>var util = require('util'); <add>const binding = process.binding('contextify'); <add>const Script = binding.ContextifyScript; <add>const util = require('util'); <ide> <ide> // The binding provides a few useful primitives: <ide> // - ContextifyScript(code, { filename = "evalmachine.anonymous", <ide><path>lib/zlib.js <ide> 'use strict'; <ide> <del>var Transform = require('_stream_transform'); <del> <del>var binding = process.binding('zlib'); <del>var util = require('util'); <del>var assert = require('assert').ok; <add>const Transform = require('_stream_transform'); <add>const binding = process.binding('zlib'); <add>const util = require('util'); <add>const assert = require('assert').ok; <ide> <ide> // zlib doesn't provide these, so kludge them in following the same <ide> // const naming scheme zlib uses. <ide> binding.Z_MAX_LEVEL = 9; <ide> binding.Z_DEFAULT_LEVEL = binding.Z_DEFAULT_COMPRESSION; <ide> <ide> // expose all the zlib constants <del>var bkeys = Object.keys(binding); <add>const bkeys = Object.keys(binding); <ide> for (var bk = 0; bk < bkeys.length; bk++) { <ide> var bkey = bkeys[bk]; <ide> if (bkey.match(/^Z/)) exports[bkey] = binding[bkey]; <ide> exports.codes = { <ide> Z_VERSION_ERROR: binding.Z_VERSION_ERROR <ide> }; <ide> <del>var ckeys = Object.keys(exports.codes); <add>const ckeys = Object.keys(exports.codes); <ide> for (var ck = 0; ck < ckeys.length; ck++) { <ide> var ckey = ckeys[ck]; <ide> exports.codes[exports.codes[ckey]] = ckey;
48
Python
Python
improve error messages in data validation checks
b2f0dd4cb2eba673c25742c87d78b895af1a9c53
<ide><path>keras/engine/training.py <ide> def _standardize_input_data(data, names, shapes=None, <ide> # Raises <ide> ValueError: in case of improperly formatted user-provided data. <ide> """ <add> if not names: <add> return [] <ide> if data is None: <ide> return [None for _ in range(len(names))] <ide> if isinstance(data, dict): <ide> def _standardize_input_data(data, names, shapes=None, <ide> elif isinstance(data, list): <ide> if len(data) != len(names): <ide> if data and hasattr(data[0], 'shape'): <del> raise ValueError('Error when checking ' + exception_prefix + <add> raise ValueError('Error when checking model ' + <add> exception_prefix + <ide> ': the list of Numpy arrays ' <ide> 'that you are passing to your model ' <ide> 'is not the size the model expected. ' <ide> def _standardize_input_data(data, names, shapes=None, <ide> data = [np.asarray(data)] <ide> else: <ide> raise ValueError( <del> 'Error when checking ' + exception_prefix + <add> 'Error when checking model ' + <add> exception_prefix + <ide> ': you are passing a list as ' <ide> 'input to your model, ' <ide> 'but the model expects ' <ide> def _standardize_input_data(data, names, shapes=None, <ide> arrays = data <ide> else: <ide> if not hasattr(data, 'shape'): <del> raise TypeError('Error when checking ' + exception_prefix + <add> raise TypeError('Error when checking model ' + <add> exception_prefix + <ide> ': data should be a Numpy array, ' <ide> 'or list/dict of Numpy arrays. ' <ide> 'Found: ' + str(data)[:200] + '...') <del> if len(names) != 1: <add> if len(names) > 1: <ide> # Case: model expects multiple inputs but only received <ide> # a single Numpy array. <ide> raise ValueError('The model expects ' + str(len(names)) + <del> ' input arrays, but only received one array. ' <add> exception_prefix + <add> ' arrays, but only received one array. ' <ide> 'Found: array with shape ' + str(data.shape)) <ide> arrays = [data] <ide> <ide> def _standardize_user_data(self, x, y, <ide> x = _standardize_input_data(x, self._feed_input_names, <ide> self._feed_input_shapes, <ide> check_batch_axis=False, <del> exception_prefix='model input') <add> exception_prefix='input') <ide> y = _standardize_input_data(y, self._feed_output_names, <ide> output_shapes, <ide> check_batch_axis=False, <del> exception_prefix='model target') <add> exception_prefix='target') <ide> sample_weights = _standardize_sample_weights(sample_weight, <ide> self._feed_output_names) <ide> class_weights = _standardize_class_weights(class_weight,
1
Javascript
Javascript
remove donate page tests
7a4e84d163a5ebdff1a69c1fc46538c999ea298a
<ide><path>client/src/pages/donate.test.js <del>/* global jest, expect */ <del>import React from 'react'; <del>import 'jest-dom/extend-expect'; <del>import ShallowRenderer from 'react-test-renderer/shallow'; <del>import { apiLocation } from '../../config/env.json'; <del> <del>import { DonatePage } from './donate'; <del> <del>describe('<DonatePage />', () => { <del> it('renders to the DOM when user is logged in', () => { <del> const shallow = new ShallowRenderer(); <del> shallow.render(<DonatePage {...loggedInProps} />); <del> expect(navigate).toHaveBeenCalledTimes(0); <del> const result = shallow.getRenderOutput(); <del> expect(result.type.toString()).toBe('Symbol(react.fragment)'); <del> // Renders Helmet component rather than Loader <del> expect(result.props.children[0].props.title).toEqual( <del> 'Support our nonprofit | freeCodeCamp.org' <del> ); <del> }); <del> <del> it('redirects to sign in page when user is not logged in', () => { <del> const shallow = new ShallowRenderer(); <del> shallow.render(<DonatePage {...loggedOutProps} />); <del> expect(navigate).toHaveBeenCalledTimes(1); <del> expect(navigate).toHaveBeenCalledWith( <del> `${apiLocation}/signin?returnTo=donate` <del> ); <del> const result = shallow.getRenderOutput(); <del> // Renders Loader rather than DonatePage <del> expect(result.type.displayName).toBe('Loader'); <del> }); <del>}); <del> <del>const navigate = jest.fn(); <del>const loggedInProps = { <del> createFlashMessage: () => {}, <del> isSignedIn: true, <del> showLoading: false, <del> navigate: navigate <del>}; <del>const loggedOutProps = { ...loggedInProps }; <del>loggedOutProps.isSignedIn = false;
1
Javascript
Javascript
remove `name` from `stringify()`
8d3bc88bbe3c0690f433a97c1df33fca099f18be
<ide><path>lib/querystring.js <ide> var stringifyPrimitive = function(v) { <ide> }; <ide> <ide> <del>QueryString.stringify = QueryString.encode = function(obj, sep, eq, name) { <add>QueryString.stringify = QueryString.encode = function(obj, sep, eq) { <ide> sep = sep || '&'; <ide> eq = eq || '='; <ide> if (util.isNull(obj)) { <ide> QueryString.stringify = QueryString.encode = function(obj, sep, eq, name) { <ide> }).join(sep); <ide> <ide> } <del> <del> if (!name) return ''; <del> return QueryString.escape(stringifyPrimitive(name)) + eq + <del> QueryString.escape(stringifyPrimitive(obj)); <add> return ''; <ide> }; <ide> <ide> // Parse a key=val string. <ide><path>test/simple/test-querystring.js <ide> qsWeirdObjects.forEach(function(testCase) { <ide> }); <ide> <ide> qsNoMungeTestCases.forEach(function(testCase) { <del> assert.deepEqual(testCase[0], qs.stringify(testCase[1], '&', '=', false)); <add> assert.deepEqual(testCase[0], qs.stringify(testCase[1], '&', '=')); <ide> }); <ide> <ide> // test the nested qs-in-qs case
2
Javascript
Javascript
use template literals in test-writewrap
25f27b787e804585b59d7d30df37fed63412bbb8
<ide><path>test/async-hooks/test-writewrap.js <ide> hooks.enable(); <ide> // <ide> const server = tls <ide> .createServer({ <del> cert: fs.readFileSync(common.fixturesDir + '/test_cert.pem'), <del> key: fs.readFileSync(common.fixturesDir + '/test_key.pem') <add> cert: fs.readFileSync(`${common.fixturesDir}/test_cert.pem`), <add> key: fs.readFileSync(`${common.fixturesDir}/test_key.pem`) <ide> }) <ide> .on('listening', common.mustCall(onlistening)) <ide> .on('secureConnection', common.mustCall(onsecureConnection))
1
Ruby
Ruby
convert inject to map + join
1ef2b47fb12a94f960b34c4bb1e6ad1f9c900e18
<ide><path>actionpack/lib/action_view/helpers/form_options_helper.rb <ide> def options_from_collection_for_select(collection, value_method, text_method, se <ide> # <b>Note:</b> Only the <tt><optgroup></tt> and <tt><option></tt> tags are returned, so you still have to <ide> # wrap the output in an appropriate <tt><select></tt> tag. <ide> def option_groups_from_collection_for_select(collection, group_method, group_label_method, option_key_method, option_value_method, selected_key = nil) <del> collection.inject("") do |options_for_select, group| <add> collection.map do |group| <ide> group_label_string = eval("group.#{group_label_method}") <del> options_for_select += "<optgroup label=\"#{html_escape(group_label_string)}\">" <del> options_for_select += options_from_collection_for_select(eval("group.#{group_method}"), option_key_method, option_value_method, selected_key) <del> options_for_select += '</optgroup>' <del> end.html_safe <add> "<optgroup label=\"#{html_escape(group_label_string)}\">" + <add> options_from_collection_for_select(eval("group.#{group_method}"), option_key_method, option_value_method, selected_key) + <add> '</optgroup>' <add> end.join.html_safe <ide> end <ide> <ide> # Returns a string of <tt><option></tt> tags, like <tt>options_for_select</tt>, but
1
PHP
PHP
add comment for content-type removal
2ecd01521fa95f2d79e9a483d6b84bc26145ddbc
<ide><path>src/Http/Response.php <ide> protected function _setStatus(int $code, string $reasonPhrase = ''): void <ide> } <ide> $this->_reasonPhrase = $reasonPhrase; <ide> <add> // These status codes don't have bodies and can't have content-types. <ide> if (in_array($code, [304, 204], true)) { <ide> $this->_clearHeader('Content-Type'); <ide> }
1
Text
Text
remove two more react.min.js references
76a0a9cba72b61c1c9df641a4f653619a174d68d
<ide><path>docs/docs/02-displaying-data.md <ide> Let's look at a really simple example. Create a `hello-react.html` file with the <ide> <html> <ide> <head> <ide> <title>Hello React</title> <del> <script src="http://fb.me/react-{{site.react_version}}.min.js"></script> <add> <script src="http://fb.me/react-{{site.react_version}}.js"></script> <ide> <script src="http://fb.me/JSXTransformer-{{site.react_version}}.js"></script> <ide> </head> <ide> <body> <ide><path>docs/docs/getting-started.md <ide> Update your HTML file as below: <ide> <html> <ide> <head> <ide> <title>Hello React!</title> <del> <script src="build/react.min.js"></script> <add> <script src="build/react.js"></script> <ide> <!-- No need for JSXTransformer! --> <ide> </head> <ide> <body>
2
Ruby
Ruby
let version.parse instantiate subclasses
35793f0e0cf855a687176e44ad8e564605de925f
<ide><path>Library/Homebrew/version.rb <ide> def tokenize <ide> <ide> def self.parse spec <ide> version = _parse(spec) <del> Version.new(version, true) unless version.nil? <add> new(version, true) unless version.nil? <ide> end <ide> <ide> def self._parse spec
1
Text
Text
add v3.23.0-beta.1 to changelog
c79a57ae3732d461aba234b2bd78d9fb4e90f862
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### v3.23.0-beta.1 (October 5, 2020) <add> <add>- [#19160](https://github.com/emberjs/ember.js/pull/19160) / [#19182](https://github.com/emberjs/ember.js/pull/19182) [FEATURE] Implements the helper manager feature specified in the [Helper Managers RFC](https://github.com/emberjs/rfcs/blob/master/text/0625-helper-managers.md). <add>- [#19171](https://github.com/emberjs/ember.js/pull/19171) / [#19182](https://github.com/emberjs/ember.js/pull/19182) [FEATURE] Implements `invokeHelper` from the [JavaScript Helper Invocation API RFC](https://github.com/emberjs/rfcs/blob/master/text/0626-invoke-helper.md). <add>- [#19148](https://github.com/emberjs/ember.js/pull/19148) / [#19119](https://github.com/emberjs/ember.js/pull/19119) Update rendering engine to `@glimmer/*` 0.62.1 <add>- [#19122](https://github.com/emberjs/ember.js/pull/19122) [BUGFIX] Prevents dynamic invocations of string values when referenced directly in angle brackets <add>- [#19136](https://github.com/emberjs/ember.js/pull/19136) [BUGFIX] Update router microlib to improve Transition related debugging <add>- [#19173](https://github.com/emberjs/ember.js/pull/19173) [BUGFIX] Enforce usage of `capabilities` generation. <add> <ide> ### v3.22.0 (October 5, 2020) <ide> <ide> - [#19062](https://github.com/emberjs/ember.js/pull/19062) / [#19068](https://github.com/emberjs/ember.js/pull/19068) [FEATURE] Add @ember/destroyable feature from the [Destroyables RFC](https://github.com/emberjs/rfcs/blob/master/text/0580-destroyables.md).
1
Ruby
Ruby
remove test ordering bug
ab3503b496b2f489391c6cc76240d8516182a2c1
<ide><path>activesupport/test/core_ext/class/delegating_attributes_test.rb <ide> class Child < Parent <ide> <ide> class Mokopuna < Child <ide> end <add> <add> class PercysMom <add> superclass_delegating_accessor :superpower <add> end <add> <add> class Percy < PercysMom <add> end <ide> end <ide> <ide> class DelegatingAttributesTest < Test::Unit::TestCase <ide> def test_child_class_delegates_to_parent_but_can_be_overridden <ide> end <ide> <ide> def test_delegation_stops_at_the_right_level <del> assert_nil Mokopuna.some_attribute <del> assert_nil Child.some_attribute <del> Child.some_attribute="1" <del> assert_equal "1", Mokopuna.some_attribute <del> ensure <del> Child.some_attribute=nil <add> assert_nil Percy.superpower <add> assert_nil PercysMom.superpower <add> <add> PercysMom.superpower = :heatvision <add> assert_equal :heatvision, Percy.superpower <ide> end <del> <add> <ide> def test_delegation_stops_for_nil <ide> Mokopuna.some_attribute = nil <ide> Child.some_attribute="1" <del> <add> <ide> assert_equal "1", Child.some_attribute <ide> assert_nil Mokopuna.some_attribute <ide> ensure
1
PHP
PHP
remove unneeded exception classes
7e861c136815ebe82bf8fb6da96e1eb3453b1b33
<ide><path>src/I18n/Exception/CannotFormatException.php <del><?php <del>declare(strict_types=1); <del> <del>/** <del> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <del> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <del> * <del> * Licensed under The MIT License <del> * For full copyright and license information, please see the LICENSE.txt <del> * Redistributions of files must retain the above copyright notice. <del> * <del> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <del> * @copyright Copyright (c) 2017 Aura for PHP <del> * @link https://cakephp.org CakePHP(tm) Project <del> * @since 4.2.0 <del> * @license https://opensource.org/licenses/mit-license.php MIT License <del> */ <del>namespace Cake\I18n\Exception; <del> <del>/** <del> * Could not format a message. <del> */ <del>class CannotFormatException extends I18nException <del>{ <del>} <ide><path>src/I18n/Exception/FormatterNotMappedException.php <del><?php <del>declare(strict_types=1); <del> <del>/** <del> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <del> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <del> * <del> * Licensed under The MIT License <del> * For full copyright and license information, please see the LICENSE.txt <del> * Redistributions of files must retain the above copyright notice. <del> * <del> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <del> * @copyright Copyright (c) 2017 Aura for PHP <del> * @link https://cakephp.org CakePHP(tm) Project <del> * @since 4.2.0 <del> * @license https://opensource.org/licenses/mit-license.php MIT License <del> */ <del>namespace Cake\I18n\Exception; <del> <del>/** <del> * A formatter name is not mapped in the locator. <del> */ <del>class FormatterNotMappedException extends I18nException <del>{ <del>} <ide><path>src/I18n/Formatter/IcuFormatter.php <ide> */ <ide> namespace Cake\I18n\Formatter; <ide> <del>use Cake\I18n\Exception\CannotFormatException; <add>use Cake\I18n\Exception\I18nException; <ide> use Cake\I18n\FormatterInterface; <ide> use MessageFormatter; <ide> <ide> class IcuFormatter implements FormatterInterface <ide> * @param string $message The message to be translated <ide> * @param array $tokenValues The list of values to interpolate in the message <ide> * @return string The formatted message <del> * @throws \Cake\I18n\Exception\CannotFormatException <add> * @throws \Cake\I18n\Exception\I18nException <ide> */ <ide> public function format($locale, $message, array $tokenValues): string <ide> { <ide> public function format($locale, $message, array $tokenValues): string <ide> * @param string $message The message to be translated <ide> * @param array $tokenValues The list of values to interpolate in the message <ide> * @return string The formatted message <del> * @throws \Cake\I18n\Exception\CannotFormatException If any error related to the passed <add> * @throws \Cake\I18n\Exception\I18nException If any error related to the passed <ide> * variables is found <ide> */ <ide> protected function _formatMessage(string $locale, string $message, array $tokenValues): string <ide> protected function _formatMessage(string $locale, string $message, array $tokenV <ide> // previous action using the object oriented style to figure out <ide> $formatter = new MessageFormatter($locale, $message); <ide> $formatter->format($tokenValues); <del> throw new CannotFormatException($formatter->getErrorMessage(), $formatter->getErrorCode()); <add> throw new I18nException($formatter->getErrorMessage(), $formatter->getErrorCode()); <ide> } <ide> <ide> return $result; <ide><path>src/I18n/FormatterLocator.php <ide> */ <ide> namespace Cake\I18n; <ide> <del>use Cake\I18n\Exception\FormatterNotMappedException; <add>use Cake\I18n\Exception\I18nException; <ide> <ide> /** <ide> * A ServiceLocator implementation for loading and retaining formatter objects. <ide> public function set(string $name, callable $spec): void <ide> * <ide> * @param string $name The formatter to retrieve. <ide> * @return \Cake\I18n\FormatterInterface A formatter object. <del> * @throws \Cake\I18n\Exception\FormatterNotMappedException <add> * @throws \Cake\I18n\Exception\I18nException <ide> */ <ide> public function get(string $name): FormatterInterface <ide> { <ide> if (!isset($this->registry[$name])) { <del> throw new FormatterNotMappedException($name); <add> throw new I18nException("Formatter named `{$name}` has not been registered"); <ide> } <ide> <ide> if (!$this->converted[$name]) {
4
Python
Python
fix syntax error in azure driver
a42cd63b2e747c1d8ab6cf63b81b222f8c61dd90
<ide><path>libcloud/compute/drivers/azure.py <ide> def reboot_node(self, node=None, ex_cloud_service_name=None, <ide> return True <ide> else: <ide> return False <del> except Exception, e: <add> except Exception: <ide> return False <ide> <ide> def ex_start_node(self, node=None, ex_cloud_service_name=None,
1
Javascript
Javascript
update historymanager spec to mock the state store
4f86d60f7bfce22804a4e76a6eafe28f2cbbed1b
<ide><path>spec/history-manager-spec.js <del>/** @babel */ <add>const {it, fit, ffit, fffit, beforeEach, afterEach} = require('./async-spec-helpers') <add>const {Emitter, Disposable, CompositeDisposable} = require('event-kit') <ide> <del>import {it, fit, ffit, fffit, beforeEach, afterEach} from './async-spec-helpers' <del>import {Emitter, Disposable, CompositeDisposable} from 'event-kit' <del> <del>import {HistoryManager, HistoryProject} from '../src/history-manager' <del>import StateStore from '../src/state-store' <add>const {HistoryManager, HistoryProject} = require('../src/history-manager') <add>const StateStore = require('../src/state-store') <ide> <ide> describe("HistoryManager", () => { <ide> let historyManager, commandRegistry, project, stateStore <ide> let commandDisposable, projectDisposable <ide> <ide> beforeEach(async () => { <del> // Do not clobber recent project history <del> spyOn(atom.applicationDelegate, 'didChangeHistoryManager') <del> <ide> commandDisposable = jasmine.createSpyObj('Disposable', ['dispose']) <ide> commandRegistry = jasmine.createSpyObj('CommandRegistry', ['add']) <ide> commandRegistry.add.andReturn(commandDisposable) <ide> describe("HistoryManager", () => { <ide> }) <ide> }) <ide> <del> describe("saveState" ,() => { <add> describe("saveState", () => { <add> let savedProjects <add> beforeEach(() => { <add> jasmine.unspy(historyManager, 'saveState') <add> <add> spyOn(historyManager.stateStore, 'save').andCallFake((name, {projects}) => { <add> savedProjects = {projects} <add> return Promise.resolve() <add> }) <add> }) <add> <ide> it("saves the state", async () => { <ide> await historyManager.addProject(["/save/state"]) <ide> await historyManager.saveState() <ide> const historyManager2 = new HistoryManager({stateStore, project, commands: commandRegistry}) <add> spyOn(historyManager2.stateStore, 'load').andCallFake(name => Promise.resolve(savedProjects)) <ide> await historyManager2.loadState() <ide> expect(historyManager2.getProjects()[0].paths).toEqual(['/save/state']) <ide> })
1
Ruby
Ruby
fix rubocop warnings
d1191c8bb0a60baf14f78cf7c5e903aa363ce53e
<ide><path>Library/Homebrew/os/mac/architecture_list.rb <ide> def universal? <ide> end <ide> <ide> def ppc? <del> (Hardware::CPU::PPC_32BIT_ARCHS+Hardware::CPU::PPC_64BIT_ARCHS).any? { |a| self.include? a } <add> (Hardware::CPU::PPC_32BIT_ARCHS+Hardware::CPU::PPC_64BIT_ARCHS).any? { |a| include? a } <ide> end <ide> <ide> # @private <ide> def as_cmake_arch_flags <ide> <ide> def intersects_all?(*set) <ide> set.all? do |archset| <del> archset.any? { |a| self.include? a } <add> archset.any? { |a| include? a } <ide> end <ide> end <ide> end
1
Text
Text
update html tags to fix misalignment
fcddfc90b2b93b624e04c5b720ebdb5b5b9d4211
<ide><path>client/src/pages/learn/apis-and-microservices/basic-node-and-express/index.md <ide> Express, while not included with Node.js, is another module often used with it. <ide> <ide> Working on these challenges will involve you writing your code on Glitch on our starter project. After completing each challenge you can copy your public Glitch url (to the homepage of your app) into the challenge screen to test it! Optionally you may choose to write your project on another platform but it must be publicly visible for our testing. <ide> <del>Start this project on Glitch using the **<a href='https://glitch.com/edit/#!/remix/clone-from-repo?REPO_URL=https://github.com/freeCodeCamp/boilerplate-express/'>Backend Challenges Boilerplate</a>** (required if you use Glitch) or clone <a href='https://github.com/freeCodeCamp/boilerplate-express/'>this repository</a> on GitHub! If you use Glitch, remember to save the link to your project somewhere safe! <add>Start this project on Glitch using **<a href='https://glitch.com/edit/#!/remix/clone-from-repo?REPO_URL=https://github.com/freeCodeCamp/boilerplate-express/'>this link</a>** or clone <a href='https://github.com/freeCodeCamp/boilerplate-express/'>this repository</a> on GitHub! If you use Glitch, remember to save the link to your project somewhere safe!
1
Javascript
Javascript
name anonymous functions
bbed075325a45569a9038a087c7a40f81582000a
<ide><path>lib/child_process.js <ide> exports._forkChild = function(fd) { <ide> p.open(fd); <ide> p.unref(); <ide> const control = setupChannel(process, p); <del> process.on('newListener', function(name) { <add> process.on('newListener', function onNewListener(name) { <ide> if (name === 'message' || name === 'disconnect') control.ref(); <ide> }); <del> process.on('removeListener', function(name) { <add> process.on('removeListener', function onRemoveListener(name) { <ide> if (name === 'message' || name === 'disconnect') control.unref(); <ide> }); <ide> }; <ide> exports.execFile = function(file /*, args, options, callback*/) { <ide> } <ide> <ide> if (options.timeout > 0) { <del> timeoutId = setTimeout(function() { <add> timeoutId = setTimeout(function delayedKill() { <ide> kill(); <ide> timeoutId = null; <ide> }, options.timeout); <ide> exports.execFile = function(file /*, args, options, callback*/) { <ide> if (encoding) <ide> child.stdout.setEncoding(encoding); <ide> <del> child.stdout.addListener('data', function(chunk) { <add> child.stdout.on('data', function onChildStdout(chunk) { <ide> stdoutLen += encoding ? Buffer.byteLength(chunk, encoding) : chunk.length; <ide> <ide> if (stdoutLen > options.maxBuffer) { <ide> exports.execFile = function(file /*, args, options, callback*/) { <ide> if (encoding) <ide> child.stderr.setEncoding(encoding); <ide> <del> child.stderr.addListener('data', function(chunk) { <add> child.stderr.on('data', function onChildStderr(chunk) { <ide> stderrLen += encoding ? Buffer.byteLength(chunk, encoding) : chunk.length; <ide> <ide> if (stderrLen > options.maxBuffer) { <ide> exports.execFile = function(file /*, args, options, callback*/) { <ide> return child; <ide> }; <ide> <del>var _deprecatedCustomFds = internalUtil.deprecate(function(options) { <del> options.stdio = options.customFds.map(function(fd) { <del> return fd === -1 ? 'pipe' : fd; <del> }); <del>}, 'child_process: options.customFds option is deprecated. ' + <del> 'Use options.stdio instead.'); <add>const _deprecatedCustomFds = internalUtil.deprecate( <add> function deprecateCustomFds(options) { <add> options.stdio = options.customFds.map(function mapCustomFds(fd) { <add> return fd === -1 ? 'pipe' : fd; <add> }); <add> }, 'child_process: options.customFds option is deprecated. ' + <add> 'Use options.stdio instead.' <add>); <ide> <ide> function _convertCustomFds(options) { <ide> if (options.customFds && !options.stdio) {
1
PHP
PHP
create authorize middleware
648fa7e35b1163e255a6f1a8939d79900761087c
<ide><path>src/Illuminate/Auth/Access/Middleware/Authorize.php <add><?php <add> <add>namespace Illuminate\Auth\Access\Middleware; <add> <add>use Closure; <add>use Illuminate\Contracts\Auth\Access\Gate; <add> <add>class Authorize <add>{ <add> /** <add> * The gate instance. <add> * <add> * @var \Illuminate\Contracts\Auth\Access\Gate <add> */ <add> protected $gate; <add> <add> /** <add> * Create a new middleware instance. <add> * <add> * @param \Illuminate\Contracts\Auth\Access\Gate $gate <add> * @return void <add> */ <add> public function __construct(Gate $gate) <add> { <add> $this->gate = $gate; <add> } <add> <add> /** <add> * Handle an incoming request. <add> * <add> * @param \Illuminate\Http\Request $request <add> * @param \Closure $next <add> * @param string $ability <add> * @param string|null $model <add> * @return mixed <add> * <add> * @throws \Illuminate\Auth\Access\AuthorizationException <add> */ <add> public function handle($request, Closure $next, $ability, $model = null) <add> { <add> $this->gate->authorize($ability, $this->getGateArguments($request, $model)); <add> <add> return $next($request); <add> } <add> <add> /** <add> * Get the arguments parameter for the gate. <add> * <add> * @param \Illuminate\Http\Request $request <add> * @param string|null $model <add> * @return array|string|\Illuminate\Database\Eloquent\Model <add> */ <add> protected function getGateArguments($request, $model) <add> { <add> // If there's no model, we'll pass an empty array to the gate. If it <add> // looks like a FQCN of a model, we'll send it to the gate as is. <add> // Otherwise, we'll resolve the Eloquent model from the route. <add> if (is_null($model)) { <add> return []; <add> } <add> <add> if (strpos($model, '\\') !== false) { <add> return $model; <add> } <add> <add> return $request->route($model); <add> } <add>}
1
Ruby
Ruby
use block variable instead of global
b28b192af194ca63fad6e3cde3b56b78f9132cac
<ide><path>activesupport/lib/active_support/core_ext/uri.rb <ide> def unescape(str, escaped = /%[a-fA-F\d]{2}/) <ide> # YK: My initial experiments say yes, but let's be sure please <ide> enc = str.encoding <ide> enc = Encoding::UTF_8 if enc == Encoding::US_ASCII <del> str.gsub(escaped) { [$&[1, 2].hex].pack('C') }.force_encoding(enc) <add> str.gsub(escaped) { |match| [match[1, 2].hex].pack('C') }.force_encoding(enc) <ide> end <ide> end <ide> end
1
Java
Java
add a way to dismiss popupmenu elements
353c070be9e9a5528d2098db4df3f0dc02d758a9
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/NativeViewHierarchyManager.java <ide> public class NativeViewHierarchyManager { <ide> private final LayoutAnimationController mLayoutAnimator = new LayoutAnimationController(); <ide> <ide> private boolean mLayoutAnimationEnabled; <add> private PopupMenu mPopupMenu; <ide> <ide> public NativeViewHierarchyManager(ViewManagerRegistry viewManagers) { <ide> this(viewManagers, new RootViewManager()); <ide> public synchronized void showPopupMenu(int reactTag, ReadableArray items, Callba <ide> error.invoke("Can't display popup. Could not find view with tag " + reactTag); <ide> return; <ide> } <del> PopupMenu popupMenu = new PopupMenu(getReactContextForView(reactTag), anchor); <add> mPopupMenu = new PopupMenu(getReactContextForView(reactTag), anchor); <ide> <del> Menu menu = popupMenu.getMenu(); <add> Menu menu = mPopupMenu.getMenu(); <ide> for (int i = 0; i < items.size(); i++) { <ide> menu.add(Menu.NONE, Menu.NONE, i, items.getString(i)); <ide> } <ide> <ide> PopupMenuCallbackHandler handler = new PopupMenuCallbackHandler(success); <del> popupMenu.setOnMenuItemClickListener(handler); <del> popupMenu.setOnDismissListener(handler); <add> mPopupMenu.setOnMenuItemClickListener(handler); <add> mPopupMenu.setOnDismissListener(handler); <ide> <del> popupMenu.show(); <add> mPopupMenu.show(); <add> } <add> <add> /** <add> * Dismiss the last opened PopupMenu {@link PopupMenu}. <add> */ <add> public void dismissPopupMenu() { <add> if (mPopupMenu != null) { <add> mPopupMenu.dismiss(); <add> } <ide> } <ide> <ide> private static class PopupMenuCallbackHandler implements PopupMenu.OnMenuItemClickListener, <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIImplementation.java <ide> public void showPopupMenu(int reactTag, ReadableArray items, Callback error, Cal <ide> mOperationsQueue.enqueueShowPopupMenu(reactTag, items, error, success); <ide> } <ide> <add> public void dismissPopupMenu() { <add> mOperationsQueue.enqueueDismissPopupMenu(); <add> } <add> <ide> public void sendAccessibilityEvent(int tag, int eventType) { <ide> mOperationsQueue.enqueueSendAccessibilityEvent(tag, eventType); <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModule.java <ide> public void showPopupMenu(int reactTag, ReadableArray items, Callback error, Cal <ide> mUIImplementation.showPopupMenu(reactTag, items, error, success); <ide> } <ide> <add> @ReactMethod <add> public void dismissPopupMenu() { <add> mUIImplementation.dismissPopupMenu(); <add> } <add> <ide> /** <ide> * LayoutAnimation API on Android is currently experimental. Therefore, it needs to be enabled <ide> * explicitly in order to avoid regression in existing application written for iOS using this API. <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIViewOperationQueue.java <ide> public void execute() { <ide> } <ide> } <ide> <add> private final class DismissPopupMenuOperation implements UIOperation { <add> @Override <add> public void execute() { <add> mNativeViewHierarchyManager.dismissPopupMenu(); <add> } <add> } <add> <ide> /** <ide> * A spec for animation operations (add/remove) <ide> */ <ide> public void enqueueShowPopupMenu( <ide> mOperations.add(new ShowPopupMenuOperation(reactTag, items, error, success)); <ide> } <ide> <add> public void enqueueDismissPopupMenu() { <add> mOperations.add(new DismissPopupMenuOperation()); <add> } <add> <ide> public void enqueueCreateView( <ide> ThemedReactContext themedContext, <ide> int viewReactTag, <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/toolbar/ReactToolbarManager.java <ide> public class ReactToolbarManager extends ViewGroupManager<ReactToolbar> { <ide> <ide> private static final String REACT_CLASS = "ToolbarAndroid"; <add> private static final int COMMAND_DISMISS_POPUP_MENUS = 1; <ide> <ide> @Override <ide> public String getName() { <ide> public boolean needsCustomLayoutForChildren() { <ide> return true; <ide> } <ide> <add> @Nullable <add> @Override <add> public Map<String, Integer> getCommandsMap() { <add> return MapBuilder.of("dismissPopupMenus", COMMAND_DISMISS_POPUP_MENUS); <add> } <add> <add> @Override <add> public void receiveCommand(ReactToolbar view, int commandType, @Nullable ReadableArray args) { <add> switch (commandType) { <add> case COMMAND_DISMISS_POPUP_MENUS: { <add> view.dismissPopupMenus(); <add> return; <add> } <add> default: <add> throw new IllegalArgumentException(String.format( <add> "Unsupported command %d received by %s.", <add> commandType, <add> getClass().getSimpleName())); <add> } <add> } <add> <ide> private int[] getDefaultContentInsets(Context context) { <ide> Resources.Theme theme = context.getTheme(); <ide> TypedArray toolbarStyle = null;
5
Python
Python
add test for ticket #449
19ab75e0741b1c4bda24f753779b8862bca6aaeb
<ide><path>numpy/core/tests/test_regression.py <ide> def check_noncommutative_reduce_accumulate(self, level=rlevel): <ide> todivide = N.array([2.0, 0.5, 0.25]) <ide> assert_equal(N.subtract.reduce(tosubtract), -10) <ide> assert_equal(N.divide.reduce(todivide), 16.0) <del> assert_array_equal(N.subtract.accumulate(tosubtract), <add> assert_array_equal(N.subtract.accumulate(tosubtract), <ide> N.array([0, -1, -3, -6, -10])) <ide> assert_array_equal(N.divide.accumulate(todivide), <ide> N.array([2., 4., 16.])) <ide> def check_convolve_empty(self, level=rlevel): <ide> self.failUnlessRaises(AssertionError,N.convolve,[],[1]) <ide> self.failUnlessRaises(AssertionError,N.convolve,[1],[]) <ide> <add> def check_multidim_byteswap(self, level=rlevel): <add> """Ticket #449""" <add> r=N.array([(1,(0,1,2))], dtype="i2,3i2") <add> assert_array_equal(r.byteswap(), <add> N.array([(256,(0,256,512))],r.dtype)) <add> <ide> def check_string_NULL(self, level=rlevel): <ide> """Changeset 3557""" <ide> assert_equal(N.array("a\x00\x0b\x0c\x00").item(),
1
Javascript
Javascript
use reactfibererrordialog fork for fabric renderer
8c747d01cb395ce06d93c2db6bb3f7b95b57d09d
<ide><path>scripts/rollup/forks.js <ide> const forks = Object.freeze({ <ide> case RN_FB_PROD: <ide> switch (entry) { <ide> case 'react-native-renderer': <add> case 'react-native-renderer/fabric': <ide> // Use the RN fork which plays well with redbox. <ide> return 'react-reconciler/src/forks/ReactFiberErrorDialog.native.js'; <ide> default:
1
Python
Python
remove trailing dot
a468d264285122ed589fd763f9c170e000649bdf
<ide><path>docs/conf.py <ide> # General information about the project. <ide> now = datetime.datetime.utcnow() <ide> project = u'Apache Libcloud' <del>copyright = u'2013 - %s, The Apache Software Foundation. Apache Libcloud, Libcloud, Apache, the Apache feather, and the Apache Libcloud project logo are trademarks of the Apache Software Foundation. All other marks mentioned may be trademarks or registered trademarks of their respective owners.' % (now.year) <add>copyright = u'2013 - %s, The Apache Software Foundation. Apache Libcloud, Libcloud, Apache, the Apache feather, and the Apache Libcloud project logo are trademarks of the Apache Software Foundation. All other marks mentioned may be trademarks or registered trademarks of their respective owners' % (now.year) <ide> <ide> html_show_sphinx = False <ide>
1
Text
Text
move changelog entry to the top [ci skip]
939ff861396857d6a476b5a2e8c53a69d8305688
<ide><path>actionpack/CHANGELOG.md <ide> ## Rails 4.0.0 (unreleased) ## <ide> <add>* Extract support for email address obfuscation via `:encode`, `:replace_at`, and `replace_dot` <add> options from the `mail_to` helper into the `actionview-encoded_mail_to` gem. <add> <add> *Nick Reed + DHH* <add> <ide> * Handle `:protocol` option in `stylesheet_link_tag` and `javascript_include_tag` <ide> <ide> *Vasiliy Ermolovich* <ide> <del>* Extract support for email address obfuscation via `:encode`, `:replace_at`, and `replace_dot` options <del> from the `mail_to` helper into the `actionview-encoded_mail_to` gem. <del> <del> *Nick Reed + DHH* <del> <ide> * Clear url helper methods when routes are reloaded. *Andrew White* <ide> <ide> * Fix a bug in `ActionDispatch::Request#raw_post` that caused `env['rack.input']`
1
Text
Text
add new notebooks
f744b81572e533af5a8469c2fba661c5972f2b66
<ide><path>notebooks/README.md <ide> Pull Request so it can be included under the Community notebooks. <ide> |[Fine-tune Roberta for sentiment analysis](https://github.com/DhavalTaunk08/NLP_scripts/blob/master/sentiment_analysis_using_roberta.ipynb) | How to fine-tune an Roberta model for sentiment analysis | [Dhaval Taunk](https://github.com/DhavalTaunk08) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/DhavalTaunk08/NLP_scripts/blob/master/sentiment_analysis_using_roberta.ipynb)| <ide> |[Evaluating Question Generation Models](https://github.com/flexudy-pipe/qugeev) | How accurate are the answers to questions generated by your seq2seq transformer model? | [Pascal Zoleko](https://github.com/zolekode) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1bpsSqCQU-iw_5nNoRm_crPq6FRuJthq_?usp=sharing)| <ide> |[Classify text with DistilBERT and Tensorflow](https://github.com/peterbayerle/huggingface_notebook/blob/main/distilbert_tf.ipynb) | How to fine-tune DistilBERT for text classification in TensorFlow | [Peter Bayerle](https://github.com/peterbayerle) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/peterbayerle/huggingface_notebook/blob/main/distilbert_tf.ipynb)| <add>|[Leverage BERT for Encoder-Decoder Summarization on CNN/Dailymail](https://github.com/patrickvonplaten/notebooks/blob/master/BERT2BERT_for_CNN_Dailymail.ipynb) | How to warm-start a *EncoderDecoderModel* with a *bert-base-uncased* checkpoint for summarization on CNN/Dailymail | [Patrick von Platen](https://github.com/patrickvonplaten) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/BERT2BERT_for_CNN_Dailymail.ipynb)| <add>|[Leverage RoBERTa for Encoder-Decoder Summarization on BBC XSum](https://github.com/patrickvonplaten/notebooks/blob/master/RoBERTaShared_for_BBC_XSum.ipynb) | How to warm-start a shared *EncoderDecoderModel* with a *roberta-base* checkpoint for summarization on BBC/XSum | [Patrick von Platen](https://github.com/patrickvonplaten) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/RoBERTaShared_for_BBC_XSum.ipynb)|
1
PHP
PHP
use secure default for session cookie
7d37bfd75eac2ae175e619bbaee7c559ef829f67
<ide><path>src/Http/Session.php <ide> protected static function _defaultConfig(string $name) <ide> ]; <ide> <ide> if (isset($defaults[$name])) { <add> if ( <add> PHP_VERSION_ID >= 70300 <add> && ($name !== 'php' || empty(ini_get('session.cookie_samesite'))) <add> ) { <add> $defaults['php']['ini']['session.cookie_samesite'] = 'Strict'; <add> } <add> <ide> return $defaults[$name]; <ide> } <ide>
1
Ruby
Ruby
add deprecatedoption class
da0a65356d662575c0005b70371050b8015227b2
<ide><path>Library/Homebrew/options.rb <ide> def inspect <ide> end <ide> end <ide> <add>class DeprecatedOption <add> attr_reader :old, :current <add> <add> def initialize(old, current) <add> @old = old <add> @current = current <add> end <add> <add> def old_flag <add> "--#{old}" <add> end <add> <add> def current_flag <add> "--#{current}" <add> end <add>end <add> <ide> class Options <ide> include Enumerable <ide> <ide><path>Library/Homebrew/test/test_options.rb <ide> def test_description <ide> end <ide> end <ide> <add>class DeprecatedOptionTests < Homebrew::TestCase <add> def setup <add> @deprecated_option = DeprecatedOption.new("foo", "bar") <add> end <add> <add> def test_old <add> assert_equal "foo", @deprecated_option.old <add> end <add> <add> def test_current <add> assert_equal "bar", @deprecated_option.current <add> end <add>end <add> <ide> class OptionsTests < Homebrew::TestCase <ide> def setup <ide> @options = Options.new
2
Ruby
Ruby
add spec for svn directory name containing `@`
d14f5dae7eaedc48ca1048c169f54a7cbce5b021
<ide><path>Library/Homebrew/test/unpack_strategy/subversion_spec.rb <ide> require_relative "shared_examples" <ide> <ide> describe UnpackStrategy::Subversion do <del> let(:repo) { <del> mktmpdir.tap do |repo| <del> system "svnadmin", "create", repo <del> end <del> } <del> let(:working_copy) { <del> mktmpdir.tap do |working_copy| <del> system "svn", "checkout", "file://#{repo}", working_copy <del> <del> FileUtils.touch working_copy/"test" <del> system "svn", "add", working_copy/"test" <del> system "svn", "commit", working_copy, "-m", "Add `test` file." <del> end <del> } <add> let(:repo) { mktmpdir } <add> let(:working_copy) { mktmpdir } <ide> let(:path) { working_copy } <ide> <add> before(:each) do <add> system "svnadmin", "create", repo <add> <add> system "svn", "checkout", "file://#{repo}", working_copy <add> <add> FileUtils.touch working_copy/"test" <add> system "svn", "add", working_copy/"test" <add> system "svn", "commit", working_copy, "-m", "Add `test` file." <add> end <add> <ide> include_examples "UnpackStrategy::detect" <ide> include_examples "#extract", children: ["test"] <add> <add> context "when the directory name contains an '@' symbol" do <add> let(:working_copy) { mktmpdir(["", "@1.2.3"]) } <add> <add> include_examples "#extract", children: ["test"] <add> end <ide> end
1
Java
Java
add param map to freemarker url macro
32ebf18429a179e6bf416db42ae2d474802369ea
<ide><path>org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/support/RequestContext.java <ide> import org.springframework.web.util.WebUtils; <ide> <ide> /** <del> * Context holder for request-specific state, like current web application <del> * context, current locale, current theme, and potential binding errors. <del> * Provides easy access to localized messages and Errors instances. <del> * <del> * <p>Suitable for exposition to views, and usage within JSP's "useBean" tag, <del> * JSP scriptlets, JSTL EL, Velocity templates, etc. Necessary for views <del> * that do not have access to the servlet request, like Velocity templates. <del> * <del> * <p>Can be instantiated manually, or automatically exposed to views as <del> * model attribute via AbstractView's "requestContextAttribute" property. <del> * <del> * <p>Will also work outside of DispatcherServlet requests, accessing the root <del> * WebApplicationContext and using an appropriate fallback for the locale <del> * (the HttpServletRequest's primary locale). <del> * <add> * Context holder for request-specific state, like current web application context, current locale, current theme, and <add> * potential binding errors. Provides easy access to localized messages and Errors instances. <add> * <add> * <p>Suitable for exposition to views, and usage within JSP's "useBean" tag, JSP scriptlets, JSTL EL, Velocity <add> * templates, etc. Necessary for views that do not have access to the servlet request, like Velocity templates. <add> * <add> * <p>Can be instantiated manually, or automatically exposed to views as model attribute via AbstractView's <add> * "requestContextAttribute" property. <add> * <add> * <p>Will also work outside of DispatcherServlet requests, accessing the root WebApplicationContext and using an <add> * appropriate fallback for the locale (the HttpServletRequest's primary locale). <add> * <ide> * @author Juergen Hoeller <ide> * @since 03.03.2003 <ide> * @see org.springframework.web.servlet.DispatcherServlet <ide> public class RequestContext { <ide> <ide> /** <del> * Default theme name used if the RequestContext cannot find a ThemeResolver. <del> * Only applies to non-DispatcherServlet requests. <del> * <p>Same as AbstractThemeResolver's default, but not linked in here to <del> * avoid package interdependencies. <add> * Default theme name used if the RequestContext cannot find a ThemeResolver. Only applies to non-DispatcherServlet <add> * requests. <p>Same as AbstractThemeResolver's default, but not linked in here to avoid package interdependencies. <ide> * @see org.springframework.web.servlet.theme.AbstractThemeResolver#ORIGINAL_DEFAULT_THEME_NAME <ide> */ <ide> public static final String DEFAULT_THEME_NAME = "theme"; <ide> <ide> /** <del> * Request attribute to hold the current web application context for RequestContext usage. <del> * By default, the DispatcherServlet's context (or the root context as fallback) is exposed. <add> * Request attribute to hold the current web application context for RequestContext usage. By default, the <add> * DispatcherServlet's context (or the root context as fallback) is exposed. <ide> */ <ide> public static final String WEB_APPLICATION_CONTEXT_ATTRIBUTE = RequestContext.class.getName() + ".CONTEXT"; <ide> <del> <del> protected static final boolean jstlPresent = ClassUtils.isPresent( <del> "javax.servlet.jsp.jstl.core.Config", RequestContext.class.getClassLoader()); <del> <add> protected static final boolean jstlPresent = ClassUtils.isPresent("javax.servlet.jsp.jstl.core.Config", <add> RequestContext.class.getClassLoader()); <ide> <ide> private HttpServletRequest request; <ide> <ide> public class RequestContext { <ide> <ide> private Map<String, Errors> errorsMap; <ide> <del> <ide> /** <del> * Create a new RequestContext for the given request, <del> * using the request attributes for Errors retrieval. <del> * <p>This only works with InternalResourceViews, as Errors instances <del> * are part of the model and not normally exposed as request attributes. <del> * It will typically be used within JSPs or custom tags. <del> * <p><b>Will only work within a DispatcherServlet request.</b> Pass in a <del> * ServletContext to be able to fallback to the root WebApplicationContext. <add> * Create a new RequestContext for the given request, using the request attributes for Errors retrieval. <p>This <add> * only works with InternalResourceViews, as Errors instances are part of the model and not normally exposed as <add> * request attributes. It will typically be used within JSPs or custom tags. <p><b>Will only work within a <add> * DispatcherServlet request.</b> Pass in a ServletContext to be able to fallback to the root WebApplicationContext. <ide> * @param request current HTTP request <ide> * @see org.springframework.web.servlet.DispatcherServlet <ide> * @see #RequestContext(javax.servlet.http.HttpServletRequest, javax.servlet.ServletContext) <ide> public RequestContext(HttpServletRequest request) { <ide> } <ide> <ide> /** <del> * Create a new RequestContext for the given request, <del> * using the request attributes for Errors retrieval. <del> * <p>This only works with InternalResourceViews, as Errors instances <del> * are part of the model and not normally exposed as request attributes. <del> * It will typically be used within JSPs or custom tags. <del> * <p>If a ServletContext is specified, the RequestContext will also <del> * work with the root WebApplicationContext (outside a DispatcherServlet). <add> * Create a new RequestContext for the given request, using the request attributes for Errors retrieval. <p>This <add> * only works with InternalResourceViews, as Errors instances are part of the model and not normally exposed as <add> * request attributes. It will typically be used within JSPs or custom tags. <p>If a ServletContext is specified, <add> * the RequestContext will also work with the root WebApplicationContext (outside a DispatcherServlet). <ide> * @param request current HTTP request <del> * @param servletContext the servlet context of the web application <del> * (can be <code>null</code>; necessary for fallback to root WebApplicationContext) <add> * @param servletContext the servlet context of the web application (can be <code>null</code>; necessary for <add> * fallback to root WebApplicationContext) <ide> * @see org.springframework.web.context.WebApplicationContext <ide> * @see org.springframework.web.servlet.DispatcherServlet <ide> */ <ide> public RequestContext(HttpServletRequest request, ServletContext servletContext) <ide> } <ide> <ide> /** <del> * Create a new RequestContext for the given request, <del> * using the given model attributes for Errors retrieval. <del> * <p>This works with all View implementations. <del> * It will typically be used by View implementations. <del> * <p><b>Will only work within a DispatcherServlet request.</b> Pass in a <del> * ServletContext to be able to fallback to the root WebApplicationContext. <add> * Create a new RequestContext for the given request, using the given model attributes for Errors retrieval. <p>This <add> * works with all View implementations. It will typically be used by View implementations. <p><b>Will only work <add> * within a DispatcherServlet request.</b> Pass in a ServletContext to be able to fallback to the root <add> * WebApplicationContext. <ide> * @param request current HTTP request <del> * @param model the model attributes for the current view <del> * (can be <code>null</code>, using the request attributes for Errors retrieval) <add> * @param model the model attributes for the current view (can be <code>null</code>, using the request attributes <add> * for Errors retrieval) <ide> * @see org.springframework.web.servlet.DispatcherServlet <ide> * @see #RequestContext(javax.servlet.http.HttpServletRequest, javax.servlet.ServletContext, Map) <ide> */ <ide> public RequestContext(HttpServletRequest request, Map<String, Object> model) { <ide> } <ide> <ide> /** <del> * Create a new RequestContext for the given request, <del> * using the given model attributes for Errors retrieval. <del> * <p>This works with all View implementations. <del> * It will typically be used by View implementations. <del> * <p>If a ServletContext is specified, the RequestContext will also <del> * work with a root WebApplicationContext (outside a DispatcherServlet). <add> * Create a new RequestContext for the given request, using the given model attributes for Errors retrieval. <p>This <add> * works with all View implementations. It will typically be used by View implementations. <p>If a ServletContext is <add> * specified, the RequestContext will also work with a root WebApplicationContext (outside a DispatcherServlet). <ide> * @param request current HTTP request <ide> * @param response current HTTP response <del> * @param servletContext the servlet context of the web application <del> * (can be <code>null</code>; necessary for fallback to root WebApplicationContext) <del> * @param model the model attributes for the current view <del> * (can be <code>null</code>, using the request attributes for Errors retrieval) <add> * @param servletContext the servlet context of the web application (can be <code>null</code>; necessary for <add> * fallback to root WebApplicationContext) <add> * @param model the model attributes for the current view (can be <code>null</code>, using the request attributes <add> * for Errors retrieval) <ide> * @see org.springframework.web.context.WebApplicationContext <ide> * @see org.springframework.web.servlet.DispatcherServlet <ide> */ <del> public RequestContext(HttpServletRequest request, HttpServletResponse response, <del> ServletContext servletContext, Map<String, Object> model) { <add> public RequestContext(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext, <add> Map<String, Object> model) { <ide> <ide> initContext(request, response, servletContext, model); <ide> } <ide> public RequestContext(HttpServletRequest request, HttpServletResponse response, <ide> protected RequestContext() { <ide> } <ide> <del> <ide> /** <del> * Initialize this context with the given request, <del> * using the given model attributes for Errors retrieval. <del> * <p>Delegates to <code>getFallbackLocale</code> and <code>getFallbackTheme</code> <del> * for determining the fallback locale and theme, respectively, if no LocaleResolver <del> * and/or ThemeResolver can be found in the request. <add> * Initialize this context with the given request, using the given model attributes for Errors retrieval. <add> * <p>Delegates to <code>getFallbackLocale</code> and <code>getFallbackTheme</code> for determining the fallback <add> * locale and theme, respectively, if no LocaleResolver and/or ThemeResolver can be found in the request. <ide> * @param request current HTTP request <del> * @param servletContext the servlet context of the web application <del> * (can be <code>null</code>; necessary for fallback to root WebApplicationContext) <del> * @param model the model attributes for the current view <del> * (can be <code>null</code>, using the request attributes for Errors retrieval) <add> * @param servletContext the servlet context of the web application (can be <code>null</code>; necessary for <add> * fallback to root WebApplicationContext) <add> * @param model the model attributes for the current view (can be <code>null</code>, using the request attributes <add> * for Errors retrieval) <ide> * @see #getFallbackLocale <ide> * @see #getFallbackTheme <ide> * @see org.springframework.web.servlet.DispatcherServlet#LOCALE_RESOLVER_ATTRIBUTE <ide> * @see org.springframework.web.servlet.DispatcherServlet#THEME_RESOLVER_ATTRIBUTE <ide> */ <del> protected void initContext(HttpServletRequest request, HttpServletResponse response, <del> ServletContext servletContext, Map<String, Object> model) { <add> protected void initContext(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext, <add> Map<String, Object> model) { <ide> <ide> this.request = request; <ide> this.response = response; <ide> this.model = model; <ide> <ide> // Fetch WebApplicationContext, either from DispatcherServlet or the root context. <ide> // ServletContext needs to be specified to be able to fall back to the root context! <del> this.webApplicationContext = <del> (WebApplicationContext) request.getAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE); <add> this.webApplicationContext = (WebApplicationContext) request.getAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE); <ide> if (this.webApplicationContext == null) { <ide> this.webApplicationContext = RequestContextUtils.getWebApplicationContext(request, servletContext); <ide> } <ide> protected void initContext(HttpServletRequest request, HttpServletResponse respo <ide> if (localeResolver != null) { <ide> // Try LocaleResolver (we're within a DispatcherServlet request). <ide> this.locale = localeResolver.resolveLocale(request); <del> } <del> else { <add> } else { <ide> // No LocaleResolver available -> try fallback. <ide> this.locale = getFallbackLocale(); <ide> } <ide> protected void initContext(HttpServletRequest request, HttpServletResponse respo <ide> } <ide> <ide> /** <del> * Determine the fallback locale for this context. <del> * <p>The default implementation checks for a JSTL locale attribute <del> * in request, session or application scope; if not found, <del> * returns the <code>HttpServletRequest.getLocale()</code>. <add> * Determine the fallback locale for this context. <p>The default implementation checks for a JSTL locale attribute <add> * in request, session or application scope; if not found, returns the <code>HttpServletRequest.getLocale()</code>. <ide> * @return the fallback locale (never <code>null</code>) <ide> * @see javax.servlet.http.HttpServletRequest#getLocale() <ide> */ <ide> protected Locale getFallbackLocale() { <ide> } <ide> <ide> /** <del> * Determine the fallback theme for this context. <del> * <p>The default implementation returns the default theme (with name "theme"). <add> * Determine the fallback theme for this context. <p>The default implementation returns the default theme (with name <add> * "theme"). <ide> * @return the fallback theme (never <code>null</code>) <ide> */ <ide> protected Theme getFallbackTheme() { <ide> protected Theme getFallbackTheme() { <ide> return theme; <ide> } <ide> <del> <ide> /** <del> * Return the underlying HttpServletRequest. <del> * Only intended for cooperating classes in this package. <add> * Return the underlying HttpServletRequest. Only intended for cooperating classes in this package. <ide> */ <ide> protected final HttpServletRequest getRequest() { <ide> return this.request; <ide> } <ide> <ide> /** <del> * Return the underlying ServletContext. <del> * Only intended for cooperating classes in this package. <add> * Return the underlying ServletContext. Only intended for cooperating classes in this package. <ide> */ <ide> protected final ServletContext getServletContext() { <ide> return this.webApplicationContext.getServletContext(); <ide> public final Locale getLocale() { <ide> } <ide> <ide> /** <del> * Return the current theme (never <code>null</code>). <del> * <p>Resolved lazily for more efficiency when theme support is not being used. <add> * Return the current theme (never <code>null</code>). <p>Resolved lazily for more efficiency when theme support is <add> * not being used. <ide> */ <ide> public final Theme getTheme() { <ide> if (this.theme == null) { <ide> public final Theme getTheme() { <ide> return this.theme; <ide> } <ide> <del> <ide> /** <del> * (De)activate default HTML escaping for messages and errors, for the scope <del> * of this RequestContext. The default is the application-wide setting <del> * (the "defaultHtmlEscape" context-param in web.xml). <add> * (De)activate default HTML escaping for messages and errors, for the scope of this RequestContext. The default is <add> * the application-wide setting (the "defaultHtmlEscape" context-param in web.xml). <ide> * @see org.springframework.web.util.WebUtils#isDefaultHtmlEscape <ide> */ <ide> public void setDefaultHtmlEscape(boolean defaultHtmlEscape) { <ide> this.defaultHtmlEscape = defaultHtmlEscape; <ide> } <ide> <ide> /** <del> * Is default HTML escaping active? <del> * Falls back to <code>false</code> in case of no explicit default given. <add> * Is default HTML escaping active? Falls back to <code>false</code> in case of no explicit default given. <ide> */ <ide> public boolean isDefaultHtmlEscape() { <ide> return (this.defaultHtmlEscape != null && this.defaultHtmlEscape.booleanValue()); <ide> } <ide> <ide> /** <del> * Return the default HTML escape setting, differentiating <del> * between no default specified and an explicit value. <add> * Return the default HTML escape setting, differentiating between no default specified and an explicit value. <ide> * @return whether default HTML escaping is enabled (null = no explicit default) <ide> */ <ide> public Boolean getDefaultHtmlEscape() { <ide> return this.defaultHtmlEscape; <ide> } <ide> <ide> /** <del> * Set the UrlPathHelper to use for context path and request URI decoding. <del> * Can be used to pass a shared UrlPathHelper instance in. <del> * <p>A default UrlPathHelper is always available. <add> * Set the UrlPathHelper to use for context path and request URI decoding. Can be used to pass a shared <add> * UrlPathHelper instance in. <p>A default UrlPathHelper is always available. <ide> */ <ide> public void setUrlPathHelper(UrlPathHelper urlPathHelper) { <ide> Assert.notNull(urlPathHelper, "UrlPathHelper must not be null"); <ide> this.urlPathHelper = urlPathHelper; <ide> } <ide> <ide> /** <del> * Return the UrlPathHelper used for context path and request URI decoding. <del> * Can be used to configure the current UrlPathHelper. <del> * <p>A default UrlPathHelper is always available. <add> * Return the UrlPathHelper used for context path and request URI decoding. Can be used to configure the current <add> * UrlPathHelper. <p>A default UrlPathHelper is always available. <ide> */ <ide> public UrlPathHelper getUrlPathHelper() { <ide> return this.urlPathHelper; <ide> } <ide> <del> <ide> /** <del> * Return the context path of the original request, <del> * that is, the path that indicates the current web application. <del> * This is useful for building links to other resources within the application. <del> * <p>Delegates to the UrlPathHelper for decoding. <add> * Return the context path of the original request, that is, the path that indicates the current web application. <add> * This is useful for building links to other resources within the application. <p>Delegates to the UrlPathHelper <add> * for decoding. <ide> * @see javax.servlet.http.HttpServletRequest#getContextPath <ide> * @see #getUrlPathHelper <ide> */ <ide> public String getContextPath() { <ide> /** <ide> * Return a context-aware URl for the given relative URL. <ide> * @param relativeUrl the relative URL part <del> * @return a URL that points back to the server with an absolute path <del> * (also URL-encoded accordingly) <add> * @return a URL that points back to the server with an absolute path (also URL-encoded accordingly) <ide> */ <ide> public String getContextUrl(String relativeUrl) { <ide> String url = getContextPath() + relativeUrl; <ide> public String getContextUrl(String relativeUrl) { <ide> } <ide> <ide> /** <del> * Return a context-aware URl for the given relative URL with placeholders (named keys with braces <code>{}</code>). <add> * Return a context-aware URl for the given relative URL with placeholders (named keys with braces <code>{}</code>). <add> * For example, send in a relative URL <code>foo/{bar}?spam={spam}</code> and a parameter map <add> * <code>{bar=baz,spam=nuts}</code> and the result will be <code>[contextpath]/foo/baz?spam=nuts</code>. <add> * <ide> * @param relativeUrl the relative URL part <ide> * @param a map of parameters to insert as placeholders in the url <del> * @return a URL that points back to the server with an absolute path <del> * (also URL-encoded accordingly) <add> * @return a URL that points back to the server with an absolute path (also URL-encoded accordingly) <ide> */ <del> public String getContextUrl(String relativeUrl, Map<String,?> params) { <add> public String getContextUrl(String relativeUrl, Map<String, ?> params) { <ide> String url = getContextPath() + relativeUrl; <ide> UriTemplate template = new UriTemplate(url); <ide> url = template.expand(params).toASCIIString(); <ide> public String getContextUrl(String relativeUrl, Map<String,?> params) { <ide> } <ide> <ide> /** <del> * Return the request URI of the original request, that is, the invoked URL <del> * without parameters. This is particularly useful as HTML form action target, <del> * possibly in combination with the original query string. <del> * <p><b>Note this implementation will correctly resolve to the URI of any <del> * originating root request in the presence of a forwarded request. However, this <del> * can only work when the Servlet 2.4 'forward' request attributes are present. <del> * <p>Delegates to the UrlPathHelper for decoding. <add> * Return the request URI of the original request, that is, the invoked URL without parameters. This is particularly <add> * useful as HTML form action target, possibly in combination with the original query string. <p><b>Note this <add> * implementation will correctly resolve to the URI of any originating root request in the presence of a forwarded <add> * request. However, this can only work when the Servlet 2.4 'forward' request attributes are present. <p>Delegates <add> * to the UrlPathHelper for decoding. <ide> * @see #getQueryString <ide> * @see org.springframework.web.util.UrlPathHelper#getOriginatingRequestUri <ide> * @see #getUrlPathHelper <ide> public String getRequestUri() { <ide> } <ide> <ide> /** <del> * Return the query string of the current request, that is, the part after <del> * the request path. This is particularly useful for building an HTML form <del> * action target in combination with the original request URI. <del> * <p><b>Note this implementation will correctly resolve to the query string of any <del> * originating root request in the presence of a forwarded request. However, this <del> * can only work when the Servlet 2.4 'forward' request attributes are present. <add> * Return the query string of the current request, that is, the part after the request path. This is particularly <add> * useful for building an HTML form action target in combination with the original request URI. <p><b>Note this <add> * implementation will correctly resolve to the query string of any originating root request in the presence of a <add> * forwarded request. However, this can only work when the Servlet 2.4 'forward' request attributes are present. <ide> * <p>Delegates to the UrlPathHelper for decoding. <ide> * @see #getRequestUri <ide> * @see org.springframework.web.util.UrlPathHelper#getOriginatingQueryString <ide> public String getQueryString() { <ide> return this.urlPathHelper.getOriginatingQueryString(this.request); <ide> } <ide> <del> <ide> /** <ide> * Retrieve the message for the given code, using the "defaultHtmlEscape" setting. <ide> * @param code code of the message <ide> public String getMessage(String code, Object[] args, boolean htmlEscape) throws <ide> } <ide> <ide> /** <del> * Retrieve the given MessageSourceResolvable (e.g. an ObjectError instance), <del> * using the "defaultHtmlEscape" setting. <add> * Retrieve the given MessageSourceResolvable (e.g. an ObjectError instance), using the "defaultHtmlEscape" setting. <ide> * @param resolvable the MessageSourceResolvable <ide> * @return the message <ide> * @throws org.springframework.context.NoSuchMessageException if not found <ide> public String getMessage(MessageSourceResolvable resolvable, boolean htmlEscape) <ide> return (htmlEscape ? HtmlUtils.htmlEscape(msg) : msg); <ide> } <ide> <del> <ide> /** <del> * Retrieve the theme message for the given code. <del> * <p>Note that theme messages are never HTML-escaped, as they typically <del> * denote theme-specific resource paths and not client-visible messages. <add> * Retrieve the theme message for the given code. <p>Note that theme messages are never HTML-escaped, as they <add> * typically denote theme-specific resource paths and not client-visible messages. <ide> * @param code code of the message <ide> * @param defaultMessage String to return if the lookup fails <ide> * @return the message <ide> public String getThemeMessage(String code, String defaultMessage) { <ide> } <ide> <ide> /** <del> * Retrieve the theme message for the given code. <del> * <p>Note that theme messages are never HTML-escaped, as they typically <del> * denote theme-specific resource paths and not client-visible messages. <add> * Retrieve the theme message for the given code. <p>Note that theme messages are never HTML-escaped, as they <add> * typically denote theme-specific resource paths and not client-visible messages. <ide> * @param code code of the message <ide> * @param args arguments for the message, or <code>null</code> if none <ide> * @param defaultMessage String to return if the lookup fails <ide> public String getThemeMessage(String code, Object[] args, String defaultMessage) <ide> } <ide> <ide> /** <del> * Retrieve the theme message for the given code. <del> * <p>Note that theme messages are never HTML-escaped, as they typically <del> * denote theme-specific resource paths and not client-visible messages. <add> * Retrieve the theme message for the given code. <p>Note that theme messages are never HTML-escaped, as they <add> * typically denote theme-specific resource paths and not client-visible messages. <ide> * @param code code of the message <ide> * @param args arguments for the message as a List, or <code>null</code> if none <ide> * @param defaultMessage String to return if the lookup fails <ide> * @return the message <ide> */ <ide> public String getThemeMessage(String code, List args, String defaultMessage) { <del> return getTheme().getMessageSource().getMessage( <del> code, (args != null ? args.toArray() : null), defaultMessage, this.locale); <add> return getTheme().getMessageSource().getMessage(code, (args != null ? args.toArray() : null), defaultMessage, <add> this.locale); <ide> } <ide> <ide> /** <del> * Retrieve the theme message for the given code. <del> * <p>Note that theme messages are never HTML-escaped, as they typically <del> * denote theme-specific resource paths and not client-visible messages. <add> * Retrieve the theme message for the given code. <p>Note that theme messages are never HTML-escaped, as they <add> * typically denote theme-specific resource paths and not client-visible messages. <ide> * @param code code of the message <ide> * @return the message <ide> * @throws org.springframework.context.NoSuchMessageException if not found <ide> public String getThemeMessage(String code) throws NoSuchMessageException { <ide> } <ide> <ide> /** <del> * Retrieve the theme message for the given code. <del> * <p>Note that theme messages are never HTML-escaped, as they typically <del> * denote theme-specific resource paths and not client-visible messages. <add> * Retrieve the theme message for the given code. <p>Note that theme messages are never HTML-escaped, as they <add> * typically denote theme-specific resource paths and not client-visible messages. <ide> * @param code code of the message <ide> * @param args arguments for the message, or <code>null</code> if none <ide> * @return the message <ide> public String getThemeMessage(String code, Object[] args) throws NoSuchMessageEx <ide> } <ide> <ide> /** <del> * Retrieve the theme message for the given code. <del> * <p>Note that theme messages are never HTML-escaped, as they typically <del> * denote theme-specific resource paths and not client-visible messages. <add> * Retrieve the theme message for the given code. <p>Note that theme messages are never HTML-escaped, as they <add> * typically denote theme-specific resource paths and not client-visible messages. <ide> * @param code code of the message <ide> * @param args arguments for the message as a List, or <code>null</code> if none <ide> * @return the message <ide> * @throws org.springframework.context.NoSuchMessageException if not found <ide> */ <ide> public String getThemeMessage(String code, List args) throws NoSuchMessageException { <del> return getTheme().getMessageSource().getMessage( <del> code, (args != null ? args.toArray() : null), this.locale); <add> return getTheme().getMessageSource().getMessage(code, (args != null ? args.toArray() : null), this.locale); <ide> } <ide> <ide> /** <del> * Retrieve the given MessageSourceResolvable in the current theme. <del> * <p>Note that theme messages are never HTML-escaped, as they typically <del> * denote theme-specific resource paths and not client-visible messages. <add> * Retrieve the given MessageSourceResolvable in the current theme. <p>Note that theme messages are never <add> * HTML-escaped, as they typically denote theme-specific resource paths and not client-visible messages. <ide> * @param resolvable the MessageSourceResolvable <ide> * @return the message <ide> * @throws org.springframework.context.NoSuchMessageException if not found <ide> public String getThemeMessage(MessageSourceResolvable resolvable) throws NoSuchM <ide> return getTheme().getMessageSource().getMessage(resolvable, this.locale); <ide> } <ide> <del> <ide> /** <del> * Retrieve the Errors instance for the given bind object, <del> * using the "defaultHtmlEscape" setting. <add> * Retrieve the Errors instance for the given bind object, using the "defaultHtmlEscape" setting. <ide> * @param name name of the bind object <ide> * @return the Errors instance, or <code>null</code> if not found <ide> */ <ide> public Errors getErrors(String name, boolean htmlEscape) { <ide> if (htmlEscape && !(errors instanceof EscapedErrors)) { <ide> errors = new EscapedErrors(errors); <ide> put = true; <del> } <del> else if (!htmlEscape && errors instanceof EscapedErrors) { <add> } else if (!htmlEscape && errors instanceof EscapedErrors) { <ide> errors = ((EscapedErrors) errors).getSource(); <ide> put = true; <ide> } <ide> else if (!htmlEscape && errors instanceof EscapedErrors) { <ide> } <ide> <ide> /** <del> * Retrieve the model object for the given model name, <del> * either from the model or from the request attributes. <add> * Retrieve the model object for the given model name, either from the model or from the request attributes. <ide> * @param modelName the name of the model object <ide> * @return the model object <ide> */ <ide> protected Object getModelObject(String modelName) { <ide> if (this.model != null) { <ide> return this.model.get(modelName); <del> } <del> else { <add> } else { <ide> return this.request.getAttribute(modelName); <ide> } <ide> } <ide> <ide> /** <del> * Create a BindStatus for the given bind object, <del> * using the "defaultHtmlEscape" setting. <del> * @param path the bean and property path for which values and errors <del> * will be resolved (e.g. "person.age") <add> * Create a BindStatus for the given bind object, using the "defaultHtmlEscape" setting. <add> * @param path the bean and property path for which values and errors will be resolved (e.g. "person.age") <ide> * @return the new BindStatus instance <ide> * @throws IllegalStateException if no corresponding Errors object found <ide> */ <ide> public BindStatus getBindStatus(String path) throws IllegalStateException { <ide> } <ide> <ide> /** <del> * Create a BindStatus for the given bind object, <del> * using the "defaultHtmlEscape" setting. <del> * @param path the bean and property path for which values and errors <del> * will be resolved (e.g. "person.age") <add> * Create a BindStatus for the given bind object, using the "defaultHtmlEscape" setting. <add> * @param path the bean and property path for which values and errors will be resolved (e.g. "person.age") <ide> * @param htmlEscape create a BindStatus with automatic HTML escaping? <ide> * @return the new BindStatus instance <ide> * @throws IllegalStateException if no corresponding Errors object found <ide> public BindStatus getBindStatus(String path, boolean htmlEscape) throws IllegalS <ide> return new BindStatus(this, path, htmlEscape); <ide> } <ide> <del> <ide> /** <del> * Inner class that isolates the JSTL dependency. <del> * Just called to resolve the fallback locale if the JSTL API is present. <add> * Inner class that isolates the JSTL dependency. Just called to resolve the fallback locale if the JSTL API is <add> * present. <ide> */ <ide> private static class JstlLocaleResolver { <ide> <ide><path>org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/support/RequestContextTests.java <add>/* <add> * Copyright 2002-2011 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.web.servlet.support; <add> <add>import static org.junit.Assert.assertEquals; <add> <add>import java.util.HashMap; <add>import java.util.Map; <add> <add>import org.junit.Before; <add>import org.junit.Test; <add>import org.springframework.mock.web.MockHttpServletRequest; <add>import org.springframework.mock.web.MockHttpServletResponse; <add>import org.springframework.mock.web.MockServletContext; <add>import org.springframework.web.context.WebApplicationContext; <add>import org.springframework.web.context.support.GenericWebApplicationContext; <add> <add>/** <add> * @author Dave Syer <add> * <add> */ <add>public class RequestContextTests { <add> <add> private MockHttpServletRequest request = new MockHttpServletRequest(); <add> <add> private MockHttpServletResponse response = new MockHttpServletResponse(); <add> <add> private MockServletContext servletContext = new MockServletContext(); <add> <add> private Map<String, Object> model = new HashMap<String, Object>(); <add> <add> @Before <add> public void init() { <add> GenericWebApplicationContext applicationContext = new GenericWebApplicationContext(); <add> servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, applicationContext); <add> } <add> <add> @Test <add> public void testGetContextUrlString() throws Exception { <add> request.setContextPath("foo/"); <add> RequestContext context = new RequestContext(request, response, servletContext, model); <add> assertEquals("foo/bar", context.getContextUrl("bar")); <add> } <add> <add> @Test <add> public void testGetContextUrlStringMap() throws Exception { <add> request.setContextPath("foo/"); <add> RequestContext context = new RequestContext(request, response, servletContext, model); <add> Map<String, Object> map = new HashMap<String, Object>(); <add> map.put("foo", "bar"); <add> map.put("spam", "bucket"); <add> assertEquals("foo/bar?spam=bucket", context.getContextUrl("{foo}?spam={spam}", map)); <add> } <add> <add> // TODO: test escaping of query params (not supported by UriTemplate but some features present in UriUtils). <add> <add>}
2
Javascript
Javascript
fix deprecation code
da40050b59046b615ae50c6dd8c71c315d8578de
<ide><path>lib/repl.js <ide> REPLServer.prototype.setPrompt = function setPrompt(prompt) { <ide> REPLServer.prototype.turnOffEditorMode = util.deprecate( <ide> function() { _turnOffEditorMode(this); }, <ide> 'REPLServer.turnOffEditorMode() is deprecated', <del> 'DEP00XX'); <add> 'DEP0078'); <ide> <ide> // A stream to push an array into a REPL <ide> // used in REPLServer.complete
1
Ruby
Ruby
delete only unnecessary reporter
d82bf140030a62d216e68a81e63ea5d97c45125b
<ide><path>railties/lib/rails/test_unit/minitest_plugin.rb <ide> def self.plugin_rails_init(options) <ide> Minitest.backtrace_filter = ::Rails.backtrace_cleaner if ::Rails.respond_to?(:backtrace_cleaner) <ide> end <ide> <del> self.reporter.reporters.clear # Replace progress reporter for colors. <add> # Replace progress reporter for colors. <add> self.reporter.reporters.delete_if { |reporter| reporter.kind_of?(SummaryReporter) || reporter.kind_of?(ProgressReporter) } <ide> self.reporter << SuppressedSummaryReporter.new(options[:io], options) <ide> self.reporter << ::Rails::TestUnitReporter.new(options[:io], options) <ide> end
1
PHP
PHP
add missing curly brackets
ae4ff8e705ba9f3f6e6c2dc9e758ceb03446d1b9
<ide><path>src/Illuminate/Foundation/Application.php <ide> public function registerConfiguredProviders() <ide> public function register($provider, $options = array(), $force = false) <ide> { <ide> if ($registered = $this->getProvider($provider) && ! $force) <del> return $registered; <add> { <add> return $registered; <add> } <ide> <ide> // If the given "provider" is a string, we will resolve it, passing in the <ide> // application instance automatically for the developer. This is simply <ide><path>src/Illuminate/Routing/Route.php <ide> public function run(Request $request) <ide> try <ide> { <ide> if ( ! is_string($this->action['uses'])) <add> { <ide> return $this->runCallable($request); <add> } <ide> <ide> if ($this->customDispatcherIsBound()) <add> { <ide> return $this->runWithCustomDispatcher($request); <add> } <ide> <ide> return $this->runController($request); <ide> } <ide> protected function runController(Request $request) <ide> ); <ide> <ide> if ( ! method_exists($instance = $this->container->make($class), $method)) <add> { <ide> throw new NotFoundHttpException; <add> } <ide> <ide> return call_user_func_array([$instance, $method], $parameters); <ide> }
2
PHP
PHP
add env variable
e1b8847a92bdd85163990ee2e3284262da09b5fd
<ide><path>config/logging.php <ide> 'stderr' => [ <ide> 'driver' => 'monolog', <ide> 'handler' => StreamHandler::class, <add> 'formatter' => env('LOG_STDERR_FORMATTER'), <ide> 'with' => [ <ide> 'stream' => 'php://stderr', <ide> ],
1
Go
Go
fix remote build target as dockerfile
a74cc833450dfc48cc95b2b109cbcb24feff4929
<ide><path>builder/remotecontext/archive.go <ide> func FromArchive(tarStream io.Reader) (builder.Source, error) { <ide> } <ide> <ide> tsc.sums = sum.GetSums() <del> <ide> return tsc, nil <ide> } <ide> <ide><path>builder/remotecontext/detect.go <ide> func newGitRemote(gitURL string, dockerfilePath string) (builder.Source, *parser <ide> } <ide> <ide> func newURLRemote(url string, dockerfilePath string, progressReader func(in io.ReadCloser) io.ReadCloser) (builder.Source, *parser.Result, error) { <del> var dockerfile io.ReadCloser <del> dockerfileFoundErr := errors.New("found-dockerfile") <del> c, err := MakeRemoteContext(url, map[string]func(io.ReadCloser) (io.ReadCloser, error){ <del> mimeTypes.TextPlain: func(rc io.ReadCloser) (io.ReadCloser, error) { <del> dockerfile = rc <del> return nil, dockerfileFoundErr <del> }, <del> // fallback handler (tar context) <del> "": func(rc io.ReadCloser) (io.ReadCloser, error) { <del> return progressReader(rc), nil <del> }, <del> }) <del> switch { <del> case err == dockerfileFoundErr: <del> res, err := parser.Parse(dockerfile) <del> return nil, res, err <del> case err != nil: <add> contentType, content, err := downloadRemote(url) <add> if err != nil { <ide> return nil, nil, err <ide> } <del> return withDockerfileFromContext(c.(modifiableContext), dockerfilePath) <add> defer content.Close() <add> <add> switch contentType { <add> case mimeTypes.TextPlain: <add> res, err := parser.Parse(progressReader(content)) <add> return nil, res, err <add> default: <add> source, err := FromArchive(progressReader(content)) <add> if err != nil { <add> return nil, nil, err <add> } <add> return withDockerfileFromContext(source.(modifiableContext), dockerfilePath) <add> } <ide> } <ide> <ide> func removeDockerfile(c modifiableContext, filesToRemove ...string) error { <ide><path>builder/remotecontext/remote.go <ide> import ( <ide> "net/url" <ide> "regexp" <ide> <del> "github.com/docker/docker/builder" <add> "github.com/docker/docker/pkg/ioutils" <ide> "github.com/pkg/errors" <ide> ) <ide> <ide> const acceptableRemoteMIME = `(?:application/(?:(?:x\-)?tar|octet\-stream|((?:x\ <ide> <ide> var mimeRe = regexp.MustCompile(acceptableRemoteMIME) <ide> <del>// MakeRemoteContext downloads a context from remoteURL and returns it. <del>// <del>// If contentTypeHandlers is non-nil, then the Content-Type header is read along with a maximum of <del>// maxPreambleLength bytes from the body to help detecting the MIME type. <del>// Look at acceptableRemoteMIME for more details. <del>// <del>// If a match is found, then the body is sent to the contentType handler and a (potentially compressed) tar stream is expected <del>// to be returned. If no match is found, it is assumed the body is a tar stream (compressed or not). <del>// In either case, an (assumed) tar stream is passed to FromArchive whose result is returned. <del>func MakeRemoteContext(remoteURL string, contentTypeHandlers map[string]func(io.ReadCloser) (io.ReadCloser, error)) (builder.Source, error) { <del> f, err := GetWithStatusError(remoteURL) <add>// downloadRemote context from a url and returns it, along with the parsed content type <add>func downloadRemote(remoteURL string) (string, io.ReadCloser, error) { <add> response, err := GetWithStatusError(remoteURL) <ide> if err != nil { <del> return nil, fmt.Errorf("error downloading remote context %s: %v", remoteURL, err) <add> return "", nil, fmt.Errorf("error downloading remote context %s: %v", remoteURL, err) <ide> } <del> defer f.Body.Close() <ide> <del> var contextReader io.ReadCloser <del> if contentTypeHandlers != nil { <del> contentType := f.Header.Get("Content-Type") <del> clen := f.ContentLength <del> <del> contentType, contextReader, err = inspectResponse(contentType, f.Body, clen) <del> if err != nil { <del> return nil, fmt.Errorf("error detecting content type for remote %s: %v", remoteURL, err) <del> } <del> defer contextReader.Close() <del> <del> // This loop tries to find a content-type handler for the detected content-type. <del> // If it could not find one from the caller-supplied map, it tries the empty content-type `""` <del> // which is interpreted as a fallback handler (usually used for raw tar contexts). <del> for _, ct := range []string{contentType, ""} { <del> if fn, ok := contentTypeHandlers[ct]; ok { <del> defer contextReader.Close() <del> if contextReader, err = fn(contextReader); err != nil { <del> return nil, err <del> } <del> break <del> } <del> } <add> contentType, contextReader, err := inspectResponse( <add> response.Header.Get("Content-Type"), <add> response.Body, <add> response.ContentLength) <add> if err != nil { <add> response.Body.Close() <add> return "", nil, fmt.Errorf("error detecting content type for remote %s: %v", remoteURL, err) <ide> } <ide> <del> // Pass through - this is a pre-packaged context, presumably <del> // with a Dockerfile with the right name inside it. <del> return FromArchive(contextReader) <add> return contentType, ioutils.NewReadCloserWrapper(contextReader, response.Body.Close), nil <ide> } <ide> <ide> // GetWithStatusError does an http.Get() and returns an error if the <ide> func GetWithStatusError(address string) (resp *http.Response, err error) { <ide> // - an io.Reader for the response body <ide> // - an error value which will be non-nil either when something goes wrong while <ide> // reading bytes from r or when the detected content-type is not acceptable. <del>func inspectResponse(ct string, r io.Reader, clen int64) (string, io.ReadCloser, error) { <add>func inspectResponse(ct string, r io.Reader, clen int64) (string, io.Reader, error) { <ide> plen := clen <ide> if plen <= 0 || plen > maxPreambleLength { <ide> plen = maxPreambleLength <ide> func inspectResponse(ct string, r io.Reader, clen int64) (string, io.ReadCloser, <ide> preamble := make([]byte, plen) <ide> rlen, err := r.Read(preamble) <ide> if rlen == 0 { <del> return ct, ioutil.NopCloser(r), errors.New("empty response") <add> return ct, r, errors.New("empty response") <ide> } <ide> if err != nil && err != io.EOF { <del> return ct, ioutil.NopCloser(r), err <add> return ct, r, err <ide> } <ide> <ide> preambleR := bytes.NewReader(preamble[:rlen]) <del> bodyReader := ioutil.NopCloser(io.MultiReader(preambleR, r)) <add> bodyReader := io.MultiReader(preambleR, r) <ide> // Some web servers will use application/octet-stream as the default <ide> // content type for files without an extension (e.g. 'Dockerfile') <ide> // so if we receive this value we better check for text content <ide><path>builder/remotecontext/remote_test.go <ide> import ( <ide> <ide> "github.com/docker/docker/builder" <ide> "github.com/docker/docker/internal/testutil" <del> "github.com/docker/docker/pkg/archive" <add> "github.com/gotestyourself/gotestyourself/fs" <ide> "github.com/stretchr/testify/assert" <ide> "github.com/stretchr/testify/require" <ide> ) <ide> func TestUnknownContentLength(t *testing.T) { <ide> } <ide> } <ide> <del>func TestMakeRemoteContext(t *testing.T) { <del> contextDir, cleanup := createTestTempDir(t, "", "builder-tarsum-test") <del> defer cleanup() <del> <del> createTestTempFile(t, contextDir, builder.DefaultDockerfileName, dockerfileContents, 0777) <add>func TestDownloadRemote(t *testing.T) { <add> contextDir := fs.NewDir(t, "test-builder-download-remote", <add> fs.WithFile(builder.DefaultDockerfileName, dockerfileContents)) <add> defer contextDir.Remove() <ide> <ide> mux := http.NewServeMux() <ide> server := httptest.NewServer(mux) <ide> func TestMakeRemoteContext(t *testing.T) { <ide> serverURL.Path = "/" + builder.DefaultDockerfileName <ide> remoteURL := serverURL.String() <ide> <del> mux.Handle("/", http.FileServer(http.Dir(contextDir))) <del> <del> remoteContext, err := MakeRemoteContext(remoteURL, map[string]func(io.ReadCloser) (io.ReadCloser, error){ <del> mimeTypes.TextPlain: func(rc io.ReadCloser) (io.ReadCloser, error) { <del> dockerfile, err := ioutil.ReadAll(rc) <del> if err != nil { <del> return nil, err <del> } <del> <del> r, err := archive.Generate(builder.DefaultDockerfileName, string(dockerfile)) <del> if err != nil { <del> return nil, err <del> } <del> return ioutil.NopCloser(r), nil <del> }, <del> }) <del> <del> if err != nil { <del> t.Fatalf("Error when executing DetectContextFromRemoteURL: %s", err) <del> } <del> <del> if remoteContext == nil { <del> t.Fatal("Remote context should not be nil") <del> } <add> mux.Handle("/", http.FileServer(http.Dir(contextDir.Path()))) <ide> <del> h, err := remoteContext.Hash(builder.DefaultDockerfileName) <del> if err != nil { <del> t.Fatalf("failed to compute hash %s", err) <del> } <add> contentType, content, err := downloadRemote(remoteURL) <add> require.NoError(t, err) <ide> <del> if expected, actual := "7b6b6b66bee9e2102fbdc2228be6c980a2a23adf371962a37286a49f7de0f7cc", h; expected != actual { <del> t.Fatalf("There should be file named %s %s in fileInfoSums", expected, actual) <del> } <add> assert.Equal(t, mimeTypes.TextPlain, contentType) <add> raw, err := ioutil.ReadAll(content) <add> require.NoError(t, err) <add> assert.Equal(t, dockerfileContents, string(raw)) <ide> } <ide> <ide> func TestGetWithStatusError(t *testing.T) {
4
Go
Go
fix usageinusermode value on windows
ec16053ccfe2f5bab23730b8611dd9c2e5edf9b4
<ide><path>daemon/daemon_windows.go <ide> func (daemon *Daemon) stats(c *container.Container) (*types.StatsJSON, error) { <ide> CPUUsage: types.CPUUsage{ <ide> TotalUsage: hcss.Processor.TotalRuntime100ns, <ide> UsageInKernelmode: hcss.Processor.RuntimeKernel100ns, <del> UsageInUsermode: hcss.Processor.RuntimeKernel100ns, <add> UsageInUsermode: hcss.Processor.RuntimeUser100ns, <ide> }, <ide> } <ide>
1
Javascript
Javascript
fix bindattr with keywords - fixed #798
27eca01d12ee22de0997be117158699678b40ca9
<ide><path>packages/ember-handlebars/lib/helpers/binding.js <ide> require('ember-handlebars/ext'); <ide> require('ember-handlebars/views/handlebars_bound_view'); <ide> require('ember-handlebars/views/metamorph_view'); <ide> <del>var get = Ember.get, getPath = Ember.Handlebars.getPath, set = Ember.set, fmt = Ember.String.fmt; <add>var get = Ember.get, getPath = Ember.getPath, set = Ember.set, fmt = Ember.String.fmt; <add>var normalizePath = Ember.Handlebars.normalizePath; <ide> var forEach = Ember.ArrayUtils.forEach; <ide> <ide> var EmberHandlebars = Ember.Handlebars, helpers = EmberHandlebars.helpers; <ide> var bind = function(property, options, preserveContext, shouldDisplay, valueNorm <ide> currentContext = this, <ide> pathRoot, path, normalized; <ide> <del> normalized = Ember.Handlebars.normalizePath(currentContext, property, data); <add> normalized = normalizePath(currentContext, property, data); <ide> <ide> pathRoot = normalized.root; <ide> path = normalized.path; <ide> EmberHandlebars.registerHelper('bindAttr', function(options) { <ide> // For each attribute passed, create an observer and emit the <ide> // current value of the property as an attribute. <ide> forEach(attrKeys, function(attr) { <del> var property = attrs[attr]; <add> var path = attrs[attr], <add> pathRoot, normalized; <ide> <del> Ember.assert(fmt("You must provide a String for a bound attribute, not %@", [property]), typeof property === 'string'); <add> Ember.assert(fmt("You must provide a String for a bound attribute, not %@", [path]), typeof path === 'string'); <ide> <del> var value = (property === 'this') ? ctx : getPath(ctx, property, options), <add> normalized = normalizePath(ctx, path, options.data); <add> <add> pathRoot = normalized.root; <add> path = normalized.path; <add> <add> var value = (path === 'this') ? pathRoot : getPath(pathRoot, path, options), <ide> type = Ember.typeOf(value); <ide> <ide> Ember.assert(fmt("Attributes must be numbers, strings or booleans, not %@", [value]), value === null || value === undefined || type === 'number' || type === 'string' || type === 'boolean'); <ide> EmberHandlebars.registerHelper('bindAttr', function(options) { <ide> <ide> /** @private */ <ide> observer = function observer() { <del> var result = getPath(ctx, property, options); <add> var result = getPath(pathRoot, path, options); <ide> <ide> Ember.assert(fmt("Attributes must be numbers, strings or booleans, not %@", [result]), result === null || result === undefined || typeof result === 'number' || typeof result === 'string' || typeof result === 'boolean'); <ide> <ide> EmberHandlebars.registerHelper('bindAttr', function(options) { <ide> // In that case, we can assume the template has been re-rendered <ide> // and we need to clean up the observer. <ide> if (elem.length === 0) { <del> Ember.removeObserver(ctx, property, invoker); <add> Ember.removeObserver(pathRoot, path, invoker); <ide> return; <ide> } <ide> <ide> EmberHandlebars.registerHelper('bindAttr', function(options) { <ide> // Add an observer to the view for when the property changes. <ide> // When the observer fires, find the element using the <ide> // unique data id and update the attribute to the new value. <del> if (property !== 'this') { <del> Ember.addObserver(ctx, property, invoker); <add> if (path !== 'this') { <add> Ember.addObserver(pathRoot, path, invoker); <ide> } <ide> <ide> // if this changes, also change the logic in ember-views/lib/views/view.js <ide> EmberHandlebars.bindClasses = function(context, classBindings, view, bindAttrId, <ide> // Helper method to retrieve the property from the context and <ide> // determine which class string to return, based on whether it is <ide> // a Boolean or not. <del> var classStringForProperty = function(property) { <del> var split = property.split(':'), <del> className = split[1]; <del> <del> property = split[0]; <del> <del> var val = property !== '' ? getPath(context, property, options) : true; <add> var classStringForPath = function(root, path, className, options) { <add> var val = path !== '' ? getPath(root, path, options) : true; <ide> <ide> // If the value is truthy and we're using the colon syntax, <ide> // we should return the className directly <ide> EmberHandlebars.bindClasses = function(context, classBindings, view, bindAttrId, <ide> // Normalize property path to be suitable for use <ide> // as a class name. For exaple, content.foo.barBaz <ide> // becomes bar-baz. <del> var parts = property.split('.'); <add> var parts = path.split('.'); <ide> return Ember.String.dasherize(parts[parts.length-1]); <ide> <ide> // If the value is not false, undefined, or null, return the current <ide> EmberHandlebars.bindClasses = function(context, classBindings, view, bindAttrId, <ide> <ide> var observer, invoker; <ide> <add> var split = binding.split(':'), <add> path = split[0], <add> className = split[1], <add> pathRoot = context, <add> normalized; <add> <add> if (path !== '') { <add> normalized = normalizePath(context, path, options.data); <add> <add> pathRoot = normalized.root; <add> path = normalized.path; <add> } <add> <ide> // Set up an observer on the context. If the property changes, toggle the <ide> // class name. <ide> /** @private */ <ide> observer = function() { <ide> // Get the current value of the property <del> newClass = classStringForProperty(binding); <add> newClass = classStringForPath(pathRoot, path, className, options); <ide> elem = bindAttrId ? view.$("[data-bindattr-" + bindAttrId + "='" + bindAttrId + "']") : view.$(); <ide> <ide> // If we can't find the element anymore, a parent template has been <ide> // re-rendered and we've been nuked. Remove the observer. <ide> if (elem.length === 0) { <del> Ember.removeObserver(context, binding, invoker); <add> Ember.removeObserver(pathRoot, path, invoker); <ide> } else { <ide> // If we had previously added a class to the element, remove it. <ide> if (oldClass) { <ide> EmberHandlebars.bindClasses = function(context, classBindings, view, bindAttrId, <ide> Ember.run.once(observer); <ide> }; <ide> <del> var property = binding.split(':')[0]; <del> if (property !== '') { <del> Ember.addObserver(context, property, invoker); <add> if (path !== '') { <add> Ember.addObserver(pathRoot, path, invoker); <ide> } <ide> <ide> // We've already setup the observer; now we just need to figure out the <ide> // correct behavior right now on the first pass through. <del> value = classStringForProperty(binding); <add> value = classStringForPath(pathRoot, path, className, options); <ide> <ide> if (value) { <ide> ret.push(value); <ide><path>packages/ember-handlebars/tests/handlebars_test.js <ide> test("should be able to bind element attributes using {{bindAttr}}", function() <ide> equal(view.$('img').attr('alt'), "Nanananana Ember!", "updates alt attribute when title property is computed"); <ide> }); <ide> <add>test("should be able to bind to view attributes with {{bindAttr}}", function() { <add> view = Ember.View.create({ <add> value: 'test.jpg', <add> template: Ember.Handlebars.compile('<img {{bindAttr src="view.value"}}>') <add> }); <add> <add> appendView(); <add> <add> equal(view.$('img').attr('src'), "test.jpg", "renders initial value"); <add> <add> Ember.run(function() { <add> view.set('value', 'updated.jpg'); <add> }); <add> <add> equal(view.$('img').attr('src'), "updated.jpg", "updates value"); <add>}); <add> <ide> test("should not allow XSS injection via {{bindAttr}}", function() { <ide> view = Ember.View.create({ <ide> template: Ember.Handlebars.compile('<img {{bindAttr src="content.url"}}>'), <ide> test("should be able to bind class attribute via a truthy property with {{bindAt <ide> equal(view.$('.is-truthy').length, 0, "removes class name if bound property is set to something non-truthy"); <ide> }); <ide> <add>test("should be able to bind class to view attribute with {{bindAttr}}", function() { <add> var template = Ember.Handlebars.compile('<img {{bindAttr class="view.foo"}}>'); <add> <add> view = Ember.View.create({ <add> template: template, <add> foo: 'bar' <add> }); <add> <add> appendView(); <add> <add> equal(view.$('img').attr('class'), 'bar', "renders class"); <add> <add> Ember.run(function() { <add> set(view, 'foo', 'baz'); <add> }); <add> <add> equal(view.$('img').attr('class'), 'baz', "updates class"); <add>}); <add> <ide> test("should not allow XSS injection via {{bindAttr}} with class", function() { <ide> view = Ember.View.create({ <ide> template: Ember.Handlebars.compile('<img {{bindAttr class="foo"}}>'),
2
Java
Java
add generation context interface
1816c77c51132b6fff6bd2f275c993bc7e1250c6
<ide><path>spring-core/src/main/java/org/springframework/aot/generate/DefaultGenerationContext.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.aot.generate; <add> <add>import java.io.IOException; <add> <add>import org.springframework.aot.hint.RuntimeHints; <add>import org.springframework.util.Assert; <add> <add>/** <add> * Default implementation of {@link GenerationContext}. <add> * <add> * @author Phillip Webb <add> * @author Stephane Nicoll <add> * @since 6.0 <add> */ <add>public class DefaultGenerationContext implements GenerationContext { <add> <add> private final ClassNameGenerator classNameGenerator; <add> <add> private final GeneratedClasses generatedClasses; <add> <add> private final GeneratedFiles generatedFiles; <add> <add> private final RuntimeHints runtimeHints; <add> <add> <add> /** <add> * Create a new {@link DefaultGenerationContext} instance backed by the <add> * specified {@code generatedFiles}. <add> * @param generatedFiles the generated files <add> */ <add> public DefaultGenerationContext(GeneratedFiles generatedFiles) { <add> this(new ClassNameGenerator(), generatedFiles, new RuntimeHints()); <add> } <add> <add> /** <add> * Create a new {@link DefaultGenerationContext} instance backed by the <add> * specified items. <add> * @param classNameGenerator the class name generator <add> * @param generatedFiles the generated files <add> * @param runtimeHints the runtime hints <add> */ <add> public DefaultGenerationContext(ClassNameGenerator classNameGenerator, <add> GeneratedFiles generatedFiles, RuntimeHints runtimeHints) { <add> Assert.notNull(classNameGenerator, "'classNameGenerator' must not be null"); <add> Assert.notNull(generatedFiles, "'generatedFiles' must not be null"); <add> Assert.notNull(runtimeHints, "'runtimeHints' must not be null"); <add> this.classNameGenerator = classNameGenerator; <add> this.generatedClasses = new GeneratedClasses(classNameGenerator); <add> this.generatedFiles = generatedFiles; <add> this.runtimeHints = runtimeHints; <add> } <add> <add> <add> @Override <add> public ClassNameGenerator getClassNameGenerator() { <add> return this.classNameGenerator; <add> } <add> <add> @Override <add> public GeneratedClasses getClassGenerator() { <add> return this.generatedClasses; <add> } <add> <add> @Override <add> public GeneratedFiles getGeneratedFiles() { <add> return this.generatedFiles; <add> } <add> <add> @Override <add> public RuntimeHints getRuntimeHints() { <add> return this.runtimeHints; <add> } <add> <add> /** <add> * Write any generated content out to the generated files. <add> */ <add> public void writeGeneratedContent() { <add> try { <add> this.generatedClasses.writeTo(this.generatedFiles); <add> } <add> catch (IOException ex) { <add> throw new IllegalStateException(ex); <add> } <add> } <add> <add>} <ide><path>spring-core/src/main/java/org/springframework/aot/generate/GenerationContext.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.aot.generate; <add> <add>import org.springframework.aot.hint.JavaSerializationHints; <add>import org.springframework.aot.hint.ProxyHints; <add>import org.springframework.aot.hint.ReflectionHints; <add>import org.springframework.aot.hint.ResourceHints; <add>import org.springframework.aot.hint.RuntimeHints; <add> <add>/** <add> * Central interface used for code generation. <add> * <p> <add> * A generation context provides: <add> * <ul> <add> * <li>Support for {@link #getClassNameGenerator() class name generation}.</li> <add> * <li>Central management of all {@link #getGeneratedFiles() generated <add> * files}.</li> <add> * <li>Support for the recording of {@link #getRuntimeHints() runtime <add> * hints}.</li> <add> * </ul> <add> * <add> * @author Phillip Webb <add> * @author Stephane Nicoll <add> * @since 6.0 <add> */ <add>public interface GenerationContext { <add> <add> /** <add> * Return the {@link ClassNameGenerator} being used by the context. Allows <add> * new class names to be generated before they are added to the <add> * {@link #getGeneratedFiles() generated files}. <add> * @return the class name generator <add> * @see #getGeneratedFiles() <add> */ <add> ClassNameGenerator getClassNameGenerator(); <add> <add> /** <add> * Return the {@link GeneratedClasses} being used by the context. Allows a <add> * single generated class to be shared across multiple AOT processors. All <add> * generated classes are written at the end of AOT processing. <add> * @return the generated classes <add> */ <add> ClassGenerator getClassGenerator(); <add> <add> /** <add> * Return the {@link GeneratedFiles} being used by the context. Used to <add> * write resource, java source or class bytecode files. <add> * @return the generated files <add> */ <add> GeneratedFiles getGeneratedFiles(); <add> <add> /** <add> * Return the {@link RuntimeHints} being used by the context. Used to record <add> * {@link ReflectionHints reflection}, {@link ResourceHints resource}, <add> * {@link JavaSerializationHints serialization} and {@link ProxyHints proxy} <add> * hints so that the application can run as a native image. <add> * @return the runtime hints <add> */ <add> RuntimeHints getRuntimeHints(); <add> <add>} <ide><path>spring-core/src/test/java/org/springframework/aot/generate/DefaultGenerationContextTests.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.aot.generate; <add> <add>import org.junit.jupiter.api.Test; <add> <add>import org.springframework.aot.hint.RuntimeHints; <add> <add>import static org.assertj.core.api.Assertions.assertThat; <add>import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; <add> <add>/** <add> * Tests for {@link DefaultGenerationContext}. <add> * <add> * @author Phillip Webb <add> * @author Stephane Nicoll <add> */ <add>class DefaultGenerationContextTests { <add> <add> private final ClassNameGenerator classNameGenerator = new ClassNameGenerator(); <add> <add> private final GeneratedFiles generatedFiles = new InMemoryGeneratedFiles(); <add> <add> private final RuntimeHints runtimeHints = new RuntimeHints(); <add> <add> <add> @Test <add> void createWithOnlyGeneratedFilesCreatesContext() { <add> DefaultGenerationContext context = new DefaultGenerationContext( <add> this.generatedFiles); <add> assertThat(context.getClassNameGenerator()) <add> .isInstanceOf(ClassNameGenerator.class); <add> assertThat(context.getGeneratedFiles()).isSameAs(this.generatedFiles); <add> assertThat(context.getRuntimeHints()).isInstanceOf(RuntimeHints.class); <add> } <add> <add> @Test <add> void createCreatesContext() { <add> DefaultGenerationContext context = new DefaultGenerationContext( <add> this.classNameGenerator, this.generatedFiles, this.runtimeHints); <add> assertThat(context.getClassNameGenerator()).isNotNull(); <add> assertThat(context.getGeneratedFiles()).isNotNull(); <add> assertThat(context.getRuntimeHints()).isNotNull(); <add> } <add> <add> @Test <add> void createWhenClassNameGeneratorIsNullThrowsException() { <add> assertThatIllegalArgumentException() <add> .isThrownBy(() -> new DefaultGenerationContext(null, this.generatedFiles, <add> this.runtimeHints)) <add> .withMessage("'classNameGenerator' must not be null"); <add> } <add> <add> @Test <add> void createWhenGeneratedFilesIsNullThrowsException() { <add> assertThatIllegalArgumentException() <add> .isThrownBy(() -> new DefaultGenerationContext(this.classNameGenerator, <add> null, this.runtimeHints)) <add> .withMessage("'generatedFiles' must not be null"); <add> } <add> <add> @Test <add> void createWhenRuntimeHintsIsNullThrowsException() { <add> assertThatIllegalArgumentException() <add> .isThrownBy(() -> new DefaultGenerationContext(this.classNameGenerator, <add> this.generatedFiles, null)) <add> .withMessage("'runtimeHints' must not be null"); <add> } <add> <add> @Test <add> void getClassNameGeneratorReturnsClassNameGenerator() { <add> DefaultGenerationContext context = new DefaultGenerationContext( <add> this.classNameGenerator, this.generatedFiles, this.runtimeHints); <add> assertThat(context.getClassNameGenerator()).isSameAs(this.classNameGenerator); <add> } <add> <add> @Test <add> void getGeneratedFilesReturnsGeneratedFiles() { <add> DefaultGenerationContext context = new DefaultGenerationContext( <add> this.classNameGenerator, this.generatedFiles, this.runtimeHints); <add> assertThat(context.getGeneratedFiles()).isSameAs(this.generatedFiles); <add> } <add> <add> @Test <add> void getRuntimeHintsReturnsRuntimeHints() { <add> DefaultGenerationContext context = new DefaultGenerationContext( <add> this.classNameGenerator, this.generatedFiles, this.runtimeHints); <add> assertThat(context.getRuntimeHints()).isSameAs(this.runtimeHints); <add> } <add> <add>}
3
Go
Go
add vxfs magic number, fixes
e1c5e9b5610e46bf9526dafcbfba3332fe1983e0
<ide><path>daemon/graphdriver/driver_linux.go <ide> const ( <ide> FsMagicSmbFs = FsMagic(0x0000517B) <ide> FsMagicSquashFs = FsMagic(0x73717368) <ide> FsMagicTmpFs = FsMagic(0x01021994) <add> FsMagicVxFS = FsMagic(0xa501fcf5) <ide> FsMagicXfs = FsMagic(0x58465342) <ide> FsMagicZfs = FsMagic(0x2fc12fc1) <ide> ) <ide> var ( <ide> FsMagicSquashFs: "squashfs", <ide> FsMagicTmpFs: "tmpfs", <ide> FsMagicUnsupported: "unsupported", <add> FsMagicVxFS: "vxfs", <ide> FsMagicXfs: "xfs", <ide> FsMagicZfs: "zfs", <ide> }
1
Text
Text
fix small typos
a612a5ba3fddb6f1634ced0f2bafe3341ea50466
<ide><path>website/docs/usage/layers-architectures.md <ide> that we want to classify as being related or not. As these candidate pairs are <ide> typically formed within one document, this function takes a [`Doc`](/api/doc) as <ide> input and outputs a `List` of `Span` tuples. For instance, the following <ide> implementation takes any two entities from the same document, as long as they <del>are within a **maximum distance** (in number of tokens) of eachother: <add>are within a **maximum distance** (in number of tokens) of each other: <ide> <ide> > #### config.cfg (excerpt) <ide> > <ide> def create_instances(max_length: int) -> Callable[[Doc], List[Tuple[Span, Span]] <ide> return get_candidates <ide> ``` <ide> <del>This function in added to the [`@misc` registry](/api/top-level#registry) so we <add>This function is added to the [`@misc` registry](/api/top-level#registry) so we <ide> can refer to it from the config, and easily swap it out for any other candidate <ide> generation function. <ide> <ide><path>website/docs/usage/training.md <ide> In this example we assume a custom function `read_custom_data` which loads or <ide> generates texts with relevant text classification annotations. Then, small <ide> lexical variations of the input text are created before generating the final <ide> [`Example`](/api/example) objects. The `@spacy.registry.readers` decorator lets <del>you register the function creating the custom reader in the `readers` <add>you register the function creating the custom reader in the `readers` <ide> [registry](/api/top-level#registry) and assign it a string name, so it can be <ide> used in your config. All arguments on the registered function become available <ide> as **config settings** – in this case, `source`.
2
Go
Go
add support for extra_hosts in composefile v3
f32869d956eb175f88fd0b16992d2377d8eae79c
<ide><path>cli/command/stack/deploy.go <ide> func convertService( <ide> Command: service.Entrypoint, <ide> Args: service.Command, <ide> Hostname: service.Hostname, <add> Hosts: convertExtraHosts(service.ExtraHosts), <ide> Env: convertEnvironment(service.Environment), <ide> Labels: getStackLabels(namespace.name, service.Labels), <ide> Dir: service.WorkingDir, <ide> func convertService( <ide> return serviceSpec, nil <ide> } <ide> <add>func convertExtraHosts(extraHosts map[string]string) []string { <add> hosts := []string{} <add> for host, ip := range extraHosts { <add> hosts = append(hosts, fmt.Sprintf("%s %s", host, ip)) <add> } <add> return hosts <add>} <add> <ide> func convertRestartPolicy(restart string, source *composetypes.RestartPolicy) (*swarm.RestartPolicy, error) { <ide> // TODO: log if restart is being ignored <ide> if source == nil {
1
Ruby
Ruby
fix rdoc list markup in `databasetasks`. [ci skip]
31af8c90b60dc475fd80d2919bfb874b4acc4507
<ide><path>activerecord/lib/active_record/tasks/database_tasks.rb <ide> class DatabaseNotSupported < StandardError; end # :nodoc: <ide> # <ide> # The possible config values are: <ide> # <del> # * +env+: current environment (like Rails.env). <del> # * +database_configuration+: configuration of your databases (as in +config/database.yml+). <del> # * +db_dir+: your +db+ directory. <del> # * +fixtures_path+: a path to fixtures directory. <del> # * +migrations_paths+: a list of paths to directories with migrations. <del> # * +seed_loader+: an object which will load seeds, it needs to respond to the +load_seed+ method. <del> # * +root+: a path to the root of the application. <add> # * +env+: current environment (like Rails.env). <add> # * +database_configuration+: configuration of your databases (as in +config/database.yml+). <add> # * +db_dir+: your +db+ directory. <add> # * +fixtures_path+: a path to fixtures directory. <add> # * +migrations_paths+: a list of paths to directories with migrations. <add> # * +seed_loader+: an object which will load seeds, it needs to respond to the +load_seed+ method. <add> # * +root+: a path to the root of the application. <ide> # <ide> # Example usage of +DatabaseTasks+ outside Rails could look as such: <ide> #
1
Ruby
Ruby
update expected versions for mojave
1cf2ea79cf1e0f32f6db5cc56614357db5ecfbbe
<ide><path>Library/Homebrew/os/mac/xcode.rb <ide> def latest_version <ide> # on the older supported platform for that Xcode release, i.e there's no <ide> # CLT package for 10.11 that contains the Clang version from Xcode 8. <ide> case MacOS.version <del> when "10.14" then "1000.10.38" <add> when "10.14" then "1000.10.43.1" <ide> when "10.13" then "902.0.39.2" <ide> when "10.12" then "900.0.39.2" <ide> when "10.11" then "800.0.42.1" <ide> def latest_version <ide> <ide> def minimum_version <ide> case MacOS.version <add> when "10.14" then "10.0.0" <ide> when "10.13" then "9.0.0" <ide> when "10.12" then "8.0.0" <ide> else "1.0.0"
1
Javascript
Javascript
remove require() for backburner instance
872eb97fad1bd7f8f34001182cc9b37d06f82858
<ide><path>packages/ember-metal/lib/tags.js <ide> import { CONSTANT_TAG, DirtyableTag } from '@glimmer/reference'; <ide> import { meta as metaFor } from './meta'; <del>import require from 'require'; <add>import run from './run_loop'; <ide> <ide> let hasViews = () => false; <ide> <ide> export function markObjectAsDirty(meta, propertyKey) { <ide> let backburner; <ide> function ensureRunloop() { <ide> if (backburner === undefined) { <del> // TODO why does this need to be lazy <del> backburner = require('ember-metal').run.backburner; <add> backburner = run.backburner; <ide> } <ide> <ide> if (hasViews()) {
1
Ruby
Ruby
set default_formula to gnupg (2.1.x)
ca303f6195bbe0a8cc47e87a6fa530a35d3b6b5e
<ide><path>Library/Homebrew/requirements/gpg2_requirement.rb <ide> <ide> class GPG2Requirement < Requirement <ide> fatal true <del> default_formula "gnupg2" <add> default_formula "gnupg" <ide> <ide> # MacGPG2/GPGTools installs GnuPG 2.0.x as a vanilla `gpg` symlink <ide> # pointing to `gpg2`, as do we. Ensure we're actually using a 2.0 `gpg`.
1
Ruby
Ruby
simplify package uninstallation
1a4874dc6253f2eb2d077fbfc40ae88457a4ba40
<ide><path>Library/Homebrew/cask/pkg.rb <ide> def uninstall <ide> odebug "Deleting pkg files" <ide> @command.run!( <ide> "/usr/bin/xargs", <del> args: [ <del> "-0", "--", "/bin/rm", "--" <del> ], <add> args: ["-0", "--", "/bin/rm", "--"], <ide> input: pkgutil_bom_files.join("\0"), <ide> sudo: true, <ide> ) <ide> def uninstall <ide> odebug "Deleting pkg symlinks and special files" <ide> @command.run!( <ide> "/usr/bin/xargs", <del> args: [ <del> "-0", "--", "/bin/rm", "--" <del> ], <add> args: ["-0", "--", "/bin/rm", "--"], <ide> input: pkgutil_bom_specials.join("\0"), <ide> sudo: true, <ide> ) <ide> end <ide> <ide> unless pkgutil_bom_dirs.empty? <ide> odebug "Deleting pkg directories" <del> deepest_path_first(pkgutil_bom_dirs).each do |dir| <del> with_full_permissions(dir) do <del> clean_broken_symlinks(dir) <del> clean_ds_store(dir) <del> rmdir(dir) <del> end <del> end <add> rmdir(deepest_path_first(pkgutil_bom_dirs)) <ide> end <ide> <del> if root.directory? && !MacOS.undeletable?(root) <del> clean_ds_store(root) <del> rmdir(root) <del> end <add> rmdir(root) unless MacOS.undeletable?(root) <ide> <ide> forget <ide> end <ide> def special?(path) <ide> path.symlink? || path.chardev? || path.blockdev? <ide> end <ide> <del> sig { params(path: Pathname).void } <add> # Helper script to delete empty directories after deleting `.DS_Store` files and broken symlinks. <add> # Needed in order to execute all file operations with `sudo`. <add> RMDIR_SH = <<~'BASH' <add> set -euo pipefail <add> <add> for path in "${@}"; do <add> if [[ -e "${path}/.DS_Store" ]]; then <add> /bin/rm -f "${path}/.DS_Store" <add> fi <add> <add> # Some packages leave broken symlinks around; we clean them out before <add> # attempting to `rmdir` to prevent extra cruft from accumulating. <add> /usr/bin/find "${path}" -mindepth 1 -maxdepth 1 -type l ! -exec /bin/test -e {} \; -delete <add> <add> if [[ -L "${path}" ]]; then <add> # Delete directory symlink. <add> /bin/rm "${path}" <add> elif [[ -d "${path}" ]]; then <add> # Delete directory if empty. <add> /usr/bin/find "${path}" -maxdepth 0 -type d -empty -exec /bin/rmdir {} \; <add> else <add> # Try `rmdir` anyways to show a proper error. <add> /bin/rmdir "${path}" <add> fi <add> done <add> BASH <add> private_constant :RMDIR_SH <add> <add> sig { params(path: T.any(Pathname, T::Array[Pathname])).void } <ide> def rmdir(path) <del> return unless path.children.empty? <del> <del> if path.symlink? <del> @command.run!("/bin/rm", args: ["-f", "--", path], sudo: true) <del> else <del> @command.run!("/bin/rmdir", args: ["--", path], sudo: true) <del> end <del> end <del> <del> sig { params(path: Pathname, _block: T.proc.void).void } <del> def with_full_permissions(path, &_block) <del> original_mode = (path.stat.mode % 01000).to_s(8) <del> original_flags = @command.run!("/usr/bin/stat", args: ["-f", "%Of", "--", path]).stdout.chomp <del> <del> @command.run!("/bin/chmod", args: ["--", "777", path], sudo: true) <del> yield <del> ensure <del> if path.exist? # block may have removed dir <del> @command.run!("/bin/chmod", args: ["--", original_mode, path], sudo: true) <del> @command.run!("/usr/bin/chflags", args: ["--", original_flags, path], sudo: true) <del> end <add> @command.run!( <add> "/usr/bin/xargs", <add> args: ["-0", "--", "/bin/bash", "-c", RMDIR_SH, "--"], <add> input: Array(path).join("\0"), <add> sudo: true, <add> ) <ide> end <ide> <ide> sig { params(paths: T::Array[Pathname]).returns(T::Array[Pathname]) } <ide> def deepest_path_first(paths) <ide> paths.sort_by { |path| -path.to_s.split(File::SEPARATOR).count } <ide> end <del> <del> sig { params(dir: Pathname).void } <del> def clean_ds_store(dir) <del> return unless (ds_store = dir.join(".DS_Store")).exist? <del> <del> @command.run!("/bin/rm", args: ["--", ds_store], sudo: true) <del> end <del> <del> # Some packages leave broken symlinks around; we clean them out before <del> # attempting to `rmdir` to prevent extra cruft from accumulating. <del> sig { params(dir: Pathname).void } <del> def clean_broken_symlinks(dir) <del> dir.children.select(&method(:broken_symlink?)).each do |path| <del> @command.run!("/bin/rm", args: ["--", path], sudo: true) <del> end <del> end <del> <del> sig { params(path: Pathname).returns(T::Boolean) } <del> def broken_symlink?(path) <del> path.symlink? && !path.exist? <del> end <ide> end <ide> end <ide><path>Library/Homebrew/test/cask/pkg_spec.rb <ide> allow(pkg).to receive(:root).and_return(fake_root) <ide> allow(pkg).to receive(:forget) <ide> <add> # This is expected to fail in tests since we don't use `sudo`. <add> allow(fake_system_command).to receive(:run!).and_call_original <add> expect(fake_system_command).to receive(:run!).with( <add> "/usr/bin/xargs", <add> args: ["-0", "--", "/bin/bash", "-c", a_string_including("/bin/rmdir"), "--"], <add> input: [fake_dir].join("\0"), <add> sudo: true, <add> ).and_return(instance_double(SystemCommand::Result, stdout: "")) <add> <ide> pkg.uninstall <ide> <ide> expect(fake_dir).to be_a_directory
2
Text
Text
clarify changes in readableflowing
3ebe7535b456771078368ba72345f8d2e16ce695
<ide><path>doc/api/stream.md <ide> pass.unpipe(writable); <ide> // readableFlowing is now false. <ide> <ide> pass.on('data', (chunk) => { console.log(chunk.toString()); }); <add>// readableFlowing is still false. <ide> pass.write('ok'); // Will not emit 'data'. <ide> pass.resume(); // Must be called to make stream emit 'data'. <add>// readableFlowing is now true. <ide> ``` <ide> <ide> While `readable.readableFlowing` is `false`, data may be accumulating
1
Javascript
Javascript
fix typo in breakpoint config
c082972b9393693096a2dc857ce09039ef154903
<ide><path>examples/with-stitches/stitches.config.js <ide> export const { css, styled, global, getCssString } = createCss({ <ide> }), <ide> }, <ide> media: { <del> bp1: '@media (min-width: 520px)', <del> bp2: '@media (min-width: 900px)', <add> bp1: '(min-width: 520px)', <add> bp2: '(min-width: 900px)', <ide> }, <ide> })
1
Python
Python
fix spanish noun_chunks (resolves )
686225eaddd56fac86cb18a3e172d84371ea8be1
<ide><path>spacy/lang/es/syntax_iterators.py <ide> <ide> def noun_chunks(obj): <ide> doc = obj.doc <del> np_label = doc.vocab.strings['NP'] <del> left_labels = ['det', 'fixed', 'neg'] #['nunmod', 'det', 'appos', 'fixed'] <add> np_label = doc.vocab.strings.add('NP') <add> left_labels = ['det', 'fixed', 'neg'] # ['nunmod', 'det', 'appos', 'fixed'] <ide> right_labels = ['flat', 'fixed', 'compound', 'neg'] <ide> stop_labels = ['punct'] <ide> np_left_deps = [doc.vocab.strings[label] for label in left_labels] <ide> np_right_deps = [doc.vocab.strings[label] for label in right_labels] <ide> stop_deps = [doc.vocab.strings[label] for label in stop_labels] <add> <add> def noun_bounds(root): <add> left_bound = root <add> for token in reversed(list(root.lefts)): <add> if token.dep in np_left_deps: <add> left_bound = token <add> right_bound = root <add> for token in root.rights: <add> if (token.dep in np_right_deps): <add> left, right = noun_bounds(token) <add> if list(filter(lambda t: is_verb_token(t) or t.dep in stop_deps, <add> doc[left_bound.i: right.i])): <add> break <add> else: <add> right_bound = right <add> return left_bound, right_bound <add> <ide> token = doc[0] <ide> while token and token.i < len(doc): <ide> if token.pos in [PROPN, NOUN, PRON]: <ide> def next_token(token): <ide> return None <ide> <ide> <del>def noun_bounds(root): <del> left_bound = root <del> for token in reversed(list(root.lefts)): <del> if token.dep in np_left_deps: <del> left_bound = token <del> right_bound = root <del> for token in root.rights: <del> if (token.dep in np_right_deps): <del> left, right = noun_bounds(token) <del> if list(filter(lambda t: is_verb_token(t) or t.dep in stop_deps, <del> doc[left_bound.i: right.i])): <del> break <del> else: <del> right_bound = right <del> return left_bound, right_bound <del> <del> <ide> SYNTAX_ITERATORS = { <ide> 'noun_chunks': noun_chunks <ide> }
1
PHP
PHP
add docblock and comment
8c36b31e36f9073edaa1672e892d81e819528fd1
<ide><path>src/Illuminate/Database/Eloquent/Model.php <ide> protected function performInsert(Builder $query, array $options = []) <ide> <ide> $this->wasRecentlyCreated = true; <ide> <add> // When inserting newly created models, they might have default values for some <add> // attributes. So it's important that we refresh the model after it has been <add> // saved so that any missing fields with database defaults are populated. <ide> $this->refresh(); <ide> <ide> $this->fireModelEvent('created', false); <ide> <ide> return true; <ide> } <ide> <add> /** <add> * Refresh the current model with the current attributes from the database. <add> * @return void <add> */ <ide> protected function refresh() <ide> { <ide> $fresh = $this->fresh();
1
Javascript
Javascript
allow enfile in test-worker-init-failure
97d9b9c90eb5ba9943d451e85e115ddf95f9f1d4
<ide><path>test/parallel/test-worker-init-failure.js <ide> if (process.argv[2] === 'child') { <ide> }); <ide> <ide> // We want to test that if there is an error in a constrained running <del> // environment, it will be one of `EMFILE` or `ERR_WORKER_INIT_FAILED`. <add> // environment, it will be one of `ENFILE`, `EMFILE`, or <add> // `ERR_WORKER_INIT_FAILED`. <add> const allowableCodes = ['ERR_WORKER_INIT_FAILED', 'EMFILE', 'ENFILE']; <add> <ide> // `common.mustCall*` cannot be used here as in some environments <ide> // (i.e. single cpu) `ulimit` may not lead to such an error. <del> <ide> worker.on('error', (e) => { <del> assert.ok(e.code === 'ERR_WORKER_INIT_FAILED' || e.code === 'EMFILE'); <add> assert.ok(allowableCodes.includes(e.code), `${e.code} not expected`); <ide> }); <ide> } <ide>
1
Text
Text
refine spaces in example from vm.md
a235e670a820107210be27e0cd266164763fb014
<ide><path>doc/api/vm.md <ide> to the `http` module passed to it. For instance: <ide> 'use strict'; <ide> const vm = require('vm'); <ide> <del>const code = <del>`(function(require) { <add>const code = ` <add>(function(require) { <add> const http = require('http'); <ide> <del> const http = require('http'); <add> http.createServer((request, response) => { <add> response.writeHead(200, { 'Content-Type': 'text/plain' }); <add> response.end('Hello World\\n'); <add> }).listen(8124); <ide> <del> http.createServer( (request, response) => { <del> response.writeHead(200, {'Content-Type': 'text/plain'}); <del> response.end('Hello World\\n'); <del> }).listen(8124); <del> <del> console.log('Server running at http://127.0.0.1:8124/'); <del> })`; <add> console.log('Server running at http://127.0.0.1:8124/'); <add>})`; <ide> <ide> vm.runInThisContext(code)(require); <ide> ```
1
Javascript
Javascript
fix typo in messagechannel test
74de55533de68e8a70663c9c38d175834994de31
<ide><path>test/parallel/test-worker-message-port-infinite-message-loop.js <ide> const { MessageChannel } = require('worker_threads'); <ide> <ide> // Make sure that an infinite asynchronous .on('message')/postMessage loop <ide> // does not lead to a stack overflow and does not starve the event loop. <del>// We schedule timeouts both from before the the .on('message') handler and <add>// We schedule timeouts both from before the .on('message') handler and <ide> // inside of it, which both should run. <ide> <ide> const { port1, port2 } = new MessageChannel();
1
PHP
PHP
add assert to clarify what happened
5dfed195412e81754bbd4d36359d9851d031c29a
<ide><path>tests/TestCase/ORM/MarshallerTest.php <ide> public function testMergeManyWithAppend() { <ide> $this->assertNotSame($entities[0], $result[0]); <ide> $this->assertSame($entities[1], $result[0]); <ide> $this->assertEquals('Changed 2', $result[0]->comment); <add> <add> $this->assertEquals('Comment 1', $result[1]->comment); <ide> } <ide> <ide> /**
1
Mixed
Javascript
enable autoskip for time scale to match others
a33086bfc13d08f6421ea15ef91b56331d2f2551
<ide><path>docs/docs/getting-started/v3-migration.md <ide> options: { <ide> } <ide> ``` <ide> <del>Also, the time scale option `distribution: 'series'` was removed and a new scale type `timeseries` was introduced in its place. <add>* The time scale option `distribution: 'series'` was removed and a new scale type `timeseries` was introduced in its place <add>* In the time scale, `autoSkip` is now enabled by default for consistency with the other scales <ide> <ide> #### Animations <ide> <ide><path>src/scales/scale.time.js <ide> const defaultConfig = { <ide> displayFormats: {} <ide> }, <ide> ticks: { <del> autoSkip: false, <del> <ide> /** <ide> * Ticks generation input values: <ide> * - 'auto': generates "optimal" ticks based on scale size and time options. <ide><path>test/specs/scale.time.tests.js <ide> describe('Time scale tests', function() { <ide> padding: 0, <ide> display: true, <ide> callback: defaultConfig.ticks.callback, // make this nicer, then check explicitly below, <del> autoSkip: false, <add> autoSkip: true, <ide> autoSkipPadding: 0, <ide> labelOffset: 0, <ide> minor: {},
3
Ruby
Ruby
add example of params to button_to docs [ci skip]
4bfc35a4f9ce8bd2df00b92ba730787977947d78
<ide><path>actionview/lib/action_view/helpers/url_helper.rb <ide> def link_to(name = nil, options = nil, html_options = nil, &block) <ide> # <%= button_to "New", action: "new" %> <ide> # # => "<form method="post" action="/controller/new" class="button_to"> <ide> # # <button type="submit">New</button> <add> # # <input name="authenticity_token" type="hidden" value="10f2163b45388899ad4d5ae948988266befcb6c3d1b2451cf657a0c293d605a6"/> <ide> # # </form>" <ide> # <ide> # <%= button_to "New", new_article_path %> <ide> # # => "<form method="post" action="/articles/new" class="button_to"> <ide> # # <button type="submit">New</button> <add> # # <input name="authenticity_token" type="hidden" value="10f2163b45388899ad4d5ae948988266befcb6c3d1b2451cf657a0c293d605a6"/> <add> # # </form>" <add> # <add> # <%= button_to "New", new_article_path, params: { time: Time.now } %> <add> # # => "<form method="post" action="/articles/new" class="button_to"> <add> # # <button type="submit">New</button> <add> # # <input name="authenticity_token" type="hidden" value="10f2163b45388899ad4d5ae948988266befcb6c3d1b2451cf657a0c293d605a6"/> <add> # # <input type="hidden" name="time" value="2021-04-08 14:06:09 -0500"> <ide> # # </form>" <ide> # <ide> # <%= button_to [:make_happy, @user] do %> <ide> def link_to(name = nil, options = nil, html_options = nil, &block) <ide> # # <button type="submit"> <ide> # # Make happy <strong><%= @user.name %></strong> <ide> # # </button> <add> # # <input name="authenticity_token" type="hidden" value="10f2163b45388899ad4d5ae948988266befcb6c3d1b2451cf657a0c293d605a6"/> <ide> # # </form>" <ide> # <ide> # <%= button_to "New", { action: "new" }, form_class: "new-thing" %> <ide> # # => "<form method="post" action="/controller/new" class="new-thing"> <ide> # # <button type="submit">New</button> <add> # # <input name="authenticity_token" type="hidden" value="10f2163b45388899ad4d5ae948988266befcb6c3d1b2451cf657a0c293d605a6"/> <ide> # # </form>" <ide> # <del> # <ide> # <%= button_to "Create", { action: "create" }, remote: true, form: { "data-type" => "json" } %> <ide> # # => "<form method="post" action="/images/create" class="button_to" data-remote="true" data-type="json"> <ide> # # <button type="submit">Create</button> <ide> # # <input name="authenticity_token" type="hidden" value="10f2163b45388899ad4d5ae948988266befcb6c3d1b2451cf657a0c293d605a6"/> <ide> # # </form>" <ide> # <del> # <ide> # <%= button_to "Delete Image", { action: "delete", id: @image.id }, <ide> # method: :delete, data: { confirm: "Are you sure?" } %> <ide> # # => "<form method="post" action="/images/delete/1" class="button_to"> <ide> def link_to(name = nil, options = nil, html_options = nil, &block) <ide> # # <input name="authenticity_token" type="hidden" value="10f2163b45388899ad4d5ae948988266befcb6c3d1b2451cf657a0c293d605a6"/> <ide> # # </form>" <ide> # <del> # <ide> # <%= button_to('Destroy', 'http://www.example.com', <ide> # method: :delete, remote: true, data: { confirm: 'Are you sure?', disable_with: 'loading...' }) %> <ide> # # => "<form class='button_to' method='post' action='http://www.example.com' data-remote='true'>
1
PHP
PHP
update doc block
328f505d6cac8bffdb6dc103d60af0b7ce54066b
<ide><path>src/Illuminate/Support/Testing/Fakes/MailFake.php <ide> public function assertSent($mailable, $callback = null) <ide> } <ide> <ide> /** <del> * Determine if a mailable was sent based on a truth-test callback. <add> * Determine if a mailable was not sent based on a truth-test callback. <ide> * <ide> * @param string $mailable <ide> * @param callable|null $callback
1
PHP
PHP
add withstringbody method
738e44e6fdac3fe5ff0f7f1117b40eda47787713
<ide><path>src/Http/Response.php <ide> public function withFile($path, array $options = []) <ide> return $new; <ide> } <ide> <add> /** <add> * Convenience method to set a string into the response body <add> * <add> * @param string $string The string to be sent <add> * @return static <add> */ <add> public function withStringBody($string) <add> { <add> $new = clone $this; <add> $new->_createStream(); <add> $new->stream->write((string)$string); <add> <add> return $new; <add> } <add> <ide> /** <ide> * Validate a file path is a valid response body. <ide> * <ide><path>tests/TestCase/Network/ResponseTest.php <ide> public function testWithBody() <ide> $this->assertEquals('', $result); <ide> } <ide> <add> /** <add> * Test with string body. <add> * <add> * @return void <add> */ <add> public function testWithStringBody() <add> { <add> $response = new Response(); <add> $newResponse = $response->withStringBody('Foo'); <add> $body = $newResponse->getBody(); <add> $this->assertSame('Foo', (string)$body); <add> $this->assertNotSame($response, $newResponse); <add> <add> $response = new Response(); <add> $newResponse = $response->withStringBody(''); <add> $body = $newResponse->getBody(); <add> $this->assertSame('', (string)$body); <add> $this->assertNotSame($response, $newResponse); <add> <add> $response = new Response(); <add> $newResponse = $response->withStringBody(null); <add> $body = $newResponse->getBody(); <add> $this->assertSame('', (string)$body); <add> $this->assertNotSame($response, $newResponse); <add> <add> $response = new Response(); <add> $newResponse = $response->withStringBody(1337); <add> $body = $newResponse->getBody(); <add> $this->assertSame('1337', (string)$body); <add> $this->assertNotSame($response, $newResponse); <add> } <add> <add> /** <add> * Test with string body with passed array. <add> * <add> * This should produce an "Array to string conversion" error <add> * which gets thrown as a \PHPUnit\Framework\Error\Error Exception by PHPUnit. <add> * <add> * @expectedException \PHPUnit\Framework\Error\Error <add> * @expectedExceptionMessage Array to string conversion <add> * @return void <add> */ <add> public function testWithStringBodyArray() <add> { <add> $response = new Response(); <add> $newResponse = $response->withStringBody(['foo' => 'bar']); <add> $body = $newResponse->getBody(); <add> $this->assertSame('', (string)$body); <add> $this->assertNotSame($response, $newResponse); <add> } <add> <ide> /** <ide> * Test get Body. <ide> *
2
PHP
PHP
tweak the csrf token a little more
aa55f3441fbc1ec78cf96f2c76ab83e8d6d58f82
<ide><path>laravel/session.php <ide> public static function start(Driver $driver) <ide> { <ide> static::$exists = false; <ide> <add> static::$session = array('id' => Str::random(40), 'data' => array()); <add> } <add> <add> if ( ! static::has('csrf_token')) <add> { <ide> // A CSRF token is stored in every session. The token is used by the <ide> // Form class and the "csrf" filter to protect the application from <ide> // cross-site request forgery attacks. The token is simply a long, <ide> // random string which should be posted with each request. <del> $csrf_token = Str::random(40); <del> <del> static::$session = array('id' => Str::random(40), 'data' => compact('csrf_token')); <add> static::put('csrf_token', Str::random(40)); <ide> } <ide> } <ide>
1
Python
Python
fix the timeout error on travis
8b59e31d2b1d854a1eae585db7bd1582ef95c978
<ide><path>tests/keras/utils/data_utils_test.py <ide> from keras import backend as K <ide> <ide> pytestmark = pytest.mark.skipif( <del> K.backend() == 'tensorflow' and 'TRAVIS_PYTHON_VERSION' in os.environ, <add> K.backend() in {'tensorflow', 'cntk'} and 'TRAVIS_PYTHON_VERSION' in os.environ, <ide> reason='Temporarily disabled until the use_multiprocessing problem is solved') <ide> <ide> if sys.version_info < (3,): <ide><path>tests/test_multiprocessing.py <ide> from keras import backend as K <ide> <ide> pytestmark = pytest.mark.skipif( <del> K.backend() == 'tensorflow' and 'TRAVIS_PYTHON_VERSION' in os.environ, <add> K.backend() in {'tensorflow', 'cntk'} and 'TRAVIS_PYTHON_VERSION' in os.environ, <ide> reason='Temporarily disabled until the use_multiprocessing problem is solved') <ide> <ide> STEPS_PER_EPOCH = 100
2
Python
Python
use httplib constants
35620f7b8e7a5c8659427f6c7b1ced929a6ef3dc
<ide><path>libcloud/base.py <ide> class Response(object): <ide> <ide> tree = None <ide> body = None <del> status_code = 200 <add> status_code = httplib.OK <ide> headers = {} <ide> error = None <ide>
1
PHP
PHP
remove config entry
641fcfb60aa47266c5b4767830dc45bad00c561c
<ide><path>config/view.php <ide> realpath(storage_path('framework/views')) <ide> ), <ide> <del> /* <del> |-------------------------------------------------------------------------- <del> | Blade View Modification Checking <del> |-------------------------------------------------------------------------- <del> | <del> | On every request the framework will check to see if a view has expired <del> | to determine if it needs to be recompiled. If you are in production <del> | and precompiling views this feature may be disabled to save time. <del> | <del> */ <del> <del> 'expires' => env('VIEW_CHECK_EXPIRATION', true), <del> <ide> ];
1