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 |
|---|---|---|---|---|---|
Go | Go | use errdefs for errors | e214503789111f76ae08af66cf71740bc6483f99 | <ide><path>image/store.go
<ide> import (
<ide> "sync"
<ide> "time"
<ide>
<add> "github.com/docker/docker/errdefs"
<ide> "github.com/docker/docker/layer"
<ide> "github.com/docker/docker/pkg/system"
<ide> "github.com/opencontainers/go-digest"
<ide> func (is *store) Create(config []byte) (ID, error) {
<ide> }
<ide> }
<ide> if layerCounter > len(img.RootFS.DiffIDs) {
<del> return "", errors.New("too many non-empty layers in History section")
<add> return "", errdefs.InvalidParameter(errors.New("too many non-empty layers in History section"))
<ide> }
<ide>
<ide> dgst, err := is.fs.Set(config)
<ide> if err != nil {
<del> return "", err
<add> return "", errdefs.InvalidParameter(err)
<ide> }
<ide> imageID := IDFromDigest(dgst)
<ide>
<ide> func (is *store) Create(config []byte) (ID, error) {
<ide> var l layer.Layer
<ide> if layerID != "" {
<ide> if !system.IsOSSupported(img.OperatingSystem()) {
<del> return "", system.ErrNotSupportedOperatingSystem
<add> return "", errdefs.InvalidParameter(system.ErrNotSupportedOperatingSystem)
<ide> }
<ide> l, err = is.lss.Get(layerID)
<ide> if err != nil {
<del> return "", errors.Wrapf(err, "failed to get layer %s", layerID)
<add> return "", errdefs.InvalidParameter(errors.Wrapf(err, "failed to get layer %s", layerID))
<ide> }
<ide> }
<ide>
<ide> func (is *store) Create(config []byte) (ID, error) {
<ide> is.images[imageID] = imageMeta
<ide> if err := is.digestSet.Add(imageID.Digest()); err != nil {
<ide> delete(is.images, imageID)
<del> return "", err
<add> return "", errdefs.InvalidParameter(err)
<ide> }
<ide>
<ide> return imageID, nil
<ide> func (is *store) Get(id ID) (*Image, error) {
<ide> // todo: Detect manual insertions and start using them
<ide> config, err := is.fs.Get(id.Digest())
<ide> if err != nil {
<del> return nil, err
<add> return nil, errdefs.NotFound(err)
<ide> }
<ide>
<ide> img, err := NewFromJSON(config)
<ide> if err != nil {
<del> return nil, err
<add> return nil, errdefs.InvalidParameter(err)
<ide> }
<ide> img.computedID = id
<ide>
<ide> func (is *store) Delete(id ID) ([]layer.Metadata, error) {
<ide>
<ide> imageMeta := is.images[id]
<ide> if imageMeta == nil {
<del> return nil, fmt.Errorf("unrecognized image ID %s", id.String())
<add> return nil, errdefs.NotFound(fmt.Errorf("unrecognized image ID %s", id.String()))
<ide> }
<ide> _, err := is.Get(id)
<ide> if err != nil {
<del> return nil, fmt.Errorf("unrecognized image %s, %v", id.String(), err)
<add> return nil, errdefs.NotFound(fmt.Errorf("unrecognized image %s, %v", id.String(), err))
<ide> }
<ide> for id := range imageMeta.children {
<ide> is.fs.DeleteMetadata(id.Digest(), "parent")
<ide> func (is *store) SetParent(id, parent ID) error {
<ide> defer is.Unlock()
<ide> parentMeta := is.images[parent]
<ide> if parentMeta == nil {
<del> return fmt.Errorf("unknown parent image ID %s", parent.String())
<add> return errdefs.NotFound(fmt.Errorf("unknown parent image ID %s", parent.String()))
<ide> }
<ide> if parent, err := is.GetParent(id); err == nil && is.images[parent] != nil {
<ide> delete(is.images[parent].children, id)
<ide> func (is *store) SetParent(id, parent ID) error {
<ide> func (is *store) GetParent(id ID) (ID, error) {
<ide> d, err := is.fs.GetMetadata(id.Digest(), "parent")
<ide> if err != nil {
<del> return "", err
<add> return "", errdefs.NotFound(err)
<ide> }
<ide> return ID(d), nil // todo: validate?
<ide> }
<ide><path>image/store_test.go
<ide> import (
<ide> "fmt"
<ide> "testing"
<ide>
<add> "github.com/docker/docker/errdefs"
<ide> "github.com/docker/docker/layer"
<ide> "gotest.tools/v3/assert"
<ide> is "gotest.tools/v3/assert/cmp"
<ide> func TestRestore(t *testing.T) {
<ide> assert.Check(t, is.Equal("def", img2.Comment))
<ide>
<ide> _, err = imgStore.GetParent(ID(id1))
<add> assert.Check(t, is.ErrorType(err, errdefs.IsNotFound))
<ide> assert.ErrorContains(t, err, "failed to read metadata")
<ide>
<ide> p, err := imgStore.GetParent(ID(id2))
<ide> func TestRestore(t *testing.T) {
<ide>
<ide> invalidPattern := id1.Encoded()[1:6]
<ide> _, err = imgStore.Search(invalidPattern)
<del> assert.ErrorContains(t, err, "No such image")
<add> assert.Check(t, is.ErrorType(err, errdefs.IsNotFound))
<add> assert.Check(t, is.ErrorContains(err, invalidPattern))
<ide> }
<ide>
<ide> func TestAddDelete(t *testing.T) {
<ide> func TestAddDelete(t *testing.T) {
<ide> assert.NilError(t, err)
<ide>
<ide> _, err = imgStore.Get(id1)
<add> assert.Check(t, is.ErrorType(err, errdefs.IsNotFound))
<ide> assert.ErrorContains(t, err, "failed to get digest")
<ide>
<ide> _, err = imgStore.Get(id2)
<ide> assert.NilError(t, err)
<ide>
<ide> _, err = imgStore.GetParent(id2)
<add> assert.Check(t, is.ErrorType(err, errdefs.IsNotFound))
<ide> assert.ErrorContains(t, err, "failed to read metadata")
<ide> }
<ide>
<ide> func TestSearchAfterDelete(t *testing.T) {
<ide> assert.NilError(t, err)
<ide>
<ide> _, err = imgStore.Search(string(id)[:15])
<add> assert.Check(t, is.ErrorType(err, errdefs.IsNotFound))
<ide> assert.ErrorContains(t, err, "No such image")
<ide> }
<ide>
<add>func TestDeleteNotExisting(t *testing.T) {
<add> imgStore, cleanup := defaultImageStore(t)
<add> defer cleanup()
<add>
<add> _, err := imgStore.Delete(ID("i_dont_exists"))
<add> assert.Check(t, is.ErrorType(err, errdefs.IsNotFound))
<add>}
<add>
<ide> func TestParentReset(t *testing.T) {
<ide> imgStore, cleanup := defaultImageStore(t)
<ide> defer cleanup() | 2 |
Ruby | Ruby | prefer a feature check to a version check | 02b716a322d07fbb87eec0ad48f7029da1682648 | <ide><path>activesupport/lib/active_support/core_ext/rexml.rb
<ide> # This fix is identical to rexml-expansion-fix version 1.0.1
<ide>
<ide> # Earlier versions of rexml defined REXML::Version, newer ones REXML::VERSION
<del>unless (defined?(REXML::VERSION) ? REXML::VERSION : REXML::Version) > "3.1.7.2"
<add>unless REXML::Document.respond_to?(:entity_expansion_limit=)
<ide> module REXML
<ide> class Entity < Child
<ide> undef_method :unnormalized | 1 |
Javascript | Javascript | add tests for end event of stream.duplex | 383b1b6d3c5f753798d33ab6758ce8d5313f67e8 | <ide><path>test/parallel/test-stream-duplex-end.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const Duplex = require('stream').Duplex;
<add>
<add>{
<add> const stream = new Duplex({
<add> read() {}
<add> });
<add> assert.strictEqual(stream.allowHalfOpen, true);
<add> stream.on('finish', common.mustNotCall());
<add> assert.strictEqual(stream.listenerCount('end'), 0);
<add> stream.resume();
<add> stream.push(null);
<add>}
<add>
<add>{
<add> const stream = new Duplex({
<add> read() {},
<add> allowHalfOpen: false
<add> });
<add> assert.strictEqual(stream.allowHalfOpen, false);
<add> stream.on('finish', common.mustCall());
<add> assert.strictEqual(stream.listenerCount('end'), 1);
<add> stream.resume();
<add> stream.push(null);
<add>}
<add>
<add>{
<add> const stream = new Duplex({
<add> read() {},
<add> allowHalfOpen: false
<add> });
<add> assert.strictEqual(stream.allowHalfOpen, false);
<add> stream._writableState.ended = true;
<add> stream.on('finish', common.mustNotCall());
<add> assert.strictEqual(stream.listenerCount('end'), 1);
<add> stream.resume();
<add> stream.push(null);
<add>} | 1 |
Python | Python | add tensorboard to run_squad | 326944d627ad166f0e6a6921b7168a2caf31dd1e | <ide><path>examples/run_squad.py
<ide> from torch.utils.data.distributed import DistributedSampler
<ide> from tqdm import tqdm, trange
<ide>
<add>from tensorboardX import SummaryWriter
<add>
<ide> from pytorch_pretrained_bert.file_utils import PYTORCH_PRETRAINED_BERT_CACHE, WEIGHTS_NAME, CONFIG_NAME
<ide> from pytorch_pretrained_bert.modeling import BertForQuestionAnswering, BertConfig
<ide> from pytorch_pretrained_bert.optimization import BertAdam, WarmupLinearSchedule
<ide> def main():
<ide> model = torch.nn.DataParallel(model)
<ide>
<ide> if args.do_train:
<del>
<add> writer = SummaryWriter()
<ide> # Prepare data loader
<del>
<ide> train_examples = read_squad_examples(
<ide> input_file=args.train_file, is_training=True, version_2_with_negative=args.version_2_with_negative)
<ide> cached_train_features_file = args.train_file+'_{0}_{1}_{2}_{3}'.format(
<ide> def main():
<ide> logger.info(" Num steps = %d", num_train_optimization_steps)
<ide>
<ide> model.train()
<del> for _ in trange(int(args.num_train_epochs), desc="Epoch"):
<add> for epoch in trange(int(args.num_train_epochs), desc="Epoch"):
<ide> for step, batch in enumerate(tqdm(train_dataloader, desc="Iteration", disable=args.local_rank not in [-1, 0])):
<ide> if n_gpu == 1:
<ide> batch = tuple(t.to(device) for t in batch) # multi-gpu does scattering it-self
<ide> def main():
<ide> else:
<ide> loss.backward()
<ide> if (step + 1) % args.gradient_accumulation_steps == 0:
<add> writer.add_scalar('lr', optimizer.get_lr()[0], global_step)
<add> writer.add_scalar('loss', loss.item(), global_step)
<ide> if args.fp16:
<ide> # modify learning rate with special warm up BERT uses
<ide> # if args.fp16 is False, BertAdam is used and handles this automatically | 1 |
PHP | PHP | provide retry callback with the attempt count | 96de5cc1753323f4a69ce72d5e7c2a549718670c | <ide><path>src/Illuminate/Support/helpers.php
<ide> function preg_replace_array($pattern, array $replacements, $subject)
<ide> * Retry an operation a given number of times.
<ide> *
<ide> * @param int $times
<del> * @param callable $callback
<add> * @param callable $callback First parameter is the number of attempt
<ide> * @param int $sleep
<ide> * @return mixed
<ide> *
<ide> * @throws \Exception
<ide> */
<ide> function retry($times, callable $callback, $sleep = 0)
<ide> {
<add> $attempt = 0;
<ide> $times--;
<ide>
<ide> beginning:
<add> $attempt++;
<ide> try {
<del> return $callback();
<add> return $callback($attempt);
<ide> } catch (Exception $e) {
<ide> if (! $times) {
<ide> throw $e;
<ide><path>tests/Support/SupportHelpersTest.php
<ide> public function something()
<ide> })->present()->something());
<ide> }
<ide>
<add> public function testRetry()
<add> {
<add> $startTime = microtime(true);
<add>
<add> $attempts = retry(2, function ($attempts) {
<add> if ($attempts > 1) {
<add> return $attempts;
<add> }
<add>
<add> throw new RuntimeException;
<add> }, 100);
<add>
<add> // Make sure we made two attempts
<add> $this->assertEquals(2, $attempts);
<add>
<add> // Make sure we waited 100ms for the first attempt
<add> $this->assertTrue(microtime(true) - $startTime >= 0.1);
<add> }
<add>
<ide> public function testTransform()
<ide> {
<ide> $this->assertEquals(10, transform(5, function ($value) { | 2 |
Mixed | Javascript | improve errors thrown in header validation | 0a84e95cd9293bfcf1e746857921684f0732dd60 | <ide><path>doc/api/errors.md
<ide> more headers.
<ide> Used when an invalid character is found in an HTTP response status message
<ide> (reason phrase).
<ide>
<add><a id="ERR_HTTP_INVALID_HEADER_VALUE"></a>
<add>### ERR_HTTP_INVALID_HEADER_VALUE
<add>
<add>Used to indicate that an invalid HTTP header value has been specified.
<add>
<ide> <a id="ERR_HTTP_INVALID_STATUS_CODE"></a>
<ide> ### ERR_HTTP_INVALID_STATUS_CODE
<ide>
<ide><path>lib/_http_outgoing.js
<ide> function _storeHeader(firstLine, headers) {
<ide>
<ide> function storeHeader(self, state, key, value, validate) {
<ide> if (validate) {
<del> if (typeof key !== 'string' || !key || !checkIsHttpToken(key)) {
<del> throw new errors.TypeError(
<del> 'ERR_INVALID_HTTP_TOKEN', 'Header name', key);
<del> }
<del> if (value === undefined) {
<del> throw new errors.TypeError('ERR_MISSING_ARGS', `header "${key}"`);
<del> } else if (checkInvalidHeaderChar(value)) {
<del> debug('Header "%s" contains invalid characters', key);
<del> throw new errors.TypeError('ERR_INVALID_CHAR', 'header content', key);
<del> }
<add> validateHeader(key, value);
<ide> }
<ide> state.header += key + ': ' + escapeHeaderValue(value) + CRLF;
<ide> matchHeader(self, state, key, value);
<ide> function matchHeader(self, state, field, value) {
<ide> }
<ide> }
<ide>
<del>function validateHeader(msg, name, value) {
<del> if (typeof name !== 'string' || !name || !checkIsHttpToken(name))
<del> throw new errors.TypeError('ERR_INVALID_HTTP_TOKEN', 'Header name', name);
<del> if (value === undefined)
<del> throw new errors.TypeError('ERR_MISSING_ARGS', 'value');
<del> if (msg._header)
<del> throw new errors.Error('ERR_HTTP_HEADERS_SENT', 'set');
<del> if (checkInvalidHeaderChar(value)) {
<add>function validateHeader(name, value) {
<add> let err;
<add> if (typeof name !== 'string' || !name || !checkIsHttpToken(name)) {
<add> err = new errors.TypeError('ERR_INVALID_HTTP_TOKEN', 'Header name', name);
<add> } else if (value === undefined) {
<add> err = new errors.TypeError('ERR_HTTP_INVALID_HEADER_VALUE', value, name);
<add> } else if (checkInvalidHeaderChar(value)) {
<ide> debug('Header "%s" contains invalid characters', name);
<del> throw new errors.TypeError('ERR_INVALID_CHAR', 'header content', name);
<add> err = new errors.TypeError('ERR_INVALID_CHAR', 'header content', name);
<add> }
<add> if (err !== undefined) {
<add> Error.captureStackTrace(err, validateHeader);
<add> throw err;
<ide> }
<ide> }
<add>
<ide> OutgoingMessage.prototype.setHeader = function setHeader(name, value) {
<del> validateHeader(this, name, value);
<add> if (this._header) {
<add> throw new errors.Error('ERR_HTTP_HEADERS_SENT', 'set');
<add> }
<add> validateHeader(name, value);
<ide>
<ide> if (!this[outHeadersKey])
<ide> this[outHeadersKey] = {};
<ide><path>lib/internal/errors.js
<ide> E('ERR_HTTP2_UNSUPPORTED_PROTOCOL',
<ide> E('ERR_HTTP_HEADERS_SENT',
<ide> 'Cannot %s headers after they are sent to the client');
<ide> E('ERR_HTTP_INVALID_CHAR', 'Invalid character in statusMessage.');
<add>E('ERR_HTTP_INVALID_HEADER_VALUE', 'Invalid value "%s" for header "%s"');
<ide> E('ERR_HTTP_INVALID_STATUS_CODE',
<ide> (originalStatusCode) => `Invalid status code: ${originalStatusCode}`);
<ide> E('ERR_HTTP_TRAILER_INVALID',
<ide><path>test/parallel/test-http-mutable-headers.js
<ide> const s = http.createServer(common.mustCall((req, res) => {
<ide> common.expectsError(
<ide> () => res.setHeader('someHeader'),
<ide> {
<del> code: 'ERR_MISSING_ARGS',
<add> code: 'ERR_HTTP_INVALID_HEADER_VALUE',
<ide> type: TypeError,
<del> message: 'The "value" argument must be specified'
<add> message: 'Invalid value "undefined" for header "someHeader"'
<ide> }
<ide> );
<ide> common.expectsError(
<ide><path>test/parallel/test-http-outgoing-proto.js
<ide> assert.throws(() => {
<ide> const outgoingMessage = new OutgoingMessage();
<ide> outgoingMessage.setHeader('test');
<ide> }, common.expectsError({
<del> code: 'ERR_MISSING_ARGS',
<add> code: 'ERR_HTTP_INVALID_HEADER_VALUE',
<ide> type: TypeError,
<del> message: 'The "value" argument must be specified'
<add> message: 'Invalid value "undefined" for header "test"'
<ide> }));
<ide>
<ide> assert.throws(() => {
<ide><path>test/parallel/test-http-write-head.js
<ide> const s = http.createServer(common.mustCall((req, res) => {
<ide> common.expectsError(
<ide> () => res.setHeader('foo', undefined),
<ide> {
<del> code: 'ERR_MISSING_ARGS',
<add> code: 'ERR_HTTP_INVALID_HEADER_VALUE',
<ide> type: TypeError,
<del> message: 'The "value" argument must be specified'
<add> message: 'Invalid value "undefined" for header "foo"'
<ide> }
<ide> );
<ide> | 6 |
Ruby | Ruby | put exit statements in both conditional branches | 753adbb0ce1498bd74d1c2935a4394497624b373 | <ide><path>Library/Homebrew/cmd/upgrade.rb
<ide> def upgrade
<ide>
<ide> if ARGV.named.empty?
<ide> outdated = Homebrew.outdated_brews
<add> exit 0 if outdated.empty?
<ide> else
<ide> outdated = ARGV.formulae.select do |f|
<ide> if f.installed? | 1 |
Ruby | Ruby | avoid extra hash creation | 7b1fe264724e35182f6e7799163feba93a6da07f | <ide><path>actionpack/lib/action_dispatch/http/cache.rb
<ide> def handle_conditional_get!
<ide> end
<ide>
<ide> def merge_and_normalize_cache_control!(cache_control)
<del> control = {}
<ide> cc_headers = cache_control_headers
<ide> if extras = cc_headers.delete(:extras)
<ide> cache_control[:extras] ||= []
<ide> cache_control[:extras] += extras
<ide> cache_control[:extras].uniq!
<ide> end
<ide>
<del> control.merge! cc_headers
<add> control = cc_headers
<ide> control.merge! cache_control
<ide>
<ide> if control.empty? | 1 |
Python | Python | simplify code, delete redundancy line | 22a465a91fb4f3708c8c9437db8765e38fad8ae0 | <ide><path>examples/run_classifier.py
<ide> def main():
<ide> optimizer.zero_grad()
<ide> global_step += 1
<ide>
<del> if args.do_train:
<ide> # Save a trained model and the associated configuration
<ide> model_to_save = model.module if hasattr(model, 'module') else model # Only save the model it-self
<ide> output_model_file = os.path.join(args.output_dir, WEIGHTS_NAME) | 1 |
PHP | PHP | add the abstract uuid type | 1dc3029e1d7b0838c01685ddefef14e8e7536a05 | <ide><path>Cake/Database/Schema/MysqlSchema.php
<ide> protected function _convertColumn($column) {
<ide> if (strpos($col, 'int') !== false) {
<ide> return ['type' => 'integer', 'length' => $length];
<ide> }
<add> if ($col === 'char' && $length === 36) {
<add> return ['type' => 'uuid', 'length' => null];
<add> }
<ide> if ($col === 'char') {
<ide> return ['type' => 'string', 'fixed' => true, 'length' => $length];
<ide> }
<ide><path>Cake/Database/Schema/PostgresSchema.php
<ide> protected function _convertColumn($column) {
<ide> return ['type' => 'string', 'length' => 39];
<ide> }
<ide> if ($col === 'uuid') {
<del> return ['type' => 'string', 'fixed' => true, 'length' => 36];
<add> return ['type' => 'uuid', 'length' => null];
<ide> }
<ide> if ($col === 'char' || $col === 'character') {
<ide> return ['type' => 'string', 'fixed' => true, 'length' => $length];
<ide><path>Cake/Database/Schema/SqliteSchema.php
<ide> protected function _convertColumn($column) {
<ide> if (strpos($col, 'int') !== false) {
<ide> return ['type' => 'integer', 'length' => $length];
<ide> }
<add> if ($col === 'char' && $length === 36) {
<add> return ['type' => 'uuid', 'length' => null];
<add> }
<ide> if ($col === 'char') {
<ide> return ['type' => 'string', 'fixed' => true, 'length' => $length];
<ide> }
<ide><path>Cake/Test/TestCase/Database/Schema/MysqlSchemaTest.php
<ide> public static function convertColumnProvider() {
<ide> 'CHAR(25)',
<ide> ['type' => 'string', 'length' => 25, 'fixed' => true]
<ide> ],
<add> [
<add> 'CHAR(36)',
<add> ['type' => 'uuid', 'length' => null]
<add> ],
<ide> [
<ide> 'TINYTEXT',
<ide> ['type' => 'string', 'length' => null]
<ide><path>Cake/Test/TestCase/Database/Schema/PostgresSchemaTest.php
<ide> public static function convertColumnProvider() {
<ide> ],
<ide> [
<ide> 'UUID',
<del> ['type' => 'string', 'fixed' => true, 'length' => 36]
<add> ['type' => 'uuid', 'length' => null]
<ide> ],
<ide> [
<ide> 'INET',
<ide><path>Cake/Test/TestCase/Database/Schema/SqliteSchemaTest.php
<ide> public static function convertColumnProvider() {
<ide> 'CHAR(25)',
<ide> ['type' => 'string', 'fixed' => true, 'length' => 25]
<ide> ],
<add> [
<add> 'CHAR(36)',
<add> ['type' => 'uuid', 'length' => null]
<add> ],
<ide> [
<ide> 'BLOB',
<ide> ['type' => 'binary', 'length' => null] | 6 |
Mixed | Python | add files via upload | a368d620ae41dece6382c4f14b3ec1d629502360 | <ide><path>linear-algebra-python/README.md
<ide> This module contains some useful classes and functions for dealing with linear a
<ide> - returns a unit basis vector with a One at index 'pos' (indexing at 0)
<ide> - function axpy(scalar,vector1,vector2)
<ide> - computes the axpy operation
<add>- function randomVector(N,a,b)
<add> - returns a random vector of size N, with random integer components between 'a' and 'b'.
<ide> - class Matrix
<ide> - This class represents a matrix of arbitrary size and operations on it.
<ide>
<ide> This module contains some useful classes and functions for dealing with linear a
<ide> - operator - _ implements the matrix-subtraction
<ide> - function squareZeroMatrix(N)
<ide> - returns a square zero-matrix of dimension NxN
<add>- function randomMatrix(W,H,a,b)
<add> - returns a random matrix WxH with integer components between 'a' and 'b'
<ide> ---
<ide>
<ide> ## Documentation
<ide><path>linear-algebra-python/src/lib.py
<ide> - function zeroVector(dimension)
<ide> - function unitBasisVector(dimension,pos)
<ide> - function axpy(scalar,vector1,vector2)
<add>- function randomVector(N,a,b)
<ide> - class Matrix
<del>- squareZeroMatrix(N)
<add>- function squareZeroMatrix(N)
<add>- function randomMatrix(W,H,a,b)
<ide> """
<ide>
<ide>
<ide> import math
<add>import random
<ide>
<ide>
<ide> class Vector(object):
<ide> def axpy(scalar,x,y):
<ide> return (x*scalar + y)
<ide>
<ide>
<add>def randomVector(N,a,b):
<add> """
<add> input: size (N) of the vector.
<add> random range (a,b)
<add> output: returns a random vector of size N, with
<add> random integer components between 'a' and 'b'.
<add> """
<add> ans = zeroVector(N)
<add> random.seed(None)
<add> for i in range(N):
<add> ans.changeComponent(i,random.randint(a,b))
<add> return ans
<add>
<add>
<ide> class Matrix(object):
<ide> """
<ide> class: Matrix
<ide> def squareZeroMatrix(N):
<ide> row.append(0)
<ide> ans.append(row)
<ide> return Matrix(ans,N,N)
<add>
<add>
<add>def randomMatrix(W,H,a,b):
<add> """
<add> returns a random matrix WxH with integer components
<add> between 'a' and 'b'
<add> """
<add> matrix = []
<add> random.seed(None)
<add> for i in range(H):
<add> row = []
<add> for j in range(W):
<add> row.append(random.randint(a,b))
<add> matrix.append(row)
<add> return Matrix(matrix,W,H)
<ide>
<ide>
<ide>\ No newline at end of file | 2 |
Javascript | Javascript | update chart when attached | d5eaa12d96bc059eae7d7768f5b4f4ee45fa42ca | <ide><path>src/core/core.controller.js
<ide> class Chart {
<ide> const attached = () => {
<ide> _remove('attach', attached);
<ide>
<del> me.resize();
<ide> me.attached = true;
<add> me.resize();
<ide>
<ide> _add('resize', listener);
<ide> _add('detach', detached);
<ide><path>test/specs/core.controller.tests.js
<ide> describe('Chart', function() {
<ide> dw: 0, dh: 0,
<ide> rw: 0, rh: 0,
<ide> });
<add> expect(chart.chartArea).toBeUndefined();
<ide>
<ide> waitForResize(chart, function() {
<ide> expect(chart).toBeChartOfSize({
<ide> dw: 455, dh: 355,
<ide> rw: 455, rh: 355,
<ide> });
<ide>
<add> expect(chart.chartArea).not.toBeUndefined();
<add>
<ide> body.removeChild(wrapper);
<ide> chart.destroy();
<ide> done(); | 2 |
PHP | PHP | remove unused method | 463bb87662143734251923b36a473f5b4cdb5440 | <ide><path>src/Illuminate/Session/Middleware/StartSession.php
<ide> protected function sessionIsPersistent(array $config = null)
<ide>
<ide> return ! in_array($config['driver'], [null, 'array']);
<ide> }
<del>
<del> /**
<del> * Determine if the session is using cookie sessions.
<del> *
<del> * @return bool
<del> */
<del> protected function usingCookieSessions()
<del> {
<del> if ($this->sessionConfigured()) {
<del> return $this->manager->driver()->getHandler() instanceof CookieSessionHandler;
<del> }
<del>
<del> return false;
<del> }
<ide> } | 1 |
Ruby | Ruby | raise option to as number helpers | 77b89c293594e6b7d1bf9092244a43ae1e2bd67c | <ide><path>actionpack/lib/action_view/helpers/number_helper.rb
<ide> def number_to_phone(number, options = {})
<ide> return unless number
<ide> options = options.symbolize_keys
<ide>
<del> parse_float(number, true) if options[:raise]
<add> parse_float(number, true) if options.delete(:raise)
<ide> ERB::Util.html_escape(ActiveSupport::NumberHelper.number_to_phone(number, options))
<ide> end
<ide>
<ide> def number_to_currency(number, options = {})
<ide> return unless number
<ide> options = escape_unsafe_delimiters_and_separators(options.symbolize_keys)
<ide>
<del> wrap_with_output_safety_handling(number, options[:raise]){ ActiveSupport::NumberHelper.number_to_currency(number, options) }
<add> wrap_with_output_safety_handling(number, options.delete(:raise)) {
<add> ActiveSupport::NumberHelper.number_to_currency(number, options)
<add> }
<ide> end
<ide>
<ide> # Formats a +number+ as a percentage string (e.g., 65%). You can
<ide> def number_to_percentage(number, options = {})
<ide> return unless number
<ide> options = escape_unsafe_delimiters_and_separators(options.symbolize_keys)
<ide>
<del> wrap_with_output_safety_handling(number, options[:raise]){ ActiveSupport::NumberHelper.number_to_percentage(number, options) }
<add> wrap_with_output_safety_handling(number, options.delete(:raise)) {
<add> ActiveSupport::NumberHelper.number_to_percentage(number, options)
<add> }
<ide> end
<ide>
<ide> # Formats a +number+ with grouped thousands using +delimiter+
<ide> def number_to_percentage(number, options = {})
<ide> def number_with_delimiter(number, options = {})
<ide> options = escape_unsafe_delimiters_and_separators(options.symbolize_keys)
<ide>
<del> wrap_with_output_safety_handling(number, options[:raise]){ ActiveSupport::NumberHelper.number_to_delimited(number, options) }
<add> wrap_with_output_safety_handling(number, options.delete(:raise)) {
<add> ActiveSupport::NumberHelper.number_to_delimited(number, options)
<add> }
<ide> end
<ide>
<ide> # Formats a +number+ with the specified level of
<ide> def number_with_delimiter(number, options = {})
<ide> def number_with_precision(number, options = {})
<ide> options = escape_unsafe_delimiters_and_separators(options.symbolize_keys)
<ide>
<del> wrap_with_output_safety_handling(number, options[:raise]){ ActiveSupport::NumberHelper.number_to_rounded(number, options) }
<add> wrap_with_output_safety_handling(number, options.delete(:raise)) {
<add> ActiveSupport::NumberHelper.number_to_rounded(number, options)
<add> }
<ide> end
<ide>
<ide>
<ide> def number_with_precision(number, options = {})
<ide> def number_to_human_size(number, options = {})
<ide> options = escape_unsafe_delimiters_and_separators(options.symbolize_keys)
<ide>
<del> wrap_with_output_safety_handling(number, options[:raise]){ ActiveSupport::NumberHelper.number_to_human_size(number, options) }
<add> wrap_with_output_safety_handling(number, options.delete(:raise)) {
<add> ActiveSupport::NumberHelper.number_to_human_size(number, options)
<add> }
<ide> end
<ide>
<ide> # Pretty prints (formats and approximates) a number in a way it
<ide> def number_to_human_size(number, options = {})
<ide> def number_to_human(number, options = {})
<ide> options = escape_unsafe_delimiters_and_separators(options.symbolize_keys)
<ide>
<del> wrap_with_output_safety_handling(number, options[:raise]){ ActiveSupport::NumberHelper.number_to_human(number, options) }
<add> wrap_with_output_safety_handling(number, options.delete(:raise)) {
<add> ActiveSupport::NumberHelper.number_to_human(number, options)
<add> }
<ide> end
<ide>
<ide> private | 1 |
Go | Go | make errors from graphdriver init friendlier | c0f7819905050ebdb583afba5b6f760d3892adb8 | <ide><path>daemon/daemon.go
<ide> func NewDaemonFromDirectory(config *Config, eng *engine.Engine) (*Daemon, error)
<ide> // Load storage driver
<ide> driver, err := graphdriver.New(config.Root, config.GraphOptions)
<ide> if err != nil {
<del> return nil, err
<add> return nil, fmt.Errorf("error intializing graphdriver: %v", err)
<ide> }
<ide> log.Debugf("Using graph driver %s", driver)
<ide>
<ide><path>daemon/graphdriver/aufs/aufs.go
<ide> func (a *Driver) mount(id, mountLabel string) error {
<ide> }
<ide>
<ide> if err := a.aufsMount(layers, rw, target, mountLabel); err != nil {
<del> return err
<add> return fmt.Errorf("error creating aufs mount to %s: %v", target, err)
<ide> }
<ide> return nil
<ide> }
<ide><path>daemon/graphdriver/overlay/overlay.go
<ide> func (d *Driver) Get(id string, mountLabel string) (string, error) {
<ide>
<ide> opts := fmt.Sprintf("lowerdir=%s,upperdir=%s,workdir=%s", lowerDir, upperDir, workDir)
<ide> if err := syscall.Mount("overlay", mergedDir, "overlay", 0, label.FormatMountLabel(opts, mountLabel)); err != nil {
<del> return "", err
<add> return "", fmt.Errorf("error creating overlay mount to %s: %v", mergedDir, err)
<ide> }
<ide> mount.path = mergedDir
<ide> mount.mounted = true | 3 |
Text | Text | change urls directly from 'http' to 'https' | c6b7e748b0eead30df423bd267a855e773691519 | <ide><path>BUILDING.md
<ide> $ backtrace
<ide> [Build Tools](https://www.visualstudio.com/downloads/#build-tools-for-visual-studio-2017),
<ide> with the default optional components.
<ide> * Basic Unix tools required for some tests,
<del> [Git for Windows](http://git-scm.com/download/win) includes Git Bash
<add> [Git for Windows](https://git-scm.com/download/win) includes Git Bash
<ide> and tools which can be included in the global `PATH`.
<del>* The [NetWide Assembler](http://www.nasm.us/), for OpenSSL assembler modules.
<add>* The [NetWide Assembler](https://www.nasm.us/), for OpenSSL assembler modules.
<ide> If not installed in the default location, it needs to be manually added
<ide> to `PATH`. A build with the `openssl-no-asm` option does not need this, nor
<ide> does a build targeting ARM64 Windows.
<ide>
<ide> Optional requirements to build the MSI installer package:
<ide>
<del>* The [WiX Toolset v3.11](http://wixtoolset.org/releases/) and the
<add>* The [WiX Toolset v3.11](https://wixtoolset.org/releases/) and the
<ide> [Wix Toolset Visual Studio 2017 Extension](https://marketplace.visualstudio.com/items?itemName=RobMensching.WixToolsetVisualStudio2017Extension).
<ide>
<ide> Optional requirements for compiling for Windows 10 on ARM (ARM64):
<ide> Optional requirements for compiling for Windows 10 on ARM (ARM64):
<ide> ##### Option 2: Automated install with Boxstarter
<ide> <a name="boxstarter"></a>
<ide>
<del>A [Boxstarter](http://boxstarter.org/) script can be used for easy setup of
<add>A [Boxstarter](https://boxstarter.org/) script can be used for easy setup of
<ide> Windows systems with all the required prerequisites for Node.js development.
<ide> This script will install the following [Chocolatey](https://chocolatey.org/)
<ide> packages:
<ide> packages:
<ide> * [NetWide Assembler](https://chocolatey.org/packages/nasm)
<ide>
<ide> To install Node.js prerequisites using
<del>[Boxstarter WebLauncher](http://boxstarter.org/WebLauncher), open
<del><http://boxstarter.org/package/nr/url?https://raw.githubusercontent.com/nodejs/node/master/tools/bootstrap/windows_boxstarter>
<add>[Boxstarter WebLauncher](https://boxstarter.org/WebLauncher), open
<add><https://boxstarter.org/package/nr/url?https://raw.githubusercontent.com/nodejs/node/master/tools/bootstrap/windows_boxstarter>
<ide> with Internet Explorer or Edge browser on the target machine.
<ide>
<ide> Alternatively, you can use PowerShell. Run those commands from an elevated
<ide> PowerShell terminal:
<ide>
<ide> ```powershell
<ide> Set-ExecutionPolicy Unrestricted -Force
<del>iex ((New-Object System.Net.WebClient).DownloadString('http://boxstarter.org/bootstrapper.ps1'))
<add>iex ((New-Object System.Net.WebClient).DownloadString('https://boxstarter.org/bootstrapper.ps1'))
<ide> get-boxstarter -Force
<ide> Install-BoxstarterPackage https://raw.githubusercontent.com/nodejs/node/master/tools/bootstrap/windows_boxstarter -DisableReboots
<ide> ```
<ide><path>doc/STYLE_GUIDE.md
<ide> See also API documentation structure overview in [doctools README][].
<ide> [Javascript type]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Data_structures_and_types
<ide> [serial commas]: https://en.wikipedia.org/wiki/Serial_comma
<ide> [The New York Times Manual of Style and Usage]: https://en.wikipedia.org/wiki/The_New_York_Times_Manual_of_Style_and_Usage
<del>[plugin]: http://editorconfig.org/#download
<add>[plugin]: https://editorconfig.org/#download
<ide> [doctools README]: ../tools/doc/README.md
<ide><path>doc/api/fs.md
<ide> the file contents.
<ide> [`URL`]: url.html#url_the_whatwg_url_api
<ide> [`UV_THREADPOOL_SIZE`]: cli.html#cli_uv_threadpool_size_size
<ide> [`WriteStream`]: #fs_class_fs_writestream
<del>[`event ports`]: http://illumos.org/man/port_create
<add>[`event ports`]: https://illumos.org/man/port_create
<ide> [`fs.Dirent`]: #fs_class_fs_dirent
<ide> [`fs.FSWatcher`]: #fs_class_fs_fswatcher
<ide> [`fs.Stats`]: #fs_class_fs_stats
<ide><path>doc/guides/contributing/pull-requests.md
<ide> use `Refs:`.
<ide>
<ide> Examples:
<ide> - `Fixes: https://github.com/nodejs/node/issues/1337`
<del> - `Refs: http://eslint.org/docs/rules/space-in-parens.html`
<add> - `Refs: https://eslint.org/docs/rules/space-in-parens.html`
<ide> - `Refs: https://github.com/nodejs/node/pull/3615`
<ide>
<ide> 5. If your commit introduces a breaking change (`semver-major`), it should
<ide> things in more detail. Please word-wrap to keep columns to 72 characters or
<ide> less.
<ide>
<ide> Fixes: https://github.com/nodejs/node/issues/1337
<del>Refs: http://eslint.org/docs/rules/space-in-parens.html
<add>Refs: https://eslint.org/docs/rules/space-in-parens.html
<ide> ```
<ide>
<ide> If you are new to contributing to Node.js, please try to do your best at
<ide><path>doc/guides/writing-tests.md
<ide> https://coverage.nodejs.org/.
<ide> [Google Test]: https://github.com/google/googletest
<ide> [`common` module]: https://github.com/nodejs/node/blob/master/test/common/README.md
<ide> [all maintained branches]: https://github.com/nodejs/lts
<del>[node.green]: http://node.green/
<add>[node.green]: https://node.green/
<ide> [test fixture]: https://github.com/google/googletest/blob/master/googletest/docs/Primer.md#test-fixtures-using-the-same-data-configuration-for-multiple-tests
<ide> [Test Coverage section of the Building guide]: https://github.com/nodejs/node/blob/master/BUILDING.md#running-coverage
<ide> [directory structure overview]: https://github.com/nodejs/node/blob/master/test/README.md#test-directories | 5 |
Javascript | Javascript | rewrite the clone and merge helpers | 225bfd36f3daae2cfd0e2869658144ee6bfd988b | <ide><path>src/core/core.helpers.js
<ide> module.exports = function(Chart) {
<ide> var helpers = Chart.helpers;
<ide>
<ide> // -- Basic js utility methods
<del> helpers.clone = function(obj) {
<del> var objClone = {};
<del> helpers.each(obj, function(value, key) {
<del> if (helpers.isArray(value)) {
<del> objClone[key] = value.slice(0);
<del> } else if (typeof value === 'object' && value !== null) {
<del> objClone[key] = helpers.clone(value);
<del> } else {
<del> objClone[key] = value;
<del> }
<del> });
<del> return objClone;
<del> };
<add>
<ide> helpers.extend = function(base) {
<ide> var setFn = function(value, key) {
<ide> base[key] = value;
<ide> module.exports = function(Chart) {
<ide> }
<ide> return base;
<ide> };
<del> // Need a special merge function to chart configs since they are now grouped
<del> helpers.configMerge = function(_base) {
<del> var base = helpers.clone(_base);
<del> helpers.each(Array.prototype.slice.call(arguments, 1), function(extension) {
<del> helpers.each(extension, function(value, key) {
<del> var baseHasProperty = base.hasOwnProperty(key);
<del> var baseVal = baseHasProperty ? base[key] : {};
<add>
<add> helpers.configMerge = function(/* objects ... */) {
<add> return helpers.merge(helpers.clone(arguments[0]), [].slice.call(arguments, 1), {
<add> merger: function(key, target, source, options) {
<add> var tval = target[key] || {};
<add> var sval = source[key];
<ide>
<ide> if (key === 'scales') {
<del> // Scale config merging is complex. Add our own function here for that
<del> base[key] = helpers.scaleMerge(baseVal, value);
<add> // scale config merging is complex. Add our own function here for that
<add> target[key] = helpers.scaleMerge(tval, sval);
<ide> } else if (key === 'scale') {
<del> // Used in polar area & radar charts since there is only one scale
<del> base[key] = helpers.configMerge(baseVal, Chart.scaleService.getScaleDefaults(value.type), value);
<del> } else if (baseHasProperty
<del> && typeof baseVal === 'object'
<del> && !helpers.isArray(baseVal)
<del> && baseVal !== null
<del> && typeof value === 'object'
<del> && !helpers.isArray(value)) {
<del> // If we are overwriting an object with an object, do a merge of the properties.
<del> base[key] = helpers.configMerge(baseVal, value);
<add> // used in polar area & radar charts since there is only one scale
<add> target[key] = helpers.merge(tval, [Chart.scaleService.getScaleDefaults(sval.type), sval]);
<ide> } else {
<del> // can just overwrite the value in this case
<del> base[key] = value;
<add> helpers._merger(key, target, source, options);
<ide> }
<del> });
<add> }
<ide> });
<del>
<del> return base;
<ide> };
<del> helpers.scaleMerge = function(_base, extension) {
<del> var base = helpers.clone(_base);
<del>
<del> helpers.each(extension, function(value, key) {
<del> if (key === 'xAxes' || key === 'yAxes') {
<del> // These properties are arrays of items
<del> if (base.hasOwnProperty(key)) {
<del> helpers.each(value, function(valueObj, index) {
<del> var axisType = helpers.valueOrDefault(valueObj.type, key === 'xAxes' ? 'category' : 'linear');
<del> var axisDefaults = Chart.scaleService.getScaleDefaults(axisType);
<del> if (index >= base[key].length || !base[key][index].type) {
<del> base[key].push(helpers.configMerge(axisDefaults, valueObj));
<del> } else if (valueObj.type && valueObj.type !== base[key][index].type) {
<del> // Type changed. Bring in the new defaults before we bring in valueObj so that valueObj can override the correct scale defaults
<del> base[key][index] = helpers.configMerge(base[key][index], axisDefaults, valueObj);
<add>
<add> helpers.scaleMerge = function(/* objects ... */) {
<add> return helpers.merge(helpers.clone(arguments[0]), [].slice.call(arguments, 1), {
<add> merger: function(key, target, source, options) {
<add> if (key === 'xAxes' || key === 'yAxes') {
<add> var slen = source[key].length;
<add> var i, type, scale, defaults;
<add>
<add> if (!target[key]) {
<add> target[key] = [];
<add> }
<add>
<add> for (i = 0; i < slen; ++i) {
<add> scale = source[key][i];
<add> type = helpers.valueOrDefault(scale.type, key === 'xAxes'? 'category' : 'linear');
<add> defaults = Chart.scaleService.getScaleDefaults(type);
<add>
<add> if (i >= target[key].length) {
<add> target[key].push({});
<add> }
<add>
<add> if (!target[key][i].type || (scale.type && scale.type !== target[key][i].type)) {
<add> // new/untyped scale or type changed: let's apply the new defaults
<add> // then merge source scale to correctly overwrite the defaults.
<add> helpers.merge(target[key][i], [defaults, scale]);
<ide> } else {
<del> // Type is the same
<del> base[key][index] = helpers.configMerge(base[key][index], valueObj);
<add> // scales type are the same
<add> helpers.merge(target[key][i], scale);
<ide> }
<del> });
<add> }
<ide> } else {
<del> base[key] = [];
<del> helpers.each(value, function(valueObj) {
<del> var axisType = helpers.valueOrDefault(valueObj.type, key === 'xAxes' ? 'category' : 'linear');
<del> base[key].push(helpers.configMerge(Chart.scaleService.getScaleDefaults(axisType), valueObj));
<del> });
<add> helpers._merger(key, target, source, options);
<ide> }
<del> } else if (base.hasOwnProperty(key) && typeof base[key] === 'object' && base[key] !== null && typeof value === 'object') {
<del> // If we are overwriting an object with an object, do a merge of the properties.
<del> base[key] = helpers.configMerge(base[key], value);
<del>
<del> } else {
<del> // can just overwrite the value in this case
<del> base[key] = value;
<ide> }
<ide> });
<del>
<del> return base;
<ide> };
<ide>
<ide> helpers.where = function(collection, filterCallback) {
<ide><path>src/core/core.scaleService.js
<ide> module.exports = function(Chart) {
<ide> },
<ide> getScaleDefaults: function(type) {
<ide> // Return the scale defaults merged with the global settings so that we always use the latest ones
<del> return this.defaults.hasOwnProperty(type) ? helpers.scaleMerge(Chart.defaults.scale, this.defaults[type]) : {};
<add> return this.defaults.hasOwnProperty(type) ? helpers.merge({}, [Chart.defaults.scale, this.defaults[type]]) : {};
<ide> },
<ide> updateScaleDefaults: function(type, additions) {
<ide> var defaults = this.defaults;
<ide><path>src/helpers/helpers.core.js
<ide> module.exports = function(Chart) {
<ide> }
<ide>
<ide> return true;
<add> },
<add>
<add> /**
<add> * Returns a deep copy of `source` without keeping references on objects and arrays.
<add> * @param {*} source - The value to clone.
<add> * @returns {*}
<add> */
<add> clone: function(source) {
<add> if (helpers.isArray(source)) {
<add> return source.map(helpers.clone);
<add> }
<add>
<add> if (helpers.isObject(source)) {
<add> var target = {};
<add> var keys = Object.keys(source);
<add> var klen = keys.length;
<add> var k = 0;
<add>
<add> for (; k<klen; ++k) {
<add> target[keys[k]] = helpers.clone(source[keys[k]]);
<add> }
<add>
<add> return target;
<add> }
<add>
<add> return source;
<add> },
<add>
<add> /**
<add> * The default merger when Chart.helpers.merge is called without merger option.
<add> * Note(SB): this method is also used by configMerge and scaleMerge as fallback.
<add> * @private
<add> */
<add> _merger: function(key, target, source, options) {
<add> var tval = target[key];
<add> var sval = source[key];
<add>
<add> if (helpers.isObject(tval) && helpers.isObject(sval)) {
<add> helpers.merge(tval, sval, options);
<add> } else {
<add> target[key] = helpers.clone(sval);
<add> }
<add> },
<add>
<add> /**
<add> * Merges source[key] in target[key] only if target[key] is undefined.
<add> * @private
<add> */
<add> _mergerIf: function(key, target, source) {
<add> var tval = target[key];
<add> var sval = source[key];
<add>
<add> if (helpers.isObject(tval) && helpers.isObject(sval)) {
<add> helpers.mergeIf(tval, sval);
<add> } else if (!target.hasOwnProperty(key)) {
<add> target[key] = helpers.clone(sval);
<add> }
<add> },
<add>
<add> /**
<add> * Recursively deep copies `source` properties into `target` with the given `options`.
<add> * IMPORTANT: `target` is not cloned and will be updated with `source` properties.
<add> * @param {Object} target - The target object in which all sources are merged into.
<add> * @param {Object|Array(Object)} source - Object(s) to merge into `target`.
<add> * @param {Object} [options] - Merging options:
<add> * @param {Function} [options.merger] - The merge method (key, target, source, options)
<add> * @returns {Object} The `target` object.
<add> */
<add> merge: function(target, source, options) {
<add> var sources = helpers.isArray(source)? source : [source];
<add> var ilen = sources.length;
<add> var merge, i, keys, klen, k;
<add>
<add> if (!helpers.isObject(target)) {
<add> return target;
<add> }
<add>
<add> options = options || {};
<add> merge = options.merger || helpers._merger;
<add>
<add> for (i=0; i<ilen; ++i) {
<add> source = sources[i];
<add> if (!helpers.isObject(source)) {
<add> continue;
<add> }
<add>
<add> keys = Object.keys(source);
<add> for (k=0, klen = keys.length; k<klen; ++k) {
<add> merge(keys[k], target, source, options);
<add> }
<add> }
<add>
<add> return target;
<add> },
<add>
<add> /**
<add> * Recursively deep copies `source` properties into `target` *only* if not defined in target.
<add> * IMPORTANT: `target` is not cloned and will be updated with `source` properties.
<add> * @param {Object} target - The target object in which all sources are merged into.
<add> * @param {Object|Array(Object)} source - Object(s) to merge into `target`.
<add> * @returns {Object} The `target` object.
<add> */
<add> mergeIf: function(target, source) {
<add> return helpers.merge(target, source, {merger: helpers._mergerIf});
<ide> }
<ide> };
<ide>
<ide><path>src/plugins/plugin.legend.js
<ide> module.exports = function(Chart) {
<ide> var legend = chart.legend;
<ide>
<ide> if (legendOpts) {
<del> legendOpts = helpers.configMerge(Chart.defaults.global.legend, legendOpts);
<add> helpers.mergeIf(legendOpts, Chart.defaults.global.legend);
<ide>
<ide> if (legend) {
<ide> layout.configure(chart, legend, legendOpts);
<ide><path>src/plugins/plugin.title.js
<ide> module.exports = function(Chart) {
<ide> var titleBlock = chart.titleBlock;
<ide>
<ide> if (titleOpts) {
<del> titleOpts = helpers.configMerge(Chart.defaults.global.title, titleOpts);
<add> helpers.mergeIf(titleOpts, Chart.defaults.global.title);
<ide>
<ide> if (titleBlock) {
<ide> layout.configure(chart, titleBlock, titleOpts);
<ide><path>test/specs/core.helpers.tests.js
<ide> describe('Core helper tests', function() {
<ide> helpers = window.Chart.helpers;
<ide> });
<ide>
<del> it('should clone an object', function() {
<del> var testData = {
<del> myProp1: 'abc',
<del> myProp2: ['a', 'b'],
<del> myProp3: {
<del> myProp4: 5,
<del> myProp5: [1, 2]
<del> }
<del> };
<del>
<del> var clone = helpers.clone(testData);
<del> expect(clone).toEqual(testData);
<del> expect(clone).not.toBe(testData);
<del>
<del> expect(clone.myProp2).not.toBe(testData.myProp2);
<del> expect(clone.myProp3).not.toBe(testData.myProp3);
<del> expect(clone.myProp3.myProp5).not.toBe(testData.myProp3.myProp5);
<del> });
<del>
<ide> it('should extend an object', function() {
<ide> var original = {
<ide> myProp1: 'abc',
<ide><path>test/specs/helpers.core.tests.js
<ide> describe('Chart.helpers.core', function() {
<ide> expect(helpers.arrayEquals([o0, o1, o2], [o0, o1, o2])).toBeTruthy();
<ide> });
<ide> });
<add>
<add> describe('clone', function() {
<add> it('should clone primitive values', function() {
<add> expect(helpers.clone()).toBe(undefined);
<add> expect(helpers.clone(null)).toBe(null);
<add> expect(helpers.clone(true)).toBe(true);
<add> expect(helpers.clone(42)).toBe(42);
<add> expect(helpers.clone('foo')).toBe('foo');
<add> });
<add> it('should perform a deep copy of arrays', function() {
<add> var o0 = {a: 42};
<add> var o1 = {s: 's'};
<add> var a0 = ['bar'];
<add> var a1 = [a0, o0, 2];
<add> var f0 = function() {};
<add> var input = [a1, o1, f0, 42, 'foo'];
<add> var output = helpers.clone(input);
<add>
<add> expect(output).toEqual(input);
<add> expect(output).not.toBe(input);
<add> expect(output[0]).not.toBe(a1);
<add> expect(output[0][0]).not.toBe(a0);
<add> expect(output[1]).not.toBe(o1);
<add> });
<add> it('should perform a deep copy of objects', function() {
<add> var a0 = ['bar'];
<add> var a1 = [1, 2, 3];
<add> var o0 = {a: a1, i: 42};
<add> var f0 = function() {};
<add> var input = {o: o0, a: a0, f: f0, s: 'foo', i: 42};
<add> var output = helpers.clone(input);
<add>
<add> expect(output).toEqual(input);
<add> expect(output).not.toBe(input);
<add> expect(output.o).not.toBe(o0);
<add> expect(output.o.a).not.toBe(a1);
<add> expect(output.a).not.toBe(a0);
<add> });
<add> });
<add>
<add> describe('merge', function() {
<add> it('should update target and return it', function() {
<add> var target = {a: 1};
<add> var result = helpers.merge(target, {a: 2, b: 'foo'});
<add> expect(target).toEqual({a: 2, b: 'foo'});
<add> expect(target).toBe(result);
<add> });
<add> it('should return target if not an object', function() {
<add> expect(helpers.merge(undefined, {a: 42})).toEqual(undefined);
<add> expect(helpers.merge(null, {a: 42})).toEqual(null);
<add> expect(helpers.merge('foo', {a: 42})).toEqual('foo');
<add> expect(helpers.merge(['foo', 'bar'], {a: 42})).toEqual(['foo', 'bar']);
<add> });
<add> it('should ignore sources which are not objects', function() {
<add> expect(helpers.merge({a: 42})).toEqual({a: 42});
<add> expect(helpers.merge({a: 42}, null)).toEqual({a: 42});
<add> expect(helpers.merge({a: 42}, 42)).toEqual({a: 42});
<add> });
<add> it('should recursively overwrite target with source properties', function() {
<add> expect(helpers.merge({a: {b: 1}}, {a: {c: 2}})).toEqual({a: {b: 1, c: 2}});
<add> expect(helpers.merge({a: {b: 1}}, {a: {b: 2}})).toEqual({a: {b: 2}});
<add> expect(helpers.merge({a: [1, 2]}, {a: [3, 4]})).toEqual({a: [3, 4]});
<add> expect(helpers.merge({a: 42}, {a: {b: 0}})).toEqual({a: {b: 0}});
<add> expect(helpers.merge({a: 42}, {a: null})).toEqual({a: null});
<add> expect(helpers.merge({a: 42}, {a: undefined})).toEqual({a: undefined});
<add> });
<add> it('should merge multiple sources in the correct order', function() {
<add> var t0 = {a: {b: 1, c: [1, 2]}};
<add> var s0 = {a: {d: 3}, e: {f: 4}};
<add> var s1 = {a: {b: 5}};
<add> var s2 = {a: {c: [6, 7]}, e: 'foo'};
<add>
<add> expect(helpers.merge(t0, [s0, s1, s2])).toEqual({a: {b: 5, c: [6, 7], d: 3}, e: 'foo'});
<add> });
<add> it('should deep copy merged values from sources', function() {
<add> var a0 = ['foo'];
<add> var a1 = [1, 2, 3];
<add> var o0 = {a: a1, i: 42};
<add> var output = helpers.merge({}, {a: a0, o: o0});
<add>
<add> expect(output).toEqual({a: a0, o: o0});
<add> expect(output.a).not.toBe(a0);
<add> expect(output.o).not.toBe(o0);
<add> expect(output.o.a).not.toBe(a1);
<add> });
<add> });
<add>
<add> describe('mergeIf', function() {
<add> it('should update target and return it', function() {
<add> var target = {a: 1};
<add> var result = helpers.mergeIf(target, {a: 2, b: 'foo'});
<add> expect(target).toEqual({a: 1, b: 'foo'});
<add> expect(target).toBe(result);
<add> });
<add> it('should return target if not an object', function() {
<add> expect(helpers.mergeIf(undefined, {a: 42})).toEqual(undefined);
<add> expect(helpers.mergeIf(null, {a: 42})).toEqual(null);
<add> expect(helpers.mergeIf('foo', {a: 42})).toEqual('foo');
<add> expect(helpers.mergeIf(['foo', 'bar'], {a: 42})).toEqual(['foo', 'bar']);
<add> });
<add> it('should ignore sources which are not objects', function() {
<add> expect(helpers.mergeIf({a: 42})).toEqual({a: 42});
<add> expect(helpers.mergeIf({a: 42}, null)).toEqual({a: 42});
<add> expect(helpers.mergeIf({a: 42}, 42)).toEqual({a: 42});
<add> });
<add> it('should recursively copy source properties in target only if they do not exist in target', function() {
<add> expect(helpers.mergeIf({a: {b: 1}}, {a: {c: 2}})).toEqual({a: {b: 1, c: 2}});
<add> expect(helpers.mergeIf({a: {b: 1}}, {a: {b: 2}})).toEqual({a: {b: 1}});
<add> expect(helpers.mergeIf({a: [1, 2]}, {a: [3, 4]})).toEqual({a: [1, 2]});
<add> expect(helpers.mergeIf({a: 0}, {a: {b: 2}})).toEqual({a: 0});
<add> expect(helpers.mergeIf({a: null}, {a: 42})).toEqual({a: null});
<add> expect(helpers.mergeIf({a: undefined}, {a: 42})).toEqual({a: undefined});
<add> });
<add> it('should merge multiple sources in the correct order', function() {
<add> var t0 = {a: {b: 1, c: [1, 2]}};
<add> var s0 = {a: {d: 3}, e: {f: 4}};
<add> var s1 = {a: {b: 5}};
<add> var s2 = {a: {c: [6, 7]}, e: 'foo'};
<add>
<add> expect(helpers.mergeIf(t0, [s0, s1, s2])).toEqual({a: {b: 1, c: [1, 2], d: 3}, e: {f: 4}});
<add> });
<add> it('should deep copy merged values from sources', function() {
<add> var a0 = ['foo'];
<add> var a1 = [1, 2, 3];
<add> var o0 = {a: a1, i: 42};
<add> var output = helpers.mergeIf({}, {a: a0, o: o0});
<add>
<add> expect(output).toEqual({a: a0, o: o0});
<add> expect(output.a).not.toBe(a0);
<add> expect(output.o).not.toBe(o0);
<add> expect(output.o.a).not.toBe(a1);
<add> });
<add> });
<ide> }); | 7 |
Javascript | Javascript | fix coding style in src/core/core.js | 131a16b65ea7cb306213cbf7b7bc18929dfab9e9 | <ide><path>src/core/core.js
<ide> var Page = (function PageClosure() {
<ide> var xref = this.xref;
<ide> var i, n = content.length;
<ide> var streams = [];
<del> for (i = 0; i < n; ++i)
<add> for (i = 0; i < n; ++i) {
<ide> streams.push(xref.fetchIfRef(content[i]));
<add> }
<ide> stream = new StreamsSequenceStream(streams);
<ide> } else if (isStream(content)) {
<ide> stream = content;
<ide> var Page = (function PageClosure() {
<ide> // Properties
<ide> ]);
<ide>
<del> var partialEvaluator = new PartialEvaluator(
<del> pdfManager, this.xref, handler,
<del> this.pageIndex, 'p' + this.pageIndex + '_',
<del> this.idCounters, this.fontCache);
<add> var partialEvaluator = new PartialEvaluator(pdfManager, this.xref,
<add> handler, this.pageIndex,
<add> 'p' + this.pageIndex + '_',
<add> this.idCounters,
<add> this.fontCache);
<ide>
<del> var dataPromises = Promise.all(
<del> [contentStreamPromise, resourcesPromise], reject);
<add> var dataPromises = Promise.all([contentStreamPromise, resourcesPromise],
<add> reject);
<ide> dataPromises.then(function(data) {
<ide> var contentStream = data[0];
<del>
<del>
<ide> var opList = new OperatorList(intent, handler, self.pageIndex);
<ide>
<ide> handler.send('StartRenderPage', {
<ide> var Page = (function PageClosure() {
<ide> resourcesPromise]);
<ide> dataPromises.then(function(data) {
<ide> var contentStream = data[0];
<del> var partialEvaluator = new PartialEvaluator(
<del> pdfManager, self.xref, handler,
<del> self.pageIndex, 'p' + self.pageIndex + '_',
<del> self.idCounters, self.fontCache);
<add> var partialEvaluator = new PartialEvaluator(pdfManager, self.xref,
<add> handler, self.pageIndex,
<add> 'p' + self.pageIndex + '_',
<add> self.idCounters,
<add> self.fontCache);
<ide>
<ide> var bidiTexts = partialEvaluator.getTextContent(contentStream,
<ide> self.resources);
<ide> var Page = (function PageClosure() {
<ide>
<ide> get annotations() {
<ide> var annotations = [];
<del> var annotationRefs = this.annotationRefs || [];
<add> var annotationRefs = (this.annotationRefs || []);
<ide> for (var i = 0, n = annotationRefs.length; i < n; ++i) {
<ide> var annotationRef = annotationRefs[i];
<ide> var annotation = Annotation.fromRef(this.xref, annotationRef);
<ide> var Page = (function PageClosure() {
<ide> */
<ide> var PDFDocument = (function PDFDocumentClosure() {
<ide> function PDFDocument(pdfManager, arg, password) {
<del> if (isStream(arg))
<add> if (isStream(arg)) {
<ide> init.call(this, pdfManager, arg, password);
<del> else if (isArrayBuffer(arg))
<add> } else if (isArrayBuffer(arg)) {
<ide> init.call(this, pdfManager, new Stream(arg), password);
<del> else
<add> } else {
<ide> error('PDFDocument: Unknown argument type');
<add> }
<ide> }
<ide>
<ide> function init(pdfManager, stream, password) {
<ide> var PDFDocument = (function PDFDocumentClosure() {
<ide> var pos = stream.pos;
<ide> var end = stream.end;
<ide> var strBuf = [];
<del> if (pos + limit > end)
<add> if (pos + limit > end) {
<ide> limit = end - pos;
<add> }
<ide> for (var n = 0; n < limit; ++n) {
<ide> strBuf.push(String.fromCharCode(stream.getByte()));
<ide> }
<ide> var str = strBuf.join('');
<ide> stream.pos = pos;
<ide> var index = backwards ? str.lastIndexOf(needle) : str.indexOf(needle);
<del> if (index == -1)
<add> if (index == -1) {
<ide> return false; /* not found */
<add> }
<ide> stream.pos += index;
<ide> return true; /* found */
<ide> }
<ide> var PDFDocument = (function PDFDocumentClosure() {
<ide> if (linearization) {
<ide> // Find end of first obj.
<ide> stream.reset();
<del> if (find(stream, 'endobj', 1024))
<add> if (find(stream, 'endobj', 1024)) {
<ide> startXRef = stream.pos + 6;
<add> }
<ide> } else {
<ide> // Find startxref by jumping backward from the end of the file.
<ide> var step = 1024;
<ide> var found = false, pos = stream.end;
<ide> while (!found && pos > 0) {
<ide> pos -= step - 'startxref'.length;
<del> if (pos < 0)
<add> if (pos < 0) {
<ide> pos = 0;
<add> }
<ide> stream.pos = pos;
<ide> found = find(stream, 'startxref', step, true);
<ide> }
<ide> var PDFDocument = (function PDFDocumentClosure() {
<ide> ch = stream.getByte();
<ide> }
<ide> startXRef = parseInt(str, 10);
<del> if (isNaN(startXRef))
<add> if (isNaN(startXRef)) {
<ide> startXRef = 0;
<add> }
<ide> }
<ide> }
<ide> // shadow the prototype getter with a data property
<ide> var PDFDocument = (function PDFDocumentClosure() {
<ide> get mainXRefEntriesOffset() {
<ide> var mainXRefEntriesOffset = 0;
<ide> var linearization = this.linearization;
<del> if (linearization)
<add> if (linearization) {
<ide> mainXRefEntriesOffset = linearization.mainXRefEntriesOffset;
<add> }
<ide> // shadow the prototype getter with a data property
<ide> return shadow(this, 'mainXRefEntriesOffset', mainXRefEntriesOffset);
<ide> },
<ide> var PDFDocument = (function PDFDocumentClosure() {
<ide> var value = infoDict.get(key);
<ide> // Make sure the value conforms to the spec.
<ide> if (validEntries[key](value)) {
<del> docInfo[key] = typeof value !== 'string' ? value :
<del> stringToPDFString(value);
<add> docInfo[key] = (typeof value !== 'string' ?
<add> value : stringToPDFString(value));
<ide> } else {
<ide> info('Bad value in document info for "' + key + '"');
<ide> } | 1 |
Javascript | Javascript | remove unneeded bind() and related comments | 93bacfd00fd04d5c219fb392382250d96bb3a7be | <ide><path>test/internet/test-dgram-multicast-multi-process.js
<ide> if (process.argv[2] !== 'child') {
<ide> }
<ide>
<ide> var sendSocket = dgram.createSocket('udp4');
<del> // FIXME: a libuv limitation makes it necessary to bind()
<del> // before calling any of the set*() functions. The bind()
<del> // call is what creates the actual socket.
<del> sendSocket.bind();
<ide>
<ide> // The socket is actually created async now.
<ide> sendSocket.on('listening', function() { | 1 |
Javascript | Javascript | fix missing end of file newline | c8a64817d2c62cdfda072dcae75d190746e7572e | <ide><path>test/ngRoute/directive/ngViewSpec.js
<ide> describe('ngView', function() {
<ide> ));
<ide> });
<ide> });
<del>});
<ide>\ No newline at end of file
<add>}); | 1 |
Javascript | Javascript | remove an unneccessary directive definition | b58a7f8a12dc7a2ae0023837ed77c165b62cefcc | <ide><path>angularFiles.js
<ide> var angularFiles = {
<ide> 'src/ng/directive/ngTransclude.js',
<ide> 'src/ng/directive/script.js',
<ide> 'src/ng/directive/select.js',
<del> 'src/ng/directive/style.js',
<ide> 'src/ng/directive/validators.js',
<ide> 'src/angular.bind.js',
<ide> 'src/publishExternalApis.js',
<ide><path>src/AngularPublic.js
<ide> formDirective,
<ide> scriptDirective,
<ide> selectDirective,
<del> styleDirective,
<ide> optionDirective,
<ide> ngBindDirective,
<ide> ngBindHtmlDirective,
<ide> function publishExternalAPI(angular) {
<ide> form: formDirective,
<ide> script: scriptDirective,
<ide> select: selectDirective,
<del> style: styleDirective,
<ide> option: optionDirective,
<ide> ngBind: ngBindDirective,
<ide> ngBindHtml: ngBindHtmlDirective,
<ide><path>src/ng/directive/style.js
<del>'use strict';
<del>
<del>var styleDirective = valueFn({
<del> restrict: 'E',
<del> terminal: false
<del>}); | 3 |
Javascript | Javascript | flow typing activityindicator | 0b71d1ddb03c036ed118574c105b0af505da19fc | <ide><path>Libraries/Components/ActivityIndicator/ActivityIndicator.js
<ide> const ViewPropTypes = require('ViewPropTypes');
<ide>
<ide> const createReactClass = require('create-react-class');
<ide> const requireNativeComponent = require('requireNativeComponent');
<add>
<add>import type {ViewProps} from 'ViewPropTypes';
<add>
<ide> let RCTActivityIndicator;
<ide>
<ide> const GRAY = '#999999';
<ide>
<ide> type IndicatorSize = number | 'small' | 'large';
<ide>
<add>type Props = $ReadOnly<{|
<add> ...ViewProps,
<add>
<add> animating?: ?boolean,
<add> color?: ?string,
<add> hidesWhenStopped?: ?boolean,
<add> size?: ?IndicatorSize,
<add>|}>;
<add>
<ide> type DefaultProps = {
<ide> animating: boolean,
<del> color: any,
<add> color: ?string,
<ide> hidesWhenStopped: boolean,
<ide> size: IndicatorSize,
<ide> };
<ide> type DefaultProps = {
<ide> *
<ide> * See http://facebook.github.io/react-native/docs/activityindicator.html
<ide> */
<del>const ActivityIndicator = createReactClass({
<add>const ActivityIndicator = ((createReactClass({
<ide> displayName: 'ActivityIndicator',
<ide> mixins: [NativeMethodsMixin],
<ide>
<ide> const ActivityIndicator = createReactClass({
<ide> getDefaultProps(): DefaultProps {
<ide> return {
<ide> animating: true,
<del> color: Platform.OS === 'ios' ? GRAY : undefined,
<add> color: Platform.OS === 'ios' ? GRAY : null,
<ide> hidesWhenStopped: true,
<ide> size: 'small',
<ide> };
<ide> const ActivityIndicator = createReactClass({
<ide> </View>
<ide> );
<ide> },
<del>});
<add>}): any): React.ComponentType<Props>);
<ide>
<ide> if (Platform.OS === 'ios') {
<ide> RCTActivityIndicator = requireNativeComponent( | 1 |
Javascript | Javascript | remove some duplication in the `dict.merge` method | e1ee3835cdd9e12d664c8d25db0a5dca845374b6 | <ide><path>src/core/primitives.js
<ide> class Dict {
<ide> }
<ide>
<ide> static merge({ xref, dictArray, mergeSubDicts = false }) {
<del> const mergedDict = new Dict(xref);
<del>
<del> if (!mergeSubDicts) {
<del> for (const dict of dictArray) {
<del> if (!(dict instanceof Dict)) {
<del> continue;
<del> }
<del> for (const [key, value] of Object.entries(dict._map)) {
<del> if (mergedDict._map[key] === undefined) {
<del> mergedDict._map[key] = value;
<del> }
<del> }
<del> }
<del> return mergedDict.size > 0 ? mergedDict : Dict.empty;
<del> }
<del> const properties = new Map();
<add> const mergedDict = new Dict(xref),
<add> properties = new Map();
<ide>
<ide> for (const dict of dictArray) {
<ide> if (!(dict instanceof Dict)) {
<ide> class Dict {
<ide> if (property === undefined) {
<ide> property = [];
<ide> properties.set(key, property);
<add> } else if (!mergeSubDicts) {
<add> continue; // Ignore additional entries for a "shallow" merge.
<ide> }
<ide> property.push(value);
<ide> } | 1 |
Go | Go | fix wrong untag when using rmi via id | e608296bc62ceeaf41ebf2bc80b21c0a1883d4f0 | <ide><path>server.go
<ide> func (srv *Server) deleteImage(img *Image, repoName, tag string) ([]APIRmi, erro
<ide> parsedRepo := strings.Split(repoAndTag, ":")[0]
<ide> if strings.Contains(img.ID, repoName) {
<ide> repoName = parsedRepo
<add> if len(strings.Split(repoAndTag, ":")) > 1 {
<add> tag = strings.Split(repoAndTag, ":")[1]
<add> }
<ide> } else if repoName != parsedRepo {
<ide> // the id belongs to multiple repos, like base:latest and user:test,
<ide> // in that case return conflict | 1 |
Text | Text | add changelogs for console | 7b5a4ba9fd1c59ee2c30d4d90ba5b20b4094271e | <ide><path>doc/api/console.md
<ide> milliseconds to `stdout`. Timer durations are accurate to the sub-millisecond.
<ide> ### console.timeEnd(label)
<ide> <!-- YAML
<ide> added: v0.1.104
<add>changes:
<add> - version: v6.0.0
<add> pr-url: https://github.com/nodejs/node/pull/5901
<add> description: This method no longer supports multiple calls that don’t map
<add> to individual `console.time()` calls; see below for details.
<ide> -->
<ide>
<ide> Stops a timer that was previously started by calling [`console.time()`][] and | 1 |
Python | Python | improve test syntax | a996d3d9773a98a85eeab243e3d0d58750c0500c | <ide><path>tests/keras/engine/test_training.py
<ide> def test_check_not_failing():
<ide>
<ide> def test_check_last_is_one():
<ide> a = np.random.random((2, 3, 1))
<del> with pytest.raises(ValueError) as exc:
<add> with pytest.raises(ValueError,
<add> match='You are passing a target array'):
<ide> training_utils.check_loss_and_target_compatibility(
<ide> [a], [losses.CategoricalCrossentropy()], [a.shape])
<ide>
<del> assert 'You are passing a target array' in str(exc)
<del>
<ide>
<ide> def test_check_bad_shape():
<ide> a = np.random.random((2, 3, 5))
<del> with pytest.raises(ValueError) as exc:
<add> with pytest.raises(ValueError,
<add> match='targets to have the same shape'):
<ide> training_utils.check_loss_and_target_compatibility(
<ide> [a], [losses.CategoricalCrossentropy()], [(2, 3, 6)])
<ide>
<del> assert 'targets to have the same shape' in str(exc)
<del>
<ide>
<ide> @pytest.mark.skipif(K.backend() != 'tensorflow',
<ide> reason='Requires TensorFlow backend')
<ide><path>tests/keras/losses_test.py
<ide> def test_unweighted(self):
<ide> y_true = K.constant([1, 9, 2, -5, -2, 6], shape=(2, 3))
<ide> y_pred = K.constant([4, 8, 12, 8, 1, 3], shape=(2, 3))
<ide> loss = mse_obj(y_true, y_pred)
<del> assert np.isclose(K.eval(loss), 49.5, rtol=1e-3)
<add> assert np.isclose(K.eval(loss), 49.5, atol=1e-3)
<ide>
<ide> def test_scalar_weighted(self):
<ide> mse_obj = losses.MeanSquaredError()
<ide> y_true = K.constant([1, 9, 2, -5, -2, 6], shape=(2, 3))
<ide> y_pred = K.constant([4, 8, 12, 8, 1, 3], shape=(2, 3))
<ide> loss = mse_obj(y_true, y_pred, sample_weight=2.3)
<del> assert np.isclose(K.eval(loss), 113.85, rtol=1e-3)
<add> assert np.isclose(K.eval(loss), 113.85, atol=1e-3)
<ide>
<ide> def test_sample_weighted(self):
<ide> mse_obj = losses.MeanSquaredError()
<ide> y_true = K.constant([1, 9, 2, -5, -2, 6], shape=(2, 3))
<ide> y_pred = K.constant([4, 8, 12, 8, 1, 3], shape=(2, 3))
<ide> sample_weight = K.constant([1.2, 3.4], shape=(2, 1))
<ide> loss = mse_obj(y_true, y_pred, sample_weight=sample_weight)
<del> assert np.isclose(K.eval(loss), 767.8 / 6, rtol=1e-3)
<add> assert np.isclose(K.eval(loss), 767.8 / 6, atol=1e-3)
<ide>
<ide> def test_timestep_weighted(self):
<ide> mse_obj = losses.MeanSquaredError()
<ide> y_true = K.constant([1, 9, 2, -5, -2, 6], shape=(2, 3, 1))
<ide> y_pred = K.constant([4, 8, 12, 8, 1, 3], shape=(2, 3, 1))
<ide> sample_weight = K.constant([3, 6, 5, 0, 4, 2], shape=(2, 3))
<ide> loss = mse_obj(y_true, y_pred, sample_weight=sample_weight)
<del> assert np.isclose(K.eval(loss), 97.833, rtol=1e-3)
<add> assert np.isclose(K.eval(loss), 97.833, atol=1e-3)
<ide>
<ide> def test_zero_weighted(self):
<ide> mse_obj = losses.MeanSquaredError()
<ide> def test_no_reduction(self):
<ide> y_true = K.constant([1, 9, 2, -5, -2, 6], shape=(2, 3))
<ide> y_pred = K.constant([4, 8, 12, 8, 1, 3], shape=(2, 3))
<ide> loss = mse_obj(y_true, y_pred, sample_weight=2.3)
<del> assert np.allclose(K.eval(loss), [84.3333, 143.3666], rtol=1e-3)
<add> assert np.allclose(K.eval(loss), [84.3333, 143.3666], atol=1e-3)
<ide>
<ide> def test_sum_reduction(self):
<ide> mse_obj = losses.MeanSquaredError(
<ide> reduction=losses_utils.Reduction.SUM)
<ide> y_true = K.constant([1, 9, 2, -5, -2, 6], shape=(2, 3))
<ide> y_pred = K.constant([4, 8, 12, 8, 1, 3], shape=(2, 3))
<ide> loss = mse_obj(y_true, y_pred, sample_weight=2.3)
<del> assert np.isclose(K.eval(loss), 227.69998, rtol=1e-3)
<add> assert np.isclose(K.eval(loss), 227.69998, atol=1e-3)
<ide>
<ide>
<ide> @skipif_not_tf
<ide> def test_all_correct_unweighted(self):
<ide> mae_obj = losses.MeanAbsoluteError()
<ide> y_true = K.constant([4, 8, 12, 8, 1, 3], shape=(2, 3))
<ide> loss = mae_obj(y_true, y_true)
<del> assert np.isclose(K.eval(loss), 0.0, rtol=1e-3)
<add> assert np.isclose(K.eval(loss), 0.0, atol=1e-3)
<ide>
<ide> def test_unweighted(self):
<ide> mae_obj = losses.MeanAbsoluteError()
<ide> y_true = K.constant([1, 9, 2, -5, -2, 6], shape=(2, 3))
<ide> y_pred = K.constant([4, 8, 12, 8, 1, 3], shape=(2, 3))
<ide> loss = mae_obj(y_true, y_pred)
<del> assert np.isclose(K.eval(loss), 5.5, rtol=1e-3)
<add> assert np.isclose(K.eval(loss), 5.5, atol=1e-3)
<ide>
<ide> def test_scalar_weighted(self):
<ide> mae_obj = losses.MeanAbsoluteError()
<ide> y_true = K.constant([1, 9, 2, -5, -2, 6], shape=(2, 3))
<ide> y_pred = K.constant([4, 8, 12, 8, 1, 3], shape=(2, 3))
<ide> loss = mae_obj(y_true, y_pred, sample_weight=2.3)
<del> assert np.isclose(K.eval(loss), 12.65, rtol=1e-3)
<add> assert np.isclose(K.eval(loss), 12.65, atol=1e-3)
<ide>
<ide> def test_sample_weighted(self):
<ide> mae_obj = losses.MeanAbsoluteError()
<ide> y_true = K.constant([1, 9, 2, -5, -2, 6], shape=(2, 3))
<ide> y_pred = K.constant([4, 8, 12, 8, 1, 3], shape=(2, 3))
<ide> sample_weight = K.constant([1.2, 3.4], shape=(2, 1))
<ide> loss = mae_obj(y_true, y_pred, sample_weight=sample_weight)
<del> assert np.isclose(K.eval(loss), 81.4 / 6, rtol=1e-3)
<add> assert np.isclose(K.eval(loss), 81.4 / 6, atol=1e-3)
<ide>
<ide> def test_timestep_weighted(self):
<ide> mae_obj = losses.MeanAbsoluteError()
<ide> y_true = K.constant([1, 9, 2, -5, -2, 6], shape=(2, 3, 1))
<ide> y_pred = K.constant([4, 8, 12, 8, 1, 3], shape=(2, 3, 1))
<ide> sample_weight = K.constant([3, 6, 5, 0, 4, 2], shape=(2, 3))
<ide> loss = mae_obj(y_true, y_pred, sample_weight=sample_weight)
<del> assert np.isclose(K.eval(loss), 13.833, rtol=1e-3)
<add> assert np.isclose(K.eval(loss), 13.833, atol=1e-3)
<ide>
<ide> def test_zero_weighted(self):
<ide> mae_obj = losses.MeanAbsoluteError()
<ide> y_true = K.constant([1, 9, 2, -5, -2, 6], shape=(2, 3))
<ide> y_pred = K.constant([4, 8, 12, 8, 1, 3], shape=(2, 3))
<ide> loss = mae_obj(y_true, y_pred, sample_weight=0)
<del> assert np.isclose(K.eval(loss), 0.0, rtol=1e-3)
<add> assert np.isclose(K.eval(loss), 0.0, atol=1e-3)
<ide>
<ide> def test_invalid_sample_weight(self):
<ide> mae_obj = losses.MeanAbsoluteError()
<ide> def test_no_reduction(self):
<ide> y_true = K.constant([1, 9, 2, -5, -2, 6], shape=(2, 3))
<ide> y_pred = K.constant([4, 8, 12, 8, 1, 3], shape=(2, 3))
<ide> loss = mae_obj(y_true, y_pred, sample_weight=2.3)
<del> assert np.allclose(K.eval(loss), [10.7333, 14.5666], rtol=1e-3)
<add> assert np.allclose(K.eval(loss), [10.7333, 14.5666], atol=1e-3)
<ide>
<ide> def test_sum_reduction(self):
<ide> mae_obj = losses.MeanAbsoluteError(
<ide> reduction=losses_utils.Reduction.SUM)
<ide> y_true = K.constant([1, 9, 2, -5, -2, 6], shape=(2, 3))
<ide> y_pred = K.constant([4, 8, 12, 8, 1, 3], shape=(2, 3))
<ide> loss = mae_obj(y_true, y_pred, sample_weight=2.3)
<del> assert np.isclose(K.eval(loss), 25.29999, rtol=1e-3)
<add> assert np.isclose(K.eval(loss), 25.29999, atol=1e-3)
<ide>
<ide>
<ide> @skipif_not_tf
<ide> def test_all_correct_unweighted(self):
<ide> mape_obj = losses.MeanAbsolutePercentageError()
<ide> y_true = K.constant([4, 8, 12, 8, 1, 3], shape=(2, 3))
<ide> loss = mape_obj(y_true, y_true)
<del> assert np.allclose(K.eval(loss), 0.0, rtol=1e-3)
<add> assert np.allclose(K.eval(loss), 0.0, atol=1e-3)
<ide>
<ide> def test_unweighted(self):
<ide> mape_obj = losses.MeanAbsolutePercentageError()
<ide> y_true = K.constant([1, 9, 2, -5, -2, 6], shape=(2, 3))
<ide> y_pred = K.constant([4, 8, 12, 8, 1, 3], shape=(2, 3))
<ide> loss = mape_obj(y_true, y_pred)
<del> assert np.allclose(K.eval(loss), 211.8518, rtol=1e-3)
<add> assert np.allclose(K.eval(loss), 211.8518, atol=1e-3)
<ide>
<ide> def test_scalar_weighted(self):
<ide> mape_obj = losses.MeanAbsolutePercentageError()
<ide> y_true = K.constant([1, 9, 2, -5, -2, 6], shape=(2, 3))
<ide> y_pred = K.constant([4, 8, 12, 8, 1, 3], shape=(2, 3))
<ide> loss = mape_obj(y_true, y_pred, sample_weight=2.3)
<del> assert np.allclose(K.eval(loss), 487.259, rtol=1e-3)
<add> assert np.allclose(K.eval(loss), 487.259, atol=1e-3)
<ide>
<ide> def test_sample_weighted(self):
<ide> mape_obj = losses.MeanAbsolutePercentageError()
<ide> y_true = K.constant([1, 9, 2, -5, -2, 6], shape=(2, 3))
<ide> y_pred = K.constant([4, 8, 12, 8, 1, 3], shape=(2, 3))
<ide> sample_weight = K.constant([1.2, 3.4], shape=(2, 1))
<ide> loss = mape_obj(y_true, y_pred, sample_weight=sample_weight)
<del> assert np.allclose(K.eval(loss), 422.8888, rtol=1e-3)
<add> assert np.allclose(K.eval(loss), 422.8888, atol=1e-3)
<ide>
<ide> def test_timestep_weighted(self):
<ide> mape_obj = losses.MeanAbsolutePercentageError()
<ide> y_true = K.constant([1, 9, 2, -5, -2, 6], shape=(2, 3, 1))
<ide> y_pred = K.constant([4, 8, 12, 8, 1, 3], shape=(2, 3, 1))
<ide> sample_weight = K.constant([3, 6, 5, 0, 4, 2], shape=(2, 3))
<ide> loss = mape_obj(y_true, y_pred, sample_weight=sample_weight)
<del> assert np.allclose(K.eval(loss), 694.4445, rtol=1e-3)
<add> assert np.allclose(K.eval(loss), 694.4445, atol=1e-3)
<ide>
<ide> def test_zero_weighted(self):
<ide> mape_obj = losses.MeanAbsolutePercentageError()
<ide> y_true = K.constant([1, 9, 2, -5, -2, 6], shape=(2, 3))
<ide> y_pred = K.constant([4, 8, 12, 8, 1, 3], shape=(2, 3))
<ide> loss = mape_obj(y_true, y_pred, sample_weight=0)
<del> assert np.allclose(K.eval(loss), 0.0, rtol=1e-3)
<add> assert np.allclose(K.eval(loss), 0.0, atol=1e-3)
<ide>
<ide> def test_no_reduction(self):
<ide> mape_obj = losses.MeanAbsolutePercentageError(
<ide> reduction=losses_utils.Reduction.NONE)
<ide> y_true = K.constant([1, 9, 2, -5, -2, 6], shape=(2, 3))
<ide> y_pred = K.constant([4, 8, 12, 8, 1, 3], shape=(2, 3))
<ide> loss = mape_obj(y_true, y_pred, sample_weight=2.3)
<del> assert np.allclose(K.eval(loss), [621.8518, 352.6666], rtol=1e-3)
<add> assert np.allclose(K.eval(loss), [621.8518, 352.6666], atol=1e-3)
<ide>
<ide>
<ide> @skipif_not_tf
<ide> def test_unweighted(self):
<ide> y_true = K.constant([1, 9, 2, -5, -2, 6], shape=(2, 3))
<ide> y_pred = K.constant([4, 8, 12, 8, 1, 3], shape=(2, 3))
<ide> loss = msle_obj(y_true, y_pred)
<del> assert np.allclose(K.eval(loss), 1.4370, rtol=1e-3)
<add> assert np.allclose(K.eval(loss), 1.4370, atol=1e-3)
<ide>
<ide> def test_scalar_weighted(self):
<ide> msle_obj = losses.MeanSquaredLogarithmicError()
<ide> y_true = K.constant([1, 9, 2, -5, -2, 6], shape=(2, 3))
<ide> y_pred = K.constant([4, 8, 12, 8, 1, 3], shape=(2, 3))
<ide> loss = msle_obj(y_true, y_pred, sample_weight=2.3)
<del> assert np.allclose(K.eval(loss), 3.3051, rtol=1e-3)
<add> assert np.allclose(K.eval(loss), 3.3051, atol=1e-3)
<ide>
<ide> def test_sample_weighted(self):
<ide> msle_obj = losses.MeanSquaredLogarithmicError()
<ide> y_true = K.constant([1, 9, 2, -5, -2, 6], shape=(2, 3))
<ide> y_pred = K.constant([4, 8, 12, 8, 1, 3], shape=(2, 3))
<ide> sample_weight = K.constant([1.2, 3.4], shape=(2, 1))
<ide> loss = msle_obj(y_true, y_pred, sample_weight=sample_weight)
<del> assert np.allclose(K.eval(loss), 3.7856, rtol=1e-3)
<add> assert np.allclose(K.eval(loss), 3.7856, atol=1e-3)
<ide>
<ide> def test_timestep_weighted(self):
<ide> msle_obj = losses.MeanSquaredLogarithmicError()
<ide> y_true = K.constant([1, 9, 2, -5, -2, 6], shape=(2, 3, 1))
<ide> y_pred = K.constant([4, 8, 12, 8, 1, 3], shape=(2, 3, 1))
<ide> sample_weight = K.constant([3, 6, 5, 0, 4, 2], shape=(2, 3))
<ide> loss = msle_obj(y_true, y_pred, sample_weight=sample_weight)
<del> assert np.allclose(K.eval(loss), 2.6473, rtol=1e-3)
<add> assert np.allclose(K.eval(loss), 2.6473, atol=1e-3)
<ide>
<ide> def test_zero_weighted(self):
<ide> msle_obj = losses.MeanSquaredLogarithmicError()
<ide> y_true = K.constant([1, 9, 2, -5, -2, 6], shape=(2, 3))
<ide> y_pred = K.constant([4, 8, 12, 8, 1, 3], shape=(2, 3))
<ide> loss = msle_obj(y_true, y_pred, sample_weight=0)
<del> assert np.allclose(K.eval(loss), 0.0, rtol=1e-3)
<add> assert np.allclose(K.eval(loss), 0.0, atol=1e-3)
<ide>
<ide>
<ide> @skipif_not_tf
<ide> def test_all_correct_unweighted(self):
<ide> y_true = K.constant([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]])
<ide> bce_obj = losses.BinaryCrossentropy()
<ide> loss = bce_obj(y_true, y_true)
<del> assert np.isclose(K.eval(loss), 0.0, rtol=1e-3)
<add> assert np.isclose(K.eval(loss), 0.0, atol=1e-3)
<ide>
<ide> # Test with logits.
<ide> logits = K.constant([[100.0, -100.0, -100.0],
<ide> def test_unweighted(self):
<ide> # = [0, 15.33, 0, 0]
<ide> # Reduced loss = 15.33 / 4
<ide>
<del> assert np.isclose(K.eval(loss), 3.833, rtol=1e-3)
<add> assert np.isclose(K.eval(loss), 3.833, atol=1e-3)
<ide>
<ide> # Test with logits.
<ide> y_true = K.constant([[1., 0., 1.], [0., 1., 1.]])
<ide> def test_unweighted(self):
<ide> # = [(0 + 0 + 0) / 3, 200 / 3]
<ide> # Reduced loss = (0 + 66.666) / 2
<ide>
<del> assert np.isclose(K.eval(loss), 33.333, rtol=1e-3)
<add> assert np.isclose(K.eval(loss), 33.333, atol=1e-3)
<ide>
<ide> def test_scalar_weighted(self):
<ide> bce_obj = losses.BinaryCrossentropy()
<ide> def test_scalar_weighted(self):
<ide> # Weighted loss = [0, 15.33 * 2.3, 0, 0]
<ide> # Reduced loss = 15.33 * 2.3 / 4
<ide>
<del> assert np.isclose(K.eval(loss), 8.817, rtol=1e-3)
<add> assert np.isclose(K.eval(loss), 8.817, atol=1e-3)
<ide>
<ide> # Test with logits.
<ide> y_true = K.constant([[1, 0, 1], [0, 1, 1]])
<ide> def test_scalar_weighted(self):
<ide> # Weighted loss = [0 * 2.3, 66.666 * 2.3]
<ide> # Reduced loss = (0 + 66.666 * 2.3) / 2
<ide>
<del> assert np.isclose(K.eval(loss), 76.667, rtol=1e-3)
<add> assert np.isclose(K.eval(loss), 76.667, atol=1e-3)
<ide>
<ide> def test_sample_weighted(self):
<ide> bce_obj = losses.BinaryCrossentropy()
<ide> def test_sample_weighted(self):
<ide> # = [0, 15.33, 0, 0]
<ide> # Reduced loss = 15.33 * 1.2 / 4
<ide>
<del> assert np.isclose(K.eval(loss), 4.6, rtol=1e-3)
<add> assert np.isclose(K.eval(loss), 4.6, atol=1e-3)
<ide>
<ide> # Test with logits.
<ide> y_true = K.constant([[1, 0, 1], [0, 1, 1]])
<ide> def test_sample_weighted(self):
<ide> # Weighted loss = [0 * 4, 66.666 * 3]
<ide> # Reduced loss = (0 + 66.666 * 3) / 2
<ide>
<del> assert np.isclose(K.eval(loss), 100, rtol=1e-3)
<add> assert np.isclose(K.eval(loss), 100, atol=1e-3)
<ide>
<ide> def test_no_reduction(self):
<ide> y_true = K.constant([[1, 0, 1], [0, 1, 1]])
<ide> def test_no_reduction(self):
<ide> # (where x = logits and z = y_true)
<ide> # Loss = [(0 + 0 + 0)/3, (200)/3]
<ide>
<del> assert np.allclose(K.eval(loss), (0., 66.6666), rtol=1e-3)
<add> assert np.allclose(K.eval(loss), (0., 66.6666), atol=1e-3)
<ide>
<ide> def test_label_smoothing(self):
<ide> logits = K.constant([[100.0, -100.0, -100.0]]) | 2 |
Go | Go | fix typos in error messages | a447894946ca2ac47bf1c46f78c4839c75fd740d | <ide><path>daemon/graphdriver/devmapper/attach_loopback.go
<ide> func openNextAvailableLoopback(index int, sparseFile *os.File) (loopFile *os.Fil
<ide> // OpenFile adds O_CLOEXEC
<ide> loopFile, err = os.OpenFile(target, os.O_RDWR, 0644)
<ide> if err != nil {
<del> log.Errorf("Error openning loopback device: %s", err)
<add> log.Errorf("Error opening loopback device: %s", err)
<ide> return nil, ErrAttachLoopbackDevice
<ide> }
<ide>
<ide> func attachLoopDevice(sparseName string) (loop *os.File, err error) {
<ide> // OpenFile adds O_CLOEXEC
<ide> sparseFile, err := os.OpenFile(sparseName, os.O_RDWR, 0644)
<ide> if err != nil {
<del> log.Errorf("Error openning sparse file %s: %s", sparseName, err)
<add> log.Errorf("Error opening sparse file %s: %s", sparseName, err)
<ide> return nil, ErrAttachLoopbackDevice
<ide> }
<ide> defer sparseFile.Close() | 1 |
Text | Text | add client-side and node.js recommended libraries | e0da99eb83a06dcd07a5f22a19702499aa8ac56a | <ide><path>README.md
<ide> Obtaining API Keys
<ide>
<ide> Recommended Node.js Libraries
<ide> -----------------------------
<del>- nodemon - automatically restart node.js server on code change.
<del>- geoip-lite - get location name from IP address.
<del>- [node-validator](https://github.com/chriso/node-validator) - input validation and sanitization.
<add>- [nodemon](https://github.com/remy/nodemon) - automatically restart node.js server on code change.
<add>- [geoip-lite](https://github.com/bluesmoon/node-geoip) - get location name from IP address.
<add>- [email.js](https://github.com/eleith/emailjs) - send emails with node.js (without sendgrid or mailgun).
<add>- [filesize.js](http://filesizejs.com/) - make file size pretty, e.g. `filesize(265318); // "265.32 kB"`.
<ide>
<del>
<del>Recommended client-side libraries
<add>Recommended Client-Side libraries
<ide> ---------------------------------
<del>- [Hover](https://github.com/IanLunn/Hover) - awesome css3 animations on mouse hover.
<del>- [platform.js](https://github.com/bestiejs/platform.js) - get client's operating system name, version, and other useful information.
<del>- [iCheck](https://github.com/fronteed/iCheck) - custom nice looking radio and check boxes.
<add>- [Hover](https://github.com/IanLunn/Hover) - Awesome css3 animations on mouse hover.
<add>- [platform.js](https://github.com/bestiejs/platform.js) - Get client's operating system name, version, and other useful information.
<add>- [iCheck](https://github.com/fronteed/iCheck) - Custom nice looking radio and check boxes.
<add>- [Magnific Popup](http://dimsemenov.com/plugins/magnific-popup/) - Responsive jQuery Lightbox Plugin.
<add>- [jQuery Raty](http://wbotelhos.com/raty/) Star Rating Plugin.
<ide>
<ide> TODO
<ide> ----
<ide> - Pages that require login, should automatically redirect to last attempted URL on successful sign-in.
<del>- Add more API examples
<add>- Add more API examples.
<ide>
<ide> Contributing
<ide> ------------ | 1 |
Go | Go | tidy hostconfig struct | 51cf074e77020ab45b84c22259488b7a0eddc36a | <ide><path>runconfig/hostconfig.go
<ide> type LogConfig struct {
<ide> // Here, "non-portable" means "dependent of the host we are running on".
<ide> // Portable information *should* appear in Config.
<ide> type HostConfig struct {
<del> Binds []string // List of volume bindings for this container
<del> ContainerIDFile string // File (path) where the containerId is written
<del> Memory int64 // Memory limit (in bytes)
<del> MemoryReservation int64 // Memory soft limit (in bytes)
<del> MemorySwap int64 // Total memory usage (memory + swap); set `-1` to disable swap
<del> KernelMemory int64 // Kernel memory limit (in bytes)
<del> CPUShares int64 `json:"CpuShares"` // CPU shares (relative weight vs. other containers)
<add> // Applicable to all platforms
<add> Binds []string // List of volume bindings for this container
<add> ContainerIDFile string // File (path) where the containerId is written
<add> CPUShares int64 `json:"CpuShares"` // CPU shares (relative weight vs. other containers)
<add> LogConfig LogConfig // Configuration of the logs for this container
<add> NetworkMode NetworkMode // Network mode to use for the container
<add> PortBindings nat.PortMap // Port mapping between the exposed port (container) and the host
<add> RestartPolicy RestartPolicy // Restart policy to be used for the container
<add> VolumeDriver string // Name of the volume driver used to mount volumes
<add> VolumesFrom []string // List of volumes to take from other container
<add>
<add> // Applicable to UNIX platforms
<add> BlkioWeight uint16 // Block IO weight (relative weight vs. other containers)
<add> CapAdd *stringutils.StrSlice // List of kernel capabilities to add to the container
<add> CapDrop *stringutils.StrSlice // List of kernel capabilities to remove from the container
<add> CgroupParent string // Parent cgroup.
<ide> CPUPeriod int64 `json:"CpuPeriod"` // CPU CFS (Completely Fair Scheduler) period
<add> CPUQuota int64 `json:"CpuQuota"` // CPU CFS (Completely Fair Scheduler) quota
<ide> CpusetCpus string // CpusetCpus 0-2, 0,1
<ide> CpusetMems string // CpusetMems 0-2, 0,1
<del> CPUQuota int64 `json:"CpuQuota"` // CPU CFS (Completely Fair Scheduler) quota
<del> BlkioWeight uint16 // Block IO weight (relative weight vs. other containers)
<del> OomKillDisable bool // Whether to disable OOM Killer or not
<del> MemorySwappiness *int64 // Tuning container memory swappiness behaviour
<del> Privileged bool // Is the container in privileged mode
<del> PortBindings nat.PortMap // Port mapping between the exposed port (container) and the host
<del> Links []string // List of links (in the name:alias form)
<del> PublishAllPorts bool // Should docker publish all exposed port for the container
<add> Devices []DeviceMapping // List of devices to map inside the container
<ide> DNS []string `json:"Dns"` // List of DNS server to lookup
<ide> DNSOptions []string `json:"DnsOptions"` // List of DNSOption to look for
<ide> DNSSearch []string `json:"DnsSearch"` // List of DNSSearch to look for
<ide> ExtraHosts []string // List of extra hosts
<del> VolumesFrom []string // List of volumes to take from other container
<del> Devices []DeviceMapping // List of devices to map inside the container
<del> NetworkMode NetworkMode // Network namespace to use for the container
<del> IpcMode IpcMode // IPC namespace to use for the container // Unix specific
<del> PidMode PidMode // PID namespace to use for the container // Unix specific
<del> UTSMode UTSMode // UTS namespace to use for the container // Unix specific
<del> CapAdd *stringutils.StrSlice // List of kernel capabilities to add to the container
<del> CapDrop *stringutils.StrSlice // List of kernel capabilities to remove from the container
<ide> GroupAdd []string // List of additional groups that the container process will run as
<del> RestartPolicy RestartPolicy // Restart policy to be used for the container
<add> IpcMode IpcMode // IPC namespace to use for the container
<add> KernelMemory int64 // Kernel memory limit (in bytes)
<add> Links []string // List of links (in the name:alias form)
<add> Memory int64 // Memory limit (in bytes)
<add> MemoryReservation int64 // Memory soft limit (in bytes)
<add> MemorySwap int64 // Total memory usage (memory + swap); set `-1` to disable swap
<add> MemorySwappiness *int64 // Tuning container memory swappiness behaviour
<add> OomKillDisable bool // Whether to disable OOM Killer or not
<add> PidMode PidMode // PID namespace to use for the container
<add> Privileged bool // Is the container in privileged mode
<add> PublishAllPorts bool // Should docker publish all exposed port for the container
<add> ReadonlyRootfs bool // Is the container root filesystem in read-only
<ide> SecurityOpt []string // List of string values to customize labels for MLS systems, such as SELinux.
<del> ReadonlyRootfs bool // Is the container root filesystem in read-only // Unix specific
<ide> Ulimits []*ulimit.Ulimit // List of ulimits to be set in the container
<del> LogConfig LogConfig // Configuration of the logs for this container
<del> CgroupParent string // Parent cgroup.
<del> ConsoleSize [2]int // Initial console size on Windows
<del> VolumeDriver string // Name of the volume driver used to mount volumes
<del> Isolation IsolationLevel // Isolation level of the container (eg default, hyperv)
<add> UTSMode UTSMode // UTS namespace to use for the container
<add>
<add> // Applicable to Windows
<add> ConsoleSize [2]int // Initial console size
<add> Isolation IsolationLevel // Isolation level of the container (eg default, hyperv)
<ide> }
<ide>
<ide> // DecodeHostConfig creates a HostConfig based on the specified Reader. | 1 |
Text | Text | add docs for option `--isolation` | 38ec5d86a355674cfddf8c998591abb098475bab | <ide><path>docs/reference/commandline/build.md
<ide> parent = "smn_cli"
<ide> -f, --file="" Name of the Dockerfile (Default is 'PATH/Dockerfile')
<ide> --force-rm=false Always remove intermediate containers
<ide> --help=false Print usage
<add> --isolation="" Container isolation technology
<ide> -m, --memory="" Memory limit for all build containers
<ide> --memory-swap="" Total memory (memory + swap), `-1` to disable swap
<ide> --no-cache=false Do not use cache when building the image
<ide> like `ENV` values do.
<ide>
<ide> For detailed information on using `ARG` and `ENV` instructions, see the
<ide> [Dockerfile reference](../builder.md).
<add>
<add>### Specify isolation technology for container (--isolation)
<add>
<add>This option is useful in situations where you are running Docker containers on
<add>Windows. The `--isolation=<value>` option sets a container's isolation
<add>technology. On Linux, the only supported is the `default` option which uses
<add>Linux namespaces. On Microsoft Windows, you can specify these values:
<add>
<add>
<add>| Value | Description |
<add>|-----------|---------------------------------------------------------------------------------------------------------------------------------------------------------------|
<add>| `default` | Use the value specified by the Docker daemon's `--exec-opt` . If the `daemon` does not specify an isolation technology, Microsoft Windows uses `process` as its default value. |
<add>| `process` | Namespace isolation only. |
<add>| `hyperv` | Hyper-V hypervisor partition-based isolation. |
<add>
<add>Specifying the `--isolation` flag without a value is the same as setting `--isolation="default"`.
<ide><path>docs/reference/commandline/create.md
<ide> Creates a new container.
<ide> --help=false Print usage
<ide> -i, --interactive=false Keep STDIN open even if not attached
<ide> --ipc="" IPC namespace to use
<add> --isolation="" Container isolation technology
<ide> --kernel-memory="" Kernel memory limit
<ide> -l, --label=[] Set metadata on the container (e.g., --label=com.example.key=value)
<ide> --label-file=[] Read in a line delimited file of labels
<ide> then be used from the subsequent container:
<ide> -rw-r--r-- 1 1000 staff 920 Nov 28 11:51 .profile
<ide> drwx--S--- 2 1000 staff 460 Dec 5 00:51 .ssh
<ide> drwxr-xr-x 32 1000 staff 1140 Dec 5 04:01 docker
<add>
<add>### Specify isolation technology for container (--isolation)
<add>
<add>This option is useful in situations where you are running Docker containers on
<add>Windows. The `--isolation=<value>` option sets a container's isolation
<add>technology. On Linux, the only supported is the `default` option which uses
<add>Linux namespaces. On Microsoft Windows, you can specify these values:
<add>
<add>
<add>| Value | Description |
<add>|-----------|---------------------------------------------------------------------------------------------------------------------------------------------------------------|
<add>| `default` | Use the value specified by the Docker daemon's `--exec-opt` . If the `daemon` does not specify an isolation technology, Microsoft Windows uses `process` as its default value. |
<add>| `process` | Namespace isolation only. |
<add>| `hyperv` | Hyper-V hypervisor partition-based isolation. |
<add>
<add>Specifying the `--isolation` flag without a value is the same as setting `--isolation="default"`.
<ide><path>docs/reference/commandline/daemon.md
<ide> This example sets the `cgroupdriver` to `systemd`:
<ide>
<ide> Setting this option applies to all containers the daemon launches.
<ide>
<add>Also Windows Container makes use of `--exec-opt` for special purpose. Docker user
<add>can specify default container isolation technology with this, for example:
<add>
<add> $ docker daemon --exec-opt isolation=hyperv
<add>
<add>Will make `hyperv` the default isolation technology on Windows, without specifying
<add>isolation value on daemon start, Windows isolation technology will default to `process`.
<add>
<ide> ## Daemon DNS options
<ide>
<ide> To set the DNS server for all Docker containers, use
<ide><path>docs/reference/commandline/run.md
<ide> parent = "smn_cli"
<ide> --help=false Print usage
<ide> -i, --interactive=false Keep STDIN open even if not attached
<ide> --ipc="" IPC namespace to use
<add> --isolation="" Container isolation technology
<ide> --kernel-memory="" Kernel memory limit
<ide> -l, --label=[] Set metadata on the container (e.g., --label=com.example.key=value)
<ide> --label-file=[] Read in a file of labels (EOL delimited)
<ide> the three processes quota set for the `daemon` user.
<ide> The `--stop-signal` flag sets the system call signal that will be sent to the container to exit.
<ide> This signal can be a valid unsigned number that matches a position in the kernel's syscall table, for instance 9,
<ide> or a signal name in the format SIGNAME, for instance SIGKILL.
<add>
<add>### Specify isolation technology for container (--isolation)
<add>
<add>This option is useful in situations where you are running Docker containers on
<add>Microsoft Windows. The `--isolation <value>` option sets a container's isolation
<add>technology. On Linux, the only supported is the `default` option which uses
<add>Linux namespaces. These two commands are equivalent on Linux:
<add>
<add>```
<add>$ docker run -d busybox top
<add>$ docker run -d --isolation default busybox top
<add>```
<add>
<add>On Microsoft Windows, can take any of these values:
<add>
<add>
<add>| Value | Description |
<add>|-----------|---------------------------------------------------------------------------------------------------------------------------------------------------------------|
<add>| `default` | Use the value specified by the Docker daemon's `--exec-opt` . If the `daemon` does not specify an isolation technology, Microsoft Windows uses `process` as its default value. |
<add>| `process` | Namespace isolation only. |
<add>| `hyperv` | Hyper-V hypervisor partition-based isolation. |
<add>
<add>In practice, when running on Microsoft Windows without a `daemon` option set, these two commands are equivalent:
<add>
<add>```
<add>$ docker run -d --isolation default busybox top
<add>$ docker run -d --isolation process busybox top
<add>```
<add>
<add>If you have set the `--exec-opt isolation=hyperv` option on the Docker `daemon`, any of these commands also result in `hyperv` isolation:
<add>
<add>```
<add>$ docker run -d --isolation default busybox top
<add>$ docker run -d --isolation hyperv busybox top
<add>```
<ide><path>man/docker-build.1.md
<ide> docker-build - Build a new image from the source code at PATH
<ide> [**--help**]
<ide> [**-f**|**--file**[=*PATH/Dockerfile*]]
<ide> [**--force-rm**[=*false*]]
<add>[**--isolation**[=*default*]]
<ide> [**--no-cache**[=*false*]]
<ide> [**--pull**[=*false*]]
<ide> [**-q**|**--quiet**[=*false*]]
<ide> set as the **URL**, the repository is cloned locally and then sent as the contex
<ide> **--force-rm**=*true*|*false*
<ide> Always remove intermediate containers, even after unsuccessful builds. The default is *false*.
<ide>
<add>**--isolation**="*default*"
<add> Isolation specifies the type of isolation technology used by containers.
<add>
<ide> **--no-cache**=*true*|*false*
<ide> Do not use cache when building the image. The default is *false*.
<ide>
<ide> the system will look for that file inside the contents of the tarball.
<ide>
<ide> Note: supported compression formats are 'xz', 'bzip2', 'gzip' and 'identity' (no compression).
<ide>
<add>## Specify isolation technology for container (--isolation)
<add>
<add>This option is useful in situations where you are running Docker containers on
<add>Windows. The `--isolation=<value>` option sets a container's isolation
<add>technology. On Linux, the only supported is the `default` option which uses
<add>Linux namespaces. On Microsoft Windows, you can specify these values:
<add>
<add>* `default`: Use the value specified by the Docker daemon's `--exec-opt` . If the `daemon` does not specify an isolation technology, Microsoft Windows uses `process` as its default value.
<add>* `process`: Namespace isolation only.
<add>* `hyperv`: Hyper-V hypervisor partition-based isolation.
<add>
<add>Specifying the `--isolation` flag without a value is the same as setting `--isolation="default"`.
<add>
<ide> # HISTORY
<ide> March 2014, Originally compiled by William Henry (whenry at redhat dot com)
<ide> based on docker.com source material and internal work.
<ide><path>man/docker-create.1.md
<ide> docker-create - Create a new container
<ide> [**--help**]
<ide> [**-i**|**--interactive**[=*false*]]
<ide> [**--ipc**[=*IPC*]]
<add>[**--isolation**[=*default*]]
<ide> [**--kernel-memory**[=*KERNEL-MEMORY*]]
<ide> [**-l**|**--label**[=*[]*]]
<ide> [**--label-file**[=*[]*]]
<ide> two memory nodes.
<ide> 'container:<name|id>': reuses another container shared memory, semaphores and message queues
<ide> 'host': use the host shared memory,semaphores and message queues inside the container. Note: the host mode gives the container full access to local shared memory and is therefore considered insecure.
<ide>
<add>**--isolation**="*default*"
<add> Isolation specifies the type of isolation technology used by containers.
<add>
<ide> **--kernel-memory**=""
<ide> Kernel memory limit (format: `<number>[<unit>]`, where unit = b, k, m or g)
<ide>
<ide> This value should always larger than **-m**, so you should always use this with
<ide> **-w**, **--workdir**=""
<ide> Working directory inside the container
<ide>
<add># EXAMPLES
<add>
<add>## Specify isolation technology for container (--isolation)
<add>
<add>This option is useful in situations where you are running Docker containers on
<add>Windows. The `--isolation=<value>` option sets a container's isolation
<add>technology. On Linux, the only supported is the `default` option which uses
<add>Linux namespaces. On Microsoft Windows, you can specify these values:
<add>
<add>* `default`: Use the value specified by the Docker daemon's `--exec-opt` . If the `daemon` does not specify an isolation technology, Microsoft Windows uses `process` as its default value.
<add>* `process`: Namespace isolation only.
<add>* `hyperv`: Hyper-V hypervisor partition-based isolation.
<add>
<add>Specifying the `--isolation` flag without a value is the same as setting `--isolation="default"`.
<add>
<ide> # HISTORY
<ide> August 2014, updated by Sven Dowideit <SvenDowideit@home.org.au>
<ide> September 2014, updated by Sven Dowideit <SvenDowideit@home.org.au>
<ide><path>man/docker-run.1.md
<ide> docker-run - Run a command in a new container
<ide> [**--help**]
<ide> [**-i**|**--interactive**[=*false*]]
<ide> [**--ipc**[=*IPC*]]
<add>[**--isolation**[=*default*]]
<ide> [**--kernel-memory**[=*KERNEL-MEMORY*]]
<ide> [**-l**|**--label**[=*[]*]]
<ide> [**--label-file**[=*[]*]]
<ide> redirection on the host system.
<ide> 'container:<name|id>': reuses another container shared memory, semaphores and message queues
<ide> 'host': use the host shared memory,semaphores and message queues inside the container. Note: the host mode gives the container full access to local shared memory and is therefore considered insecure.
<ide>
<add>**--isolation**="*default*"
<add> Isolation specifies the type of isolation technology used by containers.
<add>
<ide> **-l**, **--label**=[]
<ide> Set metadata on the container (e.g., --label com.example.key=value)
<ide>
<ide> weight by `--blkio-weight-device` flag. Use the following command:
<ide>
<ide> # docker run -it --blkio-weight-device "/dev/sda:200" ubuntu
<ide>
<add>## Specify isolation technology for container (--isolation)
<add>
<add>This option is useful in situations where you are running Docker containers on
<add>Microsoft Windows. The `--isolation <value>` option sets a container's isolation
<add>technology. On Linux, the only supported is the `default` option which uses
<add>Linux namespaces. These two commands are equivalent on Linux:
<add>
<add>```
<add>$ docker run -d busybox top
<add>$ docker run -d --isolation default busybox top
<add>```
<add>
<add>On Microsoft Windows, can take any of these values:
<add>
<add>* `default`: Use the value specified by the Docker daemon's `--exec-opt` . If the `daemon` does not specify an isolation technology, Microsoft Windows uses `process` as its default value.
<add>* `process`: Namespace isolation only.
<add>* `hyperv`: Hyper-V hypervisor partition-based isolation.
<add>
<add>In practice, when running on Microsoft Windows without a `daemon` option set, these two commands are equivalent:
<add>
<add>```
<add>$ docker run -d --isolation default busybox top
<add>$ docker run -d --isolation process busybox top
<add>```
<add>
<add>If you have set the `--exec-opt isolation=hyperv` option on the Docker `daemon`, any of these commands also result in `hyperv` isolation:
<add>
<add>```
<add>$ docker run -d --isolation default busybox top
<add>$ docker run -d --isolation hyperv busybox top
<add>```
<add>
<ide> # HISTORY
<ide> April 2014, Originally compiled by William Henry (whenry at redhat dot com)
<ide> based on docker.com source material and internal work. | 7 |
Javascript | Javascript | reduce number of calls to map | c061c33e0f2d4540432827b11f418b331c48cf93 | <ide><path>lib/util/identifier.js
<ide> exports.makePathsRelative = (context, identifier, cache) => {
<ide> if(!cache) return _makePathsRelative(context, identifier);
<ide>
<ide> const relativePaths = cache.relativePaths || (cache.relativePaths = new Map());
<del> if(!relativePaths.has(context)) {
<del> relativePaths.set(context, new Map());
<del> }
<ide>
<del> const contextCache = relativePaths.get(context);
<add> let cachedResult;
<add> let contextCache = relativePaths.get(context)
<add> if(typeof contextCache === "undefined") {
<add> relativePaths.set(context, contextCache = new Map());
<add> } else {
<add> cachedResult = contextCache.get(identifier)
<add> }
<ide>
<del> if(contextCache.has(identifier)) {
<del> return contextCache.get(identifier);
<add> if(typeof cachedResult !== "undefined") {
<add> return cachedResult;
<ide> } else {
<del> let relativePath = _makePathsRelative(context, identifier);
<add> const relativePath = _makePathsRelative(context, identifier);
<ide> contextCache.set(identifier, relativePath);
<ide> return relativePath;
<ide> }
<del>
<ide> }; | 1 |
PHP | PHP | fix failing tests by 1 second difference | 09a623e07b7aa5ebfbd8d14374209c87c7874b97 | <ide><path>lib/Cake/Test/Case/Utility/FileTest.php
<ide> public function testExecutable() {
<ide> * @return void
<ide> */
<ide> public function testLastAccess() {
<add> $ts = time();
<ide> $someFile = new File(TMP . 'some_file.txt', false);
<ide> $this->assertFalse($someFile->lastAccess());
<ide> $this->assertTrue($someFile->open());
<del> $this->assertEquals($someFile->lastAccess(), time());
<add> $this->assertTrue($someFile->lastAccess() >= $ts);
<ide> $someFile->close();
<ide> $someFile->delete();
<ide> } | 1 |
Ruby | Ruby | fix error in virtualenv_install_with_resources | f9481d4d35ca03706fe0d1885e5c83b89e89966e | <ide><path>Library/Homebrew/language/python.rb
<ide> def virtualenv_install_with_resources(options = {})
<ide> wanted = pythons.select { |py| needs_python?(py) }
<ide> raise FormulaAmbiguousPythonError, self if wanted.size > 1
<ide>
<add> python = wanted.first
<ide> python = "python3" if python == "python"
<ide> end
<ide> venv = virtualenv_create(libexec, python.delete("@")) | 1 |
Javascript | Javascript | improve child_process tests | 366495d4e221ccd7080a0a05ce67160905b4a6a5 | <ide><path>test/parallel/test-child-process-stdin.js
<ide> 'use strict';
<del>var common = require('../common');
<del>var assert = require('assert');
<add>const common = require('../common');
<add>const assert = require('assert');
<ide>
<del>var spawn = require('child_process').spawn;
<add>const spawn = require('child_process').spawn;
<ide>
<del>var cat = spawn(common.isWindows ? 'more' : 'cat');
<add>const cat = spawn(common.isWindows ? 'more' : 'cat');
<ide> cat.stdin.write('hello');
<ide> cat.stdin.write(' ');
<ide> cat.stdin.write('world');
<ide> assert.ok(!cat.stdin.readable);
<ide>
<ide> cat.stdin.end();
<ide>
<del>var response = '';
<add>let response = '';
<ide>
<ide> cat.stdout.setEncoding('utf8');
<ide> cat.stdout.on('data', function(chunk) {
<ide><path>test/parallel/test-child-process-stdio-big-write-end.js
<ide> 'use strict';
<ide> require('../common');
<del>var assert = require('assert');
<del>var BUFSIZE = 1024;
<add>const assert = require('assert');
<add>const BUFSIZE = 1024;
<ide>
<ide> switch (process.argv[2]) {
<ide> case undefined:
<ide> switch (process.argv[2]) {
<ide> }
<ide>
<ide> function parent() {
<del> var spawn = require('child_process').spawn;
<del> var child = spawn(process.execPath, [__filename, 'child']);
<del> var sent = 0;
<add> const spawn = require('child_process').spawn;
<add> const child = spawn(process.execPath, [__filename, 'child']);
<add> let sent = 0;
<ide>
<del> var n = '';
<add> let n = '';
<ide> child.stdout.setEncoding('ascii');
<ide> child.stdout.on('data', function(c) {
<ide> n += c;
<ide> function parent() {
<ide> } while (child.stdin.write(buf));
<ide>
<ide> // then write a bunch more times.
<del> for (var i = 0; i < 100; i++) {
<add> for (let i = 0; i < 100; i++) {
<ide> const buf = Buffer.alloc(BUFSIZE, '.');
<ide> sent += BUFSIZE;
<ide> child.stdin.write(buf);
<ide> function parent() {
<ide> }
<ide>
<ide> function child() {
<del> var received = 0;
<add> let received = 0;
<ide> process.stdin.on('data', function(c) {
<ide> received += c.length;
<ide> });
<ide><path>test/parallel/test-child-process-stdio.js
<ide> 'use strict';
<del>var common = require('../common');
<del>var assert = require('assert');
<add>const common = require('../common');
<add>const assert = require('assert');
<ide>
<del>var options = {stdio: ['pipe']};
<del>var child = common.spawnPwd(options);
<add>let options = {stdio: ['pipe']};
<add>let child = common.spawnPwd(options);
<ide>
<ide> assert.notEqual(child.stdout, null);
<ide> assert.notEqual(child.stderr, null); | 3 |
Python | Python | fix xlnet imports | c21bec54e15ab57ca4127cfb28f7a2e909ec1e09 | <ide><path>official/nlp/xlnet/preprocess_pretrain_data.py
<ide> import os
<ide> import random
<ide>
<add>from absl import app
<ide> from absl import flags
<ide> import absl.logging as _logging # pylint: disable=unused-import
<ide>
<ide> def input_fn(params):
<ide> "using multiple workers to identify each worker.")
<ide>
<ide> tf.logging.set_verbosity(tf.logging.INFO)
<del> absl_app.run(create_data)
<add> app.run(create_data)
<ide><path>official/nlp/xlnet/run_classifier.py
<ide> import numpy as np
<ide> import tensorflow as tf
<ide> # pylint: disable=unused-import
<del># Initialize TPU System.
<ide> from official.nlp import xlnet_config
<ide> from official.nlp import xlnet_modeling as modeling
<ide> from official.nlp.xlnet import common_flags
<ide> from official.nlp.xlnet import data_utils
<ide> from official.nlp.xlnet import optimization
<ide> from official.nlp.xlnet import training_utils
<add>from official.utils.misc import tpu_lib
<ide>
<ide> flags.DEFINE_integer("n_class", default=2, help="Number of classes.")
<ide>
<ide> def main(unused_argv):
<ide> if FLAGS.strategy_type == "mirror":
<ide> strategy = tf.distribute.MirroredStrategy()
<ide> elif FLAGS.strategy_type == "tpu":
<del>
<add> # Initialize TPU System.
<ide> cluster_resolver = tpu_lib.tpu_initialize(FLAGS.tpu)
<ide> strategy = tf.distribute.experimental.TPUStrategy(cluster_resolver)
<ide> use_remote_tpu = True
<ide><path>official/nlp/xlnet/run_pretrain.py
<ide> from absl import logging
<ide> import tensorflow as tf
<ide> # pylint: disable=unused-import
<del># Initialize TPU System.
<ide> from official.nlp import xlnet_config
<ide> from official.nlp import xlnet_modeling as modeling
<ide> from official.nlp.xlnet import common_flags
<ide> from official.nlp.xlnet import data_utils
<ide> from official.nlp.xlnet import optimization
<ide> from official.nlp.xlnet import training_utils
<add>from official.utils.misc import tpu_lib
<ide>
<ide> flags.DEFINE_integer(
<ide> "mask_alpha", default=6, help="How many tokens to form a group.")
<ide> def main(unused_argv):
<ide> if FLAGS.strategy_type == "mirror":
<ide> strategy = tf.distribute.MirroredStrategy()
<ide> elif FLAGS.strategy_type == "tpu":
<del>
<add> # Initialize TPU System.
<ide> cluster_resolver = tpu_lib.tpu_initialize(FLAGS.tpu)
<ide> strategy = tf.distribute.experimental.TPUStrategy(cluster_resolver)
<ide> use_remote_tpu = True
<ide><path>official/nlp/xlnet/run_squad.py
<ide>
<ide> import tensorflow as tf
<ide> # pylint: disable=unused-import
<del># Initialize TPU System.
<ide> from official.nlp import xlnet_config
<ide> from official.nlp import xlnet_modeling as modeling
<ide> from official.nlp.xlnet import common_flags
<ide> from official.nlp.xlnet import data_utils
<ide> from official.nlp.xlnet import optimization
<ide> from official.nlp.xlnet import squad_utils
<ide> from official.nlp.xlnet import training_utils
<add>from official.utils.misc import tpu_lib
<ide>
<ide> flags.DEFINE_string(
<ide> "test_feature_path", default=None, help="Path to feature of test set.")
<ide> def main(unused_argv):
<ide> if FLAGS.strategy_type == "mirror":
<ide> strategy = tf.distribute.MirroredStrategy()
<ide> elif FLAGS.strategy_type == "tpu":
<del>
<add> # Initialize TPU System.
<ide> cluster_resolver = tpu_lib.tpu_initialize(FLAGS.tpu)
<ide> strategy = tf.distribute.experimental.TPUStrategy(cluster_resolver)
<ide> use_remote_tpu = True | 4 |
PHP | PHP | add information to deprecation message | 16f698268791b88757ff3444497caf40df0fe4b4 | <ide><path>src/View/ViewVarsTrait.php
<ide> trait ViewVarsTrait
<ide> * Variables for the view
<ide> *
<ide> * @var array
<del> * @deprecated 3.7.0 Use `$this->set()` instead.
<add> * @deprecated 3.7.0 Use `$this->set()` instead, also see `\Cake\View\View::get()`.
<ide> */
<ide> public $viewVars = [];
<ide> | 1 |
Javascript | Javascript | remove transparent based on alphamap | 66b4d70fb0d35175f7130b2bfb4e4a7fd8e2903f | <ide><path>src/loaders/MaterialLoader.js
<ide> MaterialLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
<ide> if ( json.map !== undefined ) material.map = getTexture( json.map );
<ide> if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
<ide>
<del> if ( json.alphaMap !== undefined ) {
<del>
<del> material.alphaMap = getTexture( json.alphaMap );
<del> material.transparent = true;
<del>
<del> }
<add> if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
<ide>
<ide> if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
<ide> if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale; | 1 |
Ruby | Ruby | initialize #min_cost to avoid warning in ruby 2.0 | 0b63da9d5aad9382515cc04f840a4ad73c269d4d | <ide><path>activemodel/lib/active_model/secure_password.rb
<ide> module SecurePassword
<ide> extend ActiveSupport::Concern
<ide>
<ide> class << self; attr_accessor :min_cost; end
<add> self.min_cost = false
<ide>
<ide> module ClassMethods
<ide> # Adds methods to set and authenticate against a BCrypt password.
<ide> module ClassMethods
<ide> # you wish to turn off validations, pass <tt>validations: false</tt> as an
<ide> # argument. You can add more validations by hand if need be.
<ide> #
<del> # If you don't need the confirmation validation, just don't set any
<del> # value to the password_confirmation attribute and the the validation
<add> # If you don't need the confirmation validation, just don't set any
<add> # value to the password_confirmation attribute and the the validation
<ide> # will not be triggered.
<ide> #
<ide> # You need to add bcrypt-ruby (~> 3.0.0) to Gemfile to use #has_secure_password: | 1 |
Mixed | Ruby | add sqlcommenter formatting support on query logs | 6df894fd568b8f6e828442369b39a0fd63f6bad2 | <ide><path>activerecord/CHANGELOG.md
<add>* Add configurable formatter on query log tags to support sqlcommenter. See #45139
<add>
<add> It is now possible to opt into sqlcommenter-formatted query log tags with `config.active_record.query_log_tags_format = :sqlcommenter`.
<add>
<add> *Modulitos and Iheanyi*
<add>
<ide> * Allow any ERB in the database.yml when creating rake tasks.
<ide>
<ide> Any ERB can be used in `database.yml` even if it accesses environment
<ide><path>activerecord/lib/active_record/query_logs.rb
<ide> # frozen_string_literal: true
<ide>
<ide> require "active_support/core_ext/module/attribute_accessors_per_thread"
<add>require "active_record/query_logs_formatter"
<ide>
<ide> module ActiveRecord
<ide> # = Active Record Query Logs
<ide> module QueryLogs
<ide> mattr_accessor :tags, instance_accessor: false, default: [ :application ]
<ide> mattr_accessor :prepend_comment, instance_accessor: false, default: false
<ide> mattr_accessor :cache_query_log_tags, instance_accessor: false, default: false
<add> mattr_accessor :tags_formatter, instance_accessor: false
<ide> thread_mattr_accessor :cached_comment, instance_accessor: false
<ide>
<ide> class << self
<ide> def clear_cache # :nodoc:
<ide> self.cached_comment = nil
<ide> end
<ide>
<add> # Updates the formatter to be what the passed in format is.
<add> def update_formatter(format = :legacy)
<add> self.tags_formatter = QueryLogs::FormatterFactory.from_symbol(format)
<add> end
<add>
<ide> ActiveSupport::ExecutionContext.after_change { ActiveRecord::QueryLogs.clear_cache }
<ide>
<ide> private
<ide> def comment
<ide> end
<ide> end
<ide>
<add> def formatter
<add> self.tags_formatter ||= QueryLogs::FormatterFactory.from_symbol(:legacy)
<add> end
<add>
<ide> def uncached_comment
<ide> content = tag_content
<ide> if content.present?
<ide> def tag_content
<ide> else
<ide> handler
<ide> end
<del> "#{key}:#{val}" unless val.nil?
<add> "#{key}#{self.formatter.key_value_separator}#{self.formatter.format_value(val)}" unless val.nil?
<ide> end.join(",")
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/query_logs_formatter.rb
<add># frozen_string_literal: true
<add>
<add>module ActiveRecord
<add> module QueryLogs
<add> class Formatter # :nodoc:
<add> attr_reader :key_value_separator
<add>
<add> # @param [String] key_value_separator: indicates the string used for
<add> # separating keys and values.
<add> #
<add> # @param [Symbol] quote_values: indicates how values will be formatted (eg:
<add> # in single quotes, not quoted at all, etc)
<add> def initialize(key_value_separator:)
<add> @key_value_separator = key_value_separator
<add> end
<add>
<add> # @param [String-coercible] value
<add> # @return [String] The formatted value that will be used in our key-value
<add> # pairs.
<add> def format_value(value)
<add> value
<add> end
<add> end
<add>
<add> class QuotingFormatter < Formatter # :nodoc:
<add> def format_value(value)
<add> "'#{value.to_s.gsub("'", "\\\\'")}'"
<add> end
<add> end
<add>
<add> class FormatterFactory # :nodoc:
<add> # @param [Symbol] formatter: the kind of formatter we're building.
<add> # @return [Formatter]
<add> def self.from_symbol(formatter)
<add> case formatter
<add> when :legacy
<add> Formatter.new(key_value_separator: ":")
<add> when :sqlcommenter
<add> QuotingFormatter.new(key_value_separator: "=")
<add> else
<add> raise ArgumentError, "Formatter is unsupported: #{formatter}"
<add> end
<add> end
<add> end
<add> end
<add>end
<ide><path>activerecord/lib/active_record/railtie.rb
<ide> class Railtie < Rails::Railtie # :nodoc:
<ide> config.active_record.sqlite3_production_warning = true
<ide> config.active_record.query_log_tags_enabled = false
<ide> config.active_record.query_log_tags = [ :application ]
<add> config.active_record.query_log_tags_format = :legacy
<ide> config.active_record.cache_query_log_tags = false
<ide>
<ide> config.active_record.queues = ActiveSupport::InheritableOptions.new
<ide> class Railtie < Rails::Railtie # :nodoc:
<ide> :shard_resolver,
<ide> :query_log_tags_enabled,
<ide> :query_log_tags,
<add> :query_log_tags_format,
<ide> :cache_query_log_tags,
<ide> :sqlite3_production_warning,
<ide> :sqlite3_adapter_strict_strings_by_default,
<ide> class Railtie < Rails::Railtie # :nodoc:
<ide> ActiveRecord.query_transformers << ActiveRecord::QueryLogs
<ide> ActiveRecord::QueryLogs.taggings.merge!(
<ide> application: Rails.application.class.name.split("::").first,
<del> pid: -> { Process.pid },
<add> pid: -> { Process.pid.to_s },
<ide> socket: -> { ActiveRecord::Base.connection_db_config.socket },
<ide> db_host: -> { ActiveRecord::Base.connection_db_config.host },
<ide> database: -> { ActiveRecord::Base.connection_db_config.database }
<ide> class Railtie < Rails::Railtie # :nodoc:
<ide> ActiveRecord::QueryLogs.tags = app.config.active_record.query_log_tags
<ide> end
<ide>
<add> if app.config.active_record.query_log_tags_format.present?
<add> ActiveRecord::QueryLogs.update_formatter(app.config.active_record.query_log_tags_format)
<add> end
<add>
<ide> if app.config.active_record.cache_query_log_tags
<ide> ActiveRecord::QueryLogs.cache_query_log_tags = true
<ide> end
<ide><path>activerecord/test/cases/query_logs_formatter_test.rb
<add># frozen_string_literal: true
<add>
<add>require "cases/helper"
<add>
<add>class QueryLogsFormatter < ActiveRecord::TestCase
<add> def test_factory_invalid_formatter
<add> assert_raises(ArgumentError) do
<add> ActiveRecord::QueryLogs::FormatterFactory.from_symbol(:non_existing_formatter)
<add> end
<add> end
<add>
<add> def test_sqlcommenter_key_value_separator
<add> formatter = ActiveRecord::QueryLogs::FormatterFactory.from_symbol(:sqlcommenter)
<add> assert_equal("=", formatter.key_value_separator)
<add> end
<add>
<add> def test_sqlcommenter_format_value
<add> formatter = ActiveRecord::QueryLogs::FormatterFactory.from_symbol(:sqlcommenter)
<add> assert_equal("'Joe\\'s Crab Shack'", formatter.format_value("Joe's Crab Shack"))
<add> end
<add>
<add> def test_sqlcommenter_format_value_string_coercible
<add> formatter = ActiveRecord::QueryLogs::FormatterFactory.from_symbol(:sqlcommenter)
<add> assert_equal("'1234'", formatter.format_value(1234))
<add> end
<add>end
<ide><path>activerecord/test/cases/query_logs_test.rb
<ide> def teardown
<ide> ActiveRecord::QueryLogs.prepend_comment = false
<ide> ActiveRecord::QueryLogs.cache_query_log_tags = false
<ide> ActiveRecord::QueryLogs.cached_comment = nil
<add> ActiveRecord::QueryLogs.update_formatter
<add>
<ide> # ActiveSupport::ExecutionContext context is automatically reset in Rails app via an executor hooks set in railtie
<ide> # But not in Active Record's own test suite.
<ide> ActiveSupport::ExecutionContext.clear
<ide> def test_escaping_good_comment
<ide> assert_equal "app:foo", ActiveRecord::QueryLogs.send(:escape_sql_comment, "app:foo")
<ide> end
<ide>
<add> def test_escaping_good_comment_with_custom_separator
<add> ActiveRecord::QueryLogs.update_formatter(:sqlcommenter)
<add> assert_equal "app='foo'", ActiveRecord::QueryLogs.send(:escape_sql_comment, "app='foo'")
<add> end
<add>
<ide> def test_escaping_bad_comments
<ide> assert_equal "; DROP TABLE USERS;", ActiveRecord::QueryLogs.send(:escape_sql_comment, "*/; DROP TABLE USERS;/*")
<ide> assert_equal "; DROP TABLE USERS;", ActiveRecord::QueryLogs.send(:escape_sql_comment, "**//; DROP TABLE USERS;/*")
<ide> def test_empty_comments_are_not_added
<ide> end
<ide> end
<ide>
<add> def test_sql_commenter_format
<add> ActiveRecord::QueryLogs.update_formatter(:sqlcommenter)
<add> assert_sql(%r{/\*application='active_record'\*/}) do
<add> Dashboard.first
<add> end
<add> end
<add>
<ide> def test_custom_basic_tags
<ide> ActiveRecord::QueryLogs.tags = [ :application, { custom_string: "test content" } ]
<ide>
<ide><path>guides/source/configuring.md
<ide> Define an `Array` specifying the key/value tags to be inserted in an SQL
<ide> comment. Defaults to `[ :application ]`, a predefined tag returning the
<ide> application name.
<ide>
<add>#### `config.active_record.query_log_tags_format`
<add>
<add>A `Symbol` specifying the formatter to use for tags. Valid values are `:sqlcommenter` and `:legacy`. Defaults to `:legacy`.
<add>
<ide> #### `config.active_record.cache_query_log_tags`
<ide>
<ide> Specifies whether or not to enable caching of query log tags. For applications
<ide><path>railties/test/application/query_logs_test.rb
<ide> def index
<ide> end
<ide>
<ide> def dynamic_content
<del> Time.now.to_f
<add> Time.now.to_f.to_s
<ide> end
<ide> end
<ide> RUBY
<ide> def perform
<ide> end
<ide>
<ide> def dynamic_content
<del> Time.now.to_f
<add> Time.now.to_f.to_s
<ide> end
<ide> end
<ide> RUBY
<ide> def app
<ide> assert_includes comment, "controller:users"
<ide> end
<ide>
<add> test "sqlcommenter formatting works when specified" do
<add> add_to_config "config.active_record.query_log_tags_enabled = true"
<add> add_to_config "config.active_record.query_log_tags_format = :sqlcommenter"
<add>
<add> add_to_config "config.active_record.query_log_tags = [ :pid ]"
<add>
<add> boot_app
<add>
<add> get "/"
<add> comment = last_response.body.strip
<add>
<add> assert_match(/pid='\d+'/, comment)
<add> assert_includes comment, "controller='users'"
<add> end
<add>
<ide> test "controller actions tagging filters can be disabled" do
<ide> add_to_config "config.active_record.query_log_tags_enabled = true"
<ide> add_to_config "config.action_controller.log_query_tags_around_actions = false" | 8 |
Text | Text | add missing punctuation in changelog. [ci skip] | 1ceeadad3b3431e97ab333545bd9bbf263c0ecc7 | <ide><path>activesupport/CHANGELOG.md
<del>* Patch `Delegator` to work with `#try`
<add>* Patch `Delegator` to work with `#try`.
<ide>
<del> Fixes #5790
<add> Fixes #5790.
<ide>
<ide> *Nate Smith*
<ide> | 1 |
Ruby | Ruby | use class_attribute so we dont bleed | 0093dafd804c59ea1685cdab2a79b37d63c8dbf0 | <ide><path>actionpack/lib/action_controller/metal/conditional_get.rb
<add>require 'active_support/core_ext/class/attribute'
<add>
<ide> module ActionController
<ide> module ConditionalGet
<ide> extend ActiveSupport::Concern
<ide>
<ide> include RackDelegation
<ide> include Head
<ide>
<del> included { cattr_accessor(:etaggers) { Array.new } }
<add> included do
<add> class_attribute :etaggers
<add> self.etaggers = []
<add> end
<ide>
<ide> module ClassMethods
<ide> # Allows you to consider additional controller-wide information when generating an etag. | 1 |
Javascript | Javascript | add "coiney madoguchi" to showcase | 298dc7c15214e85564e5b76105d335fc4b4a6acd | <ide><path>website/src/react-native/showcase.js
<ide> var apps = [
<ide> link: 'https://www.codementor.io/downloads',
<ide> author: 'Codementor',
<ide> },
<add> {
<add> name: 'Coiney窓口',
<add> icon: 'http://a4.mzstatic.com/us/r30/Purple69/v4/c9/bc/3a/c9bc3a29-9c11-868f-b960-ca46d5fcd509/icon175x175.jpeg',
<add> link: 'https://itunes.apple.com/jp/app/coiney-chuang-kou/id1069271336?mt=8',
<add> author: 'Coiney, Inc.'
<add> },
<ide> {
<ide> name: 'Collegiate - Learn Anywhere',
<ide> icon: 'http://a3.mzstatic.com/us/r30/Purple69/v4/17/a9/60/17a960d3-8cbd-913a-9f08-ebd9139c116c/icon175x175.png', | 1 |
Text | Text | fix typo in http2 doc | 29de91b64f2ec18e9d91fb89f58f371452f7b76e | <ide><path>doc/api/http2.md
<ide> Shortcut for `http2stream.rstStream()` using error code `0x02` (Internal Error).
<ide> added: v8.4.0
<ide> -->
<ide>
<del>* Value: {Http2Sesssion}
<add>* Value: {Http2Session}
<ide>
<ide> A reference to the `Http2Session` instance that owns this `Http2Stream`. The
<ide> value will be `undefined` after the `Http2Stream` instance is destroyed. | 1 |
PHP | PHP | fix typo variable name in _deletedependent() | e1c27af9e9d7d6d8a2c36f6aef63fa266afb7fae | <ide><path>lib/Cake/Model/Model.php
<ide> protected function _deleteDependent($id, $cascade) {
<ide> return;
<ide> }
<ide> if (!empty($this->__backAssociation)) {
<del> $savedAssociatons = $this->__backAssociation;
<add> $savedAssociations = $this->__backAssociation;
<ide> $this->__backAssociation = array();
<ide> }
<ide>
<ide> protected function _deleteDependent($id, $cascade) {
<ide> }
<ide> }
<ide> }
<del> if (isset($savedAssociatons)) {
<del> $this->__backAssociation = $savedAssociatons;
<add> if (isset($savedAssociations)) {
<add> $this->__backAssociation = $savedAssociations;
<ide> }
<ide> }
<ide> | 1 |
Text | Text | fix community link [404 not found] | a26db2292f153b825101f49577ce9b6f3a0a2cf6 | <ide><path>README.md
<ide> <span> · </span>
<ide> <a href="https://reactnative.dev/docs/contributing">Contribute</a>
<ide> <span> · </span>
<del> <a href="https://reactnative.dev/en/help">Community</a>
<add> <a href="https://reactnative.dev/help">Community</a>
<ide> <span> · </span>
<ide> <a href="https://github.com/facebook/react-native/blob/master/.github/SUPPORT.md">Support</a>
<ide> </h3> | 1 |
Text | Text | update docs on django-oauth-toolkit | 059947028bd9e741a06ef40b3d9f0bd9cecae090 | <ide><path>docs/api-guide/authentication.md
<ide> The following third party packages are also available.
<ide>
<ide> ## Django OAuth Toolkit
<ide>
<del>The [Django OAuth Toolkit][django-oauth-toolkit] package provides OAuth 2.0 support, and works with Python 2.7 and Python 3.3+. The package is maintained by [Evonove][evonove] and uses the excellent [OAuthLib][oauthlib]. The package is well documented, and well supported and is currently our **recommended package for OAuth 2.0 support**.
<add>The [Django OAuth Toolkit][django-oauth-toolkit] package provides OAuth 2.0 support and works with Python 3.4+. The package is maintained by [Evonove][evonove] and uses the excellent [OAuthLib][oauthlib]. The package is well documented, and well supported and is currently our **recommended package for OAuth 2.0 support**.
<ide>
<ide> #### Installation & configuration
<ide> | 1 |
Ruby | Ruby | correct an indent | aec45a6ee66c28f0be7c8d1d608596676fe65550 | <ide><path>Library/Homebrew/patches.rb
<ide> def download!
<ide> private
<ide>
<ide> def external_patches
<del> @patches.select{|p| p.external?}
<add> @patches.select{|p| p.external?}
<ide> end
<ide>
<ide> # Collects the urls and output names of all external patches | 1 |
Javascript | Javascript | update usdzexporter.js | 061ac286ba1f92bc01ff95a4f6f99edc95ff5c8a | <ide><path>examples/jsm/exporters/USDZExporter.js
<ide> function buildMaterial( material, textures ) {
<ide> float outputs:r
<ide> float outputs:g
<ide> float outputs:b
<del> float3 outputs:rgb
<add> float outputs:a
<add> float3 outputs:rgba
<ide> }`;
<ide>
<ide> }
<ide> function buildMaterial( material, textures ) {
<ide>
<ide> }
<ide>
<del> inputs.push( `${ pad }float inputs:opacity = ${ material.opacity }` );
<add> if ( material.alphaMap !== null ) {
<add>
<add> inputs.push( `${pad}float inputs:opacity.connect = </Materials/Material_${material.id}/Texture_${material.alphaMap.id}_opacity.outputs:r>` );
<add> inputs.push( `${pad}float inputs:opacityThreshold = 0.0001` );
<add>
<add> samplers.push( buildTexture( material.alphaMap, 'opacity' ) );
<add>
<add> } else if ( material.map !== null && material.map.format === 1023 ) {
<add>
<add> inputs.push( `${pad}float inputs:opacity.connect = </Materials/Material_${material.id}/Texture_${material.map.id}_diffuse.outputs:a>` );
<add> inputs.push( `${pad}float inputs:opacityThreshold = 0.0001` );
<add>
<add> } else {
<add>
<add> inputs.push( `${pad}float inputs:opacity = ${material.opacity}` );
<add>
<add> }
<ide>
<ide> if ( material.isMeshPhysicalMaterial ) {
<ide> | 1 |
Ruby | Ruby | check raise deprecation exceptions value | c56625f8b76f5e33ac5e086af4c9d3d79c593218 | <ide><path>Library/Homebrew/utils.rb
<ide> def odeprecated(method, replacement = nil, options = {})
<ide> #{caller_message}#{tap_message}
<ide> EOS
<ide>
<del> if ARGV.homebrew_developer? || options[:die]
<add> if ARGV.homebrew_developer? || options[:die] ||
<add> Homebrew.raise_deprecation_exceptions?
<ide> raise FormulaMethodDeprecatedError, message
<ide> else
<ide> opoo "#{message}\n" | 1 |
Mixed | Ruby | add a method full_messages_for to the errors class | ec1b715b0e6f0a345b94a44b2a03b6044091a706 | <ide><path>activemodel/CHANGELOG.md
<ide> ## Rails 4.0.0 (unreleased) ##
<ide>
<add>* Add ActiveModel::Errors#full_messages_for, a method that returns all the error
<add> messages for a given attribute.
<add>
<add> *Volodymyr Shatsky*
<add>
<ide> * Added a method so that validations can be easily cleared on a model.
<ide> For example:
<ide>
<ide><path>activemodel/lib/active_model/errors.rb
<ide> def full_messages
<ide> map { |attribute, message| full_message(attribute, message) }
<ide> end
<ide>
<add> # Returns all the full error messages for a given attribute in an array.
<add> #
<add> # class Person
<add> # validates_presence_of :name, :email
<add> # validates_length_of :name, in: 5..30
<add> # end
<add> #
<add> # person = Person.create()
<add> # person.errors.full_messages_for(:name)
<add> # # => ["Name is too short (minimum is 5 characters)", "Name can't be blank"]
<add> def full_messages_for(attribute)
<add> (get(attribute) || []).map { |message| full_message(attribute, message) }
<add> end
<add>
<ide> # Returns a full message for a given attribute.
<ide> #
<ide> # person.errors.full_message(:name, 'is invalid') # => "Name is invalid"
<ide><path>activemodel/test/cases/errors_test.rb
<ide> def test_has_key?
<ide> person.errors.add(:name, "can not be nil")
<ide> assert_equal ["name can not be blank", "name can not be nil"], person.errors.full_messages
<ide> end
<add>
<add> test 'full_messages_for should contain all the messages for a given attribute' do
<add> person = Person.new
<add> person.errors.add(:name, "can not be blank")
<add> person.errors.add(:name, "can not be nil")
<add> assert_equal ["name can not be blank", "name can not be nil"], person.errors.full_messages_for(:name)
<add> end
<add>
<add> test 'full_messages_for should not contain messages for another attributes' do
<add> person = Person.new
<add> person.errors.add(:name, "can not be blank")
<add> person.errors.add(:email, "can not be blank")
<add> assert_equal ["name can not be blank"], person.errors.full_messages_for(:name)
<add> end
<add>
<add> test "full_messages_for should return an empty array in case if errors hash doesn't contain a given attribute" do
<add> person = Person.new
<add> person.errors.add(:name, "can not be blank")
<add> assert_equal [], person.errors.full_messages_for(:email)
<add> end
<ide>
<ide> test 'full_message should return the given message if attribute equals :base' do
<ide> person = Person.new | 3 |
PHP | PHP | add macroable trait to blueprint class | d29f5eb315b330b0e0be3591f032acf016797b5a | <ide><path>src/Illuminate/Database/Schema/Blueprint.php
<ide> use Closure;
<ide> use Illuminate\Support\Fluent;
<ide> use Illuminate\Database\Connection;
<add>use Illuminate\Support\Traits\Macroable;
<ide> use Illuminate\Database\Schema\Grammars\Grammar;
<ide>
<ide> class Blueprint
<ide> {
<add> use Macroable;
<add>
<ide> /**
<ide> * The table the blueprint describes.
<ide> * | 1 |
PHP | PHP | use getter methods instead of properties | 5e355eee0215c25ce0f57af534c149578459aaac | <ide><path>tests/TestCase/Controller/Component/RequestHandlerComponentTest.php
<ide> public function testNoViewClassExtension()
<ide> public function testUnrecognizedExtensionFailure()
<ide> {
<ide> Router::extensions(['json', 'foo'], false);
<del> $this->Controller->setRequest($this->Controller->request->withParam('_ext', 'foo'));
<add> $this->Controller->setRequest($this->Controller->getRequest()->withParam('_ext', 'foo'));
<ide> $event = new Event('Controller.startup', $this->Controller);
<ide> $this->RequestHandler->startup($event);
<ide> $this->Controller->getEventManager()->on('Controller.beforeRender', function () {
<del> return $this->Controller->response;
<add> return $this->Controller->getResponse();
<ide> });
<ide> $this->Controller->render();
<ide> $this->assertEquals('RequestHandlerTest' . DS . 'csv', $this->Controller->viewBuilder()->getTemplatePath()); | 1 |
Javascript | Javascript | update test-dns.js to work with latest api | 3c97a4391af24aea35cb5efa7a40956f7a51d547 | <ide><path>test/disabled/test-dns.js
<ide> while (i--) {
<ide> "| sed -E 's/[[:space:]]+/ /g' | cut -d ' ' -f 5- " +
<ide> "| sed -e 's/\\.$//'";
<ide>
<del> sys.exec(hostCmd).addCallback(checkDnsRecord(hosts[i], records[j]));
<add> sys.exec(hostCmd, checkDnsRecord(hosts[i], records[j]));
<ide> }
<ide> }
<ide>
<ide> function checkDnsRecord(host, record) {
<ide> var myHost = host,
<ide> myRecord = record;
<del> return function(stdout) {
<del> var expected = stdout.substr(0, stdout.length - 1).split("\n");
<del>
<del> var resolution = dns.resolve(myHost, myRecord);
<add> return function(err, stdout) {
<add> var expected = [];
<add> if(stdout.length)
<add> expected = stdout.substr(0, stdout.length - 1).split("\n");
<ide>
<ide> switch (myRecord) {
<ide> case "A":
<ide> case "AAAA":
<del> resolution.addCallback(function (result, ttl, cname) {
<add> dns.resolve(myHost, myRecord, function (error, result, ttl, cname) {
<add> if(error) result = [];
<add>
<ide> cmpResults(expected, result, ttl, cname);
<ide>
<ide> // do reverse lookup check
<ide> function checkDnsRecord(host, record) {
<ide> "| cut -d \" \" -f 5-" +
<ide> "| sed -e 's/\\.$//'";
<ide>
<del> sys.exec(reverseCmd).addCallback(checkReverse(ip));
<add> sys.exec(reverseCmd, checkReverse(ip));
<ide> }
<ide> });
<ide> break;
<ide> case "MX":
<del> resolution.addCallback(function (result, ttl, cname) {
<add> dns.resolve(myHost, myRecord, function (error, result, ttl, cname) {
<add> if(error) result = [];
<add>
<ide> var strResult = [];
<ide> var ll = result.length;
<ide> while (ll--) {
<ide> function checkDnsRecord(host, record) {
<ide> });
<ide> break;
<ide> case "TXT":
<del> resolution.addCallback(function (result, ttl, cname) {
<add> dns.resolve(myHost, myRecord, function (error, result, ttl, cname) {
<add> if(error) result = [];
<add>
<ide> var strResult = [];
<ide> var ll = result.length;
<ide> while (ll--) {
<ide> function checkDnsRecord(host, record) {
<ide> });
<ide> break;
<ide> case "SRV":
<del> resolution.addCallback(function (result, ttl, cname) {
<add> dns.resolve(myHost, myRecord, function (error, result, ttl, cname) {
<add> if(error) result = [];
<add>
<ide> var strResult = [];
<ide> var ll = result.length;
<ide> while (ll--) {
<ide> function checkDnsRecord(host, record) {
<ide> function checkReverse(ip) {
<ide> var myIp = ip;
<ide>
<del> return function (stdout) {
<add> return function (errr, stdout) {
<ide> var expected = stdout.substr(0, stdout.length - 1).split("\n");
<ide>
<del> var reversing = dns.reverse(myIp);
<del>
<del> reversing.addCallback(
<del> function (domains, ttl, cname) {
<del> cmpResults(expected, domains, ttl, cname);
<del> });
<add> reversing = dns.reverse(myIp, function (error, domains, ttl, cname) {
<add> if(error) domains = [];
<add> cmpResults(expected, domains, ttl, cname);
<add> });
<ide> }
<ide> }
<ide>
<ide> function cmpResults(expected, result, ttl, cname) {
<ide> ll = expected.length;
<ide> while (ll--) {
<ide> assert.equal(result[ll], expected[ll]);
<del>// puts("Result " + result[ll] + " was equal to expected " + expected[ll]);
<add> puts("Result " + result[ll] + " was equal to expected " + expected[ll]);
<ide> }
<ide> } | 1 |
Text | Text | fix incorrect url in cli.md | 226eabb1aa4b178c32c002b641bef3688c4097ba | <ide><path>doc/api/cli.md
<ide> $ node --max-old-space-size=1536 index.js
<ide> [`tls.DEFAULT_MAX_VERSION`]: tls.html#tls_tls_default_max_version
<ide> [`tls.DEFAULT_MIN_VERSION`]: tls.html#tls_tls_default_min_version
<ide> [`unhandledRejection`]: process.html#process_event_unhandledrejection
<del>[`worker_threads.threadId`]: worker_threads.html##worker_threads_worker_threadid
<add>[`worker_threads.threadId`]: worker_threads.html#worker_threads_worker_threadid
<ide> [Chrome DevTools Protocol]: https://chromedevtools.github.io/devtools-protocol/
<ide> [REPL]: repl.html
<ide> [ScriptCoverage]: https://chromedevtools.github.io/devtools-protocol/tot/Profiler#type-ScriptCoverage | 1 |
Text | Text | fix backticks in crypto api docs | c2c6fbb0eadc584c1613ed466c50d7e8fc4d3214 | <ide><path>doc/api/crypto.md
<ide> changes:
<ide> `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING` or
<ide> `crypto.constants.RSA_PKCS1_PADDING`.
<ide> * `encoding` {string} The string encoding to use when `buffer`, `key`,
<del> or 'passphrase` are strings.
<add> or `passphrase` are strings.
<ide> * `buffer` {string|ArrayBuffer|Buffer|TypedArray|DataView}
<ide> * Returns: {Buffer} A new `Buffer` with the encrypted content.
<ide> <!--lint enable maximum-line-length remark-lint-->
<ide> changes:
<ide> `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING` or
<ide> `crypto.constants.RSA_PKCS1_PADDING`.
<ide> * `encoding` {string} The string encoding to use when `buffer`, `key`,
<del> or 'passphrase` are strings.
<add> or `passphrase` are strings.
<ide> * `buffer` {string|ArrayBuffer|Buffer|TypedArray|DataView}
<ide> * Returns: {Buffer} A new `Buffer` with the decrypted content.
<ide> <!--lint enable maximum-line-length remark-lint-->
<ide> changes:
<ide> `crypto.constants.RSA_PKCS1_PADDING`, or
<ide> `crypto.constants.RSA_PKCS1_OAEP_PADDING`.
<ide> * `encoding` {string} The string encoding to use when `buffer`, `key`,
<del> `oaepLabel`, or 'passphrase` are strings.
<add> `oaepLabel`, or `passphrase` are strings.
<ide> * `buffer` {string|ArrayBuffer|Buffer|TypedArray|DataView}
<ide> * Returns: {Buffer} A new `Buffer` with the encrypted content.
<ide> <!--lint enable maximum-line-length remark-lint--> | 1 |
Go | Go | get err type in removenetworks() w/ errors.cause() | 6225d1f15c5fd916c3e0ef3afe022f6cc14ac696 | <ide><path>daemon/cluster/executor/container/adapter.go
<ide> import (
<ide> "context"
<ide> "encoding/base64"
<ide> "encoding/json"
<del> "errors"
<ide> "fmt"
<ide> "io"
<ide> "os"
<ide> import (
<ide> "github.com/docker/swarmkit/log"
<ide> gogotypes "github.com/gogo/protobuf/types"
<ide> "github.com/opencontainers/go-digest"
<add> "github.com/pkg/errors"
<ide> "github.com/sirupsen/logrus"
<ide> "golang.org/x/time/rate"
<ide> )
<ide> func (c *containerAdapter) createNetworks(ctx context.Context) error {
<ide> func (c *containerAdapter) removeNetworks(ctx context.Context) error {
<ide> for name, v := range c.container.networksAttachments {
<ide> if err := c.backend.DeleteManagedNetwork(v.Network.ID); err != nil {
<del> switch err.(type) {
<add> switch errors.Cause(err).(type) {
<ide> case *libnetwork.ActiveEndpointsError:
<ide> continue
<ide> case libnetwork.ErrNoSuchNetwork: | 1 |
Text | Text | incorporate changes from code review | 5a1adeae06a6660d43274e10bb60d5d14b7cd178 | <ide><path>docs/Deprecating-Disabling-and-Removing-Formulae.md
<ide> There are many reasons why formulae may be deprecated, disabled, or removed. Thi
<ide>
<ide> This general rule of thumb can be followed:
<ide>
<del>- `deprecate!` should be used for formulae that _should_ no longer be used
<del>- `disable!` should be used for formulae that _cannot_ be used
<del>- Formulae that have been disabled for a long time or have a more serious issue should be removed
<add>- `deprecate!` should be used for formulae that _should_ no longer be used.
<add>- `disable!` should be used for formulae that _cannot_ be used.
<add>- Formulae that have are not longer acceptable in homebrew/core or have been disabled for over a year should be removed.
<ide>
<ide> ## Deprecation
<ide>
<ide> If a user attempts to install a deprecated formula, they will be shown a warning message but the install will succeed.
<ide>
<del>A formula should be deprecated to indicate to users that the formula should not be used and may be disabled in the future. Deprecated formulae should still be able to build from source and all bottles should continue to work. Users who choose to install deprecated formulae should not have any issues.
<add>A formula should be deprecated to indicate to users that the formula should not be used and may be disabled in the future. Deprecated formulae should still be able to build from source and their bottles should continue to work.
<ide>
<ide> The most common reasons for deprecation are when the upstream project is deprecated, unmaintained, or archived.
<ide>
<ide> To deprecate a formula, add a `deprecate!` call. This call should include a depr
<ide> deprecate! date: "YYYY-MM-DD", because: :reason
<ide> ```
<ide>
<del>The `date` parameter should be set to the date that the project became (or will become) deprecated. If there is no clear date but the formula needs to be deprecated, use today's date. If the `date` parameter is set to a date in the future, the formula will not become deprecated until that date. This can be useful if the upstream developers have indicated a date where the project will stop being supported.
<add>The `date` parameter should be set to the date that the project or version became (or will become) deprecated. If there is no clear date but the formula needs to be deprecated, use today's date. If the `date` parameter is set to a date in the future, the formula will not become deprecated until that date. This can be useful if the upstream developers have indicated a date where the project or version will stop being supported.
<ide>
<ide> The `because` parameter can be set to a preset reason (using a symbol) or a custom reason. See the [Deprecate and Disable Reasons](#deprecate-and-disable-reasons) section below for more details about the `because` parameter.
<ide>
<ide> ## Disabling
<ide>
<ide> If a user attempts to install a disabled formula, they will be shown an error message and the install will fail.
<ide>
<del>A formula should be disabled to indicate to users that the formula cannot be used and may be removed in the future. Disabled formulae may not be able to build from source and may not have working bottles. Users who choose to attempt to install disabled formulae will likely run into issues.
<add>A formula should be disabled to indicate to users that the formula cannot be used and will be removed in the future. Disabled formulae may no longer be able to build from source or have working bottles.
<ide>
<ide> The most common reasons for disabling are when the formula cannot be built from source (meaning no bottles can be built), has been deprecated for a long time, the upstream repository has been removed, or the project has no license.
<ide>
<ide> The `because` parameter can be set to a preset reason (using a symbol) or a cust
<ide>
<ide> ## Removal
<ide>
<del>A formula should be removed if there is a serious issue with the formula or the formula has been disabled for a long period of time.
<del>
<del>A formula should be removed if it has been disabled for a long period of time, it has a non-open-source license, or there is another serious issue with the formula that makes it not compatible with homebrew/core.
<add>A formula should be removed if it does not meet our criteria for [acceptable formulae](Acceptable-Formulae.md) or [versioned formulae](Versions.md), has a non-open-source license, or has been disabled for a long period of time.
<ide>
<ide> **Note: disabled formulae in homebrew/core will be automatically removed one year after their disable date**
<ide>
<ide> ## Deprecate and Disable Reasons
<ide>
<del>When a formula is deprecated or disabled, a reason explaining the action should be provided.
<add>When a formula is deprecated or disabled, a reason explaining the action must be provided.
<ide>
<del>There are two ways to indicate the reason. The preferred way is to use a pre-existing symbol to indicate the reason. The available symbols are:
<add>There are two ways to indicate the reason. The preferred way is to use a pre-existing symbol to indicate the reason. The available symbols are listed below and can be found in the [`DeprecateDisable` module](https://rubydoc.brew.sh/DeprecateDisable.html#DEPRECATE_DISABLE_REASONS-constant):
<ide>
<del>- `:does_not_build`: the formulae that cannot be build from source
<del>- `:no_license`: the formulae does not have a license
<add>- `:does_not_build`: the formula cannot be built from source
<add>- `:no_license`: the formula does not have a license
<ide> - `:repo_archived`: the upstream repository has been archived
<ide> - `:repo_removed`: the upstream repository has been removed
<ide> - `:unmaintained`: the project appears to be abandoned
<ide> disable! date: "2020-01-01", because: :does_not_build
<ide>
<ide> If these pre-existing reasons do not fit, a custom reason can be specified. These reasons should be written to fit into the sentence `<formula> has been deprecated/disabled because it <reason>!`.
<ide>
<del>Here are examples of a well-worded custom reason:
<add>A well-worded example of a custom reason would be:
<ide>
<ide> ```ruby
<ide> # Warning: <formula> has been deprecated because it fetches unversioned dependencies at runtime!
<ide> deprecate! date: "2020-01-01", because: "fetches unversioned dependencies at runtime"
<ide> ```
<ide>
<del>```ruby
<del># Error: <formula> has been disabled because it requires Python 2.7!
<del>disable! date: "2020-01-01", because: "requires Python 2.7"
<del>```
<del>
<del>Here is an example of a poorly-worded custom reason:
<del>
<del>```ruby
<del># Warning: <formula> has been deprecated because it the formula fetches unversioned dependencies at runtime!
<del>deprecate! date: "2020-01-01", because: "the formula fetches unversioned dependencies at runtime"
<del>```
<add>A poorly-worded example of a custom reason would be:
<ide>
<ide> ```ruby
<ide> # Error: <formula> has been disabled because it invalid license!
<ide><path>docs/Formula-Cookbook.md
<ide> You can set environment variables in a formula's `install` method using `ENV["VA
<ide>
<ide> In summary, environment variables used by a formula need to conform to these filtering rules in order to be available.
<ide>
<add>### Deprecating and disabling a formula
<add>
<add>See our [Deprecating, Disabling, and Removing Formulae](Deprecating-Disabling-and-Removing-Formulae.md) documentation for more information about how and when to deprecate or disable a formula.
<add>
<ide> ## Updating formulae
<ide>
<ide> Eventually a new version of the software will be released. In this case you should update the [`url`](https://rubydoc.brew.sh/Formula#url-class_method) and [`sha256`](https://rubydoc.brew.sh/Formula#sha256%3D-class_method). If a [`revision`](https://rubydoc.brew.sh/Formula#revision%3D-class_method) line exists outside any `bottle do` block it should be removed. | 2 |
Javascript | Javascript | fix minor issues and linter | ef78c1b69181c55029ec25be9f4ef87f03a9f0f5 | <ide><path>src/materials/Material.js
<ide> function Material() {
<ide>
<ide> this.toneMapped = true;
<ide> this.userData = {};
<del>
<ide> this.needsUpdate = true;
<ide>
<ide> }
<ide><path>src/renderers/WebGLRenderer.js
<ide> function WebGLRenderer( parameters ) {
<ide>
<ide> var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
<ide> _context = parameters.context !== undefined ? parameters.context : null,
<add>
<ide> _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
<ide> _depth = parameters.depth !== undefined ? parameters.depth : true,
<ide> _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
<ide> function WebGLRenderer( parameters ) {
<ide>
<ide> if ( capabilities.multiview ) {
<ide>
<del> multiview.detachRenderTarget( camera );
<add> multiview.detachCamera( camera );
<ide>
<ide> }
<ide>
<ide><path>src/renderers/webgl/WebGLCapabilities.js
<ide> function WebGLCapabilities( gl, extensions, parameters ) {
<ide> var maxSamples = isWebGL2 ? gl.getParameter( gl.MAX_SAMPLES ) : 0;
<ide>
<ide> var multiviewExt = extensions.get( 'OVR_multiview2' );
<del> var multiview = isWebGL2 && ( !! multiviewExt ) && ! gl.getContextAttributes().antialias;
<add> var multiview = isWebGL2 && !! multiviewExt && ! gl.getContextAttributes().antialias;
<ide> var maxMultiviewViews = multiview ? gl.getParameter( multiviewExt.MAX_VIEWS_OVR ) : 0;
<ide>
<ide> return {
<ide><path>src/renderers/webgl/WebGLMultiview.js
<ide> function WebGLMultiview( renderer, gl ) {
<ide>
<ide> }
<ide>
<del> function detachRenderTarget( camera ) {
<add> function detachCamera( camera ) {
<ide>
<ide> if ( renderTarget !== renderer.getRenderTarget() ) return;
<ide>
<ide> function WebGLMultiview( renderer, gl ) {
<ide>
<ide>
<ide> this.attachCamera = attachCamera;
<del> this.detachRenderTarget = detachRenderTarget;
<add> this.detachCamera = detachCamera;
<ide> this.updateCameraProjectionMatricesUniform = updateCameraProjectionMatricesUniform;
<ide> this.updateCameraViewMatricesUniform = updateCameraViewMatricesUniform;
<ide> this.updateObjectMatricesUniforms = updateObjectMatricesUniforms;
<ide><path>src/renderers/webgl/WebGLProgram.js
<ide> import { WebGLUniforms } from './WebGLUniforms.js';
<ide> import { WebGLShader } from './WebGLShader.js';
<ide> import { ShaderChunk } from '../shaders/ShaderChunk.js';
<del>import { WebGLMultiviewRenderTarget } from '../WebGLMultiviewRenderTarget.js';
<ide> import { NoToneMapping, AddOperation, MixOperation, MultiplyOperation, EquirectangularRefractionMapping, CubeRefractionMapping, SphericalReflectionMapping, EquirectangularReflectionMapping, CubeUVRefractionMapping, CubeUVReflectionMapping, CubeReflectionMapping, PCFSoftShadowMap, PCFShadowMap, VSMShadowMap, ACESFilmicToneMapping, CineonToneMapping, Uncharted2ToneMapping, ReinhardToneMapping, LinearToneMapping, GammaEncoding, RGBDEncoding, RGBM16Encoding, RGBM7Encoding, RGBEEncoding, sRGBEncoding, LinearEncoding, LogLuvEncoding } from '../../constants.js';
<ide>
<ide> var programIdCount = 0; | 5 |
Java | Java | reduce visibility of hint factory methods | cfd37d948d935258c55dd403bb112328eb402cf5 | <ide><path>spring-core/src/main/java/org/springframework/aot/hint/ExecutableHint.java
<ide> private ExecutableHint(Builder builder) {
<ide> * @param parameterTypes the parameter types of the constructor
<ide> * @return a builder
<ide> */
<del> public static Builder ofConstructor(List<TypeReference> parameterTypes) {
<add> static Builder ofConstructor(List<TypeReference> parameterTypes) {
<ide> return new Builder("<init>", parameterTypes);
<ide> }
<ide>
<ide> public static Builder ofConstructor(List<TypeReference> parameterTypes) {
<ide> * @param parameterTypes the parameter types of the method
<ide> * @return a builder
<ide> */
<del> public static Builder ofMethod(String name, List<TypeReference> parameterTypes) {
<add> static Builder ofMethod(String name, List<TypeReference> parameterTypes) {
<ide> return new Builder(name, parameterTypes);
<ide> }
<ide>
<ide><path>spring-core/src/main/java/org/springframework/aot/hint/TypeHint.java
<ide> private TypeHint(Builder builder) {
<ide> * @param type the type to use
<ide> * @return a builder
<ide> */
<del> public static Builder of(TypeReference type) {
<add> static Builder of(TypeReference type) {
<ide> Assert.notNull(type, "'type' must not be null");
<ide> return new Builder(type);
<ide> }
<ide> public static class Builder {
<ide> private final Set<MemberCategory> memberCategories = new HashSet<>();
<ide>
<ide>
<del> public Builder(TypeReference type) {
<add> Builder(TypeReference type) {
<ide> this.type = type;
<ide> }
<ide> | 2 |
Text | Text | clarify replit use of env files | 1ba88935b2c9999b1c77b3fdcdd852cf717a738e | <ide><path>curriculum/challenges/english/05-apis-and-microservices/basic-node-and-express/use-the-.env-file.md
<ide> The environment variables are accessible from the app as `process.env.VAR_NAME`.
<ide>
<ide> Let's add an environment variable as a configuration option.
<ide>
<del>Create a `.env` file in the root of your project directory, and store the variable `MESSAGE_STYLE=uppercase` in it. Then, in the GET `/json` route handler that you created in the last challenge, transform the response object’s message to uppercase if `process.env.MESSAGE_STYLE` equals `uppercase`. The response object should become `{"message": "HELLO JSON"}`.
<add>Create a `.env` file in the root of your project directory, and store the variable `MESSAGE_STYLE=uppercase` in it.
<add>
<add>Then, in the `/json` GET route handler you created in the last challenge, transform the response object's message to uppercase if `process.env.MESSAGE_STYLE` equals `uppercase`. The response object should either be `{"message": "Hello json"}` or `{"message": "HELLO JSON"}`, depending on the `MESSAGE_STYLE` value.
<add>
<add>**Note:** If you are using Replit, you cannot create a `.env` file. Instead, use the built-in <dfn>SECRETS</dfn> tab to add the variable.
<ide>
<ide> # --hints--
<ide> | 1 |
Java | Java | show columns in redboxes | 8c1b773e4d81ef452a70ae073033d6cffd33c5eb | <ide><path>ReactAndroid/src/main/java/com/facebook/react/devsupport/RedBoxDialog.java
<ide> public View getView(int position, View convertView, ViewGroup parent) {
<ide> StackFrame frame = mStack[position - 1];
<ide> FrameViewHolder holder = (FrameViewHolder) convertView.getTag();
<ide> holder.mMethodView.setText(frame.getMethod());
<del> holder.mFileView.setText(frame.getFileName() + ":" + frame.getLine());
<add> final int column = frame.getColumn();
<add> final String columnString = column < 0 ? "" : ":" + column;
<add> holder.mFileView.setText(frame.getFileName() + ":" + frame.getLine() + columnString);
<ide> return convertView;
<ide> }
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/devsupport/StackTraceHelper.java
<ide> public static StackFrame[] convertJavaStackTrace(Throwable exception) {
<ide> stackTrace[i].getFileName(),
<ide> stackTrace[i].getMethodName(),
<ide> stackTrace[i].getLineNumber(),
<del> 0);
<add> -1);
<ide> }
<ide> return result;
<ide> } | 2 |
Go | Go | stop health checks before deleting task | 8b748bd326d102e4188f55b78ebd06fea0770ffc | <ide><path>daemon/monitor.go
<ide> func (daemon *Daemon) setStateCounter(c *container.Container) {
<ide> func (daemon *Daemon) handleContainerExit(c *container.Container, e *libcontainerdtypes.EventInfo) error {
<ide> var exitStatus container.ExitStatus
<ide> c.Lock()
<add>
<add> // Health checks will be automatically restarted if/when the
<add> // container is started again.
<add> daemon.stopHealthchecks(c)
<add>
<ide> tsk, ok := c.Task()
<ide> if ok {
<ide> ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
<ide> func (daemon *Daemon) handleContainerExit(c *container.Container, e *libcontaine
<ide> restart = false
<ide> }
<ide>
<del> // cancel healthcheck here, they will be automatically
<del> // restarted if/when the container is started again
<del> daemon.stopHealthchecks(c)
<ide> attributes := map[string]string{
<ide> "exitCode": strconv.Itoa(exitStatus.ExitCode),
<ide> } | 1 |
Go | Go | move base device creation in separate function | efc1ddd7e3341124a2ebbb8a358f44754b32f310 | <ide><path>daemon/graphdriver/devmapper/deviceset.go
<ide> func (devices *DeviceSet) saveBaseDeviceUUID(baseInfo *devInfo) error {
<ide> return nil
<ide> }
<ide>
<add>func (devices *DeviceSet) createBaseImage() error {
<add> logrus.Debugf("Initializing base device-mapper thin volume")
<add>
<add> // Create initial device
<add> info, err := devices.createRegisterDevice("")
<add> if err != nil {
<add> return err
<add> }
<add>
<add> logrus.Debugf("Creating filesystem on base device-mapper thin volume")
<add>
<add> if err := devices.activateDeviceIfNeeded(info); err != nil {
<add> return err
<add> }
<add>
<add> if err := devices.createFilesystem(info); err != nil {
<add> return err
<add> }
<add>
<add> info.Initialized = true
<add> if err := devices.saveMetadata(info); err != nil {
<add> info.Initialized = false
<add> return err
<add> }
<add>
<add> if err := devices.saveBaseDeviceUUID(info); err != nil {
<add> return fmt.Errorf("Could not query and save base device UUID:%v", err)
<add> }
<add>
<add> return nil
<add>}
<add>
<ide> func (devices *DeviceSet) setupBaseImage() error {
<ide> oldInfo, _ := devices.lookupDeviceWithLock("")
<ide> if oldInfo != nil && oldInfo.Initialized {
<ide> func (devices *DeviceSet) setupBaseImage() error {
<ide> }
<ide> }
<ide>
<del> logrus.Debugf("Initializing base device-mapper thin volume")
<del>
<del> // Create initial device
<del> info, err := devices.createRegisterDevice("")
<del> if err != nil {
<del> return err
<del> }
<del>
<del> logrus.Debugf("Creating filesystem on base device-mapper thin volume")
<del>
<del> if err := devices.activateDeviceIfNeeded(info); err != nil {
<del> return err
<del> }
<del>
<del> if err := devices.createFilesystem(info); err != nil {
<del> return err
<del> }
<del>
<del> info.Initialized = true
<del> if err := devices.saveMetadata(info); err != nil {
<del> info.Initialized = false
<add> // Create new base image device
<add> if err := devices.createBaseImage(); err != nil {
<ide> return err
<ide> }
<ide>
<del> if err := devices.saveBaseDeviceUUID(info); err != nil {
<del> return fmt.Errorf("Could not query and save base device UUID:%v", err)
<del> }
<del>
<ide> return nil
<ide> }
<ide> | 1 |
Javascript | Javascript | use new buffer api where appropriate | 8ed44ff1c4b48fe62a0aef88bd1d0385f0eadd03 | <ide><path>benchmark/streams/pipe.js
<ide> const bench = common.createBenchmark(main, {
<ide> });
<ide>
<ide> function main({ n }) {
<del> const b = new Buffer(1024);
<add> const b = Buffer.alloc(1024);
<ide> const r = new Readable();
<ide> const w = new Writable();
<ide>
<ide><path>benchmark/streams/readable-bigread.js
<ide> const bench = common.createBenchmark(main, {
<ide> });
<ide>
<ide> function main({ n }) {
<del> const b = new Buffer(32);
<add> const b = Buffer.alloc(32);
<ide> const s = new Readable();
<ide> function noop() {}
<ide> s._read = noop;
<ide><path>benchmark/streams/readable-bigunevenread.js
<ide> const bench = common.createBenchmark(main, {
<ide> });
<ide>
<ide> function main({ n }) {
<del> const b = new Buffer(32);
<add> const b = Buffer.alloc(32);
<ide> const s = new Readable();
<ide> function noop() {}
<ide> s._read = noop;
<ide><path>benchmark/streams/readable-readall.js
<ide> const bench = common.createBenchmark(main, {
<ide> });
<ide>
<ide> function main({ n }) {
<del> const b = new Buffer(32);
<add> const b = Buffer.alloc(32);
<ide> const s = new Readable();
<ide> function noop() {}
<ide> s._read = noop;
<ide><path>benchmark/streams/readable-unevenread.js
<ide> const bench = common.createBenchmark(main, {
<ide> });
<ide>
<ide> function main({ n }) {
<del> const b = new Buffer(32);
<add> const b = Buffer.alloc(32);
<ide> const s = new Readable();
<ide> function noop() {}
<ide> s._read = noop;
<ide><path>test/async-hooks/test-udpsendwrap.js
<ide> const sock = dgram
<ide>
<ide> function onlistening() {
<ide> sock.send(
<del> new Buffer(2), 0, 2, sock.address().port,
<add> Buffer.alloc(2), 0, 2, sock.address().port,
<ide> undefined, common.mustCall(onsent));
<ide>
<ide> // init not called synchronously because dns lookup always wraps
<ide><path>test/parallel/test-buffer-badhex.js
<ide> const assert = require('assert');
<ide> {
<ide> const buf = Buffer.alloc(4);
<ide> assert.strictEqual(buf.length, 4);
<del> assert.deepStrictEqual(buf, new Buffer([0, 0, 0, 0]));
<add> assert.deepStrictEqual(buf, Buffer.from([0, 0, 0, 0]));
<ide> assert.strictEqual(buf.write('abcdxx', 0, 'hex'), 2);
<del> assert.deepStrictEqual(buf, new Buffer([0xab, 0xcd, 0x00, 0x00]));
<add> assert.deepStrictEqual(buf, Buffer.from([0xab, 0xcd, 0x00, 0x00]));
<ide> assert.strictEqual(buf.toString('hex'), 'abcd0000');
<ide> assert.strictEqual(buf.write('abcdef01', 0, 'hex'), 4);
<del> assert.deepStrictEqual(buf, new Buffer([0xab, 0xcd, 0xef, 0x01]));
<add> assert.deepStrictEqual(buf, Buffer.from([0xab, 0xcd, 0xef, 0x01]));
<ide> assert.strictEqual(buf.toString('hex'), 'abcdef01');
<ide>
<ide> const copy = Buffer.from(buf.toString('hex'), 'hex');
<ide> const assert = require('assert');
<ide>
<ide> {
<ide> const buf = Buffer.alloc(4);
<del> assert.deepStrictEqual(buf, new Buffer([0, 0, 0, 0]));
<add> assert.deepStrictEqual(buf, Buffer.from([0, 0, 0, 0]));
<ide> assert.strictEqual(buf.write('xxabcd', 0, 'hex'), 0);
<del> assert.deepStrictEqual(buf, new Buffer([0, 0, 0, 0]));
<add> assert.deepStrictEqual(buf, Buffer.from([0, 0, 0, 0]));
<ide> assert.strictEqual(buf.write('xxab', 1, 'hex'), 0);
<del> assert.deepStrictEqual(buf, new Buffer([0, 0, 0, 0]));
<add> assert.deepStrictEqual(buf, Buffer.from([0, 0, 0, 0]));
<ide> assert.strictEqual(buf.write('cdxxab', 0, 'hex'), 1);
<del> assert.deepStrictEqual(buf, new Buffer([0xcd, 0, 0, 0]));
<add> assert.deepStrictEqual(buf, Buffer.from([0xcd, 0, 0, 0]));
<ide> }
<ide>
<ide> {
<ide><path>test/parallel/test-buffer-fill.js
<ide> assert.strictEqual(
<ide>
<ide> // Test that bypassing 'length' won't cause an abort.
<ide> common.expectsError(() => {
<del> const buf = new Buffer('w00t');
<add> const buf = Buffer.from('w00t');
<ide> Object.defineProperty(buf, 'length', {
<ide> value: 1337,
<ide> enumerable: true
<ide><path>test/parallel/test-buffer-indexof.js
<ide> assert.strictEqual(buf_bc.lastIndexOf('你好', 5, 'binary'), -1);
<ide> assert.strictEqual(buf_bc.lastIndexOf(Buffer.from('你好'), 7), -1);
<ide>
<ide> // Test lastIndexOf on a longer buffer:
<del>const bufferString = new Buffer('a man a plan a canal panama');
<add>const bufferString = Buffer.from('a man a plan a canal panama');
<ide> assert.strictEqual(15, bufferString.lastIndexOf('canal'));
<ide> assert.strictEqual(21, bufferString.lastIndexOf('panama'));
<ide> assert.strictEqual(0, bufferString.lastIndexOf('a man a plan a canal panama'));
<ide> const parts = [];
<ide> for (let i = 0; i < 1000000; i++) {
<ide> parts.push((countBits(i) % 2 === 0) ? 'yolo' : 'swag');
<ide> }
<del>const reallyLong = new Buffer(parts.join(' '));
<add>const reallyLong = Buffer.from(parts.join(' '));
<ide> assert.strictEqual('yolo swag swag yolo', reallyLong.slice(0, 19).toString());
<ide>
<ide> // Expensive reverse searches. Stress test lastIndexOf:
<ide><path>test/parallel/test-buffer-zero-fill.js
<ide> require('../common');
<ide> const assert = require('assert');
<ide>
<add>// Tests deprecated Buffer API on purpose
<ide> const buf1 = Buffer(100);
<ide> const buf2 = new Buffer(100);
<ide>
<ide><path>test/parallel/test-net-socket-byteswritten.js
<ide> server.listen(0, common.mustCall(function() {
<ide> socket.cork();
<ide>
<ide> socket.write('one');
<del> socket.write(new Buffer('twø', 'utf8'));
<add> socket.write(Buffer.from('twø', 'utf8'));
<ide>
<ide> socket.uncork();
<ide>
<ide><path>test/parallel/test-zlib-empty-buffer.js
<ide> const common = require('../common');
<ide> const zlib = require('zlib');
<ide> const { inspect, promisify } = require('util');
<ide> const assert = require('assert');
<del>const emptyBuffer = new Buffer(0);
<add>const emptyBuffer = Buffer.alloc(0);
<ide>
<ide> common.crashOnUnhandledRejection();
<ide> | 12 |
Javascript | Javascript | increase coverage for exec() functions | 58cb9cde91f9b6851e98e590a54db5d8980674f7 | <ide><path>test/parallel/test-child-process-exec-buffer.js
<del>'use strict';
<del>const common = require('../common');
<del>const assert = require('assert');
<del>const exec = require('child_process').exec;
<del>const os = require('os');
<del>const str = 'hello';
<del>
<del>// default encoding
<del>exec('echo ' + str, common.mustCall(function(err, stdout, stderr) {
<del> assert.strictEqual(typeof stdout, 'string', 'Expected stdout to be a string');
<del> assert.strictEqual(typeof stderr, 'string', 'Expected stderr to be a string');
<del> assert.strictEqual(str + os.EOL, stdout);
<del>}));
<del>
<del>// no encoding (Buffers expected)
<del>exec('echo ' + str, {
<del> encoding: null
<del>}, common.mustCall(function(err, stdout, stderr) {
<del> assert.strictEqual(stdout instanceof Buffer, true,
<del> 'Expected stdout to be a Buffer');
<del> assert.strictEqual(stderr instanceof Buffer, true,
<del> 'Expected stderr to be a Buffer');
<del> assert.strictEqual(str + os.EOL, stdout.toString());
<del>}));
<ide><path>test/parallel/test-child-process-exec-encoding.js
<add>'use strict';
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const cp = require('child_process');
<add>const stdoutData = 'foo';
<add>const stderrData = 'bar';
<add>const expectedStdout = `${stdoutData}\n`;
<add>const expectedStderr = `${stderrData}\n`;
<add>
<add>if (process.argv[2] === 'child') {
<add> // The following console calls are part of the test.
<add> console.log(stdoutData);
<add> console.error(stderrData);
<add>} else {
<add> function run(options, callback) {
<add> const cmd = `${process.execPath} ${__filename} child`;
<add>
<add> cp.exec(cmd, options, common.mustCall((err, stdout, stderr) => {
<add> assert.ifError(err);
<add> callback(stdout, stderr);
<add> }));
<add> }
<add>
<add> // Test default encoding, which should be utf8.
<add> run({}, (stdout, stderr) => {
<add> assert.strictEqual(typeof stdout, 'string');
<add> assert.strictEqual(typeof stderr, 'string');
<add> assert.strictEqual(stdout, expectedStdout);
<add> assert.strictEqual(stderr, expectedStderr);
<add> });
<add>
<add> // Test explicit utf8 encoding.
<add> run({ encoding: 'utf8' }, (stdout, stderr) => {
<add> assert.strictEqual(typeof stdout, 'string');
<add> assert.strictEqual(typeof stderr, 'string');
<add> assert.strictEqual(stdout, expectedStdout);
<add> assert.strictEqual(stderr, expectedStderr);
<add> });
<add>
<add> // Test cases that result in buffer encodings.
<add> [undefined, null, 'buffer', 'invalid'].forEach((encoding) => {
<add> run({ encoding }, (stdout, stderr) => {
<add> assert(stdout instanceof Buffer);
<add> assert(stdout instanceof Buffer);
<add> assert.strictEqual(stdout.toString(), expectedStdout);
<add> assert.strictEqual(stderr.toString(), expectedStderr);
<add> });
<add> });
<add>} | 2 |
Go | Go | implement docker cp with standalone client lib | 1b2b91ba43dc6fa1b4b758fc5a8090ce6cc597ff | <ide><path>api/client/cp.go
<ide> package client
<ide>
<ide> import (
<del> "encoding/base64"
<del> "encoding/json"
<ide> "fmt"
<ide> "io"
<del> "net/http"
<del> "net/url"
<ide> "os"
<ide> "path/filepath"
<ide> "strings"
<ide>
<add> "github.com/docker/docker/api/client/lib"
<ide> "github.com/docker/docker/api/types"
<ide> Cli "github.com/docker/docker/cli"
<ide> "github.com/docker/docker/pkg/archive"
<ide> func splitCpArg(arg string) (container, path string) {
<ide> }
<ide>
<ide> func (cli *DockerCli) statContainerPath(containerName, path string) (types.ContainerPathStat, error) {
<del> var stat types.ContainerPathStat
<del>
<del> query := make(url.Values, 1)
<del> query.Set("path", filepath.ToSlash(path)) // Normalize the paths used in the API.
<del>
<del> urlStr := fmt.Sprintf("/containers/%s/archive?%s", containerName, query.Encode())
<del>
<del> response, err := cli.call("HEAD", urlStr, nil, nil)
<del> if err != nil {
<del> return stat, err
<del> }
<del> defer response.body.Close()
<del>
<del> if response.statusCode != http.StatusOK {
<del> return stat, fmt.Errorf("unexpected status code from daemon: %d", response.statusCode)
<del> }
<del>
<del> return getContainerPathStatFromHeader(response.header)
<del>}
<del>
<del>func getContainerPathStatFromHeader(header http.Header) (types.ContainerPathStat, error) {
<del> var stat types.ContainerPathStat
<del>
<del> encodedStat := header.Get("X-Docker-Container-Path-Stat")
<del> statDecoder := base64.NewDecoder(base64.StdEncoding, strings.NewReader(encodedStat))
<del>
<del> err := json.NewDecoder(statDecoder).Decode(&stat)
<del> if err != nil {
<del> err = fmt.Errorf("unable to decode container path stat header: %s", err)
<del> }
<del>
<del> return stat, err
<add> return cli.client.StatContainerPath(containerName, path)
<ide> }
<ide>
<ide> func resolveLocalPath(localPath string) (absPath string, err error) {
<ide> func (cli *DockerCli) copyFromContainer(srcContainer, srcPath, dstPath string, c
<ide>
<ide> }
<ide>
<del> query := make(url.Values, 1)
<del> query.Set("path", filepath.ToSlash(srcPath)) // Normalize the paths used in the API.
<del>
<del> urlStr := fmt.Sprintf("/containers/%s/archive?%s", srcContainer, query.Encode())
<del>
<del> response, err := cli.call("GET", urlStr, nil, nil)
<add> content, stat, err := cli.client.CopyFromContainer(srcContainer, srcPath)
<ide> if err != nil {
<ide> return err
<ide> }
<del> defer response.body.Close()
<del>
<del> if response.statusCode != http.StatusOK {
<del> return fmt.Errorf("unexpected status code from daemon: %d", response.statusCode)
<del> }
<add> defer content.Close()
<ide>
<ide> if dstPath == "-" {
<ide> // Send the response to STDOUT.
<del> _, err = io.Copy(os.Stdout, response.body)
<add> _, err = io.Copy(os.Stdout, content)
<ide>
<ide> return err
<ide> }
<ide>
<del> // In order to get the copy behavior right, we need to know information
<del> // about both the source and the destination. The response headers include
<del> // stat info about the source that we can use in deciding exactly how to
<del> // copy it locally. Along with the stat info about the local destination,
<del> // we have everything we need to handle the multiple possibilities there
<del> // can be when copying a file/dir from one location to another file/dir.
<del> stat, err := getContainerPathStatFromHeader(response.header)
<del> if err != nil {
<del> return fmt.Errorf("unable to get resource stat from response: %s", err)
<del> }
<del>
<ide> // Prepare source copy info.
<ide> srcInfo := archive.CopyInfo{
<ide> Path: srcPath,
<ide> func (cli *DockerCli) copyFromContainer(srcContainer, srcPath, dstPath string, c
<ide> RebaseName: rebaseName,
<ide> }
<ide>
<del> preArchive := response.body
<add> preArchive := content
<ide> if len(srcInfo.RebaseName) != 0 {
<ide> _, srcBase := archive.SplitPathDirEntry(srcInfo.Path)
<del> preArchive = archive.RebaseArchiveEntries(response.body, srcBase, srcInfo.RebaseName)
<add> preArchive = archive.RebaseArchiveEntries(content, srcBase, srcInfo.RebaseName)
<ide> }
<ide> // See comments in the implementation of `archive.CopyTo` for exactly what
<ide> // goes into deciding how and whether the source archive needs to be
<ide> func (cli *DockerCli) copyToContainer(srcPath, dstContainer, dstPath string, cpP
<ide> content = preparedArchive
<ide> }
<ide>
<del> query := make(url.Values, 2)
<del> query.Set("path", filepath.ToSlash(resolvedDstPath)) // Normalize the paths used in the API.
<del> // Do not allow for an existing directory to be overwritten by a non-directory and vice versa.
<del> query.Set("noOverwriteDirNonDir", "true")
<del>
<del> urlStr := fmt.Sprintf("/containers/%s/archive?%s", dstContainer, query.Encode())
<del>
<del> response, err := cli.stream("PUT", urlStr, &streamOpts{in: content})
<del> if err != nil {
<del> return err
<del> }
<del> defer response.body.Close()
<del>
<del> if response.statusCode != http.StatusOK {
<del> return fmt.Errorf("unexpected status code from daemon: %d", response.statusCode)
<add> options := lib.CopyToContainerOptions{
<add> ContainerID: dstContainer,
<add> Path: resolvedDstPath,
<add> Content: content,
<add> AllowOverwriteDirWithFile: false,
<ide> }
<ide>
<del> return nil
<add> return cli.client.CopyToContainer(options)
<ide> }
<ide><path>api/client/lib/copy.go
<add>package lib
<add>
<add>import (
<add> "encoding/base64"
<add> "encoding/json"
<add> "fmt"
<add> "io"
<add> "net/http"
<add> "net/url"
<add> "path/filepath"
<add> "strings"
<add>
<add> "github.com/docker/docker/api/types"
<add>)
<add>
<add>// CopyToContainerOptions holds information
<add>// about files to copy into a container
<add>type CopyToContainerOptions struct {
<add> ContainerID string
<add> Path string
<add> Content io.Reader
<add> AllowOverwriteDirWithFile bool
<add>}
<add>
<add>// StatContainerPath returns Stat information about a path inside the container filesystem.
<add>func (cli *Client) StatContainerPath(containerID, path string) (types.ContainerPathStat, error) {
<add> query := make(url.Values, 1)
<add> query.Set("path", filepath.ToSlash(path)) // Normalize the paths used in the API.
<add>
<add> urlStr := fmt.Sprintf("/containers/%s/archive", containerID)
<add> response, err := cli.HEAD(urlStr, query, nil)
<add> if err != nil {
<add> return types.ContainerPathStat{}, err
<add> }
<add> defer ensureReaderClosed(response)
<add> return getContainerPathStatFromHeader(response.header)
<add>}
<add>
<add>// CopyToContainer copies content into the container filesystem.
<add>func (cli *Client) CopyToContainer(options CopyToContainerOptions) error {
<add> var query url.Values
<add> query.Set("path", filepath.ToSlash(options.Path)) // Normalize the paths used in the API.
<add> // Do not allow for an existing directory to be overwritten by a non-directory and vice versa.
<add> if !options.AllowOverwriteDirWithFile {
<add> query.Set("noOverwriteDirNonDir", "true")
<add> }
<add>
<add> path := fmt.Sprintf("/containers/%s/archive", options.ContainerID)
<add>
<add> response, err := cli.PUT(path, query, options.Content, nil)
<add> if err != nil {
<add> return err
<add> }
<add>
<add> if response.statusCode != http.StatusOK {
<add> return fmt.Errorf("unexpected status code from daemon: %d", response.statusCode)
<add> }
<add>
<add> return nil
<add>}
<add>
<add>// CopyFromContainer get the content from the container and return it as a Reader
<add>// to manipulate it in the host. It's up to the caller to close the reader.
<add>func (cli *Client) CopyFromContainer(containerID, srcPath string) (io.ReadCloser, types.ContainerPathStat, error) {
<add> query := make(url.Values, 1)
<add> query.Set("path", filepath.ToSlash(srcPath)) // Normalize the paths used in the API.
<add>
<add> apiPath := fmt.Sprintf("/containers/%s/archive", containerID)
<add> response, err := cli.GET(apiPath, query, nil)
<add> if err != nil {
<add> return nil, types.ContainerPathStat{}, err
<add> }
<add>
<add> if response.statusCode != http.StatusOK {
<add> return nil, types.ContainerPathStat{}, fmt.Errorf("unexpected status code from daemon: %d", response.statusCode)
<add> }
<add>
<add> // In order to get the copy behavior right, we need to know information
<add> // about both the source and the destination. The response headers include
<add> // stat info about the source that we can use in deciding exactly how to
<add> // copy it locally. Along with the stat info about the local destination,
<add> // we have everything we need to handle the multiple possibilities there
<add> // can be when copying a file/dir from one location to another file/dir.
<add> stat, err := getContainerPathStatFromHeader(response.header)
<add> if err != nil {
<add> return nil, stat, fmt.Errorf("unable to get resource stat from response: %s", err)
<add> }
<add> return response.body, stat, err
<add>}
<add>
<add>func getContainerPathStatFromHeader(header http.Header) (types.ContainerPathStat, error) {
<add> var stat types.ContainerPathStat
<add>
<add> encodedStat := header.Get("X-Docker-Container-Path-Stat")
<add> statDecoder := base64.NewDecoder(base64.StdEncoding, strings.NewReader(encodedStat))
<add>
<add> err := json.NewDecoder(statDecoder).Decode(&stat)
<add> if err != nil {
<add> err = fmt.Errorf("unable to decode container path stat header: %s", err)
<add> }
<add>
<add> return stat, err
<add>} | 2 |
Ruby | Ruby | remove warnings from rake test | a2338c583349ebd48f3c9ec18f1df5c7cf21dfdb | <ide><path>railties/test/application/rake_test.rb
<ide> def test_the_test_rake_task_is_protected_when_previous_migration_was_production
<ide> env RAILS_ENV=production bin/rake db:create db:migrate;
<ide> env RAILS_ENV=production bin/rake db:test:prepare test 2>&1`
<ide>
<del> assert_match /ActiveRecord::ProtectedEnvironmentError/, output
<add> assert_match(/ActiveRecord::ProtectedEnvironmentError/, output)
<ide> end
<ide> end
<ide>
<ide> def test_not_protected_when_previous_migration_was_not_production
<ide> env RAILS_ENV=test bin/rake db:create db:migrate;
<ide> env RAILS_ENV=test bin/rake db:test:prepare test 2>&1`
<ide>
<del> refute_match /ActiveRecord::ProtectedEnvironmentError/, output
<add> refute_match(/ActiveRecord::ProtectedEnvironmentError/, output)
<ide> end
<ide> end
<ide> | 1 |
Text | Text | fix "hashownproperty" typo in querystring | 24e4488891b6189c52ea803efed5087d31651a5f | <ide><path>doc/api/querystring.md
<ide> For example, the query string `'foo=bar&abc=xyz&abc=123'` is parsed into:
<ide>
<ide> *Note*: The object returned by the `querystring.parse()` method _does not_
<ide> prototypically extend from the JavaScript `Object`. This means that the
<del>typical `Object` methods such as `obj.toString()`, `obj.hashOwnProperty()`,
<add>typical `Object` methods such as `obj.toString()`, `obj.hasOwnProperty()`,
<ide> and others are not defined and *will not work*.
<ide>
<ide> By default, percent-encoded characters within the query string will be assumed | 1 |
Javascript | Javascript | remove underline colour in android text inputs | 6ed49341f315434ee0c2016c356aa1c3f29209c1 | <ide><path>Libraries/Image/ImageSource.js
<ide>
<ide> export type ImageSource = {
<ide> uri: string,
<del>};
<add>} | number; | 1 |
PHP | PHP | move view/widget/idgeneratortrait to view/helper | 17bcaf393d486eb1a53dfed76d279da3aa7d2581 | <ide><path>src/View/Helper/FormHelper.php
<ide> use Cake\View\Form\EntityContext;
<ide> use Cake\View\Form\NullContext;
<ide> use Cake\View\Helper;
<add>use Cake\View\Helper\IdGeneratorTrait;
<ide> use Cake\View\Helper\StringTemplateTrait;
<ide> use Cake\View\StringTemplate;
<ide> use Cake\View\View;
<del>use Cake\View\Widget\IdGeneratorTrait;
<ide> use Cake\View\Widget\WidgetRegistry;
<ide> use DateTime;
<ide> use Traversable;
<add><path>src/View/Helper/IdGeneratorTrait.php
<del><path>src/View/Widget/IdGeneratorTrait.php
<ide> * @since CakePHP(tm) v3.0
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<del>namespace Cake\View\Widget;
<add>namespace Cake\View\Helper;
<ide>
<ide> use Cake\Utility\Inflector;
<ide>
<ide><path>src/View/Widget/MultiCheckbox.php
<ide> */
<ide> namespace Cake\View\Widget;
<ide>
<del>use Cake\View\Widget\IdGeneratorTrait;
<add>use Cake\View\Helper\IdGeneratorTrait;
<ide> use Cake\View\Widget\WidgetInterface;
<ide>
<ide> /**
<ide><path>src/View/Widget/Radio.php
<ide> */
<ide> namespace Cake\View\Widget;
<ide>
<del>use Cake\View\Widget\IdGeneratorTrait;
<add>use Cake\View\Helper\IdGeneratorTrait;
<ide> use Cake\View\Widget\WidgetInterface;
<ide> use Traversable;
<ide> | 4 |
Go | Go | fix minor spelling error in service inspect | 920e65ccbca0423c43579c9ce3b9331efe14c97b | <ide><path>api/client/service/inspect.go
<ide> func printService(out io.Writer, service swarm.Service) {
<ide> }
<ide> fmt.Fprintln(out, "Placement:")
<ide> fmt.Fprintln(out, " Strategy:\tSPREAD")
<del> fmt.Fprintf(out, "UpateConfig:\n")
<add> fmt.Fprintf(out, "UpdateConfig:\n")
<ide> fmt.Fprintf(out, " Parallelism:\t%d\n", service.Spec.UpdateConfig.Parallelism)
<ide> if service.Spec.UpdateConfig.Delay.Nanoseconds() > 0 {
<ide> fmt.Fprintf(out, " Delay:\t\t%s\n", service.Spec.UpdateConfig.Delay) | 1 |
Java | Java | restore stringutils.haslength check | b3d56ebf3b2dae906d13ae5cdd7f23b8945f3d85 | <ide><path>spring-core/src/main/java/org/springframework/util/MimeTypeUtils.java
<ide> public abstract class MimeTypeUtils {
<ide> * @throws InvalidMimeTypeException if the string cannot be parsed
<ide> */
<ide> public static MimeType parseMimeType(String mimeType) {
<del> return cachedMimeTypes.get(mimeType);
<del> }
<del>
<del> private static MimeType parseMimeTypeInternal(String mimeType) {
<ide> if (!StringUtils.hasLength(mimeType)) {
<ide> throw new InvalidMimeTypeException(mimeType, "'mimeType' must not be empty");
<ide> }
<add> return cachedMimeTypes.get(mimeType);
<add> }
<ide>
<add> private static MimeType parseMimeTypeInternal(String mimeType) {
<ide> int index = mimeType.indexOf(';');
<ide> String fullType = (index >= 0 ? mimeType.substring(0, index) : mimeType).trim();
<ide> if (fullType.isEmpty()) {
<ide><path>spring-core/src/test/java/org/springframework/util/MimeTypeTests.java
<ide> public void parseMimeTypeIllegalQuotedParameterValue() {
<ide> MimeTypeUtils.parseMimeType("audio/*;attr=\""));
<ide> }
<ide>
<add> @Test
<add> public void parseMimeTypeNull() {
<add> assertThatExceptionOfType(InvalidMimeTypeException.class).isThrownBy(() ->
<add> MimeTypeUtils.parseMimeType(null));
<add> }
<add>
<ide> @Test
<ide> public void parseMimeTypes() {
<ide> String s = "text/plain, text/html, text/x-dvi, text/x-c"; | 2 |
Javascript | Javascript | fix regression in string argument handling | 41ec6d0580d91c4f2e5f30f279225eb4ec07886d | <ide><path>lib/dgram.js
<ide> Socket.prototype.send = function(buffer,
<ide> if (!util.isBuffer(buffer))
<ide> throw new TypeError('First argument must be a buffer object.');
<ide>
<add> offset = offset | 0;
<add> if (offset < 0)
<add> throw new RangeError('Offset should be >= 0');
<add>
<ide> if (offset >= buffer.length)
<del> throw new Error('Offset into buffer too large');
<add> throw new RangeError('Offset into buffer too large');
<add>
<add> // Sending a zero-length datagram is kind of pointless but it _is_
<add> // allowed, hence check that length >= 0 rather than > 0.
<add> length = length | 0;
<add> if (length < 0)
<add> throw new RangeError('Length should be >= 0');
<ide>
<ide> if (offset + length > buffer.length)
<del> throw new Error('Offset + length beyond buffer length');
<add> throw new RangeError('Offset + length beyond buffer length');
<add>
<add> port = port | 0;
<add> if (port <= 0 || port > 65535)
<add> throw new RangeError('Port should be > 0 and < 65536');
<ide>
<ide> callback = callback || noop;
<ide>
<ide><path>test/simple/test-dgram-close.js
<ide> var buf = new Buffer(1024);
<ide> buf.fill(42);
<ide>
<ide> var socket = dgram.createSocket('udp4');
<del>
<del>socket.send(buf, 0, buf.length, common.port, 'localhost');
<add>socket.send(buf, 0, buf.length, common.PORT, 'localhost');
<ide> socket.close();
<ide><path>test/simple/test-dgram-send-bad-arguments.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>var common = require('../common');
<add>var assert = require('assert');
<add>var dgram = require('dgram');
<add>
<add>var buf = Buffer('test');
<add>var host = '127.0.0.1';
<add>var sock = dgram.createSocket('udp4');
<add>
<add>assert.throws(function() {
<add> sock.send();
<add>}, TypeError); // First argument should be a buffer.
<add>
<add>assert.throws(function() { sock.send(buf, -1, 1, 1, host); }, RangeError);
<add>assert.throws(function() { sock.send(buf, 1, -1, 1, host); }, RangeError);
<add>assert.throws(function() { sock.send(buf, 1, 1, -1, host); }, RangeError);
<add>assert.throws(function() { sock.send(buf, 5, 1, 1, host); }, RangeError);
<add>assert.throws(function() { sock.send(buf, 1, 5, 1, host); }, RangeError);
<add>assert.throws(function() { sock.send(buf, 1, 1, 0, host); }, RangeError);
<add>assert.throws(function() { sock.send(buf, 1, 1, 65536, host); }, RangeError); | 3 |
Text | Text | use arrow function for anonymous callbacks | e958ee7a70d0af136fae8a708882cccdd4601658 | <ide><path>doc/api/async_hooks.md
<ide> The ID returned from `executionAsyncId()` is related to execution timing, not
<ide> causality (which is covered by `triggerAsyncId()`):
<ide>
<ide> ```js
<del>const server = net.createServer(function onConnection(conn) {
<add>const server = net.createServer((conn) => {
<ide> // Returns the ID of the server, not of the new connection, because the
<del> // onConnection callback runs in the execution scope of the server's
<del> // MakeCallback().
<add> // callback runs in the execution scope of the server's MakeCallback().
<ide> async_hooks.executionAsyncId();
<ide>
<del>}).listen(port, function onListening() {
<add>}).listen(port, () => {
<ide> // Returns the ID of a TickObject (i.e. process.nextTick()) because all
<ide> // callbacks passed to .listen() are wrapped in a nextTick().
<ide> async_hooks.executionAsyncId(); | 1 |
PHP | PHP | add missing interface check | e6ab885ba675a858a4b18e0c1acf215bf2824670 | <ide><path>src/ORM/Marshaller.php
<ide> public function merge(EntityInterface $entity, array $data, array $options = [])
<ide> $properties = $marshalledAssocs = [];
<ide> foreach ($data as $key => $value) {
<ide> if (!empty($errors[$key])) {
<del> if (method_exists($entity, 'invalid')) {
<add> if ($entity instanceof InvalidPropertyInterface) {
<ide> $entity->invalid($key, $value);
<ide> }
<ide> continue; | 1 |
Python | Python | add ascii encoding on network interface name | a17f68c1b4b073432ddef67c7c3307bce0a044ef | <ide><path>glances/glances.py
<ide> def displayNetwork(self, network):
<ide> # network interface name
<ide> self.term_window.addnstr(
<ide> self.network_y + 1 + i, self.network_x,
<del> unicode(network[i]['interface_name'], 'ascii', 'ignore') + ':', 8)
<add> network[i]['interface_name'].encode('ascii', 'ignore') + ':', 8)
<ide>
<ide> # Byte/s or bit/s
<ide> if self.net_byteps_tag: | 1 |
Java | Java | harmonize default converters | 0612bc7bc5a82ff7414d8c8bcf665599d23a5225 | <ide><path>spring-core/src/main/java/org/springframework/core/convert/support/DefaultConversionService.java
<ide>
<ide> package org.springframework.core.convert.support;
<ide>
<add>import java.nio.charset.Charset;
<add>import java.util.Currency;
<ide> import java.util.Locale;
<ide> import java.util.UUID;
<ide>
<ide> public static void addDefaultConverters(ConverterRegistry converterRegistry) {
<ide>
<ide> converterRegistry.addConverter(new ByteBufferConverter((ConversionService) converterRegistry));
<ide> if (jsr310Available) {
<del> Jsr310ConverterRegistrar.registerZoneIdConverters(converterRegistry);
<add> Jsr310ConverterRegistrar.registerJsr310Converters(converterRegistry);
<ide> }
<ide>
<ide> converterRegistry.addConverter(new ObjectToObjectConverter());
<ide> private static void addScalarConverters(ConverterRegistry converterRegistry) {
<ide> converterRegistry.addConverter(new StringToLocaleConverter());
<ide> converterRegistry.addConverter(Locale.class, String.class, new ObjectToStringConverter());
<ide>
<add> converterRegistry.addConverter(new StringToCharsetConverter());
<add> converterRegistry.addConverter(Charset.class, String.class, new ObjectToStringConverter());
<add>
<add> converterRegistry.addConverter(new StringToCurrencyConverter());
<add> converterRegistry.addConverter(Currency.class, String.class, new ObjectToStringConverter());
<add>
<ide> converterRegistry.addConverter(new StringToPropertiesConverter());
<ide> converterRegistry.addConverter(new PropertiesToStringConverter());
<ide>
<ide> private static void addCollectionConverters(ConverterRegistry converterRegistry)
<ide> */
<ide> private static final class Jsr310ConverterRegistrar {
<ide>
<del> public static void registerZoneIdConverters(ConverterRegistry converterRegistry) {
<add> public static void registerJsr310Converters(ConverterRegistry converterRegistry) {
<add> converterRegistry.addConverter(new StringToTimeZoneConverter());
<ide> converterRegistry.addConverter(new ZoneIdToTimeZoneConverter());
<ide> converterRegistry.addConverter(new ZonedDateTimeToCalendarConverter());
<ide> }
<ide><path>spring-core/src/main/java/org/springframework/core/convert/support/StringToCharsetConverter.java
<add>/*
<add> * Copyright 2002-2015 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.core.convert.support;
<add>
<add>import java.nio.charset.Charset;
<add>
<add>import org.springframework.core.convert.converter.Converter;
<add>
<add>/**
<add> * Convert a String to a {@link Charset}.
<add> *
<add> * @author Stephane Nicoll
<add> * @since 4.2
<add> */
<add>public class StringToCharsetConverter implements Converter<String, Charset> {
<add>
<add> @Override
<add> public Charset convert(String source) {
<add> return Charset.forName(source);
<add> }
<add>
<add>}
<ide><path>spring-core/src/main/java/org/springframework/core/convert/support/StringToCurrencyConverter.java
<add>/*
<add> * Copyright 2002-2015 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.core.convert.support;
<add>
<add>import java.util.Currency;
<add>
<add>import org.springframework.core.convert.converter.Converter;
<add>
<add>/**
<add> * Convert a String to a {@link Currency}.
<add> *
<add> * @author Stephane Nicoll
<add> * @since 4.2
<add> */
<add>class StringToCurrencyConverter implements Converter<String, Currency> {
<add>
<add> @Override
<add> public Currency convert(String source) {
<add> return Currency.getInstance(source);
<add> }
<add>
<add>}
<ide><path>spring-core/src/main/java/org/springframework/core/convert/support/StringToTimeZoneConverter.java
<add>/*
<add> * Copyright 2002-2015 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.core.convert.support;
<add>
<add>import java.util.TimeZone;
<add>
<add>import org.springframework.core.convert.converter.Converter;
<add>import org.springframework.lang.UsesJava8;
<add>import org.springframework.util.StringUtils;
<add>
<add>/**
<add> * Convert a String to a {@link TimeZone}.
<add> *
<add> * @author Stephane Nicoll
<add> * @since 4.2
<add> */
<add>@UsesJava8
<add>class StringToTimeZoneConverter implements Converter<String, TimeZone> {
<add>
<add> @Override
<add> public TimeZone convert(String source) {
<add> return StringUtils.parseTimeZoneString(source);
<add> }
<add>
<add>}
<ide><path>spring-core/src/test/java/org/springframework/core/convert/support/DefaultConversionServiceTests.java
<ide> import java.lang.reflect.Method;
<ide> import java.math.BigDecimal;
<ide> import java.math.BigInteger;
<add>import java.nio.charset.Charset;
<ide> import java.time.ZoneId;
<ide> import java.util.AbstractList;
<ide> import java.util.ArrayList;
<ide> import java.util.Arrays;
<ide> import java.util.Collection;
<ide> import java.util.Collections;
<add>import java.util.Currency;
<ide> import java.util.EnumSet;
<ide> import java.util.HashMap;
<ide> import java.util.LinkedHashMap;
<ide> import java.util.Optional;
<ide> import java.util.Properties;
<ide> import java.util.Set;
<add>import java.util.TimeZone;
<ide> import java.util.UUID;
<ide> import java.util.stream.Stream;
<ide>
<ide> public void testStringToLocale() {
<ide> assertEquals(Locale.ENGLISH, conversionService.convert("en", Locale.class));
<ide> }
<ide>
<add> @Test
<add> public void testStringToCharset() {
<add> assertEquals(Charset.forName("UTF-8"), conversionService.convert("UTF-8", Charset.class));
<add> }
<add>
<add> @Test
<add> public void testCharsetToString() {
<add> assertEquals("UTF-8", conversionService.convert(Charset.forName("UTF-8"), String.class));
<add> }
<add>
<add> @Test
<add> public void testStringToCurrency() {
<add> assertEquals(Currency.getInstance("EUR"), conversionService.convert("EUR", Currency.class));
<add> }
<add>
<add> @Test
<add> public void testCurrencyToString() {
<add> assertEquals("USD", conversionService.convert(Currency.getInstance("USD"), String.class));
<add> }
<add>
<ide> @Test
<ide> public void testStringToString() {
<ide> String str = "test";
<ide> public void convertObjectToObjectUsingObjectConstructor() {
<ide> assertEquals("toString() invocations", 0, SSN.toStringCount);
<ide> }
<ide>
<add> @Test
<add> public void convertStringToTimezone() {
<add> assertEquals("GMT+02:00", conversionService.convert("GMT+2", TimeZone.class).getID());
<add> }
<add>
<ide> @Test
<ide> public void convertObjectToStringWithJavaTimeOfMethodPresent() {
<ide> assertTrue(conversionService.convert(ZoneId.of("GMT+1"), String.class).startsWith("GMT+")); | 5 |
Text | Text | add link to djangorestframework-digestauth | 7ffb2435ca87676173e8c634401a9c871b1e2087 | <ide><path>docs/api-guide/authentication.md
<ide> Unauthenticated responses that are denied permission will result in an `HTTP 401
<ide>
<ide> **Note:** If you use `TokenAuthentication` in production you must ensure that your API is only available over `https` only.
<ide>
<del>=======
<add>---
<add>
<ide> If you want every user to have an automatically generated Token, you can simply catch the User's `post_save` signal.
<ide>
<ide> @receiver(post_save, sender=User)
<ide> The following example will authenticate any incoming request as the user given b
<ide> raise authenticate.AuthenticationFailed('No such user')
<ide>
<ide> return (user, None)
<del>
<add>
<add>---
<add>
<add># Third party packages
<add>
<add>The following third party packages are also available.
<add>
<add>## Digest Authentication
<add>
<add>HTTP digest authentication is a widely implemented scheme that was intended to replace HTTP basic authentication, and which provides a simple encrypted authentication mechanism. [Juan Riaza][juanriaza] maintains the [djangorestframework-digestauth][djangorestframework-digestauth] package which provides HTTP digest authentication support for REST framework.
<ide>
<ide> [cite]: http://jacobian.org/writing/rest-worst-practices/
<ide> [http401]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2
<ide> The following example will authenticate any incoming request as the user given b
<ide> [throttling]: throttling.md
<ide> [csrf-ajax]: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
<ide> [mod_wsgi_official]: http://code.google.com/p/modwsgi/wiki/ConfigurationDirectives#WSGIPassAuthorization
<add>[juanriaza]: https://github.com/juanriaza
<add>[djangorestframework-digestauth]: https://github.com/juanriaza/django-rest-framework-digestauth | 1 |
Mixed | Javascript | fix umd bundles by removing usage of global | eeb1325b03388184f61796ccf57835d33739249a | <ide><path>packages/react-art/src/ReactARTHostConfig.js
<ide> export function getChildHostContext() {
<ide> export const scheduleTimeout = setTimeout;
<ide> export const cancelTimeout = clearTimeout;
<ide> export const noTimeout = -1;
<del>export function queueMicrotask(callback: Function) {
<add>export function scheduleMicrotask(callback: Function) {
<ide> invariant(false, 'Not implemented.');
<ide> }
<ide>
<ide><path>packages/react-dom/src/client/ReactDOMHostConfig.js
<ide> export const scheduleTimeout: any =
<ide> export const cancelTimeout: any =
<ide> typeof clearTimeout === 'function' ? clearTimeout : (undefined: any);
<ide> export const noTimeout = -1;
<del>export const queueMicrotask: any =
<del> typeof global.queueMicrotask === 'function'
<del> ? global.queueMicrotask
<add>export const scheduleMicrotask: any =
<add> typeof queueMicrotask === 'function'
<add> ? queueMicrotask
<ide> : typeof Promise !== 'undefined'
<ide> ? callback =>
<ide> Promise.resolve(null)
<ide><path>packages/react-native-renderer/src/ReactFabricHostConfig.js
<ide> export const warnsIfNotActing = false;
<ide> export const scheduleTimeout = setTimeout;
<ide> export const cancelTimeout = clearTimeout;
<ide> export const noTimeout = -1;
<del>export function queueMicrotask(callback: Function) {
<add>export function scheduleMicrotask(callback: Function) {
<ide> invariant(false, 'Not implemented.');
<ide> }
<ide>
<ide><path>packages/react-native-renderer/src/ReactNativeHostConfig.js
<ide> export const warnsIfNotActing = true;
<ide> export const scheduleTimeout = setTimeout;
<ide> export const cancelTimeout = clearTimeout;
<ide> export const noTimeout = -1;
<del>export function queueMicrotask(callback: Function) {
<add>export function scheduleMicrotask(callback: Function) {
<ide> invariant(false, 'Not implemented.');
<ide> }
<ide>
<ide><path>packages/react-noop-renderer/src/createReactNoop.js
<ide> function createReactNoop(reconciler: Function, useMutation: boolean) {
<ide> scheduleTimeout: setTimeout,
<ide> cancelTimeout: clearTimeout,
<ide> noTimeout: -1,
<del> queueMicrotask:
<add> scheduleMicrotask:
<ide> typeof queueMicrotask === 'function'
<ide> ? queueMicrotask
<ide> : typeof Promise !== 'undefined'
<ide><path>packages/react-reconciler/README.md
<ide> You can proxy this to `clearTimeout` or its equivalent in your environment.
<ide>
<ide> This is a property (not a function) that should be set to something that can never be a valid timeout ID. For example, you can set it to `-1`.
<ide>
<del>#### `queueMicrotask(fn)`
<add>#### `scheduleMicrotask(fn)`
<ide>
<ide> You can proxy this to `queueMicrotask` or its equivalent in your environment.
<ide>
<ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.new.js
<ide> import {
<ide> warnsIfNotActing,
<ide> afterActiveInstanceBlur,
<ide> clearContainer,
<del> queueMicrotask,
<add> scheduleMicrotask,
<ide> } from './ReactFiberHostConfig';
<ide>
<ide> import {
<ide> function ensureRootIsScheduled(root: FiberRoot, currentTime: number) {
<ide> enableDiscreteEventMicroTasks &&
<ide> newCallbackPriority === InputDiscreteLanePriority
<ide> ) {
<del> queueMicrotask(performSyncWorkOnRoot.bind(null, root));
<add> scheduleMicrotask(performSyncWorkOnRoot.bind(null, root));
<ide> newCallbackNode = null;
<ide> } else {
<ide> const schedulerPriorityLevel = lanePriorityToSchedulerPriority(
<ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.old.js
<ide> import {
<ide> warnsIfNotActing,
<ide> afterActiveInstanceBlur,
<ide> clearContainer,
<del> queueMicrotask,
<add> scheduleMicrotask,
<ide> } from './ReactFiberHostConfig';
<ide>
<ide> import {
<ide> function ensureRootIsScheduled(root: FiberRoot, currentTime: number) {
<ide> enableDiscreteEventMicroTasks &&
<ide> newCallbackPriority === InputDiscreteLanePriority
<ide> ) {
<del> queueMicrotask(performSyncWorkOnRoot.bind(null, root));
<add> scheduleMicrotask(performSyncWorkOnRoot.bind(null, root));
<ide> newCallbackNode = null;
<ide> } else {
<ide> const schedulerPriorityLevel = lanePriorityToSchedulerPriority(
<ide><path>packages/react-reconciler/src/forks/ReactFiberHostConfig.custom.js
<ide> export const shouldSetTextContent = $$$hostConfig.shouldSetTextContent;
<ide> export const createTextInstance = $$$hostConfig.createTextInstance;
<ide> export const scheduleTimeout = $$$hostConfig.scheduleTimeout;
<ide> export const cancelTimeout = $$$hostConfig.cancelTimeout;
<del>export const queueMicrotask = $$$hostConfig.queueMicrotask;
<add>export const scheduleMicrotask = $$$hostConfig.scheduleMicrotask;
<ide> export const noTimeout = $$$hostConfig.noTimeout;
<ide> export const now = $$$hostConfig.now;
<ide> export const isPrimaryRenderer = $$$hostConfig.isPrimaryRenderer;
<ide><path>packages/react-test-renderer/src/ReactTestHostConfig.js
<ide> export const warnsIfNotActing = true;
<ide>
<ide> export const scheduleTimeout = setTimeout;
<ide> export const cancelTimeout = clearTimeout;
<del>export const queueMicrotask =
<del> typeof global.queueMicrotask === 'function'
<del> ? global.queueMicrotask
<add>export const scheduleMicrotask =
<add> typeof queueMicrotask === 'function'
<add> ? queueMicrotask
<ide> : typeof Promise !== 'undefined'
<ide> ? (callback: Function) =>
<ide> Promise.resolve(null)
<ide><path>scripts/flow/environment.js
<ide> declare var __REACT_DEVTOOLS_GLOBAL_HOOK__: any; /*?{
<ide> inject: ?((stuff: Object) => void)
<ide> };*/
<ide>
<add>declare var queueMicrotask: (fn: Function) => void;
<add>
<ide> declare module 'create-react-class' {
<ide> declare var exports: React$CreateClass;
<ide> } | 11 |
PHP | PHP | remove unused "use" statements | a70cc4975e2a8254a91d74e0f15ce3b8400869c8 | <ide><path>src/Auth/DigestAuthenticate.php
<ide> namespace Cake\Auth;
<ide>
<ide> use Cake\Controller\ComponentRegistry;
<del>use Cake\Core\Configure;
<ide> use Cake\Http\ServerRequest;
<ide> use Cake\Utility\Security;
<ide>
<ide><path>src/Collection/Collection.php
<ide> use ArrayIterator;
<ide> use InvalidArgumentException;
<ide> use IteratorIterator;
<del>use LogicException;
<ide> use Serializable;
<ide> use Traversable;
<ide>
<ide><path>src/Command/HelpCommand.php
<ide> use Cake\Console\ConsoleIo;
<ide> use Cake\Console\ConsoleOptionParser;
<ide> use Cake\Console\ConsoleOutput;
<del>use Cake\Utility\Inflector;
<ide> use SimpleXMLElement;
<ide>
<ide> /**
<ide><path>src/Console/CommandScanner.php
<ide> use Cake\Core\Plugin;
<ide> use Cake\Filesystem\Folder;
<ide> use Cake\Utility\Inflector;
<del>use InvalidArgumentException;
<ide>
<ide> /**
<ide> * Used by CommandCollection and CommandTask to scan the filesystem
<ide><path>src/Controller/Component/RequestHandlerComponent.php
<ide> use Cake\Controller\Controller;
<ide> use Cake\Core\App;
<ide> use Cake\Core\Configure;
<del>use Cake\Core\Exception\Exception;
<ide> use Cake\Event\Event;
<del>use Cake\Http\Response;
<ide> use Cake\Routing\Router;
<ide> use Cake\Utility\Exception\XmlException;
<ide> use Cake\Utility\Inflector;
<ide><path>src/Core/BasePlugin.php
<ide> */
<ide> namespace Cake\Core;
<ide>
<del>use Cake\Event\EventManagerInterface;
<ide> use InvalidArgumentException;
<ide> use ReflectionClass;
<ide>
<ide><path>src/Core/PluginApplicationInterface.php
<ide> namespace Cake\Core;
<ide>
<ide> use Cake\Event\EventDispatcherInterface;
<del>use Cake\Event\EventManagerInterface;
<ide>
<ide> /**
<ide> * Interface for Applications that leverage plugins & events.
<ide><path>src/Core/PluginCollection.php
<ide> */
<ide> namespace Cake\Core;
<ide>
<del>use ArrayIterator;
<ide> use Cake\Core\Exception\MissingPluginException;
<ide> use Countable;
<ide> use InvalidArgumentException;
<ide> use Iterator;
<del>use RuntimeException;
<ide>
<ide> /**
<ide> * Plugin Collection
<ide><path>src/Core/PluginInterface.php
<ide> */
<ide> namespace Cake\Core;
<ide>
<del>use Cake\Event\EventManagerInterface;
<ide>
<ide> /**
<ide> * Plugin Interface
<ide><path>src/Database/DriverInterface.php
<ide> namespace Cake\Database;
<ide>
<ide> use Cake\Database\Query;
<del>use Cake\Database\Statement\PDOStatement;
<del>use InvalidArgumentException;
<del>use PDO;
<del>use PDOException;
<ide>
<ide> /**
<ide> * Interface for database driver.
<ide><path>src/Database/SchemaCache.php
<ide>
<ide> use Cake\Cache\Cache;
<ide> use Cake\Database\Connection;
<del>use Cake\Datasource\ConnectionManager;
<del>use InvalidArgumentException;
<del>use RuntimeException;
<ide>
<ide> /**
<ide> * Schema Cache.
<ide><path>src/Database/Type/BinaryType.php
<ide>
<ide> use Cake\Core\Exception\Exception;
<ide> use Cake\Database\Driver;
<del>use Cake\Database\Driver\Sqlserver;
<ide> use PDO;
<ide>
<ide> /**
<ide><path>src/Database/Type/BinaryUuidType.php
<ide>
<ide> use Cake\Core\Exception\Exception;
<ide> use Cake\Database\Driver;
<del>use Cake\Database\Driver\Sqlserver;
<ide> use Cake\Utility\Text;
<ide> use PDO;
<ide>
<ide><path>src/Form/Form.php
<ide> use Cake\Form\Schema;
<ide> use Cake\Validation\ValidatorAwareInterface;
<ide> use Cake\Validation\ValidatorAwareTrait;
<del>use ReflectionMethod;
<ide>
<ide> /**
<ide> * Form abstraction used to create forms not tied to ORM backed models,
<ide><path>src/Http/ActionDispatcher.php
<ide>
<ide> use Cake\Controller\Controller;
<ide> use Cake\Event\EventDispatcherTrait;
<del>use Cake\Event\EventListenerInterface;
<ide> use Cake\Routing\Router;
<ide> use LogicException;
<ide>
<ide><path>src/ORM/ResultSet.php
<ide> use Cake\Collection\Collection;
<ide> use Cake\Collection\CollectionTrait;
<ide> use Cake\Database\Exception;
<del>use Cake\Database\TypeFactory;
<ide> use Cake\Datasource\EntityInterface;
<ide> use Cake\Datasource\ResultSetInterface;
<ide> use SplFixedArray;
<ide><path>src/Routing/Middleware/RoutingMiddleware.php
<ide> namespace Cake\Routing\Middleware;
<ide>
<ide> use Cake\Cache\Cache;
<del>use Cake\Core\Configure;
<ide> use Cake\Core\PluginApplicationInterface;
<ide> use Cake\Http\BaseApplication;
<ide> use Cake\Http\MiddlewareQueue;
<ide><path>src/Routing/Route/Route.php
<ide> */
<ide> namespace Cake\Routing\Route;
<ide>
<del>use Cake\Http\ServerRequest;
<del>use Cake\Http\ServerRequestFactory;
<del>use Cake\Routing\Router;
<ide> use InvalidArgumentException;
<ide> use Psr\Http\Message\ServerRequestInterface;
<ide>
<ide><path>src/Routing/Router.php
<ide> use Cake\Routing\Exception\MissingRouteException;
<ide> use Cake\Utility\Inflector;
<ide> use Psr\Http\Message\ServerRequestInterface;
<del>use RuntimeException;
<ide>
<ide> /**
<ide> * Parses the request URL into controller, action, and parameters. Uses the connected routes
<ide><path>src/Shell/Task/CommandTask.php
<ide> */
<ide> namespace Cake\Shell\Task;
<ide>
<del>use Cake\Console\Command;
<ide> use Cake\Console\Shell;
<ide> use Cake\Core\App;
<ide> use Cake\Core\Plugin;
<ide><path>src/TestSuite/IntegrationTestCase.php
<ide> use Cake\Core\Configure;
<ide> use Cake\Database\Exception as DatabaseException;
<ide> use Cake\Http\ServerRequest;
<del>use Cake\Http\ServerRequestFactory;
<ide> use Cake\Http\Session;
<ide> use Cake\Routing\Router;
<ide> use Cake\TestSuite\Stub\TestExceptionRenderer;
<ide><path>src/Utility/Crypto/OpenSsl.php
<ide> */
<ide> namespace Cake\Utility\Crypto;
<ide>
<del>use LogicException;
<ide>
<ide> /**
<ide> * OpenSSL implementation of crypto features for Cake\Utility\Security
<ide><path>src/Utility/Security.php
<ide> */
<ide> namespace Cake\Utility;
<ide>
<del>use Cake\Utility\Crypto\Mcrypt;
<ide> use Cake\Utility\Crypto\OpenSsl;
<ide> use InvalidArgumentException;
<ide> use RuntimeException;
<ide><path>src/View/Helper/FormHelper.php
<ide> use Cake\View\StringTemplateTrait;
<ide> use Cake\View\View;
<ide> use Cake\View\Widget\WidgetLocator;
<del>use Cake\View\Widget\WidgetRegistry;
<ide> use DateTime;
<ide> use RuntimeException;
<ide> use Traversable;
<ide><path>tests/TestCase/Console/CommandCollectionTest.php
<ide> */
<ide> namespace Cake\Test\Console;
<ide>
<del>use Cake\Console\Command;
<ide> use Cake\Console\CommandCollection;
<ide> use Cake\Core\Configure;
<ide> use Cake\Core\Plugin;
<ide> use Cake\Shell\I18nShell;
<ide> use Cake\Shell\RoutesShell;
<ide> use Cake\TestSuite\TestCase;
<del>use InvalidArgumentException;
<ide> use stdClass;
<ide> use TestApp\Command\DemoCommand;
<ide>
<ide><path>tests/TestCase/Console/CommandFactoryTest.php
<ide> namespace Cake\Test\TestCase\Console;
<ide>
<ide> use Cake\Console\CommandFactory;
<del>use Cake\Console\ConsoleIo;
<ide> use Cake\TestSuite\TestCase;
<ide> use InvalidArgumentException;
<ide> use TestApp\Command\DemoCommand;
<ide><path>tests/TestCase/Console/CommandRunnerTest.php
<ide> use Cake\Console\Shell;
<ide> use Cake\Core\Configure;
<ide> use Cake\Core\ConsoleApplicationInterface;
<del>use Cake\Event\EventList;
<ide> use Cake\Event\EventManager;
<ide> use Cake\Http\BaseApplication;
<ide> use Cake\Routing\Router;
<ide> use Cake\TestSuite\Stub\ConsoleOutput;
<ide> use Cake\TestSuite\TestCase;
<ide> use InvalidArgumentException;
<ide> use TestApp\Command\DemoCommand;
<del>use TestApp\Http\EventApplication;
<ide> use TestApp\Shell\SampleShell;
<ide>
<ide> /**
<ide><path>tests/TestCase/Controller/Component/RequestHandlerComponentTest.php
<ide> use Cake\Event\Event;
<ide> use Cake\Http\Response;
<ide> use Cake\Http\ServerRequest;
<del>use Cake\Routing\DispatcherFactory;
<ide> use Cake\Routing\Router;
<ide> use Cake\TestSuite\TestCase;
<ide> use Cake\View\AjaxView;
<ide><path>tests/TestCase/Core/BasePluginTest.php
<ide> use Cake\Core\Configure;
<ide> use Cake\Core\Plugin;
<ide> use Cake\Core\PluginApplicationInterface;
<del>use Cake\Event\EventManager;
<ide> use Cake\Http\MiddlewareQueue;
<ide> use Cake\TestSuite\TestCase;
<ide> use Company\TestPluginThree\Plugin as TestPluginThree;
<ide><path>tests/TestCase/Database/ConnectionTest.php
<ide> use Cake\Database\Exception\NestedTransactionRollbackException;
<ide> use Cake\Database\Log\LoggingStatement;
<ide> use Cake\Database\Log\QueryLogger;
<del>use Cake\Database\Retry\CommandRetry;
<del>use Cake\Database\Retry\ReconnectStrategy;
<ide> use Cake\Database\StatementInterface;
<ide> use Cake\Datasource\ConnectionManager;
<ide> use Cake\Log\Log;
<ide><path>tests/TestCase/Database/SchemaCacheTest.php
<ide> use Cake\Database\SchemaCache;
<ide> use Cake\Database\Schema\CachedCollection;
<ide> use Cake\Datasource\ConnectionManager;
<del>use Cake\ORM\Entity;
<ide> use Cake\TestSuite\TestCase;
<ide>
<ide> /**
<ide><path>tests/TestCase/Database/Type/BinaryUuidTypeTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\Database\Type;
<ide>
<del>use Cake\Database\TypeFactory;
<ide> use Cake\Database\Type\BinaryUuidType;
<ide> use Cake\TestSuite\TestCase;
<ide> use Cake\Utility\Text;
<ide><path>tests/TestCase/Error/ExceptionRendererTest.php
<ide> use Cake\Mailer\Exception\MissingActionException as MissingMailerActionException;
<ide> use Cake\Network\Exception\SocketException;
<ide> use Cake\ORM\Exception\MissingBehaviorException;
<del>use Cake\Routing\DispatcherFactory;
<ide> use Cake\Routing\Exception\MissingControllerException;
<ide> use Cake\Routing\Router;
<ide> use Cake\TestSuite\TestCase;
<ide><path>tests/TestCase/Form/FormTest.php
<ide> use Cake\Validation\Validator;
<ide> use TestApp\Form\AppForm;
<ide> use TestApp\Form\FormSchema;
<del>use TestApp\Form\ValidateForm;
<ide>
<ide> /**
<ide> * Form test case.
<ide><path>tests/TestCase/Http/ActionDispatcherTest.php
<ide> use Cake\Http\Response;
<ide> use Cake\Http\ServerRequest;
<ide> use Cake\Http\Session;
<del>use Cake\Routing\DispatcherFactory;
<del>use Cake\Routing\Filter\ControllerFactoryFilter;
<ide> use Cake\Routing\Router;
<ide> use Cake\TestSuite\TestCase;
<ide>
<ide><path>tests/TestCase/Http/ServerTest.php
<ide>
<ide> use Cake\Core\HttpApplicationInterface;
<ide> use Cake\Event\Event;
<del>use Cake\Event\EventList;
<ide> use Cake\Event\EventManager;
<ide> use Cake\Http\BaseApplication;
<ide> use Cake\Http\CallbackStream;
<ide> use Cake\Http\MiddlewareQueue;
<ide> use Cake\Http\Server;
<ide> use Cake\TestSuite\TestCase;
<ide> use InvalidArgumentException;
<del>use Psr\Http\Message\ResponseInterface;
<ide> use RuntimeException;
<ide> use TestApp\Http\BadResponseApplication;
<del>use TestApp\Http\EventApplication;
<ide> use TestApp\Http\InvalidMiddlewareApplication;
<ide> use TestApp\Http\MiddlewareApplication;
<ide> use Zend\Diactoros\Response;
<ide><path>tests/TestCase/ORM/TableRegressionTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\ORM;
<ide>
<del>use Cake\ORM\TableRegistry;
<ide> use Cake\TestSuite\TestCase;
<ide> use InvalidArgumentException;
<ide>
<ide><path>tests/TestCase/Routing/Middleware/RoutingMiddlewareTest.php
<ide> namespace Cake\Test\TestCase\Routing\Middleware;
<ide>
<ide> use Cake\Cache\Cache;
<del>use Cake\Core\Configure;
<ide> use Cake\Routing\Middleware\RoutingMiddleware;
<ide> use Cake\Routing\RouteBuilder;
<ide> use Cake\Routing\RouteCollection;
<ide><path>tests/TestCase/Shell/Task/LoadTaskTest.php
<ide> namespace Cake\Test\TestCase\Shell\Task;
<ide>
<ide> use Cake\Console\Shell;
<del>use Cake\Core\Plugin;
<ide> use Cake\Filesystem\File;
<ide> use Cake\TestSuite\ConsoleIntegrationTestCase;
<ide>
<ide><path>tests/TestCase/TestSuite/IntegrationTestCaseTest.php
<ide> use Cake\Core\Configure;
<ide> use Cake\Event\EventManager;
<ide> use Cake\Http\Response;
<del>use Cake\Routing\RouteBuilder;
<ide> use Cake\Routing\Router;
<ide> use Cake\Routing\Route\InflectedRoute;
<ide> use Cake\TestSuite\IntegrationTestCase;
<ide><path>tests/TestCase/Utility/SecurityTest.php
<ide> use Cake\TestSuite\TestCase;
<ide> use Cake\Utility\Crypto\OpenSsl;
<ide> use Cake\Utility\Security;
<del>use RuntimeException;
<ide>
<ide> /**
<ide> * SecurityTest class
<ide><path>tests/TestCase/Validation/ValidationSetTest.php
<ide> use Cake\TestSuite\TestCase;
<ide> use Cake\Validation\ValidationRule;
<ide> use Cake\Validation\ValidationSet;
<del>use PHPUnit\Framework\Error\Deprecated;
<ide>
<ide> /**
<ide> * ValidationSetTest | 42 |
Python | Python | remove hyphen in tap result | de051757e28e2fd256eb9a64d44bf22a0e0bbf00 | <ide><path>tools/test.py
<ide> def HasRun(self, output):
<ide> self._done += 1
<ide> command = basename(output.command[-1])
<ide> if output.UnexpectedOutput():
<del> status_line = 'not ok %i - %s' % (self._done, command)
<add> status_line = 'not ok %i %s' % (self._done, command)
<ide> if FLAKY in output.test.outcomes and self.flaky_tests_mode == DONTCARE:
<ide> status_line = status_line + ' # TODO : Fix flaky test'
<ide> logger.info(status_line)
<ide> def HasRun(self, output):
<ide> skip = skip_regex.search(output.output.stdout)
<ide> if skip:
<ide> logger.info(
<del> 'ok %i - %s # skip %s' % (self._done, command, skip.group(1)))
<add> 'ok %i %s # skip %s' % (self._done, command, skip.group(1)))
<ide> else:
<del> status_line = 'ok %i - %s' % (self._done, command)
<add> status_line = 'ok %i %s' % (self._done, command)
<ide> if FLAKY in output.test.outcomes:
<ide> status_line = status_line + ' # TODO : Fix flaky test'
<ide> logger.info(status_line) | 1 |
Javascript | Javascript | fix typo in `pre_execution.js` | 3c423a2030d35faace4aa85a7a05ed816a32f8d1 | <ide><path>lib/internal/process/pre_execution.js
<ide> const {
<ide> isBuildingSnapshot,
<ide> } = require('v8').startupSnapshot;
<ide>
<del>function prepareMainThreadExecution(expandArgv1 = false, initialzeModules = true) {
<add>function prepareMainThreadExecution(expandArgv1 = false, initializeModules = true) {
<ide> prepareExecution({
<ide> expandArgv1,
<del> initialzeModules,
<add> initializeModules,
<ide> isMainThread: true
<ide> });
<ide> }
<ide>
<ide> function prepareWorkerThreadExecution() {
<ide> prepareExecution({
<ide> expandArgv1: false,
<del> initialzeModules: false, // Will need to initialize it after policy setup
<add> initializeModules: false, // Will need to initialize it after policy setup
<ide> isMainThread: false
<ide> });
<ide> }
<ide>
<ide> function prepareExecution(options) {
<del> const { expandArgv1, initialzeModules, isMainThread } = options;
<add> const { expandArgv1, initializeModules, isMainThread } = options;
<ide>
<ide> refreshRuntimeOptions();
<ide> reconnectZeroFillToggle();
<ide> function prepareExecution(options) {
<ide> } else {
<ide> assert(!internalBinding('worker').isMainThread);
<ide> // The setup should be called in LOAD_SCRIPT message handler.
<del> assert(!initialzeModules);
<add> assert(!initializeModules);
<ide> }
<ide>
<del> if (initialzeModules) {
<add> if (initializeModules) {
<ide> setupUserModules();
<ide> }
<ide> } | 1 |
Javascript | Javascript | fix parse query | c7a90e04219ec6177b42f6e5c26c5202ecbbbe23 | <ide><path>web/viewer.js
<ide> var PDFView = {
<ide>
<ide> // Helper function to parse query string (e.g. ?param1=value&parm2=...).
<ide> parseQueryString: function pdfViewParseQueryString(query) {
<del> var params = query.split('&');
<del> for (var i = 0; i < params.length; i++) {
<del> var param = params[i].split('=');
<del> params[unescape(param[0])] = unescape(param[1]);
<add> var parts = query.split('&');
<add> var params = [];
<add> for (var i = 0, ii = parts.length; i < parts.length; ++i) {
<add> var param = parts[i].split('=');
<add> var key = param[0];
<add> var value = param.length > 1 ? param[1] : null;
<add> params[unescape(key)] = unescape(value);
<ide> }
<ide> return params;
<ide> } | 1 |
Ruby | Ruby | add examples to array#to_sentence [ci skip] | 1e1d1da3ad71ed43fcff73bc3956579b69a1563d | <ide><path>activesupport/lib/active_support/core_ext/array/conversions.rb
<ide> require 'active_support/core_ext/string/inflections'
<ide>
<ide> class Array
<del> # Converts the array to a comma-separated sentence where the last element is joined by the connector word. Options:
<del> # * <tt>:words_connector</tt> - The sign or word used to join the elements in arrays with two or more elements (default: ", ")
<del> # * <tt>:two_words_connector</tt> - The sign or word used to join the elements in arrays with two elements (default: " and ")
<del> # * <tt>:last_word_connector</tt> - The sign or word used to join the last element in arrays with three or more elements (default: ", and ")
<add> # Converts the array to a comma-separated sentence where the last element is
<add> # joined by the connector word.
<add> #
<add> # Options:
<add> #
<add> # * <tt>:words_connector</tt> - The sign or word used to join the elements
<add> # in arrays with two or more elements (default: ", ").
<add> # * <tt>:two_words_connector</tt> - The sign or word used to join the elements
<add> # in arrays with two elements (default: " and ").
<add> # * <tt>:last_word_connector</tt> - The sign or word used to join the last element
<add> # in arrays with three or more elements (default: ", and ").
<add> #
<add> # Examples:
<add> #
<add> # [].to_sentence # => ""
<add> # ['one'].to_sentence # => "one"
<add> # ['one', 'two'].to_sentence # => "one and two"
<add> # ['one', 'two', 'three'].to_sentence # => "one, two, and three"
<add> #
<add> # ['one', 'two'].to_sentence(two_words_connector: '-')
<add> # # => "one-two"
<add> #
<add> # ['one', 'two', 'three'].to_sentence(words_connector: ' or ', last_word_connector: ' or at least ')
<add> # # => "one or two or at least three"
<ide> def to_sentence(options = {})
<ide> options.assert_valid_keys(:words_connector, :two_words_connector, :last_word_connector, :locale)
<ide> | 1 |
Ruby | Ruby | remove unused argument `expected_database` | a444bae3f29ffc09231e31526631bcb35fa2bfa0 | <ide><path>railties/test/application/rake/multi_dbs_test.rb
<ide> def db_migrate_and_schema_dump_and_load(format)
<ide> end
<ide> end
<ide>
<del> def db_migrate_namespaced(namespace, expected_database)
<add> def db_migrate_namespaced(namespace)
<ide> Dir.chdir(app_path) do
<ide> generate_models_for_animals
<ide> output = rails("db:migrate:#{namespace}")
<ide> def db_migrate_namespaced(namespace, expected_database)
<ide> end
<ide> end
<ide>
<del> def db_migrate_status_namespaced(namespace, expected_database)
<add> def db_migrate_status_namespaced(namespace)
<ide> Dir.chdir(app_path) do
<ide> generate_models_for_animals
<ide> output = rails("db:migrate:status:#{namespace}")
<ide> def generate_models_for_animals
<ide> test "db:migrate:namespace works" do
<ide> require "#{app_path}/config/environment"
<ide> ActiveRecord::Base.configurations.configs_for(env_name: Rails.env).each do |db_config|
<del> db_migrate_namespaced db_config.spec_name, db_config.config["database"]
<add> db_migrate_namespaced db_config.spec_name
<ide> end
<ide> end
<ide>
<ide> def generate_models_for_animals
<ide> test "db:migrate:status:namespace works" do
<ide> require "#{app_path}/config/environment"
<ide> ActiveRecord::Base.configurations.configs_for(env_name: Rails.env).each do |db_config|
<del> db_migrate_namespaced db_config.spec_name, db_config.config["database"]
<del> db_migrate_status_namespaced db_config.spec_name, db_config.config["database"]
<add> db_migrate_namespaced db_config.spec_name
<add> db_migrate_status_namespaced db_config.spec_name
<ide> end
<ide> end
<ide> | 1 |
Ruby | Ruby | improve tests to use only public api | 13c18fe2cab630798bd8f7946bc2646f0d295c7f | <ide><path>activerecord/test/cases/relation_test.rb
<ide> def test_relation_merging_with_joins_as_join_dependency_pick_proper_parent
<ide> comment = post.comments.create!(body: "hu")
<ide> 3.times { comment.ratings.create! }
<ide>
<del> relation = Post.joins Associations::JoinDependency.new(Post, :comments, [])
<del> relation = relation.joins Associations::JoinDependency.new(Comment, :ratings, [])
<add> relation = Post.joins(:comments).merge Comment.joins(:ratings)
<ide>
<del> assert_equal 3, relation.pluck(:id).select { |id| id == post.id }.count
<add> assert_equal 3, relation.where(id: post.id).pluck(:id).size
<ide> end
<ide>
<ide> def test_respond_to_for_non_selected_element | 1 |
Python | Python | describe dag owner more carefully | b6c20a8f5dadd14e45ecec05b8434f9a76fb4e27 | <ide><path>airflow/models/baseoperator.py
<ide> class derived from this one results in the creation of a task object,
<ide>
<ide> :param task_id: a unique, meaningful id for the task
<ide> :type task_id: str
<del> :param owner: the owner of the task, using the unix username is recommended
<add> :param owner: the owner of the task. Using a meaningful description
<add> (e.g. user/person/team/role name) to clarify ownership is recommended.
<ide> :type owner: str
<ide> :param email: the 'to' email address(es) used in email alerts. This can be a
<ide> single email or multiple ones. Multiple addresses can be specified as a | 1 |
Java | Java | fix timezone issue in datetimeformatterfactory | 93c01e071098bb2e07e127c3b091d89ce73de983 | <ide><path>spring-context/src/main/java/org/springframework/format/datetime/joda/DateTimeFormatterFactory.java
<ide> * or {@link #setStyle(String) style} (considered in that order).
<ide> *
<ide> * @author Phillip Webb
<add> * @author Sam Brannen
<ide> * @see #getDateTimeFormatter()
<ide> * @see #getDateTimeFormatter(DateTimeFormatter)
<ide> * @since 3.2
<ide> public DateTimeFormatter getDateTimeFormatter() {
<ide> public DateTimeFormatter getDateTimeFormatter(DateTimeFormatter fallbackFormatter) {
<ide> DateTimeFormatter dateTimeFormatter = createDateTimeFormatter();
<ide> if(dateTimeFormatter != null && this.timeZone != null) {
<del> dateTimeFormatter.withZone(DateTimeZone.forTimeZone(this.timeZone));
<add> dateTimeFormatter = dateTimeFormatter.withZone(DateTimeZone.forTimeZone(this.timeZone));
<ide> }
<ide> return (dateTimeFormatter != null ? dateTimeFormatter : fallbackFormatter);
<ide> }
<ide><path>spring-context/src/test/java/org/springframework/format/datetime/joda/DateTimeFormatterFactoryTests.java
<ide>
<ide> package org.springframework.format.datetime.joda;
<ide>
<del>import static org.hamcrest.Matchers.equalTo;
<del>import static org.hamcrest.Matchers.is;
<del>import static org.hamcrest.Matchers.nullValue;
<del>import static org.hamcrest.Matchers.sameInstance;
<add>import static org.hamcrest.Matchers.*;
<ide> import static org.junit.Assert.*;
<ide>
<ide> import java.util.Locale;
<ide> import java.util.TimeZone;
<ide>
<ide> import org.joda.time.DateTime;
<add>import org.joda.time.DateTimeZone;
<ide> import org.joda.time.format.DateTimeFormat;
<ide> import org.joda.time.format.DateTimeFormatter;
<ide> import org.junit.Test;
<ide> * Tests for {@link DateTimeFormatterFactory}.
<ide> *
<ide> * @author Phillip Webb
<add> * @author Sam Brannen
<ide> */
<ide> public class DateTimeFormatterFactoryTests {
<ide>
<ide> private DateTimeFormatterFactory factory = new DateTimeFormatterFactory();
<ide>
<ide> private DateTime dateTime = new DateTime(2009, 10, 21, 12, 10, 00, 00);
<ide>
<add>
<ide> @Test
<ide> public void shouldDefaultToMediumFormat() throws Exception {
<ide> assertThat(factory.getObject(), is(equalTo(DateTimeFormat.mediumDateTime())));
<ide> public void shouldBeSingleton() throws Exception {
<ide> @Test
<ide> @SuppressWarnings("rawtypes")
<ide> public void shouldCreateDateTimeFormatter() throws Exception {
<del> assertThat(factory.getObjectType(), is(equalTo((Class)DateTimeFormatter.class)));
<add> assertThat(factory.getObjectType(), is(equalTo((Class) DateTimeFormatter.class)));
<ide> }
<ide>
<ide> @Test
<ide> public void shouldGetDateTimeFormatter() throws Exception {
<ide>
<ide> @Test
<ide> public void shouldGetWithTimeZone() throws Exception {
<add>
<add> TimeZone zurich = TimeZone.getTimeZone("Europe/Zurich");
<add> TimeZone newYork = TimeZone.getTimeZone("America/New_York");
<add>
<add> // Ensure that we are testing against a timezone other than the default.
<add> TimeZone testTimeZone;
<add> String offset;
<add>
<add> if (zurich.equals(TimeZone.getDefault())) {
<add> testTimeZone = newYork;
<add> offset = "-0400"; // Daylight savings on October 21st
<add> }
<add> else {
<add> testTimeZone = zurich;
<add> offset = "+0200"; // Daylight savings on October 21st
<add> }
<add>
<ide> factory.setPattern("yyyyMMddHHmmss Z");
<del> factory.setTimeZone(TimeZone.getTimeZone("-0700"));
<del> assertThat(factory.getDateTimeFormatter().print(dateTime), is("20091021121000 -0700"));
<add> factory.setTimeZone(testTimeZone);
<add>
<add> DateTimeZone dateTimeZone = DateTimeZone.forTimeZone(testTimeZone);
<add> DateTime dateTime = new DateTime(2009, 10, 21, 12, 10, 00, 00, dateTimeZone);
<add>
<add> assertThat(factory.getDateTimeFormatter().print(dateTime), is("20091021121000 " + offset));
<ide> }
<ide>
<ide> private DateTimeFormatter applyLocale(DateTimeFormatter dateTimeFormatter) {
<ide> return dateTimeFormatter.withLocale(Locale.US);
<ide> }
<add>
<ide> } | 2 |
Python | Python | add chroot detection | 21532aa519e4d07a052dd4e4f1561e511c466620 | <ide><path>setup.py
<ide>
<ide> from setuptools import setup
<ide>
<add>is_chroot = os.stat('/').st_ino != 2
<add>
<ide>
<ide> def get_data_files():
<ide> data_files = [
<ide> def get_data_files():
<ide> ('share/man/man1', ['man/glances.1'])
<ide> ]
<ide>
<del> if os.name == 'posix' and os.getuid() == 0: # Unix-like + root privileges
<add> if hasattr(sys, 'real_prefix'): # virtualenv
<add> conf_path = os.path.join(sys.prefix, 'etc', 'glances')
<add> elif os.name == 'posix' and (os.getuid() == 0 or is_chroot):
<add> # Unix-like + root privileges/chroot environment
<ide> if 'bsd' in sys.platform:
<ide> conf_path = os.path.join(sys.prefix, 'etc', 'glances')
<ide> elif 'linux' in sys.platform:
<ide> conf_path = os.path.join('/etc', 'glances')
<ide> elif 'darwin' in sys.platform:
<ide> conf_path = os.path.join('/usr/local', 'etc', 'glances')
<del> elif hasattr(sys, 'real_prefix'): # virtualenv
<del> conf_path = os.path.join(sys.prefix, 'etc', 'glances')
<ide> elif 'win32' in sys.platform: # windows
<ide> conf_path = os.path.join(os.environ.get('APPDATA'), 'glances')
<ide> else: # Unix-like + per-user install | 1 |
Javascript | Javascript | add support for changing /route/#hashes | ad1b6310deb6ccaec16016e999049fa307a8a61c | <ide><path>examples/with-google-analytics/pages/_app.js
<ide> const App = ({ Component, pageProps }) => {
<ide> gtag.pageview(url)
<ide> }
<ide> router.events.on('routeChangeComplete', handleRouteChange)
<add> router.events.on('hashChangeComplete', handleRouteChange)
<ide> return () => {
<ide> router.events.off('routeChangeComplete', handleRouteChange)
<add> router.events.off('hashChangeComplete', handleRouteChange)
<ide> }
<ide> }, [router.events])
<ide> | 1 |
Python | Python | clean markdown with dedent to respect indents | 6f9c0ceeb40947c226d35587097529d04c3e3e59 | <ide><path>airflow/www/utils.py
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<ide> import json
<add>import textwrap
<ide> import time
<ide> from urllib.parse import urlencode
<ide>
<ide> def wrapped_markdown(s, css_class='rich_doc'):
<ide> """Convert a Markdown string to HTML."""
<ide> if s is None:
<ide> return None
<del>
<del> s = '\n'.join(line.lstrip() for line in s.split('\n'))
<del>
<add> s = textwrap.dedent(s)
<ide> return Markup(f'<div class="{css_class}" >' + markdown.markdown(s, extensions=['tables']) + "</div>")
<ide>
<ide>
<ide><path>tests/www/test_utils.py
<ide> def test_wrapped_markdown_with_indented_lines(self):
<ide> )
<ide>
<ide> assert '<div class="rich_doc" ><h1>header</h1>\n<p>1st line\n2nd line</p></div>' == rendered
<add>
<add> def test_wrapped_markdown_with_raw_code_block(self):
<add> rendered = wrapped_markdown(
<add> """\
<add> # Markdown code block
<add>
<add> Inline `code` works well.
<add>
<add> Code block
<add> does not
<add> respect
<add> newlines
<add>
<add> """
<add> )
<add>
<add> assert (
<add> '<div class="rich_doc" ><h1>Markdown code block</h1>\n'
<add> '<p>Inline <code>code</code> works well.</p>\n'
<add> '<pre><code>Code block\ndoes not\nrespect\nnewlines\n</code></pre></div>'
<add> ) == rendered
<add>
<add> def test_wrapped_markdown_with_nested_list(self):
<add> rendered = wrapped_markdown(
<add> """
<add> ### Docstring with a code block
<add>
<add> - And
<add> - A nested list
<add> """
<add> )
<add>
<add> assert (
<add> '<div class="rich_doc" ><h3>Docstring with a code block</h3>\n'
<add> '<ul>\n<li>And<ul>\n<li>A nested list</li>\n</ul>\n</li>\n</ul></div>'
<add> ) == rendered | 2 |
Python | Python | fix previous fix to numpy/g2py/setup.py | 8f6114b11efc2a01fe1158a444aeb788ddea6b01 | <ide><path>numpy/f2py/setup.py
<ide> def generate_f2py_py(build_dir):
<ide> elif mode=="2e-numpy":
<ide> from numpy.f2py import main
<ide> else:
<del> sys.stderr.write("Unknown mode: '%s'\n" % mode)
<add> sys.stderr.write("Unknown mode: " + repr(mode))
<ide> sys.exit(1)
<ide> main()
<ide> '''%(os.path.basename(sys.executable))) | 1 |
Python | Python | update cversions.py links and wording | 8727cae494004e621fd099f32b601e4498721e69 | <ide><path>numpy/core/setup_common.py
<ide> #-------------------
<ide> # How to change C_API_VERSION ?
<ide> # - increase C_API_VERSION value
<del># - record the hash for the new C API with the script cversions.py
<add># - record the hash for the new C API with the cversions.py script
<ide> # and add the hash to cversions.txt
<ide> # The hash values are used to remind developers when the C API number was not
<ide> # updated - generates a MismatchCAPIWarning warning which is turned into an
<ide> def check_api_version(apiversion, codegen_dir):
<ide> # codegen_dir have been updated without the API version being
<ide> # updated. Any modification in those .txt files should be reflected
<ide> # in the api and eventually abi versions.
<del> # To compute the checksum of the current API, use
<del> # code_generators/cversions.py script
<add> # To compute the checksum of the current API, use numpy/core/cversions.py
<ide> if not curapi_hash == api_hash:
<ide> msg = ("API mismatch detected, the C API version "
<ide> "numbers have to be updated. Current C api version is %d, "
<del> "with checksum %s, but recorded checksum for C API version %d in "
<del> "codegen_dir/cversions.txt is %s. If functions were added in the "
<del> "C API, you have to update C_API_VERSION in %s."
<add> "with checksum %s, but recorded checksum for C API version %d "
<add> "in core/codegen_dir/cversions.txt is %s. If functions were "
<add> "added in the C API, you have to update C_API_VERSION in %s."
<ide> )
<ide> warnings.warn(msg % (apiversion, curapi_hash, apiversion, api_hash,
<ide> __file__), | 1 |
Python | Python | add usernames to todos | 5c37e69cf1e3fb053380a15b1df79a2813c6b5c3 | <ide><path>official/recommendation/data_pipeline.py
<ide> def get_dataset(self, batch_size, epochs_between_evals):
<ide>
<ide> file_pattern = os.path.join(
<ide> epoch_data_dir, rconst.SHARD_TEMPLATE.format("*"))
<del> # TODO: remove this contrib import
<add> # TODO(seemuch): remove this contrib import
<ide> # pylint: disable=line-too-long
<ide> from tensorflow.contrib.tpu.python.tpu.datasets import StreamingFilesDataset
<ide> # pylint: enable=line-too-long
<ide><path>official/recommendation/ncf_estimator_main.py
<ide> def construct_estimator(model_dir, params):
<ide>
<ide> model_fn = neumf_model.neumf_model_fn
<ide> if params["use_xla_for_gpu"]:
<del> # TODO: remove the contrib imput
<add> # TODO(seemuch): remove the contrib imput
<ide> from tensorflow.contrib.compiler import xla
<ide> logging.info("Using XLA for GPU for training and evaluation.")
<ide> model_fn = xla.estimator_model_fn(model_fn)
<ide><path>official/recommendation/neumf_model.py
<ide> def neumf_model_fn(features, labels, mode, params):
<ide> beta2=params["beta2"],
<ide> epsilon=params["epsilon"])
<ide> if params["use_tpu"]:
<del> # TODO: remove this contrib import
<add> # TODO(seemuch): remove this contrib import
<ide> optimizer = tf.contrib.tpu.CrossShardOptimizer(optimizer)
<ide>
<ide> mlperf_helper.ncf_print(key=mlperf_helper.TAGS.MODEL_HP_LOSS_FN, | 3 |
Python | Python | fix multiple migrations heads | 7d37391a2b93259281cbe99125240727319633ba | <ide><path>airflow/migrations/versions/e38be357a868_update_schema_for_smart_sensor.py
<ide> """Add sensor_instance table
<ide>
<ide> Revision ID: e38be357a868
<del>Revises: 03afc6b6f902
<add>Revises: 8d48763f6d53
<ide> Create Date: 2019-06-07 04:03:17.003939
<ide>
<ide> """
<ide>
<ide> # revision identifiers, used by Alembic.
<ide> revision = 'e38be357a868'
<del>down_revision = '03afc6b6f902'
<add>down_revision = '8d48763f6d53'
<ide> branch_labels = None
<ide> depends_on = None
<ide> | 1 |
Javascript | Javascript | avoid extra listener | 2fd2dd75657af12a74e01a9a5e39e5f677ff3c88 | <ide><path>lib/_http_client.js
<ide> ClientRequest.prototype.abort = function abort() {
<ide> // If we're aborting, we don't care about any more response data.
<ide> if (this.res) {
<ide> this.res._dump();
<del> } else {
<del> this.once('response', (res) => {
<del> res._dump();
<del> });
<ide> }
<ide>
<ide> // In the event that we don't have a socket, we will pop out of
<ide> function parserOnIncomingClient(res, shouldKeepAlive) {
<ide> // Add our listener first, so that we guarantee socket cleanup
<ide> res.on('end', responseOnEnd);
<ide> req.on('prefinish', requestOnPrefinish);
<del> const handled = req.emit('response', res);
<ide>
<ide> // If the user did not listen for the 'response' event, then they
<ide> // can't possibly read the data, so we ._dump() it into the void
<ide> // so that the socket doesn't hang there in a paused state.
<del> if (!handled)
<add> if (req.aborted || !req.emit('response', res))
<ide> res._dump();
<ide>
<ide> if (method === 'HEAD') | 1 |
Ruby | Ruby | add --unsafe-perm to std_args only if run as root | 79a1500f2b7416cac9da55f02e8ba1d09e66404f | <ide><path>Library/Homebrew/language/node.rb
<ide> def self.std_npm_install_args(libexec)
<ide> pack = pack_for_installation
<ide>
<ide> # npm install args for global style module format installed into libexec
<del> %W[
<add> args = %W[
<ide> -ddd
<ide> --global
<del> --unsafe-perm
<ide> --build-from-source
<ide> --#{npm_cache_config}
<ide> --prefix=#{libexec}
<ide> #{Dir.pwd}/#{pack}
<ide> ]
<add>
<add> args << "--unsafe-perm" if ENV["USER"] == "root"
<add>
<add> args
<ide> end
<ide>
<ide> def self.local_npm_install_args | 1 |
PHP | PHP | fix coding standards | 072ec650e6a87371baaf6ab2d5f20921649d7bba | <ide><path>tests/TestCase/Console/Command/Task/ControllerTaskTest.php
<ide> public function setUp() {
<ide> TableRegistry::get('BakeArticles', [
<ide> 'className' => __NAMESPACE__ . '\BakeArticlesTable'
<ide> ]);
<del>
<ide> }
<ide>
<ide> /**
<ide> public function testBakePrefixed() {
<ide> ->method('createFile')
<ide> ->with($filename, $this->anything());
<ide> $result = $this->Task->bake('BakeArticles');
<del>
<add>
<ide> $this->assertTextContains('namespace App\Controller\Admin;', $result);
<ide> $this->assertTextContains('use App\Controller\AppController;', $result);
<ide> } | 1 |
Mixed | Ruby | add a monitor to modelschema#load_schema | 6a5a814eaa0d4f98d6151df5bd96cc8ec1ae5675 | <ide><path>activerecord/CHANGELOG.md
<add>* Loading model schema from database is now thread-safe.
<add>
<add> Fixes #28589.
<add>
<add> *Vikrant Chaudhary*, *David Abdemoulaie*
<add>
<ide> * Add `ActiveRecord::Base#cache_version` to support recyclable cache keys via the new versioned entries
<ide> in `ActiveSupport::Cache`. This also means that `ActiveRecord::Base#cache_key` will now return a stable key
<ide> that does not include a timestamp any more.
<ide><path>activerecord/lib/active_record/model_schema.rb
<add>require "monitor"
<add>
<ide> module ActiveRecord
<ide> module ModelSchema
<ide> extend ActiveSupport::Concern
<ide> module ModelSchema
<ide> self.inheritance_column = "type"
<ide>
<ide> delegate :type_for_attribute, to: :class
<add>
<add> initialize_load_schema_monitor
<ide> end
<ide>
<ide> # Derives the join table name for +first_table+ and +second_table+. The
<ide> def reset_column_information
<ide> initialize_find_by_cache
<ide> end
<ide>
<add> protected
<add>
<add> def initialize_load_schema_monitor
<add> @load_schema_monitor = Monitor.new
<add> end
<add>
<ide> private
<ide>
<add> def inherited(child_class)
<add> super
<add> child_class.initialize_load_schema_monitor
<add> end
<add>
<ide> def schema_loaded?
<del> defined?(@columns_hash) && @columns_hash
<add> defined?(@schema_loaded) && @schema_loaded
<ide> end
<ide>
<ide> def load_schema
<del> unless schema_loaded?
<del> load_schema!
<add> return if schema_loaded?
<add> @load_schema_monitor.synchronize do
<add> load_schema! unless defined?(@columns_hash) && @columns_hash
<ide> end
<ide> end
<ide>
<ide> def load_schema!
<ide> user_provided_default: false
<ide> )
<ide> end
<add>
<add> @schema_loaded = true
<ide> end
<ide>
<ide> def reload_schema_from_cache
<ide> def reload_schema_from_cache
<ide> @attributes_builder = nil
<ide> @columns = nil
<ide> @columns_hash = nil
<add> @schema_loaded = false
<ide> @attribute_names = nil
<ide> @yaml_encoder = nil
<ide> direct_descendants.each do |descendant|
<ide><path>activerecord/test/cases/serialized_attribute_test.rb
<ide> def deserialize(value)
<ide> topic.foo
<ide> refute topic.changed?
<ide> end
<add>
<add> def test_serialized_attribute_works_under_concurrent_initial_access
<add> model = Topic.dup
<add>
<add> topic = model.last
<add> topic.update group: "1"
<add>
<add> model.serialize :group, JSON
<add> model.reset_column_information
<add>
<add> # This isn't strictly necessary for the test, but a little bit of
<add> # knowledge of internals allows us to make failures far more likely.
<add> model.define_singleton_method(:define_attribute) do |*args|
<add> Thread.pass
<add> super(*args)
<add> end
<add>
<add> threads = 4.times.map do
<add> Thread.new do
<add> topic.reload.group
<add> end
<add> end
<add>
<add> # All the threads should retrieve the value knowing it is JSON, and
<add> # thus decode it. If this fails, some threads will instead see the
<add> # raw string ("1"), or raise an exception.
<add> assert_equal [1] * threads.size, threads.map(&:value)
<add> end
<ide> end | 3 |
PHP | PHP | add env class | e965a0a8b94fd79303eb2b1846605d4a9bc56be0 | <ide><path>src/Illuminate/Support/Env.php
<add><?php
<add>
<add>namespace Illuminate\Support;
<add>
<add>use PhpOption\Option;
<add>use Dotenv\Environment\DotenvFactory;
<add>use Dotenv\Environment\Adapter\PutenvAdapter;
<add>use Dotenv\Environment\Adapter\EnvConstAdapter;
<add>use Dotenv\Environment\Adapter\ServerConstAdapter;
<add>
<add>class Env
<add>{
<add> /**
<add> * Gets the value of an environment variable.
<add> *
<add> * @param string $key
<add> * @param mixed $default
<add> * @return mixed
<add> */
<add> public static function get($key, $default = null)
<add> {
<add> static $variables;
<add>
<add> if ($variables === null) {
<add> $variables = (new DotenvFactory([new EnvConstAdapter, new PutenvAdapter, new ServerConstAdapter]))->createImmutable();
<add> }
<add>
<add> return Option::fromValue($variables->get($key))
<add> ->map(function ($value) {
<add> switch (strtolower($value)) {
<add> case 'true':
<add> case '(true)':
<add> return true;
<add> case 'false':
<add> case '(false)':
<add> return false;
<add> case 'empty':
<add> case '(empty)':
<add> return '';
<add> case 'null':
<add> case '(null)':
<add> return;
<add> }
<add>
<add> if (preg_match('/\A([\'"])(.*)\1\z/', $value, $matches)) {
<add> return $matches[2];
<add> }
<add>
<add> return $value;
<add> })
<add> ->getOrCall(function () use ($default) {
<add> return value($default);
<add> });
<add> }
<add>}
<ide><path>src/Illuminate/Support/helpers.php
<ide> <?php
<ide>
<del>use PhpOption\Option;
<ide> use Illuminate\Support\Arr;
<add>use Illuminate\Support\Env;
<ide> use Illuminate\Support\Optional;
<ide> use Illuminate\Support\Collection;
<del>use Dotenv\Environment\DotenvFactory;
<ide> use Illuminate\Contracts\Support\Htmlable;
<ide> use Illuminate\Support\HigherOrderTapProxy;
<del>use Dotenv\Environment\Adapter\EnvConstAdapter;
<del>use Dotenv\Environment\Adapter\ServerConstAdapter;
<ide>
<ide> if (! function_exists('append_config')) {
<ide> /**
<ide> function e($value, $doubleEncode = true)
<ide> */
<ide> function env($key, $default = null)
<ide> {
<del> static $variables;
<del>
<del> if ($variables === null) {
<del> $variables = (new DotenvFactory([new EnvConstAdapter, new ServerConstAdapter]))->createImmutable();
<del> }
<del>
<del> return Option::fromValue($variables->get($key))
<del> ->map(function ($value) {
<del> switch (strtolower($value)) {
<del> case 'true':
<del> case '(true)':
<del> return true;
<del> case 'false':
<del> case '(false)':
<del> return false;
<del> case 'empty':
<del> case '(empty)':
<del> return '';
<del> case 'null':
<del> case '(null)':
<del> return;
<del> }
<del>
<del> if (preg_match('/\A([\'"])(.*)\1\z/', $value, $matches)) {
<del> return $matches[2];
<del> }
<del>
<del> return $value;
<del> })
<del> ->getOrCall(function () use ($default) {
<del> return value($default);
<del> });
<add> return Env::get($key, $default);
<ide> }
<ide> }
<ide>
<ide><path>tests/Support/SupportHelpersTest.php
<ide> use ArrayAccess;
<ide> use Mockery as m;
<ide> use RuntimeException;
<add>use Illuminate\Support\Env;
<ide> use PHPUnit\Framework\TestCase;
<ide> use Illuminate\Support\Optional;
<ide> use Illuminate\Contracts\Support\Htmlable;
<ide> public function testEnv()
<ide> {
<ide> $_SERVER['foo'] = 'bar';
<ide> $this->assertSame('bar', env('foo'));
<add> $this->assertSame('bar', Env::get('foo'));
<ide> }
<ide>
<ide> public function testEnvTrue() | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.