content_type stringclasses 8
values | main_lang stringclasses 7
values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
Ruby | Ruby | use argv.include? instead of argv.flag? | 1ead0d4fe556cd7a671ea2f66f72354f4a40fc8c | <ide><path>Library/Homebrew/cmd/tests.rb
<ide> module Homebrew
<ide> def tests
<ide> (HOMEBREW_LIBRARY/"Homebrew/test").cd do
<ide> ENV["TESTOPTS"] = "-v" if ARGV.verbose?
<del> ENV["HOMEBREW_TESTS_COVERAGE"] = "1" if ARGV.flag? "--coverage"
<add> ENV["HOMEBREW_TESTS_COVERAGE"] = "1" if ARGV.include? "--coverage"
<ide> Homebrew.install_gem_setup_path! "bundler"
<ide> quiet_system("bundle", "check") || \
<ide> system("bundle", "install", "--path", "vendor/bundle") | 1 |
PHP | PHP | add tests for | a8672ed3022d019577de0c8c444b9787f5584be4 | <ide><path>tests/TestCase/ORM/TableTest.php
<ide> public function testSaveUpdatePrimaryKeyNotModified() {
<ide> ->will($this->returnValue($query));
<ide>
<ide> $statement = $this->getMock('\Cake\Database\Statement\StatementDecorator');
<del> $statement->expects($this->once())->method('rowCount')
<del> ->will($this->returnValue(1));
<add> $statement->expects($this->once())
<add> ->method('errorCode')
<add> ->will($this->returnValue('00000'));
<ide>
<del> $query->expects($this->once())->method('execute')
<add> $query->expects($this->once())
<add> ->method('execute')
<ide> ->will($this->returnValue($statement));
<ide>
<ide> $query->expects($this->once())->method('set')
<ide> public function testUpdateNoChange() {
<ide> $this->assertSame($entity, $table->save($entity));
<ide> }
<ide>
<add>/**
<add> * Tests that passing only the primary key to save will not execute any queries
<add> * but still return success
<add> *
<add> * @group save
<add> * @group integration
<add> * @return void
<add> */
<add> public function testUpdateDirtyNoActualChanges() {
<add> $table = TableRegistry::get('Articles');
<add> $entity = $table->get(1);
<add>
<add> $entity->accessible('*', true);
<add> $entity->set($entity->toArray());
<add> $this->assertSame($entity, $table->save($entity));
<add> }
<add>
<ide> /**
<ide> * Tests that failing to pass a primary key to save will result in exception
<ide> * | 1 |
Go | Go | move hijack to it's own file | 8c9192cd76ad46bda3d0ec5ba7eb4a30669afb40 | <ide><path>api/client/hijack.go
<add>package client
<add>
<add>import (
<add> "crypto/tls"
<add> "fmt"
<add> "io"
<add> "net"
<add> "net/http"
<add> "net/http/httputil"
<add> "os"
<add> "runtime"
<add> "strings"
<add>
<add> "github.com/dotcloud/docker/api"
<add> "github.com/dotcloud/docker/dockerversion"
<add> "github.com/dotcloud/docker/pkg/term"
<add> "github.com/dotcloud/docker/utils"
<add>)
<add>
<add>func (cli *DockerCli) dial() (net.Conn, error) {
<add> if cli.tlsConfig != nil && cli.proto != "unix" {
<add> return tls.Dial(cli.proto, cli.addr, cli.tlsConfig)
<add> }
<add> return net.Dial(cli.proto, cli.addr)
<add>}
<add>
<add>func (cli *DockerCli) hijack(method, path string, setRawTerminal bool, in io.ReadCloser, stdout, stderr io.Writer, started chan io.Closer) error {
<add> defer func() {
<add> if started != nil {
<add> close(started)
<add> }
<add> }()
<add>
<add> req, err := http.NewRequest(method, fmt.Sprintf("/v%s%s", api.APIVERSION, path), nil)
<add> if err != nil {
<add> return err
<add> }
<add> req.Header.Set("User-Agent", "Docker-Client/"+dockerversion.VERSION)
<add> req.Header.Set("Content-Type", "plain/text")
<add> req.Host = cli.addr
<add>
<add> dial, err := cli.dial()
<add> if err != nil {
<add> if strings.Contains(err.Error(), "connection refused") {
<add> return fmt.Errorf("Cannot connect to the Docker daemon. Is 'docker -d' running on this host?")
<add> }
<add> return err
<add> }
<add> clientconn := httputil.NewClientConn(dial, nil)
<add> defer clientconn.Close()
<add>
<add> // Server hijacks the connection, error 'connection closed' expected
<add> clientconn.Do(req)
<add>
<add> rwc, br := clientconn.Hijack()
<add> defer rwc.Close()
<add>
<add> if started != nil {
<add> started <- rwc
<add> }
<add>
<add> var receiveStdout chan error
<add>
<add> var oldState *term.State
<add>
<add> if in != nil && setRawTerminal && cli.isTerminal && os.Getenv("NORAW") == "" {
<add> oldState, err = term.SetRawTerminal(cli.terminalFd)
<add> if err != nil {
<add> return err
<add> }
<add> defer term.RestoreTerminal(cli.terminalFd, oldState)
<add> }
<add>
<add> if stdout != nil || stderr != nil {
<add> receiveStdout = utils.Go(func() (err error) {
<add> defer func() {
<add> if in != nil {
<add> if setRawTerminal && cli.isTerminal {
<add> term.RestoreTerminal(cli.terminalFd, oldState)
<add> }
<add> // For some reason this Close call blocks on darwin..
<add> // As the client exists right after, simply discard the close
<add> // until we find a better solution.
<add> if runtime.GOOS != "darwin" {
<add> in.Close()
<add> }
<add> }
<add> }()
<add>
<add> // When TTY is ON, use regular copy
<add> if setRawTerminal {
<add> _, err = io.Copy(stdout, br)
<add> } else {
<add> _, err = utils.StdCopy(stdout, stderr, br)
<add> }
<add> utils.Debugf("[hijack] End of stdout")
<add> return err
<add> })
<add> }
<add>
<add> sendStdin := utils.Go(func() error {
<add> if in != nil {
<add> io.Copy(rwc, in)
<add> utils.Debugf("[hijack] End of stdin")
<add> }
<add> if tcpc, ok := rwc.(*net.TCPConn); ok {
<add> if err := tcpc.CloseWrite(); err != nil {
<add> utils.Debugf("Couldn't send EOF: %s\n", err)
<add> }
<add> } else if unixc, ok := rwc.(*net.UnixConn); ok {
<add> if err := unixc.CloseWrite(); err != nil {
<add> utils.Debugf("Couldn't send EOF: %s\n", err)
<add> }
<add> }
<add> // Discard errors due to pipe interruption
<add> return nil
<add> })
<add>
<add> if stdout != nil || stderr != nil {
<add> if err := <-receiveStdout; err != nil {
<add> utils.Debugf("Error receiveStdout: %s", err)
<add> return err
<add> }
<add> }
<add>
<add> if !cli.isTerminal {
<add> if err := <-sendStdin; err != nil {
<add> utils.Debugf("Error sendStdin: %s", err)
<add> return err
<add> }
<add> }
<add> return nil
<add>}
<ide><path>api/client/utils.go
<ide> package client
<ide>
<ide> import (
<ide> "bytes"
<del> "crypto/tls"
<ide> "encoding/base64"
<ide> "encoding/json"
<ide> "errors"
<ide> import (
<ide> "io/ioutil"
<ide> "net"
<ide> "net/http"
<del> "net/http/httputil"
<ide> "net/url"
<ide> "os"
<ide> gosignal "os/signal"
<del> "regexp"
<del> goruntime "runtime"
<ide> "strconv"
<ide> "strings"
<ide> "syscall"
<ide> var (
<ide>
<ide> func (cli *DockerCli) HTTPClient() *http.Client {
<ide> tr := &http.Transport{
<add> TLSClientConfig: cli.tlsConfig,
<ide> Dial: func(network, addr string) (net.Conn, error) {
<ide> return net.Dial(cli.proto, cli.addr)
<ide> },
<ide> }
<del> if cli.proto != "unix" {
<del> tr.TLSClientConfig = cli.tlsConfig
<del> }
<ide> return &http.Client{Transport: tr}
<ide> }
<ide>
<del>func (cli *DockerCli) dial() (net.Conn, error) {
<del> if cli.tlsConfig != nil && cli.proto != "unix" {
<del> return tls.Dial(cli.proto, cli.addr, cli.tlsConfig)
<del> }
<del> return net.Dial(cli.proto, cli.addr)
<del>}
<del>
<ide> func (cli *DockerCli) call(method, path string, data interface{}, passAuthInfo bool) (io.ReadCloser, int, error) {
<ide> params := bytes.NewBuffer(nil)
<ide> if data != nil {
<ide> func (cli *DockerCli) call(method, path string, data interface{}, passAuthInfo b
<ide> }
<ide> }
<ide> }
<del> // fixme: refactor client to support redirect
<del> re := regexp.MustCompile("/+")
<del> path = re.ReplaceAllString(path, "/")
<ide>
<ide> req, err := http.NewRequest(method, fmt.Sprintf("http://v%s%s", api.APIVERSION, path), params)
<ide> if err != nil {
<ide> func (cli *DockerCli) streamHelper(method, path string, setRawTerminal bool, in
<ide> in = bytes.NewReader([]byte{})
<ide> }
<ide>
<del> // fixme: refactor client to support redirect
<del> re := regexp.MustCompile("/+")
<del> path = re.ReplaceAllString(path, "/")
<del>
<ide> req, err := http.NewRequest(method, fmt.Sprintf("http://v%s%s", api.APIVERSION, path), in)
<ide> if err != nil {
<ide> return err
<ide> func (cli *DockerCli) streamHelper(method, path string, setRawTerminal bool, in
<ide> return nil
<ide> }
<ide>
<del>func (cli *DockerCli) hijack(method, path string, setRawTerminal bool, in io.ReadCloser, stdout, stderr io.Writer, started chan io.Closer) error {
<del> defer func() {
<del> if started != nil {
<del> close(started)
<del> }
<del> }()
<del> // fixme: refactor client to support redirect
<del> re := regexp.MustCompile("/+")
<del> path = re.ReplaceAllString(path, "/")
<del>
<del> req, err := http.NewRequest(method, fmt.Sprintf("/v%s%s", api.APIVERSION, path), nil)
<del> if err != nil {
<del> return err
<del> }
<del> req.Header.Set("User-Agent", "Docker-Client/"+dockerversion.VERSION)
<del> req.Header.Set("Content-Type", "plain/text")
<del> req.Host = cli.addr
<del>
<del> dial, err := cli.dial()
<del> if err != nil {
<del> if strings.Contains(err.Error(), "connection refused") {
<del> return fmt.Errorf("Cannot connect to the Docker daemon. Is 'docker -d' running on this host?")
<del> }
<del> return err
<del> }
<del> clientconn := httputil.NewClientConn(dial, nil)
<del> defer clientconn.Close()
<del>
<del> // Server hijacks the connection, error 'connection closed' expected
<del> clientconn.Do(req)
<del>
<del> rwc, br := clientconn.Hijack()
<del> defer rwc.Close()
<del>
<del> if started != nil {
<del> started <- rwc
<del> }
<del>
<del> var receiveStdout chan error
<del>
<del> var oldState *term.State
<del>
<del> if in != nil && setRawTerminal && cli.isTerminal && os.Getenv("NORAW") == "" {
<del> oldState, err = term.SetRawTerminal(cli.terminalFd)
<del> if err != nil {
<del> return err
<del> }
<del> defer term.RestoreTerminal(cli.terminalFd, oldState)
<del> }
<del>
<del> if stdout != nil || stderr != nil {
<del> receiveStdout = utils.Go(func() (err error) {
<del> defer func() {
<del> if in != nil {
<del> if setRawTerminal && cli.isTerminal {
<del> term.RestoreTerminal(cli.terminalFd, oldState)
<del> }
<del> // For some reason this Close call blocks on darwin..
<del> // As the client exists right after, simply discard the close
<del> // until we find a better solution.
<del> if goruntime.GOOS != "darwin" {
<del> in.Close()
<del> }
<del> }
<del> }()
<del>
<del> // When TTY is ON, use regular copy
<del> if setRawTerminal {
<del> _, err = io.Copy(stdout, br)
<del> } else {
<del> _, err = utils.StdCopy(stdout, stderr, br)
<del> }
<del> utils.Debugf("[hijack] End of stdout")
<del> return err
<del> })
<del> }
<del>
<del> sendStdin := utils.Go(func() error {
<del> if in != nil {
<del> io.Copy(rwc, in)
<del> utils.Debugf("[hijack] End of stdin")
<del> }
<del> if tcpc, ok := rwc.(*net.TCPConn); ok {
<del> if err := tcpc.CloseWrite(); err != nil {
<del> utils.Debugf("Couldn't send EOF: %s\n", err)
<del> }
<del> } else if unixc, ok := rwc.(*net.UnixConn); ok {
<del> if err := unixc.CloseWrite(); err != nil {
<del> utils.Debugf("Couldn't send EOF: %s\n", err)
<del> }
<del> }
<del> // Discard errors due to pipe interruption
<del> return nil
<del> })
<del>
<del> if stdout != nil || stderr != nil {
<del> if err := <-receiveStdout; err != nil {
<del> utils.Debugf("Error receiveStdout: %s", err)
<del> return err
<del> }
<del> }
<del>
<del> if !cli.isTerminal {
<del> if err := <-sendStdin; err != nil {
<del> utils.Debugf("Error sendStdin: %s", err)
<del> return err
<del> }
<del> }
<del> return nil
<del>
<del>}
<del>
<ide> func (cli *DockerCli) resizeTty(id string) {
<ide> height, width := cli.getTtySize()
<ide> if height == 0 && width == 0 { | 2 |
Javascript | Javascript | fix context-switching #each | a82291a8b484236215623b6ecd77b50494184e1f | <ide><path>packages/ember-htmlbars/lib/env.js
<ide> import bindShadowScope from "ember-htmlbars/hooks/bind-shadow-scope";
<ide> import bindSelf from "ember-htmlbars/hooks/bind-self";
<ide> import bindScope from "ember-htmlbars/hooks/bind-scope";
<ide> import bindLocal from "ember-htmlbars/hooks/bind-local";
<add>import updateSelf from "ember-htmlbars/hooks/update-self";
<ide> import getRoot from "ember-htmlbars/hooks/get-root";
<ide> import getChild from "ember-htmlbars/hooks/get-child";
<ide> import getValue from "ember-htmlbars/hooks/get-value";
<ide> merge(emberHooks, {
<ide> bindSelf: bindSelf,
<ide> bindScope: bindScope,
<ide> bindLocal: bindLocal,
<add> updateSelf: updateSelf,
<ide> getRoot: getRoot,
<ide> getChild: getChild,
<ide> getValue: getValue,
<ide><path>packages/ember-htmlbars/lib/helpers/each.js
<ide> export default function eachHelper(params, hash, blocks) {
<ide> }
<ide>
<ide> forEach(list, function(item, i) {
<add> var self;
<add> if (blocks.template.arity === 0) {
<add> Ember.deprecate(deprecation);
<add> self = item;
<add> }
<add>
<ide> var key = keyPath ? get(item, keyPath) : String(i);
<del> blocks.template.yieldItem(key, [item, i]);
<add> blocks.template.yieldItem(key, [item, i], self);
<ide> });
<ide> }
<add>
<add>export var deprecation = "Using the context switching form of {{each}} is deprecated. Please use the keyword form (`{{#each items as |item|}}`) instead.";
<ide><path>packages/ember-htmlbars/lib/hooks/bind-self.js
<ide> */
<ide>
<ide> import { get } from "ember-metal/property_get";
<del>import updateScope from "ember-htmlbars/utils/update-scope";
<add>import SimpleStream from "ember-metal/streams/simple-stream";
<add>import subscribe from "ember-htmlbars/utils/subscribe";
<ide>
<ide> export default function bindSelf(env, scope, self) {
<ide> Ember.assert("BUG: scope.attrs and self.isView should not both be true", !(scope.attrs && self.isView));
<ide>
<ide> if (self.isView) {
<ide> scope.view = self;
<del> updateScope(scope.locals, 'view', self, null);
<del> updateScope(scope, 'self', get(self, 'context'), null, true);
<add> newStream(scope.locals, 'view', self, null);
<add> newStream(scope, 'self', get(self, 'context'), null, true);
<ide> return;
<ide> }
<ide>
<del> updateScope(scope, 'self', self, null);
<add> newStream(scope, 'self', self, null);
<add>}
<add>
<add>function newStream(scope, key, newValue, renderNode, isSelf) {
<add> var stream = new SimpleStream(newValue, isSelf ? null : key);
<add> if (renderNode) { subscribe(renderNode, scope, stream); }
<add> scope[key] = stream;
<ide> }
<ide><path>packages/ember-htmlbars/lib/hooks/update-self.js
<add>/**
<add>@module ember
<add>@submodule ember-htmlbars
<add>*/
<add>
<add>import { get } from "ember-metal/property_get";
<add>import updateScope from "ember-htmlbars/utils/update-scope";
<add>
<add>export default function bindSelf(env, scope, self) {
<add> Ember.assert("BUG: scope.attrs and self.isView should not both be true", !(scope.attrs && self.isView));
<add>
<add> if (self.isView) {
<add> scope.view = self;
<add> updateScope(scope.locals, 'view', self, null);
<add> updateScope(scope, 'self', get(self, 'context'), null, true);
<add> return;
<add> }
<add>
<add> updateScope(scope, 'self', self, null);
<add>}
<ide><path>packages/ember-htmlbars/tests/helpers/each_test.js
<ide> import { set } from "ember-metal/property_set";
<ide> import { runAppend, runDestroy } from "ember-runtime/tests/utils";
<ide>
<ide> import compile from "ember-template-compiler/system/compile";
<add>import { deprecation as eachDeprecation } from "ember-htmlbars/helpers/each";
<ide>
<ide> var people, view, registry, container;
<ide> var template, templateMyView, MyView, MyEmptyView, templateMyEmptyView;
<ide> QUnit.module("the #each helper [DEPRECATED]", {
<ide>
<ide> expectDeprecation(function() {
<ide> runAppend(view);
<del> }, 'Using the context switching form of {{each}} is deprecated. Please use the keyword form (`{{#each foo in bar}}`) instead.');
<add> }, eachDeprecation);
<ide> },
<ide>
<ide> teardown() {
<ide> QUnit.test("View should not use keyword incorrectly - Issue #1315", function() {
<ide>
<ide> view = EmberView.create({
<ide> container: container,
<del> template: templateFor('{{#each value in view.content}}{{value}}-{{#each option in view.options}}{{option.value}}:{{option.label}} {{/each}}{{/each}}'),
<add> template: templateFor('{{#each view.content as |value|}}{{value}}-{{#each view.options as |option|}}{{option.value}}:{{option.label}} {{/each}}{{/each}}'),
<ide>
<ide> content: A(['X', 'Y']),
<ide> options: A([
<ide> QUnit.test("views inside #each preserve the new context [DEPRECATED]", function(
<ide>
<ide> expectDeprecation(function() {
<ide> runAppend(view);
<del> }, 'Using the context switching form of {{each}} is deprecated. Please use the keyword form (`{{#each foo in bar}}`) instead.');
<add> }, eachDeprecation);
<ide>
<ide> equal(view.$().text(), "AdamSteve");
<ide> });
<ide> QUnit.test("single-arg each defaults to current context [DEPRECATED]", function(
<ide>
<ide> expectDeprecation(function() {
<ide> runAppend(view);
<del> }, 'Using the context switching form of {{each}} is deprecated. Please use the keyword form (`{{#each foo in bar}}`) instead.');
<add> }, eachDeprecation);
<ide>
<ide> equal(view.$().text(), "AdamSteve");
<ide> });
<ide> QUnit.test("single-arg each will iterate over controller if present [DEPRECATED]
<ide>
<ide> expectDeprecation(function() {
<ide> runAppend(view);
<del> }, 'Using the context switching form of {{each}} is deprecated. Please use the keyword form (`{{#each foo in bar}}`) instead.');
<add> }, eachDeprecation);
<ide>
<ide> equal(view.$().text(), "AdamSteve");
<ide> });
<ide> function testEachWithItem(moduleName, useBlockParams) {
<ide>
<ide> expectDeprecation(function() {
<ide> runAppend(view);
<del> }, 'Using the context switching form of {{each}} is deprecated. Please use the keyword form (`{{#each foo in bar}}`) instead.');
<add> }, eachDeprecation);
<ide>
<ide> equal(view.$().text(), "AdamSteve");
<ide> });
<ide> function testEachWithItem(moduleName, useBlockParams) {
<ide>
<ide> expectDeprecation(function() {
<ide> runAppend(view);
<del> }, 'Using the context switching form of {{each}} is deprecated. Please use the keyword form (`{{#each foo in bar}}`) instead.');
<add> }, eachDeprecation);
<ide>
<ide> equal(view.$().text(), "AdamSteve");
<ide> });
<ide> function testEachWithItem(moduleName, useBlockParams) {
<ide>
<ide> expectDeprecation(function() {
<ide> runAppend(view);
<del> }, 'Using the context switching form of {{each}} is deprecated. Please use the keyword form (`{{#each foo in bar}}`) instead.');
<add> }, eachDeprecation);
<ide>
<ide> equal(view.$().text(), "AdamSteve");
<ide> }); | 5 |
PHP | PHP | register the schedulelistcommand | 34060336c9cb9b0cb5940cbac791dcd82bc9a4f5 | <ide><path>src/Illuminate/Foundation/Providers/ArtisanServiceProvider.php
<ide> use Illuminate\Cache\Console\ClearCommand as CacheClearCommand;
<ide> use Illuminate\Cache\Console\ForgetCommand as CacheForgetCommand;
<ide> use Illuminate\Console\Scheduling\ScheduleFinishCommand;
<add>use Illuminate\Console\Scheduling\ScheduleListCommand;
<ide> use Illuminate\Console\Scheduling\ScheduleRunCommand;
<ide> use Illuminate\Console\Scheduling\ScheduleWorkCommand;
<ide> use Illuminate\Contracts\Support\DeferrableProvider;
<ide> class ArtisanServiceProvider extends ServiceProvider implements DeferrableProvid
<ide> 'ScheduleFinish' => ScheduleFinishCommand::class,
<ide> 'ScheduleRun' => ScheduleRunCommand::class,
<ide> 'ScheduleWork' => ScheduleWorkCommand::class,
<add> 'ScheduleList' => ScheduleListCommand::class,
<ide> 'StorageLink' => 'command.storage.link',
<ide> 'Up' => 'command.up',
<ide> 'ViewCache' => 'command.view.cache',
<ide> protected function registerScheduleWorkCommand()
<ide> $this->app->singleton(ScheduleWorkCommand::class);
<ide> }
<ide>
<add> /**
<add> * Register the command.
<add> *
<add> * @return void
<add> */
<add> protected function registerScheduleListCommand()
<add> {
<add> $this->app->singleton(ScheduleListCommand::class);
<add> }
<add>
<ide> /**
<ide> * Register the command.
<ide> * | 1 |
Python | Python | fix style issues in backend/theano_backend.py | 577735597212a111028c2c39db2f621823346ab5 | <ide><path>keras/backend/theano_backend.py
<ide> def placeholder(shape=None, ndim=None, dtype=_FLOATX, sparse=False, name=None):
<ide> '''Instantiate an input data placeholder variable.
<ide> '''
<ide> if shape is None and ndim is None:
<del> raise Exception('Specify either a shape or ndim value.')
<add> raise ValueError('Specify either a shape or ndim value.')
<ide> if shape is not None:
<ide> ndim = len(shape)
<ide> else:
<ide> def batch_dot(x, y, axes=None):
<ide>
<ide> output_shape = (100, 30)
<ide> '''
<del> if type(axes) == int:
<add> if isinstance(axes, int):
<ide> axes = (axes, axes)
<ide> if axes is None:
<ide> # behaves like tf.batch_matmul as default
<ide> def concatenate(tensors, axis=-1):
<ide> elif axis == 1:
<ide> return th_sparse_module.basic.hstack(tensors, format='csr')
<ide> else:
<del> raise Exception('Invalid concat axis for sparse matrix: ' + axis)
<add> raise ValueError('Invalid concat axis for sparse matrix:', axis)
<ide> else:
<ide> return T.concatenate([to_dense(x) for x in tensors], axis=axis)
<ide>
<ide> def resize_images(X, height_factor, width_factor, dim_ordering):
<ide> output = repeat_elements(output, width_factor, axis=2)
<ide> return output
<ide> else:
<del> raise Exception('Invalid dim_ordering: ' + dim_ordering)
<add> raise ValueError('Invalid dim_ordering:', dim_ordering)
<ide>
<ide>
<ide> def resize_volumes(X, depth_factor, height_factor, width_factor, dim_ordering):
<ide> def resize_volumes(X, depth_factor, height_factor, width_factor, dim_ordering):
<ide> output = repeat_elements(output, width_factor, axis=3)
<ide> return output
<ide> else:
<del> raise Exception('Invalid dim_ordering: ' + dim_ordering)
<add> raise ValueError('Invalid dim_ordering:', dim_ordering)
<ide>
<ide>
<ide> def repeat(x, n):
<ide> def spatial_2d_padding(x, padding=(1, 1), dim_ordering='default'):
<ide> slice(padding[1], input_shape[2] + padding[1]),
<ide> slice(None))
<ide> else:
<del> raise Exception('Invalid dim_ordering: ' + dim_ordering)
<add> raise ValueError('Invalid dim_ordering:', dim_ordering)
<ide> return T.set_subtensor(output[indices], x)
<ide>
<ide>
<ide> def asymmetric_spatial_2d_padding(x, top_pad=1, bottom_pad=1,
<ide> slice(left_pad, input_shape[2] + left_pad),
<ide> slice(None))
<ide> else:
<del> raise Exception('Invalid dim_ordering: ' + dim_ordering)
<add> raise ValueError('Invalid dim_ordering:', dim_ordering)
<ide> return T.set_subtensor(output[indices], x)
<ide>
<ide>
<ide> def spatial_3d_padding(x, padding=(1, 1, 1), dim_ordering='default'):
<ide> slice(padding[2], input_shape[3] + padding[2]),
<ide> slice(None))
<ide> else:
<del> raise Exception('Invalid dim_ordering: ' + dim_ordering)
<add> raise ValueError('Invalid dim_ordering:', dim_ordering)
<ide> return T.set_subtensor(output[indices], x)
<ide>
<ide>
<ide> def one_hot(indices, nb_classes):
<ide> def reverse(x, axes):
<ide> '''Reverse a tensor along the the specified axes
<ide> '''
<del> if type(axes) == int:
<add> if isinstance(axes, int):
<ide> axes = [axes]
<ide> slices = [slice(None, None, -1) if i in axes else slice(None, None, None) for i in range(x.ndim)]
<ide> return x[slices]
<ide> def reverse(x, axes):
<ide>
<ide> def get_value(x):
<ide> if not hasattr(x, 'get_value'):
<del> raise Exception("'get_value() can only be called on a variable. " +
<del> "If you have an expression instead, use eval().")
<add> raise TypeError('get_value() can only be called on a variable. '
<add> 'If you have an expression instead, use eval().')
<ide> return x.get_value()
<ide>
<ide>
<ide> def __init__(self, inputs, outputs, updates=[], **kwargs):
<ide> **kwargs)
<ide>
<ide> def __call__(self, inputs):
<del> assert type(inputs) in {list, tuple}
<add> assert isinstance(inputs, (list, tuple))
<ide> return self.function(*inputs)
<ide>
<ide>
<ide> def function(inputs, outputs, updates=[], **kwargs):
<ide> function_args = inspect.getargspec(theano.function)[0]
<ide> for key in kwargs.keys():
<ide> if key not in function_args:
<del> msg = "Invalid argument '%s' passed to K.function" % key
<add> msg = 'Invalid argument "%s" passed to K.function' % key
<ide> raise ValueError(msg)
<ide> return Function(inputs, outputs, updates=updates, **kwargs)
<ide>
<ide> def rnn(step_function, inputs, initial_states,
<ide>
<ide> if unroll:
<ide> if input_length is None:
<del> raise Exception('When specifying `unroll=True`, an `input_length` '
<del> 'must be provided to `rnn`.')
<add> raise ValueError('When specifying `unroll=True`, '
<add> 'an `input_length` '
<add> 'must be provided to `rnn`.')
<ide>
<ide> axes = [1, 0] + list(range(2, ndim))
<ide> inputs = inputs.dimshuffle(axes)
<ide> def _step(input, mask, output_tm1, *states):
<ide> go_backwards=go_backwards)
<ide>
<ide> # deal with Theano API inconsistency
<del> if type(results) is list:
<add> if isinstance(results, list):
<ide> outputs = results[0]
<ide> states = results[1:]
<ide> else:
<ide> def _step(input, *states):
<ide> go_backwards=go_backwards)
<ide>
<ide> # deal with Theano API inconsistency
<del> if type(results) is list:
<add> if isinstance(results, list):
<ide> outputs = results[0]
<ide> states = results[1:]
<ide> else:
<ide> def in_test_phase(x, alt):
<ide> # NN OPERATIONS
<ide>
<ide> def _assert_has_capability(module, func):
<del> assert hasattr(module, func), ('It looks like like your version of '
<del> 'Theano is out of date. '
<del> 'Install the latest version with:\n'
<del> 'pip install git+git://github.com/Theano/Theano.git --upgrade --no-deps')
<add> if not hasattr(module, func):
<add> raise EnvironmentError(
<add> 'It looks like like your version of '
<add> 'Theano is out of date. '
<add> 'Install the latest version with:\n'
<add> 'pip install git+git://github.com/Theano/Theano.git '
<add> '--upgrade --no-deps')
<ide>
<ide>
<ide> def elu(x, alpha=1.0):
<ide> def dropout(x, level, noise_shape=None, seed=None):
<ide> seed: random seed to ensure determinism.
<ide> '''
<ide> if level < 0. or level >= 1:
<del> raise Exception('Dropout level must be in interval [0, 1[.')
<add> raise ValueError('Dropout level must be in interval [0, 1[.')
<ide> if seed is None:
<ide> seed = np.random.randint(1, 10e6)
<ide>
<ide> def _preprocess_border_mode(border_mode):
<ide> elif border_mode == 'full':
<ide> th_border_mode = 'full'
<ide> else:
<del> raise Exception('Border mode not supported: ' + str(border_mode))
<add> raise ValueError('Border mode not supported:', str(border_mode))
<ide> return th_border_mode
<ide>
<ide>
<ide> def conv2d(x, kernel, strides=(1, 1), border_mode='valid',
<ide> if dim_ordering == 'default':
<ide> dim_ordering = image_dim_ordering()
<ide> if dim_ordering not in {'th', 'tf'}:
<del> raise Exception('Unknown dim_ordering ' + str(dim_ordering))
<add> raise ValueError('Unknown dim_ordering ', dim_ordering)
<ide>
<ide> x = _preprocess_conv2d_input(x, dim_ordering)
<ide> kernel = _preprocess_conv2d_kernel(kernel, dim_ordering)
<ide> def deconv2d(x, kernel, output_shape, strides=(1, 1),
<ide> if dim_ordering == 'default':
<ide> dim_ordering = image_dim_ordering()
<ide> if dim_ordering not in {'th', 'tf'}:
<del> raise Exception('Unknown dim_ordering ' + str(dim_ordering))
<add> raise ValueError('Unknown dim_ordering ' + dim_ordering)
<ide>
<ide> x = _preprocess_conv2d_input(x, dim_ordering)
<ide> kernel = _preprocess_conv2d_kernel(kernel, dim_ordering)
<ide> def conv3d(x, kernel, strides=(1, 1, 1),
<ide> if dim_ordering == 'default':
<ide> dim_ordering = image_dim_ordering()
<ide> if dim_ordering not in {'th', 'tf'}:
<del> raise Exception('Unknown dim_ordering ' + str(dim_ordering))
<add> raise ValueError('Unknown dim_ordering:', dim_ordering)
<ide>
<ide> # TODO: remove this if statement when Theano without AbstractConv3d is deprecated
<ide> if not hasattr(T.nnet, 'conv3d'):
<ide> if filter_dilation != (1, 1, 1):
<del> raise Exception('conv3d with filter dilation requires Theano '
<del> '0.9.0dev3 or newer.')
<add> raise ValueError('conv3d with filter dilation requires Theano '
<add> '0.9.0dev3 or newer.')
<ide>
<ide> return _old_theano_conv3d(x, kernel, strides, border_mode,
<ide> dim_ordering, volume_shape, filter_shape)
<ide> def _old_theano_conv3d(x, kernel, strides=(1, 1, 1),
<ide> if dim_ordering == 'default':
<ide> dim_ordering = image_dim_ordering()
<ide> if dim_ordering not in {'th', 'tf'}:
<del> raise Exception('Unknown dim_ordering ' + str(dim_ordering))
<del>
<add> raise ValueError('Unknown dim_ordering:', dim_ordering)
<ide> if border_mode not in {'same', 'valid'}:
<del> raise Exception('Invalid border mode: ' + str(border_mode))
<add> raise ValueError('Invalid border mode:', border_mode)
<ide>
<ide> if dim_ordering == 'tf':
<ide> # TF uses the last dimension as channel dimension,
<ide> def pool2d(x, pool_size, strides=(1, 1), border_mode='valid',
<ide> if dim_ordering == 'default':
<ide> dim_ordering = image_dim_ordering()
<ide> if dim_ordering not in {'th', 'tf'}:
<del> raise Exception('Unknown dim_ordering ' + str(dim_ordering))
<add> raise ValueError('Unknown dim_ordering:', dim_ordering)
<ide>
<ide> assert pool_size[0] >= 1 and pool_size[1] >= 1
<ide>
<ide> def pool2d(x, pool_size, strides=(1, 1), border_mode='valid',
<ide> elif border_mode == 'valid':
<ide> padding = (0, 0)
<ide> else:
<del> raise Exception('Invalid border mode: ' + str(border_mode))
<add> raise ValueError('Invalid border mode:', border_mode)
<ide>
<ide> if dim_ordering not in {'th', 'tf'}:
<del> raise Exception('Unknown dim_ordering ' + str(dim_ordering))
<add> raise ValueError('Unknown dim_ordering:', dim_ordering)
<ide>
<ide> if dim_ordering == 'tf':
<ide> x = x.dimshuffle((0, 3, 1, 2))
<ide> def pool2d(x, pool_size, strides=(1, 1), border_mode='valid',
<ide> padding=padding,
<ide> mode='average_exc_pad')
<ide> else:
<del> raise Exception('Invalid pooling mode: ' + str(pool_mode))
<add> raise ValueError('Invalid pooling mode:', pool_mode)
<ide>
<ide> if border_mode == 'same':
<ide> expected_width = (x.shape[2] + strides[0] - 1) // strides[0]
<ide> def pool3d(x, pool_size, strides=(1, 1, 1), border_mode='valid',
<ide> if dim_ordering == 'default':
<ide> dim_ordering = image_dim_ordering()
<ide> if dim_ordering not in {'th', 'tf'}:
<del> raise Exception('Unknown dim_ordering ' + str(dim_ordering))
<add> raise ValueError('Unknown dim_ordering:', dim_ordering)
<ide>
<ide> # TODO: remove this if statement when Theano without pool_3d is deprecated
<ide> # (pool_3d was introduced after 0.9.0dev3)
<ide> def pool3d(x, pool_size, strides=(1, 1, 1), border_mode='valid',
<ide> elif border_mode == 'valid':
<ide> padding = (0, 0, 0)
<ide> else:
<del> raise Exception('Invalid border mode: ' + str(border_mode))
<del>
<add> raise ValueError('Invalid border mode:', border_mode)
<ide> if dim_ordering not in {'th', 'tf'}:
<del> raise Exception('Unknown dim_ordering ' + str(dim_ordering))
<add> raise ValueError('Unknown dim_ordering:', dim_ordering)
<ide>
<ide> if dim_ordering == 'tf':
<ide> x = x.dimshuffle((0, 4, 1, 2, 3))
<ide> def pool3d(x, pool_size, strides=(1, 1, 1), border_mode='valid',
<ide> padding=padding,
<ide> mode='average_exc_pad')
<ide> else:
<del> raise Exception('Invalid pooling mode: ' + str(pool_mode))
<add> raise ValueError('Invalid pooling mode:', pool_mode)
<ide>
<ide> if border_mode == 'same':
<ide> expected_width = (x.shape[2] + strides[0] - 1) // strides[0]
<ide> def _old_theano_pool3d(x, pool_size, strides=(1, 1, 1), border_mode='valid',
<ide> if dim_ordering == 'default':
<ide> dim_ordering = image_dim_ordering()
<ide> if dim_ordering not in {'th', 'tf'}:
<del> raise Exception('Unknown dim_ordering ' + str(dim_ordering))
<add> raise ValueError('Unknown dim_ordering:', dim_ordering)
<ide>
<ide> if border_mode == 'same':
<ide> # TODO: add implementation for border_mode="same"
<del> raise Exception('border_mode="same" not supported with Theano.')
<add> raise ValueError('border_mode="same" not supported with Theano.')
<ide> elif border_mode == 'valid':
<ide> ignore_border = True
<ide> padding = (0, 0)
<ide> else:
<del> raise Exception('Invalid border mode: ' + str(border_mode))
<add> raise ValueError('Invalid border mode:', border_mode)
<ide>
<ide> if dim_ordering not in {'th', 'tf'}:
<del> raise Exception('Unknown dim_ordering ' + str(dim_ordering))
<add> raise ValueError('Unknown dim_ordering:', dim_ordering)
<ide>
<ide> if dim_ordering == 'tf':
<ide> x = x.dimshuffle((0, 4, 1, 2, 3))
<ide> def _old_theano_pool3d(x, pool_size, strides=(1, 1, 1), border_mode='valid',
<ide> padding=padding,
<ide> mode='average_exc_pad')
<ide> else:
<del> raise Exception('Invalid pooling mode: ' + str(pool_mode))
<add> raise ValueError('Invalid pooling mode:', pool_mode)
<ide>
<ide> if dim_ordering == 'tf':
<ide> pool_out = pool_out.dimshuffle((0, 2, 3, 4, 1)) | 1 |
Mixed | Ruby | remove implicit coercion deprecation of durations | a91ea1d51048342d13fc73f9b09ce4cfd086bb34 | <ide><path>activesupport/CHANGELOG.md
<add>* Remove implicit coercion deprecation of durations
<add>
<add> In #28204 we deprecated implicit conversion of durations to a numeric which
<add> represented the number of seconds in the duration because of unwanted side
<add> effects with calculations on durations and dates. This unfortunately had
<add> the side effect of forcing a explicit cast when configuring third-party
<add> libraries like expiration in Redis, e.g:
<add>
<add> redis.expire("foo", 5.minutes)
<add>
<add> To work around this we've removed the deprecation and added a private class
<add> that wraps the numeric and can perform calculation involving durations and
<add> ensure that they remain a duration irrespective of the order of operations.
<add>
<add> *Andrew White*
<add>
<ide> * Update `titleize` regex to allow apostrophes
<ide>
<ide> In 4b685aa the regex in `titleize` was updated to not match apostrophes to
<ide><path>activesupport/lib/active_support/duration.rb
<ide> require "active_support/core_ext/array/conversions"
<add>require "active_support/core_ext/module/delegation"
<ide> require "active_support/core_ext/object/acts_like"
<ide> require "active_support/core_ext/string/filters"
<ide> require "active_support/deprecation"
<ide> module ActiveSupport
<ide> #
<ide> # 1.month.ago # equivalent to Time.now.advance(months: -1)
<ide> class Duration
<add> class Scalar < Numeric #:nodoc:
<add> attr_reader :value
<add> delegate :to_i, :to_f, :to_s, to: :value
<add>
<add> def initialize(value)
<add> @value = value
<add> end
<add>
<add> def coerce(other)
<add> [Scalar.new(other), self]
<add> end
<add>
<add> def -@
<add> Scalar.new(-value)
<add> end
<add>
<add> def <=>(other)
<add> if Scalar === other || Duration === other
<add> value <=> other.value
<add> elsif Numeric === other
<add> value <=> other
<add> else
<add> nil
<add> end
<add> end
<add>
<add> def +(other)
<add> calculate(:+, other)
<add> end
<add>
<add> def -(other)
<add> calculate(:-, other)
<add> end
<add>
<add> def *(other)
<add> calculate(:*, other)
<add> end
<add>
<add> def /(other)
<add> calculate(:/, other)
<add> end
<add>
<add> private
<add> def calculate(op, other)
<add> if Scalar === other
<add> Scalar.new(value.public_send(op, other.value))
<add> elsif Duration === other
<add> Duration.seconds(value).public_send(op, other)
<add> elsif Numeric === other
<add> Scalar.new(value.public_send(op, other))
<add> else
<add> raise_type_error(other)
<add> end
<add> end
<add>
<add> def raise_type_error(other)
<add> raise TypeError, "no implicit conversion of #{other.class} into #{self.class}"
<add> end
<add> end
<add>
<ide> SECONDS_PER_MINUTE = 60
<ide> SECONDS_PER_HOUR = 3600
<ide> SECONDS_PER_DAY = 86400
<ide> def initialize(value, parts) #:nodoc:
<ide> end
<ide>
<ide> def coerce(other) #:nodoc:
<del> ActiveSupport::Deprecation.warn(<<-MSG.squish)
<del> Implicit coercion of ActiveSupport::Duration to a Numeric
<del> is deprecated and will raise a TypeError in Rails 5.2.
<del> MSG
<del>
<del> [other, value]
<add> if Scalar === other
<add> [other, self]
<add> else
<add> [Scalar.new(other), self]
<add> end
<ide> end
<ide>
<ide> # Compares one Duration with another or a Numeric to this Duration.
<ide> def -(other)
<ide>
<ide> # Multiplies this Duration by a Numeric and returns a new Duration.
<ide> def *(other)
<del> if Numeric === other
<add> if Scalar === other || Duration === other
<add> Duration.new(value * other.value, parts.map { |type, number| [type, number * other.value] })
<add> elsif Numeric === other
<ide> Duration.new(value * other, parts.map { |type, number| [type, number * other] })
<ide> else
<del> value * other
<add> raise_type_error(other)
<ide> end
<ide> end
<ide>
<ide> # Divides this Duration by a Numeric and returns a new Duration.
<ide> def /(other)
<del> if Numeric === other
<add> if Scalar === other || Duration === other
<add> Duration.new(value / other.value, parts.map { |type, number| [type, number / other.value] })
<add> elsif Numeric === other
<ide> Duration.new(value / other, parts.map { |type, number| [type, number / other] })
<ide> else
<del> value / other
<add> raise_type_error(other)
<ide> end
<ide> end
<ide>
<ide> def sum(sign, time = ::Time.current)
<ide> def method_missing(method, *args, &block)
<ide> value.send(method, *args, &block)
<ide> end
<add>
<add> def raise_type_error(other)
<add> raise TypeError, "no implicit conversion of #{other.class} into #{self.class}"
<add> end
<ide> end
<ide> end
<ide><path>activesupport/test/core_ext/duration_test.rb
<ide> def test_minus
<ide> assert_instance_of ActiveSupport::Duration, 2.seconds - 1.second
<ide> assert_equal 1.second, 2.seconds - 1
<ide> assert_instance_of ActiveSupport::Duration, 2.seconds - 1
<add> assert_equal 1.second, 2 - 1.second
<add> assert_instance_of ActiveSupport::Duration, 2.seconds - 1
<ide> end
<ide>
<ide> def test_multiply
<ide> assert_equal 7.days, 1.day * 7
<ide> assert_instance_of ActiveSupport::Duration, 1.day * 7
<del>
<del> assert_deprecated do
<del> assert_equal 86400, 1.day * 1.second
<del> end
<add> assert_equal 86400, 1.day * 1.second
<ide> end
<ide>
<ide> def test_divide
<ide> assert_equal 1.day, 7.days / 7
<ide> assert_instance_of ActiveSupport::Duration, 7.days / 7
<del>
<del> assert_deprecated do
<del> assert_equal 1, 1.day / 1.day
<del> end
<add> assert_equal 1, 1.day / 1.day
<ide> end
<ide>
<ide> def test_date_added_with_multiplied_duration
<ide> assert_equal Date.civil(2017, 1, 3), Date.civil(2017, 1, 1) + 1.day * 2
<ide> end
<ide>
<ide> def test_plus_with_time
<del> assert_deprecated do
<del> assert_equal 1 + 1.second, 1.second + 1, "Duration + Numeric should == Numeric + Duration"
<del> end
<add> assert_equal 1 + 1.second, 1.second + 1, "Duration + Numeric should == Numeric + Duration"
<ide> end
<ide>
<ide> def test_time_plus_duration_returns_same_time_datatype
<ide> def test_argument_error
<ide> assert_equal 'expected a time or date, got ""', e.message, "ensure ArgumentError is not being raised by dependencies.rb"
<ide> end
<ide>
<del> def test_implicit_coercion_is_deprecated
<del> assert_deprecated { 1 + 1.second }
<del> assert_deprecated { 1 - 1.second }
<del> assert_deprecated { 1 * 1.second }
<del> assert_deprecated { 1 / 1.second }
<del> end
<del>
<ide> def test_fractional_weeks
<ide> assert_equal((86400 * 7) * 1.5, 1.5.weeks)
<ide> assert_equal((86400 * 7) * 1.7, 1.7.weeks)
<ide> def test_hash
<ide> def test_comparable
<ide> assert_equal(-1, (0.seconds <=> 1.second))
<ide> assert_equal(-1, (1.second <=> 1.minute))
<del>
<del> assert_deprecated do
<del> assert_equal(-1, (1 <=> 1.minute))
<del> end
<del>
<add> assert_equal(-1, (1 <=> 1.minute))
<ide> assert_equal(0, (0.seconds <=> 0.seconds))
<ide> assert_equal(0, (0.seconds <=> 0.minutes))
<ide> assert_equal(0, (1.second <=> 1.second))
<ide> assert_equal(1, (1.second <=> 0.second))
<ide> assert_equal(1, (1.minute <=> 1.second))
<add> assert_equal(1, (61 <=> 1.minute))
<add> end
<ide>
<del> assert_deprecated do
<del> assert_equal(1, (61 <=> 1.minute))
<add> def test_implicit_coercion
<add> assert_equal 2.days, 2 * 1.day
<add> assert_instance_of ActiveSupport::Duration, 2 * 1.day
<add> assert_equal Time.utc(2017, 1, 3), Time.utc(2017, 1, 1) + 2 * 1.day
<add> assert_equal Date.civil(2017, 1, 3), Date.civil(2017, 1, 1) + 2 * 1.day
<add> end
<add>
<add> def test_scalar_coerce
<add> scalar = ActiveSupport::Duration::Scalar.new(10)
<add> assert_instance_of ActiveSupport::Duration::Scalar, 10 + scalar
<add> assert_instance_of ActiveSupport::Duration, 10.seconds + scalar
<add> end
<add>
<add> def test_scalar_delegations
<add> scalar = ActiveSupport::Duration::Scalar.new(10)
<add> assert_kind_of Float, scalar.to_f
<add> assert_kind_of Integer, scalar.to_i
<add> assert_kind_of String, scalar.to_s
<add> end
<add>
<add> def test_scalar_unary_minus
<add> scalar = ActiveSupport::Duration::Scalar.new(10)
<add>
<add> assert_equal -10, -scalar
<add> assert_instance_of ActiveSupport::Duration::Scalar, -scalar
<add> end
<add>
<add> def test_scalar_compare
<add> scalar = ActiveSupport::Duration::Scalar.new(10)
<add>
<add> assert_equal 1, scalar <=> 5
<add> assert_equal 0, scalar <=> 10
<add> assert_equal -1, scalar <=> 15
<add> assert_equal nil, scalar <=> "foo"
<add> end
<add>
<add> def test_scalar_plus
<add> scalar = ActiveSupport::Duration::Scalar.new(10)
<add>
<add> assert_equal 20, 10 + scalar
<add> assert_instance_of ActiveSupport::Duration::Scalar, 10 + scalar
<add> assert_equal 20, scalar + 10
<add> assert_instance_of ActiveSupport::Duration::Scalar, scalar + 10
<add> assert_equal 20, 10.seconds + scalar
<add> assert_instance_of ActiveSupport::Duration, 10.seconds + scalar
<add> assert_equal 20, scalar + 10.seconds
<add> assert_instance_of ActiveSupport::Duration, scalar + 10.seconds
<add>
<add> exception = assert_raises(TypeError) do
<add> scalar + "foo"
<add> end
<add>
<add> assert_equal "no implicit conversion of String into ActiveSupport::Duration::Scalar", exception.message
<add> end
<add>
<add> def test_scalar_minus
<add> scalar = ActiveSupport::Duration::Scalar.new(10)
<add>
<add> assert_equal 10, 20 - scalar
<add> assert_instance_of ActiveSupport::Duration::Scalar, 20 - scalar
<add> assert_equal 5, scalar - 5
<add> assert_instance_of ActiveSupport::Duration::Scalar, scalar - 5
<add> assert_equal 10, 20.seconds - scalar
<add> assert_instance_of ActiveSupport::Duration, 20.seconds - scalar
<add> assert_equal 5, scalar - 5.seconds
<add> assert_instance_of ActiveSupport::Duration, scalar - 5.seconds
<add>
<add> exception = assert_raises(TypeError) do
<add> scalar - "foo"
<add> end
<add>
<add> assert_equal "no implicit conversion of String into ActiveSupport::Duration::Scalar", exception.message
<add> end
<add>
<add> def test_scalar_multiply
<add> scalar = ActiveSupport::Duration::Scalar.new(5)
<add>
<add> assert_equal 10, 2 * scalar
<add> assert_instance_of ActiveSupport::Duration::Scalar, 2 * scalar
<add> assert_equal 10, scalar * 2
<add> assert_instance_of ActiveSupport::Duration::Scalar, scalar * 2
<add> assert_equal 10, 2.seconds * scalar
<add> assert_instance_of ActiveSupport::Duration, 2.seconds * scalar
<add> assert_equal 10, scalar * 2.seconds
<add> assert_instance_of ActiveSupport::Duration, scalar * 2.seconds
<add>
<add> exception = assert_raises(TypeError) do
<add> scalar * "foo"
<ide> end
<add>
<add> assert_equal "no implicit conversion of String into ActiveSupport::Duration::Scalar", exception.message
<add> end
<add>
<add> def test_scalar_divide
<add> scalar = ActiveSupport::Duration::Scalar.new(10)
<add>
<add> assert_equal 10, 100 / scalar
<add> assert_instance_of ActiveSupport::Duration::Scalar, 100 / scalar
<add> assert_equal 5, scalar / 2
<add> assert_instance_of ActiveSupport::Duration::Scalar, scalar / 2
<add> assert_equal 10, 100.seconds / scalar
<add> assert_instance_of ActiveSupport::Duration, 2.seconds * scalar
<add> assert_equal 5, scalar / 2.seconds
<add> assert_instance_of ActiveSupport::Duration, scalar / 2.seconds
<add>
<add> exception = assert_raises(TypeError) do
<add> scalar / "foo"
<add> end
<add>
<add> assert_equal "no implicit conversion of String into ActiveSupport::Duration::Scalar", exception.message
<ide> end
<ide>
<ide> def test_twelve_months_equals_one_year | 3 |
Python | Python | fix infixes in french | 3d4bd96e8a36814132e99874c9b461f0639f2fd5 | <ide><path>spacy/fr/language_data.py
<ide> '''.strip().split('\n')
<ide>
<ide>
<del>TOKENIZER_INFIXES = tuple()
<add>TOKENIZER_INFIXES = (r'''\.\.\.+ (?<=[a-z])\.(?=[A-Z]) (?<=[a-zA-Z])-(?=[a-zA-z]) '''
<add> r'''(?<=[a-zA-Z])--(?=[a-zA-z]) (?<=[0-9])-(?=[0-9]) '''
<add> r'''(?<=[A-Za-z]),(?=[A-Za-z])''').split()
<add>
<ide>
<ide>
<ide> TOKENIZER_EXCEPTIONS = { | 1 |
Mixed | Go | allow duration strings as --since/--until | 4e3b21f99e7fb7fac0075be2e7190d5f07c9ee66 | <ide><path>api/client/events.go
<ide> package client
<ide>
<ide> import (
<ide> "net/url"
<add> "time"
<ide>
<ide> "github.com/docker/docker/opts"
<ide> flag "github.com/docker/docker/pkg/mflag"
<ide> func (cli *DockerCli) CmdEvents(args ...string) error {
<ide> return err
<ide> }
<ide> }
<add> ref := time.Now()
<ide> if *since != "" {
<del> v.Set("since", timeutils.GetTimestamp(*since))
<add> v.Set("since", timeutils.GetTimestamp(*since, ref))
<ide> }
<ide> if *until != "" {
<del> v.Set("until", timeutils.GetTimestamp(*until))
<add> v.Set("until", timeutils.GetTimestamp(*until, ref))
<ide> }
<ide> if len(eventFilterArgs) > 0 {
<ide> filterJSON, err := filters.ToParam(eventFilterArgs)
<ide><path>api/client/logs.go
<ide> import (
<ide> "encoding/json"
<ide> "fmt"
<ide> "net/url"
<add> "time"
<ide>
<ide> "github.com/docker/docker/api/types"
<ide> flag "github.com/docker/docker/pkg/mflag"
<ide> func (cli *DockerCli) CmdLogs(args ...string) error {
<ide> v.Set("stderr", "1")
<ide>
<ide> if *since != "" {
<del> v.Set("since", timeutils.GetTimestamp(*since))
<add> v.Set("since", timeutils.GetTimestamp(*since, time.Now()))
<ide> }
<ide>
<ide> if *times {
<ide><path>docs/man/docker-events.1.md
<ide> and Docker images will report:
<ide> **--until**=""
<ide> Stream events until this timestamp
<ide>
<add>You can specify `--since` and `--until` parameters as an RFC 3339 date,
<add>a UNIX timestamp, or a Go duration string (e.g. `1m30s`, `3h`). Docker computes
<add>the date relative to the client machine’s time.
<add>
<ide> # EXAMPLES
<ide>
<ide> ## Listening for Docker events
<ide> Again the output container IDs have been shortened for the purposes of this docu
<ide> 2015-01-28T20:25:45.000000000-08:00 c21f6c22ba27: (from whenry/testimage:latest) die
<ide> 2015-01-28T20:25:46.000000000-08:00 c21f6c22ba27: (from whenry/testimage:latest) stop
<ide>
<add>The following example outputs all events that were generated in the last 3 minutes,
<add>relative to the current time on the client machine:
<add>
<add> # docker events --since '3m'
<add> 2015-05-12T11:51:30.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) die
<add> 2015-05-12T15:52:12.999999999Z07:00 4 4386fb97867d: (from ubuntu-1:14.04) stop
<add> 2015-05-12T15:53:45.999999999Z07:00 7805c1d35632: (from redis:2.8) die
<add> 2015-05-12T15:54:03.999999999Z07:00 7805c1d35632: (from redis:2.8) stop
<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.
<ide><path>docs/man/docker-logs.1.md
<ide> then continue streaming new output from the container’s stdout and stderr.
<ide> **--tail**="all"
<ide> Output the specified number of lines at the end of logs (defaults to all logs)
<ide>
<add>The `--since` option shows only the container logs generated after
<add>a given date. You can specify the date as an RFC 3339 date, a UNIX
<add>timestamp, or a Go duration string (e.g. `1m30s`, `3h`). Docker computes
<add>the date relative to the client machine’s time. You can combine
<add>the `--since` option with either or both of the `--follow` or `--tail` options.
<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.
<ide><path>docs/sources/reference/commandline/cli.md
<ide> and Docker images will report:
<ide>
<ide> untag, delete
<ide>
<add>The `--since` and `--until` parameters can be Unix timestamps, RFC3339
<add>dates or Go duration strings (e.g. `10m`, `1h30m`) computed relative to
<add>client machine’s time.
<add>
<ide> #### Filtering
<ide>
<ide> The filtering flag (`-f` or `--filter`) format is of "key=value". If you would like to use
<ide> You'll need two shells for this example.
<ide> 2014-05-10T17:42:14.999999999Z07:00 7805c1d35632: (from redis:2.8) die
<ide> 2014-09-03T15:49:29.999999999Z07:00 7805c1d35632: (from redis:2.8) stop
<ide>
<add>This example outputs all events that were generated in the last 3 minutes,
<add>relative to the current time on the client machine:
<add>
<add> $ docker events --since '3m'
<add> 2015-05-12T11:51:30.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) die
<add> 2015-05-12T15:52:12.999999999Z07:00 4 4386fb97867d: (from ubuntu-1:14.04) stop
<add> 2015-05-12T15:53:45.999999999Z07:00 7805c1d35632: (from redis:2.8) die
<add> 2015-05-12T15:54:03.999999999Z07:00 7805c1d35632: (from redis:2.8) stop
<add>
<ide> **Filter events:**
<ide>
<ide> $ docker events --filter 'event=stop'
<ide> timestamp, for example `2014-09-16T06:17:46.000000000Z`, to each
<ide> log entry. To ensure that the timestamps for are aligned the
<ide> nano-second part of the timestamp will be padded with zero when necessary.
<ide>
<del>The `--since` option shows logs of a container generated only after
<del>the given date, specified as RFC 3339 or UNIX timestamp. The `--since` option
<del>can be combined with the `--follow` and `--tail` options.
<add>The `--since` option shows only the container logs generated after
<add>a given date. You can specify the date as an RFC 3339 date, a UNIX
<add>timestamp, or a Go duration string (e.g. `1m30s`, `3h`). Docker computes
<add>the date relative to the client machine’s time. You can combine
<add>the `--since` option with either or both of the `--follow` or `--tail` options.
<ide>
<ide> ## pause
<ide>
<ide><path>integration-cli/docker_cli_events_test.go
<ide> func (s *DockerSuite) TestEventsTimestampFormats(c *check.C) {
<ide> // List of available time formats to --since
<ide> unixTs := func(t time.Time) string { return fmt.Sprintf("%v", t.Unix()) }
<ide> rfc3339 := func(t time.Time) string { return t.Format(time.RFC3339) }
<add> duration := func(t time.Time) string { return time.Now().Sub(t).String() }
<ide>
<ide> // --since=$start must contain only the 'untag' event
<del> for _, f := range []func(time.Time) string{unixTs, rfc3339} {
<add> for _, f := range []func(time.Time) string{unixTs, rfc3339, duration} {
<ide> since, until := f(start), f(end)
<ide> cmd := exec.Command(dockerBinary, "events", "--since="+since, "--until="+until)
<ide> out, _, err := runCommandWithOutput(cmd)
<ide><path>pkg/timeutils/utils.go
<ide> import (
<ide> "time"
<ide> )
<ide>
<del>// GetTimestamp tries to parse given string as RFC3339 time
<del>// or Unix timestamp (with seconds precision), if successful
<del>//returns a Unix timestamp as string otherwise returns value back.
<del>func GetTimestamp(value string) string {
<add>// GetTimestamp tries to parse given string as golang duration,
<add>// then RFC3339 time and finally as a Unix timestamp. If
<add>// any of these were successful, it returns a Unix timestamp
<add>// as string otherwise returns the given value back.
<add>// In case of duration input, the returned timestamp is computed
<add>// as the given reference time minus the amount of the duration.
<add>func GetTimestamp(value string, reference time.Time) string {
<add> if d, err := time.ParseDuration(value); value != "0" && err == nil {
<add> return strconv.FormatInt(reference.Add(-d).Unix(), 10)
<add> }
<add>
<ide> var format string
<ide> if strings.Contains(value, ".") {
<ide> format = time.RFC3339Nano
<ide><path>pkg/timeutils/utils_test.go
<ide> package timeutils
<ide>
<ide> import (
<add> "fmt"
<ide> "testing"
<add> "time"
<ide> )
<ide>
<ide> func TestGetTimestamp(t *testing.T) {
<add> now := time.Now()
<ide> cases := []struct{ in, expected string }{
<ide> {"0", "-62167305600"}, // 0 gets parsed year 0
<ide>
<ide> func TestGetTimestamp(t *testing.T) {
<ide> // unix timestamps returned as is
<ide> {"1136073600", "1136073600"},
<ide>
<add> // Durations
<add> {"1m", fmt.Sprintf("%d", now.Add(-1*time.Minute).Unix())},
<add> {"1.5h", fmt.Sprintf("%d", now.Add(-90*time.Minute).Unix())},
<add> {"1h30m", fmt.Sprintf("%d", now.Add(-90*time.Minute).Unix())},
<add>
<ide> // String fallback
<ide> {"invalid", "invalid"},
<ide> }
<ide>
<ide> for _, c := range cases {
<del> o := GetTimestamp(c.in)
<add> o := GetTimestamp(c.in, now)
<ide> if o != c.expected {
<ide> t.Fatalf("wrong value for '%s'. expected:'%s' got:'%s'", c.in, c.expected, o)
<ide> } | 8 |
Python | Python | fix integration tests | ebe3f30f1122a97d4d88855ab5a73618332d81b2 | <ide><path>keras/backend/tensorflow_backend.py
<ide> def control_dependencies(control_inputs):
<ide> """A context manager that specifies control dependencies.
<ide>
<ide> # Arguments
<del> control_inputs: A list of Operation or Tensor objects which must be executed
<del> or computed before running the operations defined in the context. Can also
<del> be None to clear the control dependencies.
<add> control_inputs: A list of Operation or Tensor objects
<add> which must be executed
<add> or computed before running the operations defined in the context.
<add> Can also be None to clear the control dependencies.
<ide>
<ide> # Returns
<ide> A context manager.
<ide><path>tests/integration_tests/test_image_data_tasks.py
<ide> def test_image_classification():
<ide> history = model.fit(x_train, y_train, epochs=10, batch_size=16,
<ide> validation_data=(x_test, y_test),
<ide> verbose=0)
<del> assert history.history['val_acc'][-1] > 0.75
<add> assert history.history['val_accuracy'][-1] > 0.75
<ide> config = model.get_config()
<ide> model = Sequential.from_config(config)
<ide>
<ide> def test_image_data_generator_training():
<ide> validation_data=img_gen.flow(x_test, y_test,
<ide> batch_size=16),
<ide> verbose=0)
<del> assert history.history['val_acc'][-1] > 0.75
<add> assert history.history['val_accuracy'][-1] > 0.75
<ide> model.evaluate_generator(img_gen.flow(x_train, y_train, batch_size=16))
<ide>
<ide>
<ide><path>tests/integration_tests/test_temporal_data_tasks.py
<ide> def test_temporal_classification():
<ide> history = model.fit(x_train, y_train, epochs=4, batch_size=10,
<ide> validation_data=(x_test, y_test),
<ide> verbose=0)
<del> assert(history.history['acc'][-1] >= 0.8)
<add> assert(history.history['accuracy'][-1] >= 0.8)
<ide> config = model.get_config()
<ide> model = Sequential.from_config(config)
<ide>
<ide> def test_temporal_classification_functional():
<ide> history = model.fit(x_train, y_train, epochs=4, batch_size=10,
<ide> validation_data=(x_test, y_test),
<ide> verbose=0)
<del> assert(history.history['acc'][-1] >= 0.8)
<add> assert(history.history['accuracy'][-1] >= 0.8)
<ide>
<ide>
<ide> def test_temporal_regression():
<ide><path>tests/integration_tests/test_tensorflow_integration.py
<ide> def test_tf_optimizer():
<ide> metrics=['accuracy'])
<ide> history = model.fit(x_train, y_train, epochs=8, batch_size=16,
<ide> validation_data=(x_test, y_test), verbose=2)
<del> assert history.history['val_acc'][-1] >= target
<add> assert history.history['val_accuracy'][-1] >= target
<ide>
<ide> # Test saving.
<ide> _, fname = tempfile.mkstemp('.h5')
<ide><path>tests/integration_tests/test_vector_data_tasks.py
<ide> def test_vector_classification():
<ide> history = model.fit(x_train, y_train, epochs=15, batch_size=16,
<ide> validation_data=(x_test, y_test),
<ide> verbose=0)
<del> assert(history.history['val_acc'][-1] > 0.8)
<add> assert(history.history['val_accuracy'][-1] > 0.8)
<ide> config = model.get_config()
<ide> model = Sequential.from_config(config)
<ide>
<ide> def test_vector_classification_functional():
<ide> model = keras.models.Model(inputs, outputs)
<ide> model.compile(loss=keras.losses.sparse_categorical_crossentropy,
<ide> optimizer=keras.optimizers.Adam(1e-3),
<del> metrics=['acc'])
<add> metrics=['accuracy'])
<ide> history = model.fit(x_train, y_train, epochs=15, batch_size=16,
<ide> validation_data=(x_train, y_train),
<ide> verbose=0)
<del> assert(history.history['val_acc'][-1] > 0.8)
<add> assert(history.history['val_accuracy'][-1] > 0.8)
<ide>
<ide>
<ide> def test_vector_regression(): | 5 |
Go | Go | fix seccomp output in `docker info` | a3b9dd89a1b19e7f84617b91f3756ae816c11035 | <ide><path>daemon/info.go
<ide> func (daemon *Daemon) SystemInfo() (*types.Info, error) {
<ide> if sysInfo.AppArmor {
<ide> securityOptions = append(securityOptions, "apparmor")
<ide> }
<del> if sysInfo.Seccomp {
<add> if sysInfo.Seccomp && supportsSeccomp {
<ide> securityOptions = append(securityOptions, "seccomp")
<ide> }
<ide> if selinuxEnabled() {
<ide><path>daemon/seccomp_disabled.go
<del>// +build !seccomp,!windows
<add>// +build linux,!seccomp
<ide>
<ide> package daemon
<ide>
<ide> import (
<ide> "github.com/opencontainers/specs/specs-go"
<ide> )
<ide>
<add>var supportsSeccomp = false
<add>
<ide> func setSeccomp(daemon *Daemon, rs *specs.Spec, c *container.Container) error {
<ide> if c.SeccompProfile != "" && c.SeccompProfile != "unconfined" {
<ide> return fmt.Errorf("seccomp profiles are not supported on this daemon, you cannot specify a custom seccomp profile")
<ide><path>daemon/seccomp_linux.go
<ide> import (
<ide> "github.com/opencontainers/specs/specs-go"
<ide> )
<ide>
<add>var supportsSeccomp = true
<add>
<ide> func setSeccomp(daemon *Daemon, rs *specs.Spec, c *container.Container) error {
<ide> var profile *specs.Seccomp
<ide> var err error
<ide><path>daemon/seccomp_unsupported.go
<add>// +build !linux
<add>
<add>package daemon
<add>
<add>var supportsSeccomp = false | 4 |
Text | Text | update readme to make node.js description clearer | 6d443083e8b2057cca0b52e58cd332fc030aa87a | <ide><path>README.md
<ide> </a>
<ide> </p>
<ide>
<del>Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. For
<del>more information on using Node.js, see the [Node.js Website][].
<add>Node.js is an open-source, cross-platform, JavaScript runtime environment. It
<add>executes JavaScript code outside of a browser. For more information on using
<add>Node.js, see the [Node.js Website][].
<ide>
<ide> The Node.js project uses an [open governance model](./GOVERNANCE.md). The
<ide> [OpenJS Foundation][] provides support for the project. | 1 |
Javascript | Javascript | remove unused assignment | 7f25fe8b67eeb05a44b107378a2f3e59e4d8f2f9 | <ide><path>lib/fs.js
<ide> function rmdirSync(path, options) {
<ide> return rimrafSync(pathModule.toNamespacedPath(path), options);
<ide> }
<ide>
<del> options = validateRmdirOptions(options);
<add> validateRmdirOptions(options);
<ide> const ctx = { path };
<ide> binding.rmdir(pathModule.toNamespacedPath(path), undefined, ctx);
<ide> return handleErrorFromBinding(ctx); | 1 |
Ruby | Ruby | encourage users to user super to override methods | 8f7d9eb043dbbca9e4b424c77e643312a9927eac | <ide><path>activerecord/lib/active_record/base.rb
<ide> module ActiveRecord #:nodoc:
<ide> # All column values are automatically available through basic accessors on the Active Record
<ide> # object, but sometimes you want to specialize this behavior. This can be done by overwriting
<ide> # the default accessors (using the same name as the attribute) and calling
<del> # <tt>read_attribute(attr_name)</tt> and <tt>write_attribute(attr_name, value)</tt> to actually
<del> # change things.
<add> # super to actually change things.
<ide> #
<ide> # class Song < ActiveRecord::Base
<ide> # # Uses an integer of seconds to hold the length of the song
<ide> #
<ide> # def length=(minutes)
<del> # write_attribute(:length, minutes.to_i * 60)
<add> # super(minutes.to_i * 60)
<ide> # end
<ide> #
<ide> # def length
<del> # read_attribute(:length) / 60
<add> # super / 60
<ide> # end
<ide> # end
<ide> #
<ide> # You can alternatively use <tt>self[:attribute]=(value)</tt> and <tt>self[:attribute]</tt>
<del> # instead of <tt>write_attribute(:attribute, value)</tt> and <tt>read_attribute(:attribute)</tt>.
<add> # or <tt>write_attribute(:attribute, value)</tt> and <tt>read_attribute(:attribute)</tt>.
<ide> #
<ide> # == Attribute query methods
<ide> # | 1 |
PHP | PHP | apply fixes from styleci | ba562657ab6f44117645e77cef0f946441b15a37 | <ide><path>src/Illuminate/Support/Stringable.php
<ide> public function afterLast($search)
<ide> */
<ide> public function append(...$values)
<ide> {
<del> return new static($this->value . implode('', $values));
<add> return new static($this->value.implode('', $values));
<ide> }
<ide>
<ide> /**
<ide> public function match($pattern)
<ide> {
<ide> preg_match($pattern, $this->value, $matches);
<ide>
<del> if (!$matches) {
<add> if (! $matches) {
<ide> return new static;
<ide> }
<ide>
<ide> public function pluralStudly($count = 2)
<ide> */
<ide> public function prepend(...$values)
<ide> {
<del> return new static(implode('', $values) . $this->value);
<add> return new static(implode('', $values).$this->value);
<ide> }
<ide>
<ide> /** | 1 |
Javascript | Javascript | replace projectroots with projectroot + watchroots | c5ce7626977a7650e8dce335f2ce78b94839a2a8 | <ide><path>local-cli/bundle/buildBundle.js
<ide> async function buildBundle(
<ide> : defaultProvidesModuleNodeModules;
<ide>
<ide> const terminal = new Terminal(process.stdout);
<del>
<ide> const server = new Server({
<ide> asyncRequireModulePath: config.getAsyncRequireModulePath(),
<ide> assetExts: defaultAssetExts.concat(assetExts),
<ide> async function buildBundle(
<ide> platforms: defaultPlatforms.concat(platforms),
<ide> postMinifyProcess: config.postMinifyProcess,
<ide> postProcessBundleSourcemap: config.postProcessBundleSourcemap,
<del> projectRoots: config.getProjectRoots(),
<add> projectRoot: config.getProjectRoot(),
<ide> providesModuleNodeModules: providesModuleNodeModules,
<ide> reporter: new TerminalReporter(terminal),
<ide> resetCache: args.resetCache,
<ide> resolveRequest: config.resolveRequest,
<ide> sourceExts: sourceExts.concat(defaultSourceExts),
<ide> transformModulePath: transformModulePath,
<ide> watch: false,
<add> watchFolders: config.getWatchFolders(),
<ide> workerPath: config.getWorkerPath && config.getWorkerPath(),
<ide> });
<ide>
<ide><path>local-cli/dependencies/dependencies.js
<ide> function dependencies(argv, config, args, packagerInstance) {
<ide> const packageOpts = {
<ide> assetRegistryPath: ASSET_REGISTRY_PATH,
<ide> cacheStores: [],
<del> projectRoots: config.getProjectRoots(),
<add> projectRoot: config.getProjectRoot(),
<ide> blacklistRE: config.getBlacklistRE(),
<ide> dynamicDepsInPackages: config.dynamicDepsInPackages,
<ide> getPolyfills: config.getPolyfills,
<ide> function dependencies(argv, config, args, packagerInstance) {
<ide> transformModulePath: transformModulePath,
<ide> extraNodeModules: config.extraNodeModules,
<ide> verbose: config.verbose,
<add> watchFolders: config.getWatchFolders(),
<ide> workerPath: config.getWorkerPath(),
<ide> };
<ide>
<del> const relativePath = packageOpts.projectRoots.map(root =>
<del> path.relative(root, rootModuleAbsolutePath),
<del> )[0];
<add> const relativePath = path.relative(
<add> packageOpts.projectRoot,
<add> rootModuleAbsolutePath,
<add> );
<ide>
<ide> const options = {
<ide> platform: args.platform,
<ide> function dependencies(argv, config, args, packagerInstance) {
<ide> // (a) JS code to not depend on anything outside this directory, or
<ide> // (b) Come up with a way to declare this dependency in Buck.
<ide> const isInsideProjectRoots =
<del> packageOpts.projectRoots.filter(root => modulePath.startsWith(root))
<add> packageOpts.watchFolders.filter(root => modulePath.startsWith(root))
<ide> .length > 0;
<ide>
<ide> if (isInsideProjectRoots) {
<ide><path>local-cli/server/middleware/getDevToolsMiddleware.js
<ide> function escapePath(pathname) {
<ide> return '"' + pathname + '"';
<ide> }
<ide>
<del>function launchDevTools({host, projectRoots}, isChromeConnected) {
<add>function launchDevTools({host, watchFolders}, isChromeConnected) {
<ide> // Explicit config always wins
<ide> var customDebugger = process.env.REACT_DEBUGGER;
<ide> if (customDebugger) {
<del> var projects = projectRoots.map(escapePath).join(' ');
<add> var projects = watchFolders.map(escapePath).join(' ');
<ide> var command = customDebugger + ' ' + projects;
<ide> console.log('Starting custom debugger by executing: ' + command);
<ide> exec(command, function(error, stdout, stderr) {
<ide><path>local-cli/server/middleware/openStackFrameInEditorMiddleware.js
<ide>
<ide> const launchEditor = require('../util/launchEditor');
<ide>
<del>module.exports = function({projectRoots}) {
<add>module.exports = function({watchFolders}) {
<ide> return function(req, res, next) {
<ide> if (req.url === '/open-stack-frame') {
<ide> const frame = JSON.parse(req.rawBody);
<del> launchEditor(frame.file, frame.lineNumber, projectRoots);
<add> launchEditor(frame.file, frame.lineNumber, watchFolders);
<ide> res.end('OK');
<ide> } else {
<ide> next();
<ide><path>local-cli/server/runServer.js
<ide> export type Args = {|
<ide> +resetCache: boolean,
<ide> +sourceExts: $ReadOnlyArray<string>,
<ide> +verbose: boolean,
<add> +watchFolders: $ReadOnlyArray<string>,
<ide> |};
<ide>
<ide> function runServer(
<ide> function runServer(
<ide> .use(indexPageMiddleware)
<ide> .use(packagerServer.processRequest.bind(packagerServer));
<ide>
<del> args.projectRoots.forEach(root => app.use(serveStatic(root)));
<add> args.watchFolders.forEach(root => app.use(serveStatic(root)));
<ide>
<ide> app.use(morgan('combined')).use(errorhandler());
<ide>
<ide> function getPackagerServer(args, config, reporter) {
<ide> polyfillModuleNames: config.getPolyfillModuleNames(),
<ide> postMinifyProcess: config.postMinifyProcess,
<ide> postProcessBundleSourcemap: config.postProcessBundleSourcemap,
<del> projectRoots: args.projectRoots,
<add> projectRoot: config.getProjectRoot(),
<ide> providesModuleNodeModules: providesModuleNodeModules,
<ide> reporter,
<ide> resetCache: args.resetCache,
<ide> function getPackagerServer(args, config, reporter) {
<ide> transformModulePath: transformModulePath,
<ide> verbose: args.verbose,
<ide> watch: !args.nonPersistent,
<add> watchFolders: config.getWatchFolders(),
<ide> workerPath: config.getWorkerPath(),
<ide> });
<ide> }
<ide><path>local-cli/server/server.js
<ide> module.exports = {
<ide> default: [],
<ide> },
<ide> {
<del> command: '--projectRoots [list]',
<del> description: 'override the root(s) to be used by the packager',
<add> command: '--watchFolders [list]',
<add> description:
<add> 'Sepcify any additional folders to be added to the watch list',
<ide> parse: (val: string) => val.split(','),
<del> default: (config: ConfigT) => config.getProjectRoots(),
<add> default: (config: ConfigT) => {
<add> return config.getProjectRoots ? config.getProjectRoots() : undefined;
<add> },
<ide> },
<ide> {
<ide> command: '--assetExts [list]', | 6 |
Javascript | Javascript | use consistent types in jsdoc @returns | c241ef1a124798c0bc6fe5cde36f8cc7cb37f29e | <ide><path>lib/assert.js
<ide> function innerFail(obj) {
<ide> * @param {string | Error} [message]
<ide> * @param {string} [operator]
<ide> * @param {Function} [stackStartFn]
<del> * @returns {never}
<ide> */
<ide> function fail(actual, expected, message, operator, stackStartFn) {
<ide> const argsLen = arguments.length;
<ide><path>lib/events.js
<ide> const kMaxEventTargetListenersWarned =
<ide> /**
<ide> * Creates a new `EventEmitter` instance.
<ide> * @param {{ captureRejections?: boolean; }} [opts]
<del> * @returns {EventEmitter}
<add> * @constructs {EventEmitter}
<ide> */
<ide> function EventEmitter(opts) {
<ide> EventEmitter.init.call(this, opts);
<ide><path>lib/fs.js
<ide> function access(path, mode, callback) {
<ide> * directory specified by `path`.
<ide> * @param {string | Buffer | URL} path
<ide> * @param {number} [mode]
<del> * @returns {void | never}
<add> * @returns {void}
<ide> */
<ide> function accessSync(path, mode) {
<ide> path = getValidatedPath(path);
<ide><path>lib/internal/modules/esm/resolve.js
<ide> function emitTrailingSlashPatternDeprecation(match, pjsonUrl, base) {
<ide> * @param {URL} packageJSONUrl
<ide> * @param {string | URL | undefined} base
<ide> * @param {string} main
<del> * @returns
<add> * @returns {void}
<ide> */
<ide> function emitLegacyIndexDeprecation(url, packageJSONUrl, base, main) {
<ide> const format = defaultGetFormat(url); | 4 |
Mixed | Javascript | add multi part library example #221 | 14875d5778a6b679e490970acf3a9fdf79cfbcc3 | <ide><path>examples/multi-part-library/README.md
<add>
<add># webpack.config.js
<add>
<add>``` javascript
<add>var path = require("path");
<add>module.exports = {
<add> entry: {
<add> alpha: "./alpha",
<add> beta: "./beta"
<add> },
<add> output: {
<add> path: path.join(__dirname, "js"),
<add> filename: "MyLibrary.[name].js",
<add> library: ["MyLibrary", "[name]"],
<add> libraryTarget: "umd"
<add> }
<add>}
<add>```
<add>
<add># js/MyLibrary.alpha.js
<add>
<add>``` javascript
<add>(function webpackUniversalModuleDefinition(root, factory) {
<add> if(typeof exports === 'object' && typeof module === 'object')
<add> module.exports = factory();
<add> else if(typeof define === 'function' && define.amd)
<add> define(factory);
<add> else if(typeof exports === 'object')
<add> exports["alpha"] = factory();
<add> else
<add> root["MyLibrary"] = root["MyLibrary"] || {}, root["MyLibrary"]["alpha"] = factory();
<add>})(this, function() {
<add>return /******/ (function(modules) { // webpackBootstrap
<add>/******/
<add>/******/ // The module cache
<add>/******/ var installedModules = {};
<add>/******/
<add>/******/ // The require function
<add>/******/ function __webpack_require__(moduleId) {
<add>/******/ // Check if module is in cache
<add>/******/ if(installedModules[moduleId])
<add>/******/ return installedModules[moduleId].exports;
<add>/******/
<add>/******/ // Create a new module (and put it into the cache)
<add>/******/ var module = installedModules[moduleId] = {
<add>/******/ exports: {},
<add>/******/ id: moduleId,
<add>/******/ loaded: false
<add>/******/ };
<add>/******/
<add>/******/ // Execute the module function
<add>/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
<add>/******/
<add>/******/ // Flag the module as loaded
<add>/******/ module.loaded = true;
<add>/******/
<add>/******/ // Return the exports of the module
<add>/******/ return module.exports;
<add>/******/ }
<add>/******/
<add>/******/
<add>/******/ // expose the modules object (__webpack_modules__)
<add>/******/ __webpack_require__.m = modules;
<add>/******/
<add>/******/ // expose the module cache
<add>/******/ __webpack_require__.c = installedModules;
<add>/******/
<add>/******/ // __webpack_public_path__
<add>/******/ __webpack_require__.p = "js/";
<add>/******/
<add>/******/
<add>/******/ // Load entry module and return exports
<add>/******/ return __webpack_require__(0);
<add>/******/ })
<add>/************************************************************************/
<add>/******/ ([
<add>/* 0 */
<add>/*!******************!*\
<add> !*** ./alpha.js ***!
<add> \******************/
<add>/***/ function(module, exports, __webpack_require__) {
<add>
<add> module.exports = "alpha";
<add>
<add>/***/ }
<add>/******/ ])
<add>})
<add>
<add>```
<add>
<add># js/MyLibrary.beta.js
<add>
<add>``` javascript
<add>(function webpackUniversalModuleDefinition(root, factory) {
<add> if(typeof exports === 'object' && typeof module === 'object')
<add> module.exports = factory();
<add> else if(typeof define === 'function' && define.amd)
<add> define(factory);
<add> else if(typeof exports === 'object')
<add> exports["beta"] = factory();
<add> else
<add> root["MyLibrary"] = root["MyLibrary"] || {}, root["MyLibrary"]["beta"] = factory();
<add>})(this, function() {
<add>return /******/ (function(modules) { // webpackBootstrap
<add>/******/
<add>/******/ // The module cache
<add>/******/ var installedModules = {};
<add>/******/
<add>/******/ // The require function
<add>/******/ function __webpack_require__(moduleId) {
<add>/******/ // Check if module is in cache
<add>/******/ if(installedModules[moduleId])
<add>/******/ return installedModules[moduleId].exports;
<add>/******/
<add>/******/ // Create a new module (and put it into the cache)
<add>/******/ var module = installedModules[moduleId] = {
<add>/******/ exports: {},
<add>/******/ id: moduleId,
<add>/******/ loaded: false
<add>/******/ };
<add>/******/
<add>/******/ // Execute the module function
<add>/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
<add>/******/
<add>/******/ // Flag the module as loaded
<add>/******/ module.loaded = true;
<add>/******/
<add>/******/ // Return the exports of the module
<add>/******/ return module.exports;
<add>/******/ }
<add>/******/
<add>/******/
<add>/******/ // expose the modules object (__webpack_modules__)
<add>/******/ __webpack_require__.m = modules;
<add>/******/
<add>/******/ // expose the module cache
<add>/******/ __webpack_require__.c = installedModules;
<add>/******/
<add>/******/ // __webpack_public_path__
<add>/******/ __webpack_require__.p = "js/";
<add>/******/
<add>/******/
<add>/******/ // Load entry module and return exports
<add>/******/ return __webpack_require__(0);
<add>/******/ })
<add>/************************************************************************/
<add>/******/ ([
<add>/* 0 */
<add>/*!*****************!*\
<add> !*** ./beta.js ***!
<add> \*****************/
<add>/***/ function(module, exports, __webpack_require__) {
<add>
<add> module.exports = "beta";
<add>
<add>/***/ }
<add>/******/ ])
<add>})
<add>
<add>```
<add>
<add># Info
<add>
<add>## Uncompressed
<add>
<add>```
<add>Hash: 188fa9bfc8c26494bc09
<add>Version: webpack 1.1.3
<add>Time: 126ms
<add> Asset Size Chunks Chunk Names
<add> MyLibrary.beta.js 2047 0 [emitted] beta
<add>MyLibrary.alpha.js 2053 1 [emitted] alpha
<add>chunk {0} MyLibrary.beta.js (beta) 24 [rendered]
<add> > beta [0] ./beta.js
<add> [0] ./beta.js 24 {0} [built]
<add>chunk {1} MyLibrary.alpha.js (alpha) 25 [rendered]
<add> > alpha [0] ./alpha.js
<add> [0] ./alpha.js 25 {1} [built]
<add>```
<add>
<add>## Minimized (uglify-js, no zip)
<add>
<add>```
<add>Hash: 7ddebca59251e5368cb3
<add>Version: webpack 1.1.3
<add>Time: 380ms
<add> Asset Size Chunks Chunk Names
<add> MyLibrary.beta.js 485 0 [emitted] beta
<add>MyLibrary.alpha.js 488 1 [emitted] alpha
<add>chunk {0} MyLibrary.beta.js (beta) 24 [rendered]
<add> > beta [0] ./beta.js
<add> [0] ./beta.js 24 {0} [built]
<add>chunk {1} MyLibrary.alpha.js (alpha) 25 [rendered]
<add> > alpha [0] ./alpha.js
<add> [0] ./alpha.js 25 {1} [built]
<add>```
<ide>\ No newline at end of file
<ide><path>examples/multi-part-library/alpha.js
<add>module.exports = "alpha";
<ide>\ No newline at end of file
<ide><path>examples/multi-part-library/beta.js
<add>module.exports = "beta";
<ide>\ No newline at end of file
<ide><path>examples/multi-part-library/build.js
<add>global.NO_TARGET_ARGS = true;
<add>require("../build-common");
<ide>\ No newline at end of file
<ide><path>examples/multi-part-library/template.md
<add>
<add># webpack.config.js
<add>
<add>``` javascript
<add>{{webpack.config.js}}
<add>```
<add>
<add># js/MyLibrary.alpha.js
<add>
<add>``` javascript
<add>{{js/MyLibrary.alpha.js}}
<add>```
<add>
<add># js/MyLibrary.beta.js
<add>
<add>``` javascript
<add>{{js/MyLibrary.beta.js}}
<add>```
<add>
<add># Info
<add>
<add>## Uncompressed
<add>
<add>```
<add>{{stdout}}
<add>```
<add>
<add>## Minimized (uglify-js, no zip)
<add>
<add>```
<add>{{min:stdout}}
<add>```
<ide>\ No newline at end of file
<ide><path>examples/multi-part-library/webpack.config.js
<add>var path = require("path");
<add>module.exports = {
<add> entry: {
<add> alpha: "./alpha",
<add> beta: "./beta"
<add> },
<add> output: {
<add> path: path.join(__dirname, "js"),
<add> filename: "MyLibrary.[name].js",
<add> library: ["MyLibrary", "[name]"],
<add> libraryTarget: "umd"
<add> }
<add>}
<ide>\ No newline at end of file | 6 |
PHP | PHP | add test case, fix inconsistent indentation | a703c4d5397ac1bebf03e4d16453023e3743ee7a | <ide><path>src/Illuminate/Validation/Validator.php
<ide> protected function validate($attribute, $rule)
<ide> }
<ide>
<ide> /**
<del> * Returns the data which was valid.
<del> *
<add> * Returns the data which was valid.
<add> *
<ide> * @return array
<ide> */
<ide> public function valid()
<ide> {
<ide> if ( ! $this->messages) $this->passes();
<ide>
<del> return array_diff_key($this->data, $this->messages()->toArray());
<add> return array_diff_key($this->data, $this->messages()->toArray());
<ide> }
<ide>
<ide> /**
<del> * Returns the data which was invalid.
<del> *
<add> * Returns the data which was invalid.
<add> *
<ide> * @return array
<ide> */
<ide> public function invalid()
<ide> {
<ide> if ( ! $this->messages) $this->passes();
<ide>
<del> return array_intersect_key($this->data, $this->messages()->toArray());
<add> return array_intersect_key($this->data, $this->messages()->toArray());
<ide> }
<ide>
<ide> /**
<ide> protected function getValue($attribute)
<ide> protected function isValidatable($rule, $attribute, $value)
<ide> {
<ide> return $this->presentOrRuleIsImplicit($rule, $attribute, $value) &&
<del> $this->passesOptionalCheck($attribute);
<add> $this->passesOptionalCheck($attribute);
<ide> }
<ide>
<ide> /**
<ide> protected function passesOptionalCheck($attribute)
<ide> if ($this->hasRule($attribute, array('Sometimes')))
<ide> {
<ide> return array_key_exists($attribute, array_dot($this->data))
<del> || in_array($attribute, array_keys($this->data))
<del> || array_key_exists($attribute, $this->files);
<add> || in_array($attribute, array_keys($this->data))
<add> || array_key_exists($attribute, $this->files);
<ide> }
<ide>
<ide> return true;
<ide><path>tests/Validation/ValidationValidatorTest.php
<ide> public function testSometimesWorksOnNestedArrays()
<ide> $this->assertTrue($v->passes());
<ide> }
<ide>
<add> public function testSometimesWorksOnArrays()
<add> {
<add> $trans = $this->getRealTranslator();
<add> $v = new Validator($trans, array('foo' => array('bar', 'baz', 'moo')), array('foo' => 'sometimes|required|between:5,10'));
<add> $this->assertFalse($v->passes());
<add> $this->assertNotEmpty($v->failed());
<add>
<add> $trans = $this->getRealTranslator();
<add> $v = new Validator($trans, array('foo' => array('bar', 'baz', 'moo', 'pew', 'boom')), array('foo' => 'sometimes|required|between:5,10'));
<add> $this->assertTrue($v->passes());
<add> }
<ide>
<ide> public function testHasFailedValidationRules()
<ide> { | 2 |
Text | Text | add known issues to v1.7.0/1.7.1 changelog | 391cae3595e5b426be50cf26a2ae02c346c2a63f | <ide><path>CHANGELOG.md
<ide> will be removed at a later point. (Roman Reiss) [#1363](https://github.com/iojs/
<ide>
<ide> * **build**: A syntax error in the Makefile for release builds caused 1.7.0 to be DOA and unreleased. (Rod Vagg) [#1421](https://github.com/iojs/io.js/pull/1421).
<ide>
<add>### Known issues
<add>
<add>* Some problems with unreferenced timers running during `beforeExit` are still to be resolved. See [#1264](https://github.com/iojs/io.js/issues/1264).
<add>* Surrogate pair in REPL can freeze terminal [#690](https://github.com/iojs/io.js/issues/690)
<add>* `process.send()` is not synchronous as the docs suggest, a regression introduced in 1.0.2, see [#760](https://github.com/iojs/io.js/issues/760) and fix in [#774](https://github.com/iojs/io.js/issues/774)
<add>* Calling `dns.setServers()` while a DNS query is in progress can cause the process to crash on a failed assertion [#894](https://github.com/iojs/io.js/issues/894)
<add>* readline: split escapes are processed incorrectly, see [#1403](https://github.com/iojs/io.js/issues/1403)
<add>
<ide> ### Commits
<ide>
<ide> * [[`aee86a21f2`](https://github.com/iojs/io.js/commit/aee86a21f2)] - **build**: fix RELEASE check (Rod Vagg) [#1421](https://github.com/iojs/io.js/pull/1421)
<ide> will be removed at a later point. (Roman Reiss) [#1363](https://github.com/iojs/
<ide> * [`78005eb`](https://github.com/npm/npm/commit/78005ebb6f4103c20f077669c3929b7ea46a4c0d)[#7743](https://github.com/npm/npm/issues/7743) Always quote arguments passed to `npm run-script`. This allows build systems and the like to safely escape glob patterns passed as arguments to `run-scripts` with `npm run-script <script> -- <arguments>`. This is a tricky change to test, and may be reverted or moved to `npm@3` if it turns out it breaks things for users. ([@mantoni](https://github.com/mantoni))
<ide> * [`da015ee`](https://github.com/npm/npm/commit/da015eee45f6daf384598151d06a9b57ffce136e)[#7074](https://github.com/npm/npm/issues/7074) `read-package-json@1.3.3`: `read-package-json` no longer caches `package.json` files, which trades a very small performance loss for the elimination of a large class of really annoying race conditions. See [#7074](https://github.com/npm/npm/issues/7074) for the grisly details. ([@othiym23](https://github.com/othiym23))
<ide>
<add>### Known issues
<add>
<add>* Some problems with unreferenced timers running during `beforeExit` are still to be resolved. See [#1264](https://github.com/iojs/io.js/issues/1264).
<add>* Surrogate pair in REPL can freeze terminal [#690](https://github.com/iojs/io.js/issues/690)
<add>* `process.send()` is not synchronous as the docs suggest, a regression introduced in 1.0.2, see [#760](https://github.com/iojs/io.js/issues/760) and fix in [#774](https://github.com/iojs/io.js/issues/774)
<add>* Calling `dns.setServers()` while a DNS query is in progress can cause the process to crash on a failed assertion [#894](https://github.com/iojs/io.js/issues/894)
<add>* readline: split escapes are processed incorrectly, see [#1403](https://github.com/iojs/io.js/issues/1403)
<add>
<ide> ### Commits
<ide>
<ide> * [[`d2b62a4973`](https://github.com/iojs/io.js/commit/d2b62a4973)] - **benchmark**: don't check wrk in non-http benchmark (Jackson Tian) [#1368](https://github.com/iojs/io.js/pull/1368) | 1 |
Javascript | Javascript | add strict equalities in src/core/obj.js | ee0c0dd8a9848cb41d4a8a850af62790b1620fc3 | <ide><path>src/core/obj.js
<ide> var Dict = (function DictClosure() {
<ide> get: function Dict_get(key1, key2, key3) {
<ide> var value;
<ide> var xref = this.xref;
<del> if (typeof (value = this.map[key1]) != 'undefined' || key1 in this.map ||
<del> typeof key2 == 'undefined') {
<add> if (typeof (value = this.map[key1]) !== 'undefined' || key1 in this.map ||
<add> typeof key2 === 'undefined') {
<ide> return xref ? xref.fetchIfRef(value) : value;
<ide> }
<del> if (typeof (value = this.map[key2]) != 'undefined' || key2 in this.map ||
<del> typeof key3 == 'undefined') {
<add> if (typeof (value = this.map[key2]) !== 'undefined' || key2 in this.map ||
<add> typeof key3 === 'undefined') {
<ide> return xref ? xref.fetchIfRef(value) : value;
<ide> }
<ide> value = this.map[key3] || null;
<ide> var Catalog = (function CatalogClosure() {
<ide> for (var i = 0; i < kids.length; i++) {
<ide> var kid = kids[i];
<ide> assert(isRef(kid), 'kids must be a ref');
<del> if (kid.num == kidRef.num) {
<add> if (kid.num === kidRef.num) {
<ide> found = true;
<ide> break;
<ide> }
<ide> var XRef = (function XRefClosure() {
<ide> // finding byte sequence
<ide> while (offset < dataLength) {
<ide> var i = 0;
<del> while (i < length && data[offset + i] == what[i]) {
<add> while (i < length && data[offset + i] === what[i]) {
<ide> ++i;
<ide> }
<ide> if (i >= length) { | 1 |
Ruby | Ruby | remove code duplication | 44ea48efc3c2a759026ac95aac981aa78afaf320 | <ide><path>activerecord/lib/active_record/migration.rb
<ide> def run
<ide> raise UnknownMigrationVersionError.new(@target_version) if migration.nil?
<ide> unless (up? && migrated.include?(migration.version.to_i)) || (down? && !migrated.include?(migration.version.to_i))
<ide> begin
<del> ddl_transaction(migration) do
<del> migration.migrate(@direction)
<del> record_version_state_after_migrating(migration.version)
<del> end
<add> execute_migration_in_transaction(migration, @direction)
<ide> rescue => e
<ide> canceled_msg = use_transaction?(migration) ? ", this migration was canceled" : ""
<ide> raise StandardError, "An error has occurred#{canceled_msg}:\n\n#{e}", e.backtrace
<ide> def migrate
<ide> Base.logger.info "Migrating to #{migration.name} (#{migration.version})" if Base.logger
<ide>
<ide> begin
<del> ddl_transaction(migration) do
<del> migration.migrate(@direction)
<del> record_version_state_after_migrating(migration.version)
<del> end
<add> execute_migration_in_transaction(migration, @direction)
<ide> rescue => e
<ide> canceled_msg = use_transaction?(migration) ? "this and " : ""
<ide> raise StandardError, "An error has occurred, #{canceled_msg}all later migrations canceled:\n\n#{e}", e.backtrace
<ide> def ran?(migration)
<ide> migrated.include?(migration.version.to_i)
<ide> end
<ide>
<add> def execute_migration_in_transaction(migration, direction)
<add> ddl_transaction(migration) do
<add> migration.migrate(direction)
<add> record_version_state_after_migrating(migration.version)
<add> end
<add> end
<add>
<ide> def target
<ide> migrations.detect { |m| m.version == @target_version }
<ide> end | 1 |
Ruby | Ruby | dump datetime precision always in mysql | 3432d6b03e8d5a7aae873520013489e853e9a631 | <ide><path>activerecord/lib/active_record/connection_adapters/mysql/schema_dumper.rb
<ide> def schema_limit(column)
<ide> end
<ide>
<ide> def schema_precision(column)
<del> return if /\Adatetime\b/.match(column.sql_type) && column.precision == 6
<del> return if /\Atime(?:stamp)?\b/.match?(column.sql_type) && column.precision == 0
<del> super
<add> super unless /\Atime(?:stamp)?\b/.match?(column.sql_type) && column.precision == 0
<ide> end
<ide>
<ide> def schema_collation(column)
<ide><path>activerecord/test/cases/date_time_precision_test.rb
<ide> def test_writing_a_blank_attribute_timestamptz
<ide> end
<ide> end
<ide>
<del> def test_schema_dump_includes_non_default_datetime_precision
<add> def test_schema_dump_includes_datetime_precision
<ide> @connection.create_table(:foos, force: true) do |t|
<del> t.datetime :datetime_zero, precision: 0
<ide> t.timestamps precision: 6
<ide> end
<ide> output = dump_table_schema("foos")
<del> assert_match %r{t\.datetime\s+"datetime_zero",\s+precision: 0$}, output
<del> assert_match %r{t\.datetime\s+"created_at",\s+null: false$}, output
<del> assert_match %r{t\.datetime\s+"updated_at",\s+null: false$}, output
<add> assert_match %r{t\.datetime\s+"created_at",\s+precision: 6,\s+null: false$}, output
<add> assert_match %r{t\.datetime\s+"updated_at",\s+precision: 6,\s+null: false$}, output
<ide> end
<ide>
<ide> if current_adapter?(:PostgreSQLAdapter, :SQLServerAdapter)
<ide><path>activerecord/test/cases/primary_keys_test.rb
<ide> def test_any_type_primary_key
<ide> test "schema typed primary key column" do
<ide> @connection.create_table(:scheduled_logs, id: :timestamp, precision: 6, force: true)
<ide> schema = dump_table_schema("scheduled_logs")
<del> assert_match %r/create_table "scheduled_logs", id: { type: :timestamp.* }/, schema
<add> assert_match %r/create_table "scheduled_logs", id: { type: :timestamp, precision: 6.* }/, schema
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/test/cases/schema_dumper_test.rb
<ide> def test_schema_dump_defaults_with_universally_supported_types
<ide> assert_match %r{t\.date\s+"date_with_default",\s+default: "2014-06-05"}, output
<ide>
<ide> if supports_datetime_with_precision?
<del> assert_match %r{t\.datetime\s+"datetime_with_default",\s+default: "2014-06-05 07:17:04"}, output
<add> assert_match %r{t\.datetime\s+"datetime_with_default",\s+precision: 6,\s+default: "2014-06-05 07:17:04"}, output
<ide> else
<ide> assert_match %r{t\.datetime\s+"datetime_with_default",\s+default: "2014-06-05 07:17:04"}, output
<ide> end | 4 |
Python | Python | add global_step to reduce_aggregated_logs() | 48192d5453df4164d15d40ca9de61aa8e7f3ef31 | <ide><path>official/core/base_task.py
<ide> def aggregate_logs(self, state, step_logs):
<ide> """Optional aggregation over logs returned from a validation step."""
<ide> pass
<ide>
<del> def reduce_aggregated_logs(self, aggregated_logs):
<add> def reduce_aggregated_logs(self,
<add> aggregated_logs,
<add> global_step: Optional[tf.Tensor] = None):
<ide> """Optional reduce of aggregated logs over validation steps."""
<ide> return {}
<ide><path>official/core/base_trainer.py
<ide> def eval_end(self, aggregated_logs=None):
<ide> # loss was not returned from the task's `validation_step` method.
<ide> logging.info("The task did not report validation loss.")
<ide> if aggregated_logs:
<del> metrics = self.task.reduce_aggregated_logs(aggregated_logs)
<add> metrics = self.task.reduce_aggregated_logs(
<add> aggregated_logs, global_step=self.global_step)
<ide> logs.update(metrics)
<ide>
<ide> if self._checkpoint_exporter:
<ide><path>official/modeling/multitask/evaluator.py
<ide> def evaluate(self, num_steps: tf.Tensor):
<ide> for metric in task_metrics + [task_loss]:
<ide> logs[metric.name] = metric.result()
<ide> if outputs:
<del> metrics = task.reduce_aggregated_logs(outputs)
<add> metrics = task.reduce_aggregated_logs(
<add> outputs, global_step=self.global_step)
<ide> logs.update(metrics)
<ide> results[name] = logs
<ide>
<ide><path>official/modeling/multitask/evaluator_test.py
<ide> def aggregate_logs(self, state, step_outputs):
<ide> np.concatenate([np.expand_dims(v.numpy(), axis=0) for v in value]))
<ide> return state
<ide>
<del> def reduce_aggregated_logs(self, aggregated_logs):
<add> def reduce_aggregated_logs(self,
<add> aggregated_logs,
<add> global_step=None):
<ide> for k, v in aggregated_logs.items():
<ide> aggregated_logs[k] = np.sum(np.stack(v, axis=0))
<ide> return aggregated_logs
<ide><path>official/nlp/tasks/question_answering.py
<ide> def aggregate_logs(self, state=None, step_outputs=None):
<ide> end_logits=values[2]))
<ide> return state
<ide>
<del> def reduce_aggregated_logs(self, aggregated_logs):
<add> def reduce_aggregated_logs(self, aggregated_logs, global_step=None):
<ide> all_predictions, _, scores_diff = (
<ide> self.squad_lib.postprocess_output(
<ide> self._eval_examples,
<ide><path>official/nlp/tasks/sentence_prediction.py
<ide> def aggregate_logs(self, state=None, step_outputs=None):
<ide> np.concatenate([v.numpy() for v in step_outputs['labels']], axis=0))
<ide> return state
<ide>
<del> def reduce_aggregated_logs(self, aggregated_logs):
<add> def reduce_aggregated_logs(self, aggregated_logs, global_step=None):
<ide> if self.metric_type == 'accuracy':
<ide> return None
<ide> elif self.metric_type == 'matthews_corrcoef':
<ide><path>official/nlp/tasks/tagging.py
<ide> def id_to_class_name(batched_ids):
<ide> state['label_class'].extend(id_to_class_name(step_outputs['label_ids']))
<ide> return state
<ide>
<del> def reduce_aggregated_logs(self, aggregated_logs):
<add> def reduce_aggregated_logs(self, aggregated_logs, global_step=None):
<ide> """Reduces aggregated logs over validation steps."""
<ide> label_class = aggregated_logs['label_class']
<ide> predict_class = aggregated_logs['predict_class']
<ide><path>official/nlp/tasks/translation.py
<ide> def aggregate_logs(self, state=None, step_outputs=None):
<ide> state[u_id] = (in_ids, out_ids)
<ide> return state
<ide>
<del> def reduce_aggregated_logs(self, aggregated_logs):
<add> def reduce_aggregated_logs(self, aggregated_logs, global_step=None):
<ide>
<ide> def _decode(ids):
<ide> return self._sp_tokenizer.detokenize(ids).numpy().decode()
<ide><path>official/utils/testing/mock_task.py
<ide> def aggregate_logs(self, state, step_outputs):
<ide> np.concatenate([np.expand_dims(v.numpy(), axis=0) for v in value]))
<ide> return state
<ide>
<del> def reduce_aggregated_logs(self, aggregated_logs):
<add> def reduce_aggregated_logs(self, aggregated_logs, global_step=None):
<ide> for k, v in aggregated_logs.items():
<ide> aggregated_logs[k] = np.sum(np.stack(v, axis=0))
<ide> return aggregated_logs
<ide><path>official/vision/beta/tasks/maskrcnn.py
<ide> def aggregate_logs(self, state=None, step_outputs=None):
<ide> step_outputs[self.coco_metric.name][1])
<ide> return state
<ide>
<del> def reduce_aggregated_logs(self, aggregated_logs):
<add> def reduce_aggregated_logs(self, aggregated_logs, global_step=None):
<ide> return self.coco_metric.result()
<ide><path>official/vision/beta/tasks/retinanet.py
<ide> def aggregate_logs(self, state=None, step_outputs=None):
<ide> step_outputs[self.coco_metric.name][1])
<ide> return state
<ide>
<del> def reduce_aggregated_logs(self, aggregated_logs):
<add> def reduce_aggregated_logs(self, aggregated_logs, global_step=None):
<ide> return self.coco_metric.result()
<ide><path>official/vision/beta/tasks/semantic_segmentation.py
<ide> def aggregate_logs(self, state=None, step_outputs=None):
<ide> step_outputs[self.iou_metric.name][1])
<ide> return state
<ide>
<del> def reduce_aggregated_logs(self, aggregated_logs):
<add> def reduce_aggregated_logs(self, aggregated_logs, global_step=None):
<ide> result = {}
<ide> ious = self.iou_metric.result()
<ide> # TODO(arashwan): support loading class name from a label map file. | 12 |
PHP | PHP | create getter for the http route middlewares | 8412218059b94c3f781fdeee3f0eb507a66550d4 | <ide><path>src/Illuminate/Foundation/Http/Kernel.php
<ide> public function getMiddlewareGroups()
<ide> return $this->middlewareGroups;
<ide> }
<ide>
<add> /**
<add> * Get the application's route middleware.
<add> *
<add> * @return array
<add> */
<add> public function getRouteMiddleware()
<add> {
<add> return $this->routeMiddleware;
<add> }
<add>
<ide> /**
<ide> * Get the Laravel application instance.
<ide> *
<ide><path>tests/Foundation/Http/KernelTest.php
<ide> public function testGetMiddlewareGroups()
<ide> $this->assertEquals([], $kernel->getMiddlewareGroups());
<ide> }
<ide>
<add> public function testGetRouteMiddleware()
<add> {
<add> $kernel = new Kernel($this->getApplication(), $this->getRouter());
<add>
<add> $this->assertEquals([], $kernel->getRouteMiddleware());
<add> }
<add>
<ide> /**
<ide> * @return \Illuminate\Contracts\Foundation\Application
<ide> */ | 2 |
Ruby | Ruby | show latest version | 91fffeeff6a5b1d9fd042716035a14698bc674be | <ide><path>Library/Homebrew/cmd/info.rb
<ide> def info_formula(f, args:)
<ide> specs = []
<ide>
<ide> if (stable = f.stable)
<del> s = "stable #{stable.version}"
<add> latest_version = if ENV["HOMEBREW_JSON_CORE"].present?
<add> BottleAPI.latest_pkg_version(f.name).version || stable.version
<add> else
<add> stable.version
<add> end
<add>
<add> s = "stable #{latest_version}"
<ide> s += " (bottled)" if stable.bottled? && f.pour_bottle?
<ide> specs << s
<ide> end | 1 |
Python | Python | fix #726 - get_lr in examples | 59cefd4f985b7221846189690ead3300ff864b3d | <ide><path>examples/run_bert_squad.py
<ide> def main():
<ide> optimizer.zero_grad()
<ide> global_step += 1
<ide> if args.local_rank in [-1, 0]:
<del> tb_writer.add_scalar('lr', optimizer.get_lr()[0], global_step)
<add> if not args.fp16:
<add> tb_writer.add_scalar('lr', optimizer.get_lr()[0], global_step)
<ide> tb_writer.add_scalar('loss', loss.item(), global_step)
<ide>
<ide> if args.do_train and (args.local_rank == -1 or torch.distributed.get_rank() == 0):
<ide><path>examples/run_xlnet_classifier.py
<ide> def main():
<ide> optimizer.zero_grad()
<ide> global_step += 1
<ide> if args.local_rank in [-1, 0] and (args.log_every <= 0 or (step + 1) % args.log_every == 0):
<del> tb_writer.add_scalar('lr', optimizer.get_lr()[0], global_step)
<add> if not args.fp16:
<add> tb_writer.add_scalar('lr', optimizer.get_lr()[0], global_step)
<ide> tb_writer.add_scalar('loss', loss.item(), global_step)
<ide>
<ide> ### Saving best-practices: if you use defaults names for the model, you can reload it using from_pretrained()
<ide><path>examples/run_xlnet_squad.py
<ide> def main():
<ide> optimizer.zero_grad()
<ide> global_step += 1
<ide> if args.local_rank in [-1, 0]:
<del> tb_writer.add_scalar('lr', optimizer.get_lr()[0], global_step)
<add> if not args.fp16:
<add> tb_writer.add_scalar('lr', optimizer.get_lr()[0], global_step)
<ide> tb_writer.add_scalar('loss', loss.item(), global_step)
<ide>
<ide> if args.do_train and (args.local_rank == -1 or torch.distributed.get_rank() == 0): | 3 |
Javascript | Javascript | put comment back in correct spot | 93ee8f85f66e3dcfc9b213ae9733ae12a513953e | <ide><path>src/core/core.js
<ide> // High pixel density displays - multiply the size of the canvas height/width by the device pixel ratio, then scale.
<ide> Chart.helpers.retinaScale(this);
<ide>
<del> // Always bind this so that if the responsive state changes we still work
<ide> if (config) {
<ide> this.controller = new Chart.Controller(this);
<ide> }
<ide>
<add> // Always bind this so that if the responsive state changes we still work
<ide> var _this = this;
<ide> Chart.helpers.addResizeListener(context.canvas.parentNode, function() {
<ide> if (_this.controller && _this.controller.config.options.responsive) { | 1 |
Javascript | Javascript | improve stream error messages | 560a589e75c12cfd2c2813622a70271c962f6e0e | <ide><path>lib/_stream_readable.js
<ide> function maybeReadMore_(stream, state) {
<ide> // for virtual (non-string, non-buffer) streams, "length" is somewhat
<ide> // arbitrary, and perhaps not very meaningful.
<ide> Readable.prototype._read = function(n) {
<del> this.emit('error', new Error('not implemented'));
<add> this.emit('error', new Error('_read() is not implemented'));
<ide> };
<ide>
<ide> Readable.prototype.pipe = function(dest, pipeOpts) {
<ide><path>lib/_stream_transform.js
<ide> Transform.prototype.push = function(chunk, encoding) {
<ide> // an error, then that'll put the hurt on the whole operation. If you
<ide> // never call cb(), then you'll never get another chunk.
<ide> Transform.prototype._transform = function(chunk, encoding, cb) {
<del> throw new Error('Not implemented');
<add> throw new Error('_transform() is not implemented');
<ide> };
<ide>
<ide> Transform.prototype._write = function(chunk, encoding, cb) {
<ide><path>lib/_stream_writable.js
<ide> function clearBuffer(stream, state) {
<ide> }
<ide>
<ide> Writable.prototype._write = function(chunk, encoding, cb) {
<del> cb(new Error('_write() method is not implemented'));
<add> cb(new Error('_write() is not implemented'));
<ide> };
<ide>
<ide> Writable.prototype._writev = null; | 3 |
Python | Python | calrify tiny/xmin in finfo and machar (gh-16253) | 0eb532de60c9caaaa568ea294e7e1427265b6552 | <ide><path>numpy/core/getlimits.py
<ide> class finfo:
<ide> The approximate decimal resolution of this type, i.e.,
<ide> ``10**-precision``.
<ide> tiny : float
<del> The smallest positive usable number. Type of `tiny` is an
<del> appropriate floating point type.
<add> The smallest positive floating point number with full precision
<add> (see Notes).
<ide>
<ide> Parameters
<ide> ----------
<ide> class finfo:
<ide> impacts import times. These objects are cached, so calling ``finfo()``
<ide> repeatedly inside your functions is not a problem.
<ide>
<add> Note that ``tiny`` is not actually the smallest positive representable
<add> value in a NumPy floating point type. As in the IEEE-754 standard [1]_,
<add> NumPy floating point types make use of subnormal numbers to fill the
<add> gap between 0 and ``tiny``. However, subnormal numbers may have
<add> significantly reduced precision [2]_.
<add>
<add> References
<add> ----------
<add> .. [1] IEEE Standard for Floating-Point Arithmetic, IEEE Std 754-2008,
<add> pp.1-70, 2008, http://www.doi.org/10.1109/IEEESTD.2008.4610935
<add> .. [2] Wikipedia, "Denormal Numbers",
<add> https://en.wikipedia.org/wiki/Denormal_number
<ide> """
<ide>
<ide> _finfo_cache = {}
<ide> def __str__(self):
<ide> def __repr__(self):
<ide> return "%s(min=%s, max=%s, dtype=%s)" % (self.__class__.__name__,
<ide> self.min, self.max, self.dtype)
<del>
<ide><path>numpy/core/machar.py
<ide> class MachAr:
<ide> Smallest (most negative) power of `ibeta` consistent with there
<ide> being no leading zeros in the mantissa.
<ide> xmin : float
<del> Floating point number ``beta**minexp`` (the smallest [in
<del> magnitude] usable floating value).
<add> Floating-point number ``beta**minexp`` (the smallest [in
<add> magnitude] positive floating point number with full precision).
<ide> maxexp : int
<ide> Smallest (positive) power of `ibeta` that causes overflow.
<ide> xmax : float | 2 |
Python | Python | set version for 2.0.2 release | 49fd5a646f329be1147b43b8c2c611f1424abe22 | <ide><path>spacy/about.py
<ide> # https://github.com/pypa/warehouse/blob/master/warehouse/__about__.py
<ide>
<ide> __title__ = 'spacy'
<del>__version__ = '2.0.2.dev1'
<add>__version__ = '2.0.2'
<ide> __summary__ = 'Industrial-strength Natural Language Processing (NLP) with Python and Cython'
<ide> __uri__ = 'https://spacy.io'
<ide> __author__ = 'Explosion AI'
<ide> __email__ = 'contact@explosion.ai'
<ide> __license__ = 'MIT'
<del>__release__ = False
<add>__release__ = True
<ide>
<ide> __docs_models__ = 'https://spacy.io/usage/models'
<ide> __download_url__ = 'https://github.com/explosion/spacy-models/releases/download' | 1 |
Ruby | Ruby | add configuration option for driver adapter | 0dc63281da1c7075ce63d8dba62e4230d72bfc2a | <ide><path>actionpack/lib/system_testing/base.rb
<ide> module SystemTesting
<ide> module Base
<ide> include TestHelper
<ide> include DriverAdapter
<add>
<add> ActiveSupport.run_load_hooks(:system_testing, self)
<ide> end
<ide> end
<ide><path>actionpack/lib/system_testing/driver_adapter.rb
<ide> module SystemTesting
<ide> module DriverAdapter
<ide> extend ActiveSupport::Concern
<ide>
<del> included do
<del> self.driver_adapter = :capybara_rack_test_driver
<del> end
<del>
<ide> module ClassMethods
<add> attr_accessor :driver_adapter
<add>
<ide> def driver_adapter=(driver_name_or_class)
<ide> driver = DriverAdapters.lookup(driver_name_or_class).new
<ide> driver.call
<ide><path>actionpack/lib/system_testing/railtie.rb
<add>module SystemTesting
<add> class Railtie < Rails::Railtie
<add> config.system_testing = ActiveSupport::OrderedOptions.new
<add>
<add> initializer "system_testing.set_configs" do |app|
<add> options = app.config.system_testing
<add> options.driver_adapter ||= :capybara_rack_test_driver
<add>
<add> ActiveSupport.on_load(:system_testing) do
<add> options.each { |k,v| send("#{k}=", v) }
<add> end
<add> end
<add> end
<add>end
<ide><path>railties/lib/rails/all.rb
<ide> action_cable/engine
<ide> rails/test_unit/railtie
<ide> sprockets/railtie
<add> system_testing/railtie
<ide> ).each do |railtie|
<ide> begin
<ide> require railtie | 4 |
Python | Python | do some basic testing of the recorder | eb5e50215a630ed028eca2d85d4131e9e186377d | <ide><path>tests/migrations/tests.py
<del>from django.test import TransactionTestCase
<add>from django.test import TransactionTestCase, TestCase
<ide> from django.db import connection
<ide> from django.db.migrations.graph import MigrationGraph, CircularDependencyError
<ide> from django.db.migrations.loader import MigrationLoader
<add>from django.db.migrations.recorder import MigrationRecorder
<ide>
<ide>
<ide> class GraphTests(TransactionTestCase):
<ide> def test_load(self):
<ide> graph.forwards_plan(("migrations", "0002_second")),
<ide> [("migrations", "0001_initial"), ("migrations", "0002_second")],
<ide> )
<add>
<add>
<add>class RecorderTests(TestCase):
<add> """
<add> Tests the disk and database loader.
<add> """
<add>
<add> def test_apply(self):
<add> """
<add> Tests marking migrations as applied/unapplied.
<add> """
<add> recorder = MigrationRecorder(connection)
<add> self.assertEqual(
<add> recorder.applied_migrations(),
<add> set(),
<add> )
<add> recorder.record_applied("myapp", "0432_ponies")
<add> self.assertEqual(
<add> recorder.applied_migrations(),
<add> set([("myapp", "0432_ponies")]),
<add> )
<add> recorder.record_unapplied("myapp", "0432_ponies")
<add> self.assertEqual(
<add> recorder.applied_migrations(),
<add> set(),
<add> ) | 1 |
Text | Text | move 8 collaborators to emeriti | 4db84724cadddb85c7690310cc2cb8f02c78cbee | <ide><path>README.md
<ide> For more information about the governance of the Node.js project, see
<ide> **Ilkka Myller** <ilkka.myller@nodefield.com>
<ide> * [indutny](https://github.com/indutny) -
<ide> **Fedor Indutny** <fedor.indutny@gmail.com>
<del>* [isaacs](https://github.com/isaacs) -
<del>**Isaac Z. Schlueter** <i@izs.me>
<ide> * [italoacasas](https://github.com/italoacasas) -
<ide> **Italo A. Casas** <me@italoacasas.com> (he/him)
<ide> * [JacksonTian](https://github.com/JacksonTian) -
<ide> For more information about the governance of the Node.js project, see
<ide> **Luigi Pinca** <luigipinca@gmail.com> (he/him)
<ide> * [lucamaraschi](https://github.com/lucamaraschi) -
<ide> **Luca Maraschi** <luca.maraschi@gmail.com> (he/him)
<del>* [lxe](https://github.com/lxe) -
<del>**Aleksey Smolenchuk** <lxe@lxe.co>
<ide> * [matthewloring](https://github.com/matthewloring) -
<ide> **Matthew Loring** <mattloring@google.com>
<ide> * [mcollina](https://github.com/mcollina) -
<ide> For more information about the governance of the Node.js project, see
<ide> **Mikeal Rogers** <mikeal.rogers@gmail.com>
<ide> * [misterdjules](https://github.com/misterdjules) -
<ide> **Julien Gilli** <jgilli@nodejs.org>
<del>* [monsanto](https://github.com/monsanto) -
<del>**Christopher Monsanto** <chris@monsan.to>
<ide> * [mscdex](https://github.com/mscdex) -
<ide> **Brian White** <mscdex@mscdex.net>
<ide> * [MylesBorins](https://github.com/MylesBorins) -
<ide> For more information about the governance of the Node.js project, see
<ide> **Teddy Katz** <teddy.katz@gmail.com>
<ide> * [ofrobots](https://github.com/ofrobots) -
<ide> **Ali Ijaz Sheikh** <ofrobots@google.com>
<del>* [Olegas](https://github.com/Olegas) -
<del>**Oleg Elifantiev** <oleg@elifantiev.ru>
<ide> * [orangemocha](https://github.com/orangemocha) -
<ide> **Alexis Campailla** <orangemocha@nodejs.org>
<ide> * [othiym23](https://github.com/othiym23) -
<ide> **Forrest L Norvell** <ogd@aoaioxxysz.net> (he/him)
<del>* [petkaantonov](https://github.com/petkaantonov) -
<del>**Petka Antonov** <petka_antonov@hotmail.com>
<ide> * [phillipj](https://github.com/phillipj) -
<ide> **Phillip Johnsen** <johphi@gmail.com>
<del>* [piscisaureus](https://github.com/piscisaureus) -
<del>**Bert Belder** <bertbelder@gmail.com>
<ide> * [pmq20](https://github.com/pmq20) -
<ide> **Minqi Pan** <pmq2001@gmail.com>
<ide> * [princejwesley](https://github.com/princejwesley) -
<ide> For more information about the governance of the Node.js project, see
<ide> **Refael Ackermann** <refack@gmail.com> (he/him)
<ide> * [richardlau](https://github.com/richardlau) -
<ide> **Richard Lau** <riclau@uk.ibm.com>
<del>* [rlidwka](https://github.com/rlidwka) -
<del>**Alex Kocharin** <alex@kocharin.ru>
<ide> * [rmg](https://github.com/rmg) -
<ide> **Ryan Graham** <r.m.graham@gmail.com>
<ide> * [robertkowalski](https://github.com/robertkowalski) -
<ide> For more information about the governance of the Node.js project, see
<ide> **Stefan Budeanu** <stefan@budeanu.com>
<ide> * [targos](https://github.com/targos) -
<ide> **Michaël Zasso** <targos@protonmail.com> (he/him)
<del>* [tellnes](https://github.com/tellnes) -
<del>**Christian Tellnes** <christian@tellnes.no>
<ide> * [thefourtheye](https://github.com/thefourtheye) -
<ide> **Sakthipriyan Vairamani** <thechargingvolcano@gmail.com> (he/him)
<ide> * [thekemkid](https://github.com/thekemkid) -
<ide> For more information about the governance of the Node.js project, see
<ide> * [yosuke-furukawa](https://github.com/yosuke-furukawa) -
<ide> **Yosuke Furukawa** <yosuke.furukawa@gmail.com>
<ide>
<add>### Collaborator Emeriti
<add>
<add>* [isaacs](https://github.com/isaacs) -
<add>**Isaac Z. Schlueter** <i@izs.me>
<add>* [lxe](https://github.com/lxe) -
<add>**Aleksey Smolenchuk** <lxe@lxe.co>
<add>* [monsanto](https://github.com/monsanto) -
<add>**Christopher Monsanto** <chris@monsan.to>
<add>* [Olegas](https://github.com/Olegas) -
<add>**Oleg Elifantiev** <oleg@elifantiev.ru>
<add>* [petkaantonov](https://github.com/petkaantonov) -
<add>**Petka Antonov** <petka_antonov@hotmail.com>
<add>* [piscisaureus](https://github.com/piscisaureus) -
<add>**Bert Belder** <bertbelder@gmail.com>
<add>* [rlidwka](https://github.com/rlidwka) -
<add>**Alex Kocharin** <alex@kocharin.ru>
<add>* [tellnes](https://github.com/tellnes) -
<add>**Christian Tellnes** <christian@tellnes.no>
<add>
<ide> Collaborators follow the [COLLABORATOR_GUIDE.md](./COLLABORATOR_GUIDE.md) in
<ide> maintaining the Node.js project.
<ide> | 1 |
Text | Text | add contributer aggreement | ada4712250a8e02b13a2bbf06f0e150348494a6d | <ide><path>.github/contributors/fsonntag.md
<add># spaCy contributor agreement
<add>
<add>This spaCy Contributor Agreement (**"SCA"**) is based on the
<add>[Oracle Contributor Agreement](http://www.oracle.com/technetwork/oca-405177.pdf).
<add>The SCA applies to any contribution that you make to any product or project
<add>managed by us (the **"project"**), and sets out the intellectual property rights
<add>you grant to us in the contributed materials. The term **"us"** shall mean
<add>[ExplosionAI UG (haftungsbeschränkt)](https://explosion.ai/legal). The term
<add>**"you"** shall mean the person or entity identified below.
<add>
<add>If you agree to be bound by these terms, fill in the information requested
<add>below and include the filled-in version with your first pull request, under the
<add>folder [`.github/contributors/`](/.github/contributors/). The name of the file
<add>should be your GitHub username, with the extension `.md`. For example, the user
<add>example_user would create the file `.github/contributors/example_user.md`.
<add>
<add>Read this agreement carefully before signing. These terms and conditions
<add>constitute a binding legal agreement.
<add>
<add>## Contributor Agreement
<add>
<add>1. The term "contribution" or "contributed materials" means any source code,
<add>object code, patch, tool, sample, graphic, specification, manual,
<add>documentation, or any other material posted or submitted by you to the project.
<add>
<add>2. With respect to any worldwide copyrights, or copyright applications and
<add>registrations, in your contribution:
<add>
<add> * you hereby assign to us joint ownership, and to the extent that such
<add> assignment is or becomes invalid, ineffective or unenforceable, you hereby
<add> grant to us a perpetual, irrevocable, non-exclusive, worldwide, no-charge,
<add> royalty-free, unrestricted license to exercise all rights under those
<add> copyrights. This includes, at our option, the right to sublicense these same
<add> rights to third parties through multiple levels of sublicensees or other
<add> licensing arrangements;
<add>
<add> * you agree that each of us can do all things in relation to your
<add> contribution as if each of us were the sole owners, and if one of us makes
<add> a derivative work of your contribution, the one who makes the derivative
<add> work (or has it made will be the sole owner of that derivative work;
<add>
<add> * you agree that you will not assert any moral rights in your contribution
<add> against us, our licensees or transferees;
<add>
<add> * you agree that we may register a copyright in your contribution and
<add> exercise all ownership rights associated with it; and
<add>
<add> * you agree that neither of us has any duty to consult with, obtain the
<add> consent of, pay or render an accounting to the other for any use or
<add> distribution of your contribution.
<add>
<add>3. With respect to any patents you own, or that you can license without payment
<add>to any third party, you hereby grant to us a perpetual, irrevocable,
<add>non-exclusive, worldwide, no-charge, royalty-free license to:
<add>
<add> * make, have made, use, sell, offer to sell, import, and otherwise transfer
<add> your contribution in whole or in part, alone or in combination with or
<add> included in any product, work or materials arising out of the project to
<add> which your contribution was submitted, and
<add>
<add> * at our option, to sublicense these same rights to third parties through
<add> multiple levels of sublicensees or other licensing arrangements.
<add>
<add>4. Except as set out above, you keep all right, title, and interest in your
<add>contribution. The rights that you grant to us under these terms are effective
<add>on the date you first submitted a contribution to us, even if your submission
<add>took place before the date you sign these terms.
<add>
<add>5. You covenant, represent, warrant and agree that:
<add>
<add> * Each contribution that you submit is and shall be an original work of
<add> authorship and you can legally grant the rights set out in this SCA;
<add>
<add> * to the best of your knowledge, each contribution will not violate any
<add> third party's copyrights, trademarks, patents, or other intellectual
<add> property rights; and
<add>
<add> * each contribution shall be in compliance with U.S. export control laws and
<add> other applicable export and import laws. You agree to notify us if you
<add> become aware of any circumstance which would make any of the foregoing
<add> representations inaccurate in any respect. We may publicly disclose your
<add> participation in the project, including the fact that you have signed the SCA.
<add>
<add>6. This SCA is governed by the laws of the State of California and applicable
<add>U.S. Federal law. Any choice of law rules will not apply.
<add>
<add>7. Please place an “x” on one of the applicable statement below. Please do NOT
<add>mark both statements:
<add>
<add> * [ ] I am signing on behalf of myself as an individual and no other person
<add> or entity, including my employer, has or will have rights with respect to my
<add> contributions.
<add>
<add> * [x] I am signing on behalf of my employer or a legal entity and I have the
<add> actual authority to contractually bind that entity.
<add>
<add>## Contributor Details
<add>
<add>| Field | Entry |
<add>|------------------------------- | -------------------- |
<add>| Name | Felix Sonntag |
<add>| Company name (if applicable) | - |
<add>| Title or role (if applicable) | Student |
<add>| Date | 2017-11-19 |
<add>| GitHub username | fsonntag |
<add>| Website (optional) | http://github.com/fsonntag/ | | 1 |
Python | Python | fix typo timeouttimer -> timeouttimer | 64526470221e72f4c4782fae38030a33d3e2fa97 | <ide><path>celery/task.py
<ide> def join(self, timeout=None):
<ide> the :class:`celery.timer.TimeoutError` exception.
<ide>
<ide> """
<del> timeout_timer = TimeOutTimer(timeout) # Timeout timer starts here.
<add> timeout_timer = TimeoutTimer(timeout) # Timeout timer starts here.
<ide> taskset_id, subtask_ids = self.run()
<ide> pending_results = map(AsyncResult, subtask_ids)
<ide> results = PositionQueue(length=len(subtask_ids)) | 1 |
Ruby | Ruby | use direction instead of rtl flag | 5020c2e3022ad9f07c29679f489cdb836425c552 | <ide><path>guides/rails_guides.rb
<ide> edge = `git rev-parse HEAD`.strip unless version
<ide>
<ide> RailsGuides::Generator.new(
<del> edge: edge,
<del> version: version,
<del> all: env_flag["ALL"],
<del> only: env_value["ONLY"],
<del> kindle: env_flag["KINDLE"],
<del> language: env_value["GUIDES_LANGUAGE"],
<del> rtl: env_value["RTL"]
<add> edge: edge,
<add> version: version,
<add> all: env_flag["ALL"],
<add> only: env_value["ONLY"],
<add> kindle: env_flag["KINDLE"],
<add> language: env_value["GUIDES_LANGUAGE"],
<add> direction: env_value["DIRECTION"].to_sym
<ide> ).generate
<ide><path>guides/rails_guides/generator.rb
<ide> module RailsGuides
<ide> class Generator
<ide> GUIDES_RE = /\.(?:erb|md)\z/
<ide>
<del> def initialize(edge:, version:, all:, only:, kindle:, language:, rtl: false)
<del> @edge = edge
<del> @version = version
<del> @all = all
<del> @only = only
<del> @kindle = kindle
<del> @language = language
<del> @rtl = rtl
<add> def initialize(edge:, version:, all:, only:, kindle:, language:, direction: :ltr)
<add> @edge = edge
<add> @version = version
<add> @all = all
<add> @only = only
<add> @kindle = kindle
<add> @language = language
<add> @direction = direction
<ide>
<ide> if @kindle
<ide> check_for_kindlegen
<ide> def select_only(guides)
<ide> def copy_assets
<ide> FileUtils.cp_r(Dir.glob("#{@guides_dir}/assets/*"), @output_dir)
<ide>
<del> if @rtl
<del> FileUtils.rm(Dir.glob("#{@output_dir}/stylesheets/main.css"))
<del> FileUtils.mv("#{@output_dir}/stylesheets/main.rtl.css", "#{@output_dir}/stylesheets/main.css")
<add> if @direction == :rtl
<add> overwrite_css_with_right_to_left_direction
<ide> end
<ide> end
<ide>
<add> def overwrite_css_with_right_to_left_direction
<add> FileUtils.mv("#{@output_dir}/stylesheets/main.rtl.css", "#{@output_dir}/stylesheets/main.css")
<add> end
<add>
<ide> def output_file_for(guide)
<ide> if guide.end_with?(".md")
<ide> guide.sub(/md\z/, "html") | 2 |
Javascript | Javascript | increase information logged to messagequeue.spy | f445ac8ef1f0f4666f36ced70e5ee3b74dd00924 | <ide><path>Libraries/BatchedBridge/BatchedBridge.js
<ide> *
<ide> * @providesModule BatchedBridge
<ide> * @flow
<add> * @format
<ide> */
<ide> 'use strict';
<ide>
<ide> const MessageQueue = require('MessageQueue');
<add>
<ide> const BatchedBridge = new MessageQueue();
<ide>
<ide> // Wire up the batched bridge on the global object so that we can call into it.
<ide><path>Libraries/BatchedBridge/MessageQueue.js
<ide> *
<ide> * @providesModule MessageQueue
<ide> * @flow
<add> * @format
<ide> */
<ide>
<ide> /*eslint no-bitwise: 0*/
<ide> const stringifySafe = require('stringifySafe');
<ide> export type SpyData = {
<ide> type: number,
<ide> module: ?string,
<del> method: string|number,
<del> args: any
<del>}
<add> method: string | number,
<add> isSync: boolean,
<add> successCbId: number,
<add> failCbId: number,
<add> args: any[],
<add> returnValue?: any,
<add>};
<ide>
<ide> const TO_JS = 0;
<ide> const TO_NATIVE = 1;
<ide> const MIN_TIME_BETWEEN_FLUSHES_MS = 5;
<ide>
<ide> const TRACE_TAG_REACT_APPS = 1 << 17;
<ide>
<del>const DEBUG_INFO_LIMIT = 32;
<add>const DEBUG_INFO_LIMIT = 64;
<ide>
<ide> // Work around an initialization order issue
<ide> let JSTimers = null;
<ide>
<ide> class MessageQueue {
<del> _lazyCallableModules: {[key: string]: void => Object};
<add> _lazyCallableModules: {[key: string]: (void) => Object};
<ide> _queue: [Array<number>, Array<number>, Array<any>, number];
<ide> _successCallbacks: Array<?Function>;
<ide> _failureCallbacks: Array<?Function>;
<ide> class MessageQueue {
<ide> this._remoteModuleTable = {};
<ide> this._remoteMethodTable = {};
<ide> }
<del>
<del> (this:any).callFunctionReturnFlushedQueue = this.callFunctionReturnFlushedQueue.bind(this);
<del> (this:any).callFunctionReturnResultAndFlushedQueue = this.callFunctionReturnResultAndFlushedQueue.bind(this);
<del> (this:any).flushedQueue = this.flushedQueue.bind(this);
<del> (this:any).invokeCallbackAndReturnFlushedQueue = this.invokeCallbackAndReturnFlushedQueue.bind(this);
<ide> }
<ide>
<ide> /**
<ide> * Public APIs
<ide> */
<del>
<del> static spy(spyOrToggle: boolean|(data: SpyData) => void){
<del> if (spyOrToggle === true){
<add> static spy(spyOrToggle: boolean | ((data: SpyData) => void)) {
<add> if (spyOrToggle === true) {
<ide> MessageQueue.prototype.__spy = info => {
<del> console.log(`${info.type === TO_JS ? 'N->JS' : 'JS->N'} : ` +
<del> `${info.module ? (info.module + '.') : ''}${info.method}` +
<del> `(${JSON.stringify(info.args)})`);
<add> console.log(
<add> `${info.type === TO_JS ? 'N->JS' : 'JS->N'} : ` +
<add> `${info.module ? info.module + '.' : ''}${info.method}` +
<add> `(${JSON.stringify(info.args)})`,
<add> );
<ide> };
<ide> } else if (spyOrToggle === false) {
<ide> MessageQueue.prototype.__spy = null;
<ide> class MessageQueue {
<ide> }
<ide> }
<ide>
<del> callFunctionReturnFlushedQueue(module: string, method: string, args: Array<any>) {
<add> callFunctionReturnFlushedQueue = (
<add> module: string,
<add> method: string,
<add> args: Array<any>,
<add> ) => {
<ide> this.__guard(() => {
<ide> this.__callFunction(module, method, args);
<ide> });
<ide>
<ide> return this.flushedQueue();
<del> }
<add> };
<ide>
<del> callFunctionReturnResultAndFlushedQueue(module: string, method: string, args: Array<any>) {
<add> callFunctionReturnResultAndFlushedQueue = (
<add> module: string,
<add> method: string,
<add> args: Array<any>,
<add> ) => {
<ide> let result;
<ide> this.__guard(() => {
<ide> result = this.__callFunction(module, method, args);
<ide> });
<ide>
<ide> return [result, this.flushedQueue()];
<del> }
<add> };
<ide>
<del> invokeCallbackAndReturnFlushedQueue(cbID: number, args: Array<any>) {
<add> invokeCallbackAndReturnFlushedQueue = (cbID: number, args: Array<any>) => {
<ide> this.__guard(() => {
<ide> this.__invokeCallback(cbID, args);
<ide> });
<ide>
<ide> return this.flushedQueue();
<del> }
<add> };
<ide>
<del> flushedQueue() {
<add> flushedQueue = () => {
<ide> this.__guard(() => {
<ide> this.__callImmediates();
<ide> });
<ide>
<ide> const queue = this._queue;
<ide> this._queue = [[], [], [], this._callID];
<ide> return queue[0].length ? queue : null;
<del> }
<add> };
<ide>
<ide> getEventLoopRunningTime() {
<ide> return new Date().getTime() - this._eventLoopStartTime;
<ide> class MessageQueue {
<ide>
<ide> registerLazyCallableModule(name: string, factory: void => Object) {
<ide> let module: Object;
<del> let getValue: ?(void => Object) = factory;
<add> let getValue: ?(void) => Object = factory;
<ide> this._lazyCallableModules[name] = () => {
<ide> if (getValue) {
<ide> module = getValue();
<ide> class MessageQueue {
<ide> return getValue ? getValue() : null;
<ide> }
<ide>
<del> enqueueNativeCall(moduleID: number, methodID: number, params: Array<any>, onFail: ?Function, onSucc: ?Function) {
<add> enqueueNativeCall(
<add> moduleID: number,
<add> methodID: number,
<add> params: Array<any>,
<add> onFail: ?Function,
<add> onSucc: ?Function,
<add> ) {
<ide> if (onFail || onSucc) {
<ide> if (__DEV__) {
<ide> this._debugInfo[this._callID] = [moduleID, methodID];
<ide> class MessageQueue {
<ide>
<ide> if (__DEV__) {
<ide> global.nativeTraceBeginAsyncFlow &&
<del> global.nativeTraceBeginAsyncFlow(TRACE_TAG_REACT_APPS, 'native', this._callID);
<add> global.nativeTraceBeginAsyncFlow(
<add> TRACE_TAG_REACT_APPS,
<add> 'native',
<add> this._callID,
<add> );
<ide> }
<ide> this._callID++;
<ide>
<ide> class MessageQueue {
<ide> JSON.stringify(params);
<ide>
<ide> // The params object should not be mutated after being queued
<del> deepFreezeAndThrowOnMutationInDev((params:any));
<add> deepFreezeAndThrowOnMutationInDev((params: any));
<ide> }
<ide> this._queue[PARAMS].push(params);
<ide>
<ide> const now = new Date().getTime();
<del> if (global.nativeFlushQueueImmediate &&
<del> (now - this._lastFlush >= MIN_TIME_BETWEEN_FLUSHES_MS ||
<del> this._inCall === 0)) {
<add> if (
<add> global.nativeFlushQueueImmediate &&
<add> (now - this._lastFlush >= MIN_TIME_BETWEEN_FLUSHES_MS ||
<add> this._inCall === 0)
<add> ) {
<ide> var queue = this._queue;
<ide> this._queue = [[], [], [], this._callID];
<ide> this._lastFlush = now;
<ide> global.nativeFlushQueueImmediate(queue);
<ide> }
<ide> Systrace.counterEvent('pending_js_to_native_queue', this._queue[0].length);
<del> if (__DEV__ && this.__spy && isFinite(moduleID)) {
<del> this.__spy(
<del> { type: TO_NATIVE,
<del> module: this._remoteModuleTable[moduleID],
<del> method: this._remoteMethodTable[moduleID][methodID],
<del> args: params }
<add>
<add> if (this.__spy) {
<add> this.__spyNativeCall(moduleID, methodID, params.slice(0, -2), {
<add> failCbId: onFail ? params[params.length - 2] : -1,
<add> successCbId: onSucc ? params[params.length - 1] : -1,
<add> });
<add> }
<add> }
<add>
<add> callSyncHook(moduleID: number, methodID: number, args: Array<any>) {
<add> if (__DEV__) {
<add> invariant(
<add> global.nativeCallSyncHook,
<add> 'Calling synchronous methods on native ' +
<add> 'modules is not supported in Chrome.\n\n Consider providing alternative ' +
<add> 'methods to expose this method in debug mode, e.g. by exposing constants ' +
<add> 'ahead-of-time.',
<ide> );
<del> } else if (this.__spy) {
<del> this.__spy({type: TO_NATIVE, module: moduleID + '', method: methodID, args: params});
<ide> }
<add> const returnValue = global.nativeCallSyncHook(moduleID, methodID, args);
<add>
<add> if (this.__spy) {
<add> this.__spyNativeCall(moduleID, methodID, args, {
<add> isSync: true,
<add> returnValue,
<add> });
<add> }
<add> return returnValue;
<ide> }
<ide>
<ide> createDebugLookup(moduleID: number, name: string, methods: Array<string>) {
<ide> class MessageQueue {
<ide> this._eventLoopStartTime = this._lastFlush;
<ide> Systrace.beginEvent(`${module}.${method}()`);
<ide> if (this.__spy) {
<del> this.__spy({ type: TO_JS, module, method, args});
<add> this.__spy({
<add> type: TO_JS,
<add> module,
<add> method,
<add> isSync: false,
<add> failCbId: -1,
<add> successCbId: -1,
<add> args,
<add> });
<ide> }
<ide> const moduleMethods = this.getCallableModule(module);
<ide> invariant(
<ide> !!moduleMethods,
<ide> 'Module %s is not a registered callable module (calling %s)',
<del> module, method
<add> module,
<add> method,
<ide> );
<ide> invariant(
<ide> !!moduleMethods[method],
<ide> 'Method %s does not exist on module %s',
<del> method, module
<add> method,
<add> module,
<ide> );
<ide> const result = moduleMethods[method].apply(moduleMethods, args);
<ide> Systrace.endEvent();
<ide> class MessageQueue {
<ide>
<ide> // The rightmost bit of cbID indicates fail (0) or success (1), the other bits are the callID shifted left.
<ide> const callID = cbID >>> 1;
<del> const callback = (cbID & 1) ? this._successCallbacks[callID] : this._failureCallbacks[callID];
<add> const isSuccess = cbID & 1;
<add> const callback = isSuccess
<add> ? this._successCallbacks[callID]
<add> : this._failureCallbacks[callID];
<ide>
<ide> if (__DEV__) {
<ide> const debug = this._debugInfo[callID];
<ide> class MessageQueue {
<ide> if (!callback) {
<ide> let errorMessage = `Callback with id ${cbID}: ${module}.${method}() not found`;
<ide> if (method) {
<del> errorMessage = `The callback ${method}() exists in module ${module}, `
<del> + 'but only one callback may be registered to a function in a native module.';
<add> errorMessage =
<add> `The callback ${method}() exists in module ${module}, ` +
<add> 'but only one callback may be registered to a function in a native module.';
<ide> }
<del> invariant(
<del> callback,
<del> errorMessage
<del> );
<add> invariant(callback, errorMessage);
<ide> }
<del> const profileName = debug ? '<callback for ' + module + '.' + method + '>' : cbID;
<del> if (callback && this.__spy) {
<del> this.__spy({ type: TO_JS, module:null, method:profileName, args });
<add> const profileName = debug
<add> ? '<callback for ' + module + '.' + method + '>'
<add> : cbID + '';
<add> console.log(
<add> 'invokeCallback',
<add> cbID,
<add> debug,
<add> callback,
<add> module,
<add> method,
<add> profileName,
<add> );
<add> if (this.__spy) {
<add> this.__spy({
<add> type: TO_JS,
<add> module: null,
<add> method: profileName,
<add> isSync: false,
<add> args,
<add> failCbId: isSuccess ? -1 : cbID,
<add> successCbId: isSuccess ? cbID : -1,
<add> });
<ide> }
<ide> Systrace.beginEvent(
<del> `MessageQueue.invokeCallback(${profileName}, ${stringifySafe(args)})`);
<add> `MessageQueue.invokeCallback(${profileName}, ${stringifySafe(args)})`,
<add> );
<ide> }
<ide>
<ide> if (!callback) {
<ide> class MessageQueue {
<ide> Systrace.endEvent();
<ide> }
<ide> }
<add>
<add> __spyNativeCall(
<add> moduleID: number,
<add> methodID: number,
<add> args: any[],
<add> params: any,
<add> ) {
<add> const spy = this.__spy;
<add> if (!spy) {
<add> return;
<add> }
<add>
<add> let moduleName = moduleID + '';
<add> let methodName = methodID;
<add> if (__DEV__ && isFinite(moduleID)) {
<add> moduleName = this._remoteModuleTable[moduleID];
<add> methodName = this._remoteMethodTable[moduleID][methodID];
<add> }
<add>
<add> spy({
<add> type: TO_NATIVE,
<add> isSync: false,
<add> module: moduleName,
<add> method: methodName,
<add> failCbId: -1,
<add> successCbId: -1,
<add> args,
<add> ...params,
<add> });
<add> }
<ide> }
<ide>
<ide> module.exports = MessageQueue;
<ide><path>Libraries/BatchedBridge/NativeModules.js
<ide> function genMethod(moduleID: number, methodID: number, type: MethodType) {
<ide> };
<ide> } else if (type === 'sync') {
<ide> fn = function(...args: Array<any>) {
<del> if (__DEV__) {
<del> invariant(global.nativeCallSyncHook, 'Calling synchronous methods on native ' +
<del> 'modules is not supported in Chrome.\n\n Consider providing alternative ' +
<del> 'methods to expose this method in debug mode, e.g. by exposing constants ' +
<del> 'ahead-of-time.');
<del> }
<del> return global.nativeCallSyncHook(moduleID, methodID, args);
<add> return BatchedBridge.callSyncHook(moduleID, methodID, args);
<ide> };
<ide> } else {
<ide> fn = function(...args: Array<any>) {
<ide><path>Libraries/Interaction/BridgeSpyStallHandler.js
<ide> const BridgeSpyStallHandler = {
<ide> }
<ide> }
<ide> return `${info.type === TO_JS ? 'N->JS' : 'JS->N'} : ` +
<del> `${info.module ? (info.module + '.') : ''}${info.method}(${args})`;
<add> `${info.module ? (info.module + '.') : ''}${info.method}(${JSON.stringify(args)})`;
<ide> }),
<ide> );
<ide> }, | 4 |
Go | Go | add retry checks to testswarmpublishadd | 7bd1c1195998c10c732ccfa67c568e634d58166e | <ide><path>integration-cli/daemon_swarm.go
<ide> func (d *SwarmDaemon) checkLeader(c *check.C) (interface{}, check.CommentInterfa
<ide> }
<ide> return fmt.Errorf("no leader"), check.Commentf("could not find leader")
<ide> }
<add>
<add>func (d *SwarmDaemon) cmdRetryOutOfSequence(args ...string) (string, error) {
<add> for i := 0; ; i++ {
<add> out, err := d.Cmd(args...)
<add> if err != nil {
<add> if strings.Contains(err.Error(), "update out of sequence") {
<add> if i < 10 {
<add> continue
<add> }
<add> }
<add> }
<add> return out, err
<add> }
<add>}
<ide><path>integration-cli/docker_cli_swarm_test.go
<ide> func (s *DockerSwarmSuite) TestSwarmPublishAdd(c *check.C) {
<ide> out, err = d.Cmd("service", "update", "--publish-add", "80:80", name)
<ide> c.Assert(err, checker.IsNil)
<ide>
<del> out, err = d.Cmd("service", "update", "--publish-add", "80:80", name)
<add> out, err = d.cmdRetryOutOfSequence("service", "update", "--publish-add", "80:80", name)
<ide> c.Assert(err, checker.IsNil)
<ide>
<del> out, err = d.Cmd("service", "update", "--publish-add", "80:80", "--publish-add", "80:20", name)
<add> out, err = d.cmdRetryOutOfSequence("service", "update", "--publish-add", "80:80", "--publish-add", "80:20", name)
<ide> c.Assert(err, checker.NotNil)
<ide>
<del> out, err = d.Cmd("service", "update", "--publish-add", "80:20", name)
<add> out, err = d.cmdRetryOutOfSequence("service", "update", "--publish-add", "80:20", name)
<ide> c.Assert(err, checker.IsNil)
<ide>
<ide> out, err = d.Cmd("service", "inspect", "--format", "{{ .Spec.EndpointSpec.Ports }}", name) | 2 |
Go | Go | fix tests which didn't cleanup properly | acf58362cb957bf4d02af460935a9c5febd112f4 | <ide><path>auth/auth_test.go
<ide> func TestCreateAccount(t *testing.T) {
<ide> }
<ide>
<ide> func setupTempConfigFile() (*ConfigFile, error) {
<del> root, err := ioutil.TempDir("", "docker-test")
<add> root, err := ioutil.TempDir("", "docker-test-auth")
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide> func TestSameAuthDataPostSave(t *testing.T) {
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<add> defer os.RemoveAll(configFile.rootPath)
<ide>
<ide> err = SaveConfig(configFile)
<ide> if err != nil {
<ide> func TestResolveAuthConfigIndexServer(t *testing.T) {
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<add> defer os.RemoveAll(configFile.rootPath)
<ide>
<ide> for _, registry := range []string{"", IndexServerAddress()} {
<ide> resolved := configFile.ResolveAuthConfig(registry)
<ide> func TestResolveAuthConfigFullURL(t *testing.T) {
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<add> defer os.RemoveAll(configFile.rootPath)
<ide>
<ide> registryAuth := AuthConfig{
<ide> Username: "foo-user",
<ide><path>container_test.go
<ide> func BenchmarkRunParallel(b *testing.B) {
<ide> }
<ide>
<ide> func tempDir(t *testing.T) string {
<del> tmpDir, err := ioutil.TempDir("", "docker-test")
<add> tmpDir, err := ioutil.TempDir("", "docker-test-container")
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> } | 2 |
Javascript | Javascript | display error messages on more problems | b40af3555b2be14311c6d7cf4cc28dc750d72387 | <ide><path>src/core.js
<ide> function getPdf(arg, callback) {
<ide> if ('error' in params)
<ide> xhr.onerror = params.error || undefined;
<ide>
<del> xhr.onreadystatechange = function getPdfOnreadystatechange() {
<del> if (xhr.readyState === 4 && xhr.status === xhr.expected) {
<del> var data = (xhr.mozResponseArrayBuffer || xhr.mozResponse ||
<del> xhr.responseArrayBuffer || xhr.response);
<del> callback(data);
<add> xhr.onreadystatechange = function getPdfOnreadystatechange(e) {
<add> if (xhr.readyState === 4) {
<add> if (xhr.status === xhr.expected) {
<add> var data = (xhr.mozResponseArrayBuffer || xhr.mozResponse ||
<add> xhr.responseArrayBuffer || xhr.response);
<add> callback(data);
<add> } else {
<add> params.error(e);
<add> }
<ide> }
<ide> };
<ide> xhr.send(null);
<ide><path>web/viewer.js
<ide> var PDFView = {
<ide> if (evt.lengthComputable)
<ide> self.progress(evt.loaded / evt.total);
<ide> },
<del> error: self.error
<add> error: function getPdfError(e) {
<add> var loadingIndicator = document.getElementById('loading');
<add> loadingIndicator.innerHTML = 'Error';
<add> var moreInfo = {
<add> message: 'Unexpected server response of ' + e.target.status + '.'
<add> };
<add> self.error('An error occurred while loading the PDF.', moreInfo);
<add> }
<ide> },
<ide> function getPdfLoad(data) {
<ide> self.loading = true;
<ide> var PDFView = {
<ide> return '';
<ide> },
<ide>
<del> error: function pdfViewError(message, error) {
<add> /**
<add> * Show the error box.
<add> * @param {String} message A message that is human readable.
<add> * @param {Object} moreInfo (optional) Further information about the error
<add> * that is more technical. Should have a 'message'
<add> * and optionally a 'stack' property.
<add> */
<add> error: function pdfViewError(message, moreInfo) {
<ide> var errorWrapper = document.getElementById('errorWrapper');
<ide> errorWrapper.removeAttribute('hidden');
<ide>
<ide> var errorMessage = document.getElementById('errorMessage');
<ide> errorMessage.innerHTML = message;
<ide>
<del> if (error) {
<del> var errorMoreInfo = document.getElementById('errorMoreInfo');
<del> var moreInfoButton = document.getElementById('errorShowMore');
<del> var lessInfoButton = document.getElementById('errorShowLess');
<del> var closeButton = document.getElementById('errorClose');
<del> moreInfoButton.onclick = function() {
<del> errorMoreInfo.removeAttribute('hidden');
<del> moreInfoButton.setAttribute('hidden', 'true');
<del> lessInfoButton.removeAttribute('hidden');
<del> };
<del> lessInfoButton.onclick = function() {
<del> errorMoreInfo.setAttribute('hidden', 'true');
<del> moreInfoButton.removeAttribute('hidden');
<del> lessInfoButton.setAttribute('hidden', 'true');
<del> };
<del> closeButton.onclick = function() {
<del> errorWrapper.setAttribute('hidden', 'true');
<del> };
<add> var closeButton = document.getElementById('errorClose');
<add> closeButton.onclick = function() {
<add> errorWrapper.setAttribute('hidden', 'true');
<add> };
<add>
<add> var errorMoreInfo = document.getElementById('errorMoreInfo');
<add> var moreInfoButton = document.getElementById('errorShowMore');
<add> var lessInfoButton = document.getElementById('errorShowLess');
<add> moreInfoButton.onclick = function() {
<add> errorMoreInfo.removeAttribute('hidden');
<add> moreInfoButton.setAttribute('hidden', 'true');
<add> lessInfoButton.removeAttribute('hidden');
<add> };
<add> lessInfoButton.onclick = function() {
<add> errorMoreInfo.setAttribute('hidden', 'true');
<ide> moreInfoButton.removeAttribute('hidden');
<del> errorMoreInfo.innerHTML = error.message + '\n' + error.stack;
<add> lessInfoButton.setAttribute('hidden', 'true');
<add> };
<add> moreInfoButton.removeAttribute('hidden');
<add> lessInfoButton.setAttribute('hidden', 'true');
<add> errorMoreInfo.innerHTML = 'PDF.JS Build: ' + PDFJS.build + '\n';
<add>
<add> if (moreInfo) {
<add> errorMoreInfo.innerHTML += 'Message: ' + moreInfo.message;
<add> if (moreInfo.stack)
<add> errorMoreInfo.innerHTML += '\n' + 'Stack: ' + moreInfo.stack;
<ide> }
<ide> },
<ide>
<ide> var PDFView = {
<ide> };
<ide> }
<ide>
<add> var errorWrapper = document.getElementById('errorWrapper');
<add> errorWrapper.setAttribute('hidden', 'true');
<add>
<ide> var loadingIndicator = document.getElementById('loading');
<ide> loadingIndicator.setAttribute('hidden', 'true');
<ide>
<ide> var PDFView = {
<ide> while (container.hasChildNodes())
<ide> container.removeChild(container.lastChild);
<ide>
<del> var pdf = new PDFJS.PDFDoc(data);
<add> try {
<add> var pdf = new PDFJS.PDFDoc(data);
<add> } catch (e) {
<add> this.error('An error occurred while reading the PDF.', e);
<add> }
<ide> var pagesCount = pdf.numPages;
<ide> document.getElementById('numPages').innerHTML = pagesCount;
<ide> document.getElementById('pageNumber').max = pagesCount;
<ide> var PageView = function pageView(container, content, id, pageWidth, pageHeight,
<ide> this.onAfterDraw();
<ide> }).bind(this),
<ide> function pageViewErrorback(e) {
<del> PDFView.error('An error occured while rendering the page.', e);
<add> PDFView.error('An error occurred while rendering the page.', e);
<ide> }
<ide> );
<ide> | 2 |
Python | Python | add test for object array creation | 747579e371dc1515d76df0a10f474f58786ebe22 | <ide><path>numpy/core/tests/test_regression.py
<ide> def check_chararray_rstrip(self,level=rlevel):
<ide> x[0] = 'a '
<ide> x = x.rstrip()
<ide> assert_equal(x[0], 'a')
<add>
<add> def check_object_array_shape(self,level=rlevel):
<add> """Ticket #239"""
<add> assert_equal(N.array([[1,2],3,4],dtype=object).shape, (3,))
<add> assert_equal(N.array([[1,2],[3,4]],dtype=object).shape, (2,2))
<add> #assert_equal(N.array([(1,2),(3,4)],dtype=object).shape, (2,))
<add> assert_equal(N.array([],dtype=object).shape, ())
<add> assert_equal(N.array([[],[],[]],dtype=object).shape, (3,))
<add> assert_equal(N.array([[3,4],[5,6],None],dtype=object).shape, (3,))
<ide>
<ide> if __name__ == "__main__":
<ide> NumpyTest().run() | 1 |
Ruby | Ruby | add magic token to hide commands from man page | 9b36e8377142241218cb472dcaf64561f70b96e9 | <ide><path>Library/Homebrew/cmd/help.rb
<ide> def command_help(path)
<ide> line.slice(2..-1).
<ide> sub(/^ \* /, "#{Tty.highlight}brew#{Tty.reset} ").
<ide> gsub(/`(.*?)`/, "#{Tty.highlight}\\1#{Tty.reset}").
<del> gsub(/<(.*?)>/, "#{Tty.em}\\1#{Tty.reset}")
<del> end.join
<add> gsub(/<(.*?)>/, "#{Tty.em}\\1#{Tty.reset}").
<add> gsub("@hide_from_man_page", "")
<add> end.join.strip
<ide> end
<ide> end
<ide> end
<ide><path>Library/Homebrew/cmd/man.rb
<ide> def build_man_page
<ide> map { |line| line.slice(2..-1) }.
<ide> join
<ide> }.
<del> reject { |s| s.strip.empty? }
<add> reject { |s| s.strip.empty? || s.include?("@hide_from_man_page") }
<ide>
<ide> variables[:maintainers] = (HOMEBREW_REPOSITORY/"README.md").
<ide> read[/Homebrew's current maintainers are (.*)\./, 1].
<ide><path>Library/Homebrew/cmd/tests.rb
<add>#: @hide_from_man_page
<ide> #: * `tests` [`-v`] [`--coverage`] [`--generic`] [`--no-compat`] [`--only=`<test_script/test_method>] [`--seed` <seed>] [`--trace`]:
<ide> #: Run Homebrew's unit and integration tests.
<ide> | 3 |
Javascript | Javascript | add test for reading a large file through a pipe | 5ecdc0314d87354166b282501435b2f6fd2248ab | <ide><path>test/parallel/test-fs-readfile-pipe-large.js
<add>var common = require('../common');
<add>var assert = require('assert');
<add>var path = require('path');
<add>
<add>// simulate `cat readfile.js | node readfile.js`
<add>
<add>// TODO: Have some way to make this work on windows.
<add>if (process.platform === 'win32') {
<add> console.error('No /dev/stdin on windows. Skipping test.');
<add> process.exit();
<add>}
<add>
<add>var fs = require('fs');
<add>
<add>var filename = path.join(common.tmpDir, '/readfile_pipe_large_test.txt');
<add>var dataExpected = new Array(1000000).join('a');
<add>fs.writeFileSync(filename, dataExpected);
<add>
<add>if (process.argv[2] === 'child') {
<add> fs.readFile('/dev/stdin', function(er, data) {
<add> if (er) throw er;
<add> process.stdout.write(data);
<add> });
<add> return;
<add>}
<add>
<add>var exec = require('child_process').exec;
<add>var f = JSON.stringify(__filename);
<add>var node = JSON.stringify(process.execPath);
<add>var cmd = 'cat ' + filename + ' | ' + node + ' ' + f + ' child';
<add>exec(cmd, { maxBuffer: 1000000 }, function(err, stdout, stderr) {
<add> if (err) console.error(err);
<add> assert(!err, 'it exits normally');
<add> assert(stdout === dataExpected, 'it reads the file and outputs it');
<add> assert(stderr === '', 'it does not write to stderr');
<add> console.log('ok');
<add>});
<add>
<add>process.on('exit', function() {
<add> fs.unlinkSync(filename);
<add>});
<ide><path>test/parallel/test-fs-readfilesync-pipe-large.js
<add>var common = require('../common');
<add>var assert = require('assert');
<add>var path = require('path');
<add>
<add>// simulate `cat readfile.js | node readfile.js`
<add>
<add>// TODO: Have some way to make this work on windows.
<add>if (process.platform === 'win32') {
<add> console.error('No /dev/stdin on windows. Skipping test.');
<add> process.exit();
<add>}
<add>
<add>var fs = require('fs');
<add>
<add>var filename = path.join(common.tmpDir, '/readfilesync_pipe_large_test.txt');
<add>var dataExpected = new Array(1000000).join('a');
<add>fs.writeFileSync(filename, dataExpected);
<add>
<add>if (process.argv[2] === 'child') {
<add> process.stdout.write(fs.readFileSync('/dev/stdin', 'utf8'));
<add> return;
<add>}
<add>
<add>var exec = require('child_process').exec;
<add>var f = JSON.stringify(__filename);
<add>var node = JSON.stringify(process.execPath);
<add>var cmd = 'cat ' + filename + ' | ' + node + ' ' + f + ' child';
<add>exec(cmd, { maxBuffer: 1000000 }, function(err, stdout, stderr) {
<add> if (err) console.error(err);
<add> assert(!err, 'it exits normally');
<add> assert(stdout === dataExpected, 'it reads the file and outputs it');
<add> assert(stderr === '', 'it does not write to stderr');
<add> console.log('ok');
<add>});
<add>
<add>process.on('exit', function() {
<add> fs.unlinkSync(filename);
<add>}); | 2 |
Go | Go | implement docker pause with standalone client lib | 55333e8f9018585f28f13231a3073e2746d7c969 | <ide><path>api/client/lib/pause.go
<add>package lib
<add>
<add>// ContainerPause pauses the main process of a given container without terminating it.
<add>func (cli *Client) ContainerPause(containerID string) error {
<add> resp, err := cli.post("/containers/"+containerID+"/pause", nil, nil, nil)
<add> ensureReaderClosed(resp)
<add> return err
<add>}
<ide><path>api/client/pause.go
<ide> func (cli *DockerCli) CmdPause(args ...string) error {
<ide>
<ide> var errNames []string
<ide> for _, name := range cmd.Args() {
<del> if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/pause", name), nil, nil)); err != nil {
<add> if err := cli.client.ContainerPause(name); err != nil {
<ide> fmt.Fprintf(cli.err, "%s\n", err)
<ide> errNames = append(errNames, name)
<ide> } else { | 2 |
Javascript | Javascript | add a default content type for path requests | f9b897de4b5cc438515cbb54519fbdf6242f5858 | <ide><path>src/ng/http.js
<ide> function isSuccess(status) {
<ide> function $HttpProvider() {
<ide> var JSON_START = /^\s*(\[|\{[^\{])/,
<ide> JSON_END = /[\}\]]\s*$/,
<del> PROTECTION_PREFIX = /^\)\]\}',?\n/;
<add> PROTECTION_PREFIX = /^\)\]\}',?\n/,
<add> CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': 'application/json;charset=utf-8'};
<ide>
<ide> var defaults = this.defaults = {
<ide> // transform incoming response data
<ide> function $HttpProvider() {
<ide> common: {
<ide> 'Accept': 'application/json, text/plain, */*'
<ide> },
<del> post: {'Content-Type': 'application/json;charset=utf-8'},
<del> put: {'Content-Type': 'application/json;charset=utf-8'}
<add> post: CONTENT_TYPE_APPLICATION_JSON,
<add> put: CONTENT_TYPE_APPLICATION_JSON,
<add> patch: CONTENT_TYPE_APPLICATION_JSON
<ide> },
<ide>
<ide> xsrfCookieName: 'XSRF-TOKEN',
<ide> function $HttpProvider() {
<ide> *
<ide> * A custom default cache built with $cacheFactory can be provided in $http.defaults.cache.
<ide> * To skip it, set configuration property `cache` to `false`.
<del> *
<add> *
<ide> *
<ide> * # Interceptors
<ide> *
<ide> function $HttpProvider() {
<ide>
<ide>
<ide> if ((config.cache || defaults.cache) && config.cache !== false && config.method == 'GET') {
<del> cache = isObject(config.cache) ? config.cache
<del> : isObject(defaults.cache) ? defaults.cache
<add> cache = isObject(config.cache) ? config.cache
<add> : isObject(defaults.cache) ? defaults.cache
<ide> : defaultCache;
<ide> }
<ide>
<ide><path>test/ng/httpSpec.js
<ide> describe('$http', function() {
<ide> $httpBackend.flush();
<ide> });
<ide>
<add> it('should set default headers for PATCH request', function() {
<add> $httpBackend.expect('PATCH', '/url', 'messageBody', function(headers) {
<add> return headers['Accept'] == 'application/json, text/plain, */*' &&
<add> headers['Content-Type'] == 'application/json;charset=utf-8';
<add> }).respond('');
<add>
<add> $http({url: '/url', method: 'PATCH', headers: {}, data: 'messageBody'});
<add> $httpBackend.flush();
<add> });
<ide>
<ide> it('should set default headers for custom HTTP method', function() {
<ide> $httpBackend.expect('FOO', '/url', undefined, function(headers) { | 2 |
Text | Text | fix incorrect link to babel preset | 045cd9e248731fc1aa55b37eb9735b914a7b507a | <ide><path>docs/api/createStore.md
<ide> console.log(store.getState())
<ide>
<ide> * It is up to you to choose the state format. You can use plain objects or something like [Immutable](http://facebook.github.io/immutable-js/). If you’re not sure, start with plain objects.
<ide>
<del>* If your state is a plain object, make sure you never mutate it! For example, instead of returning something like `Object.assign(state, newData)` from your reducers, return `Object.assign({}, state, newData)`. This way you don’t override the previous `state`. You can also write `return { ...state, ...newData }` if you enable [ES7 object spread proposal](https://github.com/sebmarkbage/ecmascript-rest-spread) with [Babel stage 1](https://babeljs.io/docs/plugins/preset-stage-1/).
<add>* If your state is a plain object, make sure you never mutate it! For example, instead of returning something like `Object.assign(state, newData)` from your reducers, return `Object.assign({}, state, newData)`. This way you don’t override the previous `state`. You can also write `return { ...state, ...newData }` if you enable [ES7 object spread proposal](https://github.com/sebmarkbage/ecmascript-rest-spread) with [Babel transform-object-rest-spread plugin](http://babeljs.io/docs/plugins/transform-object-rest-spread/).
<ide>
<ide> * For universal apps that run on the server, create a store instance with every request so that they are isolated. Dispatch a few data fetching actions to a store instance and wait for them to complete before rendering the app on the server.
<ide> | 1 |
Text | Text | use a dot before patch release number for rcs | d46ac110cd540090392adf30668fdc00a7001aea | <ide><path>Releases.md
<ide> Before cutting a release branch, make sure CI systems [Travis](https://travis-ci
<ide>
<ide> Before executing the following script, make sure you have:
<ide> - An Android emulator / Genymotion device running
<del>- No packager running in any of the projects
<add>- No packager running in any of the projects
<ide>
<ide> ```bash
<ide> ./scripts/test-manual-e2e.sh
<ide> After `npm install` completes, the script prints a set of manual checks you have
<ide> Run:
<ide>
<ide> ```bash
<del>git checkout -b <version_you_are_releasing>-stable
<add>git checkout -b <version_you_are_releasing>-stable
<ide> # e.g. git checkout -b 0.22-stable
<ide>
<del>node ./scripts/bump-oss-version.js <exact-version_you_are_releasing>
<add>node ./scripts/bump-oss-version.js <exact-version_you_are_releasing>
<ide> # e.g. node ./scripts/bump-oss-version.js 0.22.0-rc
<ide>
<ide> git push origin <version_you_are_releasing>-stable --tags
<ide> https://github.com/facebook/react-native/compare/0.21-stable...0.22-stable
<ide>
<ide> **Note**: This only shows **250** commits, if there are more use git.
<ide>
<del>When making a list of changes, ignore docs, showcase updates and minor typos.
<add>When making a list of changes, ignore docs, showcase updates and minor typos.
<ide>
<ide> Sometimes commit messages might be really short / confusing - try rewording them where it makes sense. Below are few examples:
<ide> - `Fix logging reported by RUN_JS_BUNDLE` -> `Fix systrace logging of RUN_JS_BUNDLE event`
<ide> A good way to do this is to create a github issue and post about it so people ca
<ide>
<ide> -------------------
<ide>
<del>## How to release an RC update (e.g. 0.22.0-rc1, 0.22.0-rc2)
<add>## How to release an RC update (e.g. 0.28.0-rc.1, 0.28.0-rc.2)
<ide>
<ide> After cherry-picking 1-2 bug fixes, it is a good idea to do a new RC release so that people can test again. Having a few RC releases can also help people bisect in case we cherry-pick a bad commit by mistake.
<ide>
<ide> git cherry-pick commitHash1
<ide> If everything worked:
<ide>
<ide> ```bash
<del>node ./scripts/bump-oss-version.js <exact_version_you_are_releasing>
<del># e.g. node ./scripts/bump-oss-version.js 0.22.0-rc1
<add>node ./scripts/bump-oss-version.js <exact_version_you_are_releasing>
<add># e.g. node ./scripts/bump-oss-version.js 0.28.0-rc.1
<ide>
<del>git push origin version_you_are_releasing-stable --tags
<add>git push origin version_you_are_releasing-stable --tags
<ide> # e.g. git push origin 0.22-stable --tags
<ide> ````
<ide>
<ide> git cherry-pick commitHash1
<ide> If everything worked:
<ide>
<ide> ```bash
<del>node ./scripts/bump-oss-version.js <exact_version_you_are_releasing>
<add>node ./scripts/bump-oss-version.js <exact_version_you_are_releasing>
<ide> # e.g. node ./scripts/bump-oss-version.js 0.22.0
<ide>
<ide> git tag -d latest
<ide> git push origin :latest
<ide>
<del>git tag latest
<add>git tag latest
<ide> # The latest tag marks when to regenerate the website.
<ide>
<ide> git push origin version_you_are_releasing-stable --tags | 1 |
Mixed | Ruby | remove recordtaghelper, add extraction notices | 01e94ef3b12922b77e55a067866d7a1fa62f1759 | <ide><path>actionview/CHANGELOG.md
<add>* Extracted `ActionView::Helpers::RecordTagHelper` to external gem
<add> (`record_tag_helper`) and added removal notices.
<add>
<add> *Todd Bealmear*
<add>
<ide> * Allow to pass a string value to `size` option in `image_tag` and `video_tag`.
<ide>
<ide> This makes the behavior more consistent with `width` or `height` options.
<ide><path>actionview/lib/action_view/helpers/form_helper.rb
<ide> require 'action_view/helpers/form_tag_helper'
<ide> require 'action_view/helpers/active_model_helper'
<ide> require 'action_view/model_naming'
<add>require 'action_view/record_identifier'
<ide> require 'active_support/core_ext/module/attribute_accessors'
<ide> require 'active_support/core_ext/hash/slice'
<ide> require 'active_support/core_ext/string/output_safety'
<ide> module FormHelper
<ide> include FormTagHelper
<ide> include UrlHelper
<ide> include ModelNaming
<add> include RecordIdentifier
<ide>
<ide> # Creates a form that allows the user to create or update the attributes
<ide> # of a specific model object.
<ide><path>actionview/lib/action_view/helpers/record_tag_helper.rb
<del>require 'action_view/record_identifier'
<del>
<ide> module ActionView
<del> # = Action View Record Tag Helpers
<ide> module Helpers
<ide> module RecordTagHelper
<del> include ActionView::RecordIdentifier
<del>
<del> # Produces a wrapper DIV element with id and class parameters that
<del> # relate to the specified Active Record object. Usage example:
<del> #
<del> # <%= div_for(@person, class: "foo") do %>
<del> # <%= @person.name %>
<del> # <% end %>
<del> #
<del> # produces:
<del> #
<del> # <div id="person_123" class="person foo"> Joe Bloggs </div>
<del> #
<del> # You can also pass an array of Active Record objects, which will then
<del> # get iterated over and yield each record as an argument for the block.
<del> # For example:
<del> #
<del> # <%= div_for(@people, class: "foo") do |person| %>
<del> # <%= person.name %>
<del> # <% end %>
<del> #
<del> # produces:
<del> #
<del> # <div id="person_123" class="person foo"> Joe Bloggs </div>
<del> # <div id="person_124" class="person foo"> Jane Bloggs </div>
<del> #
<del> def div_for(record, *args, &block)
<del> content_tag_for(:div, record, *args, &block)
<add> def div_for(*)
<add> raise NoMethodError, "The `div_for` method has been removed from " \
<add> "Rails. To continue using it, add the `record_tag_helper` gem to " \
<add> "your Gemfile:\n" \
<add> " gem 'record_tag_helper', '~> 1.0'\n" \
<add> "Consult the Rails upgrade guide for details."
<ide> end
<ide>
<del> # content_tag_for creates an HTML element with id and class parameters
<del> # that relate to the specified Active Record object. For example:
<del> #
<del> # <%= content_tag_for(:tr, @person) do %>
<del> # <td><%= @person.first_name %></td>
<del> # <td><%= @person.last_name %></td>
<del> # <% end %>
<del> #
<del> # would produce the following HTML (assuming @person is an instance of
<del> # a Person object, with an id value of 123):
<del> #
<del> # <tr id="person_123" class="person">....</tr>
<del> #
<del> # If you require the HTML id attribute to have a prefix, you can specify it:
<del> #
<del> # <%= content_tag_for(:tr, @person, :foo) do %> ...
<del> #
<del> # produces:
<del> #
<del> # <tr id="foo_person_123" class="person">...
<del> #
<del> # You can also pass an array of objects which this method will loop through
<del> # and yield the current object to the supplied block, reducing the need for
<del> # having to iterate through the object (using <tt>each</tt>) beforehand.
<del> # For example (assuming @people is an array of Person objects):
<del> #
<del> # <%= content_tag_for(:tr, @people) do |person| %>
<del> # <td><%= person.first_name %></td>
<del> # <td><%= person.last_name %></td>
<del> # <% end %>
<del> #
<del> # produces:
<del> #
<del> # <tr id="person_123" class="person">...</tr>
<del> # <tr id="person_124" class="person">...</tr>
<del> #
<del> # content_tag_for also accepts a hash of options, which will be converted to
<del> # additional HTML attributes. If you specify a <tt>:class</tt> value, it will be combined
<del> # with the default class name for your object. For example:
<del> #
<del> # <%= content_tag_for(:li, @person, class: "bar") %>...
<del> #
<del> # produces:
<del> #
<del> # <li id="person_123" class="person bar">...
<del> #
<del> def content_tag_for(tag_name, single_or_multiple_records, prefix = nil, options = nil, &block)
<del> options, prefix = prefix, nil if prefix.is_a?(Hash)
<del>
<del> Array(single_or_multiple_records).map do |single_record|
<del> content_tag_for_single_record(tag_name, single_record, prefix, options, &block)
<del> end.join("\n").html_safe
<add> def content_tag_for(*)
<add> raise NoMethodError, "The `content_tag_for` method has been removed from " \
<add> "Rails. To continue using it, add the `record_tag_helper` gem to " \
<add> "your Gemfile:\n" \
<add> " gem 'record_tag_helper', '~> 1.0'\n" \
<add> "Consult the Rails upgrade guide for details."
<ide> end
<del>
<del> private
<del>
<del> # Called by <tt>content_tag_for</tt> internally to render a content tag
<del> # for each record.
<del> def content_tag_for_single_record(tag_name, record, prefix, options, &block)
<del> options = options ? options.dup : {}
<del> options[:class] = [ dom_class(record, prefix), options[:class] ].compact
<del> options[:id] = dom_id(record, prefix)
<del>
<del> if block_given?
<del> content_tag(tag_name, capture(record, &block), options)
<del> else
<del> content_tag(tag_name, "", options)
<del> end
<del> end
<ide> end
<ide> end
<ide> end
<ide><path>actionview/test/template/record_tag_helper_test.rb
<ide> def setup
<ide> end
<ide>
<ide> def test_content_tag_for
<del> expected = %(<li class="record_tag_post" id="record_tag_post_45"></li>)
<del> actual = content_tag_for(:li, @post)
<del> assert_dom_equal expected, actual
<add> assert_raises(NoMethodError) { content_tag_for(:li, @post) }
<ide> end
<ide>
<del> def test_content_tag_for_prefix
<del> expected = %(<ul class="archived_record_tag_post" id="archived_record_tag_post_45"></ul>)
<del> actual = content_tag_for(:ul, @post, :archived)
<del> assert_dom_equal expected, actual
<del> end
<del>
<del> def test_content_tag_for_with_extra_html_options
<del> expected = %(<tr class="record_tag_post special" id="record_tag_post_45" style='background-color: #f0f0f0'></tr>)
<del> actual = content_tag_for(:tr, @post, class: "special", style: "background-color: #f0f0f0")
<del> assert_dom_equal expected, actual
<del> end
<del>
<del> def test_content_tag_for_with_array_css_class
<del> expected = %(<tr class="record_tag_post special odd" id="record_tag_post_45"></tr>)
<del> actual = content_tag_for(:tr, @post, class: ["special", "odd"])
<del> assert_dom_equal expected, actual
<del> end
<del>
<del> def test_content_tag_for_with_prefix_and_extra_html_options
<del> expected = %(<tr class="archived_record_tag_post special" id="archived_record_tag_post_45" style='background-color: #f0f0f0'></tr>)
<del> actual = content_tag_for(:tr, @post, :archived, class: "special", style: "background-color: #f0f0f0")
<del> assert_dom_equal expected, actual
<del> end
<del>
<del> def test_block_not_in_erb_multiple_calls
<del> expected = %(<div class="record_tag_post special" id="record_tag_post_45">What a wonderful world!</div>)
<del> actual = div_for(@post, class: "special") { @post.body }
<del> assert_dom_equal expected, actual
<del> actual = div_for(@post, class: "special") { @post.body }
<del> assert_dom_equal expected, actual
<del> end
<del>
<del> def test_block_works_with_content_tag_for_in_erb
<del> expected = %(<tr class="record_tag_post" id="record_tag_post_45">What a wonderful world!</tr>)
<del> actual = render_erb("<%= content_tag_for(:tr, @post) do %><%= @post.body %><% end %>")
<del> assert_dom_equal expected, actual
<del> end
<del>
<del> def test_div_for_in_erb
<del> expected = %(<div class="record_tag_post special" id="record_tag_post_45">What a wonderful world!</div>)
<del> actual = render_erb("<%= div_for(@post, class: 'special') do %><%= @post.body %><% end %>")
<del> assert_dom_equal expected, actual
<del> end
<del>
<del> def test_content_tag_for_collection
<del> post_1 = RecordTagPost.new { |post| post.id = 101; post.body = "Hello!" }
<del> post_2 = RecordTagPost.new { |post| post.id = 102; post.body = "World!" }
<del> expected = %(<li class="record_tag_post" id="record_tag_post_101">Hello!</li>\n<li class="record_tag_post" id="record_tag_post_102">World!</li>)
<del> actual = content_tag_for(:li, [post_1, post_2]) { |post| post.body }
<del> assert_dom_equal expected, actual
<del> end
<del>
<del> def test_content_tag_for_collection_without_given_block
<del> post_1 = RecordTagPost.new.tap { |post| post.id = 101; post.body = "Hello!" }
<del> post_2 = RecordTagPost.new.tap { |post| post.id = 102; post.body = "World!" }
<del> expected = %(<li class="record_tag_post" id="record_tag_post_101"></li>\n<li class="record_tag_post" id="record_tag_post_102"></li>)
<del> actual = content_tag_for(:li, [post_1, post_2])
<del> assert_dom_equal expected, actual
<del> end
<del>
<del> def test_div_for_collection
<del> post_1 = RecordTagPost.new { |post| post.id = 101; post.body = "Hello!" }
<del> post_2 = RecordTagPost.new { |post| post.id = 102; post.body = "World!" }
<del> expected = %(<div class="record_tag_post" id="record_tag_post_101">Hello!</div>\n<div class="record_tag_post" id="record_tag_post_102">World!</div>)
<del> actual = div_for([post_1, post_2]) { |post| post.body }
<del> assert_dom_equal expected, actual
<del> end
<del>
<del> def test_content_tag_for_single_record_is_html_safe
<del> result = div_for(@post, class: "special") { @post.body }
<del> assert result.html_safe?
<del> end
<del>
<del> def test_content_tag_for_collection_is_html_safe
<del> post_1 = RecordTagPost.new { |post| post.id = 101; post.body = "Hello!" }
<del> post_2 = RecordTagPost.new { |post| post.id = 102; post.body = "World!" }
<del> result = content_tag_for(:li, [post_1, post_2]) { |post| post.body }
<del> assert result.html_safe?
<del> end
<del>
<del> def test_content_tag_for_does_not_change_options_hash
<del> options = { class: "important" }
<del> content_tag_for(:li, @post, options)
<del> assert_equal({ class: "important" }, options)
<add> def test_div_for
<add> assert_raises(NoMethodError) { div_for(@post, class: "special") }
<ide> end
<ide> end
<ide><path>guides/source/action_view_overview.md
<ide> WIP: Not all the helpers are listed here. For a full list see the [API documenta
<ide>
<ide> The following is only a brief overview summary of the helpers available in Action View. It's recommended that you review the [API Documentation](http://api.rubyonrails.org/classes/ActionView/Helpers.html), which covers all of the helpers in more detail, but this should serve as a good starting point.
<ide>
<del>### RecordTagHelper
<del>
<del>This module provides methods for generating container tags, such as `div`, for your record. This is the recommended way of creating a container for render your Active Record object, as it adds an appropriate class and id attributes to that container. You can then refer to those containers easily by following the convention, instead of having to think about which class or id attribute you should use.
<del>
<del>#### content_tag_for
<del>
<del>Renders a container tag that relates to your Active Record Object.
<del>
<del>For example, given `@article` is the object of `Article` class, you can do:
<del>
<del>```html+erb
<del><%= content_tag_for(:tr, @article) do %>
<del> <td><%= @article.title %></td>
<del><% end %>
<del>```
<del>
<del>This will generate this HTML output:
<del>
<del>```html
<del><tr id="article_1234" class="article">
<del> <td>Hello World!</td>
<del></tr>
<del>```
<del>
<del>You can also supply HTML attributes as an additional option hash. For example:
<del>
<del>```html+erb
<del><%= content_tag_for(:tr, @article, class: "frontpage") do %>
<del> <td><%= @article.title %></td>
<del><% end %>
<del>```
<del>
<del>Will generate this HTML output:
<del>
<del>```html
<del><tr id="article_1234" class="article frontpage">
<del> <td>Hello World!</td>
<del></tr>
<del>```
<del>
<del>You can pass a collection of Active Record objects. This method will loop through your objects and create a container for each of them. For example, given `@articles` is an array of two `Article` objects:
<del>
<del>```html+erb
<del><%= content_tag_for(:tr, @articles) do |article| %>
<del> <td><%= article.title %></td>
<del><% end %>
<del>```
<del>
<del>Will generate this HTML output:
<del>
<del>```html
<del><tr id="article_1234" class="article">
<del> <td>Hello World!</td>
<del></tr>
<del><tr id="article_1235" class="article">
<del> <td>Ruby on Rails Rocks!</td>
<del></tr>
<del>```
<del>
<del>#### div_for
<del>
<del>This is actually a convenient method which calls `content_tag_for` internally with `:div` as the tag name. You can pass either an Active Record object or a collection of objects. For example:
<del>
<del>```html+erb
<del><%= div_for(@article, class: "frontpage") do %>
<del> <td><%= @article.title %></td>
<del><% end %>
<del>```
<del>
<del>Will generate this HTML output:
<del>
<del>```html
<del><div id="article_1234" class="article frontpage">
<del> <td>Hello World!</td>
<del></div>
<del>```
<del>
<ide> ### AssetTagHelper
<ide>
<ide> This module provides methods for generating HTML that links views to assets such as images, JavaScript files, stylesheets, and feeds. | 5 |
Text | Text | change improper translation | 406fdfe6b48a7ec9423ed8b08ee2e7cc78e0411f | <ide><path>guide/chinese/react/index.md
<ide> ---
<ide> title: React
<del>localeTitle: 应对
<add>localeTitle: React
<ide> ---
<del># 应对
<add># React
<ide>
<del>React是一个用于构建用户界面的JavaScript库。它被Stack Overflow 2017年开发者调查中的“框架,图书馆和其他技术”类别评为最受欢迎。 1
<add>React是一个用于构建用户界面的JavaScript库。在Stack Overflow 2017年开发者调查别评为最受欢迎的“框架,库和其他技术”之一。
<ide>
<del>React是一个JavaScript库,构建在它上面的React应用程序在浏览器中运行,而不是在服务器上运行。这种应用程序仅在必要时与服务器通信,这使得它们与传统网站相比非常快,这些网站迫使用户等待服务器重新呈现整个页面并将其发送到浏览器。
<add>React是一个JavaScript库,构建在它上面的React应用程序在浏览器中运行,而不是在服务器上运行。这种应用程序仅在必要时与服务器通信,这使得它们与传统网站相比更快,用户从此不必等待服务器重新渲染整个页面并将其发送到浏览器。
<ide>
<del>React用于构建用户界面 - 用户在屏幕上看到并与之交互以使用您的Web应用程序。这个界面被分成几个部分,而不是将一个巨大的页面拆分成称为组件的较小部分。更一般地说,这种方法称为模块化。
<add>React用于构建用户界面 - 用户在屏幕上看到并与之交互来使用React编写的的Web应用程序。用户界面将被分成几个称为组件的较小部分。更一般地说,这种方法称为模块化。
<ide>
<del>* 它是声明性的:React使用声明性范例,使您更容易推理您的应用程序。
<del>* 效率很高:React计算保持DOM最新所需的最小变更集。
<del>* 而且它很灵活:React可以与您已经知道的库和框架一起使用。
<add>* 它是声明性的:React使用声明性范例,使您更容易理解您的应用程序。
<add>* 高效率:React计算保持DOM最新所需的最小变更集。
<add>* 灵活性:React可以与您已经知道的其它库和框架一起使用。
<ide>
<ide> ## 为什么要学习React?
<ide>
<ide> const Component2 = () => {
<ide>
<ide> 2. 在大多数情况下,React是声明性的,我们更关心的是做什么而不是如何做特定的任务。声明性编程是一种编程范例,表示计算的逻辑而不描述其控制流。 声明性编程具有某些优点,例如减少副作用(当我们修改任何状态或改变某些东西或发出API请求时发生),最小化可变性(大量抽象),增强的可读性,较小的错误。
<ide>
<del>3. 单向数据流。 React中的UI实际上是状态的功能,这意味着当状态更新时它也会更新UI。所以我们的UI随着状态的变化而进步。
<add>3. 单向数据流。 React中的UI实际上是状态依赖的功能,这意味着当状态更新时它也会更新UI。所以我们的UI随着状态的变化而进步。
<ide>
<ide>
<ide> ## React的优点
<ide>
<ide> 使用React的一些原因是:
<ide>
<del>1. 快速。在React中制作的应用程序可以处理复杂的更新,并且仍然能够快速响应。
<add>1. 快速。在React中制作的应用程序可以处理复杂的更新,并且仍然能够做到快速响应。
<ide> 2. 模块化。您可以编写许多较小的可重用文件,而不是编写大而密集的代码文件。 React的模块化可以解决JavaScript的[可维护性问题](https://en.wikipedia.org/wiki/Spaghetti_code) 。
<ide> 3. 可扩展性。显示大量不断变化的数据的大型程序是React表现最佳的地方。
<ide> 4. 灵活。您可以将React用于与制作Web应用程序无关的有趣项目。人们仍然在研究React的潜力。 [有探索的空间](https://medium.mybridge.co/22-amazing-open-source-react-projects-cb8230ec719f) 。
<ide> React有一个智能的差异算法,它只用于在DOM节点中重新生成实
<ide>
<ide> 使用虚拟DOM,React将最后的DOM版本保留在内存中,当它有一个新的DOM版本带到浏览器时,新的DOM版本也将在内存中,因此React可以计算新版本和旧版本之间的差异。
<ide>
<del>然后,React将指示浏览器仅更新计算的diff而不是整个DOM节点。无论我们重新生成界面多少次,React都会向浏览器添加新的“部分”更新。
<add>然后,React将指示浏览器仅更新计算两者不同的部分而不是整个DOM节点。无论我们重新生成界面多少次,React都只会向浏览器添加更新的“部分”。
<ide>
<del>## 从Scratch反应
<add>## 开始编写React应用
<ide>
<ide> 您是否想开始学习反应的基础知识而不会陷入困境创建开发环境? 如果您不熟悉Web开发,那么设置开发环境可能会让您在尝试学习React或第一次学习React时感到有点恐惧。
<ide>
<ide> JSX非常直观。您可以非常轻松地阅读此代码,并看到这将是
<ide>
<ide> ### 来源
<ide>
<del>1. [“2017年开发者调查结果。”](https://insights.stackoverflow.com/survey/2017#technology-most-loved-dreaded-and-wanted-frameworks-libraries-and-other-technologies) _堆栈溢出。_访问时间:2017年10月28日。
<ide>\ No newline at end of file
<add>1. [“2017年开发者调查结果。”](https://insights.stackoverflow.com/survey/2017#technology-most-loved-dreaded-and-wanted-frameworks-libraries-and-other-technologies) _堆栈溢出。_访问时间:2017年10月28日。 | 1 |
Java | Java | fix concurrency issue in testdispatcherservlet | 119e793994796bc4e7ebfd7d57fe3b219c07c68b | <ide><path>spring-test/src/main/java/org/springframework/mock/web/MockAsyncContext.java
<ide> import javax.servlet.http.HttpServletRequest;
<ide> import javax.servlet.http.HttpServletResponse;
<ide>
<add>import org.apache.commons.logging.Log;
<ide> import org.springframework.beans.BeanUtils;
<add>import org.springframework.util.Assert;
<ide> import org.springframework.web.util.WebUtils;
<ide>
<ide> /**
<ide> public class MockAsyncContext implements AsyncContext {
<ide>
<ide> private long timeout = 10 * 1000L; // 10 seconds is Tomcat's default
<ide>
<add> private final List<Runnable> dispatchHandlers = new ArrayList<Runnable>();
<add>
<ide>
<ide> public MockAsyncContext(ServletRequest request, ServletResponse response) {
<ide> this.request = (HttpServletRequest) request;
<ide> this.response = (HttpServletResponse) response;
<ide> }
<ide>
<ide>
<add> public void addDispatchHandler(Runnable handler) {
<add> Assert.notNull(handler);
<add> this.dispatchHandlers.add(handler);
<add> }
<add>
<ide> @Override
<ide> public ServletRequest getRequest() {
<ide> return this.request;
<ide> public void dispatch(String path) {
<ide> @Override
<ide> public void dispatch(ServletContext context, String path) {
<ide> this.dispatchedPath = path;
<add> for (Runnable r : this.dispatchHandlers) {
<add> r.run();
<add> }
<ide> }
<ide>
<ide> public String getDispatchedPath() {
<ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/TestDispatcherServlet.java
<ide> import javax.servlet.http.HttpServletRequest;
<ide> import javax.servlet.http.HttpServletResponse;
<ide>
<add>import org.springframework.mock.web.MockAsyncContext;
<ide> import org.springframework.web.context.WebApplicationContext;
<ide> import org.springframework.web.context.request.NativeWebRequest;
<del>import org.springframework.web.context.request.async.CallableProcessingInterceptorAdapter;
<del>import org.springframework.web.context.request.async.DeferredResult;
<del>import org.springframework.web.context.request.async.DeferredResultProcessingInterceptorAdapter;
<del>import org.springframework.web.context.request.async.WebAsyncManager;
<del>import org.springframework.web.context.request.async.WebAsyncUtils;
<add>import org.springframework.web.context.request.async.*;
<ide> import org.springframework.web.servlet.DispatcherServlet;
<ide> import org.springframework.web.servlet.HandlerExecutionChain;
<ide> import org.springframework.web.servlet.ModelAndView;
<ide> final class TestDispatcherServlet extends DispatcherServlet {
<ide>
<ide> private static final String KEY = TestDispatcherServlet.class.getName() + ".interceptor";
<ide>
<add>
<ide> /**
<ide> * Create a new instance with the given web application context.
<ide> */
<ide> public TestDispatcherServlet(WebApplicationContext webApplicationContext) {
<ide> super(webApplicationContext);
<ide> }
<ide>
<add>
<ide> @Override
<ide> protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
<ide>
<del> CountDownLatch latch = registerAsyncInterceptors(request);
<del> getMvcResult(request).setAsyncResultLatch(latch);
<add> registerAsyncResultInterceptors(request);
<ide>
<ide> super.service(request, response);
<del> }
<ide>
<del> private CountDownLatch registerAsyncInterceptors(final HttpServletRequest servletRequest) {
<del>
<del> final CountDownLatch asyncResultLatch = new CountDownLatch(1);
<del>
<del> WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(servletRequest);
<add> if (request.isAsyncStarted()) {
<add> addAsyncResultLatch(request);
<add> }
<add> }
<ide>
<add> private void registerAsyncResultInterceptors(final HttpServletRequest request) {
<add> WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
<ide> asyncManager.registerCallableInterceptor(KEY, new CallableProcessingInterceptorAdapter() {
<ide> @Override
<del> public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object value) throws Exception {
<del> getMvcResult(servletRequest).setAsyncResult(value);
<del> asyncResultLatch.countDown();
<add> public <T> void postProcess(NativeWebRequest r, Callable<T> task, Object value) throws Exception {
<add> getMvcResult(request).setAsyncResult(value);
<ide> }
<ide> });
<ide> asyncManager.registerDeferredResultInterceptor(KEY, new DeferredResultProcessingInterceptorAdapter() {
<ide> @Override
<del> public <T> void postProcess(NativeWebRequest request, DeferredResult<T> result, Object value) throws Exception {
<del> getMvcResult(servletRequest).setAsyncResult(value);
<del> asyncResultLatch.countDown();
<add> public <T> void postProcess(NativeWebRequest r, DeferredResult<T> result, Object value) throws Exception {
<add> getMvcResult(request).setAsyncResult(value);
<ide> }
<ide> });
<add> }
<ide>
<del> return asyncResultLatch;
<add> private void addAsyncResultLatch(HttpServletRequest request) {
<add> final CountDownLatch latch = new CountDownLatch(1);
<add> ((MockAsyncContext) request.getAsyncContext()).addDispatchHandler(new Runnable() {
<add> @Override
<add> public void run() {
<add> latch.countDown();
<add> }
<add> });
<add> getMvcResult(request).setAsyncResultLatch(latch);
<ide> }
<ide>
<ide> protected DefaultMvcResult getMvcResult(ServletRequest request) { | 2 |
Text | Text | add thumbtack to organizations using airflow | a9286f31d2a122a7fe24475a55271256fca91305 | <ide><path>README.md
<ide> Currently **officially** using Airflow:
<ide> * [SimilarWeb](https://www.similarweb.com/) [[@similarweb](https://github.com/similarweb)]
<ide> * [SmartNews](https://www.smartnews.com/) [[@takus](https://github.com/takus)]
<ide> * Stripe [@jbalogh]
<add>* [Thumbtack](https://www.thumbtack.com/) [[@natekupp](https://github.com/natekupp)]
<ide> * [WeTransfer](https://github.com/WeTransfer) [[@jochem](https://github.com/jochem)]
<ide> * Wooga
<ide> * Xoom [[@gepser](https://github.com/gepser) & [@omarvides](https://github.com/omarvides)] | 1 |
Javascript | Javascript | add routestack in second argument | 1abd12b68be6358761411272117c830c1afd306a | <ide><path>Libraries/CustomComponents/Navigator/Navigator.js
<ide> var Navigator = React.createClass({
<ide> propTypes: {
<ide> /**
<ide> * Optional function that allows configuration about scene animations and
<del> * gestures. Will be invoked with the route and should return a scene
<del> * configuration object
<add> * gestures. Will be invoked with the route and the routeStack and should
<add> * return a scene configuration object
<ide> *
<ide> * ```
<del> * (route) => Navigator.SceneConfigs.FloatFromRight
<add> * (route, routeStack) => Navigator.SceneConfigs.FloatFromRight
<ide> * ```
<ide> */
<ide> configureScene: PropTypes.func,
<ide> var Navigator = React.createClass({
<ide> }
<ide> return {
<ide> sceneConfigStack: routeStack.map(
<del> (route) => this.props.configureScene(route)
<add> (route) => this.props.configureScene(route, routeStack)
<ide> ),
<ide> routeStack,
<ide> presentedIndex: initialRouteIndex,
<ide> var Navigator = React.createClass({
<ide> this.setState({
<ide> routeStack: nextRouteStack,
<ide> sceneConfigStack: nextRouteStack.map(
<del> this.props.configureScene
<add> route => this.props.configureScene(route, nextRouteStack)
<ide> ),
<ide> presentedIndex: destIndex,
<ide> activeGesture: null,
<ide> var Navigator = React.createClass({
<ide> var nextStack = activeStack.concat([route]);
<ide> var destIndex = nextStack.length - 1;
<ide> var nextAnimationConfigStack = activeAnimationConfigStack.concat([
<del> this.props.configureScene(route),
<add> this.props.configureScene(route, nextStack),
<ide> ]);
<ide> this._emitWillFocus(nextStack[destIndex]);
<ide> this.setState({
<ide> var Navigator = React.createClass({
<ide> var nextRouteStack = this.state.routeStack.slice();
<ide> var nextAnimationModeStack = this.state.sceneConfigStack.slice();
<ide> nextRouteStack[index] = route;
<del> nextAnimationModeStack[index] = this.props.configureScene(route);
<add> nextAnimationModeStack[index] = this.props.configureScene(route, nextRouteStack);
<ide>
<ide> if (index === this.state.presentedIndex) {
<ide> this._emitWillFocus(route); | 1 |
PHP | PHP | add same-site to config | a15f3ca8a9861563bdc6cc4838338e29f4ae28e4 | <ide><path>config/session.php
<ide>
<ide> 'http_only' => true,
<ide>
<add> /*
<add> |--------------------------------------------------------------------------
<add> | Same-site Cookies
<add> |--------------------------------------------------------------------------
<add> |
<add> | Here you may change the default value of the same-site cookie attribute.
<add> |
<add> | Supported: "lax", "strict"
<add> |
<add> */
<add>
<add> 'same_site' => null,
<add>
<ide> ]; | 1 |
Java | Java | synthesize nested maps into annotations | f17173f6d5fb167db1c0a6905c23e52caace939b | <ide><path>spring-core/src/main/java/org/springframework/core/annotation/AnnotationUtils.java
<ide> public static <A extends Annotation> A synthesizeAnnotation(A annotation, Annota
<ide> * that are annotated with {@link AliasFor @AliasFor}.
<ide> * <p>The supplied map must contain a key-value pair for every attribute
<ide> * defined in the supplied {@code annotationType} that is not aliased or
<del> * does not have a default value.
<add> * does not have a default value. Nested maps and nested arrays of maps
<add> * will be recursively synthesized into nested annotations or nested
<add> * arrays of annotations, respectively.
<ide> * <p>Note that {@link AnnotationAttributes} is a specialized type of
<ide> * {@link Map} that is an ideal candidate for this method's
<ide> * {@code attributes} argument.
<ide> public static <A extends Annotation> A synthesizeAnnotation(A annotation, Annota
<ide> * @since 4.2
<ide> * @see #synthesizeAnnotation(Annotation, AnnotatedElement)
<ide> * @see #synthesizeAnnotation(Class)
<add> * @see #getAnnotationAttributes(AnnotatedElement, Annotation)
<add> * @see #getAnnotationAttributes(AnnotatedElement, Annotation, boolean, boolean)
<ide> */
<ide> @SuppressWarnings("unchecked")
<ide> public static <A extends Annotation> A synthesizeAnnotation(Map<String, Object> attributes,
<ide> public static <A extends Annotation> A synthesizeAnnotation(Class<A> annotationT
<ide> }
<ide>
<ide> /**
<del> * <em>Synthesize</em> the supplied array of {@code annotations} by
<del> * creating a new array of the same size and type and populating it
<del> * with {@linkplain #synthesizeAnnotation(Annotation) synthesized}
<del> * versions of the annotations from the input array.
<add> * <em>Synthesize</em> an array of annotations from the supplied array
<add> * of {@code annotations} by creating a new array of the same size and
<add> * type and populating it with {@linkplain #synthesizeAnnotation(Annotation)
<add> * synthesized} versions of the annotations from the input array.
<ide> * @param annotations the array of annotations to synthesize
<ide> * @param annotatedElement the element that is annotated with the supplied
<ide> * array of annotations; may be {@code null} if unknown
<ide> public static Annotation[] synthesizeAnnotationArray(Annotation[] annotations, A
<ide> return synthesized;
<ide> }
<ide>
<add> /**
<add> * <em>Synthesize</em> an array of annotations from the supplied array
<add> * of {@code maps} of annotation attributes by creating a new array of
<add> * {@code annotationType} with the same size and populating it with
<add> * {@linkplain #synthesizeAnnotation(Map, Class, AnnotatedElement)
<add> * synthesized} versions of the maps from the input array.
<add> * @param maps the array of maps of annotation attributes to synthesize
<add> * @param annotationType the type of annotations to synthesize; never
<add> * {@code null}
<add> * @return a new array of synthesized annotations, or {@code null} if
<add> * the supplied array is {@code null}
<add> * @throws AnnotationConfigurationException if invalid configuration of
<add> * {@code @AliasFor} is detected
<add> * @since 4.2.1
<add> * @see #synthesizeAnnotation(Map, Class, AnnotatedElement)
<add> * @see #synthesizeAnnotationArray(Annotation[], AnnotatedElement)
<add> */
<add> @SuppressWarnings("unchecked")
<add> static <A extends Annotation> A[] synthesizeAnnotationArray(Map<String, Object>[] maps, Class<A> annotationType) {
<add> Assert.notNull(annotationType, "annotationType must not be null");
<add>
<add> if (maps == null) {
<add> return null;
<add> }
<add>
<add> A[] synthesized = (A[]) Array.newInstance(annotationType, maps.length);
<add> for (int i = 0; i < maps.length; i++) {
<add> synthesized[i] = synthesizeAnnotation(maps[i], annotationType, null);
<add> }
<add> return synthesized;
<add> }
<add>
<ide> /**
<ide> * Get a map of all attribute alias pairs, declared via {@code @AliasFor}
<ide> * in the supplied annotation type.
<ide><path>spring-core/src/main/java/org/springframework/core/annotation/MapAnnotationAttributeExtractor.java
<ide> protected Object getRawAttributeValue(String attributeName) {
<ide>
<ide>
<ide> /**
<del> * Enrich and validate the supplied {@code attributes} map by ensuring
<add> * Enrich and validate the supplied <em>attributes</em> map by ensuring
<ide> * that it contains a non-null entry for each annotation attribute in
<ide> * the specified {@code annotationType} and that the type of the entry
<ide> * matches the return type for the corresponding annotation attribute.
<add> * <p>If an entry is a map (presumably of annotation attributes), an
<add> * attempt will be made to synthesize an annotation from it. Similarly,
<add> * if an entry is an array of maps, an attempt will be made to synthesize
<add> * an array of annotations from those maps.
<ide> * <p>If an attribute is missing in the supplied map, it will be set
<del> * either to value of its alias (if an alias value exists) or to the
<add> * either to the value of its alias (if an alias exists) or to the
<ide> * value of the attribute's default value (if defined), and otherwise
<ide> * an {@link IllegalArgumentException} will be thrown.
<del> * @see AliasFor
<ide> */
<add> @SuppressWarnings("unchecked")
<ide> private static Map<String, Object> enrichAndValidateAttributes(
<del> Map<String, Object> original, Class<? extends Annotation> annotationType) {
<add> Map<String, Object> originalAttributes, Class<? extends Annotation> annotationType) {
<ide>
<del> Map<String, Object> attributes = new HashMap<String, Object>(original);
<add> Map<String, Object> attributes = new HashMap<String, Object>(originalAttributes);
<ide> Map<String, String> attributeAliasMap = getAttributeAliasMap(annotationType);
<ide>
<ide> for (Method attributeMethod : getAttributeMethods(annotationType)) {
<ide> private static Map<String, Object> enrichAndValidateAttributes(
<ide> attributes, attributeName, annotationType.getName()));
<ide> }
<ide>
<del> // else, ensure correct type
<del> Class<?> returnType = attributeMethod.getReturnType();
<del> if (!ClassUtils.isAssignable(returnType, attributeValue.getClass())) {
<del> throw new IllegalArgumentException(String.format(
<del> "Attributes map [%s] returned a value of type [%s] for attribute [%s], "
<del> + "but a value of type [%s] is required as defined by annotation type [%s].", attributes,
<del> attributeValue.getClass().getName(), attributeName, returnType.getName(), annotationType.getName()));
<add> // finally, ensure correct type
<add> Class<?> requiredReturnType = attributeMethod.getReturnType();
<add> Class<? extends Object> actualReturnType = attributeValue.getClass();
<add> if (!ClassUtils.isAssignable(requiredReturnType, actualReturnType)) {
<add> boolean converted = false;
<add>
<add> // Nested map representing a single annotation?
<add> if (Annotation.class.isAssignableFrom(requiredReturnType)
<add> && Map.class.isAssignableFrom(actualReturnType)) {
<add>
<add> Class<? extends Annotation> nestedAnnotationType = (Class<? extends Annotation>) requiredReturnType;
<add> Map<String, Object> map = (Map<String, Object>) attributeValue;
<add> attributes.put(attributeName, synthesizeAnnotation(map, nestedAnnotationType, null));
<add> converted = true;
<add> }
<add>
<add> // Nested array of maps representing an array of annotations?
<add> else if (requiredReturnType.isArray()
<add> && Annotation.class.isAssignableFrom(requiredReturnType.getComponentType())
<add> && actualReturnType.isArray()
<add> && Map.class.isAssignableFrom(actualReturnType.getComponentType())) {
<add>
<add> Class<? extends Annotation> nestedAnnotationType = (Class<? extends Annotation>) requiredReturnType.getComponentType();
<add> Map<String, Object>[] maps = (Map<String, Object>[]) attributeValue;
<add> attributes.put(attributeName, synthesizeAnnotationArray(maps, nestedAnnotationType));
<add> converted = true;
<add> }
<add>
<add> if (!converted) {
<add> throw new IllegalArgumentException(String.format(
<add> "Attributes map [%s] returned a value of type [%s] for attribute [%s], "
<add> + "but a value of type [%s] is required as defined by annotation type [%s].",
<add> attributes, actualReturnType.getName(), attributeName, requiredReturnType.getName(),
<add> annotationType.getName()));
<add> }
<ide> }
<ide> }
<ide>
<ide><path>spring-core/src/test/java/org/springframework/core/annotation/AnnotationUtilsTests.java
<ide> public void synthesizeAnnotationFromMapWithoutAttributeAliases() throws Exceptio
<ide> assertEquals("value from synthesized component: ", "webController", synthesizedComponent.value());
<ide> }
<ide>
<add> @Test
<add> @SuppressWarnings("unchecked")
<add> public void synthesizeAnnotationFromMapWithNestedMap() throws Exception {
<add> ComponentScanSingleFilter componentScan = ComponentScanSingleFilterClass.class.getAnnotation(ComponentScanSingleFilter.class);
<add> assertNotNull(componentScan);
<add> assertEquals("value from ComponentScan: ", "*Foo", componentScan.value().pattern());
<add>
<add> AnnotationAttributes attributes = getAnnotationAttributes(ComponentScanSingleFilterClass.class, componentScan,
<add> false, true);
<add> assertNotNull(attributes);
<add> assertEquals(ComponentScanSingleFilter.class, attributes.annotationType());
<add>
<add> Map<String, Object> filterMap = (Map<String, Object>) attributes.get("value");
<add> assertNotNull(filterMap);
<add> assertEquals("*Foo", filterMap.get("pattern"));
<add>
<add> // Modify nested map
<add> filterMap.put("pattern", "newFoo");
<add> filterMap.put("enigma", 42);
<add>
<add> ComponentScanSingleFilter synthesizedComponentScan = synthesizeAnnotation(attributes,
<add> ComponentScanSingleFilter.class, ComponentScanSingleFilterClass.class);
<add> assertNotNull(synthesizedComponentScan);
<add>
<add> assertNotSame(componentScan, synthesizedComponentScan);
<add> assertEquals("value from synthesized ComponentScan: ", "newFoo", synthesizedComponentScan.value().pattern());
<add> }
<add>
<add> @Test
<add> @SuppressWarnings("unchecked")
<add> public void synthesizeAnnotationFromMapWithNestedArrayOfMaps() throws Exception {
<add> ComponentScan componentScan = ComponentScanClass.class.getAnnotation(ComponentScan.class);
<add> assertNotNull(componentScan);
<add>
<add> AnnotationAttributes attributes = getAnnotationAttributes(ComponentScanClass.class, componentScan, false, true);
<add> assertNotNull(attributes);
<add> assertEquals(ComponentScan.class, attributes.annotationType());
<add>
<add> Map<String, Object>[] filters = (Map[]) attributes.get("excludeFilters");
<add> assertNotNull(filters);
<add>
<add> List<String> patterns = stream(filters).map(m -> (String) m.get("pattern")).collect(toList());
<add> assertEquals(asList("*Foo", "*Bar"), patterns);
<add>
<add> // Modify nested maps
<add> filters[0].put("pattern", "newFoo");
<add> filters[0].put("enigma", 42);
<add> filters[1].put("pattern", "newBar");
<add> filters[1].put("enigma", 42);
<add>
<add> ComponentScan synthesizedComponentScan = synthesizeAnnotation(attributes, ComponentScan.class, ComponentScanClass.class);
<add> assertNotNull(synthesizedComponentScan);
<add>
<add> assertNotSame(componentScan, synthesizedComponentScan);
<add> patterns = stream(synthesizedComponentScan.excludeFilters()).map(Filter::pattern).collect(toList());
<add> assertEquals(asList("newFoo", "newBar"), patterns);
<add> }
<add>
<ide> @Test
<ide> public void synthesizeAnnotationFromDefaultsWithoutAttributeAliases() throws Exception {
<ide> AnnotationWithDefaults annotationWithDefaults = synthesizeAnnotation(AnnotationWithDefaults.class);
<ide> static class AliasedComposedContextConfigNotMetaPresentClass {
<ide> static class ComponentScanClass {
<ide> }
<ide>
<add> /**
<add> * Mock of {@code org.springframework.context.annotation.ComponentScan}
<add> */
<add> @Retention(RetentionPolicy.RUNTIME)
<add> @interface ComponentScanSingleFilter {
<add> Filter value();
<add> }
<add>
<add> @ComponentScanSingleFilter(@Filter(pattern = "*Foo"))
<add> static class ComponentScanSingleFilterClass {
<add> }
<add>
<ide> @Retention(RetentionPolicy.RUNTIME)
<ide> @interface AnnotationWithDefaults {
<ide> String text() default "enigma"; | 3 |
Java | Java | add null check | 47ff92873bc35345a0e0a743be4939527a27f896 | <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/InvocableHandlerMethod.java
<ide> private void logArgumentErrorIfNecessary(
<ide>
<ide> // Leave stack trace for later, if error is not handled..
<ide> String message = cause.getMessage();
<del> if (!message.contains(parameter.getExecutable().toGenericString())) {
<add> if (message != null && !message.contains(parameter.getExecutable().toGenericString())) {
<ide> if (logger.isDebugEnabled()) {
<ide> logger.debug(exchange.getLogPrefix() + formatArgumentError(parameter, message));
<ide> } | 1 |
Java | Java | fix cache generics warnings; polish whitespace | 8abb3150420d03e7c8cd3f483bf8a411e6fbcc0e | <ide><path>org.springframework.context/src/test/java/org/springframework/cache/config/AbstractAnnotationTests.java
<ide>
<ide> /**
<ide> * Abstract annotation test (containing several reusable methods).
<del> *
<add> *
<ide> * @author Costin Leau
<ide> */
<ide> public abstract class AbstractAnnotationTests {
<ide>
<ide> protected ApplicationContext ctx;
<ide>
<del> protected CacheableService cs;
<add> protected CacheableService<?> cs;
<ide>
<del> protected CacheableService ccs;
<add> protected CacheableService<?> ccs;
<ide>
<ide> protected CacheManager cm;
<ide>
<ide> public void setup() {
<ide> assertTrue(cn.contains("primary"));
<ide> }
<ide>
<del> public void testCacheable(CacheableService service) throws Exception {
<add> public void testCacheable(CacheableService<?> service) throws Exception {
<ide> Object o1 = new Object();
<del> Object o2 = new Object();
<ide>
<ide> Object r1 = service.cache(o1);
<ide> Object r2 = service.cache(o1);
<ide> public void testCacheable(CacheableService service) throws Exception {
<ide> assertSame(r1, r3);
<ide> }
<ide>
<del> public void testInvalidate(CacheableService service) throws Exception {
<add> public void testInvalidate(CacheableService<?> service) throws Exception {
<ide> Object o1 = new Object();
<del> Object o2 = new Object();
<ide>
<ide> Object r1 = service.cache(o1);
<ide> Object r2 = service.cache(o1);
<ide> public void testInvalidate(CacheableService service) throws Exception {
<ide> assertSame(r3, r4);
<ide> }
<ide>
<del> public void testInvalidateWKey(CacheableService service) throws Exception {
<add> public void testInvalidateWKey(CacheableService<?> service) throws Exception {
<ide> Object o1 = new Object();
<del> Object o2 = new Object();
<ide>
<ide> Object r1 = service.cache(o1);
<ide> Object r2 = service.cache(o1);
<ide> public void testInvalidateWKey(CacheableService service) throws Exception {
<ide> assertSame(r3, r4);
<ide> }
<ide>
<del> public void testConditionalExpression(CacheableService service)
<add> public void testConditionalExpression(CacheableService<?> service)
<ide> throws Exception {
<ide> Object r1 = service.conditional(4);
<ide> Object r2 = service.conditional(4);
<ide> public void testConditionalExpression(CacheableService service)
<ide> assertSame(r3, r4);
<ide> }
<ide>
<del> public void testKeyExpression(CacheableService service) throws Exception {
<add> public void testKeyExpression(CacheableService<?> service) throws Exception {
<ide> Object r1 = service.key(5, 1);
<ide> Object r2 = service.key(5, 2);
<ide>
<ide> public void testKeyExpression(CacheableService service) throws Exception {
<ide> assertNotSame(r3, r4);
<ide> }
<ide>
<del> public void testNullValue(CacheableService service) throws Exception {
<add> public void testNullValue(CacheableService<?> service) throws Exception {
<ide> Object key = new Object();
<ide> assertNull(service.nullValue(key));
<ide> int nr = service.nullInvocations().intValue();
<ide> public void testNullValue(CacheableService service) throws Exception {
<ide> assertEquals(nr + 1, service.nullInvocations().intValue());
<ide> }
<ide>
<del> public void testMethodName(CacheableService service, String keyName)
<add> public void testMethodName(CacheableService<?> service, String keyName)
<ide> throws Exception {
<ide> Object key = new Object();
<ide> Object r1 = service.name(key);
<ide> public void testMethodName(CacheableService service, String keyName)
<ide> assertNotNull(cache.get(keyName));
<ide> }
<ide>
<del> public void testRootVars(CacheableService service) {
<add> public void testRootVars(CacheableService<?> service) {
<ide> Object key = new Object();
<ide> Object r1 = service.rootVars(key);
<ide> assertSame(r1, service.rootVars(key));
<ide> public void testRootVars(CacheableService service) {
<ide> assertNotNull(cache.get(expectedKey));
<ide> }
<ide>
<del> public void testCheckedThrowable(CacheableService service) throws Exception {
<add> public void testCheckedThrowable(CacheableService<?> service) throws Exception {
<ide> String arg = UUID.randomUUID().toString();
<ide> try {
<ide> service.throwChecked(arg);
<ide> public void testCheckedThrowable(CacheableService service) throws Exception {
<ide> }
<ide> }
<ide>
<del> public void testUncheckedThrowable(CacheableService service) throws Exception {
<add> public void testUncheckedThrowable(CacheableService<?> service) throws Exception {
<ide> try {
<ide> service.throwUnchecked(Long.valueOf(1));
<ide> fail("Excepted exception");
<ide> public void testUncheckedThrowable(CacheableService service) throws Exception {
<ide> }
<ide> }
<ide>
<del> public void testNullArg(CacheableService service) {
<add> public void testNullArg(CacheableService<?> service) {
<ide> Object r1 = service.cache(null);
<ide> assertSame(r1, service.cache(null));
<ide> }
<ide>
<del> public void testCacheUpdate(CacheableService service) {
<add> public void testCacheUpdate(CacheableService<?> service) {
<ide> Object o = new Object();
<ide> Cache cache = cm.getCache("default");
<ide> assertNull(cache.get(o));
<ide> public void testCacheUpdate(CacheableService service) {
<ide> assertSame(r2, cache.get(o).get());
<ide> }
<ide>
<del> public void testConditionalCacheUpdate(CacheableService service) {
<add> public void testConditionalCacheUpdate(CacheableService<?> service) {
<ide> Integer one = Integer.valueOf(1);
<ide> Integer three = Integer.valueOf(3);
<ide>
<ide> public void testConditionalCacheUpdate(CacheableService service) {
<ide> assertEquals(three, Integer.valueOf(cache.get(three).get().toString()));
<ide> }
<ide>
<del> public void testMultiCache(CacheableService service) {
<add> public void testMultiCache(CacheableService<?> service) {
<ide> Object o1 = new Object();
<ide> Object o2 = new Object();
<ide>
<ide> public void testMultiCache(CacheableService service) {
<ide> assertSame(r4, secondary.get(o2).get());
<ide> }
<ide>
<del> public void testMultiEvict(CacheableService service) {
<add> public void testMultiEvict(CacheableService<?> service) {
<ide> Object o1 = new Object();
<ide>
<ide> Object r1 = service.multiCache(o1);
<ide> public void testMultiEvict(CacheableService service) {
<ide> assertSame(r4, secondary.get(o1).get());
<ide> }
<ide>
<del> public void testMultiPut(CacheableService service) {
<add> public void testMultiPut(CacheableService<?> service) {
<ide> Object o = Integer.valueOf(1);
<ide>
<ide> Cache primary = cm.getCache("primary");
<ide> public void testMultiPut(CacheableService service) {
<ide> assertSame(r2, secondary.get(o).get());
<ide> }
<ide>
<del> public void testMultiCacheAndEvict(CacheableService service) {
<add> public void testMultiCacheAndEvict(CacheableService<?> service) {
<ide> String methodName = "multiCacheAndEvict";
<ide>
<ide> Cache primary = cm.getCache("primary");
<ide> public void testMultiCacheAndEvict(CacheableService service) {
<ide> assertNull(secondary.get(key));
<ide> }
<ide>
<del> public void testMultiConditionalCacheAndEvict(CacheableService service) {
<add> public void testMultiConditionalCacheAndEvict(CacheableService<?> service) {
<ide> Cache primary = cm.getCache("primary");
<ide> Cache secondary = cm.getCache("secondary");
<ide> Object key = Integer.valueOf(1);
<ide><path>org.springframework.context/src/test/java/org/springframework/cache/config/AnnotatedClassCacheableService.java
<ide> * @author Costin Leau
<ide> */
<ide> @Cacheable("default")
<del>public class AnnotatedClassCacheableService implements CacheableService {
<add>public class AnnotatedClassCacheableService implements CacheableService<Object> {
<ide>
<ide> private final AtomicLong counter = new AtomicLong();
<ide> public static final AtomicLong nullInvocations = new AtomicLong();
<ide><path>org.springframework.context/src/test/java/org/springframework/cache/config/AnnotationNamespaceDrivenTests.java
<ide> import org.junit.Test;
<ide> import org.springframework.cache.interceptor.CacheInterceptor;
<ide>
<del>
<ide> /**
<ide> * @author Costin Leau
<ide> */
<ide><path>org.springframework.context/src/test/java/org/springframework/cache/config/AnnotationTests.java
<ide>
<ide> package org.springframework.cache.config;
<ide>
<del>
<del>
<ide> /**
<ide> * @author Costin Leau
<ide> */
<ide><path>org.springframework.context/src/test/java/org/springframework/cache/config/CacheAdviceNamespaceTests.java
<ide> import org.junit.Test;
<ide> import org.springframework.cache.interceptor.CacheInterceptor;
<ide>
<del>
<ide> /**
<ide> * @author Costin Leau
<ide> */
<ide> public class CacheAdviceNamespaceTests extends AbstractAnnotationTests {
<ide>
<del>
<ide> @Override
<ide> protected String getConfig() {
<ide> return "/org/springframework/cache/config/cache-advice.xml";
<ide><path>org.springframework.context/src/test/java/org/springframework/cache/config/CacheableService.java
<ide>
<ide> package org.springframework.cache.config;
<ide>
<del>
<ide> /**
<ide> * Basic service interface.
<ide> * | 6 |
Ruby | Ruby | fix granular swapping for primary_abstract_class | 741d029606e96181ba3fc6ee5f0b30ea9e9450e8 | <ide><path>activerecord/lib/active_record/connection_adapters/abstract/connection_handler.rb
<ide> def establish_connection(config, owner_name: Base, role: ActiveRecord::Base.curr
<ide> existing_pool_config = pool_manager.get_pool_config(role, shard)
<ide>
<ide> if existing_pool_config && existing_pool_config.db_config == db_config
<add> # Update the pool_config's connection class if it differs. This is used
<add> # for ensuring that ActiveRecord::Base and the primary_abstract_class use
<add> # the same pool. Without this granular swapping will not work correctly.
<add> if owner_name.primary_class? && (existing_pool_config.connection_class != owner_name)
<add> existing_pool_config.connection_class = owner_name
<add> end
<add>
<ide> existing_pool_config.pool
<ide> else
<ide> disconnect_pool_from_pool_manager(pool_manager, role, shard)
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
<ide> class ConnectionPool
<ide> include ConnectionAdapters::AbstractPool
<ide>
<ide> attr_accessor :automatic_reconnect, :checkout_timeout
<del> attr_reader :db_config, :size, :reaper, :pool_config, :connection_class, :async_executor, :role, :shard
<add> attr_reader :db_config, :size, :reaper, :pool_config, :async_executor, :role, :shard
<ide>
<del> alias_method :connection_klass, :connection_class
<del> deprecate :connection_klass
<ide> delegate :schema_cache, :schema_cache=, to: :pool_config
<ide>
<ide> # Creates a new ConnectionPool object. +pool_config+ is a PoolConfig
<ide> def initialize(pool_config)
<ide>
<ide> @pool_config = pool_config
<ide> @db_config = pool_config.db_config
<del> @connection_class = pool_config.connection_class
<ide> @role = pool_config.role
<ide> @shard = pool_config.shard
<ide>
<ide> def connection
<ide> @thread_cached_conns[connection_cache_key(current_thread)] ||= checkout
<ide> end
<ide>
<add> def connection_class # :nodoc:
<add> pool_config.connection_class
<add> end
<add> alias :connection_klass :connection_class
<add> deprecate :connection_klass
<add>
<ide> # Returns true if there is an open connection being used for the current thread.
<ide> #
<ide> # This method only works for connections that have been obtained through
<ide><path>activerecord/lib/active_record/connection_adapters/pool_config.rb
<ide> module ConnectionAdapters
<ide> class PoolConfig # :nodoc:
<ide> include Mutex_m
<ide>
<del> attr_reader :db_config, :connection_class, :role, :shard
<del> attr_accessor :schema_cache
<add> attr_reader :db_config, :role, :shard
<add> attr_accessor :schema_cache, :connection_class
<ide>
<ide> INSTANCES = ObjectSpace::WeakMap.new
<ide> private_constant :INSTANCES
<ide><path>activerecord/test/cases/connection_adapters/connection_swapping_nested_test.rb
<ide> def test_application_record_prevent_writes_can_be_changed
<ide>
<ide> # Switch everything to writing
<ide> ActiveRecord::Base.connected_to(role: :writing) do
<add> assert_not_predicate ActiveRecord::Base.connection, :preventing_writes?
<ide> assert_not_predicate ApplicationRecord.connection, :preventing_writes?
<ide>
<ide> ApplicationRecord.connected_to(role: :reading) do
<ide> assert_predicate ApplicationRecord.connection, :preventing_writes?
<ide> end
<add>
<add> # reading is fine bc it's looking up by AppRec but writing is not fine
<add> # bc its looking up by ARB in the stack
<add> ApplicationRecord.connected_to(role: :writing, prevent_writes: true) do
<add> assert_predicate ApplicationRecord.connection, :preventing_writes?
<add> end
<ide> end
<ide> ensure
<ide> ApplicationRecord.remove_connection | 4 |
Javascript | Javascript | reset effect list when we recompute children | 43645a658625317d56ce526591bc143ab31b6009 | <ide><path>src/renderers/shared/fiber/ReactFiber.js
<ide> exports.cloneFiber = function(fiber : Fiber, priorityLevel : PriorityLevel) : Fi
<ide> // extra memory if needed.
<ide> let alt = fiber.alternate;
<ide> if (alt) {
<del> // Whenever we clone, we do so to get a new work in progress.
<del> // This ensures that we've reset these in the new tree.
<add> // If we clone, then we do so from the "current" state. The current state
<add> // can't have any side-effects that are still valid so we reset just to be
<add> // sure.
<ide> alt.effectTag = NoEffect;
<ide> alt.nextEffect = null;
<ide> alt.firstEffect = null;
<ide><path>src/renderers/shared/fiber/ReactFiberBeginWork.js
<ide> module.exports = function<T, P, I, TI, C>(config : HostConfig<T, P, I, TI, C>, g
<ide>
<ide> function bailoutOnLowPriority(current, workInProgress) {
<ide> if (current) {
<add> // TODO: If I have started work on this node, mark it as finished, then
<add> // return do other work, come back and hit this node... we killed that
<add> // work. It is now in an inconsistent state. We probably need to check
<add> // progressedChild or something.
<ide> workInProgress.child = current.child;
<ide> workInProgress.memoizedProps = current.memoizedProps;
<ide> workInProgress.output = current.output;
<add> workInProgress.firstEffect = null;
<add> workInProgress.lastEffect = null;
<ide> }
<ide> return null;
<ide> }
<ide> module.exports = function<T, P, I, TI, C>(config : HostConfig<T, P, I, TI, C>, g
<ide> return bailoutOnLowPriority(current, workInProgress);
<ide> }
<ide>
<add> // If we don't bail out, we're going be recomputing our children so we need
<add> // to drop our effect list.
<add> workInProgress.firstEffect = null;
<add> workInProgress.lastEffect = null;
<add>
<ide> if (workInProgress.progressedPriority === priorityLevel) {
<ide> // If we have progressed work on this priority level already, we can
<ide> // proceed this that as the child.
<ide><path>src/renderers/shared/fiber/ReactFiberScheduler.js
<ide> module.exports = function<T, P, I, TI, C>(config : HostConfig<T, P, I, TI, C>) {
<ide> effectfulFiber.nextEffect = null;
<ide> effectfulFiber = next;
<ide> }
<add>
<add> // Finally if the root itself had an effect, we perform that since it is not
<add> // part of the effect list.
<add> if (finishedWork.effectTag !== NoEffect) {
<add> const current = finishedWork.alternate;
<add> commitWork(current, finishedWork);
<add> }
<ide> }
<ide>
<ide> function resetWorkPriority(workInProgress : Fiber) {
<ide> module.exports = function<T, P, I, TI, C>(config : HostConfig<T, P, I, TI, C>) {
<ide> workInProgress.pendingProps = null;
<ide> workInProgress.updateQueue = null;
<ide>
<del> // If this fiber had side-effects, we append it to the end of its own
<del> // effect list.
<del> if (workInProgress.effectTag !== NoEffect) {
<del> // Schedule a side-effect on this fiber, AFTER the children's
<del> // side-effects. We can perform certain side-effects earlier if
<del> // needed, by doing multiple passes over the effect list.
<del> if (workInProgress.lastEffect) {
<del> workInProgress.lastEffect.nextEffect = workInProgress;
<del> } else {
<del> workInProgress.firstEffect = workInProgress;
<del> }
<del> workInProgress.lastEffect = workInProgress;
<del> }
<del>
<ide> const returnFiber = workInProgress.return;
<ide>
<ide> if (returnFiber) {
<ide> module.exports = function<T, P, I, TI, C>(config : HostConfig<T, P, I, TI, C>) {
<ide> }
<ide> returnFiber.lastEffect = workInProgress.lastEffect;
<ide> }
<add>
<add> // If this fiber had side-effects, we append it AFTER the children's
<add> // side-effects. We can perform certain side-effects earlier if
<add> // needed, by doing multiple passes over the effect list. We don't want
<add> // to schedule our own side-effect on our own list because if end up
<add> // reusing children we'll schedule this effect onto itself since we're
<add> // at the end.
<add> if (workInProgress.effectTag !== NoEffect) {
<add> if (returnFiber.lastEffect) {
<add> returnFiber.lastEffect.nextEffect = workInProgress;
<add> } else {
<add> returnFiber.firstEffect = workInProgress;
<add> }
<add> returnFiber.lastEffect = workInProgress;
<add> }
<ide> }
<ide>
<ide> if (next) { | 3 |
Go | Go | show right tag for container in ps | e45deceb462351f841aa077819fdef3166381c50 | <ide><path>daemon/list.go
<ide> import (
<ide> "strconv"
<ide> "strings"
<ide>
<add> "github.com/docker/docker/graph"
<ide> "github.com/docker/docker/pkg/graphdb"
<ide>
<ide> "github.com/docker/docker/engine"
<add> "github.com/docker/docker/pkg/parsers"
<ide> "github.com/docker/docker/pkg/parsers/filters"
<ide> )
<ide>
<ide> func (daemon *Daemon) Containers(job *engine.Job) engine.Status {
<ide> out := &engine.Env{}
<ide> out.SetJson("Id", container.ID)
<ide> out.SetList("Names", names[container.ID])
<del> out.SetJson("Image", daemon.Repositories().ImageName(container.ImageID))
<add> img := container.Config.Image
<add> _, tag := parsers.ParseRepositoryTag(container.Config.Image)
<add> if tag == "" {
<add> img = img + ":" + graph.DEFAULTTAG
<add> }
<add> out.SetJson("Image", img)
<ide> if len(container.Args) > 0 {
<ide> args := []string{}
<ide> for _, arg := range container.Args {
<ide><path>integration-cli/docker_cli_ps_test.go
<ide> func TestPsListContainersFilterExited(t *testing.T) {
<ide>
<ide> logDone("ps - test ps filter exited")
<ide> }
<add>
<add>func TestPsRightTagName(t *testing.T) {
<add> tag := "asybox:shmatest"
<add> defer deleteAllContainers()
<add> defer deleteImages(tag)
<add> if out, err := exec.Command(dockerBinary, "tag", "busybox", tag).CombinedOutput(); err != nil {
<add> t.Fatalf("Failed to tag image: %s, out: %q", err, out)
<add> }
<add>
<add> var id1 string
<add> if out, err := exec.Command(dockerBinary, "run", "-d", "busybox", "top").CombinedOutput(); err != nil {
<add> t.Fatalf("Failed to run container: %s, out: %q", err, out)
<add> } else {
<add> id1 = strings.TrimSpace(string(out))
<add> }
<add>
<add> var id2 string
<add> if out, err := exec.Command(dockerBinary, "run", "-d", tag, "top").CombinedOutput(); err != nil {
<add> t.Fatalf("Failed to run container: %s, out: %q", err, out)
<add> } else {
<add> id2 = strings.TrimSpace(string(out))
<add> }
<add> out, err := exec.Command(dockerBinary, "ps", "--no-trunc").CombinedOutput()
<add> if err != nil {
<add> t.Fatalf("Failed to run 'ps': %s, out: %q", err, out)
<add> }
<add> lines := strings.Split(strings.TrimSpace(string(out)), "\n")
<add> // skip header
<add> lines = lines[1:]
<add> if len(lines) != 2 {
<add> t.Fatalf("There should be 2 running container, got %d", len(lines))
<add> }
<add> for _, line := range lines {
<add> f := strings.Fields(line)
<add> switch f[0] {
<add> case id1:
<add> if f[1] != "busybox:latest" {
<add> t.Fatalf("Expected %s tag for id %s, got %s", "busybox", id1, f[1])
<add> }
<add> case id2:
<add> if f[1] != tag {
<add> t.Fatalf("Expected %s tag for id %s, got %s", tag, id1, f[1])
<add> }
<add> default:
<add> t.Fatalf("Unexpected id %s, expected %s and %s", f[0], id1, id2)
<add> }
<add> }
<add> logDone("ps - right tags for containers")
<add>} | 2 |
Text | Text | update doc version # | 43438d630308fb81662d6549ec74ddf49c33cd99 | <ide><path>docs/07-Advanced.md
<ide> The bar controller has a special property that you should be aware of. To correc
<ide>
<ide> ### Creating Plugins
<ide>
<del>Starting with v2.0.3, you can create plugins for chart.js. To register your plugin, simply call `Chart.pluginService.register` and pass your plugin in.
<add>Starting with v2.1.0, you can create plugins for chart.js. To register your plugin, simply call `Chart.pluginService.register` and pass your plugin in.
<ide> Plugins will be called at the following times
<ide> * Start of initialization
<ide> * End of initialization | 1 |
Javascript | Javascript | add function for checking url | 084a8bca031bf8d7aff49f51083afac5b0d5c503 | <ide><path>src/core.js
<ide> var Page = (function PageClosure() {
<ide> return null;
<ide> return item.get(name);
<ide> }
<add> function isValidUrl(url) {
<add> if (!url)
<add> return false;
<add> var colon = url.indexOf(':');
<add> if (colon < 0)
<add> return false;
<add> var protocol = url.substr(0, colon);
<add> switch (protocol) {
<add> case 'http':
<add> case 'https':
<add> case 'ftp':
<add> return true;
<add> default:
<add> return false;
<add> }
<add> }
<ide>
<ide> var annotations = xref.fetchIfRef(this.annotations) || [];
<ide> var i, n = annotations.length;
<ide> var Page = (function PageClosure() {
<ide> var url = a.get('URI');
<ide> // TODO: pdf spec mentions urls can be relative to a Base
<ide> // entry in the dictionary.
<del> // For now only allow http and https schemes.
<del> if (url.search(/^https?\:/) !== 0)
<add> if (!isValidUrl(url))
<ide> url = '';
<ide> item.url = url;
<ide> break; | 1 |
Python | Python | add ui endpoint to get "next run datasets" info | 1789f595f2de8ce441bb73c01527e1f25e9809dc | <ide><path>airflow/www/views.py
<ide> from airflow.models.dag import DAG, get_dataset_triggered_next_run_info
<ide> from airflow.models.dagcode import DagCode
<ide> from airflow.models.dagrun import DagRun, DagRunType
<del>from airflow.models.dataset import Dataset
<add>from airflow.models.dataset import Dataset, DatasetDagRef, DatasetDagRunQueue
<ide> from airflow.models.operator import Operator
<ide> from airflow.models.serialized_dag import SerializedDagModel
<ide> from airflow.models.taskinstance import TaskInstance
<ide> def grid_data(self):
<ide> {'Content-Type': 'application/json; charset=utf-8'},
<ide> )
<ide>
<add> @expose('/object/next_run_datasets/<string:dag_id>')
<add> @auth.has_access([(permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG)])
<add> def next_run_datasets(self, dag_id):
<add> """Returns datasets necessary, and their status, for the next dag run"""
<add> dag = get_airflow_app().dag_bag.get_dag(dag_id)
<add> if not dag:
<add> return {'error': f"can't find dag {dag_id}"}, 404
<add>
<add> with create_session() as session:
<add> data = [
<add> dict(info)
<add> for info in session.query(
<add> Dataset.id,
<add> Dataset.uri,
<add> DatasetDagRunQueue.created_at,
<add> )
<add> .join(DatasetDagRef, Dataset.id == DatasetDagRef.dataset_id)
<add> .join(
<add> DatasetDagRunQueue,
<add> and_(
<add> DatasetDagRunQueue.dataset_id == DatasetDagRef.dataset_id,
<add> DatasetDagRunQueue.target_dag_id == DatasetDagRef.dag_id,
<add> ),
<add> isouter=True,
<add> )
<add> .filter(DatasetDagRef.dag_id == dag_id)
<add> .order_by(Dataset.id)
<add> .all()
<add> ]
<add> return (
<add> htmlsafe_json_dumps(data, separators=(',', ':'), cls=utils_json.AirflowJsonEncoder),
<add> {'Content-Type': 'application/json; charset=utf-8'},
<add> )
<add>
<ide> @expose('/robots.txt')
<ide> @action_logging
<ide> def robots(self):
<ide><path>tests/test_utils/db.py
<ide> errors,
<ide> )
<ide> from airflow.models.dagcode import DagCode
<del>from airflow.models.dataset import Dataset, DatasetEvent
<add>from airflow.models.dataset import Dataset, DatasetDagRef, DatasetDagRunQueue, DatasetEvent, DatasetTaskRef
<ide> from airflow.models.serialized_dag import SerializedDagModel
<ide> from airflow.security.permissions import RESOURCE_DAG_PREFIX
<ide> from airflow.utils.db import add_default_pool_if_not_exists, create_default_connections, reflect_tables
<ide> def clear_db_datasets():
<ide> with create_session() as session:
<ide> session.query(DatasetEvent).delete()
<ide> session.query(Dataset).delete()
<add> session.query(DatasetDagRunQueue).delete()
<add> session.query(DatasetDagRef).delete()
<add> session.query(DatasetTaskRef).delete()
<ide>
<ide>
<ide> def clear_db_dags():
<ide><path>tests/www/views/test_views_grid.py
<ide> from airflow.lineage.entities import File
<ide> from airflow.models import DagBag
<ide> from airflow.models.dagrun import DagRun
<del>from airflow.models.dataset import Dataset
<add>from airflow.models.dataset import Dataset, DatasetDagRunQueue
<ide> from airflow.operators.empty import EmptyOperator
<ide> from airflow.utils.state import DagRunState, TaskInstanceState
<ide> from airflow.utils.task_group import TaskGroup
<ide> def _expected_task_details(task_id, has_outlet_datasets):
<ide> 'label': None,
<ide> },
<ide> }
<add>
<add>
<add>def test_next_run_datasets(admin_client, dag_maker, session, app, monkeypatch):
<add> with monkeypatch.context() as m:
<add> datasets = [Dataset(id=i, uri=f's3://bucket/key/{i}') for i in [1, 2]]
<add> session.add_all(datasets)
<add> session.commit()
<add>
<add> with dag_maker(dag_id=DAG_ID, schedule_on=datasets, serialized=True, session=session):
<add> EmptyOperator(task_id='task1')
<add>
<add> m.setattr(app, 'dag_bag', dag_maker.dagbag)
<add>
<add> ddrq = DatasetDagRunQueue(
<add> target_dag_id=DAG_ID, dataset_id=1, created_at=pendulum.DateTime(2022, 8, 1, tzinfo=UTC)
<add> )
<add> session.add(ddrq)
<add> session.commit()
<add>
<add> resp = admin_client.get(f'/object/next_run_datasets/{DAG_ID}', follow_redirects=True)
<add>
<add> assert resp.status_code == 200, resp.json
<add> assert resp.json == [
<add> {'id': 1, 'uri': 's3://bucket/key/1', 'created_at': "2022-08-01T00:00:00+00:00"},
<add> {'id': 2, 'uri': 's3://bucket/key/2', 'created_at': None},
<add> ]
<add>
<add>
<add>def test_next_run_datasets_404(admin_client):
<add> resp = admin_client.get('/object/next_run_datasets/missingdag', follow_redirects=True)
<add> assert resp.status_code == 404, resp.json
<add> assert resp.json == {'error': "can't find dag missingdag"} | 3 |
Ruby | Ruby | fix lingering references to book | b4120d0a3069e60ddcd2505e3212a4267edc1f88 | <ide><path>activerecord/test/cases/encryption/encryptable_record_test.rb
<ide> require "models/traffic_light_encrypted"
<ide>
<ide> class ActiveRecord::Encryption::EncryptableRecordTest < ActiveRecord::EncryptionTestCase
<del> fixtures :books, :posts
<add> fixtures :encrypted_books, :posts
<ide>
<ide> test "encrypts the attribute seamlessly when creating and updating records" do
<ide> post = EncryptedPost.create!(title: "The Starfleet is here!", body: "take cover!")
<ide> class ActiveRecord::Encryption::EncryptableRecordTest < ActiveRecord::Encryption
<ide> end
<ide>
<ide> test "can only save unencrypted attributes when frozen encryption is true" do
<del> book = books(:awdr).becomes(EncryptedBook)
<add> book = encrypted_books(:awdr)
<add>
<ide> ActiveRecord::Encryption.with_encryption_context frozen_encryption: true do
<ide> book.update! updated_at: Time.now
<ide> end
<ide> def encryption_key
<ide> end
<ide> end
<ide>
<del> class BookThatWillFailToEncryptName < Book
<del> self.table_name = "books"
<add> class BookThatWillFailToEncryptName < UnencryptedBook
<add> self.table_name = "encrypted_books"
<ide>
<ide> encrypts :name, key_provider: FailingKeyProvider.new
<ide> end | 1 |
Javascript | Javascript | support persistent cache | 6a7978f1bc3bd83e37756e97f01a640df0b56e33 | <ide><path>lib/dependencies/URLDependency.js
<ide> "use strict";
<ide>
<ide> const RuntimeGlobals = require("../RuntimeGlobals");
<add>const makeSerializable = require("../util/makeSerializable");
<ide> const ModuleDependency = require("./ModuleDependency");
<ide>
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<ide> URLDependency.Template = class URLDependencyTemplate extends ModuleDependency.Te
<ide> }
<ide> };
<ide>
<add>makeSerializable(URLDependency, "webpack/lib/dependencies/URLDependency");
<add>
<ide> module.exports = URLDependency;
<ide><path>lib/util/internalSerializables.js
<ide> module.exports = {
<ide> "dependencies/SystemPlugin": () => require("../dependencies/SystemPlugin"),
<ide> "dependencies/UnsupportedDependency": () =>
<ide> require("../dependencies/UnsupportedDependency"),
<add> "dependencies/URLDependency": () => require("../dependencies/URLDependency"),
<ide> "dependencies/WebAssemblyExportImportedDependency": () =>
<ide> require("../dependencies/WebAssemblyExportImportedDependency"),
<ide> "dependencies/WebAssemblyImportDependency": () => | 2 |
Text | Text | fix minor issues in airflow release guide | 42bbeb0f37c47bd6ed7e04d494fc22b6273d8ace | <ide><path>dev/README_RELEASE_AIRFLOW.md
<ide> also performs image verification before pushing the images.
<ide> Subject:
<ide>
<ide> ```
<del>[VOTE] Airflow 2.0.2rc3
<add>[VOTE] Release Airflow 2.0.2 from 2.0.2rc1
<ide> ```
<ide>
<ide> Body:
<ide>
<ide> ```
<del>Hey all,
<add>Hey fellow Airflowers,
<ide>
<ide> I have cut Airflow 2.0.2 RC3. This email is calling a vote on the release,
<ide> which will last for 72 hours. Consider this my (binding) +1.
<ide>
<ide> Airflow 2.0.2 RC3 is available at:
<ide> https://dist.apache.org/repos/dist/dev/airflow/2.0.2rc3/
<ide>
<del>*apache-airflow-2.0.2rc3-source.tar.gz* is a source release that comes
<del>with INSTALL instructions.
<del>*apache-airflow-2.0.2rc3-bin.tar.gz* is the binary Python "sdist" release.
<add>*apache-airflow-2.0.2-source.tar.gz* is a source release that comes with INSTALL instructions.
<add>*apache-airflow-2.0.2.tar.gz* is the binary Python "sdist" release.
<add>*apache_airflow-2.0.2-py3-none-any.wh*l is the binary Python wheel "binary" release.
<ide>
<ide> Public keys are available at:
<ide> https://dist.apache.org/repos/dist/release/airflow/KEYS
<ide>
<add>Please vote accordingly:
<add>
<add>[ ] +1 approve
<add>[ ] +0 no opinion
<add>[ ] -1 disapprove with the reason
<add>
<ide> Only votes from PMC members are binding, but the release manager should encourage members of the community
<ide> to test the release and vote with "(non-binding)".
<ide>
<ide> The test procedure for PMCs and Contributors who would like to test this RC are described in
<del>https://github.com/apache/airflow/blob/main/dev/README.md#vote-and-verify-the-apache-airflow-release-candidate
<add>https://github.com/apache/airflow/blob/main/dev/README_RELEASE_AIRFLOW.md#verify-the-release-candidate-by-pmcs
<ide>
<ide> Please note that the version number excludes the `rcX` string, so it's now
<ide> simply 2.0.2. This will allow us to rename the artifact without modifying
<ide> the artifact checksums when we actually release.
<ide>
<add>Full Changelog: (https://github.com/apache/airflow/blob/2.0.2rc3/CHANGELOG.txt).
<ide>
<ide> Changes since 2.0.2rc2:
<ide> *Bugs*: | 1 |
Javascript | Javascript | move multicolumn out to separate example | 0b3d28f8f17f71fbe0b889ec430005d9e4f01db4 | <add><path>packages/rn-tester/js/examples/FlatList/FlatList-multiColumn.js
<del><path>packages/rn-tester/js/examples/MultiColumn/MultiColumnExample.js
<ide> */
<ide>
<ide> 'use strict';
<add>import type {RNTesterModuleExample} from '../../types/RNTesterTypes';
<ide> const RNTesterPage = require('../../components/RNTesterPage');
<ide> const React = require('react');
<ide>
<ide> const styles = StyleSheet.create({
<ide> },
<ide> });
<ide>
<del>exports.title = 'FlatList - MultiColumn';
<del>exports.category = 'ListView';
<del>exports.description = 'Performant, scrollable grid of data.';
<del>exports.examples = [
<del> {
<del> title: 'Simple flat list multi column',
<del> render: function(): React.Element<typeof MultiColumnExample> {
<del> return <MultiColumnExample />;
<del> },
<del> },
<del>];
<add>export default ({
<add> title: 'MultiColumn',
<add> name: 'multicolumn',
<add> description: 'Performant, scrollable grid of data',
<add> render: () => <MultiColumnExample />,
<add>}: RNTesterModuleExample);
<ide><path>packages/rn-tester/js/examples/FlatList/FlatListExampleIndex.js
<ide> import ContentInsetExample from './FlatList-contentInset';
<ide> import InvertedExample from './FlatList-inverted';
<ide> import onViewableItemsChangedExample from './FlatList-onViewableItemsChanged';
<ide> import WithSeparatorsExample from './FlatList-withSeparators';
<add>import MultiColumnExample from './FlatList-multiColumn';
<ide>
<ide> export default ({
<ide> framework: 'React',
<ide> export default ({
<ide> InvertedExample,
<ide> onViewableItemsChangedExample,
<ide> WithSeparatorsExample,
<add> MultiColumnExample,
<ide> ],
<ide> }: RNTesterModule);
<ide><path>packages/rn-tester/js/utils/RNTesterList.android.js
<ide> const Components: Array<RNTesterModuleInfo> = [
<ide> category: 'UI',
<ide> module: require('../examples/Modal/ModalExample'),
<ide> },
<del> {
<del> key: 'MultiColumnExample',
<del> category: 'ListView',
<del> module: require('../examples/MultiColumn/MultiColumnExample'),
<del> },
<ide> {
<ide> key: 'NewAppScreenExample',
<ide> module: require('../examples/NewAppScreen/NewAppScreenExample'),
<ide><path>packages/rn-tester/js/utils/RNTesterList.ios.js
<ide> const Components: Array<RNTesterModuleInfo> = [
<ide> module: require('../examples/Modal/ModalExample'),
<ide> supportsTVOS: true,
<ide> },
<del> {
<del> key: 'MultiColumnExample',
<del> module: require('../examples/MultiColumn/MultiColumnExample'),
<del> supportsTVOS: true,
<del> },
<ide> {
<ide> key: 'NewAppScreenExample',
<ide> module: require('../examples/NewAppScreen/NewAppScreenExample'), | 4 |
PHP | PHP | remove header setting | 0f2db34406f6fb0aab98de10e3d2fce5a8f97fc6 | <ide><path>src/Illuminate/Routing/Router.php
<ide> public static function toResponse($request, $response)
<ide> $response->setNotModified();
<ide> }
<ide>
<del> if (! $response->headers->has('Permissions-Policy')) {
<del> $response->headers->set('Permissions-Policy', 'interest-cohort=()');
<del> }
<del>
<ide> return $response->prepare($request);
<ide> }
<ide> | 1 |
Go | Go | add more todo's for image list, and reformat | a1bc0a6d79187344e1be3b27f3710400fd6dc38c | <ide><path>daemon/containerd/image_list.go
<ide> var acceptedImageFilterTags = map[string]bool{
<ide> // Images returns a filtered list of images.
<ide> //
<ide> // TODO(thaJeztah): sort the results by created (descending); see https://github.com/moby/moby/issues/43848
<add>// TODO(thaJeztah): implement opts.ContainerCount (used for docker system df); see https://github.com/moby/moby/issues/43853
<add>// TODO(thaJeztah): add labels to results; see https://github.com/moby/moby/issues/43852
<add>// TODO(thaJeztah): verify behavior of `RepoDigests` and `RepoTags` for images without (untagged) or multiple tags; see https://github.com/moby/moby/issues/43861
<add>// TODO(thaJeztah): verify "Size" vs "VirtualSize" in images; see https://github.com/moby/moby/issues/43862
<ide> func (i *ImageService) Images(ctx context.Context, opts types.ImageListOptions) ([]*types.ImageSummary, error) {
<ide> if err := opts.Filters.Validate(acceptedImageFilterTags); err != nil {
<ide> return nil, err
<ide> func (i *ImageService) Images(ctx context.Context, opts types.ImageListOptions)
<ide>
<ide> snapshotter := i.client.SnapshotService(containerd.DefaultSnapshotter)
<ide>
<del> var ret []*types.ImageSummary
<add> var summaries []*types.ImageSummary
<ide> for _, img := range imgs {
<ide> if !filter(img) {
<ide> continue
<ide> func (i *ImageService) Images(ctx context.Context, opts types.ImageListOptions)
<ide> return nil, err
<ide> }
<ide>
<del> ret = append(ret, &types.ImageSummary{
<del> RepoDigests: []string{img.Name() + "@" + img.Target().Digest.String()}, // "hello-world@sha256:bfea6278a0a267fad2634554f4f0c6f31981eea41c553fdf5a83e95a41d40c38"},
<del> RepoTags: []string{img.Name()},
<del> Containers: -1,
<add> summaries = append(summaries, &types.ImageSummary{
<ide> ParentID: "",
<del> SharedSize: -1,
<del> VirtualSize: virtualSize,
<ide> ID: img.Target().Digest.String(),
<ide> Created: img.Metadata().CreatedAt.Unix(),
<add> RepoDigests: []string{img.Name() + "@" + img.Target().Digest.String()}, // "hello-world@sha256:bfea6278a0a267fad2634554f4f0c6f31981eea41c553fdf5a83e95a41d40c38"},
<add> RepoTags: []string{img.Name()},
<ide> Size: size,
<add> VirtualSize: virtualSize,
<add> // -1 indicates that the value has not been set (avoids ambiguity
<add> // between 0 (default) and "not set". We cannot use a pointer (nil)
<add> // for this, as the JSON representation uses "omitempty", which would
<add> // consider both "0" and "nil" to be "empty".
<add> SharedSize: -1,
<add> Containers: -1,
<ide> })
<ide> }
<ide>
<del> return ret, nil
<add> return summaries, nil
<ide> }
<ide>
<ide> type imageFilterFunc func(image containerd.Image) bool | 1 |
Javascript | Javascript | move reactelementtype to shared | 890d52bafc5f6bfad122a59b80c695473c3fa6c1 | <add><path>src/shared/ReactElementType.js
<del><path>src/isomorphic/classic/element/ReactElementType.js
<ide>
<ide> 'use strict';
<ide>
<del>import type { ReactInstance } from 'ReactInstanceType';
<del>
<ide> export type Source = {
<ide> fileName: string,
<ide> lineNumber: number,
<ide> export type ReactElement = {
<ide> key: any,
<ide> ref: any,
<ide> props: any,
<del> _owner: ReactInstance,
<add> _owner: any, // ReactInstance or ReactFiber
<ide>
<ide> // __DEV__
<ide> _store: { | 1 |
Text | Text | add native modules (ios) guide | 822e6591778a9151c5ba08bd78b255b09918a81c | <ide><path>docs/NativeModulesIOS.md
<add>---
<add>id: nativemodulesios
<add>title: Native Modules (iOS)
<add>layout: docs
<add>category: Guides
<add>permalink: docs/nativemodulesios.html
<add>next: activityindicatorios
<add>---
<add>
<add>Sometimes an app needs access to platform API, and React Native doesn't have a corresponding wrapper yet. This is a more advanced guide that shows how to build a native module. It assumes the reader knows Objective-C (Swift is not supported yet) and core libraries (Foundation, UIKit).
<add>
<add>## iOS Calendar module example
<add>
<add>This guide will use iOS Calendar API example. Let's say we would like to be able to access iOS calendar from JavaScript.
<add>
<add>Native module is just an Objectve-C class that implements `RCTBridgeModule` protocol.
<add>
<add>```objective-c
<add>// RCTCalendarManager.h
<add>#import "RCTBridgeModule.h"
<add>
<add>@interface RCTCalendarManager : NSObject <RCTBridgeModule>
<add>@end
<add>```
<add>
<add>React Native will not expose any methods of `RCTCalendarManager` to JavaScript unless explicitly asked. Fortunately this is pretty easy with `RCT_EXPORT`:
<add>
<add>```objective-c
<add>// RCTCalendarManager.m
<add>@implementation RCTCalendarManager
<add>
<add>- (void)addEventWithName:(NSString *)name location:(NSString *)location
<add>{
<add> RCT_EXPORT();
<add> RCTLogInfo(@"Pretending to create an event %@ at @%@", name, location);
<add>}
<add>
<add>@end
<add>```
<add>
<add>Now from your JavaScript file you can call the method like this:
<add>
<add>```javascript
<add>var CalendarManager = require('NativeModules').CalendarManager;
<add>CalendarManager.addEventWithName('Birthday Party', '4 Privet Drive, Surrey');
<add>```
<add>
<add>Notice that the module name doesn't have `RCT` prefix. Exported method name was generated from first part of Objective-C selector. Sometimes it results in a non-idiomatic JavaScript name (like the one in our example). You can change the name by supplying an optional argument to `RCT_EXPORT`, e.g. `RCT_EXPORT("addEvent")`.
<add>
<add>The return type of the method should always be `void`. React Native bridge is asynchronous, so the only way to pass result to JavaScript is by using callbacks or emitting events (see below).
<add>
<add>## Argument types
<add>
<add>React Native supports several types of arguments that can be passed from JavaScript code to native module:
<add>
<add>- string (`NSString`)
<add>- number (`NSInteger`, `float`, `NSNumber`)
<add>- boolean (`BOOL`, `NSNumber`)
<add>- array (`NSArray`) of any types from this list
<add>- map (`NSDictionary`) with string keys and values of any type from this list
<add>- function (`RCTResponseSenderBlock`)
<add>
<add>In our `CalendarManager` example, if we want to pass event date to native, we have to convert it to a string or a number:
<add>
<add>```objective-c
<add>- (void)addEventWithName:(NSString *)name location:(NSString *)location date:(NSInteger)secondsSinceUnixEpoch
<add>{
<add> RCT_EXPORT("addEvent");
<add> NSDate *date = [NSDate dateWithTimeIntervalSince1970:secondsSinceUnixEpoch];
<add>}
<add>```
<add>
<add>As `CalendarManager.addEvent` method gets more and more complex, the number of arguments will grow. Some of them might be optional. In this case it's worth considering changing the API a little bit to accept a dictionary of event attributes, like this:
<add>
<add>```objective-c
<add>- (void)addEventWithName:(NSString *)name details:(NSDictionary *)details
<add>{
<add> RCT_EXPORT("addEvent");
<add> NSString *location = details[@"location"];
<add> if ([location isKindOfClass:[NSString class]]) {
<add> ...
<add> }
<add>}
<add>```
<add>
<add>and call it from JavaScript:
<add>
<add>```javascript
<add>CalendarManager.addEvent('Birthday Party', {
<add> location: '4 Privet Drive, Surrey',
<add> time: date.toTime(),
<add> description: '...'
<add>})
<add>```
<add>
<add>NOTE about array and map - React Native doesn't provide any guarantees about the types of values in these structures. Your native module might expect array of strings, but if JavaScript calls your method with an array that contains number and string you'll get `NSArray` with `NSNumber` and `NSString`. It's developer's responsibility to check array/map values types.
<add>
<add># Callbacks
<add>
<add>WARNING: This section is even more experimental than others, we don't have a set of best practices around callbacks yet.
<add>
<add>Native module also supports a special kind of argument - callback. In most cases it is used to provide function call result to JavaScript.
<add>
<add>```objective-c
<add>- (void)findEvents:(RCTResponseSenderBlock)callback
<add>{
<add> RCT_EXPORT();
<add> NSArray *events = ...
<add> callback(@[[NSNull null], events]);
<add>}
<add>```
<add>
<add>`RCTResponseSenderBlock` accepts only one argument - array of arguments to pass to JavaScript callback. In this case we use node's convention to set first argument to error and the rest - to the result of the function.
<add>
<add>```javascript
<add>CalendarManager.findEvents((error, events) => {
<add> if (error) {
<add> console.error(error);
<add> } else {
<add> this.setState({events: events});
<add> }
<add>})
<add>```
<add>
<add>Native module is supposed to invoke callback only once. It can, however, store the callback as an ivar and invoke it later. This pattern is often used to wrap iOS APIs that require delegate. See `RCTAlertManager`.
<add>
<add>If you want to pass error-like object to JavaScript, use `RCTMakeError` from `RCTUtils.h`.
<add>
<add>## Implementing native module
<add>
<add>The native module should not have any assumptions about what thread it is being called on. React Native invokes native modules methods on a separate serial GCD queue, but this is an implementation detail and might change. If the native module needs to call main-thread-only iOS API, it should schedule the operation on the main queue:
<add>
<add>
<add>```objective-c
<add>- (void)addEventWithName:(NSString *)name callback:(RCTResponseSenderBlock)callback
<add>{
<add> RCT_EXPORT("addEvent");
<add> dispatch_async(dispatch_get_main_queue(), ^{
<add> // Call iOS API on main thread
<add> ...
<add> // You can invoke callback from any thread/queue
<add> callback(@[...]);
<add> });
<add>}
<add>```
<add>
<add>The same way if the operation can take a long time to complete, the native module should not block. It is a good idea to use `dispatch_async` to schedule expensive work on background queue.
<add>
<add>## Exporting constants
<add>
<add>Native module can export constants that are instantly available to JavaScript at runtime. This is useful to export some initial data that would otherwise require a bridge round-trip.
<add>
<add>```objective-c
<add>- (NSDictionary *)constantsToExport
<add>{
<add> return @{ @"firstDayOfTheWeek": @"Monday" };
<add>}
<add>```
<add>
<add>JavaScript can use this value right away:
<add>
<add>```javascript
<add>console.log(CalendarManager.firstDayOfTheWeek);
<add>```
<add>
<add>Note that the constants are exported only at initialization time, so if you change `constantsToExport` value at runtime it won't affect JavaScript environment.
<add>
<add>
<add>## Sending events to JavaScript
<add>
<add>The native module can signal events to JavaScript without being invoked directly. The easiest way to do this is to use `eventDispatcher`:
<add>
<add>```objective-c
<add>- (void)calendarEventReminderReceived:(NSNotification *)notification
<add>{
<add> NSString *eventName = notification.userInfo[@"name"];
<add> [self.bridge.eventDispatcher sendAppEventWithName:@"EventReminder"
<add> body:@{@"name": eventName}];
<add>}
<add>```
<add>
<add>JavaScript code can subscribe to these events:
<add>
<add>```javascript
<add>var subscription = RCTDeviceEventEmitter.addListener(
<add> 'EventReminder',
<add> (reminder) => console.log(reminder.name)
<add>);
<add>...
<add>// Don't forget to unsubscribe
<add>subscription.remove();
<add>```
<add>
<add>For more examples of sending events to JavaScript, see `RCTLocationObserver`.
<ide><path>docs/Style.md
<ide> title: Style
<ide> layout: docs
<ide> category: Guides
<ide> permalink: docs/style.html
<del>next: activityindicatorios
<add>next: nativemodulesios
<ide> ---
<ide>
<ide> ## Declaring Styles | 2 |
Python | Python | use normalize_axis_index in np.roll | b6850e9c00055666fe9bd5f984750743ffcb85d2 | <ide><path>numpy/core/numeric.py
<ide> def roll(a, shift, axis=None):
<ide> return roll(a.ravel(), shift, 0).reshape(a.shape)
<ide>
<ide> else:
<add> axis = _validate_axis(axis, a.ndim, allow_duplicate=True)
<ide> broadcasted = broadcast(shift, axis)
<ide> if broadcasted.ndim > 1:
<ide> raise ValueError(
<ide> "'shift' and 'axis' should be scalars or 1D sequences")
<ide> shifts = {ax: 0 for ax in range(a.ndim)}
<ide> for sh, ax in broadcasted:
<del> if -a.ndim <= ax < a.ndim:
<del> shifts[ax % a.ndim] += sh
<del> else:
<del> raise ValueError("'axis' entry is out of bounds")
<add> shifts[ax] += sh
<ide>
<ide> rolls = [((slice(None), slice(None)),)] * a.ndim
<ide> for ax, offset in shifts.items():
<ide> def rollaxis(a, axis, start=0):
<ide> return a.transpose(axes)
<ide>
<ide>
<del>def _validate_axis(axis, ndim, argname=None):
<add>def _validate_axis(axis, ndim, argname=None, allow_duplicate=False):
<ide> try:
<ide> axis = [operator.index(axis)]
<ide> except TypeError:
<ide> axis = list(axis)
<ide> axis = [normalize_axis_index(ax, ndim, argname) for ax in axis]
<del> if len(set(axis)) != len(axis):
<add> if not allow_duplicate and len(set(axis)) != len(axis):
<ide> if argname:
<ide> raise ValueError('repeated axis in `%s` argument' % argname)
<ide> else: | 1 |
Text | Text | add note to parallelize make | cffbb326a2893348f137f8c53b141a61274742b1 | <ide><path>BUILDING.md
<ide> To build Node.js:
<ide>
<ide> ```console
<ide> $ ./configure
<del>$ make
<add>$ make -j4
<ide> ```
<ide>
<add>Running `make` with the `-j4` flag will cause it to run 4 compilation jobs
<add>concurrently which may significantly reduce build time. The number after `-j`
<add>can be changed to best suit the number of processor cores on your machine. If
<add>you run into problems running `make` with concurrency, try running it without
<add>the `-j4` flag. See the
<add>[GNU Make Documentation](https://www.gnu.org/software/make/manual/html_node/Parallel.html)
<add>for more information.
<add>
<ide> Note that the above requires that `python` resolve to Python 2.6 or 2.7 and not a newer version.
<ide>
<ide> To run the tests: | 1 |
Text | Text | alter description of build a city skyline step 102 | d425994852e1cb1bb57b44b363b22cd4c6f8f14c | <ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-css-variables-by-building-a-city-skyline/5d822fd413a79914d39e992f.md
<ide> dashedName: step-102
<ide>
<ide> # --description--
<ide>
<del>Add `display: flex` and `flex-wrap: wrap` to the window container. This will put your windows side by side, and then push them down to a new row when they don't fit.
<add>The windows are stacked on top of each other on the rightmost purple building. Turn the building into a flexbox parent, and use the `flex-wrap` property to put the windows side by side, and push them down to a new row when they don't fit.
<ide>
<ide> # --hints--
<ide> | 1 |
Ruby | Ruby | ensure no full stops at the end of desc | 640b1e9dcb3fb96f6a54c0d63da4fb1985351a83 | <ide><path>Library/Homebrew/rubocops/formula_desc_cop.rb
<ide> def audit_formula(_node, _class_node, _parent_class_node, body_node)
<ide> # - Checks for correct usage of `command-line` in `desc`
<ide> # - Checks description starts with a capital letter
<ide> # - Checks if `desc` contains the formula name
<add> # - Checks if `desc` ends with a full stop
<ide> class Desc < FormulaCop
<ide> VALID_LOWERCASE_WORDS = %w[
<ide> ex
<ide> def audit_formula(_node, _class_node, _parent_class_node, body_node)
<ide> end
<ide>
<ide> # Check if formula's desc starts with formula's name
<del> return unless regex_match_group(desc, /^#{@formula_name} /i)
<del> problem "Description shouldn't start with the formula name"
<add> if regex_match_group(desc, /^#{@formula_name} /i)
<add> problem "Description shouldn't start with the formula name"
<add> end
<add>
<add> # Check if a full stop is used at the end of a formula's desc
<add> return unless regex_match_group(desc, /\.$/)
<add> problem "Description shouldn't end with a full stop"
<ide> end
<ide>
<ide> private
<ide> def autocorrect(node)
<ide> correction.gsub!(/(^|[^a-z])#{@formula_name}([^a-z]|$)/i, "\\1\\2")
<ide> correction.gsub!(/^(['"]?)\s+/, "\\1")
<ide> correction.gsub!(/\s+(['"]?)$/, "\\1")
<add> correction.gsub!(/\.$/, "")
<ide> corrector.insert_before(node.source_range, correction)
<ide> corrector.remove(node.source_range)
<ide> end
<ide><path>Library/Homebrew/test/rubocops/formula_desc_cop_spec.rb
<ide> class Foo < Formula
<ide> RUBY
<ide> end
<ide>
<add> it "When the description ends with a full stop" do
<add> expect_offense(<<~RUBY, "/homebrew-core/Formula/foo.rb")
<add> class Foo < Formula
<add> url 'http://example.com/foo-1.0.tgz'
<add> desc 'Description with a full stop at the end.'
<add> ^ Description shouldn\'t end with a full stop
<add> end
<add> RUBY
<add> end
<add>
<ide> it "autocorrects all rules" do
<ide> source = <<~EOS
<ide> class Foo < Formula | 2 |
Text | Text | edit process.title note for brevity and clarity | 607183efff97a78e4daf9b624b7d973b207db9f9 | <ide><path>doc/api/process.md
<ide> allowed for longer process title strings by also overwriting the `environ`
<ide> memory but that was potentially insecure and confusing in some (rather obscure)
<ide> cases.
<ide>
<del>Assigning a value to `process.title` _may_ not reflect an accurate
<del>(or any) label within the process manager application of the underlying
<del>operating system (i.e. macOS Activity Monitor, Windows Services Manager, etc).
<del>Inconsistencies and breaking changes within the _operating systems process
<del>interface_ make synchronization with these applications unreliable.
<add>Assigning a value to `process.title` might not result in an accurate label
<add>within process manager applications such as macOS Activity Monitor or Windows
<add>Services Manager.
<ide>
<ide> ## `process.traceDeprecation`
<ide> <!-- YAML | 1 |
Ruby | Ruby | restrict `rpath` test to `--strict` | 39923cdb7f037e719aa32da96088c5603a080595 | <ide><path>Library/Homebrew/linkage_checker.rb
<ide> def display_test_output(puts_output: true, strict: false)
<ide> display_items "Broken dependencies", @broken_deps, puts_output: puts_output
<ide> display_items "Unwanted system libraries", @unwanted_system_dylibs, puts_output: puts_output
<ide> display_items "Conflicting libraries", @version_conflict_deps, puts_output: puts_output
<del> display_items "Undeclared dependencies with linkage", @undeclared_deps, puts_output: puts_output if strict
<add> return unless strict
<add>
<add> display_items "Undeclared dependencies with linkage", @undeclared_deps, puts_output: puts_output
<ide> display_items "Files with missing rpath", @files_missing_rpaths, puts_output: puts_output
<ide> end
<ide>
<ide> sig { params(strict: T::Boolean).returns(T::Boolean) }
<ide> def broken_library_linkage?(strict: false)
<del> issues = [@broken_deps, @unwanted_system_dylibs, @version_conflict_deps, @files_missing_rpaths]
<del> issues << @undeclared_deps if strict
<add> issues = [@broken_deps, @unwanted_system_dylibs, @version_conflict_deps]
<add> issues += [@undeclared_deps, @files_missing_rpaths] if strict
<ide> [issues, unexpected_broken_dylibs, unexpected_present_dylibs].flatten.any?(&:present?)
<ide> end
<ide> | 1 |
Javascript | Javascript | fix return description | 7cd79b6f8f153d77f910cf5bdf73037223687aa2 | <ide><path>src/ngMock/angular-mocks.js
<ide> angular.mock.$IntervalProvider = function() {
<ide> /**
<ide> * @ngdoc method
<ide> * @name $interval#cancel
<del> * @description
<del> *
<del> * Clears the interval.
<ide> *
<del> * @param {promise} The promise of the interval to cancel.
<add> * @description
<add> * Cancels a task associated with the `promise`.
<ide> *
<del> * @return {boolean}
<add> * @param {number} promise A promise from calling the `$interval` function.
<add> * @returns {boolean} Returns `true` if the task was successfully cancelled.
<ide> */
<ide> $interval.cancel = function(promise) {
<ide> if(!promise) return false; | 1 |
Javascript | Javascript | add known_issues test for | e8bb9e68c0260d453d650508e56d08006be72c9f | <ide><path>test/known_issues/test-vm-data-property-writable.js
<add>'use strict';
<add>// Refs: https://github.com/nodejs/node/issues/10223
<add>
<add>require('../common');
<add>const vm = require('vm');
<add>const assert = require('assert');
<add>
<add>const context = vm.createContext({});
<add>
<add>const code = `
<add> Object.defineProperty(this, 'foo', {value: 5});
<add> Object.getOwnPropertyDescriptor(this, 'foo');
<add>`;
<add>
<add>const desc = vm.runInContext(code, context);
<add>
<add>assert.strictEqual(desc.writable, false); | 1 |
Javascript | Javascript | fix performanceobserver 'gc' crash | ea0154814a6151739129b1f13674d96135a6f1e8 | <ide><path>lib/internal/perf/observe.js
<ide> const kDeprecationMessage =
<ide> const kTypeSingle = 0;
<ide> const kTypeMultiple = 1;
<ide>
<add>let gcTrackingInstalled = false;
<add>
<ide> const kSupportedEntryTypes = ObjectFreeze([
<ide> 'function',
<ide> 'gc',
<ide> function maybeIncrementObserverCount(type) {
<ide>
<ide> if (observerType !== undefined) {
<ide> observerCounts[observerType]++;
<del> if (observerType === NODE_PERFORMANCE_ENTRY_TYPE_GC)
<add> if (!gcTrackingInstalled &&
<add> observerType === NODE_PERFORMANCE_ENTRY_TYPE_GC) {
<ide> installGarbageCollectionTracking();
<add> gcTrackingInstalled = true;
<add> }
<ide> }
<ide> }
<ide>
<ide><path>test/parallel/test-performanceobserver-gc.js
<add>'use strict';
<add>
<add>require('../common');
<add>
<add>// Verifies that setting up two observers to listen
<add>// to gc performance does not crash.
<add>
<add>const {
<add> PerformanceObserver,
<add>} = require('perf_hooks');
<add>
<add>// We don't actually care if the callback is ever invoked in this test
<add>const obs = new PerformanceObserver(() => {});
<add>const obs2 = new PerformanceObserver(() => {});
<add>
<add>obs.observe({ type: 'gc' });
<add>obs2.observe({ type: 'gc' }); | 2 |
Go | Go | fix a timeout bug in sender/receiver | dfdc03b061d5bd5a7557f077b500304d4da26d2e | <ide><path>engine/remote.go
<ide> func (rcv *Receiver) Run() error {
<ide> f.Close()
<ide> return err
<ide> }
<add> f.Close()
<add> defer peer.Close()
<ide> cmd := data.Message(p).Get("cmd")
<ide> job := rcv.Engine.Job(cmd[0], cmd[1:]...)
<ide> stdout, err := beam.SendRPipe(peer, data.Empty().Set("cmd", "log", "stdout").Bytes())
<ide><path>engine/remote_test.go
<ide> package engine
<ide>
<del>import ()
<add>import (
<add> "bytes"
<add> "fmt"
<add> "github.com/dotcloud/docker/pkg/beam"
<add> "strings"
<add> "testing"
<add> "time"
<add>)
<add>
<add>func TestHelloWorld(t *testing.T) {
<add> testRemote(t,
<add>
<add> // Sender side
<add> func(eng *Engine) {
<add> job := eng.Job("echo", "hello", "world")
<add> out := &bytes.Buffer{}
<add> job.Stdout.Add(out)
<add> job.Run()
<add> if job.status != StatusOK {
<add> t.Fatalf("#%v", job.StatusCode())
<add> }
<add> if out.String() != "hello world\n" {
<add> t.Fatalf("%#v", out.String())
<add> }
<add> },
<add>
<add> // Receiver side
<add> func(eng *Engine) {
<add> eng.Register("echo", func(job *Job) Status {
<add> fmt.Fprintf(job.Stdout, "%s\n", strings.Join(job.Args, " "))
<add> return StatusOK
<add> })
<add> },
<add> )
<add>}
<add>
<add>func testRemote(t *testing.T, senderSide, receiverSide func(*Engine)) {
<add> sndConn, rcvConn, err := beam.USocketPair()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer sndConn.Close()
<add> defer rcvConn.Close()
<add> sender := NewSender(sndConn)
<add> receiver := NewReceiver(rcvConn)
<add>
<add> // Setup the sender side
<add> eng := New()
<add> sender.Install(eng)
<add>
<add> // Setup the receiver side
<add> receiverSide(receiver.Engine)
<add> go receiver.Run()
<add>
<add> timeout(t, func() {
<add> senderSide(eng)
<add> })
<add>}
<add>
<add>func timeout(t *testing.T, f func()) {
<add> onTimeout := time.After(100 * time.Millisecond)
<add> onDone := make(chan bool)
<add> go func() {
<add> f()
<add> close(onDone)
<add> }()
<add> select {
<add> case <-onTimeout:
<add> t.Fatalf("timeout")
<add> case <-onDone:
<add> }
<add>} | 2 |
Javascript | Javascript | dashify challenge block property on seed | 4ea8c019f07a753a17123d428089c85ec7f30184 | <ide><path>index.js
<ide> Observable.combineLatest(
<ide> challenge.helpRoom = helpRoom;
<ide> challenge.order = order;
<ide> challenge.suborder = index + 1;
<del> challenge.block = blockName;
<add> challenge.block = dasherize(blockName);
<ide> challenge.blockId = block.id;
<ide> challenge.isBeta = challenge.isBeta || isBeta;
<ide> challenge.isComingSoon = challenge.isComingSoon || isComingSoon; | 1 |
Javascript | Javascript | add tls.tlssocket to typemap | 8698f691c162c87342f3533539040966ee337acd | <ide><path>tools/doc/type-parser.js
<ide> const typeMap = {
<ide> 'cluster.Worker': 'cluster.html#cluster_class_worker',
<ide> 'dgram.Socket': 'dgram.html#dgram_class_dgram_socket',
<ide> 'net.Socket': 'net.html#net_class_net_socket',
<add> 'tls.TLSSocket': 'tls.html#tls_class_tls_tlssocket',
<ide> 'EventEmitter': 'events.html#events_class_eventemitter',
<ide> 'Timer': 'timers.html#timers_timers'
<ide> }; | 1 |
Javascript | Javascript | remove the caching variable | 97c4033ebf2cf0e67c2ad0ad5dd50ea627d0efae | <ide><path>lib/readline.js
<ide> Interface.prototype._tabComplete = function(lastKeypressWasTab) {
<ide> maxColumns = 1;
<ide> }
<ide> var group = [];
<del> for (var i = 0, compLen = completions.length; i < compLen; i++) {
<add> for (var i = 0; i < completions.length; i++) {
<ide> var c = completions[i];
<ide> if (c === '') {
<ide> handleGroup(self, group, width, maxColumns);
<ide> function handleGroup(self, group, width, maxColumns) {
<ide> var item = group[idx];
<ide> self._writeToOutput(item);
<ide> if (col < maxColumns - 1) {
<del> for (var s = 0, itemLen = item.length; s < width - itemLen; s++) {
<add> for (var s = 0; s < width - item.length; s++) {
<ide> self._writeToOutput(' ');
<ide> }
<ide> } | 1 |
Ruby | Ruby | add documention for utc_offset method | 073043ff03d749bf4e929dda3f5e614c8109a129 | <ide><path>activesupport/lib/active_support/values/time_zone.rb
<ide> def initialize(name, utc_offset = nil, tzinfo = nil)
<ide> @current_period = nil
<ide> end
<ide>
<add> # Returns the offset of this time zone in seconds.
<ide> def utc_offset
<ide> if @utc_offset
<ide> @utc_offset | 1 |
PHP | PHP | fix typo in route\finder comment | 253e529c411f43df779b585bbdb15f0ef0187ca7 | <ide><path>system/route/loader.php
<ide> class Loader {
<ide> public static function load($uri)
<ide> {
<ide> // --------------------------------------------------------------
<del> // If a single routes is being used, return it.
<add> // If a single route file is being used, return it.
<ide> // --------------------------------------------------------------
<ide> if ( ! is_dir(APP_PATH.'routes'))
<ide> { | 1 |
Python | Python | remove mock test file on teardown | 3fa8975f7d1da76e6d04e52b3dcb9557a56af140 | <ide><path>libcloud/test/storage/test_google_storage.py
<ide> def setUp(self):
<ide> super(GoogleStorageTests, self).setUp()
<ide> self.driver_type.jsonConnectionCls.conn_class = GoogleStorageJSONMockHttp
<ide>
<add> def tearDown(self):
<add> self._remove_test_file()
<add>
<ide> def test_billing_not_enabled(self):
<ide> # TODO
<ide> pass
<ide> def test_download_object_data_is_not_buffered_in_memory(self):
<ide> obj = Object(name='foo_bar_object_NO_BUFFER', size=1000, hash=None, extra={},
<ide> container=container, meta_data=None,
<ide> driver=self.driver_type)
<del> destination_path = os.path.abspath(__file__) + '.temp'
<add> destination_path = self._file_path
<ide> result = self.driver.download_object(obj=obj,
<ide> destination_path=destination_path,
<ide> overwrite_existing=True,
<ide><path>libcloud/test/storage/test_s3.py
<ide> def setUp(self):
<ide> self.mock_response_klass.type = None
<ide> self.driver = self.create_driver()
<ide>
<add> self._file_path = os.path.abspath(__file__) + '.temp'
<add>
<ide> def tearDown(self):
<ide> self._remove_test_file()
<ide>
<ide> def _remove_test_file(self):
<del> file_path = os.path.abspath(__file__) + '.temp'
<del>
<ide> try:
<del> os.unlink(file_path)
<add> os.unlink(self._file_path)
<ide> except OSError:
<ide> pass
<ide>
<ide> def test_download_object_success(self):
<ide> obj = Object(name='foo_bar_object', size=1000, hash=None, extra={},
<ide> container=container, meta_data=None,
<ide> driver=self.driver_type)
<del> destination_path = os.path.abspath(__file__) + '.temp'
<add> destination_path = self._file_path
<ide> result = self.driver.download_object(obj=obj,
<ide> destination_path=destination_path,
<ide> overwrite_existing=True,
<ide> def test_download_object_data_is_not_buffered_in_memory(self):
<ide> obj = Object(name='foo_bar_object_NO_BUFFER', size=1000, hash=None, extra={},
<ide> container=container, meta_data=None,
<ide> driver=self.driver_type)
<del> destination_path = os.path.abspath(__file__) + '.temp'
<add> destination_path = self._file_path
<ide> result = self.driver.download_object(obj=obj,
<ide> destination_path=destination_path,
<ide> overwrite_existing=False,
<ide> def test_download_object_invalid_file_size(self):
<ide> obj = Object(name='foo_bar_object', size=1000, hash=None, extra={},
<ide> container=container, meta_data=None,
<ide> driver=self.driver_type)
<del> destination_path = os.path.abspath(__file__) + '.temp'
<add> destination_path = self._file_path
<ide> result = self.driver.download_object(obj=obj,
<ide> destination_path=destination_path,
<ide> overwrite_existing=False, | 2 |
PHP | PHP | extract base class out of subclasses | 4f8d1c41d6d0fe426c87a831eea451d7bcbb4acd | <ide><path>lib/Cake/Console/TaskCollection.php
<ide>
<ide> use Cake\Core\App;
<ide> use Cake\Error;
<add>use Cake\Utility\ObjectRegistry;
<ide>
<ide> /**
<ide> * Collection object for Tasks. Provides features
<ide> * for lazily loading tasks.
<ide> */
<del>class TaskCollection {
<del>
<del>/**
<del> * Map of loaded tasks.
<del> *
<del> * @var array
<del> */
<del> protected $_loaded = [];
<add>class TaskCollection extends ObjectRegistry {
<ide>
<ide> /**
<ide> * Shell to use to set params to tasks.
<ide> public function load($task, $settings = array()) {
<ide> return $this->_loaded[$alias];
<ide> }
<ide>
<del>/**
<del> * Get the loaded helpers list, or get the helper instance at a given name.
<del> *
<del> * @param null|string $name The helper name to get or null.
<del> * @return array|Helper Either a list of helper names, or a loaded helper.
<del> */
<del> public function loaded($name = null) {
<del> if (!empty($name)) {
<del> return isset($this->_loaded[$name]);
<del> }
<del> return array_keys($this->_loaded);
<del> }
<del>
<del>/**
<del> * Provide public read access to the loaded objects
<del> *
<del> * @param string $name Name of property to read
<del> * @return mixed
<del> */
<del> public function __get($name) {
<del> if (isset($this->_loaded[$name])) {
<del> return $this->_loaded[$name];
<del> }
<del> return null;
<del> }
<del>
<del>/**
<del> * Provide isset access to _loaded
<del> *
<del> * @param string $name Name of object being checked.
<del> * @return boolean
<del> */
<del> public function __isset($name) {
<del> return isset($this->_loaded[$name]);
<del> }
<del>
<ide> }
<ide><path>lib/Cake/Controller/ComponentCollection.php
<ide> use Cake\Error;
<ide> use Cake\Event\EventListener;
<ide> use Cake\Event\EventManager;
<add>use Cake\Utility\ObjectRegistry;
<ide>
<ide> /**
<ide> * Components collection is used as a registry for loaded components
<ide> *
<ide> * Handles loading, constructing and binding events for component class objects.
<ide> */
<del>class ComponentCollection {
<del>
<del>/**
<del> * Loaded objects
<del> *
<del> * @var array
<del> */
<del> protected $_loaded = [];
<add>class ComponentCollection extends ObjectRegistry {
<ide>
<ide> /**
<ide> * The controller that this collection was initialized with.
<ide> public function load($component, $settings = array()) {
<ide> return $this->_loaded[$alias];
<ide> }
<ide>
<del>/**
<del> * Get the loaded components list, or get the component instance at a given name.
<del> *
<del> * @param null|string $name The component name to get or null.
<del> * @return array|Helper Either a list of components names, or a loaded component.
<del> */
<del> public function loaded($name = null) {
<del> if (!empty($name)) {
<del> return isset($this->_loaded[$name]);
<del> }
<del> return array_keys($this->_loaded);
<del> }
<del>
<del>/**
<del> * Provide public read access to the loaded objects
<del> *
<del> * @param string $name Name of property to read
<del> * @return mixed
<del> */
<del> public function __get($name) {
<del> if (isset($this->_loaded[$name])) {
<del> return $this->_loaded[$name];
<del> }
<del> return null;
<del> }
<del>
<del>/**
<del> * Provide isset access to _loaded
<del> *
<del> * @param string $name Name of object being checked.
<del> * @return boolean
<del> */
<del> public function __isset($name) {
<del> return isset($this->_loaded[$name]);
<del> }
<del>
<ide> }
<ide><path>lib/Cake/Utility/ObjectRegistry.php
<add><?php
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * For full copyright and license information, please see the LICENSE.txt
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> * @link http://cakephp.org CakePHP(tm) Project
<add> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\Utility;
<add>
<add>/**
<add> * Acts as a registry/factory for objects.
<add> *
<add> * Provides registry & factory functionality for object types. Used
<add> * as a super class for various composition based re-use features in CakePHP.
<add> *
<add> * Each subclass needs to implement its own load() functionality. Replaces ObjectCollection
<add> * in previous versions of CakePHP.
<add> *
<add> * @since CakePHP 3.0
<add> * @see Cake\Controller\ComponentCollection
<add> * @see Cake\View\HelperCollection
<add> * @see Cake\Console\TaskCollection
<add> */
<add>abstract class ObjectRegistry {
<add>
<add>/**
<add> * Map of loaded objects.
<add> *
<add> * @var array
<add> */
<add> protected $_loaded = [];
<add>
<add>/**
<add> * Load instances for this registry.
<add> *
<add> * Overridden in subclasses.
<add> *
<add> * @param string $name The name/class of the object to load.
<add> * @param array $settings Additional settings to use when loading the object.
<add> * @return mixed.
<add> */
<add> abstract public function load($name, $settings = []);
<add>
<add>/**
<add> * Get the loaded object list, or get the object instance at a given name.
<add> *
<add> * @param null|string $name The object name to get or null.
<add> * @return array|Helper Either a list of object names, or a loaded object.
<add> */
<add> public function loaded($name = null) {
<add> if (!empty($name)) {
<add> return isset($this->_loaded[$name]);
<add> }
<add> return array_keys($this->_loaded);
<add> }
<add>
<add>/**
<add> * Provide public read access to the loaded objects
<add> *
<add> * @param string $name Name of property to read
<add> * @return mixed
<add> */
<add> public function __get($name) {
<add> if (isset($this->_loaded[$name])) {
<add> return $this->_loaded[$name];
<add> }
<add> return null;
<add> }
<add>
<add>/**
<add> * Provide isset access to _loaded
<add> *
<add> * @param string $name Name of object being checked.
<add> * @return boolean
<add> */
<add> public function __isset($name) {
<add> return isset($this->_loaded[$name]);
<add> }
<add>
<add>/**
<add> * Normalizes an object array, creates an array that makes lazy loading
<add> * easier
<add> *
<add> * @param array $objects Array of child objects to normalize.
<add> * @return array Array of normalized objects.
<add> */
<add> public static function normalizeObjectArray($objects) {
<add> $normal = array();
<add> foreach ($objects as $i => $objectName) {
<add> $options = array();
<add> if (!is_int($i)) {
<add> $options = (array)$objectName;
<add> $objectName = $i;
<add> }
<add> list(, $name) = pluginSplit($objectName);
<add> $normal[$name] = array('class' => $objectName, 'settings' => $options);
<add> }
<add> return $normal;
<add> }
<add>
<add>}
<ide><path>lib/Cake/View/HelperCollection.php
<ide> use Cake\Core\App;
<ide> use Cake\Error;
<ide> use Cake\Event\EventManager;
<add>use Cake\Utility\ObjectRegistry;
<ide> use Cake\View\View;
<ide>
<ide> /**
<ide> * Helpers collection is used as a registry for loaded helpers and handles loading
<ide> * and constructing helper class objects.
<ide> */
<del>class HelperCollection {
<del>
<del>/**
<del> * Hash of already loaded helpers.
<del> *
<del> * @var array
<del> */
<del> protected $_loaded = [];
<add>class HelperCollection extends ObjectRegistry {
<ide>
<ide> /**
<ide> * View object to use when making helpers.
<ide> public function load($helper, $settings = array()) {
<ide> return $helperObject;
<ide> }
<ide>
<del>/**
<del> * Get the loaded helpers list, or get the helper instance at a given name.
<del> *
<del> * @param null|string $name The helper name to get or null.
<del> * @return array|Helper Either a list of helper names, or a loaded helper.
<del> */
<del> public function loaded($name = null) {
<del> if (!empty($name)) {
<del> return isset($this->_loaded[$name]);
<del> }
<del> return array_keys($this->_loaded);
<del> }
<del>
<ide> } | 4 |
Ruby | Ruby | revert some warning removals related to ruby 2.0 | ded5f5b261b324767406baca41193c08c966008a | <ide><path>activesupport/lib/active_support/core_ext/date/calculations.rb
<ide> class Date
<ide> include DateAndTime::Calculations
<ide>
<del> @beginning_of_week_default = nil
<del>
<ide> class << self
<ide> attr_accessor :beginning_of_week_default
<ide>
<ide><path>activesupport/lib/active_support/core_ext/time/zones.rb
<ide> require 'active_support/time_with_zone'
<ide>
<ide> class Time
<del> @zone_default = nil
<del>
<ide> class << self
<ide> attr_accessor :zone_default
<ide>
<ide><path>railties/lib/rails/engine.rb
<ide> def find(path)
<ide> end
<ide> end
<ide>
<del> self.isolated = false
<del>
<ide> delegate :middleware, :root, :paths, to: :config
<ide> delegate :engine_name, :isolated?, to: :class
<ide> | 3 |
Javascript | Javascript | upgrade loaderplugin to es6 | 14d48beb7552027a3ecb39d990e73e784e5fc887 | <ide><path>lib/dependencies/LoaderPlugin.js
<ide> MIT License http://www.opensource.org/licenses/mit-license.php
<ide> Author Tobias Koppers @sokra
<ide> */
<del>var LoaderDependency = require("./LoaderDependency");
<add>"use strict";
<ide>
<del>function LoaderPlugin() {}
<del>module.exports = LoaderPlugin;
<del>
<del>LoaderPlugin.prototype.apply = function(compiler) {
<del> compiler.plugin("compilation", function(compilation, params) {
<del> var normalModuleFactory = params.normalModuleFactory;
<add>const LoaderDependency = require("./LoaderDependency");
<ide>
<del> compilation.dependencyFactories.set(LoaderDependency, normalModuleFactory);
<del> });
<del> compiler.plugin("compilation", function(compilation) {
<del> compilation.plugin("normal-module-loader", function(loaderContext, module) {
<del> loaderContext.loadModule = function loadModule(request, callback) {
<del> var dep = new LoaderDependency(request);
<del> dep.loc = request;
<del> compilation.addModuleDependencies(module, [
<del> [dep]
<del> ], true, "lm", false, function(err) {
<del> if(err) return callback(err);
<add>class LoaderPlugin {
<ide>
<del> if(!dep.module) return callback(new Error("Cannot load the module"));
<del> if(dep.module.building) dep.module.building.push(next);
<del> else next();
<add> apply(compiler) {
<add> compiler.plugin("compilation", (compilation, params) => {
<add> const normalModuleFactory = params.normalModuleFactory;
<ide>
<del> function next(err) {
<add> compilation.dependencyFactories.set(LoaderDependency, normalModuleFactory);
<add> });
<add> compiler.plugin("compilation", (compilation) => {
<add> compilation.plugin("normal-module-loader", (loaderContext, module) => {
<add> loaderContext.loadModule = function loadModule(request, callback) {
<add> const dep = new LoaderDependency(request);
<add> dep.loc = request;
<add> compilation.addModuleDependencies(module, [
<add> [dep]
<add> ], true, "lm", false, (err) => {
<ide> if(err) return callback(err);
<ide>
<del> if(dep.module.error) return callback(dep.module.error);
<del> if(!dep.module._source) throw new Error("The module created for a LoaderDependency must have a property _source");
<del> var source, map;
<del> var moduleSource = dep.module._source;
<del> if(moduleSource.sourceAndMap) {
<del> var sourceAndMap = moduleSource.sourceAndMap();
<del> map = sourceAndMap.map;
<del> source = sourceAndMap.source;
<del> } else {
<del> map = moduleSource.map();
<del> source = moduleSource.source();
<del> }
<del> if(dep.module.fileDependencies) {
<del> dep.module.fileDependencies.forEach(function(dep) {
<del> loaderContext.addDependency(dep);
<del> });
<del> }
<del> if(dep.module.contextDependencies) {
<del> dep.module.contextDependencies.forEach(function(dep) {
<del> loaderContext.addContextDependency(dep);
<del> });
<add> if(!dep.module) return callback(new Error("Cannot load the module"));
<add> if(dep.module.building) dep.module.building.push(next);
<add> else next();
<add>
<add> function next(err) {
<add> if(err) return callback(err);
<add>
<add> if(dep.module.error) return callback(dep.module.error);
<add> if(!dep.module._source) throw new Error("The module created for a LoaderDependency must have a property _source");
<add> let source, map;
<add> const moduleSource = dep.module._source;
<add> if(moduleSource.sourceAndMap) {
<add> const sourceAndMap = moduleSource.sourceAndMap();
<add> map = sourceAndMap.map;
<add> source = sourceAndMap.source;
<add> } else {
<add> map = moduleSource.map();
<add> source = moduleSource.source();
<add> }
<add> if(dep.module.fileDependencies) {
<add> dep.module.fileDependencies.forEach((dep) => loaderContext.addDependency(dep));
<add> }
<add> if(dep.module.contextDependencies) {
<add> dep.module.contextDependencies.forEach((dep) => loaderContext.addContextDependency(dep));
<add> }
<add> return callback(null, source, map, dep.module);
<ide> }
<del> return callback(null, source, map, dep.module);
<del> }
<del> });
<del> };
<add> });
<add> };
<add> });
<ide> });
<del> });
<del>};
<add> }
<add>}
<add>module.exports = LoaderPlugin; | 1 |
Python | Python | ignore the result of periodictask's by default | 386edbaa903244944048d39b1ecdbfcfdfcdee45 | <ide><path>celery/task/base.py
<ide> class PeriodicTask(Task):
<ide> """
<ide> abstract = True
<ide> run_every = timedelta(days=1)
<add> ignore_result = True
<ide> type = "periodic"
<ide>
<ide> def __init__(self): | 1 |
Python | Python | fix morphological features in en tag_map | 7afe56a3602e4a7876f5c87ac5b4f3531fd60487 | <ide><path>spacy/lang/en/tag_map.py
<ide> "Number": "sing",
<ide> "Person": "three",
<ide> },
<del> "WDT": {POS: ADJ, "PronType": "int,rel"},
<del> "WP": {POS: NOUN, "PronType": "int,rel"},
<del> "WP$": {POS: ADJ, "Poss": "yes", "PronType": "int,rel"},
<del> "WRB": {POS: ADV, "PronType": "int,rel"},
<add> "WDT": {POS: ADJ, "PronType": "rel"},
<add> "WP": {POS: NOUN, "PronType": "rel"},
<add> "WP$": {POS: ADJ, "Poss": "yes", "PronType": "rel"},
<add> "WRB": {POS: ADV, "PronType": "rel"},
<ide> "ADD": {POS: X},
<ide> "NFP": {POS: PUNCT},
<ide> "GW": {POS: X}, | 1 |
Ruby | Ruby | remove unnecessary .sort | 0bb7c4d3ed91648f6326bf40486e511f52e06f43 | <ide><path>Library/Homebrew/cmd/prune.rb
<ide> def prune
<ide> end
<ide> end
<ide>
<del> dirs.sort.reverse_each do |d|
<add> dirs.reverse_each do |d|
<ide> if ARGV.dry_run? && d.children.empty?
<ide> puts "Would remove (empty directory): #{d}"
<ide> else | 1 |
Javascript | Javascript | fix subarray error for ie9 | 567dd330e1dea440e0bb5f57706578278609a351 | <ide><path>web/compatibility.js
<ide> }
<ide>
<ide> function subarray(start, end) {
<del> return this.slice(start, end);
<add> return new TypedArray(this.slice(start, end));
<ide> }
<ide>
<ide> function setArrayOffset(array, offset) { | 1 |
PHP | PHP | remove deprecated pluck methods | 093a29e3ab85957998f60a4e73291bab23d3af3f | <ide><path>src/Illuminate/Database/Eloquent/Builder.php
<ide> public function value($column)
<ide> }
<ide> }
<ide>
<del> /**
<del> * Get a single column's value from the first result of a query.
<del> *
<del> * This is an alias for the "value" method.
<del> *
<del> * @param string $column
<del> * @return mixed
<del> *
<del> * @deprecated since version 5.1
<del> */
<del> public function pluck($column)
<del> {
<del> return $this->value($column);
<del> }
<del>
<ide> /**
<ide> * Chunk the results of the query.
<ide> *
<ide><path>src/Illuminate/Database/Query/Builder.php
<ide> public function value($column)
<ide> return count($result) > 0 ? reset($result) : null;
<ide> }
<ide>
<del> /**
<del> * Get a single column's value from the first result of a query.
<del> *
<del> * This is an alias for the "value" method.
<del> *
<del> * @param string $column
<del> * @return mixed
<del> *
<del> * @deprecated since version 5.1
<del> */
<del> public function pluck($column)
<del> {
<del> return $this->value($column);
<del> }
<del>
<ide> /**
<ide> * Execute the query and get the first result.
<ide> * | 2 |
Javascript | Javascript | fix typo in test-tls-cnnic-whitelist | a34f1e32453951d026a3b58a30b83df065060612 | <ide><path>test/parallel/test-tls-cnnic-whitelist.js
<ide> function loadPEM(n) {
<ide> }
<ide>
<ide> const testCases = [
<del> { // Test 0: for the check of a cert not existed in the whitelist.
<add> { // Test 0: for the check of a cert not in the whitelist.
<ide> // agent7-cert.pem is issued by the fake CNNIC root CA so that its
<ide> // hash is not listed in the whitelist.
<ide> // fake-cnnic-root-cert has the same subject name as the original | 1 |
Ruby | Ruby | pass path directly to standardloader when possible | e008ceb332ddf88a8079d504adebaaead215a4ec | <ide><path>Library/Homebrew/formulary.rb
<ide> def get_formula
<ide>
<ide> # Loads formulae from Homebrew's provided Library
<ide> class StandardLoader < FormulaLoader
<del> def initialize name
<del> super name, Formula.path(name)
<add> def initialize name, path=Formula.path(name)
<add> super
<ide> end
<ide> end
<ide>
<ide> def self.loader_for(ref)
<ide>
<ide> formula_with_that_name = Formula.path(ref)
<ide> if formula_with_that_name.file? and formula_with_that_name.readable?
<del> return StandardLoader.new(ref)
<add> return StandardLoader.new(ref, formula_with_that_name)
<ide> end
<ide>
<ide> # test if the name is a formula alias
<ide> possible_alias = Pathname.new("#{HOMEBREW_LIBRARY}/Aliases/#{ref}")
<ide> if possible_alias.file?
<del> name = possible_alias.resolved_path.basename(".rb").to_s
<del> return StandardLoader.new(name)
<add> path = possible_alias.resolved_path
<add> name = path.basename(".rb").to_s
<add> return StandardLoader.new(name, path)
<ide> end
<ide>
<ide> possible_cached_formula = Pathname.new("#{HOMEBREW_CACHE_FORMULA}/#{ref}.rb") | 1 |
PHP | PHP | fix empty data for components | f5119062ab054aba21c2fbd55e9f7363b8c7b814 | <ide><path>src/Illuminate/View/Compilers/Concerns/CompilesComponents.php
<ide> protected function compileComponent($expression)
<ide> {
<ide> [$component, $data] = strpos($expression, ',') !== false
<ide> ? array_map('trim', explode(',', trim($expression, '()'), 2))
<del> : [trim($expression, '()'), null];
<add> : [trim($expression, '()'), ''];
<ide>
<ide> $component = trim($component, '\'"');
<ide> | 1 |
Python | Python | fix push_to_hub for tpus | ba15fe7995a02357ecea6e7024918f6915564c36 | <ide><path>src/transformers/trainer.py
<ide> def push_to_hub(self, commit_message: Optional[str] = "add model", **kwargs) ->
<ide> Returns:
<ide> The url of the commit of your model in the given repository.
<ide> """
<del> if not self.args.should_save:
<del> return
<ide>
<del> self.create_model_card(model_name=self.args.push_to_hub_model_id, **kwargs)
<add> if self.args.should_save:
<add> self.create_model_card(model_name=self.args.push_to_hub_model_id, **kwargs)
<add> # Needs to be executed on all processes for TPU training, but will only save on the processed determined by
<add> # self.args.should_save.
<ide> self.save_model()
<ide>
<ide> # Only push from one node. | 1 |
Python | Python | fix missing para. | 6714b755f4938e998907e3d949c832f77a76fadc | <ide><path>rest_framework/tests/fields.py
<ide> class Meta:
<ide>
<ide> serializer = URLFieldSerializer(data={})
<ide> self.assertEqual(serializer.is_valid(), True)
<del> self.assertEqual(getattr(serializer.fields['url_field'], 'max_length'), 20
<del>
<ide>\ No newline at end of file
<add> self.assertEqual(getattr(serializer.fields['url_field'], 'max_length'), 20) | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.