content_type
stringclasses 8
values | main_lang
stringclasses 7
values | message
stringlengths 1
50
| sha
stringlengths 40
40
| patch
stringlengths 52
962k
| file_count
int64 1
300
|
---|---|---|---|---|---|
Text | Text | update turborepo examples link | d83ceeec080fb5ab52df31d57978b1ce14139133 | <ide><path>examples/with-turbo/README.md
<ide> The official examples are maintained by the Turborepo team:
<ide>
<del>- [Typescript](https://github.com/vercel/turborepo/tree/main/examples/basic)
<add>- [Turborepo + Next.js Examples](https://github.com/vercel/turborepo/tree/main/examples/with-nextjs) | 1 |
Go | Go | remove unused experimental code | 16fe5a12891984ae5d0b28e737958566a13958ae | <ide><path>cmd/dockerd/config_experimental.go
<del>package main
<del>
<del>import (
<del> "github.com/docker/docker/daemon/config"
<del> "github.com/spf13/pflag"
<del>)
<del>
<del>func attachExperimentalFlags(conf *config.Config, cmd *pflag.FlagSet) {
<del>}
<ide><path>cmd/dockerd/config_solaris.go
<ide> func installConfigFlags(conf *config.Config, flags *pflag.FlagSet) {
<ide>
<ide> // Then install flags common to unix platforms
<ide> installUnixConfigFlags(conf, flags)
<del>
<del> attachExperimentalFlags(conf, flags)
<ide> }
<ide><path>cmd/dockerd/config_unix.go
<ide> func installConfigFlags(conf *config.Config, flags *pflag.FlagSet) {
<ide> flags.Var(&conf.ShmSize, "default-shm-size", "Default shm size for containers")
<ide> flags.BoolVar(&conf.NoNewPrivileges, "no-new-privileges", false, "Set no-new-privileges by default for new containers")
<ide> flags.StringVar(&conf.IpcMode, "default-ipc-mode", config.DefaultIpcMode, `Default mode for containers ipc ("shareable" | "private")`)
<del>
<del> attachExperimentalFlags(conf, flags)
<ide> }
<ide><path>daemon/daemon_experimental.go
<del>package daemon
<del>
<del>import "github.com/docker/docker/api/types/container"
<del>
<del>func (daemon *Daemon) verifyExperimentalContainerSettings(hostConfig *container.HostConfig, config *container.Config) ([]string, error) {
<del> return nil, nil
<del>}
<ide><path>daemon/daemon_unix.go
<ide> func verifyPlatformContainerSettings(daemon *Daemon, hostConfig *containertypes.
<ide> var warnings []string
<ide> sysInfo := sysinfo.New(true)
<ide>
<del> warnings, err := daemon.verifyExperimentalContainerSettings(hostConfig, config)
<del> if err != nil {
<del> return warnings, err
<del> }
<del>
<ide> w, err := verifyContainerResources(&hostConfig.Resources, sysInfo, update)
<ide>
<ide> // no matter err is nil or not, w could have data in itself. | 5 |
Javascript | Javascript | add known issue test for sync writable callback | 5bef2ccf20cceda7975f8bce860e0f60595482fc | <ide><path>test/known_issues/test-stream-writable-sync-error.js
<add>'use strict';
<add>const common = require('../common');
<add>
<add>// Tests for the regression in _stream_writable discussed in
<add>// https://github.com/nodejs/node/pull/31756
<add>
<add>// Specifically, when a write callback is invoked synchronously
<add>// with an error, and autoDestroy is not being used, the error
<add>// should still be emitted on nextTick.
<add>
<add>const { Writable } = require('stream');
<add>
<add>class MyStream extends Writable {
<add> #cb = undefined;
<add>
<add> constructor() {
<add> super({ autoDestroy: false });
<add> }
<add>
<add> _write(_, __, cb) {
<add> this.#cb = cb;
<add> }
<add>
<add> close() {
<add> // Synchronously invoke the callback with an error.
<add> this.#cb(new Error('foo'));
<add> }
<add>}
<add>
<add>const stream = new MyStream();
<add>
<add>const mustError = common.mustCall(2);
<add>
<add>stream.write('test', () => {});
<add>
<add>// Both error callbacks should be invoked.
<add>
<add>stream.on('error', mustError);
<add>
<add>stream.close();
<add>
<add>// Without the fix in #31756, the error handler
<add>// added after the call to close will not be invoked.
<add>stream.on('error', mustError); | 1 |
Python | Python | fix bug in testing multiple browsers | 1532e86dcb82ff78d2fe0b52c0b7f1bc45eca0ce | <ide><path>test.py
<ide> def setUp(manifestFile, masterMode):
<ide> assert not os.path.isdir(TMPDIR)
<ide>
<ide> testBrowsers = [ b for b in
<del> ( 'firefox5', )
<del>#'chrome12', 'chrome13', 'firefox4', 'firefox6','opera11' ):
<add> ( 'firefox5', 'firefox6', )
<add>#'chrome12', 'chrome13', 'firefox4', 'opera11' ):
<ide> if os.access(b, os.R_OK | os.X_OK) ]
<ide>
<ide> mf = open(manifestFile)
<ide> def setUp(manifestFile, masterMode):
<ide> taskResults.append([ ])
<ide> State.taskResults[b][id] = taskResults
<ide>
<del> State.remaining = len(manifestList)
<add> State.remaining = len(testBrowsers) * len(manifestList)
<ide>
<ide> for b in testBrowsers:
<ide> print 'Launching', b | 1 |
Go | Go | fix imagesummary.size value | be20dc15af0cb281bd6d11586cfcc96bd50d12ca | <ide><path>cli/command/formatter/image.go
<ide> func (c *imageContext) CreatedAt() string {
<ide>
<ide> func (c *imageContext) Size() string {
<ide> c.AddHeader(sizeHeader)
<del> //NOTE: For backward compatibility we need to return VirtualSize
<del> return units.HumanSizeWithPrecision(float64(c.i.VirtualSize), 3)
<add> return units.HumanSizeWithPrecision(float64(c.i.Size), 3)
<ide> }
<ide>
<ide> func (c *imageContext) Containers() string {
<ide> func (c *imageContext) SharedSize() string {
<ide>
<ide> func (c *imageContext) UniqueSize() string {
<ide> c.AddHeader(uniqueSizeHeader)
<del> if c.i.Size == -1 {
<add> if c.i.VirtualSize == -1 || c.i.SharedSize == -1 {
<ide> return "N/A"
<ide> }
<del> return units.HumanSize(float64(c.i.Size))
<add> return units.HumanSize(float64(c.i.VirtualSize - c.i.SharedSize))
<ide> }
<ide><path>daemon/images.go
<ide> func (daemon *Daemon) Images(imageFilters filters.Args, all bool, withExtraAttrs
<ide> rootFS := *img.RootFS
<ide> rootFS.DiffIDs = nil
<ide>
<del> newImage.Size = 0
<ide> newImage.SharedSize = 0
<ide> for _, id := range img.RootFS.DiffIDs {
<ide> rootFS.Append(id)
<ide> func (daemon *Daemon) Images(imageFilters filters.Args, all bool, withExtraAttrs
<ide>
<ide> if layerRefs[chid] > 1 {
<ide> newImage.SharedSize += diffSize
<del> } else {
<del> newImage.Size += diffSize
<ide> }
<ide> }
<ide> }
<ide> func newImage(image *image.Image, virtualSize int64) *types.ImageSummary {
<ide> newImage.ParentID = image.Parent.String()
<ide> newImage.ID = image.ID().String()
<ide> newImage.Created = image.Created.Unix()
<del> newImage.Size = -1
<add> newImage.Size = virtualSize
<ide> newImage.VirtualSize = virtualSize
<ide> newImage.SharedSize = -1
<ide> newImage.Containers = -1 | 2 |
Javascript | Javascript | fix lint errors | 2655e47d8cb64c003e73ad3a86ad2e0ec609be51 | <ide><path>examples/js/misc/GPUComputationRenderer.js
<ide> * @param {WebGLRenderer} renderer The renderer
<ide> */
<ide>
<del>THREE.GPUComputationRenderer = function( sizeX, sizeY, renderer ) {
<add>THREE.GPUComputationRenderer = function ( sizeX, sizeY, renderer ) {
<ide>
<ide> this.variables = [];
<ide>
<ide> THREE.GPUComputationRenderer = function( sizeX, sizeY, renderer ) {
<ide> scene.add( mesh );
<ide>
<ide>
<del> this.addVariable = function( variableName, computeFragmentShader, initialValueTexture ) {
<add> this.addVariable = function ( variableName, computeFragmentShader, initialValueTexture ) {
<ide>
<ide> var material = this.createShaderMaterial( computeFragmentShader );
<ide>
<ide> THREE.GPUComputationRenderer = function( sizeX, sizeY, renderer ) {
<ide>
<ide> };
<ide>
<del> this.setVariableDependencies = function( variable, dependencies ) {
<add> this.setVariableDependencies = function ( variable, dependencies ) {
<ide>
<ide> variable.dependencies = dependencies;
<ide>
<ide> };
<ide>
<del> this.init = function() {
<add> this.init = function () {
<ide>
<ide> if ( ! renderer.extensions.get( "OES_texture_float" ) ) {
<ide>
<ide> THREE.GPUComputationRenderer = function( sizeX, sizeY, renderer ) {
<ide>
<ide> }
<ide>
<del> for ( var i = 0; i < this.variables.length; i++ ) {
<add> for ( var i = 0; i < this.variables.length; i ++ ) {
<ide>
<ide> var variable = this.variables[ i ];
<ide>
<ide> THREE.GPUComputationRenderer = function( sizeX, sizeY, renderer ) {
<ide> var uniforms = material.uniforms;
<ide> if ( variable.dependencies !== null ) {
<ide>
<del> for ( var d = 0; d < variable.dependencies.length; d++ ) {
<add> for ( var d = 0; d < variable.dependencies.length; d ++ ) {
<ide>
<ide> var depVar = variable.dependencies[ d ];
<ide>
<ide> if ( depVar.name !== variable.name ) {
<ide>
<ide> // Checks if variable exists
<ide> var found = false;
<del> for ( var j = 0; j < this.variables.length; j++ ) {
<add> for ( var j = 0; j < this.variables.length; j ++ ) {
<ide>
<ide> if ( depVar.name === this.variables[ j ].name ) {
<add>
<ide> found = true;
<ide> break;
<add>
<ide> }
<ide>
<ide> }
<ide> if ( ! found ) {
<add>
<ide> return "Variable dependency not found. Variable=" + variable.name + ", dependency=" + depVar.name;
<add>
<ide> }
<ide>
<ide> }
<ide> THREE.GPUComputationRenderer = function( sizeX, sizeY, renderer ) {
<ide> material.fragmentShader = "\nuniform sampler2D " + depVar.name + ";\n" + material.fragmentShader;
<ide>
<ide> }
<add>
<ide> }
<add>
<ide> }
<ide>
<ide> this.currentTextureIndex = 0;
<ide> THREE.GPUComputationRenderer = function( sizeX, sizeY, renderer ) {
<ide>
<ide> };
<ide>
<del> this.compute = function() {
<add> this.compute = function () {
<ide>
<ide> var currentTextureIndex = this.currentTextureIndex;
<ide> var nextTextureIndex = this.currentTextureIndex === 0 ? 1 : 0;
<ide>
<del> for ( var i = 0, il = this.variables.length; i < il; i++ ) {
<add> for ( var i = 0, il = this.variables.length; i < il; i ++ ) {
<ide>
<ide> var variable = this.variables[ i ];
<ide>
<ide> // Sets texture dependencies uniforms
<ide> if ( variable.dependencies !== null ) {
<ide>
<ide> var uniforms = variable.material.uniforms;
<del> for ( var d = 0, dl = variable.dependencies.length; d < dl; d++ ) {
<add> for ( var d = 0, dl = variable.dependencies.length; d < dl; d ++ ) {
<ide>
<ide> var depVar = variable.dependencies[ d ];
<ide>
<ide> THREE.GPUComputationRenderer = function( sizeX, sizeY, renderer ) {
<ide> }
<ide>
<ide> this.currentTextureIndex = nextTextureIndex;
<add>
<ide> };
<ide>
<del> this.getCurrentRenderTarget = function( variable ) {
<add> this.getCurrentRenderTarget = function ( variable ) {
<ide>
<ide> return variable.renderTargets[ this.currentTextureIndex ];
<ide>
<ide> };
<ide>
<del> this.getAlternateRenderTarget = function( variable ) {
<add> this.getAlternateRenderTarget = function ( variable ) {
<ide>
<ide> return variable.renderTargets[ this.currentTextureIndex === 0 ? 1 : 0 ];
<ide>
<ide> THREE.GPUComputationRenderer = function( sizeX, sizeY, renderer ) {
<ide>
<ide> this.createShaderMaterial = createShaderMaterial;
<ide>
<del> this.createRenderTarget = function( sizeXTexture, sizeYTexture, wrapS, wrapT, minFilter, magFilter ) {
<add> this.createRenderTarget = function ( sizeXTexture, sizeYTexture, wrapS, wrapT, minFilter, magFilter ) {
<ide>
<ide> sizeXTexture = sizeXTexture || sizeX;
<ide> sizeYTexture = sizeYTexture || sizeY;
<ide> THREE.GPUComputationRenderer = function( sizeX, sizeY, renderer ) {
<ide>
<ide> };
<ide>
<del> this.createTexture = function() {
<add> this.createTexture = function () {
<ide>
<ide> var a = new Float32Array( sizeX * sizeY * 4 );
<ide> var texture = new THREE.DataTexture( a, sizeX, sizeY, THREE.RGBAFormat, THREE.FloatType );
<ide> THREE.GPUComputationRenderer = function( sizeX, sizeY, renderer ) {
<ide>
<ide> };
<ide>
<del> this.renderTexture = function( input, output ) {
<add> this.renderTexture = function ( input, output ) {
<ide>
<ide> // Takes a texture, and render out in rendertarget
<ide> // input = Texture
<ide> // output = RenderTarget
<ide>
<ide> passThruUniforms.texture.value = input;
<ide>
<del> this.doRenderTarget( passThruShader, output);
<add> this.doRenderTarget( passThruShader, output );
<ide>
<ide> passThruUniforms.texture.value = null;
<ide>
<ide> };
<ide>
<del> this.doRenderTarget = function( material, output ) {
<add> this.doRenderTarget = function ( material, output ) {
<ide>
<ide> var currentRenderTarget = renderer.getRenderTarget();
<ide>
<ide><path>examples/jsm/misc/GPUComputationRenderer.js
<ide> import {
<ide> WebGLRenderTarget
<ide> } from "../../../build/three.module.js";
<ide>
<del>var GPUComputationRenderer = function( sizeX, sizeY, renderer ) {
<add>var GPUComputationRenderer = function ( sizeX, sizeY, renderer ) {
<ide>
<ide> this.variables = [];
<ide>
<ide> var GPUComputationRenderer = function( sizeX, sizeY, renderer ) {
<ide> scene.add( mesh );
<ide>
<ide>
<del> this.addVariable = function( variableName, computeFragmentShader, initialValueTexture ) {
<add> this.addVariable = function ( variableName, computeFragmentShader, initialValueTexture ) {
<ide>
<ide> var material = this.createShaderMaterial( computeFragmentShader );
<ide>
<ide> var GPUComputationRenderer = function( sizeX, sizeY, renderer ) {
<ide>
<ide> };
<ide>
<del> this.setVariableDependencies = function( variable, dependencies ) {
<add> this.setVariableDependencies = function ( variable, dependencies ) {
<ide>
<ide> variable.dependencies = dependencies;
<ide>
<ide> };
<ide>
<del> this.init = function() {
<add> this.init = function () {
<ide>
<ide> if ( ! renderer.extensions.get( "OES_texture_float" ) ) {
<ide>
<ide> var GPUComputationRenderer = function( sizeX, sizeY, renderer ) {
<ide>
<ide> }
<ide>
<del> for ( var i = 0; i < this.variables.length; i++ ) {
<add> for ( var i = 0; i < this.variables.length; i ++ ) {
<ide>
<ide> var variable = this.variables[ i ];
<ide>
<ide> var GPUComputationRenderer = function( sizeX, sizeY, renderer ) {
<ide> var uniforms = material.uniforms;
<ide> if ( variable.dependencies !== null ) {
<ide>
<del> for ( var d = 0; d < variable.dependencies.length; d++ ) {
<add> for ( var d = 0; d < variable.dependencies.length; d ++ ) {
<ide>
<ide> var depVar = variable.dependencies[ d ];
<ide>
<ide> if ( depVar.name !== variable.name ) {
<ide>
<ide> // Checks if variable exists
<ide> var found = false;
<del> for ( var j = 0; j < this.variables.length; j++ ) {
<add> for ( var j = 0; j < this.variables.length; j ++ ) {
<ide>
<ide> if ( depVar.name === this.variables[ j ].name ) {
<add>
<ide> found = true;
<ide> break;
<add>
<ide> }
<ide>
<ide> }
<add>
<ide> if ( ! found ) {
<add>
<ide> return "Variable dependency not found. Variable=" + variable.name + ", dependency=" + depVar.name;
<add>
<ide> }
<ide>
<ide> }
<ide> var GPUComputationRenderer = function( sizeX, sizeY, renderer ) {
<ide> material.fragmentShader = "\nuniform sampler2D " + depVar.name + ";\n" + material.fragmentShader;
<ide>
<ide> }
<add>
<ide> }
<add>
<ide> }
<ide>
<ide> this.currentTextureIndex = 0;
<ide> var GPUComputationRenderer = function( sizeX, sizeY, renderer ) {
<ide>
<ide> };
<ide>
<del> this.compute = function() {
<add> this.compute = function () {
<ide>
<ide> var currentTextureIndex = this.currentTextureIndex;
<ide> var nextTextureIndex = this.currentTextureIndex === 0 ? 1 : 0;
<ide>
<del> for ( var i = 0, il = this.variables.length; i < il; i++ ) {
<add> for ( var i = 0, il = this.variables.length; i < il; i ++ ) {
<ide>
<ide> var variable = this.variables[ i ];
<ide>
<ide> // Sets texture dependencies uniforms
<ide> if ( variable.dependencies !== null ) {
<ide>
<ide> var uniforms = variable.material.uniforms;
<del> for ( var d = 0, dl = variable.dependencies.length; d < dl; d++ ) {
<add> for ( var d = 0, dl = variable.dependencies.length; d < dl; d ++ ) {
<ide>
<ide> var depVar = variable.dependencies[ d ];
<ide>
<ide> var GPUComputationRenderer = function( sizeX, sizeY, renderer ) {
<ide> }
<ide>
<ide> this.currentTextureIndex = nextTextureIndex;
<add>
<ide> };
<ide>
<del> this.getCurrentRenderTarget = function( variable ) {
<add> this.getCurrentRenderTarget = function ( variable ) {
<ide>
<ide> return variable.renderTargets[ this.currentTextureIndex ];
<ide>
<ide> };
<ide>
<del> this.getAlternateRenderTarget = function( variable ) {
<add> this.getAlternateRenderTarget = function ( variable ) {
<ide>
<ide> return variable.renderTargets[ this.currentTextureIndex === 0 ? 1 : 0 ];
<ide>
<ide> var GPUComputationRenderer = function( sizeX, sizeY, renderer ) {
<ide>
<ide> this.createShaderMaterial = createShaderMaterial;
<ide>
<del> this.createRenderTarget = function( sizeXTexture, sizeYTexture, wrapS, wrapT, minFilter, magFilter ) {
<add> this.createRenderTarget = function ( sizeXTexture, sizeYTexture, wrapS, wrapT, minFilter, magFilter ) {
<ide>
<ide> sizeXTexture = sizeXTexture || sizeX;
<ide> sizeYTexture = sizeYTexture || sizeY;
<ide> var GPUComputationRenderer = function( sizeX, sizeY, renderer ) {
<ide>
<ide> };
<ide>
<del> this.createTexture = function() {
<add> this.createTexture = function () {
<ide>
<ide> var a = new Float32Array( sizeX * sizeY * 4 );
<ide> var texture = new DataTexture( a, sizeX, sizeY, RGBAFormat, FloatType );
<ide> var GPUComputationRenderer = function( sizeX, sizeY, renderer ) {
<ide>
<ide> };
<ide>
<del> this.renderTexture = function( input, output ) {
<add> this.renderTexture = function ( input, output ) {
<ide>
<ide> // Takes a texture, and render out in rendertarget
<ide> // input = Texture
<ide> // output = RenderTarget
<ide>
<ide> passThruUniforms.texture.value = input;
<ide>
<del> this.doRenderTarget( passThruShader, output);
<add> this.doRenderTarget( passThruShader, output );
<ide>
<ide> passThruUniforms.texture.value = null;
<ide>
<ide> };
<ide>
<del> this.doRenderTarget = function( material, output ) {
<add> this.doRenderTarget = function ( material, output ) {
<ide>
<ide> var currentRenderTarget = renderer.getRenderTarget();
<ide> | 2 |
Text | Text | add strategic initiatives from tsc repo | f1e936ff1590addc5efbcd04d2e71f8ee1b526a5 | <ide><path>README.md
<ide> For information on reporting security vulnerabilities in Node.js, see
<ide>
<ide> * [Contributing to the project][]
<ide> * [Working Groups][]
<del>* [Strategic Initiatives][]
<add>* [Strategic initiatives][]
<ide> * [Technical values and prioritization][]
<ide>
<ide> ## Current project team members
<ide> license text.
<ide> [Contributing to the project]: CONTRIBUTING.md
<ide> [Node.js Website]: https://nodejs.org/
<ide> [OpenJS Foundation]: https://openjsf.org/
<del>[Strategic Initiatives]: https://github.com/nodejs/TSC/blob/HEAD/Strategic-Initiatives.md
<add>[Strategic initiatives]: doc/guides/strategic-initiatives.md
<ide> [Technical values and prioritization]: doc/guides/technical-values.md
<ide> [Working Groups]: https://github.com/nodejs/TSC/blob/HEAD/WORKING_GROUPS.md
<ide><path>doc/guides/strategic-initiatives.md
<add># Strategic initiatives
<add>
<add>The Node.js project has several strategic initiatives underway. The goal of the
<add>TSC is to have a champion for each of these initiatives and enable their
<add>success.
<add>
<add>A review of the initiatives is a standing item on the TSC agenda to ensure they
<add>are active and have the support needed.
<add>
<add>## Current initiatives
<add>
<add>| Initiative | Champion | Links |
<add>|---------------------------|-----------------------------|------------------------------------------------------------------------------------------|
<add>| Core Promise APIs | [Matteo Collina][mcollina] | |
<add>| Future of Build Toolchain | [Mary Marchini][mmarchini] | <https://github.com/nodejs/TSC/issues/901>, <https://github.com/nodejs/build-toolchain-next> |
<add>| QUIC / HTTP3 | [James M Snell][jasnell] | <https://github.com/nodejs/quic> |
<add>| Startup performance | [Joyee Cheung][joyeecheung] | <https://github.com/nodejs/node/issues/17058> <https://github.com/nodejs/node/issues/21563> |
<add>| V8 Currency | [Michaël Zasso][targos] | |
<add>
<add>## Completed
<add>
<add>| Initiative | Champion | Links |
<add>|--------------------|----------------------------|--------------------------------------------------|
<add>| Build resources | Michael Dawson | <https://github.com/nodejs/build/issues/1154#issuecomment-448418977> |
<add>| CVE Management | Michael Dawson | <https://github.com/nodejs/security-wg/issues/33> |
<add>| Governance | Myles Borins | |
<add>| Moderation Team | Rich Trott | <https://github.com/nodejs/TSC/issues/329> |
<add>| Modules | Myles Borins | <https://github.com/nodejs/modules> |
<add>| N-API | Michael Dawson | <https://github.com/nodejs/abi-stable-node> |
<add>| npm Integration | Myles Borins | <https://github.com/nodejs/node/pull/21594> |
<add>| OpenSSL Evolution | Rod Vagg | <https://github.com/nodejs/TSC/issues/677> |
<add>| Open Web Standards | Myles Borins, Joyee Cheung | <https://github.com/nodejs/open-standards> |
<add>| VM module fix | Franziska Hinkelmann | <https://github.com/nodejs/node/issues/6283> |
<add>| Workers | Anna Henningsen | <https://github.com/nodejs/worker> |
<add>
<add>[jasnell]: https://github.com/jasnell
<add>[joyeecheung]: https://github.com/joyeecheung
<add>[mcollina]: https://github.com/mcollina
<add>[mmarchini]: https://github.com/mmarchini
<add>[targos]: https://github.com/targos | 2 |
Ruby | Ruby | remove unused method in routeset test | 30f93dc65ed47d193ce5ff550ada4c14baf41e4d | <ide><path>actionpack/test/dispatch/routing/route_set_test.rb
<ide> def call(env)
<ide> end
<ide>
<ide> private
<del> def clear!
<del> @set.clear!
<del> end
<del>
<ide> def draw(&block)
<ide> @set.draw(&block)
<ide> end | 1 |
Java | Java | test square brackets with index/key expressions | 6f64cfd1e5305566312bfa2125774aa4e3edfd75 | <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/namedparam/NamedParameterUtils.java
<ide> /*
<del> * Copyright 2002-2021 the original author or authors.
<add> * Copyright 2002-2022 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public abstract class NamedParameterUtils {
<ide> * Parse the SQL statement and locate any placeholders or named parameters.
<ide> * Named parameters are substituted for a JDBC placeholder.
<ide> * @param sql the SQL statement
<del> * @return the parsed statement, represented as ParsedSql instance
<add> * @return the parsed statement, represented as {@link ParsedSql} instance
<ide> */
<del> public static ParsedSql parseSqlStatement(final String sql) {
<add> public static ParsedSql parseSqlStatement(String sql) {
<ide> Assert.notNull(sql, "SQL must not be null");
<ide>
<ide> Set<String> namedParameters = new HashSet<>();
<ide> public static ParsedSql parseSqlStatement(final String sql) {
<ide> while (statement[j] != '}') {
<ide> j++;
<ide> if (j >= statement.length) {
<del> throw new InvalidDataAccessApiUsageException("Non-terminated named parameter declaration " +
<del> "at position " + i + " in statement: " + sql);
<add> throw new InvalidDataAccessApiUsageException(
<add> "Non-terminated named parameter declaration at position " + i +
<add> " in statement: " + sql);
<ide> }
<ide> if (statement[j] == ':' || statement[j] == '{') {
<del> throw new InvalidDataAccessApiUsageException("Parameter name contains invalid character '" +
<del> statement[j] + "' at position " + i + " in statement: " + sql);
<add> throw new InvalidDataAccessApiUsageException(
<add> "Parameter name contains invalid character '" + statement[j] +
<add> "' at position " + i + " in statement: " + sql);
<ide> }
<ide> }
<ide> if (j - i > 2) {
<ide> parameter = sql.substring(i + 2, j);
<del> namedParameterCount = addNewNamedParameter(namedParameters, namedParameterCount, parameter);
<add> namedParameterCount = addNewNamedParameter(
<add> namedParameters, namedParameterCount, parameter);
<ide> totalParameterCount = addNamedParameter(
<ide> parameterList, totalParameterCount, escapes, i, j + 1, parameter);
<ide> }
<ide> public static ParsedSql parseSqlStatement(final String sql) {
<ide> }
<ide> if (j - i > 1) {
<ide> parameter = sql.substring(i + 1, j);
<del> namedParameterCount = addNewNamedParameter(namedParameters, namedParameterCount, parameter);
<add> namedParameterCount = addNewNamedParameter(
<add> namedParameters, namedParameterCount, parameter);
<ide> totalParameterCount = addNamedParameter(
<ide> parameterList, totalParameterCount, escapes, i, j, parameter);
<ide> }
<ide> public static ParsedSql parseSqlStatement(final String sql) {
<ide> return parsedSql;
<ide> }
<ide>
<del> private static int addNamedParameter(
<del> List<ParameterHolder> parameterList, int totalParameterCount, int escapes, int i, int j, String parameter) {
<add> private static int addNamedParameter(List<ParameterHolder> parameterList,
<add> int totalParameterCount, int escapes, int i, int j, String parameter) {
<ide>
<ide> parameterList.add(new ParameterHolder(parameter, i - escapes, j - escapes));
<ide> totalParameterCount++;
<ide> public static String substituteNamedParameters(ParsedSql parsedSql, @Nullable Sq
<ide> if (paramNames.isEmpty()) {
<ide> return originalSql;
<ide> }
<add>
<ide> StringBuilder actualSql = new StringBuilder(originalSql.length());
<ide> int lastIndex = 0;
<ide> for (int i = 0; i < paramNames.size(); i++) {
<ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/NamedParameterUtilsTests.java
<ide> /*
<del> * Copyright 2002-2021 the original author or authors.
<add> * Copyright 2002-2022 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public void parseSqlStatementWithQuotesAndCommentAfter() {
<ide> assertThat(psql2.getParameterNames().get(0)).isEqualTo("xxx");
<ide> }
<ide>
<add> @Test // gh-27925
<add> void namedParamMapReference() {
<add> String sql = "insert into foos (id) values (:headers[id])";
<add> ParsedSql psql = NamedParameterUtils.parseSqlStatement(sql);
<add> assertThat(psql.getNamedParameterCount()).isEqualTo(1);
<add> assertThat(psql.getParameterNames()).containsExactly("headers[id]");
<add>
<add> class Foo {
<add> final Map<String, Object> headers = new HashMap<>();
<add> public Foo() {
<add> this.headers.put("id", 1);
<add> }
<add> public Map<String, Object> getHeaders() {
<add> return this.headers;
<add> }
<add> }
<add>
<add> Foo foo = new Foo();
<add> Object[] params = NamedParameterUtils.buildValueArray(psql,
<add> new BeanPropertySqlParameterSource(foo), null);
<add>
<add> assertThat(params[0]).isInstanceOf(SqlParameterValue.class);
<add> assertThat(((SqlParameterValue) params[0]).getValue()).isEqualTo(foo.getHeaders().get("id"));
<add> }
<add>
<ide> }
<ide><path>spring-r2dbc/src/main/java/org/springframework/r2dbc/core/NamedParameterUtils.java
<ide> /**
<ide> * Helper methods for named parameter parsing.
<ide> *
<del> * <p>Only intended for internal use within Spring's R2DBC
<del> * framework.
<add> * <p>Only intended for internal use within Spring's R2DBC framework.
<ide> *
<ide> * <p>References to the same parameter name are substituted with
<ide> * the same bind marker placeholder if a {@link BindMarkersFactory} uses
<ide> public static PreparedOperation<String> substituteNamedParameters(ParsedSql pars
<ide> if (paramSource.hasValue(paramName)) {
<ide> Object value = paramSource.getValue(paramName);
<ide> if (value instanceof Collection) {
<del>
<ide> Iterator<?> entryIter = ((Collection<?>) value).iterator();
<ide> int k = 0;
<ide> int counter = 0;
<ide><path>spring-r2dbc/src/test/java/org/springframework/r2dbc/core/NamedParameterUtilsUnitTests.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2022 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public class NamedParameterUtilsUnitTests {
<ide>
<ide> private final BindMarkersFactory BIND_MARKERS = BindMarkersFactory.indexed("$", 1);
<ide>
<add>
<ide> @Test
<ide> public void shouldParseSql() {
<ide> String sql = "xxx :a yyyy :b :c :a zzzzz";
<ide> public void parseSqlStatementWithPostgresContainedOperator() {
<ide> String sql = "select 'first name' from artists where info->'stat'->'albums' = ?? :album and '[\"1\",\"2\",\"3\"]'::jsonb ?? '4'";
<ide>
<ide> ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(sql);
<del>
<ide> assertThat(parsedSql.getTotalParameterCount()).isEqualTo(1);
<ide> assertThat(expand(parsedSql)).isEqualTo(expectedSql);
<ide> }
<ide> public void parseSqlStatementWithPostgresAnyArrayStringsExistsOperator() {
<ide> String sql = "select '[\"3\", \"11\"]'::jsonb ?| '{1,3,11,12,17}'::text[]";
<ide>
<ide> ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(sql);
<del>
<ide> assertThat(parsedSql.getTotalParameterCount()).isEqualTo(0);
<ide> assertThat(expand(parsedSql)).isEqualTo(expectedSql);
<ide> }
<ide> public void parseSqlStatementWithEscapedColon() {
<ide> String sql = "select '0\\:0' as a, foo from bar where baz < DATE(:p1 23\\:59\\:59) and baz = :p2";
<ide>
<ide> ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(sql);
<del>
<ide> assertThat(parsedSql.getParameterNames()).containsExactly("p1", "p2");
<ide> assertThat(expand(parsedSql)).isEqualTo(expectedSql);
<ide> }
<ide> public void parseSqlStatementWithEmptyBracketsOrBracketsInQuotes() {
<ide> String sql = "select foo from bar where baz = b:{}z";
<ide>
<ide> ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(sql);
<del>
<ide> assertThat(parsedSql.getParameterNames()).isEmpty();
<ide> assertThat(expand(parsedSql)).isEqualTo(expectedSql);
<ide>
<ide> public void parseSqlStatementWithLogicalAnd() {
<ide> String expectedSql = "xxx & yyyy";
<ide>
<ide> ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(expectedSql);
<del>
<ide> assertThat(expand(parsedSql)).isEqualTo(expectedSql);
<ide> }
<ide>
<ide> @Test
<ide> public void substituteNamedParametersWithLogicalAnd() {
<del>
<ide> String expectedSql = "xxx & yyyy";
<ide>
<ide> assertThat(expand(expectedSql)).isEqualTo(expectedSql);
<ide> public void parseSqlStatementWithQuotedSingleQuote() {
<ide> String sql = "SELECT ':foo'':doo', :xxx FROM DUAL";
<ide>
<ide> ParsedSql psql = NamedParameterUtils.parseSqlStatement(sql);
<del>
<ide> assertThat(psql.getTotalParameterCount()).isEqualTo(1);
<ide> assertThat(psql.getParameterNames()).containsExactly("xxx");
<ide> }
<ide> public void parseSqlStatementWithQuotesAndCommentBefore() {
<ide> String sql = "SELECT /*:doo*/':foo', :xxx FROM DUAL";
<ide>
<ide> ParsedSql psql = NamedParameterUtils.parseSqlStatement(sql);
<del>
<ide> assertThat(psql.getTotalParameterCount()).isEqualTo(1);
<ide> assertThat(psql.getParameterNames()).containsExactly("xxx");
<ide> }
<ide> public void parseSqlStatementWithQuotesAndCommentAfter() {
<ide> String sql2 = "SELECT ':foo'/*:doo*/, :xxx FROM DUAL";
<ide>
<ide> ParsedSql psql2 = NamedParameterUtils.parseSqlStatement(sql2);
<del>
<ide> assertThat(psql2.getTotalParameterCount()).isEqualTo(1);
<ide> assertThat(psql2.getParameterNames()).containsExactly("xxx");
<ide> }
<ide>
<add> @Test // gh-27925
<add> void namedParamMapReference() {
<add> String sql = "insert into foos (id) values (:headers[id])";
<add> ParsedSql psql = NamedParameterUtils.parseSqlStatement(sql);
<add> assertThat(psql.getNamedParameterCount()).isEqualTo(1);
<add> assertThat(psql.getParameterNames()).containsExactly("headers[id]");
<add> }
<add>
<ide> @Test
<ide> public void shouldAllowParsingMultipleUseOfParameter() {
<del>
<ide> String sql = "SELECT * FROM person where name = :id or lastname = :id";
<ide>
<ide> ParsedSql parsed = NamedParameterUtils.parseSqlStatement(sql);
<del>
<ide> assertThat(parsed.getTotalParameterCount()).isEqualTo(2);
<ide> assertThat(parsed.getNamedParameterCount()).isEqualTo(1);
<ide> assertThat(parsed.getParameterNames()).containsExactly("id", "id");
<ide> sql, factory, new MapBindParameterSource(
<ide> "SELECT * FROM person where name = $0 or lastname = $0");
<ide>
<ide> operation.bindTo(new BindTarget() {
<del>
<ide> @Override
<ide> public void bind(String identifier, Object value) {
<ide> throw new UnsupportedOperationException();
<ide> }
<del>
<ide> @Override
<ide> public void bind(int index, Object value) {
<ide> assertThat(index).isEqualTo(0);
<ide> assertThat(value).isEqualTo("foo");
<ide> }
<del>
<ide> @Override
<ide> public void bindNull(String identifier, Class<?> type) {
<ide> throw new UnsupportedOperationException();
<ide> }
<del>
<ide> @Override
<ide> public void bindNull(int index, Class<?> type) {
<ide> throw new UnsupportedOperationException();
<ide> sql, factory, new MapBindParameterSource(Collections.singletonMap("ids",
<ide> "SELECT * FROM person where name IN ($0, $1, $2) or lastname IN ($0, $1, $2)");
<ide>
<ide> operation.bindTo(new BindTarget() {
<del>
<ide> @Override
<ide> public void bind(String identifier, Object value) {
<ide> throw new UnsupportedOperationException();
<ide> }
<del>
<ide> @Override
<ide> public void bind(int index, Object value) {
<ide> assertThat(index).isIn(0, 1, 2);
<ide> assertThat(value).isIn("foo", "bar", "baz");
<del>
<ide> bindings.add(index, value);
<ide> }
<del>
<ide> @Override
<ide> public void bindNull(String identifier, Class<?> type) {
<ide> throw new UnsupportedOperationException();
<ide> }
<del>
<ide> @Override
<ide> public void bindNull(int index, Class<?> type) {
<ide> throw new UnsupportedOperationException();
<ide> sql, factory, new MapBindParameterSource(
<ide> Map<Integer, Object> bindValues = new LinkedHashMap<>();
<ide>
<ide> operation.bindTo(new BindTarget() {
<del>
<ide> @Override
<ide> public void bind(String identifier, Object value) {
<ide> throw new UnsupportedOperationException();
<ide> }
<del>
<ide> @Override
<ide> public void bind(int index, Object value) {
<ide> bindValues.put(index, value);
<ide> }
<del>
<ide> @Override
<ide> public void bindNull(String identifier, Class<?> type) {
<ide> throw new UnsupportedOperationException();
<ide> }
<del>
<ide> @Override
<ide> public void bindNull(int index, Class<?> type) {
<ide> throw new UnsupportedOperationException();
<ide> sql, factory, new MapBindParameterSource(
<ide> "SELECT * FROM person where name = $0 or lastname = $0");
<ide>
<ide> operation.bindTo(new BindTarget() {
<del>
<ide> @Override
<ide> public void bind(String identifier, Object value) {
<ide> throw new UnsupportedOperationException();
<ide> }
<del>
<ide> @Override
<ide> public void bind(int index, Object value) {
<ide> throw new UnsupportedOperationException();
<ide> }
<del>
<ide> @Override
<ide> public void bindNull(String identifier, Class<?> type) {
<ide> throw new UnsupportedOperationException();
<ide> }
<del>
<ide> @Override
<ide> public void bindNull(int index, Class<?> type) {
<ide> assertThat(index).isEqualTo(0);
<ide> public void bindNull(int index, Class<?> type) {
<ide> });
<ide> }
<ide>
<add>
<ide> private String expand(ParsedSql sql) {
<ide> return NamedParameterUtils.substituteNamedParameters(sql, BIND_MARKERS,
<ide> new MapBindParameterSource()).toQuery(); | 4 |
Javascript | Javascript | improve types for react native styles | da047966e4c2064a48e02ff74830c99808d8194b | <ide><path>Libraries/Inspector/ElementProperties.js
<ide> const flattenStyle = require('flattenStyle');
<ide> const mapWithSeparator = require('mapWithSeparator');
<ide> const openFileInEditor = require('openFileInEditor');
<ide>
<add>import type {StyleObj} from 'StyleSheetTypes';
<add>
<ide> class ElementProperties extends React.Component<{
<ide> hierarchy: Array<$FlowFixMe>,
<del> style?: Object | Array<$FlowFixMe> | number,
<add> style?: StyleObj,
<ide> source?: {
<ide> fileName?: string,
<ide> lineNumber?: number,
<ide><path>Libraries/StyleSheet/StyleSheet.js
<ide> const StyleSheetValidation = require('StyleSheetValidation');
<ide>
<ide> const flatten = require('flattenStyle');
<ide>
<del>export type Styles = {[key: string]: Object};
<del>export type StyleSheet<S: Styles> = {[key: $Keys<S>]: number};
<del>export type StyleValue = Object | number | false | null | void | '';
<del>export type StyleProp = StyleValue | Array<StyleProp>;
<add>import type {
<add> StyleSheetStyle as _StyleSheetStyle,
<add> Styles as _Styles,
<add> StyleSheet as _StyleSheet,
<add> StyleValue as _StyleValue,
<add> StyleObj,
<add>} from 'StyleSheetTypes';
<add>
<add>export type StyleProp = StyleObj;
<add>export type Styles = _Styles;
<add>export type StyleSheet<S> = _StyleSheet<S>;
<add>export type StyleValue = _StyleValue;
<add>export type StyleSheetStyle = _StyleSheetStyle;
<ide>
<ide> let hairlineWidth = PixelRatio.roundToNearestPixel(0.4);
<ide> if (hairlineWidth === 0) {
<ide> hairlineWidth = 1 / PixelRatio.get();
<ide> }
<ide>
<ide> const absoluteFillObject = {
<del> position: 'absolute',
<add> position: ('absolute': 'absolute'),
<ide> left: 0,
<ide> right: 0,
<ide> top: 0,
<ide> bottom: 0,
<ide> };
<del>const absoluteFill = ReactNativePropRegistry.register(absoluteFillObject); // This also freezes it
<add>const absoluteFill: typeof absoluteFillObject =
<add> ReactNativePropRegistry.register(absoluteFillObject); // This also freezes it
<ide>
<ide> /**
<ide> * A StyleSheet is an abstraction similar to CSS StyleSheets
<ide> module.exports = {
<ide> * Creates a StyleSheet style reference from the given object.
<ide> */
<ide> create<S: Styles>(obj: S): StyleSheet<S> {
<del> const result: StyleSheet<S> = {};
<add> const result = {};
<ide> for (const key in obj) {
<ide> StyleSheetValidation.validateStyle(key, obj);
<ide> result[key] = obj[key] && ReactNativePropRegistry.register(obj[key]);
<ide><path>Libraries/StyleSheet/StyleSheetTypes.js
<ide> *
<ide> * @providesModule StyleSheetTypes
<ide> * @flow
<add> * @format
<ide> */
<add>
<ide> 'use strict';
<ide>
<del>type Atom = number | bool | Object | Array<?Atom>;
<del>export type StyleObj = Atom;
<add>import AnimatedNode from 'AnimatedNode';
<add>
<add>export opaque type StyleSheetStyle: number = number;
<add>
<add>export type ColorValue = null | string;
<add>export type DimensionValue = null | number | string | AnimatedNode;
<add>
<add>export type LayoutStyle<+Dimension = DimensionValue> = {
<add> +display?: 'none' | 'flex',
<add> +width?: Dimension,
<add> +height?: Dimension,
<add> +top?: Dimension,
<add> +bottom?: Dimension,
<add> +left?: Dimension,
<add> +right?: Dimension,
<add> +minWidth?: Dimension,
<add> +maxWidth?: Dimension,
<add> +minHeight?: Dimension,
<add> +maxHeight?: Dimension,
<add> +margin?: Dimension,
<add> +marginVertical?: Dimension,
<add> +marginHorizontal?: Dimension,
<add> +marginTop?: Dimension,
<add> +marginBottom?: Dimension,
<add> +marginLeft?: Dimension,
<add> +marginRight?: Dimension,
<add> +padding?: Dimension,
<add> +paddingVertical?: Dimension,
<add> +paddingHorizontal?: Dimension,
<add> +paddingTop?: Dimension,
<add> +paddingBottom?: Dimension,
<add> +paddingLeft?: Dimension,
<add> +paddingRight?: Dimension,
<add> +borderWidth?: number,
<add> +borderTopWidth?: number,
<add> +borderBottomWidth?: number,
<add> +borderLeftWidth?: number,
<add> +borderRightWidth?: number,
<add> +position?: 'absolute' | 'relative',
<add> +flexDirection?: 'row' | 'row-reverse' | 'column' | 'column-reverse',
<add> +flexWrap?: 'wrap' | 'nowrap',
<add> +justifyContent?:
<add> | 'flex-start'
<add> | 'flex-end'
<add> | 'center'
<add> | 'space-between'
<add> | 'space-around',
<add> +alignItems?: 'flex-start' | 'flex-end' | 'center' | 'stretch' | 'baseline',
<add> +alignSelf?:
<add> | 'auto'
<add> | 'flex-start'
<add> | 'flex-end'
<add> | 'center'
<add> | 'stretch'
<add> | 'baseline',
<add> +alignContent?:
<add> | 'flex-start'
<add> | 'flex-end'
<add> | 'center'
<add> | 'stretch'
<add> | 'space-between'
<add> | 'space-around',
<add> +overflow?: 'visible' | 'hidden' | 'scroll',
<add> +flex?: number,
<add> +flexGrow?: number,
<add> +flexShrink?: number,
<add> +flexBasis?: number | string,
<add> +aspectRatio?: number,
<add> +zIndex?: number,
<add> +direction?: 'inherit' | 'ltr' | 'rtl',
<add>};
<add>
<add>export type TransformStyle = {
<add> +transform?: $ReadOnlyArray<
<add> | {+perspective: number | AnimatedNode}
<add> | {+rotate: string}
<add> | {+rotateX: string}
<add> | {+rotateY: string}
<add> | {+rotateZ: string}
<add> | {+scale: number | AnimatedNode}
<add> | {+scaleX: number | AnimatedNode}
<add> | {+scaleY: number | AnimatedNode}
<add> | {+translateX: number | AnimatedNode}
<add> | {+translateY: number | AnimatedNode}
<add> | {
<add> +translate: [number | AnimatedNode, number | AnimatedNode] | AnimatedNode,
<add> }
<add> | {+skewX: string}
<add> | {+skewY: string}
<add> // TODO: what is the actual type it expects?
<add> | {+matrix: $ReadOnlyArray<number | AnimatedNode> | AnimatedNode},
<add> >,
<add>};
<add>
<add>export type ShadowStyle<+Color = ColorValue> = {
<add> +shadowColor?: Color,
<add> +shadowOffset?: {
<add> +width?: number,
<add> +height?: number,
<add> },
<add> +shadowOpacity?: number | AnimatedNode,
<add> +shadowRadius?: number,
<add>};
<add>
<add>export type ViewStyle<+Dimension = DimensionValue, +Color = ColorValue> = {
<add> ...$Exact<LayoutStyle<Dimension>>,
<add> ...$Exact<ShadowStyle<Color>>,
<add> ...$Exact<TransformStyle>,
<add> +backfaceVisibility?: 'visible' | 'hidden',
<add> +backgroundColor?: Color,
<add> +borderColor?: Color,
<add> +borderTopColor?: Color,
<add> +borderRightColor?: Color,
<add> +borderBottomColor?: Color,
<add> +borderLeftColor?: Color,
<add> +borderRadius?: number,
<add> +borderTopLeftRadius?: number,
<add> +borderTopRightRadius?: number,
<add> +borderBottomLeftRadius?: number,
<add> +borderBottomRightRadius?: number,
<add> +borderStyle?: 'solid' | 'dotted' | 'dashed',
<add> +borderWidth?: number,
<add> +borderTopWidth?: number,
<add> +borderRightWidth?: number,
<add> +borderBottomWidth?: number,
<add> +borderLeftWidth?: number,
<add> +opacity?: number | AnimatedNode,
<add> +elevation?: number,
<add>};
<add>
<add>export type TextStyle<+Dimension = DimensionValue, +Color = ColorValue> = {
<add> ...$Exact<ViewStyle<Dimension, Color>>,
<add> +color?: Color,
<add> +fontFamily?: string,
<add> +fontSize?: number,
<add> +fontStyle?: 'normal' | 'italic',
<add> +fontWeight?:
<add> | 'normal'
<add> | 'bold'
<add> | '100'
<add> | '200'
<add> | '300'
<add> | '400'
<add> | '500'
<add> | '600'
<add> | '700'
<add> | '800'
<add> | '900',
<add> +fontVariant?: $ReadOnlyArray<
<add> | 'small-caps'
<add> | 'oldstyle-nums'
<add> | 'lining-nums'
<add> | 'tabular-nums'
<add> | 'proportional-nums',
<add> >,
<add> +textShadowOffset?: {+width?: number, +height?: number},
<add> +textShadowRadius?: number,
<add> +textShadowColor?: Color,
<add> +letterSpacing?: number,
<add> +lineHeight?: number,
<add> +textAlign?: 'auto' | 'left' | 'right' | 'center' | 'justify',
<add> +textAlignVertical?: 'auto' | 'top' | 'bottom' | 'center',
<add> +includeFontPadding?: boolean,
<add> +textDecorationLine?:
<add> | 'none'
<add> | 'underline'
<add> | 'line-through'
<add> | 'underline line-through',
<add> +textDecorationStyle?: 'solid' | 'double' | 'dotted' | 'dashed',
<add> +textDecorationColor?: Color,
<add> +writingDirection?: 'auto' | 'ltr' | 'rtl',
<add>};
<add>
<add>export type ImageStyle<+Dimension = DimensionValue, +Color = ColorValue> = {
<add> ...$Exact<ViewStyle<Dimension, Color>>,
<add> +resizeMode?: 'contain' | 'cover' | 'stretch' | 'center' | 'repeat',
<add> +tintColor?: Color,
<add> +overlayColor?: string,
<add>};
<add>
<add>export type Style<+Dimension = DimensionValue, +Color = ColorValue> = {
<add> ...$Exact<TextStyle<Dimension, Color>>,
<add> +resizeMode?: 'contain' | 'cover' | 'stretch' | 'center' | 'repeat',
<add> +tintColor?: Color,
<add> +overlayColor?: string,
<add>};
<add>
<add>export type StyleProp<+T> =
<add> | null
<add> | void
<add> | T
<add> | StyleSheetStyle
<add> | number
<add> | false
<add> | ''
<add> | $ReadOnlyArray<StyleProp<T>>;
<add>
<add>// export type ViewStyleProp = StyleProp<$Shape<ViewStyle<DimensionValue>>>;
<add>// export type TextStyleProp = StyleProp<
<add>// $Shape<TextStyle<DimensionValue, ColorValue>>,
<add>// >;
<add>// export type ImageStyleProp = StyleProp<
<add>// $Shape<ImageStyle<DimensionValue, ColorValue>>,
<add>// >;
<add>
<add>export type StyleObj = StyleProp<$Shape<Style<DimensionValue, ColorValue>>>;
<add>export type StyleValue = StyleObj;
<add>
<add>export type ViewStyleProp = StyleObj;
<add>export type TextStyleProp = StyleObj;
<add>export type ImageStyleProp = StyleObj;
<add>
<add>export type Styles = {
<add> +[key: string]: $Shape<Style<DimensionValue, ColorValue>>,
<add>};
<add>export type StyleSheet<+S: Styles> = $ObjMap<S, (Object) => StyleSheetStyle>;
<add>
<add>/*
<add>Utility type get non-nullable types for specific style keys.
<add>Useful when a component requires values for certain Style Keys.
<add>So Instead:
<add>```
<add>type Props = {position: string};
<add>```
<add>You should use:
<add>```
<add>type Props = {position: TypeForStyleKey<'position'>};
<add>```
<add>
<add>This will correctly give you the type 'absolute' | 'relative' instead of the
<add>weak type of just string;
<add>*/
<add>export type TypeForStyleKey<+key: $Keys<Style<>>> = $ElementType<Style<>, key>; | 3 |
Javascript | Javascript | add context provider/consumer to getcomponentname | c4abfa401503b483944d044c2d6c12c5562a1a8b | <ide><path>packages/shared/getComponentName.js
<ide> import type {Fiber} from 'react-reconciler/src/ReactFiber';
<ide> import {
<ide> REACT_ASYNC_MODE_TYPE,
<ide> REACT_CALL_TYPE,
<add> REACT_CONTEXT_TYPE,
<ide> REACT_FORWARD_REF_TYPE,
<ide> REACT_FRAGMENT_TYPE,
<del> REACT_RETURN_TYPE,
<ide> REACT_PORTAL_TYPE,
<ide> REACT_PROFILER_TYPE,
<add> REACT_PROVIDER_TYPE,
<add> REACT_RETURN_TYPE,
<ide> REACT_STRICT_MODE_TYPE,
<ide> } from 'shared/ReactSymbols';
<ide>
<ide> function getComponentName(fiber: Fiber): string | null {
<ide> return 'AsyncMode';
<ide> case REACT_CALL_TYPE:
<ide> return 'ReactCall';
<add> case REACT_CONTEXT_TYPE:
<add> return 'Context.Consumer';
<ide> case REACT_FRAGMENT_TYPE:
<ide> return 'ReactFragment';
<ide> case REACT_PORTAL_TYPE:
<ide> return 'ReactPortal';
<ide> case REACT_PROFILER_TYPE:
<ide> return `Profiler(${fiber.pendingProps.id})`;
<add> case REACT_PROVIDER_TYPE:
<add> return 'Context.Provider';
<ide> case REACT_RETURN_TYPE:
<ide> return 'ReactReturn';
<ide> case REACT_STRICT_MODE_TYPE: | 1 |
Java | Java | avoid package import cycles | 6db20eb77346c6420eef48883e89cfeb6eb1d13a | <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/AbstractEmbeddedDatabaseConfigurer.java
<ide> import org.apache.commons.logging.Log;
<ide> import org.apache.commons.logging.LogFactory;
<ide>
<del>import org.springframework.jdbc.support.JdbcUtils;
<del>
<ide> /**
<ide> * Base class for {@link EmbeddedDatabaseConfigurer} implementations
<ide> * providing common shutdown behavior through a "SHUTDOWN" statement.
<ide> public void shutdown(DataSource dataSource, String databaseName) {
<ide> logger.info("Could not shut down embedded database", ex);
<ide> }
<ide> finally {
<del> JdbcUtils.closeConnection(con);
<add> if (con != null) {
<add> try {
<add> con.close();
<add> }
<add> catch (SQLException ex) {
<add> logger.debug("Could not close JDBC Connection on shutdown", ex);
<add> }
<add> catch (Throwable ex) {
<add> logger.debug("Unexpected exception on closing JDBC Connection", ex);
<add> }
<add> }
<ide> }
<ide> }
<ide>
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/condition/PatternsRequestCondition.java
<ide> import org.springframework.util.PathMatcher;
<ide> import org.springframework.util.StringUtils;
<ide> import org.springframework.web.servlet.HandlerMapping;
<del>import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
<ide> import org.springframework.web.util.UrlPathHelper;
<ide>
<ide> /**
<ide> public PatternsRequestCondition(String[] patterns, @Nullable UrlPathHelper urlPa
<ide> * @param useSuffixPatternMatch whether to enable matching by suffix (".*")
<ide> * @param useTrailingSlashMatch whether to match irrespective of a trailing slash
<ide> * @deprecated as of 5.2.4. See class-level note in
<del> * {@link RequestMappingHandlerMapping} on the deprecation of path extension
<del> * config options.
<add> * {@link org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping}
<add> * on the deprecation of path extension config options.
<ide> */
<ide> @Deprecated
<ide> public PatternsRequestCondition(String[] patterns, @Nullable UrlPathHelper urlPathHelper,
<ide> public PatternsRequestCondition(String[] patterns, @Nullable UrlPathHelper urlPa
<ide> * @param useTrailingSlashMatch whether to match irrespective of a trailing slash
<ide> * @param fileExtensions a list of file extensions to consider for path matching
<ide> * @deprecated as of 5.2.4. See class-level note in
<del> * {@link RequestMappingHandlerMapping} on the deprecation of path extension
<del> * config options.
<add> * {@link org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping}
<add> * on the deprecation of path extension config options.
<ide> */
<ide> @Deprecated
<ide> public PatternsRequestCondition(String[] patterns, @Nullable UrlPathHelper urlPathHelper, | 2 |
Javascript | Javascript | return empty string when given null/undefined | 0645099e027cd0e31a828572169a8c25474e2b5c | <ide><path>src/serialize.js
<ide> jQuery.param = function( a, traditional ) {
<ide> encodeURIComponent( value == null ? "" : value );
<ide> };
<ide>
<add> if ( a == null ) {
<add> return "";
<add> }
<add>
<ide> // If an array was passed in, assume that it is an array of form elements.
<ide> if ( Array.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
<ide>
<ide><path>test/unit/serialize.js
<ide> QUnit.module( "serialize", { teardown: moduleTeardown } );
<ide>
<ide> QUnit.test( "jQuery.param()", function( assert ) {
<del> assert.expect( 23 );
<add> assert.expect( 24 );
<ide>
<ide> var params;
<ide>
<ide> QUnit.test( "jQuery.param()", function( assert ) {
<ide>
<ide> params = { "test": [ 1, 2, null ] };
<ide> assert.equal( jQuery.param( params ), "test%5B%5D=1&test%5B%5D=2&test%5B%5D=", "object with array property with null value" );
<add>
<add> params = undefined;
<add> assert.equal( jQuery.param( params ), "", "jQuery.param( undefined ) === empty string" );
<ide> } );
<ide>
<ide> QUnit.test( "jQuery.param() not affected by ajaxSettings", function( assert ) { | 2 |
Python | Python | add tests for underscore | 9bd81917397e558464e1dd86ab31f1b660279e62 | <ide><path>spacy/tests/test_underscore.py
<add>from mock import Mock
<add>from ..tokens.underscore import Underscore
<add>
<add>
<add>def test_create_doc_underscore():
<add> doc = Mock()
<add> doc.doc = doc
<add> uscore = Underscore(Underscore.doc_extensions, doc)
<add> assert uscore._doc is doc
<add> assert uscore._start is None
<add> assert uscore._end is None
<add>
<add>def test_doc_underscore_getattr_setattr():
<add> doc = Mock()
<add> doc.doc = doc
<add> doc.user_data = {}
<add> Underscore.doc_extensions['hello'] = (False, None, None, None)
<add> doc._ = Underscore(Underscore.doc_extensions, doc)
<add> assert doc._.hello == False
<add> doc._.hello = True
<add> assert doc._.hello == True
<add>
<add>def test_create_span_underscore():
<add> span = Mock(doc=Mock(), start=0, end=2)
<add> uscore = Underscore(Underscore.span_extensions, span,
<add> start=span.start, end=span.end)
<add> assert uscore._doc is span.doc
<add> assert uscore._start is span.start
<add> assert uscore._end is span.end
<add>
<add>def test_span_underscore_getter_setter():
<add> span = Mock(doc=Mock(), start=0, end=2)
<add> Underscore.span_extensions['hello'] = (None, None,
<add> lambda s: (s.start, 'hi'),
<add> lambda s, value: setattr(s, 'start',
<add> value))
<add> span._ = Underscore(Underscore.span_extensions, span,
<add> start=span.start, end=span.end)
<add>
<add> assert span._.hello == (0, 'hi')
<add> span._.hello = 1
<add> assert span._.hello == (1, 'hi')
<add>
<add>
<add>def test_token_underscore_method():
<add> token = Mock(doc=Mock(), idx=7, say_cheese=lambda: 'cheese')
<add> Underscore.token_extensions['hello'] = (None, token.say_cheese,
<add> None, None)
<add> token._ = Underscore(Underscore.token_extensions, token, start=token.idx)
<add> assert token._.hello() == 'cheese' | 1 |
Ruby | Ruby | fix another constant reference | 5539c97191aa499d2e1fc78fe97d534bd744076a | <ide><path>Library/Homebrew/extend/ENV.rb
<ide> def remove_cc_etc
<ide> removed
<ide> end
<ide> def append_to_cflags newflags
<del> append(CC_FLAG_VARS, newflags)
<add> append(HomebrewEnvExtension::CC_FLAG_VARS, newflags)
<ide> end
<ide> def remove_from_cflags val
<del> remove CC_FLAG_VARS, val
<add> remove HomebrewEnvExtension::CC_FLAG_VARS, val
<ide> end
<ide> def append keys, value, separator = ' '
<ide> value = value.to_s | 1 |
Javascript | Javascript | fix documentation for ie | 55ce859998ad1f34ae84175cbb322fd8ce498970 | <ide><path>docs/spec/ngdocSpec.js
<ide> describe('ngdoc', function(){
<ide> '<doc:source>\n<>\n</doc:source></doc:example> after');
<ide> doc.parse();
<ide> expect(doc.description).toContain('<p>before </p><doc:example>' +
<del> '<doc:source>\n<>\n</doc:source></doc:example><p>after</p>');
<add> '<pre class="doc-source">\n<>\n</pre></doc:example><p>after</p>');
<ide> });
<ide>
<ide> it('should escape <doc:scenario> element', function(){
<ide> var doc = new Doc('@description before <doc:example>' +
<ide> '<doc:scenario>\n<>\n</doc:scenario></doc:example> after');
<ide> doc.parse();
<ide> expect(doc.description).toContain('<p>before </p><doc:example>' +
<del> '<doc:scenario>\n<>\n</doc:scenario></doc:example><p>after</p>');
<add> '<pre class="doc-scenario">\n<>\n</pre></doc:example><p>after</p>');
<ide> });
<ide>
<ide> describe('sorting', function(){
<ide> describe('ngdoc', function(){
<ide> ' <doc:scenario><scenario></doc:scenario>\n' +
<ide> '</doc:example>').parse();
<ide> var html = doc.html();
<del> expect(html).toContain('<doc:source><escapeme></doc:source>');
<del> expect(html).toContain('<doc:scenario><scenario></doc:scenario>');
<add> expect(html).toContain('<pre class="doc-source"><escapeme></pre>');
<add> expect(html).toContain('<pre class="doc-scenario"><scenario></pre>');
<ide> expect(doc.scenarios).toEqual(['<scenario>']);
<ide> });
<ide> });
<ide><path>docs/src/ngdoc.js
<ide> Doc.prototype = {
<ide> } else if (text.match(/^<doc:example>/)) {
<ide> text = text.replace(/(<doc:source>)([\s\S]*)(<\/doc:source>)/mi,
<ide> function(_, before, content, after){
<del> return before + htmlEscape(content) + after;
<add> return '<pre class="doc-source">' + htmlEscape(content) + '</pre>';
<ide> });
<ide> text = text.replace(/(<doc:scenario>)([\s\S]*)(<\/doc:scenario>)/mi,
<ide> function(_, before, content, after){
<ide> self.scenarios.push(content);
<del> return before + htmlEscape(content) + after;
<add> return '<pre class="doc-scenario">' + htmlEscape(content) + '</pre>';
<ide> });
<ide> } else {
<ide> text = text.replace(/<angular\/>/gm, '<tt><angular/></tt>');
<ide><path>docs/src/templates/doc_widgets.js
<ide>
<ide> var angularJsUrl;
<ide> var scripts = document.getElementsByTagName("script");
<del> var angularJsRegex = /^(|.*\/)angular(-.*?)?(\.min)?.js(\?[^#]*)?(#(.*))?$/
<add> var angularJsRegex = /^(|.*\/)angular(-.*?)?(\.min)?.js(\?[^#]*)?(#(.*))?$/;
<ide> for(var j = 0; j < scripts.length; j++) {
<ide> var src = scripts[j].src;
<ide> if (src && src.match(angularJsRegex)) {
<ide> this.descend(true); //compile the example code
<ide> element.hide();
<ide>
<del> var example = element.find('doc\\:source').eq(0),
<add> var example = element.find('pre.doc-source').eq(0),
<ide> exampleSrc = example.text(),
<del> scenario = element.find('doc\\:scenario').eq(0);
<add> scenario = element.find('pre.doc-scenario').eq(0);
<ide>
<ide> var code = indent(exampleSrc);
<ide> var tabHtml =
<ide>
<ide> function indent(text) {
<ide> if (!text) return text;
<del> var lines = text.split(/\n/);
<add> var lines = text.split(/[\n|\r]/);
<ide> var lineNo = [];
<ide> // remove any leading blank lines
<ide> while (lines[0].match(/^\s*$/)) lines.shift(); | 3 |
Text | Text | add a note about pr approvals [ci skip] | dbb3ca338e21d08e18163989cf05cfa042c850ea | <ide><path>guides/source/contributing_to_ruby_on_rails.md
<ide> While you're waiting for feedback on your pull request, open up a few other
<ide> pull requests and give someone else some! I'm sure they'll appreciate it in
<ide> the same way that you appreciate feedback on your patches.
<ide>
<add>Note that your pull request may be marked as "Approved" by somebody who does not
<add>have access to merge it. Further changes may still be required before members of
<add>the core or committer teams accept it. To prevent confusion, when giving
<add>feedback on someone else's pull request please avoid marking it as "Approved."
<add>
<ide> ### Iterate as Necessary
<ide>
<ide> It's entirely possible that the feedback you get will suggest changes. Don't get discouraged: the whole point of contributing to an active open source project is to tap into the knowledge of the community. If people are encouraging you to tweak your code, then it's worth making the tweaks and resubmitting. If the feedback is that your code doesn't belong in the core, you might still think about releasing it as a gem. | 1 |
Javascript | Javascript | remove unecessary _this binding | fe73712e5b24f5a94d83df128e18ef5af2ca9e01 | <ide><path>lib/Compilation.js
<ide> class Compilation extends Tapable {
<ide> recursive,
<ide> callback
<ide> ) {
<del> let _this = this;
<del> const start = _this.profile && Date.now();
<del> const currentProfile = _this.profile && {};
<add> const start = this.profile && Date.now();
<add> const currentProfile = this.profile && {};
<ide>
<ide> asyncLib.forEach(
<ide> dependencies,
<ide> class Compilation extends Tapable {
<ide>
<ide> const errorAndCallback = err => {
<ide> err.origin = module;
<del> _this.errors.push(err);
<add> this.errors.push(err);
<ide> if (bail) {
<ide> callback(err);
<ide> } else {
<ide> class Compilation extends Tapable {
<ide> };
<ide> const warningAndCallback = err => {
<ide> err.origin = module;
<del> _this.warnings.push(err);
<add> this.warnings.push(err);
<ide> callback();
<ide> };
<ide>
<del> const semaphore = _this.semaphore;
<add> const semaphore = this.semaphore;
<ide> semaphore.acquire(() => {
<del> if (_this === null) return semaphore.release();
<del>
<ide> const factory = item.factory;
<ide> factory.create(
<ide> {
<ide> contextInfo: {
<ide> issuer: module.nameForCondition && module.nameForCondition(),
<del> compiler: _this.compiler.name
<add> compiler: this.compiler.name
<ide> },
<ide> resolveOptions: module.resolveOptions,
<ide> context: module.context,
<ide> dependencies: dependencies
<ide> },
<ide> (err, dependentModule) => {
<del> if (_this === null) return semaphore.release();
<del>
<ide> let afterFactory;
<ide>
<ide> const isOptional = () => {
<ide> class Compilation extends Tapable {
<ide> }
<ide> };
<ide>
<del> const addModuleResult = _this.addModule(
<add> const addModuleResult = this.addModule(
<ide> dependentModule,
<ide> cacheGroup
<ide> );
<ide> class Compilation extends Tapable {
<ide> }
<ide>
<ide> if (recursive && addModuleResult.dependencies) {
<del> _this.processModuleDependencies(dependentModule, callback);
<add> this.processModuleDependencies(dependentModule, callback);
<ide> } else {
<ide> return callback();
<ide> }
<ide> class Compilation extends Tapable {
<ide>
<ide> dependentModule.issuer = module;
<ide> } else {
<del> if (_this.profile) {
<add> if (this.profile) {
<ide> if (module.profile) {
<ide> const time = Date.now() - start;
<ide> if (
<ide> class Compilation extends Tapable {
<ide> }
<ide>
<ide> if (addModuleResult.build) {
<del> _this.buildModule(
<add> this.buildModule(
<ide> dependentModule,
<ide> isOptional(),
<ide> module,
<ide> dependencies,
<ide> err => {
<del> if (_this === null) return semaphore.release();
<del>
<ide> if (err) {
<ide> semaphore.release();
<ide> return errorOrWarningAndCallback(err);
<ide> class Compilation extends Tapable {
<ide> );
<ide> } else {
<ide> semaphore.release();
<del> _this.waitForBuildingFinished(dependentModule, afterBuild);
<add> this.waitForBuildingFinished(dependentModule, afterBuild);
<ide> }
<ide> }
<ide> );
<ide> class Compilation extends Tapable {
<ide> }
<ide>
<ide> assignIndex(module) {
<del> const _this = this;
<del>
<ide> const assignIndexToModule = module => {
<ide> // enter module
<ide> if (typeof module.index !== "number") {
<del> module.index = _this.nextFreeModuleIndex++;
<add> module.index = this.nextFreeModuleIndex++;
<ide>
<ide> // leave module
<del> queue.push(() => (module.index2 = _this.nextFreeModuleIndex2++));
<add> queue.push(() => (module.index2 = this.nextFreeModuleIndex2++));
<ide>
<ide> // enter it as block
<ide> assignIndexToDependencyBlock(module); | 1 |
Javascript | Javascript | save a copy of symbol in primordials | fda80e3c99855083882a01d0d2b28b7543777b32 | <ide><path>lib/internal/bootstrap/primordials.js
<ide> primordials.SafePromise = makeSafe(
<ide> 'Function',
<ide> 'Object',
<ide> 'RegExp',
<del> 'String'
<add> 'String',
<add> 'Symbol',
<ide> ].forEach((name) => {
<ide> const target = primordials[name] = Object.create(null);
<ide> copyProps(global[name], target); | 1 |
Java | Java | add mergedannotation.gettypehierarchy method | 3b145a5a73ae4418d7d5ad2b0f10b0dd48ab3fcf | <ide><path>spring-core/src/main/java/org/springframework/core/annotation/AnnotatedElementUtils.java
<ide> public static MultiValueMap<String, Object> getAllAnnotationAttributes(Annotated
<ide>
<ide> Adapt[] adaptations = Adapt.values(classValuesAsString, nestedAnnotationsAsMap);
<ide> return getAnnotations(element).stream(annotationName)
<del> .filter(MergedAnnotationPredicates.unique(AnnotatedElementUtils::parentAndType))
<add> .filter(MergedAnnotationPredicates.unique(MergedAnnotation::getTypeHierarchy))
<ide> .map(MergedAnnotation::withNonMergedAttributes)
<ide> .collect(MergedAnnotationCollectors.toMultiValueMap(AnnotatedElementUtils::nullIfEmpty, adaptations));
<ide> }
<ide> private static MergedAnnotations findRepeatableAnnotations(AnnotatedElement elem
<ide> repeatableContainers, AnnotationFilter.PLAIN);
<ide> }
<ide>
<del> private static Object parentAndType(MergedAnnotation<Annotation> annotation) {
<del> if (annotation.getParent() == null) {
<del> return annotation.getType().getName();
<del> }
<del> return annotation.getParent().getType().getName() + ":" + annotation.getParent().getType().getName();
<del> }
<del>
<ide> @Nullable
<ide> private static MultiValueMap<String, Object> nullIfEmpty(MultiValueMap<String, Object> map) {
<ide> return (map.isEmpty() ? null : map);
<ide><path>spring-core/src/main/java/org/springframework/core/annotation/AnnotationTypeMapping.java
<ide> final class AnnotationTypeMapping {
<ide>
<ide> private final Class<? extends Annotation> annotationType;
<ide>
<add> private final List<Class<? extends Annotation>> annotationTypeHierarchy;
<add>
<ide> @Nullable
<ide> private final Annotation annotation;
<ide>
<ide> final class AnnotationTypeMapping {
<ide> this.root = (parent != null ? parent.getRoot() : this);
<ide> this.depth = (parent == null ? 0 : parent.getDepth() + 1);
<ide> this.annotationType = annotationType;
<add> this.annotationTypeHierarchy = merge(
<add> parent != null ? parent.getAnnotationTypeHierarchy() : null,
<add> annotationType);
<ide> this.annotation = annotation;
<ide> this.attributes = AttributeMethods.forAnnotationType(annotationType);
<ide> this.mirrorSets = new MirrorSets();
<ide> final class AnnotationTypeMapping {
<ide> }
<ide>
<ide>
<add> private static <T> List<T> merge(@Nullable List<T> existing, T element) {
<add> if (existing == null) {
<add> return Collections.singletonList(element);
<add> }
<add> List<T> merged = new ArrayList<>(existing.size() + 1);
<add> merged.addAll(existing);
<add> merged.add(element);
<add> return Collections.unmodifiableList(merged);
<add> }
<add>
<ide> private Map<Method, List<Method>> resolveAliasedForTargets() {
<ide> Map<Method, List<Method>> aliasedBy = new HashMap<>();
<ide> for (int i = 0; i < this.attributes.size(); i++) {
<ide> Class<? extends Annotation> getAnnotationType() {
<ide> return this.annotationType;
<ide> }
<ide>
<add> List<Class<? extends Annotation>> getAnnotationTypeHierarchy() {
<add> return this.annotationTypeHierarchy;
<add> }
<add>
<ide> /**
<ide> * Get the source annotation for this mapping. This will be the
<ide> * meta-annotation, or {@code null} if this is the root mapping.
<ide><path>spring-core/src/main/java/org/springframework/core/annotation/MergedAnnotation.java
<ide> import java.lang.reflect.AnnotatedElement;
<ide> import java.lang.reflect.Proxy;
<ide> import java.util.EnumSet;
<add>import java.util.List;
<ide> import java.util.Map;
<ide> import java.util.NoSuchElementException;
<ide> import java.util.Optional;
<ide> */
<ide> Class<A> getType();
<ide>
<add> /**
<add> * Return a complete type hierarchy from this annotation to the
<add> * {@link #getRoot() root}. Provides a useful way to uniquely identify a
<add> * merged annotation instance.
<add> * @return the type heirarchy for the annotation
<add> * @see MergedAnnotationPredicates#unique(Function)
<add> */
<add> List<Class<? extends Annotation>> getTypeHierarchy();
<add>
<ide> /**
<ide> * Determine if the annotation is present on the source. Considers
<ide> * {@linkplain #isDirectlyPresent() directly present} and
<ide><path>spring-core/src/main/java/org/springframework/core/annotation/MissingMergedAnnotation.java
<ide>
<ide> import java.lang.annotation.Annotation;
<ide> import java.util.Collections;
<add>import java.util.List;
<ide> import java.util.Map;
<ide> import java.util.NoSuchElementException;
<ide> import java.util.Optional;
<ide> public Class<A> getType() {
<ide> throw new NoSuchElementException("Unable to get type for missing annotation");
<ide> }
<ide>
<add> @Override
<add> public List<Class<? extends Annotation>> getTypeHierarchy() {
<add> return Collections.emptyList();
<add> }
<add>
<ide> @Override
<ide> public boolean isPresent() {
<ide> return false;
<ide><path>spring-core/src/main/java/org/springframework/core/annotation/TypeMappedAnnotation.java
<ide> import java.lang.reflect.Method;
<ide> import java.util.Collections;
<ide> import java.util.LinkedHashMap;
<add>import java.util.List;
<ide> import java.util.Map;
<ide> import java.util.NoSuchElementException;
<ide> import java.util.Optional;
<ide> public Class<A> getType() {
<ide> return (Class<A>) this.mapping.getAnnotationType();
<ide> }
<ide>
<add> @Override
<add> public List<Class<? extends Annotation>> getTypeHierarchy() {
<add> return this.mapping.getAnnotationTypeHierarchy();
<add> }
<add>
<ide> @Override
<ide> public boolean isPresent() {
<ide> return true;
<ide><path>spring-core/src/test/java/org/springframework/core/annotation/AnnotationTypeMappingsTests.java
<ide> public void getAnnotationTypeReturnsAnnotationType() {
<ide> assertThat(mappings.get(1).getAnnotationType()).isEqualTo(MappedTarget.class);
<ide> }
<ide>
<add> @Test
<add> public void getAnnotationTypeHierarchyReturnsTypeHierarchy() {
<add> AnnotationTypeMappings mappings = AnnotationTypeMappings.forAnnotationType(
<add> ThreeDeepA.class);
<add> AnnotationTypeMapping mappingC = mappings.get(2);
<add> assertThat(mappingC.getAnnotationTypeHierarchy()).containsExactly(
<add> ThreeDeepA.class, ThreeDeepB.class, ThreeDeepC.class);
<add> }
<add>
<ide> @Test
<ide> public void getAnnotationWhenRootReturnsNull() {
<ide> AnnotationTypeMappings mappings = AnnotationTypeMappings.forAnnotationType(
<ide><path>spring-core/src/test/java/org/springframework/core/annotation/MergedAnnotationsTests.java
<ide> public void getRootWhenDirect() {
<ide> assertThat(annotation.getRoot()).isSameAs(annotation);
<ide> }
<ide>
<add> @Test
<add> public void getTypeHierarchy() {
<add> MergedAnnotation<?> annotation = MergedAnnotations.from(
<add> ComposedTransactionalComponentClass.class).get(
<add> TransactionalComponent.class);
<add> assertThat(annotation.getTypeHierarchy()).containsExactly(
<add> ComposedTransactionalComponent.class, TransactionalComponent.class);
<add> }
<add>
<ide> @Test
<ide> public void collectMultiValueMapFromNonAnnotatedClass() {
<ide> MultiValueMap<String, Object> map = MergedAnnotations.from(
<ide><path>spring-core/src/test/java/org/springframework/core/annotation/MissingMergedAnnotationTests.java
<ide> public void getTypeThrowsNoSuchElementException() {
<ide> assertThatNoSuchElementException().isThrownBy(this.missing::getType);
<ide> }
<ide>
<add> @Test
<add> public void getTypeHierarchyReturnsEmptyList() {
<add> assertThat(this.missing.getTypeHierarchy()).isEmpty();
<add> }
<add>
<ide> @Test
<ide> public void isPresentReturnsFalse() {
<ide> assertThat(this.missing.isPresent()).isFalse(); | 8 |
PHP | PHP | introduce the `strip` argument to router | 52be365598e64d3f7178475a3a3f0f46245c70e3 | <ide><path>lib/Cake/Routing/Router.php
<ide> public static function reverse($params, $full = false) {
<ide> * @param array|string $url URL to normalize Either an array or a string URL.
<ide> * @return string Normalized URL
<ide> */
<del> public static function normalize($url = '/') {
<add> public static function normalize($url = '/', $strip = true) {
<ide> if (is_array($url)) {
<ide> $url = Router::url($url);
<ide> }
<ide> public static function normalize($url = '/') {
<ide> }
<ide> $request = Router::getRequest();
<ide>
<del> if (!empty($request->base) && stristr($url, $request->base)) {
<add> if ($strip && !empty($request->base) && stristr($url, $request->base)) {
<ide> $url = preg_replace('/^' . preg_quote($request->base, '/') . '/', '', $url, 1);
<ide> }
<ide> $url = '/' . $url;
<ide><path>lib/Cake/Test/Case/Routing/RouterTest.php
<ide> public function testUrlNormalization() {
<ide> $result = Router::normalize('/us/users/logout/');
<ide> $this->assertEquals('/users/logout', $result);
<ide>
<add> $result = Router::normalize('/us/users/logout/', false);
<add> $this->assertEquals('/us/users/logout', $result);
<add>
<ide> Router::reload();
<ide>
<ide> $request = new CakeRequest(); | 2 |
Javascript | Javascript | remove dead code in compilation.js | 847bfa4c6379679540df02e4fae3da6c838d454a | <ide><path>lib/Compilation.js
<ide> class Compilation extends Tapable {
<ide> const cacheName = (cacheGroup || "m") + identifier;
<ide> if (this.cache && this.cache[cacheName]) {
<ide> const cacheModule = this.cache[cacheName];
<del>
<del> let rebuild = true;
<del> if (this.fileTimestamps && this.contextTimestamps) {
<del> rebuild = cacheModule.needRebuild(
<del> this.fileTimestamps,
<del> this.contextTimestamps
<del> );
<del> }
<del>
<del> if (!rebuild) {
<del> cacheModule.disconnect();
<del> this._modules.set(identifier, cacheModule);
<del> this.modules.push(cacheModule);
<del> for (const err of cacheModule.errors) this.errors.push(err);
<del> for (const err of cacheModule.warnings) this.warnings.push(err);
<del> return {
<del> module: cacheModule,
<del> issuer: true,
<del> build: false,
<del> dependencies: true
<del> };
<del> }
<ide> cacheModule.unbuild();
<ide> module = cacheModule;
<ide> } | 1 |
Java | Java | expose channelid from reactornettywebsocketsession | eb7b206142aa486fa49c609305e59190247ecb09 | <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/socket/adapter/ReactorNettyWebSocketSession.java
<ide>
<ide> import java.util.function.Consumer;
<ide>
<add>import io.netty.channel.ChannelId;
<ide> import io.netty.handler.codec.http.websocketx.WebSocketFrame;
<ide> import org.reactivestreams.Publisher;
<ide> import reactor.core.publisher.Flux;
<ide> import reactor.core.publisher.Mono;
<ide> import reactor.netty.Connection;
<ide> import reactor.netty.NettyInbound;
<ide> import reactor.netty.NettyOutbound;
<add>import reactor.netty.channel.ChannelOperations;
<ide> import reactor.netty.http.websocket.WebsocketInbound;
<ide> import reactor.netty.http.websocket.WebsocketOutbound;
<ide>
<ide>
<ide> private final int maxFramePayloadLength;
<ide>
<add> private final ChannelId channelId;
<add>
<ide>
<ide> /**
<ide> * Constructor for the session, using the {@link #DEFAULT_FRAME_MAX_SIZE} value.
<ide> public ReactorNettyWebSocketSession(WebsocketInbound inbound, WebsocketOutbound
<ide>
<ide> super(new WebSocketConnection(inbound, outbound), info, bufferFactory);
<ide> this.maxFramePayloadLength = maxFramePayloadLength;
<add> this.channelId = ((ChannelOperations) inbound).channel().id();
<add> }
<add>
<add>
<add> /**
<add> * Return the id of the underlying Netty channel.
<add> * @since 5.3.4
<add> */
<add> public ChannelId getChannelId() {
<add> return this.channelId;
<ide> }
<ide>
<ide> | 1 |
Javascript | Javascript | fix creation of binary folders | 415861f1f92e570ae4fcd4b5b8d8d7ac8fcbdce3 | <ide><path>src/main-process/auto-updater-win32.js
<ide> class AutoUpdater extends EventEmitter {
<ide>
<ide> quitAndInstall() {
<ide> if (SquirrelUpdate.existsSync()) {
<del> SquirrelUpdate.restartAtom(require('electron').app);
<add> SquirrelUpdate.restartAtom();
<ide> } else {
<ide> require('electron').autoUpdater.quitAndInstall();
<ide> }
<ide><path>src/main-process/start.js
<ide> function handleStartupEventWithSquirrel() {
<ide>
<ide> const SquirrelUpdate = require('./squirrel-update');
<ide> const squirrelCommand = process.argv[1];
<del> return SquirrelUpdate.handleStartupEvent(app, squirrelCommand);
<add> return SquirrelUpdate.handleStartupEvent(squirrelCommand);
<ide> }
<ide>
<ide> function getConfig() { | 2 |
Text | Text | use serial comma in cluster docs | 74af116b2e0774566225ec080b5ad7684ab4ac9a | <ide><path>doc/api/cluster.md
<ide> primary.
<ide>
<ide> The event handler is executed with two arguments, the `worker` contains the
<ide> worker object and the `address` object contains the following connection
<del>properties: `address`, `port` and `addressType`. This is very useful if the
<add>properties: `address`, `port`, and `addressType`. This is very useful if the
<ide> worker is listening on more than one address.
<ide>
<ide> ```js | 1 |
Java | Java | add support of init and destroy methods | 672555a568445d27ab3d1efc0d87dd9bde779acc | <ide><path>spring-beans/src/main/java/org/springframework/beans/factory/annotation/InitDestroyAnnotationBeanPostProcessor.java
<ide> import java.util.Map;
<ide> import java.util.Set;
<ide> import java.util.concurrent.ConcurrentHashMap;
<add>import java.util.stream.Stream;
<ide>
<ide> import org.apache.commons.logging.Log;
<ide> import org.apache.commons.logging.LogFactory;
<ide>
<ide> import org.springframework.beans.BeansException;
<ide> import org.springframework.beans.factory.BeanCreationException;
<ide> import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor;
<add>import org.springframework.beans.factory.generator.AotContributingBeanPostProcessor;
<add>import org.springframework.beans.factory.generator.BeanInstantiationContribution;
<ide> import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor;
<ide> import org.springframework.beans.factory.support.RootBeanDefinition;
<ide> import org.springframework.core.Ordered;
<ide> import org.springframework.core.PriorityOrdered;
<ide> import org.springframework.core.annotation.AnnotationUtils;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.ClassUtils;
<add>import org.springframework.util.CollectionUtils;
<ide> import org.springframework.util.ReflectionUtils;
<ide>
<ide> /**
<ide> * for annotation-driven injection of named beans.
<ide> *
<ide> * @author Juergen Hoeller
<add> * @author Stephane Nicoll
<ide> * @since 2.5
<ide> * @see #setInitAnnotationType
<ide> * @see #setDestroyAnnotationType
<ide> */
<ide> @SuppressWarnings("serial")
<del>public class InitDestroyAnnotationBeanPostProcessor
<del> implements DestructionAwareBeanPostProcessor, MergedBeanDefinitionPostProcessor, PriorityOrdered, Serializable {
<add>public class InitDestroyAnnotationBeanPostProcessor implements DestructionAwareBeanPostProcessor,
<add> MergedBeanDefinitionPostProcessor, AotContributingBeanPostProcessor, PriorityOrdered, Serializable {
<ide>
<ide> private final transient LifecycleMetadata emptyLifecycleMetadata =
<ide> new LifecycleMetadata(Object.class, Collections.emptyList(), Collections.emptyList()) {
<ide> public int getOrder() {
<ide>
<ide> @Override
<ide> public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
<add> findInjectionMetadata(beanDefinition, beanType);
<add> }
<add>
<add> @Override
<add> public BeanInstantiationContribution contribute(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
<add> LifecycleMetadata metadata = findInjectionMetadata(beanDefinition, beanType);
<add> if (!CollectionUtils.isEmpty(metadata.initMethods)) {
<add> String[] initMethodNames = safeMerge(
<add> beanDefinition.getInitMethodNames(), metadata.initMethods);
<add> beanDefinition.setInitMethodNames(initMethodNames);
<add> }
<add> if (!CollectionUtils.isEmpty(metadata.destroyMethods)) {
<add> String[] destroyMethodNames = safeMerge(
<add> beanDefinition.getDestroyMethodNames(), metadata.destroyMethods);
<add> beanDefinition.setDestroyMethodNames(destroyMethodNames);
<add> }
<add> return null;
<add> }
<add>
<add> private LifecycleMetadata findInjectionMetadata(RootBeanDefinition beanDefinition, Class<?> beanType) {
<ide> LifecycleMetadata metadata = findLifecycleMetadata(beanType);
<ide> metadata.checkConfigMembers(beanDefinition);
<add> return metadata;
<add> }
<add>
<add> private String[] safeMerge(@Nullable String[] existingNames, Collection<LifecycleElement> detectedElements) {
<add> Stream<String> detectedNames = detectedElements.stream().map(LifecycleElement::getIdentifier);
<add> Stream<String> mergedNames = (existingNames != null
<add> ? Stream.concat(Stream.of(existingNames), detectedNames) : detectedNames);
<add> return mergedNames.distinct().toArray(String[]::new);
<ide> }
<ide>
<ide> @Override
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/generator/BeanRegistrationBeanFactoryContribution.java
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.ClassUtils;
<ide> import org.springframework.util.ObjectUtils;
<add>import org.springframework.util.ReflectionUtils;
<ide> import org.springframework.util.StringUtils;
<ide>
<ide> /**
<ide> public void applyTo(BeanFactoryInitialization initialization) {
<ide> * @param runtimeHints the runtime hints to use
<ide> */
<ide> void registerRuntimeHints(RuntimeHints runtimeHints) {
<add> String[] initMethodNames = this.beanDefinition.getInitMethodNames();
<add> if (!ObjectUtils.isEmpty(initMethodNames)) {
<add> registerInitDestroyMethodsRuntimeHints(initMethodNames, runtimeHints);
<add> }
<add> String[] destroyMethodNames = this.beanDefinition.getDestroyMethodNames();
<add> if (!ObjectUtils.isEmpty(destroyMethodNames)) {
<add> registerInitDestroyMethodsRuntimeHints(destroyMethodNames, runtimeHints);
<add> }
<ide> registerPropertyValuesRuntimeHints(runtimeHints);
<ide> }
<ide>
<ide> protected CodeContribution generateBeanInstance(RuntimeHints runtimeHints) {
<ide> return this.beanInstantiationGenerator.generateBeanInstantiation(runtimeHints);
<ide> }
<ide>
<add> private void registerInitDestroyMethodsRuntimeHints(String[] methodNames, RuntimeHints runtimeHints) {
<add> for (String methodName : methodNames) {
<add> Method method = ReflectionUtils.findMethod(getUserBeanClass(), methodName);
<add> if (method != null) {
<add> runtimeHints.reflection().registerMethod(method, hint -> hint.withMode(ExecutableMode.INVOKE));
<add> }
<add> }
<add> }
<add>
<ide> private void registerPropertyValuesRuntimeHints(RuntimeHints runtimeHints) {
<ide> if (!this.beanDefinition.hasPropertyValues()) {
<ide> return;
<ide> private boolean hasUnresolvedGenerics(ResolvableType resolvableType) {
<ide> private void handleBeanDefinitionMetadata(Builder code) {
<ide> String bdVariable = determineVariableName("bd");
<ide> MultiStatement statements = new MultiStatement();
<add> String[] initMethodNames = this.beanDefinition.getInitMethodNames();
<add> if (!ObjectUtils.isEmpty(initMethodNames)) {
<add> handleInitMethodNames(statements, bdVariable, initMethodNames);
<add> }
<add> String[] destroyMethodNames = this.beanDefinition.getDestroyMethodNames();
<add> if (!ObjectUtils.isEmpty(destroyMethodNames)) {
<add> handleDestroyMethodNames(statements, bdVariable, destroyMethodNames);
<add> }
<ide> if (this.beanDefinition.isPrimary()) {
<ide> statements.addStatement("$L.setPrimary(true)", bdVariable);
<ide> }
<ide> private void handleBeanDefinitionMetadata(Builder code) {
<ide> code.add(")");
<ide> }
<ide>
<add> private void handleInitMethodNames(MultiStatement statements, String bdVariable, String[] initMethodNames) {
<add> if (initMethodNames.length == 1) {
<add> statements.addStatement("$L.setInitMethodName($S)", bdVariable, initMethodNames[0]);
<add> }
<add> else {
<add> statements.addStatement("$L.setInitMethodNames($L)", bdVariable,
<add> this.parameterGenerator.generateParameterValue(initMethodNames));
<add> }
<add> }
<add>
<add> private void handleDestroyMethodNames(MultiStatement statements, String bdVariable, String[] destroyMethodNames) {
<add> if (destroyMethodNames.length == 1) {
<add> statements.addStatement("$L.setDestroyMethodName($S)", bdVariable, destroyMethodNames[0]);
<add> }
<add> else {
<add> statements.addStatement("$L.setDestroyMethodNames($L)", bdVariable,
<add> this.parameterGenerator.generateParameterValue(destroyMethodNames));
<add> }
<add> }
<add>
<ide> private void handleArgumentValues(MultiStatement statements, String bdVariable,
<ide> Map<Integer, ValueHolder> indexedArgumentValues) {
<ide> if (indexedArgumentValues.size() == 1) {
<ide><path>spring-beans/src/test/java/org/springframework/beans/factory/annotation/InitDestroyAnnotationBeanPostProcessorTests.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.beans.factory.annotation;
<add>
<add>import org.junit.jupiter.api.Test;
<add>
<add>import org.springframework.beans.factory.generator.BeanInstantiationContribution;
<add>import org.springframework.beans.factory.support.RootBeanDefinition;
<add>import org.springframework.beans.testfixture.beans.factory.generator.lifecycle.Destroy;
<add>import org.springframework.beans.testfixture.beans.factory.generator.lifecycle.Init;
<add>import org.springframework.beans.testfixture.beans.factory.generator.lifecycle.InitDestroyBean;
<add>import org.springframework.beans.testfixture.beans.factory.generator.lifecycle.MultiInitDestroyBean;
<add>import org.springframework.lang.Nullable;
<add>
<add>import static org.assertj.core.api.Assertions.assertThat;
<add>import static org.mockito.Mockito.mock;
<add>import static org.mockito.Mockito.verifyNoInteractions;
<add>
<add>/**
<add> * Tests for {@link InitDestroyAnnotationBeanPostProcessor}.
<add> *
<add> * @author Stephane Nicoll
<add> */
<add>class InitDestroyAnnotationBeanPostProcessorTests {
<add>
<add> @Test
<add> void contributeWithNoCallbackDoesNotMutateRootBeanDefinition() {
<add> RootBeanDefinition beanDefinition = mock(RootBeanDefinition.class);
<add> assertThat(createAotContributingBeanPostProcessor().contribute(
<add> beanDefinition, String.class, "test")).isNull();
<add> verifyNoInteractions(beanDefinition);
<add> }
<add>
<add> @Test
<add> void contributeWithInitDestroyCallback() {
<add> RootBeanDefinition beanDefinition = new RootBeanDefinition(InitDestroyBean.class);
<add> assertThat(createContribution(beanDefinition)).isNull();
<add> assertThat(beanDefinition.getInitMethodNames()).containsExactly("initMethod");
<add> assertThat(beanDefinition.getDestroyMethodNames()).containsExactly("destroyMethod");
<add> }
<add>
<add> @Test
<add> void contributeWithInitDestroyCallbackRetainCustomMethods() {
<add> RootBeanDefinition beanDefinition = new RootBeanDefinition(InitDestroyBean.class);
<add> beanDefinition.setInitMethodName("customInitMethod");
<add> beanDefinition.setDestroyMethodNames("customDestroyMethod");
<add> assertThat(createContribution(beanDefinition)).isNull();
<add> assertThat(beanDefinition.getInitMethodNames())
<add> .containsExactly("customInitMethod", "initMethod");
<add> assertThat(beanDefinition.getDestroyMethodNames())
<add> .containsExactly("customDestroyMethod", "destroyMethod");
<add> }
<add>
<add> @Test
<add> void contributeWithInitDestroyCallbackFilterDuplicates() {
<add> RootBeanDefinition beanDefinition = new RootBeanDefinition(InitDestroyBean.class);
<add> beanDefinition.setInitMethodName("initMethod");
<add> beanDefinition.setDestroyMethodNames("destroyMethod");
<add> assertThat(createContribution(beanDefinition)).isNull();
<add> assertThat(beanDefinition.getInitMethodNames()).containsExactly("initMethod");
<add> assertThat(beanDefinition.getDestroyMethodNames()).containsExactly("destroyMethod");
<add> }
<add>
<add> @Test
<add> void contributeWithMultipleInitDestroyCallbacks() {
<add> RootBeanDefinition beanDefinition = new RootBeanDefinition(MultiInitDestroyBean.class);
<add> assertThat(createContribution(beanDefinition)).isNull();
<add> assertThat(beanDefinition.getInitMethodNames())
<add> .containsExactly("initMethod", "anotherInitMethod");
<add> assertThat(beanDefinition.getDestroyMethodNames())
<add> .containsExactly("anotherDestroyMethod", "destroyMethod");
<add> }
<add>
<add> @Nullable
<add> private BeanInstantiationContribution createContribution(RootBeanDefinition beanDefinition) {
<add> InitDestroyAnnotationBeanPostProcessor bpp = createAotContributingBeanPostProcessor();
<add> return bpp.contribute(beanDefinition, beanDefinition.getResolvableType().toClass(), "test");
<add> }
<add>
<add> private InitDestroyAnnotationBeanPostProcessor createAotContributingBeanPostProcessor() {
<add> InitDestroyAnnotationBeanPostProcessor bpp = new InitDestroyAnnotationBeanPostProcessor();
<add> bpp.setInitAnnotationType(Init.class);
<add> bpp.setDestroyAnnotationType(Destroy.class);
<add> return bpp;
<add> }
<add>
<add>}
<ide><path>spring-beans/src/test/java/org/springframework/beans/factory/generator/BeanRegistrationBeanFactoryContributionTests.java
<ide> import org.springframework.beans.testfixture.beans.factory.generator.SimpleConfiguration;
<ide> import org.springframework.beans.testfixture.beans.factory.generator.factory.SampleFactory;
<ide> import org.springframework.beans.testfixture.beans.factory.generator.injection.InjectionComponent;
<add>import org.springframework.beans.testfixture.beans.factory.generator.lifecycle.InitDestroyBean;
<ide> import org.springframework.beans.testfixture.beans.factory.generator.property.ConfigurableBean;
<ide> import org.springframework.beans.testfixture.beans.factory.generator.visibility.ProtectedConstructorComponent;
<ide> import org.springframework.beans.testfixture.beans.factory.generator.visibility.ProtectedFactoryMethod;
<ide> public static void registerTest(DefaultListableBeanFactory beanFactory) {
<ide> PublicFactoryBean.class.getPackageName() + ".Test.registerTest(beanFactory);\n");
<ide> }
<ide>
<add> @Test
<add> void generateWithBeanDefinitionHavingInitMethodName() {
<add> compile(simpleConfigurationRegistration(bd -> bd.setInitMethodName("someMethod")),
<add> hasBeanDefinition(generatedBd -> assertThat(generatedBd.getInitMethodNames()).containsExactly("someMethod")));
<add> }
<add>
<add> @Test
<add> void generateWithBeanDefinitionHavingInitMethodNames() {
<add> compile(simpleConfigurationRegistration(bd -> bd.setInitMethodNames("i1", "i2")),
<add> hasBeanDefinition(generatedBd -> assertThat(generatedBd.getInitMethodNames()).containsExactly("i1", "i2")));
<add> }
<add>
<add> @Test
<add> void generateWithBeanDefinitionHavingDestroyMethodName() {
<add> compile(simpleConfigurationRegistration(bd -> bd.setDestroyMethodName("someMethod")),
<add> hasBeanDefinition(generatedBd -> assertThat(generatedBd.getDestroyMethodNames()).containsExactly("someMethod")));
<add> }
<add>
<add> @Test
<add> void generateWithBeanDefinitionHavingDestroyMethodNames() {
<add> compile(simpleConfigurationRegistration(bd -> bd.setDestroyMethodNames("d1", "d2")),
<add> hasBeanDefinition(generatedBd -> assertThat(generatedBd.getDestroyMethodNames()).containsExactly("d1", "d2")));
<add> }
<add>
<ide> @Test
<ide> void generateWithBeanDefinitionHavingSyntheticFlag() {
<ide> compile(simpleConfigurationRegistration(bd -> bd.setSynthetic(true)),
<ide> protected Predicate<String> getAttributeFilter() {
<ide> }));
<ide> }
<ide>
<add> @Test
<add> void registerRuntimeHintsWithInitMethodNames() {
<add> RootBeanDefinition bd = new RootBeanDefinition(InitDestroyBean.class);
<add> bd.setInitMethodNames("customInitMethod", "initMethod");
<add> RuntimeHints runtimeHints = new RuntimeHints();
<add> getDefaultContribution(new DefaultListableBeanFactory(), bd).registerRuntimeHints(runtimeHints);
<add> assertThat(runtimeHints.reflection().getTypeHint(InitDestroyBean.class)).satisfies(hint ->
<add> assertThat(hint.methods()).anySatisfy(invokeMethodHint("customInitMethod"))
<add> .anySatisfy(invokeMethodHint("initMethod")).hasSize(2));
<add> }
<add>
<add> @Test
<add> void registerRuntimeHintsWithDestroyMethodNames() {
<add> RootBeanDefinition bd = new RootBeanDefinition(InitDestroyBean.class);
<add> bd.setDestroyMethodNames("customDestroyMethod", "destroyMethod");
<add> RuntimeHints runtimeHints = new RuntimeHints();
<add> getDefaultContribution(new DefaultListableBeanFactory(), bd).registerRuntimeHints(runtimeHints);
<add> assertThat(runtimeHints.reflection().getTypeHint(InitDestroyBean.class)).satisfies(hint ->
<add> assertThat(hint.methods()).anySatisfy(invokeMethodHint("customDestroyMethod"))
<add> .anySatisfy(invokeMethodHint("destroyMethod")).hasSize(2));
<add> }
<add>
<ide> @Test
<ide> void registerRuntimeHintsWithNoPropertyValuesDoesNotAccessRuntimeHints() {
<ide> RootBeanDefinition bd = new RootBeanDefinition(String.class);
<ide> void registerRuntimeHintsForPropertiesUseDeclaringClass() {
<ide> assertThat(typeHint.getType()).isEqualTo(TypeReference.of(BaseFactoryBean.class));
<ide> assertThat(typeHint.constructors()).isEmpty();
<ide> assertThat(typeHint.methods()).singleElement()
<del> .satisfies(methodHint("setName", String.class));
<add> .satisfies(invokeMethodHint("setName", String.class));
<ide> assertThat(typeHint.fields()).isEmpty();
<ide> }).anySatisfy(typeHint -> {
<ide> assertThat(typeHint.getType()).isEqualTo(TypeReference.of(IntegerFactoryBean.class));
<ide> assertThat(typeHint.constructors()).singleElement()
<del> .satisfies(constructorHint(Environment.class));
<add> .satisfies(introspectConstructorHint(Environment.class));
<ide> assertThat(typeHint.methods()).isEmpty();
<ide> assertThat(typeHint.fields()).isEmpty();
<ide> }).hasSize(2);
<ide> void registerRuntimeHintsForProperties() {
<ide> assertThat(reflectionHints.typeHints()).singleElement().satisfies(typeHint -> {
<ide> assertThat(typeHint.getType()).isEqualTo(TypeReference.of(NameAndCountersComponent.class));
<ide> assertThat(typeHint.constructors()).isEmpty();
<del> assertThat(typeHint.methods()).anySatisfy(methodHint("setName", String.class))
<del> .anySatisfy(methodHint("setCounter", Integer.class)).hasSize(2);
<add> assertThat(typeHint.methods()).anySatisfy(invokeMethodHint("setName", String.class))
<add> .anySatisfy(invokeMethodHint("setCounter", Integer.class)).hasSize(2);
<ide> assertThat(typeHint.fields()).isEmpty();
<ide> });
<ide> }
<ide> void registerReflectionEntriesForInnerBeanDefinition() {
<ide> assertThat(reflectionHints.typeHints()).anySatisfy(typeHint -> {
<ide> assertThat(typeHint.getType()).isEqualTo(TypeReference.of(NameAndCountersComponent.class));
<ide> assertThat(typeHint.constructors()).isEmpty();
<del> assertThat(typeHint.methods()).singleElement().satisfies(methodHint("setCounter", Integer.class));
<add> assertThat(typeHint.methods()).singleElement().satisfies(invokeMethodHint("setCounter", Integer.class));
<ide> assertThat(typeHint.fields()).isEmpty();
<ide> }).anySatisfy(typeHint -> {
<ide> assertThat(typeHint.getType()).isEqualTo(TypeReference.of(BaseFactoryBean.class));
<del> assertThat(typeHint.methods()).singleElement().satisfies(methodHint("setName", String.class));
<add> assertThat(typeHint.methods()).singleElement().satisfies(invokeMethodHint("setName", String.class));
<ide> }).anySatisfy(typeHint -> {
<ide> assertThat(typeHint.getType()).isEqualTo(TypeReference.of(IntegerFactoryBean.class));
<del> assertThat(typeHint.constructors()).singleElement().satisfies(constructorHint(Environment.class));
<add> assertThat(typeHint.constructors()).singleElement().satisfies(introspectConstructorHint(Environment.class));
<ide> }).hasSize(3);
<ide> }
<ide>
<ide> void registerReflectionEntriesForListOfInnerBeanDefinition() {
<ide> assertThat(reflectionHints.typeHints()).anySatisfy(typeHint -> {
<ide> assertThat(typeHint.getType()).isEqualTo(TypeReference.of(NameAndCountersComponent.class));
<ide> assertThat(typeHint.constructors()).isEmpty();
<del> assertThat(typeHint.methods()).singleElement().satisfies(methodHint("setCounters", List.class));
<add> assertThat(typeHint.methods()).singleElement().satisfies(invokeMethodHint("setCounters", List.class));
<ide> assertThat(typeHint.fields()).isEmpty();
<ide> }).anySatisfy(typeHint -> {
<ide> assertThat(typeHint.getType()).isEqualTo(TypeReference.of(BaseFactoryBean.class));
<del> assertThat(typeHint.methods()).singleElement().satisfies(methodHint("setName", String.class));
<add> assertThat(typeHint.methods()).singleElement().satisfies(invokeMethodHint("setName", String.class));
<ide> }).anySatisfy(typeHint -> {
<ide> assertThat(typeHint.getType()).isEqualTo(TypeReference.of(IntegerFactoryBean.class));
<del> assertThat(typeHint.constructors()).singleElement().satisfies(constructorHint(Environment.class));
<add> assertThat(typeHint.constructors()).singleElement().satisfies(introspectConstructorHint(Environment.class));
<ide> }).anySatisfy(typeHint -> {
<ide> assertThat(typeHint.getType()).isEqualTo(TypeReference.of(AnotherIntegerFactoryBean.class));
<del> assertThat(typeHint.constructors()).singleElement().satisfies(constructorHint(Environment.class));
<add> assertThat(typeHint.constructors()).singleElement().satisfies(introspectConstructorHint(Environment.class));
<ide> }).hasSize(4);
<ide> }
<ide>
<del> private Consumer<ExecutableHint> methodHint(String name, Class<?>... parameterTypes) {
<add> private Consumer<ExecutableHint> invokeMethodHint(String name, Class<?>... parameterTypes) {
<add> return executableHint(ExecutableMode.INVOKE, name, parameterTypes);
<add> }
<add>
<add> private Consumer<ExecutableHint> introspectConstructorHint(Class<?>... parameterTypes) {
<add> return executableHint(ExecutableMode.INTROSPECT, "<init>", parameterTypes);
<add> }
<add>
<add> private Consumer<ExecutableHint> executableHint(ExecutableMode mode, String name, Class<?>... parameterTypes) {
<ide> return executableHint -> {
<ide> assertThat(executableHint.getName()).isEqualTo(name);
<ide> assertThat(executableHint.getParameterTypes()).containsExactly(Arrays.stream(parameterTypes)
<ide> .map(TypeReference::of).toArray(TypeReference[]::new));
<add> assertThat(executableHint.getModes()).containsExactly(mode);
<ide> };
<ide> }
<ide>
<del> private Consumer<ExecutableHint> constructorHint(Class<?>... parameterTypes) {
<del> return methodHint("<init>", parameterTypes);
<del> }
<del>
<ide> private Consumer<DefaultListableBeanFactory> hasBeanDefinition(Consumer<RootBeanDefinition> bd) {
<ide> return beanFactory -> {
<ide> assertThat(beanFactory.getBeanDefinitionNames()).contains("test");
<ide><path>spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/beans/factory/generator/lifecycle/Destroy.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.beans.testfixture.beans.factory.generator.lifecycle;
<add>
<add>import java.lang.annotation.Documented;
<add>import java.lang.annotation.Retention;
<add>import java.lang.annotation.Target;
<add>
<add>import static java.lang.annotation.ElementType.METHOD;
<add>import static java.lang.annotation.RetentionPolicy.RUNTIME;
<add>
<add>@Documented
<add>@Retention(RUNTIME)
<add>@Target(METHOD)
<add>public @interface Destroy {
<add>}
<ide><path>spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/beans/factory/generator/lifecycle/Init.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.beans.testfixture.beans.factory.generator.lifecycle;
<add>
<add>import java.lang.annotation.Documented;
<add>import java.lang.annotation.Retention;
<add>import java.lang.annotation.Target;
<add>
<add>import static java.lang.annotation.ElementType.METHOD;
<add>import static java.lang.annotation.RetentionPolicy.RUNTIME;
<add>
<add>@Documented
<add>@Retention(RUNTIME)
<add>@Target(METHOD)
<add>public @interface Init {
<add>}
<ide><path>spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/beans/factory/generator/lifecycle/InitDestroyBean.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.beans.testfixture.beans.factory.generator.lifecycle;
<add>
<add>public class InitDestroyBean {
<add>
<add> @Init
<add> public void initMethod() {
<add> }
<add>
<add> public void customInitMethod() {
<add> }
<add>
<add> @Destroy
<add> public void destroyMethod() {
<add> }
<add>
<add> public void customDestroyMethod() {
<add> }
<add>
<add>}
<ide><path>spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/beans/factory/generator/lifecycle/MultiInitDestroyBean.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.beans.testfixture.beans.factory.generator.lifecycle;
<add>
<add>public class MultiInitDestroyBean extends InitDestroyBean {
<add>
<add> @Init
<add> void anotherInitMethod() {
<add> }
<add>
<add> @Destroy
<add> void anotherDestroyMethod() {
<add> }
<add>
<add>}
<ide><path>spring-context/src/test/java/org/springframework/context/generator/ApplicationContextAotGeneratorTests.java
<ide> import org.springframework.beans.factory.support.RootBeanDefinition;
<ide> import org.springframework.context.ApplicationContextInitializer;
<ide> import org.springframework.context.annotation.AnnotationConfigUtils;
<add>import org.springframework.context.annotation.CommonAnnotationBeanPostProcessor;
<ide> import org.springframework.context.support.GenericApplicationContext;
<ide> import org.springframework.context.testfixture.context.generator.SimpleComponent;
<ide> import org.springframework.context.testfixture.context.generator.annotation.AutowiredComponent;
<add>import org.springframework.context.testfixture.context.generator.annotation.InitDestroyComponent;
<ide> import org.springframework.javapoet.ClassName;
<ide> import org.springframework.javapoet.CodeBlock;
<ide> import org.springframework.javapoet.JavaFile;
<ide> void generateApplicationContextWithAutowiring() {
<ide> }));
<ide> }
<ide>
<add> @Test
<add> void generateApplicationContextWithInitDestroyMethods() {
<add> GenericApplicationContext context = new GenericApplicationContext();
<add> context.registerBeanDefinition(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME,
<add> BeanDefinitionBuilder.rootBeanDefinition(CommonAnnotationBeanPostProcessor.class)
<add> .setRole(BeanDefinition.ROLE_INFRASTRUCTURE).getBeanDefinition());
<add> context.registerBeanDefinition("initDestroyComponent", new RootBeanDefinition(InitDestroyComponent.class));
<add> compile(context, toFreshApplicationContext(GenericApplicationContext::new, aotContext -> {
<add> assertThat(aotContext.getBeanDefinitionNames()).containsOnly("initDestroyComponent");
<add> InitDestroyComponent bean = aotContext.getBean(InitDestroyComponent.class);
<add> assertThat(bean.events).containsExactly("init");
<add> aotContext.close();
<add> assertThat(bean.events).containsExactly("init", "destroy");
<add> }));
<add> }
<add>
<add> @Test
<add> void generateApplicationContextWithMultipleInitDestroyMethods() {
<add> GenericApplicationContext context = new GenericApplicationContext();
<add> context.registerBeanDefinition(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME,
<add> BeanDefinitionBuilder.rootBeanDefinition(CommonAnnotationBeanPostProcessor.class)
<add> .setRole(BeanDefinition.ROLE_INFRASTRUCTURE).getBeanDefinition());
<add> RootBeanDefinition beanDefinition = new RootBeanDefinition(InitDestroyComponent.class);
<add> beanDefinition.setInitMethodName("customInit");
<add> beanDefinition.setDestroyMethodName("customDestroy");
<add> context.registerBeanDefinition("initDestroyComponent", beanDefinition);
<add> compile(context, toFreshApplicationContext(GenericApplicationContext::new, aotContext -> {
<add> assertThat(aotContext.getBeanDefinitionNames()).containsOnly("initDestroyComponent");
<add> InitDestroyComponent bean = aotContext.getBean(InitDestroyComponent.class);
<add> assertThat(bean.events).containsExactly("customInit", "init");
<add> aotContext.close();
<add> assertThat(bean.events).containsExactly("customInit", "init", "customDestroy", "destroy");
<add> }));
<add> }
<add>
<ide> @Test
<ide> void generateApplicationContextWitNoContributors() {
<ide> GeneratedTypeContext generationContext = createGenerationContext();
<ide><path>spring-context/src/testFixtures/java/org/springframework/context/testfixture/context/generator/annotation/InitDestroyComponent.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.context.testfixture.context.generator.annotation;
<add>
<add>import java.util.ArrayList;
<add>import java.util.List;
<add>
<add>import jakarta.annotation.PostConstruct;
<add>import jakarta.annotation.PreDestroy;
<add>
<add>public class InitDestroyComponent {
<add>
<add> public final List<String> events = new ArrayList<>();
<add>
<add> @PostConstruct
<add> public void init() {
<add> this.events.add("init");
<add> }
<add>
<add> public void customInit() {
<add> this.events.add("customInit");
<add> }
<add>
<add> @PreDestroy
<add> public void destroy() {
<add> this.events.add("destroy");
<add> }
<add>
<add> public void customDestroy() {
<add> this.events.add("customDestroy");
<add> }
<add>
<add>} | 10 |
Python | Python | remove some outdated comments from test | c13154933e35eb34563c8c7d65e7b527fd813a7f | <ide><path>test/test_masked_recurrent.py
<ide>
<ide> model = Sequential()
<ide> model.add(Embedding(5, 2, zero_is_mask=True))
<del>#model.add(SimpleRNN(2,3, activation='relu', return_sequences=True))
<del>#model.add(SimpleRNN(3,3, activation='relu'))
<ide> model.add(SimpleRNN(2,3, activation='relu', return_sequences=True))
<del># This next one is basically just a SimpleRNN, but I'm testing that the masking is
<ide> model.add(SimpleDeepRNN(3,3, depth=2, activation='relu'))
<ide> model.add(Dense(3,4, activation='softmax'))
<ide> model.compile(loss='categorical_crossentropy', | 1 |
Ruby | Ruby | keep `info/#{f.name}/dir` files in cleaner | fbb3ccbfd6d6ea896bf1ae7b5f20ea8c267511fe | <ide><path>Library/Homebrew/cleaner.rb
<ide> def clean
<ide> # Get rid of any info 'dir' files, so they don't conflict at the link stage
<ide> Dir.glob(@f.info/"**/dir").each do |f|
<ide> info_dir_file = Pathname(f)
<del> observe_file_removal info_dir_file if info_dir_file.file? && [email protected]_clean?(info_dir_file)
<add> observe_file_removal info_dir_file if info_dir_file.file? && info_dir_file != Pathname("#{@f.info}/#{@f.name}/dir") && [email protected]_clean?(info_dir_file)
<ide> end
<ide>
<ide> rewrite_shebangs
<ide><path>Library/Homebrew/test/cleaner_spec.rb
<ide>
<ide> expect(file).not_to exist
<ide> end
<add>
<add> it "removes 'info/**/dir' files except for 'info/<name>/dir'" do
<add> file = f.info/"dir"
<add> arch_file = f.info/"i686-elf/dir"
<add> name_file = f.info/"#{f.name}/dir"
<add>
<add> f.info.mkpath
<add> (f.info/"i686-elf").mkpath
<add> (f.info/"#{f.name}").mkpath
<add>
<add> touch file
<add> touch arch_file
<add> touch name_file
<add>
<add> cleaner.clean
<add>
<add> expect(file).not_to exist
<add> expect(arch_file).not_to exist
<add> expect(name_file).to exist
<add> end
<ide> end
<ide>
<ide> describe "::skip_clean" do | 2 |
Text | Text | add issue template | 36dc0574afda6f70fb38d7612a2485d5686705ac | <ide><path>.github/issue_template.md
<add><!--- Provide a general summary of the issue in the Title above -->
<add>
<add><!--
<add> Thank you very much for contributing to Next.js by creating an issue! ❤️
<add> To avoid duplicate issues we ask you to check off the following list
<add>-->
<add>
<add><!-- Checked checkbox should look like this: [x] -->
<add>- [ ] I have searched the [issues](https://github.com/zeit/next.js/issues) of this repository and believe that this is not a duplicate.
<add>
<add>## Expected Behavior
<add><!--- If you're describing a bug, tell us what should happen -->
<add><!--- If you're suggesting a change/improvement, tell us how it should work -->
<add>
<add>## Current Behavior
<add><!--- If describing a bug, tell us what happens instead of the expected behavior -->
<add><!--- If suggesting a change/improvement, explain the difference from current behavior -->
<add>
<add>## Steps to Reproduce (for bugs)
<add><!--- Provide a link to a live example, or an unambiguous set of steps to -->
<add><!--- reproduce this bug. Include code to reproduce, if relevant -->
<add>1.
<add>2.
<add>3.
<add>4.
<add>
<add>## Context
<add><!--- How has this issue affected you? What are you trying to accomplish? -->
<add><!--- Providing context helps us come up with a solution that is most useful in the real world -->
<add>
<add>## Your Environment
<add><!--- Include as many relevant details about the environment you experienced the bug in -->
<add>* Next.js version:
<add>* Environment name and version (e.g. Chrome 39, Node.js 5.4):
<add>* Operating System (Linux, maxOS, Windows): | 1 |
Javascript | Javascript | add comments migration to loopback script | 2422663f3499cf76b354a20f7ce6680c76d1d752 | <ide><path>seed/loopbackMigration.js
<ide> var storyCount = dbObservable
<ide> })
<ide> .count();
<ide>
<add>var commentCount = dbObservable
<add> .flatMap(function(db) {
<add> return createQuery(db, 'comments', {});
<add> })
<add> .withLatestFrom(dbObservable, function(comments, db) {
<add> return {
<add> comments: comments,
<add> db: db
<add> };
<add> })
<add> .flatMap(function(dats) {
<add> return insertMany(dats.db, 'comment', dats.comments, { w: 1 });
<add> })
<add> .buffer(20)
<add> .count();
<add>
<ide> Rx.Observable.combineLatest(
<ide> userIdentityCount,
<ide> userSavesCount,
<ide> storyCount,
<del> function(userIdentCount, userCount, storyCount) {
<add> commentCount,
<add> function(userIdentCount, userCount, storyCount, commentCount) {
<ide> return {
<ide> userIdentCount: userIdentCount * 20,
<ide> userCount: userCount * 20,
<del> storyCount: storyCount * 20
<add> storyCount: storyCount * 20,
<add> commentCount: commentCount * 20
<ide> };
<ide> })
<ide> .subscribe(
<del> function(countObj) {
<del> console.log('next');
<del> count = countObj;
<del> },
<del> function(err) {
<del> console.error('an error occured', err, err.stack);
<del> },
<del> function() {
<del>
<del> console.log('finished with ', count);
<del> process.exit(0);
<del> }
<del>);
<add> function(countObj) {
<add> console.log('next');
<add> count = countObj;
<add> },
<add> function(err) {
<add> console.error('an error occured', err, err.stack);
<add> },
<add> function() {
<add>
<add> console.log('finished with ', count);
<add> process.exit(0);
<add> }
<add> ); | 1 |
Mixed | Go | initialize volumes when container is created | 7107898d5cf0f86dc1c6dab29e9dbdad3edc9411 | <ide><path>daemon/create.go
<ide> func (daemon *Daemon) Create(config *runconfig.Config, hostConfig *runconfig.Hos
<ide> return nil, nil, err
<ide> }
<ide> }
<add> if err := container.Mount(); err != nil {
<add> return nil, nil, err
<add> }
<add> defer container.Unmount()
<add> if err := container.prepareVolumes(); err != nil {
<add> return nil, nil, err
<add> }
<ide> if err := container.ToDisk(); err != nil {
<ide> return nil, nil, err
<ide> }
<ide><path>docs/sources/reference/api/docker_remote_api.md
<ide> total memory available (`MemTotal`).
<ide> **New!**
<ide> You can set the new container's MAC address explicitly.
<ide>
<add>**New!**
<add>Volumes are now initialized when the container is created.
<add>
<ide> `POST /containers/(id)/start`
<ide>
<ide> **New!**
<ide><path>integration-cli/docker_cli_create_test.go
<ide> package main
<ide>
<ide> import (
<ide> "encoding/json"
<add> "os"
<ide> "os/exec"
<ide> "testing"
<ide> "time"
<ide> func TestCreateEchoStdout(t *testing.T) {
<ide>
<ide> logDone("create - echo test123")
<ide> }
<add>
<add>func TestCreateVolumesCreated(t *testing.T) {
<add> name := "test_create_volume"
<add> cmd(t, "create", "--name", name, "-v", "/foo", "busybox")
<add> dir, err := inspectFieldMap(name, "Volumes", "/foo")
<add> if err != nil {
<add> t.Fatalf("Error getting volume host path: %q", err)
<add> }
<add>
<add> if _, err := os.Stat(dir); err != nil && os.IsNotExist(err) {
<add> t.Fatalf("Volume was not created")
<add> }
<add> if err != nil {
<add> t.Fatalf("Error statting volume host path: %q", err)
<add> }
<add>
<add> logDone("create - volumes are created")
<add>} | 3 |
Ruby | Ruby | fix indent on test case [ci skip] | b9cd5a29dd4c6142b19c861fbf1a67452320b3dd | <ide><path>activerecord/test/cases/associations/has_many_associations_test.rb
<ide> def test_select_with_block
<ide> assert_equal [1], posts(:welcome).comments.select { |c| c.id == 1 }.map(&:id)
<ide> end
<ide>
<del> def test_select_without_foreign_key
<add> def test_select_without_foreign_key
<ide> assert_equal companies(:first_firm).accounts.first.credit_limit, companies(:first_firm).accounts.select(:credit_limit).first.credit_limit
<del> end
<add> end
<ide>
<ide> def test_adding
<ide> force_signal37_to_load_all_clients_of_firm | 1 |
Go | Go | prevent ingress deletion when endpoint count == 1 | d84f18271771fa470bbab0ca4d2c4d4ad96ebc0d | <ide><path>libnetwork/network.go
<ide> func (n *network) delete(force bool) error {
<ide>
<ide> if len(n.loadBalancerIP) != 0 {
<ide> endpoints := n.Endpoints()
<del> if force || len(endpoints) == 1 {
<add> if force || (len(endpoints) == 1 && !n.ingress) {
<ide> n.deleteLoadBalancerSandbox()
<ide> }
<ide> //Reload the network from the store to update the epcnt. | 1 |
Ruby | Ruby | remove extraneous file | 29a9225b3fdda1c276b5930fa1402f3811ad7d50 | <ide><path>scripts/helpers/parsed_file.rb
<add>require 'fileutils'
<add>
<add>class ParsedFile
<add>
<add> def get_latest_file(directory)
<add> puts "- retrieving latest file in directory: #{directory}"
<add> Dir.glob("#{directory}/*").max_by(1) {|f| File.mtime(f)}[0]
<add> end
<add>
<add> def save_to(directory, data)
<add> # Create directory if does not exist
<add> FileUtils.mkdir_p directory unless Dir.exists?(directory)
<add>
<add> puts "- Generating datetime stamp"
<add> #Include time to the filename for uniqueness when fetching multiple times a day
<add> date_time = Time.new.strftime("%Y-%m-%dT%H_%M_%S")
<add>
<add> # Writing parsed data to file
<add> puts "- Writing data to file"
<add> File.write("#{directory}/#{date_time}.txt", data)
<add> end
<add>
<add>end
<ide>\ No newline at end of file | 1 |
Python | Python | fix the syntax | d26c9a61e964ae066209a8ab73baedbfb1842d96 | <ide><path>docs/examples/compute/openstack_floating_ips.py
<ide> ex_tenant_name='your_tenant')
<ide>
<ide> # get the first pool - public by default
<del>pool, = driver.ex_list_floating_ip_pools()
<add>pool = driver.ex_list_floating_ip_pools()[0]
<ide>
<ide> # create an ip in the pool
<ide> floating_ip = pool.create_floating_ip() | 1 |
Python | Python | fix sparse checkout | dc22771f879455a81d8338588aa726a58b08bf50 | <ide><path>spacy/cli/_util.py
<ide> def git_sparse_checkout(repo, subpath, dest, branch):
<ide> run_command(cmd)
<ide> # Now we need to find the missing filenames for the subpath we want.
<ide> # Looking for this 'rev-list' command in the git --help? Hah.
<del> cmd = f"git -C {tmp_dir} rev-list --objects --all {'--missing=print ' if use_sparse else ''} -- {subpath}"
<add> cmd = f"git -C {tmp_dir} rev-list --objects --all --missing=print -- {subpath}"
<ide> ret = run_command(cmd, capture=True)
<ide> git_repo = _from_http_to_git(repo)
<ide> # Now pass those missings into another bit of git internals | 1 |
Javascript | Javascript | find duplicates globally. don't fallback shortest | 15e83490b8023e34edb995346b19e8318e7be7fb | <ide><path>lib/ModuleFilenameHelpers.js
<ide> ModuleFilenameHelpers.createFooter = function createFooter(module, requestShorte
<ide> }
<ide> };
<ide>
<del>ModuleFilenameHelpers.replaceDuplicates = function replaceDuplicates(array, fn) {
<add>ModuleFilenameHelpers.replaceDuplicates = function replaceDuplicates(array, fn, comparator) {
<ide> var countMap = {};
<ide> var posMap = {};
<del> array.forEach(function(item) {
<del> countMap[item] = (countMap[item] || 0) + 1;
<add> array.forEach(function(item, idx) {
<add> countMap[item] = (countMap[item] || []);
<add> countMap[item].push(idx);
<ide> posMap[item] = 0;
<ide> });
<add> if(comparator) {
<add> Object.keys(countMap).forEach(function(item) {
<add> countMap[item].sort(comparator);
<add> });
<add> }
<ide> return array.map(function(item, i) {
<del> if(countMap[item] > 1) {
<add> if(countMap[item].length > 1) {
<add> if(comparator && countMap[item][0] === i)
<add> return item;
<ide> return fn(item, i, posMap[item]++);
<ide> } else return item;
<ide> });
<ide><path>lib/SourceMapDevToolPlugin.js
<ide> SourceMapDevToolPlugin.prototype.apply = function(compiler) {
<ide> module.useSourceMap = true;
<ide> });
<ide> compilation.plugin("after-optimize-chunk-assets", function(chunks) {
<add> var allModules = [];
<add> var allModuleFilenames = [];
<add> var tasks = [];
<ide> chunks.forEach(function(chunk) {
<del> chunk.files.slice().forEach(function(file) {
<add> chunk.files.slice().map(function(file) {
<ide> var asset = this.assets[file];
<ide> if(asset.__SourceMapDevTool_Data) {
<ide> var data = asset.__SourceMapDevTool_Data;
<ide> SourceMapDevToolPlugin.prototype.apply = function(compiler) {
<ide> }
<ide> var sourceMap = asset.map();
<ide> if(sourceMap) {
<del> var modules = sourceMap.sources.map(function(source) {
<del> var module = compilation.findModule(source);
<del> return module || source;
<del> });
<del> var moduleFilenames = modules.map(function(module) {
<del> return ModuleFilenameHelpers.createFilename(module, moduleFilenameTemplate, requestShortener);
<del> });
<del> moduleFilenames = ModuleFilenameHelpers.replaceDuplicates(moduleFilenames, function(filename, i) {
<del> return ModuleFilenameHelpers.createFilename(modules[i], fallbackModuleFilenameTemplate, requestShortener);
<del> });
<del> moduleFilenames = ModuleFilenameHelpers.replaceDuplicates(moduleFilenames, function(filename, i, n) {
<del> for(var j = 0; j < n; j++)
<del> filename += "*";
<del> return filename;
<del> });
<del> sourceMap.sources = moduleFilenames;
<del> if(sourceMap.sourcesContent) {
<del> sourceMap.sourcesContent = sourceMap.sourcesContent.map(function(content, i) {
<del> return content + "\n\n\n" + ModuleFilenameHelpers.createFooter(modules[i], requestShortener);
<del> });
<del> }
<del> sourceMap.sourceRoot = "";
<del> sourceMap.file = file;
<del> asset.__SourceMapDevTool_Data = {};
<del> if(sourceMapFilename) {
<del> var filename = file, query = "";
<del> var idx = filename.indexOf("?");
<del> if(idx >= 0) {
<del> query = filename.substr(idx);
<del> filename = filename.substr(0, idx);
<del> }
<del> var sourceMapFile = sourceMapFilename
<del> .replace(Template.REGEXP_FILE, filename)
<del> .replace(Template.REGEXP_QUERY, query)
<del> .replace(Template.REGEXP_FILEBASE, basename(filename))
<del> .replace(Template.REGEXP_HASH, this.hash)
<del> .replace(Template.REGEXP_ID, chunk.id);
<del> var sourceMapUrl = path.relative(path.dirname(file), sourceMapFile).replace(/\\/g, "/");
<del> asset.__SourceMapDevTool_Data[file] = this.assets[file] = new ConcatSource(asset, sourceMappingURLComment.replace(/\[url\]/g, sourceMapUrl));
<del> asset.__SourceMapDevTool_Data[sourceMapFile] = this.assets[sourceMapFile] = new RawSource(JSON.stringify(sourceMap));
<del> chunk.files.push(sourceMapFile);
<del> } else {
<del> asset.__SourceMapDevTool_Data[file] = this.assets[file] = new ConcatSource(asset, sourceMappingURLComment.replace(/\[url\]/g, "data:application/json;base64," + new Buffer(JSON.stringify(sourceMap)).toString("base64")));
<add> return {
<add> chunk: chunk,
<add> file: file,
<add> asset: asset,
<add> sourceMap: sourceMap
<ide> }
<ide> }
<add> }, this).filter(Boolean).map(function(task) {
<add> var modules = task.sourceMap.sources.map(function(source) {
<add> var module = compilation.findModule(source);
<add> return module || source;
<add> });
<add> var moduleFilenames = modules.map(function(module) {
<add> return ModuleFilenameHelpers.createFilename(module, moduleFilenameTemplate, requestShortener);
<add> });
<add> task.modules = modules;
<add> task.moduleFilenames = moduleFilenames;
<add> return task;
<add> }, this).forEach(function(task) {
<add> allModules = allModules.concat(task.modules);
<add> allModuleFilenames = allModuleFilenames.concat(task.moduleFilenames);
<add> tasks.push(task);
<ide> }, this);
<ide> }, this);
<add> allModuleFilenames = ModuleFilenameHelpers.replaceDuplicates(allModuleFilenames, function(filename, i) {
<add> return ModuleFilenameHelpers.createFilename(allModules[i], fallbackModuleFilenameTemplate, requestShortener);
<add> }, function(ai, bi) {
<add> var a = allModules[ai];
<add> var b = allModules[bi];
<add> a = typeof a === "string" ? a : a.identifier();
<add> b = typeof b === "string" ? b : b.identifier();
<add> return a.length - b.length;
<add> });
<add> allModuleFilenames = ModuleFilenameHelpers.replaceDuplicates(allModuleFilenames, function(filename, i, n) {
<add> for(var j = 0; j < n; j++)
<add> filename += "*";
<add> return filename;
<add> });
<add> tasks.forEach(function(task) {
<add> task.moduleFilenames = allModuleFilenames.slice(0, task.moduleFilenames.length);
<add> allModuleFilenames = allModuleFilenames.slice(task.moduleFilenames.length);
<add> }, this);
<add> tasks.forEach(function(task) {
<add> var chunk = task.chunk;
<add> var file = task.file;
<add> var asset = task.asset;
<add> var sourceMap = task.sourceMap;
<add> var moduleFilenames = task.moduleFilenames;
<add> var modules = task.modules;
<add> sourceMap.sources = moduleFilenames;
<add> if(sourceMap.sourcesContent) {
<add> sourceMap.sourcesContent = sourceMap.sourcesContent.map(function(content, i) {
<add> return content + "\n\n\n" + ModuleFilenameHelpers.createFooter(modules[i], requestShortener);
<add> });
<add> }
<add> sourceMap.sourceRoot = "";
<add> sourceMap.file = file;
<add> asset.__SourceMapDevTool_Data = {};
<add> if(sourceMapFilename) {
<add> var filename = file, query = "";
<add> var idx = filename.indexOf("?");
<add> if(idx >= 0) {
<add> query = filename.substr(idx);
<add> filename = filename.substr(0, idx);
<add> }
<add> var sourceMapFile = sourceMapFilename
<add> .replace(Template.REGEXP_FILE, filename)
<add> .replace(Template.REGEXP_QUERY, query)
<add> .replace(Template.REGEXP_FILEBASE, basename(filename))
<add> .replace(Template.REGEXP_HASH, this.hash)
<add> .replace(Template.REGEXP_ID, chunk.id);
<add> var sourceMapUrl = path.relative(path.dirname(file), sourceMapFile).replace(/\\/g, "/");
<add> asset.__SourceMapDevTool_Data[file] = this.assets[file] = new ConcatSource(asset, sourceMappingURLComment.replace(/\[url\]/g, sourceMapUrl));
<add> asset.__SourceMapDevTool_Data[sourceMapFile] = this.assets[sourceMapFile] = new RawSource(JSON.stringify(sourceMap));
<add> chunk.files.push(sourceMapFile);
<add> } else {
<add> asset.__SourceMapDevTool_Data[file] = this.assets[file] = new ConcatSource(asset, sourceMappingURLComment.replace(/\[url\]/g, "data:application/json;base64," + new Buffer(JSON.stringify(sourceMap)).toString("base64")));
<add> }
<add> }, this);
<ide> });
<ide> });
<ide> }; | 2 |
Text | Text | add v3.21.0-beta.3 to changelog | 1b8e122635607afe8f967a00f9a33c52ab1f3472 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### v3.21.0-beta.3 (July 27, 2020)
<add>
<add>- [#19048](https://github.com/emberjs/ember.js/pull/19048) [BUGFIX] Update router.js to ensure transition.abort works for query param only transitions.
<add>- [#19056](https://github.com/emberjs/ember.js/pull/19056) [BUGFIX] Update glimmer-vm to 0.54.2.
<add>
<ide> ### v3.20.2 (July 26, 2020)
<ide>
<ide> - [#19056](https://github.com/emberjs/ember.js/pull/19056) Update Glimmer rendering engine to 0.54.2. Fixes an issue with (private for now) destroyables work to enable the destroyables polyfill to work more appropriately. | 1 |
PHP | PHP | add support for "_serialized" = true for xmlview | 62f75376eac496e7f5f351c02085690ce623e667 | <ide><path>src/View/XmlView.php
<ide> use Cake\Network\Response;
<ide> use Cake\Utility\Hash;
<ide> use Cake\Utility\Xml;
<add>use Cake\View\SerializeView;
<ide>
<ide> /**
<ide> * A view class that is used for creating XML responses.
<ide> * If you don't use the `_serialize` key, you will need a view. You can use extended
<ide> * views to provide layout like functionality.
<ide> */
<del>class XmlView extends View
<add>class XmlView extends SerializedView
<ide> {
<ide>
<ide> /**
<ide> class XmlView extends View
<ide> public $subDir = 'xml';
<ide>
<ide> /**
<del> * Constructor
<add> * Response type.
<ide> *
<del> * @param \Cake\Network\Request|null $request Request instance
<del> * @param \Cake\Network\Response|null $response Response instance
<del> * @param \Cake\Event\EventManager|null $eventManager Event Manager
<del> * @param array $viewOptions View options.
<del> */
<del> public function __construct(
<del> Request $request = null,
<del> Response $response = null,
<del> EventManager $eventManager = null,
<del> array $viewOptions = []
<del> ) {
<del> parent::__construct($request, $response, $eventManager, $viewOptions);
<del>
<del> if ($response && $response instanceof Response) {
<del> $response->type('xml');
<del> }
<del> }
<del>
<del> /**
<del> * Skip loading helpers if this is a _serialize based view.
<del> *
<del> * @return void
<add> * @var string
<ide> */
<del> public function loadHelpers()
<del> {
<del> if (isset($this->viewVars['_serialize'])) {
<del> return;
<del> }
<del> parent::loadHelpers();
<del> }
<add> public $_responseType = 'xml';
<ide>
<ide> /**
<del> * Render a XML view.
<del> *
<del> * Uses the special '_serialize' parameter to convert a set of
<del> * view variables into a XML response. Makes generating simple
<del> * XML responses very easy. You can omit the '_serialize' parameter,
<del> * and use a normal view + layout as well.
<add> * List of special view vars.
<ide> *
<del> * @param string|null $view The view being rendered.
<del> * @param string|null $layout The layout being rendered.
<del> * @return string The rendered view.
<add> * @var array
<ide> */
<del> public function render($view = null, $layout = null)
<del> {
<del> if (isset($this->viewVars['_serialize'])) {
<del> return $this->_serialize($this->viewVars['_serialize']);
<del> }
<del> if ($view !== false && $this->_getViewFileName($view)) {
<del> return parent::render($view, false);
<del> }
<del> }
<add> protected $_specialVars = ['_serialize', '_rootNode', '_xmlOptions'];
<ide>
<ide> /**
<ide> * Serialize view vars.
<ide> protected function _serialize($serialize)
<ide> {
<ide> $rootNode = isset($this->viewVars['_rootNode']) ? $this->viewVars['_rootNode'] : 'response';
<ide>
<add> if ($serialize === true) {
<add> $serialize = array_diff(
<add> array_keys($this->viewVars),
<add> $this->_specialVars
<add> );
<add>
<add> if (empty($serialize)) {
<add> $serialize = null;
<add> } elseif (count($serialize) === 1) {
<add> $serialize = current($serialize);
<add> }
<add> }
<add>
<ide> if (is_array($serialize)) {
<ide> $data = [$rootNode => []];
<ide> foreach ($serialize as $alias => $key) {
<ide><path>tests/TestCase/View/XmlViewTest.php
<ide> public function testRenderWithoutViewMultipleAndAlias()
<ide> $this->assertSame(Xml::build($expected)->asXML(), $output);
<ide> }
<ide>
<add> /**
<add> * test rendering with _serialize true
<add> *
<add> * @return void
<add> */
<add> public function testRenderWithSerializeTrue()
<add> {
<add> $Request = new Request();
<add> $Response = new Response();
<add> $Controller = new Controller($Request, $Response);
<add> $data = ['users' => ['user' => ['user1', 'user2']]];
<add> $Controller->set(['users' => $data, '_serialize' => true]);
<add> $Controller->viewClass = 'Xml';
<add> $View = $Controller->createView();
<add> $output = $View->render();
<add>
<add> $this->assertSame(Xml::build($data)->asXML(), $output);
<add> $this->assertSame('application/xml', $Response->type());
<add>
<add> $data = ['no' => 'nope', 'user' => 'fake', 'list' => ['item1', 'item2']];
<add> $Controller->viewVars = [];
<add> $Controller->set($data);
<add> $Controller->set('_serialize', true);
<add> $View = $Controller->createView();
<add> $output = $View->render();
<add> $expected = [
<add> 'response' => $data
<add> ];
<add> $this->assertSame(Xml::build($expected)->asXML(), $output);
<add> }
<add>
<ide> /**
<ide> * testRenderWithView method
<ide> * | 2 |
Ruby | Ruby | simplify activesupport.test_order definition | 9f7ab82ad2d458b2bc5b3c5dba7cfc577a4b87eb | <ide><path>activesupport/lib/active_support.rb
<ide> def self.eager_load!
<ide> NumberHelper.eager_load!
<ide> end
<ide>
<del> @@test_order = nil
<del>
<del> def self.test_order=(new_order) # :nodoc:
<del> @@test_order = new_order
<del> end
<del>
<del> def self.test_order # :nodoc:
<del> @@test_order
<del> end
<add> cattr_accessor :test_order # :nodoc:
<add> self.test_order = nil
<ide> end
<ide>
<ide> autoload :I18n, "active_support/i18n" | 1 |
Text | Text | remove duplicate sentence in readme.md | 1146b3546a847dcd832148b6dbc96c9109744af1 | <ide><path>README.md
<ide> friendly** by using hashes.
<ide>
<ide> [Optimization documentation](https://webpack.github.io/docs/optimization.html)
<ide>
<del>webpack optimizes in several ways. It also makes your chunks **cache-friendly** by using hashes.
<del>
<ide> # A small example of what's possible
<ide>
<ide> ``` javascript | 1 |
Ruby | Ruby | use json to cache descriptions | 65996b5887ac6e4b669e9460b8e2a4fbc7171984 | <ide><path>Library/Homebrew/descriptions.rb
<ide> require "formula"
<ide> require "formula_versions"
<del>require "csv"
<ide>
<ide> class Descriptions
<del> CACHE_FILE = HOMEBREW_CACHE + "desc_cache"
<add> CACHE_FILE = HOMEBREW_CACHE + "desc_cache.json"
<ide>
<ide> def self.cache
<ide> @cache || self.load_cache
<ide> def self.cache
<ide> # return nil.
<ide> def self.load_cache
<ide> if CACHE_FILE.exist?
<del> @cache = {}
<del> CSV.foreach(CACHE_FILE) { |name, desc| @cache[name] = desc }
<del> @cache
<add> @cache = Utils::JSON.load(CACHE_FILE.read)
<ide> end
<ide> end
<ide>
<ide> # Write the cache to disk after ensuring the existence of the containing
<ide> # directory.
<ide> def self.save_cache
<ide> HOMEBREW_CACHE.mkpath
<del> CSV.open(CACHE_FILE, 'w') do |csv|
<del> @cache.each do |name, desc|
<del> csv << [name, desc]
<del> end
<del> end
<add> CACHE_FILE.atomic_write Utils::JSON.dump(@cache)
<ide> end
<ide>
<ide> # Create a hash mapping all formulae to their descriptions; | 1 |
Ruby | Ruby | remove extra case | 7c17fdfd11ccb991812cabf9d16acaa65eda08a5 | <ide><path>activerecord/lib/active_record/connection_adapters/abstract/quoting.rb
<ide> def type_cast(value, column)
<ide> return value unless column
<ide>
<ide> case column.type
<del> when :binary then value
<ide> when :integer then value.to_i
<ide> when :float then value.to_f
<ide> else | 1 |
Python | Python | add example section in the -h tag | 7bdbfea67b7965e49d5245bc6d3a19fcc60a840e | <ide><path>glances/core/glances_main.py
<ide> class GlancesMain(object):
<ide> username = "glances"
<ide> password = ""
<ide>
<add> # Exemple of use
<add> example_of_use = "\
<add>Examples of use:\n\
<add>\n\
<add>Monitor local machine (standalone mode):\n\
<add> $ glances\n\
<add>\n\
<add>Monitor local machine with the Web interface (Web UI):\n\
<add> $ glances -w\n\
<add> Glances web server started on http://0.0.0.0:61208/\n\
<add>\n\
<add>Monitor local machine and export stats to a CSV file (standalone mode):\n\
<add> $ glances --export-csv\n\
<add>\n\
<add>Monitor local machine and export stats to a InfluxDB server with 5s refresh time (standalone mode):\n\
<add> $ glances -t 5 --export-influxdb -t 5\n\
<add>\n\
<add>Start a Glances server (server mode):\n\
<add> $ glances -s\n\
<add>\n\
<add>Connect Glances to a Glances server (client mode):\n\
<add> $ glances -c <ip_server>\n\
<add>\n\
<add>Connect Glances to a Glances server and export stats to a StatsD server (client mode):\n\
<add> $ glances -c <ip_server> --export-statsd\n\
<add>\n\
<add>Start the client browser (browser mode):\n\
<add> $ glances --browser\n\
<add> "
<add>
<ide> def __init__(self):
<ide> """Manage the command line arguments."""
<ide> self.args = self.parse_args()
<ide> def init_args(self):
<ide> """Init all the command line arguments."""
<ide> _version = "Glances v" + version + " with psutil v" + psutil_version
<ide> parser = argparse.ArgumentParser(
<del> prog=appname, conflict_handler='resolve')
<add> prog=appname,
<add> conflict_handler='resolve',
<add> formatter_class=argparse.RawDescriptionHelpFormatter,
<add> epilog=self.example_of_use)
<ide> parser.add_argument(
<ide> '-V', '--version', action='version', version=_version)
<ide> parser.add_argument('-d', '--debug', action='store_true', default=False,
<ide> def init_args(self):
<ide> parser.add_argument('--disable-docker', action='store_true', default=False,
<ide> dest='disable_docker', help=_('disable Docker module'))
<ide> parser.add_argument('--disable-left-sidebar', action='store_true', default=False,
<del> dest='disable_left_sidebar', help=_('disable network, disk io, FS and sensors modules'))
<add> dest='disable_left_sidebar', help=_('disable network, disk io, FS and sensors modules (need Py3Sensors lib)'))
<ide> parser.add_argument('--disable-process', action='store_true', default=False,
<ide> dest='disable_process', help=_('disable process module'))
<ide> parser.add_argument('--disable-log', action='store_true', default=False,
<ide> def init_args(self):
<ide> parser.add_argument('--enable-process-extended', action='store_true', default=False,
<ide> dest='enable_process_extended', help=_('enable extended stats on top process'))
<ide> parser.add_argument('--enable-history', action='store_true', default=False,
<del> dest='enable_history', help=_('enable the history mode'))
<add> dest='enable_history', help=_('enable the history mode (need MatPlotLib lib)'))
<ide> parser.add_argument('--path-history', default=tempfile.gettempdir(),
<ide> dest='path_history', help=_('Set the export path for graph history'))
<ide> # Export modules feature
<ide> parser.add_argument('--export-csv', default=None,
<ide> dest='export_csv', help=_('export stats to a CSV file'))
<ide> parser.add_argument('--export-influxdb', action='store_true', default=False,
<del> dest='export_influxdb', help=_('export stats to an InfluxDB server'))
<add> dest='export_influxdb', help=_('export stats to an InfluxDB server (need InfluDB lib)'))
<ide> parser.add_argument('--export-statsd', action='store_true', default=False,
<del> dest='export_statsd', help=_('export stats to a Statsd server'))
<add> dest='export_statsd', help=_('export stats to a Statsd server (need StatsD lib)'))
<ide> # Client/Server option
<ide> parser.add_argument('-c', '--client', dest='client',
<ide> help=_('connect to a Glances server by IPv4/IPv6 address or hostname'))
<ide> def init_args(self):
<ide> parser.add_argument('-t', '--time', default=self.refresh_time, type=float,
<ide> dest='time', help=_('set refresh time in seconds [default: {0} sec]').format(self.refresh_time))
<ide> parser.add_argument('-w', '--webserver', action='store_true', default=False,
<del> dest='webserver', help=_('run Glances in web server mode'))
<add> dest='webserver', help=_('run Glances in web server mode (need Bootle lib)'))
<ide> # Display options
<ide> parser.add_argument('-f', '--process-filter', default=None, type=str,
<ide> dest='process_filter', help=_('set the process filter pattern (regular expression)')) | 1 |
Mixed | Go | add cert-expiry to swarm update | 7d8d51aa9d0c1737ff7f97a3efac0a2ef0975b56 | <ide><path>api/client/swarm/update.go
<ide> type updateOptions struct {
<ide> secret string
<ide> taskHistoryLimit int64
<ide> dispatcherHeartbeat time.Duration
<add> nodeCertExpiry time.Duration
<ide> }
<ide>
<ide> func newUpdateCommand(dockerCli *client.DockerCli) *cobra.Command {
<ide> func newUpdateCommand(dockerCli *client.DockerCli) *cobra.Command {
<ide> flags.StringVar(&opts.secret, "secret", "", "Set secret value needed to accept nodes into cluster")
<ide> flags.Int64Var(&opts.taskHistoryLimit, "task-history-limit", 10, "Task history retention limit")
<ide> flags.DurationVar(&opts.dispatcherHeartbeat, "dispatcher-heartbeat", time.Duration(5*time.Second), "Dispatcher heartbeat period")
<add> flags.DurationVar(&opts.nodeCertExpiry, "cert-expiry", time.Duration(90*24*time.Hour), "Validity period for node certificates")
<ide> return cmd
<ide> }
<ide>
<ide> func mergeSwarm(swarm *swarm.Swarm, flags *pflag.FlagSet) error {
<ide> }
<ide> }
<ide>
<add> if flags.Changed("cert-expiry") {
<add> if v, err := flags.GetDuration("cert-expiry"); err == nil {
<add> spec.CAConfig.NodeCertExpiry = v
<add> }
<add> }
<add>
<ide> return nil
<ide> }
<ide><path>docs/reference/commandline/swarm_update.md
<ide> parent = "smn_cli"
<ide> --help Print usage
<ide> --secret string Set secret value needed to accept nodes into cluster
<ide> --task-history-limit int Task history retention limit (default 10)
<add> --cert-expiry duration Validity period for node certificates (default 2160h0m0s)
<ide>
<ide> Updates a Swarm cluster with new parameter values. This command must target a manager node.
<ide> | 2 |
PHP | PHP | avoid code duplication | 6861cb9cbcda6054e600e221f457064a8b3ae1c4 | <ide><path>src/Filesystem/Filesystem.php
<ide> class Filesystem
<ide> public const TYPE_DIR = 'dir';
<ide>
<ide> /**
<del> * Find files (non-recursively) in given directory path.
<add> * Find files / directories (non-recursively) in given directory path.
<ide> *
<ide> * @param string $path Directory path.
<ide> * @param mixed $filter If string will be used as regex for filtering using
<ide> public function find(string $path, $filter = null, ?int $flags = null): Traversa
<ide> return $directory;
<ide> }
<ide>
<del> if (is_string($filter)) {
<del> return new RegexIterator($directory, $filter);
<del> }
<del>
<del> return new CallbackFilterIterator($directory, $filter);
<add> return $this->filterIterator($directory, $filter);
<ide> }
<ide>
<ide> /**
<del> * Find files recursively in given directory path.
<add> * Find files/ directories recursively in given directory path.
<ide> *
<ide> * @param string $path Directory path.
<ide> * @param mixed $filter If string will be used as regex for filtering using
<ide> function (SplFileInfo $current) {
<ide> return $flatten;
<ide> }
<ide>
<add> return $this->filterIterator($flatten, $filter);
<add> }
<add>
<add> /**
<add> * Wrap iterator in additional filtering iterator.
<add> *
<add> * @param \Traversable $iterator Iterator
<add> * @param mixed $filter Regex string or callback.
<add> * @return \Traversable
<add> */
<add> protected function filterIterator(Traversable $iterator, $filter): Traversable
<add> {
<ide> if (is_string($filter)) {
<del> return new RegexIterator($flatten, $filter);
<add> return new RegexIterator($iterator, $filter);
<ide> }
<ide>
<del> return new CallbackFilterIterator($flatten, $filter);
<add> return new CallbackFilterIterator($iterator, $filter);
<ide> }
<ide>
<ide> /** | 1 |
PHP | PHP | fix bug in many to many eager loading | cc4514e8f6918bf0072da22f9dd55c94268c945c | <ide><path>laravel/database/eloquent/query.php
<del><?php namespace Laravel\Database\Eloquent; use Laravel\Database;
<add><?php namespace Laravel\Database\Eloquent;
<add>
<add>use Laravel\Database;
<add>use Laravel\Database\Eloquent\Relationships\Has_Many_And_Belongs_To;
<ide>
<ide> class Query {
<ide>
<ide> public function __construct($model)
<ide> */
<ide> public function first($columns = array('*'))
<ide> {
<del> $results = $this->hydrate($this->model, $this->table->take(1)->get($columns, false));
<add> $results = $this->hydrate($this->model, $this->table->take(1)->get($columns));
<ide>
<ide> return (count($results) > 0) ? head($results) : null;
<ide> }
<ide> public function first($columns = array('*'))
<ide> * Get all of the model results for the query.
<ide> *
<ide> * @param array $columns
<del> * @param bool $include
<add> * @param bool $keyed
<ide> * @return array
<ide> */
<del> public function get($columns = array('*'), $include = true)
<add> public function get($columns = array('*'), $keyed = true)
<ide> {
<del> return $this->hydrate($this->model, $this->table->get($columns), $include);
<add> return $this->hydrate($this->model, $this->table->get($columns), $keyed);
<ide> }
<ide>
<ide> /**
<ide> public function paginate($per_page = null, $columns = array('*'))
<ide> *
<ide> * @param Model $model
<ide> * @param array $results
<add> * @param bool $keyed
<ide> * @return array
<ide> */
<del> public function hydrate($model, $results, $include = true)
<add> public function hydrate($model, $results, $keyed = true)
<ide> {
<ide> $class = get_class($model);
<ide>
<ide> public function hydrate($model, $results, $include = true)
<ide>
<ide> $new->original = $new->attributes;
<ide>
<del> $models[$result[$this->model->key()]] = $new;
<add> // Typically, the resulting models are keyed by their primary key, but it
<add> // may be useful to not do this in some circumstances such as when we
<add> // are eager loading a *-to-* relationships which has duplicates.
<add> if ($keyed)
<add> {
<add> $models[$result[$this->model->key()]] = $new;
<add> }
<add> else
<add> {
<add> $models[] = $new;
<add> }
<ide> }
<ide>
<del> if ($include and count($results) > 0)
<add> if (count($results) > 0)
<ide> {
<ide> foreach ($this->model_includes() as $relationship => $constraints)
<ide> {
<ide> protected function load(&$results, $relationship, $constraints)
<ide> $query->table->where_nested($constraints);
<ide> }
<ide>
<del> // Before matching the models, we will initialize the relationship
<del> // to either null for single-value relationships or an array for
<del> // the multi-value relationships as their baseline value.
<ide> $query->initialize($results, $relationship);
<ide>
<del> $query->match($relationship, $results, $query->get());
<add> // If we're eager loading a many-to-many relationship we will disable
<add> // the primary key indexing on the hydration since there could be
<add> // roles shared across users and we don't want to overwrite.
<add> if ( ! $query instanceof Has_Many_And_Belongs_To)
<add> {
<add> $query->match($relationship, $results, $query->get());
<add> }
<add> else
<add> {
<add> $query->match($relationship, $results, $query->get(array('*'), false));
<add> }
<ide> }
<ide>
<ide> /** | 1 |
Mixed | Javascript | deprecate repl.inputstream and repl.outputstream | e11b5d3d7d76738e1e2f3baaa9aef0d6bfe298a2 | <ide><path>doc/api/deprecations.md
<ide> Type: Documentation-only
<ide>
<ide> Use [`request.destroy()`][] instead of [`request.abort()`][].
<ide>
<add><a id="DEP0XXX"></a>
<add>### DEP0XXX: `repl.inputStream` and `repl.outputStream`
<add><!-- YAML
<add>changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/33294
<add> description: Documentation-only (supports [`--pending-deprecation`][]).
<add>-->
<add>
<add>Type: Documentation-only (supports [`--pending-deprecation`][])
<add>
<add>The `repl` module exported the input and output stream twice. Use `.input`
<add>instead of `.inputStream` and `.output` instead of `.outputStream`.
<add>
<ide> [`--pending-deprecation`]: cli.html#cli_pending_deprecation
<ide> [`--throw-deprecation`]: cli.html#cli_throw_deprecation
<ide> [`Buffer.allocUnsafeSlow(size)`]: buffer.html#buffer_class_method_buffer_allocunsafeslow_size
<ide><path>lib/repl.js
<ide> const {
<ide> overrideStackTrace,
<ide> } = require('internal/errors');
<ide> const { sendInspectorCommand } = require('internal/util/inspector');
<del>const experimentalREPLAwait = require('internal/options').getOptionValue(
<add>const { getOptionValue } = require('internal/options');
<add>const experimentalREPLAwait = getOptionValue(
<ide> '--experimental-repl-await'
<ide> );
<add>const pendingDeprecation = getOptionValue('--pending-deprecation');
<ide> const {
<ide> REPL_MODE_SLOPPY,
<ide> REPL_MODE_STRICT,
<ide> function REPLServer(prompt,
<ide> const preview = options.terminal &&
<ide> (options.preview !== undefined ? !!options.preview : !eval_);
<ide>
<del> this.inputStream = options.input;
<del> this.outputStream = options.output;
<add> ObjectDefineProperty(this, 'inputStream', {
<add> get: pendingDeprecation ?
<add> deprecate(() => this.input,
<add> 'repl.inputStream and repl.outputStream is deprecated. ' +
<add> 'Use repl.input and repl.output instead',
<add> 'DEP0XXX') :
<add> () => this.input,
<add> set: pendingDeprecation ?
<add> deprecate((val) => this.input = val,
<add> 'repl.inputStream and repl.outputStream is deprecated. ' +
<add> 'Use repl.input and repl.output instead',
<add> 'DEP0XXX') :
<add> (val) => this.input = val,
<add> enumerable: false,
<add> configurable: true
<add> });
<add> ObjectDefineProperty(this, 'outputStream', {
<add> get: pendingDeprecation ?
<add> deprecate(() => this.output,
<add> 'repl.inputStream and repl.outputStream is deprecated. ' +
<add> 'Use repl.input and repl.output instead',
<add> 'DEP0XXX') :
<add> () => this.output,
<add> set: pendingDeprecation ?
<add> deprecate((val) => this.output = val,
<add> 'repl.inputStream and repl.outputStream is deprecated. ' +
<add> 'Use repl.input and repl.output instead',
<add> 'DEP0XXX') :
<add> (val) => this.output = val,
<add> enumerable: false,
<add> configurable: true
<add> });
<add>
<ide> this.useColors = !!options.useColors;
<ide> this._domain = options.domain || domain.create();
<ide> this.useGlobal = !!useGlobal;
<ide> function REPLServer(prompt,
<ide> }
<ide> // Normalize line endings.
<ide> errStack += errStack.endsWith('\n') ? '' : '\n';
<del> self.outputStream.write(errStack);
<add> self.output.write(errStack);
<ide> self.clearBufferedCommand();
<ide> self.lines.level = [];
<ide> self.displayPrompt();
<ide> }
<ide> });
<ide>
<del> self.resetContext();
<del> self.lines.level = [];
<del>
<ide> self.clearBufferedCommand();
<ide> ObjectDefineProperty(this, 'bufferedCommand', {
<ide> get: deprecate(() => self[kBufferedCommandSymbol],
<ide> function REPLServer(prompt,
<ide> }
<ide>
<ide> Interface.call(this, {
<del> input: self.inputStream,
<del> output: self.outputStream,
<add> input: options.input,
<add> output: options.output,
<ide> completer: self.completer,
<ide> terminal: options.terminal,
<ide> historySize: options.historySize,
<ide> prompt
<ide> });
<ide>
<add> self.resetContext();
<add>
<ide> this.commands = ObjectCreate(null);
<ide> defineDefaultCommands(this);
<ide>
<ide> function REPLServer(prompt,
<ide> return;
<ide> }
<ide> if (!self[kBufferedCommandSymbol]) {
<del> self.outputStream.write('Invalid REPL keyword\n');
<add> self.output.write('Invalid REPL keyword\n');
<ide> finish(null);
<ide> return;
<ide> }
<ide> function REPLServer(prompt,
<ide> _memory.call(self, cmd);
<ide>
<ide> if (e && !self[kBufferedCommandSymbol] && cmd.trim().startsWith('npm ')) {
<del> self.outputStream.write('npm should be run outside of the ' +
<add> self.output.write('npm should be run outside of the ' +
<ide> 'node repl, in your normal shell.\n' +
<ide> '(Press Control-D to exit.)\n');
<ide> self.displayPrompt();
<ide> function REPLServer(prompt,
<ide> if (!self.underscoreAssigned) {
<ide> self.last = ret;
<ide> }
<del> self.outputStream.write(self.writer(ret) + '\n');
<add> self.output.write(self.writer(ret) + '\n');
<ide> }
<ide>
<ide> // Display prompt again
<ide> function REPLServer(prompt,
<ide>
<ide> self.on('SIGCONT', function onSigCont() {
<ide> if (self.editorMode) {
<del> self.outputStream.write(`${self._initialPrompt}.editor\n`);
<del> self.outputStream.write(
<add> self.output.write(`${self._initialPrompt}.editor\n`);
<add> self.output.write(
<ide> '// Entering editor mode (^D to finish, ^C to cancel)\n');
<del> self.outputStream.write(`${self[kBufferedCommandSymbol]}\n`);
<add> self.output.write(`${self[kBufferedCommandSymbol]}\n`);
<ide> self.prompt(true);
<ide> } else {
<ide> self.displayPrompt(true);
<ide> REPLServer.prototype.createContext = function() {
<ide> }
<ide> }
<ide> context.global = context;
<del> const _console = new Console(this.outputStream);
<add> const _console = new Console(this.output);
<ide> ObjectDefineProperty(context, 'console', {
<ide> configurable: true,
<ide> writable: true,
<ide> REPLServer.prototype.resetContext = function() {
<ide> this.last = value;
<ide> if (!this.underscoreAssigned) {
<ide> this.underscoreAssigned = true;
<del> this.outputStream.write('Expression assignment to _ now disabled.\n');
<add> this.output.write('Expression assignment to _ now disabled.\n');
<ide> }
<ide> }
<ide> });
<ide> REPLServer.prototype.resetContext = function() {
<ide> this.lastError = value;
<ide> if (!this.underscoreErrAssigned) {
<ide> this.underscoreErrAssigned = true;
<del> this.outputStream.write(
<add> this.output.write(
<ide> 'Expression assignment to _error now disabled.\n');
<ide> }
<ide> }
<ide> function defineDefaultCommands(repl) {
<ide> action: function() {
<ide> this.clearBufferedCommand();
<ide> if (!this.useGlobal) {
<del> this.outputStream.write('Clearing context...\n');
<add> this.output.write('Clearing context...\n');
<ide> this.resetContext();
<ide> }
<ide> this.displayPrompt();
<ide> function defineDefaultCommands(repl) {
<ide> const cmd = this.commands[name];
<ide> const spaces = ' '.repeat(longestNameLength - name.length + 3);
<ide> const line = `.${name}${cmd.help ? spaces + cmd.help : ''}\n`;
<del> this.outputStream.write(line);
<add> this.output.write(line);
<ide> }
<del> this.outputStream.write('\nPress ^C to abort current expression, ' +
<add> this.output.write('\nPress ^C to abort current expression, ' +
<ide> '^D to exit the repl\n');
<ide> this.displayPrompt();
<ide> }
<ide> function defineDefaultCommands(repl) {
<ide> action: function(file) {
<ide> try {
<ide> fs.writeFileSync(file, this.lines.join('\n'));
<del> this.outputStream.write(`Session saved to: ${file}\n`);
<add> this.output.write(`Session saved to: ${file}\n`);
<ide> } catch {
<del> this.outputStream.write(`Failed to save: ${file}\n`);
<add> this.output.write(`Failed to save: ${file}\n`);
<ide> }
<ide> this.displayPrompt();
<ide> }
<ide> function defineDefaultCommands(repl) {
<ide> _turnOffEditorMode(this);
<ide> this.write('\n');
<ide> } else {
<del> this.outputStream.write(
<add> this.output.write(
<ide> `Failed to load: ${file} is not a valid file\n`
<ide> );
<ide> }
<ide> } catch {
<del> this.outputStream.write(`Failed to load: ${file}\n`);
<add> this.output.write(`Failed to load: ${file}\n`);
<ide> }
<ide> this.displayPrompt();
<ide> }
<ide> function defineDefaultCommands(repl) {
<ide> help: 'Enter editor mode',
<ide> action() {
<ide> _turnOnEditorMode(this);
<del> this.outputStream.write(
<add> this.output.write(
<ide> '// Entering editor mode (^D to finish, ^C to cancel)\n');
<ide> }
<ide> });
<ide><path>test/parallel/test-repl-history-navigation.js
<ide> common.skipIfDumbTerminal();
<ide> const tmpdir = require('../common/tmpdir');
<ide> tmpdir.refresh();
<ide>
<add>process.throwDeprecation = true;
<add>
<ide> const defaultHistoryPath = path.join(tmpdir.path, '.node_repl_history');
<ide>
<ide> // Create an input stream specialized for testing an array of actions
<ide><path>test/parallel/test-repl-options.js
<ide> // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<ide> // USE OR OTHER DEALINGS IN THE SOFTWARE.
<ide>
<add>// Flags: --pending-deprecation
<add>
<ide> 'use strict';
<ide> const common = require('../common');
<ide> const ArrayStream = require('../common/arraystream');
<ide> assert.strictEqual(repl.repl, undefined);
<ide>
<ide> common.expectWarning({
<ide> DeprecationWarning: {
<del> DEP0124: 'REPLServer.rli is deprecated'
<add> DEP0XXX: 'repl.inputStream and repl.outputStream is deprecated. ' +
<add> 'Use repl.input and repl.output instead',
<add> DEP0124: 'REPLServer.rli is deprecated',
<ide> }
<ide> });
<ide> | 4 |
Java | Java | suppress recent deprecation warnings in tests | 8af0151f1b207d70ca804610fdedc24733d7d89a | <ide><path>spring-core/src/test/java/org/springframework/util/Log4jConfigurerTests.java
<ide> * @author Juergen Hoeller
<ide> * @author Sam Brannen
<ide> */
<add>@SuppressWarnings("deprecation")
<ide> public class Log4jConfigurerTests {
<ide>
<ide> @Test
<ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/support/NativeJdbcExtractorTests.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2015 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> import org.junit.Test;
<ide>
<del>import org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor;
<ide> import org.springframework.jdbc.support.nativejdbc.SimpleNativeJdbcExtractor;
<ide>
<ide> import static org.junit.Assert.*;
<ide> public class NativeJdbcExtractorTests {
<ide>
<ide> @Test
<del> public void testSimpleNativeJdbcExtractor() throws SQLException {
<add> public void simpleNativeJdbcExtractor() throws SQLException {
<ide> SimpleNativeJdbcExtractor extractor = new SimpleNativeJdbcExtractor();
<ide>
<ide> Connection con = mock(Connection.class);
<ide> public void testSimpleNativeJdbcExtractor() throws SQLException {
<ide> assertEquals(nativeRs, rs);
<ide> }
<ide>
<del> public void testCommonsDbcpNativeJdbcExtractor() throws SQLException {
<del> CommonsDbcpNativeJdbcExtractor extractor = new CommonsDbcpNativeJdbcExtractor();
<add> @SuppressWarnings("deprecation")
<add> public void commonsDbcpNativeJdbcExtractor() throws SQLException {
<add> org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor extractor = new org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor();
<ide> assertFalse(extractor.isNativeConnectionNecessaryForNativeStatements());
<ide>
<ide> Connection con = mock(Connection.class);
<ide><path>spring-web/src/test/java/org/springframework/web/util/Log4jWebConfigurerTests.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2015 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> package org.springframework.web.util;
<ide>
<ide> import java.net.URL;
<add>
<ide> import javax.servlet.ServletContextEvent;
<ide>
<ide> import org.apache.commons.logging.Log;
<ide> import org.apache.commons.logging.LogFactory;
<del>import org.junit.Ignore;
<add>
<ide> import org.junit.Test;
<ide>
<ide> import org.springframework.core.io.FileSystemResourceLoader;
<ide> import org.springframework.mock.web.test.MockServletContext;
<ide>
<add>import static org.hamcrest.CoreMatchers.*;
<ide> import static org.junit.Assert.*;
<add>import static org.junit.Assume.*;
<ide>
<ide> /**
<ide> * @author Juergen Hoeller
<ide> * @author Sam Brannen
<ide> * @since 21.02.2005
<ide> */
<add>@SuppressWarnings("deprecation")
<ide> public class Log4jWebConfigurerTests {
<ide>
<ide> private static final String TESTLOG4J_PROPERTIES = "testlog4j.properties";
<ide> public void initLoggingWithUrlAndRefreshInterval() {
<ide> initLogging(url.toString(), true);
<ide> }
<ide>
<del> @Ignore("Only works on MS Windows")
<ide> @Test
<ide> public void initLoggingWithAbsoluteFilePathAndRefreshInterval() {
<add> // Only works on MS Windows
<add> assumeThat(System.getProperty("os.name"), containsString("Windows"));
<add>
<ide> URL url = Log4jWebConfigurerTests.class.getResource(TESTLOG4J_PROPERTIES);
<ide> initLogging(url.getFile(), true);
<ide> } | 3 |
Javascript | Javascript | fix a case where attrmorph was being extended | b9020834ad51cd414678c8b3101c92907b539f2e | <ide><path>packages/ember-htmlbars/lib/morphs/attr-morph.js
<ide> export var styleWarning = '' +
<ide>
<ide> function EmberAttrMorph(element, attrName, domHelper, namespace) {
<ide> HTMLBarsAttrMorph.call(this, element, attrName, domHelper, namespace);
<add>
<add> this.streamUnsubscribers = null;
<ide> }
<ide>
<ide> var proto = EmberAttrMorph.prototype = o_create(HTMLBarsAttrMorph.prototype); | 1 |
Javascript | Javascript | increase inspect coverage | 4abe50c1d1a5b3ab943dd078de370bacd97ec9ef | <ide><path>test/parallel/test-util-inspect.js
<ide> assert(!/Object/.test(
<ide> 'ArrayBuffer { (detached), byteLength: 0 }');
<ide> }
<ide>
<add>// Truncate output for ArrayBuffers using plural or singular bytes
<add>{
<add> const ab = new ArrayBuffer(3);
<add> assert.strictEqual(util.inspect(ab, { showHidden: true, maxArrayLength: 2 }),
<add> 'ArrayBuffer { [Uint8Contents]' +
<add> ': <00 00 ... 1 more byte>, byteLength: 3 }');
<add> assert.strictEqual(util.inspect(ab, { showHidden: true, maxArrayLength: 1 }),
<add> 'ArrayBuffer { [Uint8Contents]' +
<add> ': <00 ... 2 more bytes>, byteLength: 3 }');
<add>}
<add>
<ide> // Now do the same checks but from a different context.
<ide> {
<ide> const showHidden = false;
<ide> assert.strictEqual(
<ide> assert.strictEqual(inspect(undetectable), '{}');
<ide> }
<ide>
<add>// Truncate output for Primitives with 1 character left
<add>{
<add> assert.strictEqual(util.inspect('bl', { maxStringLength: 1 }),
<add> "'b'... 1 more character");
<add>}
<add>
<ide> {
<ide> const x = 'a'.repeat(1e6);
<ide> assert(util.inspect(x).endsWith('... 990000 more characters')); | 1 |
Python | Python | fix syntax error and formatting in test (see ) | d70a64d78bb73cf6cfa381b5ca67cb6eb91d55b1 | <ide><path>spacy/tests/regression/test_issue910.py
<add># coding: utf8
<ide> from __future__ import unicode_literals
<add>
<ide> import json
<ide> import random
<ide> import contextlib
<ide> import shutil
<ide> import pytest
<ide> import tempfile
<ide> from pathlib import Path
<del>
<add>from thinc.neural.optimizers import Adam
<ide>
<ide> from ...gold import GoldParse
<ide> from ...pipeline import EntityRecognizer | 1 |
Text | Text | add section on reading files | 66e1fa154ca2ad90869de8967c3ff7fd6c077a28 | <ide><path>docs/basic-features/data-fetching.md
<ide> export const getStaticProps: GetStaticProps = async context => {
<ide> }
<ide> ```
<ide>
<add>### Reading files: Use `process.cwd()`
<add>
<add>Files can be read directly from the filesystem in `getStaticProps`.
<add>
<add>In order to do so you have to get the full path to a file.
<add>
<add>Since Next.js compiles your code into a separate directory you can't use `__dirname` as the path it will return will be different from the pages directory.
<add>
<add>Instead you can use `process.cwd()` which gives you the directory where Next.js is being executed.
<add>
<add>```jsx
<add>import fs from 'fs'
<add>import path from 'path'
<add>
<add>// posts will be populated at build time by getStaticProps()
<add>function Blog({ posts }) {
<add> return (
<add> <ul>
<add> {posts.map(post => (
<add> <li>
<add> <h3>{post.filename}</h3>
<add> <p>{post.content}</p>
<add> </li>
<add> ))}
<add> </ul>
<add> )
<add>}
<add>
<add>// This function gets called at build time on server-side.
<add>// It won't be called on client-side, so you can even do
<add>// direct database queries. See the "Technical details" section.
<add>export async function getStaticProps() {
<add> const postsDirectory = path.join(process.cwd(), 'posts')
<add> const filenames = fs.readdirSync(postsDirectory)
<add>
<add> const posts = filenames.map(filename => {
<add> const filePath = path.join(postsDirectory, filename)
<add> const fileContents = fs.readFileSync(fullPath, 'utf8')
<add>
<add> // Generally you would parse/transform the contents
<add> // For example you can transform markdown to HTML here
<add>
<add> return {
<add> filename,
<add> content: fileContents,
<add> }
<add> })
<add> // By returning { props: posts }, the Blog component
<add> // will receive `posts` as a prop at build time
<add> return {
<add> props: {
<add> posts,
<add> },
<add> }
<add>}
<add>
<add>export default Blog
<add>```
<add>
<ide> ### Technical details
<ide>
<ide> #### Only runs at build time | 1 |
Javascript | Javascript | add coverage for err_tls_invalid_protocol_version | cc3f2b386c6ee34f5574c69c29647165a9bc3aef | <ide><path>test/parallel/test-tls-basic-validations.js
<ide> assert.throws(
<ide> }
<ide> );
<ide> }
<add>
<add>assert.throws(() => { tls.createSecureContext({ minVersion: 'fhqwhgads' }); },
<add> {
<add> code: 'ERR_TLS_INVALID_PROTOCOL_VERSION',
<add> name: 'TypeError'
<add> });
<add>
<add>assert.throws(() => { tls.createSecureContext({ maxVersion: 'fhqwhgads' }); },
<add> {
<add> code: 'ERR_TLS_INVALID_PROTOCOL_VERSION',
<add> name: 'TypeError'
<add> }); | 1 |
Javascript | Javascript | add missing return in checkouthead | 196fb35b6553fd978839916994fc3b857ff3279c | <ide><path>src/git-repository-async.js
<ide> module.exports = class GitRepositoryAsync {
<ide> var checkoutOptions = new Git.CheckoutOptions()
<ide> checkoutOptions.paths = [this._gitUtilsRepo.relativize(_path)]
<ide> checkoutOptions.checkoutStrategy = Git.Checkout.STRATEGY.FORCE | Git.Checkout.STRATEGY.DISABLE_PATHSPEC_MATCH
<del> Git.Checkout.head(repo, checkoutOptions)
<add> return Git.Checkout.head(repo, checkoutOptions)
<ide> })
<ide> }
<ide> | 1 |
Ruby | Ruby | remove redundant accessors | 436ec799a46533190fd10030709bcce741f612c5 | <ide><path>actioncable/test/stubs/test_adapter.rb
<ide> # frozen_string_literal: true
<ide>
<ide> class SuccessAdapter < ActionCable::SubscriptionAdapter::Base
<del> class << self; attr_accessor :subscribe_called, :unsubscribe_called end
<del>
<ide> def broadcast(channel, payload)
<ide> end
<ide> | 1 |
Ruby | Ruby | implement #== for column | 79437642d537f24a36d9e649713941eebfff35c2 | <ide><path>activerecord/lib/active_record/connection_adapters/column.rb
<ide> def with_type(type)
<ide> clone.instance_variable_set('@cast_type', type)
<ide> end
<ide> end
<add>
<add> def ==(other)
<add> other.name == name &&
<add> other.default == default &&
<add> other.cast_type == cast_type &&
<add> other.sql_type == sql_type &&
<add> other.null == null
<add> end
<ide> end
<ide> end
<ide> # :startdoc: | 1 |
Text | Text | fix logo in readme.md | 8d07c2d1aeb3326f1f62854e6adfd26f0d8e0342 | <ide><path>README.md
<ide> It benefits directly from the experience accumulated over several years
<ide> of large-scale operation and support of hundreds of thousands of
<ide> applications and databases.
<ide>
<del>
<add>
<ide>
<ide> ## Better than VMs
<ide> | 1 |
Go | Go | fix the comments | 9cc73c62e6779bf2c8eefc4192c017a2c73daf40 | <ide><path>pkg/mflag/flag.go
<ide> flag.Var(&flagVal, []string{"name"}, "help message for flagname")
<ide> For such flags, the default value is just the initial value of the variable.
<ide>
<del> You can also add "deprecated" flags, they are still usable, bur are not shown
<add> You can also add "deprecated" flags, they are still usable, but are not shown
<ide> in the usage and will display a warning when you try to use them:
<del> var ip = flag.Int([]string{"f", "#flagname", "-flagname"}, 1234, "help message for flagname")
<del> this will display: `Warning: '-flagname' is deprecated, it will be replaced by '--flagname' soon. See usage.` and
<add> var ip = flag.Int([]string{"#f", "#flagname", "-flagname2"}, 1234, "help message for flagname")
<add> this will display: `Warning: '--flagname' is deprecated, it will be replaced by '--flagname2' soon. See usage.` and
<ide> var ip = flag.Int([]string{"f", "#flagname"}, 1234, "help message for flagname")
<del> will display: `Warning: '-t' is deprecated, it will be removed soon. See usage.`
<add> will display: `Warning: '-f' is deprecated, it will be removed soon. See usage.`
<ide>
<ide> You can also group one letter flags, bif you declare
<ide> var v = flag.Bool([]string{"v", "-verbose"}, false, "help message for verbose") | 1 |
Javascript | Javascript | resolve eslint error | 87963c4d0136215a3e50e1c8d35586d5b9c2dad5 | <ide><path>packages/react-codemod/transforms/class.js
<ide> module.exports = (file, api, options) => {
<ide> );
<ide> }
<ide> return !invalidProperties.length;
<del> }
<add> };
<ide>
<ide> const hasMixins = classPath => {
<ide> if (ReactUtils.hasMixins(classPath)) { | 1 |
Text | Text | add jump to what's new in 2.0 link at the top | 5bebaf159448e971527df60282007fe80dc6270b | <ide><path>README.md
<ide> Hackathon Starter 2.0 [
<add>
<ide> A boilerplate for **Node.js** web applications.
<ide>
<ide> If you have attended any hackathons in the past, then you know how much time it takes to | 1 |
Javascript | Javascript | remove separator code | 7758d8ed25c9ebc7af80016c75539e60bdf588fa | <ide><path>packages/ember-metal/lib/watching.js
<ide> function isProto(pvalue) {
<ide> // A ChainNode watches a single key on an object. If you provide a starting
<ide> // value for the key then the node won't actually watch it. For a root node
<ide> // pass null for parent and key and object for value.
<del>var ChainNode = function(parent, key, value, separator) {
<add>var ChainNode = function(parent, key, value) {
<ide> var obj;
<ide> this._parent = parent;
<ide> this._key = key;
<ide> var ChainNode = function(parent, key, value, separator) {
<ide> this._watching = value===undefined;
<ide>
<ide> this._value = value;
<del> this._separator = separator || '.';
<ide> this._paths = {};
<ide> if (this._watching) {
<ide> this._object = parent.value();
<ide> ChainNodePrototype.destroy = function() {
<ide>
<ide> // copies a top level object only
<ide> ChainNodePrototype.copy = function(obj) {
<del> var ret = new ChainNode(null, null, obj, this._separator),
<add> var ret = new ChainNode(null, null, obj),
<ide> paths = this._paths, path;
<ide> for (path in paths) {
<ide> if (paths[path] <= 0) { continue; } // this check will also catch non-number vals.
<ide> ChainNodePrototype.copy = function(obj) {
<ide> // called on the root node of a chain to setup watchers on the specified
<ide> // path.
<ide> ChainNodePrototype.add = function(path) {
<del> var obj, tuple, key, src, separator, paths;
<add> var obj, tuple, key, src, paths;
<ide>
<ide> paths = this._paths;
<ide> paths[path] = (paths[path] || 0) + 1;
<ide> ChainNodePrototype.add = function(path) {
<ide> } else {
<ide> src = tuple[0];
<ide> key = path.slice(0, 0-(tuple[1].length+1));
<del> separator = path.slice(key.length, key.length+1);
<ide> path = tuple[1];
<ide> }
<ide>
<ide> tuple.length = 0;
<del> this.chain(key, path, src, separator);
<add> this.chain(key, path, src);
<ide> };
<ide>
<ide> // called on the root node of a chain to teardown watcher on the specified
<ide> ChainNodePrototype.remove = function(path) {
<ide>
<ide> ChainNodePrototype.count = 0;
<ide>
<del>ChainNodePrototype.chain = function(key, path, src, separator) {
<add>ChainNodePrototype.chain = function(key, path, src) {
<ide> var chains = this._chains, node;
<ide> if (!chains) { chains = this._chains = {}; }
<ide>
<ide> node = chains[key];
<del> if (!node) { node = chains[key] = new ChainNode(this, key, src, separator); }
<add> if (!node) { node = chains[key] = new ChainNode(this, key, src); }
<ide> node.count++; // count chains...
<ide>
<ide> // chain rest of path if there is one
<ide> ChainNodePrototype.willChange = function() {
<ide> };
<ide>
<ide> ChainNodePrototype.chainWillChange = function(chain, path, depth) {
<del> if (this._key) { path = this._key + this._separator + path; }
<add> if (this._key) { path = this._key + '.' + path; }
<ide>
<ide> if (this._parent) {
<ide> this._parent.chainWillChange(this, path, depth+1);
<ide> ChainNodePrototype.chainWillChange = function(chain, path, depth) {
<ide> };
<ide>
<ide> ChainNodePrototype.chainDidChange = function(chain, path, depth) {
<del> if (this._key) { path = this._key + this._separator + path; }
<add> if (this._key) { path = this._key + '.' + path; }
<ide> if (this._parent) {
<ide> this._parent.chainDidChange(this, path, depth+1);
<ide> } else { | 1 |
Javascript | Javascript | add test for getting parse error from http client | ee9af669905aeddd6da32712e711aeee9f9d36b3 | <ide><path>test/simple/test-http-client-parse-error.js
<add>var common = require("../common");
<add>var assert = require('assert');
<add>
<add>var http = require('http');
<add>var net = require('net');
<add>
<add>// Create a TCP server
<add>var srv = net.createServer(function(c) {
<add> c.write('bad http - should trigger parse error\r\n');
<add>
<add> console.log("connection");
<add>
<add> c.addListener('end', function() { c.end(); });
<add>});
<add>srv.listen(common.PORT, '127.0.0.1');
<add>
<add>var hc = http.createClient(common.PORT, '127.0.0.1');
<add>hc.request('GET', '/').end();
<add>
<add>var parseError = false;
<add>
<add>hc.on('error', function (e) {
<add> console.log("got error from client");
<add> srv.close();
<add> assert.ok(e.message.indexOf("Parse Error") >= 0);
<add> parseError = true;
<add>});
<add>
<add>
<add>process.addListener('exit', function() {
<add> assert.ok(parseError);
<add>});
<add>
<add> | 1 |
Python | Python | allow arbitrary output shapes for custom losses | 6b122ba25f79ab0a43ff8d78f65cfba36a7bcee5 | <ide><path>keras/engine/training.py
<ide> from .. import callbacks as cbks
<ide>
<ide>
<del>def standardize_input_data(data, names, shapes=None, check_batch_dim=True,
<add>def standardize_input_data(data, names, shapes=None,
<add> check_batch_dim=True,
<ide> exception_prefix=''):
<ide> '''Users may pass data as a list of arrays, dictionary of arrays,
<ide> or as a single array. We normalize this to an ordered list of
<ide> def standardize_input_data(data, names, shapes=None, check_batch_dim=True,
<ide> # check shapes compatibility
<ide> if shapes:
<ide> for i in range(len(names)):
<add> if shapes[i] is None:
<add> continue
<ide> array = arrays[i]
<ide> if len(array.shape) != len(shapes[i]):
<ide> raise Exception('Error when checking ' + exception_prefix +
<ide> def _standardize_user_data(self, x, y,
<ide> raise Exception('You must compile a model before training/testing.'
<ide> ' Use `model.compile(optimizer, loss)`.')
<ide>
<del> # if using sparse cce replace last dim of output shapes with 1
<del> output_shapes = self.internal_output_shapes
<del> if self.loss == "sparse_categorical_crossentropy":
<del> output_shapes = [s[:-1] + (1,) for s in output_shapes]
<add> output_shapes = []
<add> for output_shape, loss_fn in zip(self.internal_output_shapes, self.loss_functions):
<add> if loss_fn.__name__ == 'sparse_categorical_crossentropy':
<add> output_shapes.append(output_shape[:-1] + (1,))
<add> elif getattr(objectives, loss_fn.__name__, None) is None:
<add> output_shapes.append(None)
<add> else:
<add> output_shapes.append(output_shape)
<ide> x = standardize_input_data(x, self.input_names,
<ide> self.internal_input_shapes,
<ide> check_batch_dim=False,
<ide> def generate_arrays_from_file(path):
<ide> outs = self.train_on_batch(x, y,
<ide> sample_weight=sample_weight,
<ide> class_weight=class_weight)
<del> except Exception as e:
<add> except:
<ide> _stop.set()
<ide> raise
<ide>
<ide> def evaluate_generator(self, generator, val_samples, max_q_size=10):
<ide> 'or (x, y). Found: ' + str(generator_output))
<ide> try:
<ide> outs = self.test_on_batch(x, y, sample_weight=sample_weight)
<del> except Exception as e:
<add> except:
<ide> _stop.set()
<ide> raise
<ide>
<ide> def predict_generator(self, generator, val_samples, max_q_size=10):
<ide>
<ide> try:
<ide> outs = self.predict_on_batch(x)
<del> except Exception as e:
<add> except:
<ide> _stop.set()
<ide> raise
<ide> | 1 |
Ruby | Ruby | add missing require and fixtures | 1d38c82b7ad98d64f5ee45c0e08d5826e14d98c0 | <ide><path>activerecord/test/cases/adapters/postgresql/timestamp_test.rb
<ide> require 'cases/helper'
<ide> require 'models/developer'
<add>require 'models/topic'
<ide>
<ide> class TimestampTest < ActiveRecord::TestCase
<add> fixtures :topics
<add>
<ide> def test_group_by_date
<ide> keys = Topic.group("date_trunc('month', created_at)").count.keys
<ide> assert_operator keys.length, :>, 0 | 1 |
Javascript | Javascript | check alternate in reacttreetraversal | 1e722e4a97dc03632d0f88ae47b2581ca9619736 | <ide><path>src/renderers/shared/shared/ReactTreeTraversal.js
<ide> function getLowestCommonAncestor(instA, instB) {
<ide> // Walk in lockstep until we find a match.
<ide> var depth = depthA;
<ide> while (depth--) {
<del> if (instA === instB) {
<add> if (instA === instB || instA === instB.alternate) {
<ide> return instA;
<ide> }
<ide> instA = getParent(instA);
<ide> function getLowestCommonAncestor(instA, instB) {
<ide> */
<ide> function isAncestor(instA, instB) {
<ide> while (instB) {
<del> if (instB === instA) {
<add> if (instA === instB || instA === instB.alternate) {
<ide> return true;
<ide> }
<ide> instB = getParent(instB); | 1 |
Javascript | Javascript | use strict equalities in web/compatibility.js | 097bf41285f69b6558f3104b2c0f73b393e6b344 | <ide><path>web/compatibility.js
<ide> if (typeof PDFJS === 'undefined') {
<ide> 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
<ide> window.atob = function (input) {
<ide> input = input.replace(/=+$/, '');
<del> if (input.length % 4 == 1) {
<add> if (input.length % 4 === 1) {
<ide> throw new Error('bad atob input');
<ide> }
<ide> for (
<ide> if (typeof PDFJS === 'undefined') {
<ide> var dataset = {};
<ide> for (var j = 0, jj = this.attributes.length; j < jj; j++) {
<ide> var attribute = this.attributes[j];
<del> if (attribute.name.substring(0, 5) != 'data-') {
<add> if (attribute.name.substring(0, 5) !== 'data-') {
<ide> continue;
<ide> }
<ide> var key = attribute.name.substring(5).replace(/\-([a-z])/g,
<ide> if (typeof PDFJS === 'undefined') {
<ide> function isDisabled(node) {
<ide> return node.disabled || (node.parentNode && isDisabled(node.parentNode));
<ide> }
<del> if (navigator.userAgent.indexOf('Opera') != -1) {
<add> if (navigator.userAgent.indexOf('Opera') !== -1) {
<ide> // use browser detection since we cannot feature-check this bug
<ide> document.addEventListener('click', ignoreIfTargetDisabled, true);
<ide> } | 1 |
Text | Text | remove spaces around slashes | 85fe13402659a174773bfecebac6e8bb5164f572 | <ide><path>doc/api/assert.md
<ide> validating against a string property. See below for examples.
<ide> If specified, `message` will be the message provided by the `AssertionError` if
<ide> the block fails to throw.
<ide>
<del>Custom validation object / error instance:
<add>Custom validation object/error instance:
<ide>
<ide> ```js
<ide> const err = new TypeError('Wrong value');
<ide><path>doc/api/crypto.md
<ide> mode must adhere to certain restrictions when using the cipher API:
<ide> bytes (`7 ≤ N ≤ 13`).
<ide> - The length of the plaintext is limited to `2 ** (8 * (15 - N))` bytes.
<ide> - When decrypting, the authentication tag must be set via `setAuthTag()` before
<del> specifying additional authenticated data and / or calling `update()`.
<add> specifying additional authenticated data or calling `update()`.
<ide> Otherwise, decryption will fail and `final()` will throw an error in
<ide> compliance with section 2.6 of [RFC 3610][].
<ide> - Using stream methods such as `write(data)`, `end(data)` or `pipe()` in CCM
<ide> mode must adhere to certain restrictions when using the cipher API:
<ide> option. This is not necessary if no AAD is used.
<ide> - As CCM processes the whole message at once, `update()` can only be called
<ide> once.
<del>- Even though calling `update()` is sufficient to encrypt / decrypt the message,
<del> applications *must* call `final()` to compute and / or verify the
<add>- Even though calling `update()` is sufficient to encrypt/decrypt the message,
<add> applications *must* call `final()` to compute or verify the
<ide> authentication tag.
<ide>
<ide> ```js
<ide><path>doc/api/dgram.md
<del># UDP / Datagram Sockets
<add># UDP/Datagram Sockets
<ide>
<ide> <!--introduced_in=v0.10.0-->
<ide>
<ide><path>doc/api/dns.md
<ide> will be present on the object:
<ide>
<ide> | Type | Properties |
<ide> |------|------------|
<del>| `'A'` | `address` / `ttl` |
<del>| `'AAAA'` | `address` / `ttl` |
<add>| `'A'` | `address`/`ttl` |
<add>| `'AAAA'` | `address`/`ttl` |
<ide> | `'CNAME'` | `value` |
<ide> | `'MX'` | Refer to [`dns.resolveMx()`][] |
<ide> | `'NAPTR'` | Refer to [`dns.resolveNaptr()`][] |
<ide><path>doc/api/errors.md
<ide> called.
<ide>
<ide> All JavaScript errors are handled as exceptions that *immediately* generate
<ide> and throw an error using the standard JavaScript `throw` mechanism. These
<del>are handled using the [`try / catch` construct][try-catch] provided by the
<add>are handled using the [`try…catch` construct][try-catch] provided by the
<ide> JavaScript language.
<ide>
<ide> ```js
<ide> try {
<ide> ```
<ide>
<ide> Any use of the JavaScript `throw` mechanism will raise an exception that
<del>*must* be handled using `try / catch` or the Node.js process will exit
<add>*must* be handled using `try…catch` or the Node.js process will exit
<ide> immediately.
<ide>
<ide> With few exceptions, _Synchronous_ APIs (any blocking method that does not
<ide> Errors that occur within _Asynchronous APIs_ may be reported in multiple ways:
<ide>
<ide> - A handful of typically asynchronous methods in the Node.js API may still
<ide> use the `throw` mechanism to raise exceptions that must be handled using
<del> `try / catch`. There is no comprehensive list of such methods; please
<add> `try…catch`. There is no comprehensive list of such methods; please
<ide> refer to the documentation of each method to determine the appropriate
<ide> error handling mechanism required.
<ide>
<ide> setImmediate(() => {
<ide> });
<ide> ```
<ide>
<del>Errors generated in this way *cannot* be intercepted using `try / catch` as
<add>Errors generated in this way *cannot* be intercepted using `try…catch` as
<ide> they are thrown *after* the calling code has already exited.
<ide>
<ide> Developers must refer to the documentation for each method to determine
<ide> fs.readFile('/some/file/that/does-not-exist', errorFirstCallback);
<ide> fs.readFile('/some/file/that/does-exist', errorFirstCallback);
<ide> ```
<ide>
<del>The JavaScript `try / catch` mechanism **cannot** be used to intercept errors
<add>The JavaScript `try…catch` mechanism **cannot** be used to intercept errors
<ide> generated by asynchronous APIs. A common mistake for beginners is to try to
<ide> use `throw` inside an error-first callback:
<ide>
<ide> Used when a child process is being forked without specifying an IPC channel.
<ide> ### ERR_CHILD_PROCESS_STDIO_MAXBUFFER
<ide>
<ide> Used when the main process is trying to read data from the child process's
<del>STDERR / STDOUT, and the data's length is longer than the `maxBuffer` option.
<add>STDERR/STDOUT, and the data's length is longer than the `maxBuffer` option.
<ide>
<ide> <a id="ERR_CLOSED_MESSAGE_PORT"></a>
<ide> ### ERR_CLOSED_MESSAGE_PORT
<ide><path>doc/api/intl.md
<ide> To control how ICU is used in Node.js, four `configure` options are available
<ide> during compilation. Additional details on how to compile Node.js are documented
<ide> in [BUILDING.md][].
<ide>
<del>- `--with-intl=none` / `--without-intl`
<add>- `--with-intl=none`/`--without-intl`
<ide> - `--with-intl=system-icu`
<ide> - `--with-intl=small-icu` (default)
<ide> - `--with-intl=full-icu`
<ide><path>doc/api/net.md
<ide> called. Otherwise, an `ERR_SERVER_ALREADY_LISTEN` error will be thrown.
<ide>
<ide> One of the most common errors raised when listening is `EADDRINUSE`.
<ide> This happens when another server is already listening on the requested
<del>`port` / `path` / `handle`. One way to handle this would be to retry
<add>`port`/`path`/`handle`. One way to handle this would be to retry
<ide> after a certain amount of time:
<ide>
<ide> ```js
<ide><path>doc/api/stream.md
<ide> added: v8.0.0
<ide>
<ide> Destroy the stream, and emit the passed `'error'` and a `'close'` event.
<ide> After this call, the writable stream has ended and subsequent calls
<del>to `write()` / `end()` will give an `ERR_STREAM_DESTROYED` error.
<add>to `write()` or `end()` will result in an `ERR_STREAM_DESTROYED` error.
<ide> Implementors should not override this method,
<ide> but instead implement [`writable._destroy()`][writable-_destroy].
<ide> | 8 |
PHP | PHP | add tests for put method of filestore | c7f4c23e17013b9c6f86a8fd1d37a590e2ad29b4 | <ide><path>tests/Cache/CacheFileStoreTest.php
<ide> public function testPutCreatesMissingDirectories()
<ide> $this->assertTrue($result);
<ide> }
<ide>
<del> public function testExpiredItemsReturnNull()
<add> public function testPutWillConsiderZeroAsEternalTime()
<add> {
<add> $files = $this->mockFilesystem();
<add>
<add> $hash = sha1('O--L / key');
<add> $filePath = __DIR__.'/'.substr($hash, 0, 2).'/'.substr($hash, 2, 2).'/'.$hash;
<add> $ten9s = '9999999999'; // The "forever" time value.
<add> $fileContents = $ten9s.serialize('gold');
<add> $exclusiveLock = true;
<add>
<add> $files->expects($this->once())->method('put')->with(
<add> $this->equalTo($filePath),
<add> $this->equalTo($fileContents),
<add> $this->equalTo($exclusiveLock) // Ensure we do lock the file while putting.
<add> )->willReturn(strlen($fileContents));
<add>
<add> (new FileStore($files, __DIR__))->put('O--L / key', 'gold', 0);
<add> }
<add>
<add> public function testPutWillConsiderBigValuesAsEternalTime()
<add> {
<add> $files = $this->mockFilesystem();
<add>
<add> $hash = sha1('O--L / key');
<add> $filePath = __DIR__.'/'.substr($hash, 0, 2).'/'.substr($hash, 2, 2).'/'.$hash;
<add> $ten9s = '9999999999'; // The "forever" time value.
<add> $fileContents = $ten9s.serialize('gold');
<add>
<add> $files->expects($this->once())->method('put')->with(
<add> $this->equalTo($filePath),
<add> $this->equalTo($fileContents),
<add> );
<add>
<add> (new FileStore($files, __DIR__))->put('O--L / key', 'gold', (int) $ten9s + 1);
<add> }
<add>
<add> public function testExpiredItemsReturnNullAndGetDeleted()
<ide> {
<ide> $files = $this->mockFilesystem();
<ide> $contents = '0000000000'; | 1 |
Ruby | Ruby | remove unused code | 1f53f06b08495395d7134bfa70093a2df5c82f6c | <ide><path>activerecord/lib/active_record/type/adapter_specific_registry.rb
<ide> def initialize
<ide>
<ide> def initialize_copy(other)
<ide> @registrations = @registrations.dup
<del> super
<ide> end
<ide>
<ide> def add_modifier(options, klass, **args) | 1 |
Go | Go | create helpers to cancel deferred deactivation | 20b38f427aa05186bd09c8c4201dcc95ed56aa46 | <ide><path>pkg/devicemapper/devmapper.go
<ide> var (
<ide> ErrLoopbackSetCapacity = errors.New("Unable set loopback capacity")
<ide> ErrBusy = errors.New("Device is Busy")
<ide> ErrDeviceIdExists = errors.New("Device Id Exists")
<add> ErrEnxio = errors.New("No such device or address")
<ide>
<ide> dmSawBusy bool
<ide> dmSawExist bool
<add> dmSawEnxio bool // No Such Device or Address
<ide> )
<ide>
<ide> type (
<ide> func RemoveDeviceDeferred(name string) error {
<ide> return nil
<ide> }
<ide>
<add>// Useful helper for cleanup
<add>func CancelDeferredRemove(deviceName string) error {
<add> task, err := TaskCreateNamed(DeviceTargetMsg, deviceName)
<add> if task == nil {
<add> return err
<add> }
<add>
<add> if err := task.SetSector(0); err != nil {
<add> return fmt.Errorf("Can't set sector %s", err)
<add> }
<add>
<add> if err := task.SetMessage(fmt.Sprintf("@cancel_deferred_remove")); err != nil {
<add> return fmt.Errorf("Can't set message %s", err)
<add> }
<add>
<add> dmSawBusy = false
<add> dmSawEnxio = false
<add> if err := task.Run(); err != nil {
<add> // A device might be being deleted already
<add> if dmSawBusy {
<add> return ErrBusy
<add> } else if dmSawEnxio {
<add> return ErrEnxio
<add> }
<add> return fmt.Errorf("Error running CancelDeferredRemove %s", err)
<add>
<add> }
<add> return nil
<add>}
<add>
<ide> func GetBlockDeviceSize(file *os.File) (uint64, error) {
<ide> size, err := ioctlBlkGetSize64(file.Fd())
<ide> if err != nil {
<ide><path>pkg/devicemapper/devmapper_log.go
<ide> func DevmapperLogCallback(level C.int, file *C.char, line C.int, dm_errno_or_cla
<ide> if strings.Contains(msg, "File exists") {
<ide> dmSawExist = true
<ide> }
<add>
<add> if strings.Contains(msg, "No such device or address") {
<add> dmSawEnxio = true
<add> }
<ide> }
<ide>
<ide> if dmLogger != nil { | 2 |
Text | Text | fix typos and formats for changelog | 84054a7d167ebefc807f2c5ec7c8ecf57f369f36 | <ide><path>actionpack/CHANGELOG.md
<ide>
<ide> ## Rails 3.1.3 (unreleased) ##
<ide>
<del>* Fix using `tranlate` helper with a html translation which uses the `:count` option for
<add>* Fix using `translate` helper with a html translation which uses the `:count` option for
<ide> pluralization.
<ide>
<ide> *Jon Leighton*
<ide> ## Rails 3.1.1 (unreleased) ##
<ide>
<ide> * javascript_path and stylesheet_path now refer to /assets if asset pipelining
<del> is on. [Santiago Pastorino]
<add> is on. *Santiago Pastorino*
<add>
<ide> * button_to support form option. Now you're able to pass for example
<del> 'data-type' => 'json'. [ihower]
<add> 'data-type' => 'json'. *ihower*
<add>
<ide> * image_path and image_tag should use /assets if asset pipelining is turned
<del> on. Closes #3126 [Santiago Pastorino and christos]
<add> on. Closes #3126 *Santiago Pastorino and christos*
<add>
<ide> * Avoid use of existing precompiled assets during rake assets:precompile run.
<del> Closes #3119 [Guillermo Iguaran]
<add> Closes #3119 *Guillermo Iguaran*
<add>
<ide> * Copy assets to nondigested filenames too *Santiago Pastorino*
<ide>
<ide> * Give precedence to `config.digest = false` over the existence of
<del> manifest.yml asset digests [christos]
<add> manifest.yml asset digests *christos*
<add>
<ide> * escape options for the stylesheet_link_tag method *Alexey Vakhov*
<ide>
<ide> * Re-launch assets:precompile task using (Rake.)ruby instead of Kernel.exec so
<del> it works on Windows [cablegram]
<del>* env var passed to process shouldn't be modified in process method. [Santiago
<del> Pastorino]
<add> it works on Windows *cablegram*
<add>
<add>* env var passed to process shouldn't be modified in process method. *Santiago
<add> Pastorino*
<add>
<ide> * `rake assets:precompile` loads the application but does not initialize
<ide> it.
<ide> To the app developer, this means configuration add in
<ide> * Fix Hash#to_query edge case with html_safe strings. *brainopia*
<ide>
<ide> * Allow asset tag helper methods to accept :digest => false option in order to completely avoid the digest generation.
<del> Useful for linking assets from static html files or from emails when the user could probably look at an older html email with an older asset. [Santiago Pastorino]
<add> Useful for linking assets from static html files or from emails when the user could probably look at an older html email with an older asset. *Santiago Pastorino*
<add>
<ide> * Don't mount Sprockets server at config.assets.prefix if config.assets.compile is false. *Mark J. Titorenko*
<ide>
<ide> * Set relative url root in assets when controller isn't available for Sprockets (eg. Sass files using asset_path). Fixes #2435 *Guillermo Iguaran*
<ide>
<ide> * ActionDispatch::MiddlewareStack now uses composition over inheritance. It is
<ide> no longer an array which means there may be methods missing that were not tested.
<add>
<ide> * Add an :authenticity_token option to form_tag for custom handling or to omit the token (pass :authenticity_token => false). *Jakub Kuźma, Igor Wiedler*
<ide>
<ide> * HTML5 button_tag helper. *Rizwan Reza*
<ide> * No changes.
<ide>
<ide>
<del>* Rails 3.0.6 (April 5, 2011)
<add>## Rails 3.0.6 (April 5, 2011) ##
<ide>
<ide> * Fixed XSS vulnerability in `auto_link`. `auto_link` no longer marks input as
<ide> html safe. Please make sure that calls to auto_link() are wrapped in a
<ide>
<ide> * Added ActionDispatch::Request#authorization to access the http authentication header regardless of its proxy hiding *DHH*
<ide>
<del>* Added :alert, :notice, and :flash as options to ActionController::Base#redirect_to that'll automatically set the proper flash before the redirection [DHH]. Examples:
<add>* Added :alert, :notice, and :flash as options to ActionController::Base#redirect_to that'll automatically set the proper flash before the redirection *DHH*. Examples:
<ide>
<ide> flash[:notice] = 'Post was created'
<ide> redirect_to(@post)
<ide>
<ide> * Added ActionController::Base#notice/= and ActionController::Base#alert/= as a convenience accessors in both the controller and the view for flash[:notice]/= and flash[:alert]/= *DHH*
<ide>
<del>
<ide> * Introduce grouped_collection_select helper. #1249 *Dan Codeape, Erik Ostrom*
<ide>
<ide> * Make sure javascript_include_tag/stylesheet_link_tag does not append ".js" or ".css" onto external urls. #1664 *Matthew Rudy Jacobs*
<ide>
<ide> * Make the form_for and fields_for helpers support the new Active Record nested update options. #1202 *Eloy Duran*
<ide>
<del> <% form_for @person do |person_form| %>
<add> <% form_for @person do |person_form| %>
<ide> ...
<ide> <% person_form.fields_for :projects do |project_fields| %>
<ide> <% if project_fields.object.active? %>
<ide> Name: <%= project_fields.text_field :name %>
<ide> <% end %>
<ide> <% end %>
<del> <% end %>
<add> <% end %>
<ide>
<ide>
<ide> * Added grouped_options_for_select helper method for wrapping option tags in optgroups. #977 *Jon Crawford*
<ide>
<del>* Implement HTTP Digest authentication. #1230 [Gregg Kellogg, Pratik Naik] Example :
<add>* Implement HTTP Digest authentication. #1230 *Gregg Kellogg, Pratik Naik* Example :
<ide>
<ide> class DummyDigestController < ActionController::Base
<ide> USERS = { "lifo" => 'world' }
<ide>
<ide> * Fixed the AssetTagHelper cache to use the computed asset host as part of the cache key instead of just assuming the its a string #1299 *DHH*
<ide>
<del>* Make ActionController#render(string) work as a shortcut for render :file/:template/:action => string. [#1435] [Pratik Naik] Examples:
<add>* Make ActionController#render(string) work as a shortcut for render :file/:template/:action => string. #1435 *Pratik Naik* Examples:
<ide>
<ide> \# Instead of render(:action => 'other_action')
<ide> render('other_action') # argument has no '/'
<ide>
<ide> * Remove deprecated ActionController::Base#assign_default_content_type_and_charset
<ide>
<del>* Changed the default of ActionView#render to assume partials instead of files when not given an options hash [David Heinemeier Hansson]. Examples:
<add>* Changed the default of ActionView#render to assume partials instead of files when not given an options hash *DHH*. Examples:
<ide>
<ide> # Instead of <%= render :partial => "account" %>
<ide> <%= render "account" %>
<ide>
<ide> * Fix incorrect closing CDATA delimiter and that HTML::Node.parse would blow up on unclosed CDATA sections *packagethief*
<ide>
<del>* Added stale? and fresh_when methods to provide a layer of abstraction above request.fresh? and friends [David Heinemeier Hansson]. Example:
<add>* Added stale? and fresh_when methods to provide a layer of abstraction above request.fresh? and friends *DHH*. Example:
<ide>
<ide> class ArticlesController < ApplicationController
<ide> def show_with_respond_to_block
<ide> end
<ide>
<ide>
<del>* Added inline builder yield to atom_feed_helper tags where appropriate [Sam Ruby]. Example:
<add>* Added inline builder yield to atom_feed_helper tags where appropriate *Sam Ruby*. Example:
<ide>
<ide> entry.summary :type => 'xhtml' do |xhtml|
<ide> xhtml.p pluralize(order.line_items.count, "line item")
<ide>
<ide> * Changed BenchmarkHelper#benchmark to report in milliseconds *David Heinemeier Hansson*
<ide>
<del>* Changed logging format to be millisecond based and skip misleading stats [David Heinemeier Hansson]. Went from:
<add>* Changed logging format to be millisecond based and skip misleading stats *DHH*. Went from:
<ide>
<ide> Completed in 0.10000 (4 reqs/sec) | Rendering: 0.04000 (40%) | DB: 0.00400 (4%) | 200 OK [http://example.com]
<ide>
<ide>
<ide> * Deprecated TemplateHandler line offset *Josh Peek*
<ide>
<del>* Allow caches_action to accept cache store options. #416. [José Valim]. Example:
<add>* Allow caches_action to accept cache store options. #416. *José Valim*. Example:
<ide>
<ide> caches_action :index, :redirected, :if => Proc.new { |c| !c.request.format.json? }, :expires_in => 1.hour
<ide>
<ide>
<ide> * Replaced TemplateFinder abstraction with ViewLoadPaths *Josh Peek*
<ide>
<del>* Added block-call style to link_to [Sam Stephenson/David Heinemeier Hansson]. Example:
<add>* Added block-call style to link_to *Sam Stephenson/David Heinemeier Hansson*. Example:
<ide>
<ide> <% link_to(@profile) do %>
<ide> <strong><%= @profile.name %></strong> -- <span>Check it out!!</span>
<ide>
<ide> * Added OPTIONS to list of default accepted HTTP methods #10449 *holoway*
<ide>
<del>* Added option to pass proc to ActionController::Base.asset_host for maximum configurability #10521 [Cheah Chu Yeow]. Example:
<add>* Added option to pass proc to ActionController::Base.asset_host for maximum configurability #10521 *Cheah Chu Yeow*. Example:
<ide>
<ide> ActionController::Base.asset_host = Proc.new { |source|
<ide> if source.starts_with?('/images')
<ide>
<ide> * Update to Prototype -r8232. *sam*
<ide>
<del>* Make sure the optimisation code for routes doesn't get used if :host, :anchor or :port are provided in the hash arguments. [pager, Michael Koziarski] #10292
<add>* Make sure the optimisation code for routes doesn't get used if :host, :anchor or :port are provided in the hash arguments. *pager, Michael Koziarski* #10292
<ide>
<ide> * Added protection from trailing slashes on page caching #10229 *devrieda*
<ide>
<ide>
<ide> * Don't warn when a path segment precedes a required segment. Closes #9615. *Nicholas Seckar*
<ide>
<del>* Fixed CaptureHelper#content_for to work with the optional content parameter instead of just the block #9434 [sandofsky/wildchild].
<add>* Fixed CaptureHelper#content_for to work with the optional content parameter instead of just the block #9434 *sandofsky/wildchild*.
<ide>
<del>* Added Mime::Type.register_alias for dealing with different formats using the same mime type [David Heinemeier Hansson]. Example:
<add>* Added Mime::Type.register_alias for dealing with different formats using the same mime type *DHH*. Example:
<ide>
<ide> class PostsController < ApplicationController
<ide> before_filter :adjust_format_for_iphone
<ide> end
<ide> end
<ide>
<del>* Added that render :json will automatically call .to_json unless it's being passed a string [David Heinemeier Hansson].
<add>* Added that render :json will automatically call .to_json unless it's being passed a string *DHH*.
<ide>
<ide> * Autolink behaves well with emails embedded in URLs. #7313 *Jeremy McAnally, Tarmo Tänav*
<ide>
<ide>
<ide> * Removed deprecated form of calling xml_http_request/xhr without the first argument being the http verb *David Heinemeier Hansson*
<ide>
<del>* Removed deprecated methods [David Heinemeier Hansson]:
<add>* Removed deprecated methods *DHH*:
<ide>
<ide> - ActionController::Base#keep_flash (use flash.keep instead)
<ide> - ActionController::Base#expire_matched_fragments (just call expire_fragment with a regular expression)
<ide>
<ide> * Reduce file stat calls when checking for template changes. #7736 *alex*
<ide>
<del>* Added custom path cache_page/expire_page parameters in addition to the options hashes [David Heinemeier Hansson]. Example:
<add>* Added custom path cache_page/expire_page parameters in addition to the options hashes *DHH*. Example:
<ide>
<ide> def index
<ide> caches_page(response.body, "/index.html")
<ide>
<ide> * Update to Prototype 1.5.1. *Sam Stephenson*
<ide>
<del>* Allow routes to be decalred under namespaces [Tobias Lütke]:
<add>* Allow routes to be decalred under namespaces *Tobias Lütke*:
<ide>
<ide> map.namespace :admin do |admin|
<ide> admin.root :controller => "products"
<ide>
<ide> * select :include_blank option can be set to a string instead of true, which just uses an empty string. #7664 *Wizard*
<ide>
<del>* Added url_for usage on render :location, which allows for record identification [David Heinemeier Hansson]. Example:
<add>* Added url_for usage on render :location, which allows for record identification *DHH*. Example:
<ide>
<ide> render :xml => person, :status => :created, :location => person
<ide>
<ide> end
<ide> end
<ide>
<del>* Added record identifications to FormHelper#form_for and PrototypeHelper#remote_form_for [David Heinemeier Hansson]. Examples:
<add>* Added record identifications to FormHelper#form_for and PrototypeHelper#remote_form_for *DHH*. Examples:
<ide>
<ide> <% form_for(@post) do |f| %>
<ide> ...
<ide>
<ide> * Rationalize route path escaping according to RFC 2396 section 3.3. #7544, #8307. *Jeremy Kemper, Chris Roos, begemot, jugend*
<ide>
<del>* Added record identification with polymorphic routes for ActionController::Base#url_for and ActionView::Base#url_for [David Heinemeier Hansson]. Examples:
<add>* Added record identification with polymorphic routes for ActionController::Base#url_for and ActionView::Base#url_for *DHH*. Examples:
<ide>
<ide> redirect_to(post) # => redirect_to(posts_url(post)) => Location: http://example.com/posts/1
<ide> link_to(post.title, post) # => link_to(post.title, posts_url(post)) => <a href="/posts/1">Hello world</a>
<ide>
<ide> * Update UrlWriter to accept :anchor parameter. Closes #6771. *Chris McGrath*
<ide>
<del>* Added RecordTagHelper for using RecordIdentifier conventions on divs and other container elements [David Heinemeier Hansson]. Example:
<add>* Added RecordTagHelper for using RecordIdentifier conventions on divs and other container elements *DHH*. Example:
<ide>
<ide> <% div_for(post) do %> <div id="post_45" class="post">
<ide> <%= post.body %> What a wonderful world!
<ide> <% end %> </div>
<ide>
<del>* Added page[record] accessor to JavaScriptGenerator that relies on RecordIdentifier to find the right dom id [David Heinemeier Hansson]. Example:
<add>* Added page[record] accessor to JavaScriptGenerator that relies on RecordIdentifier to find the right dom id *DHH*. Example:
<ide>
<ide> format.js do
<ide> # Calls: new Effect.fade('post_45');
<ide> :has_many => [ :tags, :images, :variants ]
<ide> end
<ide>
<del>* Added :name_prefix as standard for nested resources [David Heinemeier Hansson]. WARNING: May be backwards incompatible with your app
<add>* Added :name_prefix as standard for nested resources *DHH*. WARNING: May be backwards incompatible with your app
<ide>
<ide> Before:
<ide>
<ide>
<ide> map.resources :notes, :has_many => [ :comments, :attachments ], :has_one => :author
<ide>
<del>* Added that render :xml will try to call to_xml if it can [David Heinemeier Hansson]. Makes these work:
<add>* Added that render :xml will try to call to_xml if it can *DHH*. Makes these work:
<ide>
<ide> render :xml => post
<ide> render :xml => comments
<ide>
<ide> * Allow array and hash query parameters. Array route parameters are converted/to/a/path as before. #6765, #7047, #7462 *bgipsy, Jeremy McAnally, Dan Kubb, brendan*
<ide>
<del> \# Add a #dbman attr_reader for CGI::Session and make CGI::Session::CookieStore#generate_digest public so it's easy to generate digests using the cookie store's secret. [Rick Olson]
<add> \# Add a #dbman attr_reader for CGI::Session and make CGI::Session::CookieStore#generate_digest public so it's easy to generate digests using the cookie store's secret. *Rick Olson*
<ide> * Added Request#url that returns the complete URL used for the request *David Heinemeier Hansson*
<ide>
<ide> * Extract dynamic scaffolding into a plugin. #7700 *Josh Peek*
<ide>
<ide> * Allow send_file/send_data to use a registered mime type as the :type parameter #7620 *jonathan*
<ide>
<del>* Allow routing requirements on map.resource(s) #7633 [quixoten]. Example:
<add>* Allow routing requirements on map.resource(s) #7633 *quixoten*. Example:
<ide>
<ide> map.resources :network_interfaces, :requirements => { :id => /^\d+\.\d+\.\d+\.\d+$/ }
<ide>
<ide> :secret => Proc.new { User.current.secret_key }
<ide> }
<ide>
<del>* Added .erb and .builder as preferred aliases to the now deprecated .rhtml and .rxml extensions [Chad Fowler]. This is done to separate the renderer from the mime type. .erb templates are often used to render emails, atom, csv, whatever. So labeling them .rhtml doesn't make too much sense. The same goes for .rxml, which can be used to build everything from HTML to Atom to whatever. .rhtml and .rxml will continue to work until Rails 3.0, though. So this is a slow phasing out. All generators and examples will start using the new aliases, though.
<add>* Added .erb and .builder as preferred aliases to the now deprecated .rhtml and .rxml extensions *Chad Fowler*. This is done to separate the renderer from the mime type. .erb templates are often used to render emails, atom, csv, whatever. So labeling them .rhtml doesn't make too much sense. The same goes for .rxml, which can be used to build everything from HTML to Atom to whatever. .rhtml and .rxml will continue to work until Rails 3.0, though. So this is a slow phasing out. All generators and examples will start using the new aliases, though.
<ide>
<del>* Added caching option to AssetTagHelper#stylesheet_link_tag and AssetTagHelper#javascript_include_tag [David Heinemeier Hansson]. Examples:
<add>* Added caching option to AssetTagHelper#stylesheet_link_tag and AssetTagHelper#javascript_include_tag *DHH*. Examples:
<ide>
<ide> stylesheet_link_tag :all, :cache => true # when ActionController::Base.perform_caching is false =>
<ide> <link href="/stylesheets/style1.css" media="screen" rel="Stylesheet" type="text/css" />
<ide> * Fix #render_file so that TemplateError is called with the correct params and you don't get the WSOD. *Rick Olson*
<ide>
<ide> * Fix issue with deprecation messing up #template_root= usage. Add #prepend_view_path and #append_view_path to allow modification of a copy of the
<del> superclass' view_paths. [Rick Olson]
<add> superclass' view_paths. *Rick Olson*
<ide> * Allow Controllers to have multiple view_paths instead of a single template_root. Closes #2754 *John Long*
<ide>
<ide> * Add much-needed html-scanner tests. Fixed CDATA parsing bug. *Rick Olson*
<ide>
<ide> * Added map.root as an alias for map.connect '' *David Heinemeier Hansson*
<ide>
<del>* Added Request#format to return the format used for the request as a mime type. If no format is specified, the first Request#accepts type is used. This means you can stop using respond_to for anything else than responses [David Heinemeier Hansson]. Examples:
<add>* Added Request#format to return the format used for the request as a mime type. If no format is specified, the first Request#accepts type is used. This means you can stop using respond_to for anything else than responses *DHH*. Examples:
<ide>
<ide> GET /posts/5.xml | request.format => Mime::XML
<ide> GET /posts/5.xhtml | request.format => Mime::HTML
<ide> GET /posts/5 | request.format => request.accepts.first (usually Mime::HTML for browsers)
<ide>
<del>* Added the option for extension aliases to mime type registration [David Heinemeier Hansson]. Example (already in the default routes):
<add>* Added the option for extension aliases to mime type registration *DHH*. Example (already in the default routes):
<ide>
<ide> Mime::Type.register "text/html", :html, %w( application/xhtml+xml ), %w( xhtml )
<ide>
<ide>
<ide> * Add a 0 margin/padding div around the hidden _method input tag that form_tag outputs. *Rick Olson*
<ide>
<del>* Added block-usage to TagHelper#content_tag [David Heinemeier Hansson]. Example:
<add>* Added block-usage to TagHelper#content_tag *DHH*. Example:
<ide>
<ide> <% content_tag :div, :class => "strong" %>
<ide> Hello world!
<ide>
<ide> * Fix deprecation warnings when rendering the template error template. *Nicholas Seckar*
<ide>
<del>* Fix routing to correctly determine when generation fails. Closes #6300. [psross].
<add>* Fix routing to correctly determine when generation fails. Closes #6300. *psross*.
<ide>
<ide> * Fix broken assert_generates when extra keys are being checked. *Jamis Buck*
<ide>
<ide>
<ide> * Fixed that FormHelper#radio_button didn't respect an :id being passed in #6266 *evansj*
<ide>
<del>* Added an html_options hash parameter to javascript_tag() and update_page_tag() helpers #6311 [tzaharia]. Example:
<add>* Added an html_options hash parameter to javascript_tag() and update_page_tag() helpers #6311 *tzaharia*. Example:
<ide>
<ide> update_page_tag :defer => 'true' { |page| ... }
<ide>
<ide>
<ide> * Deprecation: @cookies, @headers, @request, @response will be removed after 1.2. Use the corresponding method instead. *Jeremy Kemper*
<ide>
<del>* Make the :status parameter expand to the default message for that status code if it is an integer. Also support symbol statuses. [Jamis Buck]. Examples:
<add>* Make the :status parameter expand to the default message for that status code if it is an integer. Also support symbol statuses. *Jamis Buck*. Examples:
<ide>
<ide> head :status => 404 # expands to "404 Not Found"
<ide> head :status => :not_found # expands to "404 Not Found"
<ide> head :status => :created # expands to "201 Created"
<ide>
<del>* Add head(options = {}) for responses that have no body. [Jamis Buck]. Examples:
<add>* Add head(options = {}) for responses that have no body. *Jamis Buck*. Examples:
<ide>
<ide> head :status => 404 # return an empty response with a 404 status
<ide> head :location => person_path(@person), :status => 201
<ide>
<ide> * Rescue Errno::ECONNRESET to handle an unexpectedly closed socket connection. Improves SCGI reliability. #3368, #6226 *sdsykes, [email protected]*
<ide>
<del>* Added that respond_to blocks will automatically set the content type to be the same as is requested [David Heinemeier Hansson]. Examples:
<add>* Added that respond_to blocks will automatically set the content type to be the same as is requested *DHH*. Examples:
<ide>
<ide> respond_to do |format|
<ide> format.html { render :text => "I'm being sent as text/html" }
<ide>
<ide> * Added utf-8 as the default charset for all renders. You can change this default using ActionController::Base.default_charset=(encoding) *David Heinemeier Hansson*
<ide>
<del>* Added proper getters and setters for content type and charset [David Heinemeier Hansson]. Example of what we used to do:
<add>* Added proper getters and setters for content type and charset *DHH*. Example of what we used to do:
<ide>
<ide> response.headers["Content-Type"] = "application/atom+xml; charset=utf-8"
<ide>
<ide>
<ide> * Update UrlWriter to support :only_path. *Nicholas Seckar, Dave Thomas*
<ide>
<del>* Fixed JavaScriptHelper#link_to_function and JavaScriptHelper#button_to_function to have the script argument be optional [David Heinemeier Hansson]. So what used to require a nil, like this:
<add>* Fixed JavaScriptHelper#link_to_function and JavaScriptHelper#button_to_function to have the script argument be optional *DHH*. So what used to require a nil, like this:
<ide>
<ide> link_to("Hider", nil, :class => "hider_link") { |p| p[:something].hide }
<ide>
<ide>
<ide> * Update to Prototype 1.5.0_rc1 *sam*
<ide>
<del>* Added access to nested attributes in RJS #4548 [[email protected]]. Examples:
<add>* Added access to nested attributes in RJS #4548 *[email protected]*. Examples:
<ide>
<ide> page['foo']['style'] # => $('foo').style;
<ide> page['foo']['style']['color'] # => $('blank_slate').style.color;
<ide>
<ide> * Fixed the new_#{resource}_url route and added named route tests for Simply Restful. *Rick Olson*
<ide>
<del>* Added map.resources from the Simply Restful plugin [David Heinemeier Hansson]. Examples (the API has changed to use plurals!):
<add>* Added map.resources from the Simply Restful plugin *DHH*. Examples (the API has changed to use plurals!):
<ide>
<ide> map.resources :messages
<ide> map.resources :messages, :comments
<ide>
<ide> * Added Mime::TEXT (text/plain) and Mime::ICS (text/calendar) as new default types *David Heinemeier Hansson*
<ide>
<del>* Added Mime::Type.register(string, symbol, synonyms = []) for adding new custom mime types [David Heinemeier Hansson]. Example: Mime::Type.register("image/gif", :gif)
<add>* Added Mime::Type.register(string, symbol, synonyms = []) for adding new custom mime types *DHH*. Example: Mime::Type.register("image/gif", :gif)
<ide>
<del>* Added support for Mime objects in render :content_type option [David Heinemeier Hansson]. Example: render :text => some_atom, :content_type => Mime::ATOM
<add>* Added support for Mime objects in render :content_type option *DHH*. Example: render :text => some_atom, :content_type => Mime::ATOM
<ide>
<ide> * Add :status option to send_data and send_file. Defaults to '200 OK'. #5243 *Manfred Stienstra <[email protected]>*
<ide>
<ide>
<ide> * Accept multipart PUT parameters. #5235 *[email protected]*
<ide>
<del>* Added interrogation of params[:format] to determine Accept type. If :format is specified and matches a declared extension, like "rss" or "xml", that mime type will be put in front of the accept handler. This means you can link to the same action from different extensions and use that fact to determine output [David Heinemeier Hansson]. Example:
<add>* Added interrogation of params[:format] to determine Accept type. If :format is specified and matches a declared extension, like "rss" or "xml", that mime type will be put in front of the accept handler. This means you can link to the same action from different extensions and use that fact to determine output *DHH*. Example:
<ide>
<ide> class WeblogController < ActionController::Base
<ide> def index
<ide>
<ide> * Add a 0 margin/padding div around the hidden _method input tag that form_tag outputs. *Rick Olson*
<ide>
<del>* Added block-usage to TagHelper#content_tag [David Heinemeier Hansson]. Example:
<add>* Added block-usage to TagHelper#content_tag *DHH*. Example:
<ide>
<ide> <% content_tag :div, :class => "strong" %>
<ide> Hello world!
<ide>
<ide> * Fix double-escaped entities, such as &amp;, &#123;, etc. *Rick Olson*
<ide>
<del>* Fix routing to correctly determine when generation fails. Closes #6300. [psross].
<add>* Fix routing to correctly determine when generation fails. Closes #6300. *psross*.
<ide>
<ide> * Fix broken assert_generates when extra keys are being checked. *Jamis Buck*
<ide>
<ide>
<ide> * Fixed that FormHelper#radio_button didn't respect an :id being passed in #6266 *evansj*
<ide>
<del>* Added an html_options hash parameter to javascript_tag() and update_page_tag() helpers #6311 [tzaharia]. Example:
<add>* Added an html_options hash parameter to javascript_tag() and update_page_tag() helpers #6311 *tzaharia*. Example:
<ide>
<ide> update_page_tag :defer => 'true' { |page| ... }
<ide>
<ide>
<ide> * Deprecation: @cookies, @headers, @request, @response will be removed after 1.2. Use the corresponding method instead. *Jeremy Kemper*
<ide>
<del>* Make the :status parameter expand to the default message for that status code if it is an integer. Also support symbol statuses. [Jamis Buck]. Examples:
<add>* Make the :status parameter expand to the default message for that status code if it is an integer. Also support symbol statuses. *Jamis Buck*. Examples:
<ide>
<ide> head :status => 404 # expands to "404 Not Found"
<ide> head :status => :not_found # expands to "404 Not Found"
<ide> head :status => :created # expands to "201 Created"
<ide>
<del>* Add head(options = {}) for responses that have no body. [Jamis Buck]. Examples:
<add>* Add head(options = {}) for responses that have no body. *Jamis Buck*. Examples:
<ide>
<ide> head :status => 404 # return an empty response with a 404 status
<ide> head :location => person_path(@person), :status => 201
<ide>
<ide> * Rescue Errno::ECONNRESET to handle an unexpectedly closed socket connection. Improves SCGI reliability. #3368, #6226 *sdsykes, [email protected]*
<ide>
<del>* Added that respond_to blocks will automatically set the content type to be the same as is requested [David Heinemeier Hansson]. Examples:
<add>* Added that respond_to blocks will automatically set the content type to be the same as is requested *DHH*. Examples:
<ide>
<ide> respond_to do |format|
<ide> format.html { render :text => "I'm being sent as text/html" }
<ide>
<ide> * Added utf-8 as the default charset for all renders. You can change this default using ActionController::Base.default_charset=(encoding) *David Heinemeier Hansson*
<ide>
<del>* Added proper getters and setters for content type and charset [David Heinemeier Hansson]. Example of what we used to do:
<add>* Added proper getters and setters for content type and charset *DHH*. Example of what we used to do:
<ide>
<ide> response.headers["Content-Type"] = "application/atom+xml; charset=utf-8"
<ide>
<ide>
<ide> * Update UrlWriter to support :only_path. *Nicholas Seckar, Dave Thomas*
<ide>
<del>* Fixed JavaScriptHelper#link_to_function and JavaScriptHelper#button_to_function to have the script argument be optional [David Heinemeier Hansson]. So what used to require a nil, like this:
<add>* Fixed JavaScriptHelper#link_to_function and JavaScriptHelper#button_to_function to have the script argument be optional *DHH*. So what used to require a nil, like this:
<ide>
<ide> link_to("Hider", nil, :class => "hider_link") { |p| p[:something].hide }
<ide>
<ide> ...can be written like this:
<ide>
<ide> link_to("Hider", :class => "hider_link") { |p| p[:something].hide }
<ide>
<del>* Added access to nested attributes in RJS #4548 [[email protected]]. Examples:
<add>* Added access to nested attributes in RJS #4548 *[email protected]*. Examples:
<ide>
<ide> page['foo']['style'] # => $('foo').style;
<ide> page['foo']['style']['color'] # => $('blank_slate').style.color;
<ide>
<ide> * Fixed the new_#{resource}_url route and added named route tests for Simply Restful. *Rick Olson*
<ide>
<del>* Added map.resources from the Simply Restful plugin [David Heinemeier Hansson]. Examples (the API has changed to use plurals!):
<add>* Added map.resources from the Simply Restful plugin *DHH*. Examples (the API has changed to use plurals!):
<ide>
<ide> map.resources :messages
<ide> map.resources :messages, :comments
<ide>
<ide> * Added Mime::TEXT (text/plain) and Mime::ICS (text/calendar) as new default types *David Heinemeier Hansson*
<ide>
<del>* Added Mime::Type.register(string, symbol, synonyms = []) for adding new custom mime types [David Heinemeier Hansson]. Example: Mime::Type.register("image/gif", :gif)
<add>* Added Mime::Type.register(string, symbol, synonyms = []) for adding new custom mime types *DHH*. Example: Mime::Type.register("image/gif", :gif)
<ide>
<del>* Added support for Mime objects in render :content_type option [David Heinemeier Hansson]. Example: render :text => some_atom, :content_type => Mime::ATOM
<add>* Added support for Mime objects in render :content_type option *DHH*. Example: render :text => some_atom, :content_type => Mime::ATOM
<ide>
<ide> * Add :status option to send_data and send_file. Defaults to '200 OK'. #5243 *Manfred Stienstra <[email protected]>*
<ide>
<ide>
<ide> * Accept multipart PUT parameters. #5235 *[email protected]*
<ide>
<del>* Added interrogation of params[:format] to determine Accept type. If :format is specified and matches a declared extension, like "rss" or "xml", that mime type will be put in front of the accept handler. This means you can link to the same action from different extensions and use that fact to determine output [David Heinemeier Hansson]. Example:
<add>* Added interrogation of params[:format] to determine Accept type. If :format is specified and matches a declared extension, like "rss" or "xml", that mime type will be put in front of the accept handler. This means you can link to the same action from different extensions and use that fact to determine output *DHH*. Example:
<ide>
<ide> class WeblogController < ActionController::Base
<ide> def index
<ide>
<ide> * Applied Prototype $() performance patches (#4465, #4477) and updated script.aculo.us *Sam Stephenson, Thomas Fuchs*
<ide>
<del>* Added automated timestamping to AssetTagHelper methods for stylesheets, javascripts, and images when Action Controller is run under Rails [David Heinemeier Hansson]. Example:
<add>* Added automated timestamping to AssetTagHelper methods for stylesheets, javascripts, and images when Action Controller is run under Rails *DHH*. Example:
<ide>
<ide> image_tag("rails.png") # => '<img alt="Rails" src="/images/rails.png?1143664135" />'
<ide>
<ide>
<ide> * Change url_for to escape the resulting URLs when called from a view. *Nicholas Seckar, coffee2code*
<ide>
<del>* Added easy support for testing file uploads with fixture_file_upload #4105 [[email protected]]. Example:
<add>* Added easy support for testing file uploads with fixture_file_upload #4105 *[email protected]*. Example:
<ide>
<ide> # Looks in Test::Unit::TestCase.fixture_path + '/files/spongebob.png'
<ide> post :change_avatar, :avatar => fixture_file_upload('/files/spongebob.png', 'image/png')
<ide>
<ide> * Added simple alert() notifications for RJS exceptions when config.action_view.debug_rjs = true. *Sam Stephenson*
<ide>
<del>* Added :content_type option to render, so you can change the content type on the fly [David Heinemeier Hansson]. Example: render :action => "atom.rxml", :content_type => "application/atom+xml"
<add>* Added :content_type option to render, so you can change the content type on the fly *DHH*. Example: render :action => "atom.rxml", :content_type => "application/atom+xml"
<ide>
<ide> * CHANGED DEFAULT: The default content type for .rxml is now application/xml instead of type/xml, see http://www.xml.com/pub/a/2004/07/21/dive.html for reason *David Heinemeier Hansson*
<ide>
<del>* Added option to render action/template/file of a specific extension (and here by template type). This means you can have multiple templates with the same name but a different extension [David Heinemeier Hansson]. Example:
<add>* Added option to render action/template/file of a specific extension (and here by template type). This means you can have multiple templates with the same name but a different extension *DHH*. Example:
<ide>
<ide> class WeblogController < ActionController::Base
<ide> def index
<ide> end
<ide> end
<ide>
<del>* Added better support for using the same actions to output for different sources depending on the Accept header [David Heinemeier Hansson]. Example:
<add>* Added better support for using the same actions to output for different sources depending on the Accept header *DHH*. Example:
<ide>
<ide> class WeblogController < ActionController::Base
<ide> def create
<ide>
<ide> * Integration test's url_for now runs in the context of the last request (if any) so after post /products/show/1 url_for :action => 'new' will yield /product/new *Tobias Lütke*
<ide>
<del>* Re-added mixed-in helper methods for the JavascriptGenerator. Moved JavascriptGenerators methods to a module that is mixed in after the helpers are added. Also fixed that variables set in the enumeration methods like #collect are set correctly. Documentation added for the enumeration methods [Rick Olson]. Examples:
<add>* Re-added mixed-in helper methods for the JavascriptGenerator. Moved JavascriptGenerators methods to a module that is mixed in after the helpers are added. Also fixed that variables set in the enumeration methods like #collect are set correctly. Documentation added for the enumeration methods *Rick Olson*. Examples:
<ide>
<ide> page.select('#items li').collect('items') do |element|
<ide> element.hide
<ide> # Assign the default XmlSimple to a new content type
<ide> ActionController::Base.param_parsers['application/backpack+xml'] = :xml_simple
<ide>
<del> Default YAML web services were retired, ActionController::Base.param_parsers carries an example which shows how to get this functionality back. As part of this new plugin support, request.[formatted_post?, xml_post?, yaml_post? and post_format] were all deprecated in favor of request.content_type [Tobias Lütke]
<add> Default YAML web services were retired, ActionController::Base.param_parsers carries an example which shows how to get this functionality back. As part of this new plugin support, request.[formatted_post?, xml_post?, yaml_post? and post_format] were all deprecated in favor of request.content_type *Tobias Lütke*
<ide> * Fixed Effect.Appear in effects.js to work with floats in Safari #3524, #3813, #3044 *Thomas Fuchs*
<ide>
<ide> * Fixed that default image extension was not appended when using a full URL with AssetTagHelper#image_tag #4032, #3728 *[email protected]*
<ide>
<ide> * Added .rxml (and any non-rhtml template, really) supportfor CaptureHelper#content_for and CaptureHelper#capture #3287 *Brian Takita*
<ide>
<del>* Added script.aculo.us drag and drop helpers to RJS [Thomas Fuchs]. Examples:
<add>* Added script.aculo.us drag and drop helpers to RJS *Thomas Fuchs*. Examples:
<ide>
<ide> page.draggable 'product-1'
<ide> page.drop_receiving 'wastebasket', :url => { :action => 'delete' }
<ide>
<ide> * Update script.aculo.us to V1.5.2 *Thomas Fuchs*
<ide>
<del>* Added element and collection proxies to RJS [David Heinemeier Hansson]. Examples:
<add>* Added element and collection proxies to RJS *DHH*. Examples:
<ide>
<ide> page['blank_slate'] # => $('blank_slate');
<ide> page['blank_slate'].show # => $('blank_slate').show();
<ide>
<ide> * Ensure that the instance variables are copied to the template when performing render :update. *Nicholas Seckar*
<ide>
<del>* Add the ability to call JavaScriptGenerator methods from helpers called in update blocks. [Sam Stephenson] Example:
<add>* Add the ability to call JavaScriptGenerator methods from helpers called in update blocks. *Sam Stephenson* Example:
<ide> module ApplicationHelper
<ide> def update_time
<ide> page.replace_html 'time', Time.now.to_s(:db)
<ide>
<ide> * Pass along blocks from render_to_string to render. *Sam Stephenson*
<ide>
<del>* Add render :update for inline RJS. [Sam Stephenson] Example:
<add>* Add render :update for inline RJS. *Sam Stephenson* Example:
<ide> class UserController < ApplicationController
<ide> def refresh
<ide> render :update do |page|
<ide>
<ide> * Added :select option for JavaScriptMacroHelper#auto_complete_field that makes it easier to only use part of the auto-complete suggestion as the value for insertion *Thomas Fuchs*
<ide>
<del>* Added delayed execution of Javascript from within RJS #3264 [[email protected]]. Example:
<add>* Added delayed execution of Javascript from within RJS #3264 *[email protected]*. Example:
<ide>
<ide> page.delay(20) do
<ide> page.visual_effect :fade, 'notice'
<ide>
<ide> * Handle cookie parsing irregularity for certain Nokia phones. #2530 *[email protected]*
<ide>
<del>* Added PrototypeHelper::JavaScriptGenerator and PrototypeHelper#update_page for easily modifying multiple elements in an Ajax response. [Sam Stephenson] Example:
<add>* Added PrototypeHelper::JavaScriptGenerator and PrototypeHelper#update_page for easily modifying multiple elements in an Ajax response. *Sam Stephenson* Example:
<ide>
<ide> update_page do |page|
<ide> page.insert_html :bottom, 'list', '<li>Last item</li>'
<ide>
<ide> * Only include builtin filters whose filenames match /^[a-z][a-z_]*_helper.rb$/ to avoid including operating system metadata such as ._foo_helper.rb. #2855 *court3nay*
<ide>
<del>* Added FormHelper#form_for and FormHelper#fields_for that makes it easier to work with forms for single objects also if they don't reside in instance variables [David Heinemeier Hansson]. Examples:
<add>* Added FormHelper#form_for and FormHelper#fields_for that makes it easier to work with forms for single objects also if they don't reside in instance variables *DHH*. Examples:
<ide>
<ide> <% form_for :person, @person, :url => { :action => "update" } do |f| %>
<ide> First name: <%= f.text_field :first_name %>
<ide>
<ide> * Added short-hand to assert_tag so assert_tag :tag => "span" can be written as assert_tag "span" *David Heinemeier Hansson*
<ide>
<del>* Added skip_before_filter/skip_after_filter for easier control of the filter chain in inheritance hierachies [David Heinemeier Hansson]. Example:
<add>* Added skip_before_filter/skip_after_filter for easier control of the filter chain in inheritance hierachies *DHH*. Example:
<ide>
<ide> class ApplicationController < ActionController::Base
<ide> before_filter :authenticate
<ide>
<ide> * Fixed that number_to_currency(1000, {:precision => 0})) should return "$1,000", instead of "$1,000." #2122 *[email protected]*
<ide>
<del>* Allow link_to_remote to use any DOM-element as the parent of the form elements to be submitted #2137 [[email protected]]. Example:
<add>* Allow link_to_remote to use any DOM-element as the parent of the form elements to be submitted #2137 *[email protected]*. Example:
<ide>
<ide> <tr id="row023">
<ide> <td><input name="foo"/></td>
<ide>
<ide> * Updated vendor copy of html-scanner to support better xml parsing
<ide>
<del>* Added :popup option to UrlHelper#link_to #1996 [[email protected]]. Examples:
<add>* Added :popup option to UrlHelper#link_to #1996 *[email protected]*. Examples:
<ide>
<ide> link_to "Help", { :action => "help" }, :popup => true
<ide> link_to "Busy loop", { :action => "busy" }, :popup => ['new_window', 'height=300,width=600']
<ide>
<ide> * Added support for per-action session management #1763
<ide>
<del>* Improved rendering speed on complicated templates by up to 100% (the more complex the templates, the higher the speedup) #1234 [Stefan Kaes]. This did necessasitate a change to the internals of ActionView#render_template that now has four parameters. Developers of custom view handlers (like Amrita) need to update for that.
<add>* Improved rendering speed on complicated templates by up to 100% (the more complex the templates, the higher the speedup) #1234 *Stefan Kaes*. This did necessasitate a change to the internals of ActionView#render_template that now has four parameters. Developers of custom view handlers (like Amrita) need to update for that.
<ide>
<ide> * Added options hash as third argument to FormHelper#input, so you can do input('person', 'zip', :size=>10) #1719 *[email protected]*
<ide>
<ide>
<ide> * Added :prompt option to FormOptions#select (and the users of it, like FormOptions#select_country etc) to create "Please select" style descriptors #1181 *Michael Schuerig*
<ide>
<del>* Added JavascriptHelper#update_element_function, which returns a Javascript function (or expression) that'll update a DOM element according to the options passed #933 [[email protected]]. Examples:
<add>* Added JavascriptHelper#update_element_function, which returns a Javascript function (or expression) that'll update a DOM element according to the options passed #933 *[email protected]*. Examples:
<ide>
<ide> <%= update_element_function("products", :action => :insert, :position => :bottom, :content => "<p>New product!</p>") %>
<ide>
<ide>
<ide> * Removed the default option of wrap=virtual on FormHelper#text_area to ensure XHTML compatibility #1300 *[email protected]*
<ide>
<del>* Adds the ability to include XML CDATA tags using Builder #1563 [Josh Knowles]. Example:
<add>* Adds the ability to include XML CDATA tags using Builder #1563 *Josh Knowles*. Example:
<ide>
<ide> xml.cdata! "some text" # => <![CDATA[some text]]>
<ide>
<ide>
<ide> * Routes fail with leading slash #1540 *Nicholas Seckar*
<ide>
<del>* Added support for graceful error handling of Ajax calls #1217 [Jamis Buck/Thomas Fuchs]. Example:
<add>* Added support for graceful error handling of Ajax calls #1217 *Jamis Buck/Thomas Fuchs*. Example:
<ide>
<ide> link_to_remote(
<ide> "test",
<ide>
<ide> * Added TextHelper#word_wrap(text, line_length = 80) #1449 *[email protected]*
<ide>
<del>* Added a fall-through action for form_remote_tag that'll be used in case Javascript is unavailable #1459 [Scott Barron]. Example:
<add>* Added a fall-through action for form_remote_tag that'll be used in case Javascript is unavailable #1459 *Scott Barron*. Example:
<ide>
<ide> form_remote_tag :html => { :action => url_for(:controller => "some", :action => "place") }
<ide>
<ide> * Added :xhr => true/false option to verify so you can ensure that a request is coming from an Ajax call or not #1464 *Thomas Fuchs*
<ide>
<ide> * Added tag_options as a third parameter to AssetHelper#auto_discovery_link_tag to control options like the title of the link #1430 *Kevin Clark*
<ide>
<del>* Added option to pass in parameters to CaptureHelper#capture, so you can create more advanced view helper methods #1466 [[email protected]]. Example:
<add>* Added option to pass in parameters to CaptureHelper#capture, so you can create more advanced view helper methods #1466 *[email protected]*. Example:
<ide>
<ide> <% show_calendar(:year => 2005, :month => 6) do |day, options| %>
<ide> <% options[:bgcolor] = '#dfd' if 10..15.include? day %>
<ide>
<ide> * Correct distance_of_time_in_words for integer arguments and make the second arg optional, treating the first arg as a duration in seconds. #1458 *madrobby <[email protected]>*
<ide>
<del>* Fixed query parser to deal gracefully with equal signs inside keys and values #1345 [gorou].
<add>* Fixed query parser to deal gracefully with equal signs inside keys and values #1345 *gorou*.
<ide> Example: /?sig=abcdef=:foobar=&x=y will pass now.
<ide>
<ide> * Added Cuba to country list #1351 *todd*
<ide>
<ide> * Fixed image_tag so an exception is not thrown just because the image is missing and alt value can't be generated #1395 *Marcel Molina Jr.*
<ide>
<del>* Added a third parameter to TextHelper#auto_link called href_options for specifying additional tag options on the links generated #1401 [[email protected]]. Example: auto_link(text, :all, { :target => "_blank" }) to have all the generated links open in a new window.
<add>* Added a third parameter to TextHelper#auto_link called href_options for specifying additional tag options on the links generated #1401 *[email protected]*. Example: auto_link(text, :all, { :target => "_blank" }) to have all the generated links open in a new window.
<ide>
<ide> * Fixed TextHelper#highlight to return the text, not nil, if the phrase is blank #1409 *Patrick Lenz*
<ide>
<ide>
<ide> ## 1.8.1 (20th April, 2005) ##
<ide>
<del>* Added xml_http_request/xhr method for simulating XMLHttpRequest in functional tests #1151 [Sam Stephenson]. Example:
<add>* Added xml_http_request/xhr method for simulating XMLHttpRequest in functional tests #1151 *Sam Stephenson*. Example:
<ide>
<ide> xhr :post, :index
<ide>
<ide> * Deprecated the majority of all the testing assertions and replaced them with a much smaller core and access to all the collections the old assertions relied on. That way the regular test/unit assertions can be used against these. Added documentation about how to use it all.
<ide>
<ide> * Added a wide range of new Javascript effects:
<del> * Effect.Puff zooms the element out and makes it smoothly transparent at the same time, giving a "puff" illusion #996 [[email protected]]
<add> * Effect.Puff zooms the element out and makes it smoothly transparent at the same time, giving a "puff" illusion #996 *[email protected]*
<ide> After the animation is completed, the display property will be set to none.
<ide> This effect will work on relative and absolute positioned elements.
<ide>
<del> * Effect.Appear as the opposite of Effect.Fade #990 [[email protected]]
<add> * Effect.Appear as the opposite of Effect.Fade #990 *[email protected]*
<ide> You should return elements with style="display:none;" or a like class for this to work best and have no chance of flicker.
<ide>
<del> * Effect.Squish for scaling down an element and making it disappear at the end #972 [[email protected]]
<add> * Effect.Squish for scaling down an element and making it disappear at the end #972 *[email protected]*
<ide>
<del> * Effect.Scale for smoothly scaling images or text up and down #972 [[email protected]]
<add> * Effect.Scale for smoothly scaling images or text up and down #972 *[email protected]*
<ide>
<del> * Effect.Fade which smoothly turns opacity from 100 to 0 and then hides the element #960 [[email protected]]
<add> * Effect.Fade which smoothly turns opacity from 100 to 0 and then hides the element #960 *[email protected]*
<ide>
<ide> * Added Request#xml_http_request? (and an alias xhr?) to that'll return true when the request came from one of the Javascript helper methods (Ajax). This can be used to give one behavior for modern browsers supporting Ajax, another to old browsers #1127 *Sam Stephenson*
<ide>
<ide>
<ide> * Fixed routing and helpers to make Rails work on non-vhost setups #826 *Nicholas Seckar/Tobias Lütke*
<ide>
<del>* Added a much improved Flash module that allows for finer-grained control on expiration and allows you to flash the current action #839 [Caio Chassot]. Example of flash.now:
<add>* Added a much improved Flash module that allows for finer-grained control on expiration and allows you to flash the current action #839 *Caio Chassot*. Example of flash.now:
<ide>
<ide> class SomethingController < ApplicationController
<ide> def save
<ide> end
<ide> end
<ide>
<del>* Added to_param call for parameters when composing an url using url_for from something else than strings #812 [Sam Stephenson]. Example:
<add>* Added to_param call for parameters when composing an url using url_for from something else than strings #812 *Sam Stephenson*. Example:
<ide>
<ide> class Page
<ide> def initialize(number)
<ide>
<ide> * Added that the html options disabled, readonly, and multiple can all be treated as booleans. So specifying <tt>disabled => :true</tt> will give <tt>disabled="disabled"</tt>. #809 *mindel*
<ide>
<del>* Added path collection syntax for Routes that will gobble up the rest of the url and pass it on to the controller #830 [rayners]. Example:
<add>* Added path collection syntax for Routes that will gobble up the rest of the url and pass it on to the controller #830 *rayners*. Example:
<ide>
<ide> map.connect 'categories/*path_info', :controller => 'categories', :action => 'show'
<ide>
<ide>
<ide> * Removed the reliance on PATH_INFO as it was causing problems for caching and inhibited the new non-vhost support #822 *Nicholas Seckar*
<ide>
<del>* Added assigns shortcut for @response.template.assigns to controller test cases [Jeremy Kemper]. Example:
<add>* Added assigns shortcut for @response.template.assigns to controller test cases *Jeremy Kemper*. Example:
<ide>
<ide> Before:
<ide>
<ide>
<ide> * Added that ActiveRecordHelper#form now calls url_for on the :action option.
<ide>
<del>* Added all the HTTP methods as alternatives to the generic "process" for functional testing #276 [Tobias Lütke]. Examples:
<add>* Added all the HTTP methods as alternatives to the generic "process" for functional testing #276 *Tobias Lütke*. Examples:
<ide>
<ide> # Calls Controller#miletone with a GET request
<ide> process :milestone
<ide> * Added assert_flash_equal(expected, key, message), assert_session_equal(expected, key, message),
<ide> assert_assigned_equal(expected, key, message) to test the contents of flash, session, and template assigns.
<ide>
<del>* Improved the failure report on assert_success when the action triggered a redirection [alexey].
<add>* Improved the failure report on assert_success when the action triggered a redirection *alexey*.
<ide>
<ide> * Added "markdown" to accompany "textilize" as a TextHelper method for converting text to HTML using the Markdown syntax.
<ide> BlueCloth must be installed in order for this method to become available.
<ide>
<ide> *Builder is created by Jim Weirich*
<ide>
<del>* Added much improved support for functional testing [what-a-day].
<add>* Added much improved support for functional testing *what-a-day*.
<ide>
<ide> # Old style
<ide> def test_failing_authenticate
<ide> following the suggestion from Matz on:
<ide> http://groups.google.com/groups?th=e3a4e68ba042f842&seekm=c3sioe%241qvm%241%40news.cybercity.dk#link14
<ide>
<del>* Added caching for compiled ERb templates. On Basecamp, it gave between 8.5% and 71% increase in performance [Andreas Schwarz].
<add>* Added caching for compiled ERb templates. On Basecamp, it gave between 8.5% and 71% increase in performance *Andreas Schwarz*.
<ide>
<ide> * Added implicit counter variable to render_collection_of_partials [Marcel Molina Jr.]. From the docs:
<ide>
<ide> :confirm => 'Are you sure?', the link will be guarded with a JS popup asking that question.
<ide> If the user accepts, the link is processed, otherwise not.
<ide>
<del>* Added link_to_unless_current as a UrlHelper method [Sam Stephenson]. Documentation:
<add>* Added link_to_unless_current as a UrlHelper method *Sam Stephenson*. Documentation:
<ide>
<ide> Creates a link tag of the given +name+ using an URL created by the set of +options+, unless the current
<ide> controller, action, and id are the same as the link's, in which case only the name is returned (or the
<ide> So this will render "advertiser/_ad.rhtml" and pass the local variable +ad+ for
<ide> the template to display.
<ide>
<del>* Improved send_file by allowing a wide range of options to be applied [Jeremy Kemper]:
<add>* Improved send_file by allowing a wide range of options to be applied *Jeremy Kemper*:
<ide>
<ide> Sends the file by streaming it 4096 bytes at a time. This way the
<ide> whole file doesn't need to be read into memory at once. This makes
<ide>
<ide> * Fixed that exceptions raised during filters are now also caught by the default rescues
<ide>
<del>* Added new around_filter for doing before and after filtering with a single object [Florian Weber]:
<add>* Added new around_filter for doing before and after filtering with a single object *Florian Weber*:
<ide>
<ide> class WeblogController < ActionController::Base
<ide> around_filter BenchmarkingFilter.new
<ide> end
<ide> end
<ide>
<del>* Added the options for specifying a different name and id for the form helper methods than what is guessed [Florian Weber]:
<add>* Added the options for specifying a different name and id for the form helper methods than what is guessed *Florian Weber*:
<ide>
<ide> text_field "post", "title"
<ide> ...just gives: <input id="post_title" name="post[title]" size="30" type="text" value="" /> | 1 |
Javascript | Javascript | remove check in renderdidsuspenddelayifpossible | df61e708c82134133e002f8559c19d4897204b54 | <ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.new.js
<ide> export function renderDidSuspend(): void {
<ide> }
<ide>
<ide> export function renderDidSuspendDelayIfPossible(): void {
<del> if (
<del> workInProgressRootExitStatus === RootInProgress ||
<del> workInProgressRootExitStatus === RootSuspended ||
<del> workInProgressRootExitStatus === RootErrored
<del> ) {
<del> workInProgressRootExitStatus = RootSuspendedWithDelay;
<del> }
<add> workInProgressRootExitStatus = RootSuspendedWithDelay;
<ide>
<ide> // Check if there are updates that we skipped tree that might have unblocked
<ide> // this render.
<ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.old.js
<ide> export function renderDidSuspend(): void {
<ide> }
<ide>
<ide> export function renderDidSuspendDelayIfPossible(): void {
<del> if (
<del> workInProgressRootExitStatus === RootInProgress ||
<del> workInProgressRootExitStatus === RootSuspended ||
<del> workInProgressRootExitStatus === RootErrored
<del> ) {
<del> workInProgressRootExitStatus = RootSuspendedWithDelay;
<del> }
<add> workInProgressRootExitStatus = RootSuspendedWithDelay;
<ide>
<ide> // Check if there are updates that we skipped tree that might have unblocked
<ide> // this render. | 2 |
Python | Python | fix naming convention | 6a550005471f76754cbe7bcf6652bb44fd494bfc | <ide><path>glances/core/glances_client.py
<ide> # Import Glances libs
<ide> from glances.core.glances_globals import version
<ide> from glances.core.glances_stats import GlancesStatsClient
<del>from glances.outputs.glances_curses import glancesCurses
<add>from glances.outputs.glances_curses import GlancesCurses
<ide>
<ide>
<del>class GlancesClient():
<add>class GlancesClient(object):
<ide> """
<ide> This class creates and manages the TCP client
<ide> """
<ide> def login(self):
<ide> self.stats.load_limits(self.config)
<ide>
<ide> # Init screen
<del> self.screen = glancesCurses(args=self.args)
<add> self.screen = GlancesCurses(args=self.args)
<ide>
<ide> # Return result
<ide> return ret
<ide> def end(self):
<ide> End of the client session
<ide> """
<ide> self.screen.end()
<del>
<ide><path>glances/core/glances_globals.py
<ide> # ============================================
<ide>
<ide> # glances_processes for processcount and processlist plugins
<del>from glances.core.glances_processes import glancesProcesses
<del>glances_processes = glancesProcesses()
<add>from glances.core.glances_processes import GlancesProcesses
<add>glances_processes = GlancesProcesses()
<ide>
<ide> # The global instance for the logs
<del>from glances.core.glances_logs import glancesLogs
<del>glances_logs = glancesLogs()
<add>from glances.core.glances_logs import GlancesLogs
<add>glances_logs = GlancesLogs()
<ide><path>glances/core/glances_logs.py
<ide> from glances.core.glances_globals import glances_processes
<ide>
<ide>
<del>class glancesLogs:
<add>class GlancesLogs(object):
<ide> """
<ide> Manage logs inside the Glances software
<ide> Logs is a list of list (stored in the self.logs_list var)
<ide><path>glances/core/glances_main.py
<ide> def __hash_password(self, plain_password):
<ide> """
<ide> Hash a plain password and return the hashed one
<ide> """
<del> from glances.core.glances_password import glancesPassword
<add> from glances.core.glances_password import GlancesPassword
<ide>
<del> password = glancesPassword()
<add> password = GlancesPassword()
<ide>
<ide> return password.hash_password(plain_password)
<ide>
<ide> def __get_password(self, description='', confirm=False, clear=False):
<ide> - with confirmation if confirm = True
<ide> - plain (clear password) if clear = True
<ide> """
<del> from glances.core.glances_password import glancesPassword
<add> from glances.core.glances_password import GlancesPassword
<ide>
<del> password = glancesPassword()
<add> password = GlancesPassword()
<ide>
<ide> return password.get_password(description, confirm, clear)
<ide>
<ide><path>glances/core/glances_monitor_list.py
<ide> from glances.core.glances_globals import glances_processes
<ide>
<ide>
<del>class monitorList:
<add>class MonitorList(object):
<ide> """
<ide> This class describes the optionnal monitored processes list
<ide> A list of 'important' processes to monitor.
<ide> def __init__(self, config):
<ide>
<ide> if self.config is not None and self.config.has_section('monitor'):
<ide> # Process monitoring list
<del> self.__setMonitorList('monitor', 'list')
<add> self.__set_monitor_list('monitor', 'list')
<ide> else:
<ide> self.__monitor_list = []
<ide>
<del> def __setMonitorList(self, section, key):
<add> def __set_monitor_list(self, section, key):
<ide> """
<ide> Init the monitored processes list
<ide> The list is defined in the Glances configuration file
<ide><path>glances/core/glances_password.py
<ide> pass
<ide>
<ide>
<del>class glancesPassword:
<add>class GlancesPassword(object):
<ide> """
<ide> Manage password
<ide> """
<ide><path>glances/core/glances_processes.py
<ide> # You should have received a copy of the GNU Lesser General Public License
<ide> # along with this program. If not, see <http://www.gnu.org/licenses/>.
<ide>
<del>import psutil
<del>
<del># Import Glances lib
<ide> from glances.core.glances_globals import is_bsd, is_mac, is_windows
<ide> from glances.core.glances_timer import Timer, getTimeSinceLastUpdate
<ide>
<add>import psutil
<add>
<ide>
<del>class glancesProcesses:
<add>class GlancesProcesses(object):
<ide> """
<ide> Get processed stats using the PsUtil lib
<ide> """
<ide><path>glances/core/glances_server.py
<ide> def authenticate(self, headers):
<ide> assert basic == 'Basic', 'Only basic authentication supported'
<ide> # Encoded portion of the header is a string
<ide> # Need to convert to bytestring
<del> encodedByteString = encoded.encode()
<add> encoded_byte_string = encoded.encode()
<ide> # Decode Base64 byte String to a decoded Byte String
<del> decodedBytes = b64decode(encodedByteString)
<add> decoded_bytes = b64decode(encoded_byte_string)
<ide> # Convert from byte string to a regular String
<del> decodedString = decodedBytes.decode()
<add> decoded_string = decoded_bytes.decode()
<ide> # Get the username and password from the string
<del> (username, _, password) = decodedString.partition(':')
<add> (username, _, password) = decoded_string.partition(':')
<ide> # Check that username and password match internal global dictionary
<ide> return self.check_user(username, password)
<ide>
<ide> def check_user(self, username, password):
<ide> # Check username and password in the dictionnary
<ide> if username in self.server.user_dict:
<del> from glances.core.glances_password import glancesPassword
<add> from glances.core.glances_password import GlancesPassword
<ide>
<del> pwd = glancesPassword()
<add> pwd = GlancesPassword()
<ide>
<ide> return pwd.check_password(self.server.user_dict[username], password)
<ide> else:
<ide> def __init__(self, bind_address, bind_port=61209,
<ide> requestHandler)
<ide>
<ide>
<del>class GlancesInstance():
<add>class GlancesInstance(object):
<ide> """
<ide> All the methods of this class are published as XML RPC methods
<ide> """
<ide> def __getattr__(self, item):
<ide> raise AttributeError(item)
<ide>
<ide>
<del>class GlancesServer():
<add>class GlancesServer(object):
<ide> """
<ide> This class creates and manages the TCP server
<ide> """
<ide><path>glances/core/glances_standalone.py
<ide>
<ide> # Import Glances libs
<ide> from glances.core.glances_stats import GlancesStats
<del>from glances.outputs.glances_curses import glancesCurses
<add>from glances.outputs.glances_curses import GlancesCurses
<ide>
<ide>
<del>class GlancesStandalone():
<add>class GlancesStandalone(object):
<ide> """
<ide> This class creates and manages the Glances standalone session
<ide> """
<ide> def __init__(self, config=None, args=None):
<ide>
<ide> # Init CSV output
<ide> if args.output_csv is not None:
<del> from glances.outputs.glances_csv import glancesCSV
<add> from glances.outputs.glances_csv import GlancesCSV
<ide>
<del> self.csvoutput = glancesCSV(args=args)
<add> self.csvoutput = GlancesCSV(args=args)
<ide> self.csv_tag = True
<ide> else:
<ide> self.csv_tag = False
<ide>
<ide> # Init screen
<del> self.screen = glancesCurses(args=args)
<add> self.screen = GlancesCurses(args=args)
<ide>
<ide> def serve_forever(self):
<ide> """
<ide><path>glances/core/glances_timer.py
<ide> def getTimeSinceLastUpdate(IOType):
<ide> return time_since_update
<ide>
<ide>
<del>class Timer:
<add>class Timer(object):
<ide> """
<ide> The timer class
<ide> A simple chrono
<ide> def set(self, duration):
<ide>
<ide> def finished(self):
<ide> return time() > self.target
<del>
<ide><path>glances/core/glances_webserver.py
<ide>
<ide> # Import Glances libs
<ide> from glances.core.glances_stats import GlancesStats
<del>from glances.outputs.glances_bottle import glancesBottle
<add>from glances.outputs.glances_bottle import GlancesBottle
<ide>
<ide>
<del>class GlancesWebServer():
<add>class GlancesWebServer(object):
<ide> """
<ide> This class creates and manages the Glances Web Server session
<ide> """
<ide> def __init__(self, config=None, args=None):
<ide> self.stats.update()
<ide>
<ide> # Init the Bottle Web server
<del> self.web = glancesBottle(args=args)
<add> self.web = GlancesBottle(args=args)
<ide>
<ide> def serve_forever(self):
<ide> """
<ide><path>glances/outputs/glances_bottle.py
<ide> sys.exit(1)
<ide>
<ide>
<del>class glancesBottle:
<add>class GlancesBottle(object):
<ide> """
<ide> This class manage the Bottle Web Server
<ide> """
<ide> def display_plugin(self, plugin_name, plugin_stats):
<ide> if m['msg'].split(' ', 1)[0] != '':
<ide> tpl += '<span class="cell" id="%s"> %s</span>' % \
<ide> (self.__style_list[m['decoration']],
<del> m['msg'].split(' ', 1)[0].replace(' ', ' ')[:20])
<add> m['msg'].split(' ', 1)[0].replace(' ', ' ')[:20])
<ide> elif m['optional']:
<ide> # Manage optional stats (responsive design)
<ide> tpl += '<span class="cell hide" id="%s">%s</span>' % \
<ide><path>glances/outputs/glances_colorconsole.py
<ide> def get(self, default=None):
<ide> return default
<ide>
<ide>
<del>class Screen():
<add>class Screen(object):
<ide>
<ide> COLOR_DEFAULT_WIN = '0F' # 07'#'0F'
<ide> COLOR_BK_DEFAULT = colorconsole.terminal.colors["BLACK"]
<ide> def restore_buffered_mode(self):
<ide> return None
<ide>
<ide>
<del>class WCurseLight():
<add>class WCurseLight(object):
<ide>
<ide> COLOR_WHITE = colorconsole.terminal.colors["WHITE"]
<ide> COLOR_RED = colorconsole.terminal.colors["RED"]
<ide><path>glances/outputs/glances_csv.py
<ide> csv_stats_list = ['cpu', 'load', 'mem', 'memswap']
<ide>
<ide>
<del>class glancesCSV:
<add>class GlancesCSV(object):
<ide> """
<ide> This class manages the CSV output
<ide> """
<ide><path>glances/outputs/glances_curses.py
<ide> curses = WCurseLight()
<ide>
<ide>
<del>class glancesCurses:
<add>class GlancesCurses(object):
<ide> """
<ide> This class manage the curses display (and key pressed)
<ide> """
<ide> def __init__(self, args=None):
<ide> self.term_window.nodelay(1)
<ide> self.pressedkey = -1
<ide>
<del> def __getkey(self, window):
<add> def __get_key(self, window):
<ide> """
<ide> A getKey function to catch ESC key AND Numlock key (issue #163)
<ide> """
<ide> def __getkey(self, window):
<ide> else:
<ide> return keycode[0]
<ide>
<del> def __catchKey(self):
<add> def __catch_key(self):
<ide> # Get key
<del> #~ self.pressedkey = self.term_window.getch()
<del> self.pressedkey = self.__getkey(self.term_window)
<add> # ~ self.pressedkey = self.term_window.getch()
<add> self.pressedkey = self.__get_key(self.term_window)
<ide>
<ide> # Actions...
<ide> if self.pressedkey == ord('\x1b') or self.pressedkey == ord('q'):
<ide> def update(self, stats, cs_status="None"):
<ide> countdown = Timer(self.__refresh_time)
<ide> while (not countdown.finished()):
<ide> # Getkey
<del> if self.__catchKey() > -1:
<add> if self.__catch_key() > -1:
<ide> # flush display
<ide> self.flush(stats, cs_status=cs_status)
<ide> # Wait 100ms...
<ide><path>glances/plugins/glances_batpercent.py
<ide> def __init__(self, args=None):
<ide> GlancesPlugin.__init__(self, args=args)
<ide>
<ide> # Init the sensor class
<del> self.glancesgrabbat = glancesGrabBat()
<add> self.glancesgrabbat = GlancesGrabBat()
<ide>
<ide> # We do not want to display the stat in a dedicated area
<ide> # The HDD temp is displayed within the sensors plugin
<ide> def update(self):
<ide> return self.stats
<ide>
<ide>
<del>class glancesGrabBat:
<add>class GlancesGrabBat(object):
<ide> """
<ide> Get batteries stats using the Batinfo library
<ide> """
<ide><path>glances/plugins/glances_core.py
<ide> # You should have received a copy of the GNU Lesser General Public License
<ide> # along with this program. If not, see <http://www.gnu.org/licenses/>.
<ide>
<del>import psutil
<del>
<ide> from glances.plugins.glances_plugin import GlancesPlugin
<ide>
<add>import psutil
<add>
<ide>
<ide> class Plugin(GlancesPlugin):
<ide> """
<ide><path>glances/plugins/glances_cpu.py
<ide> Glances CPU plugin
<ide> """
<ide>
<del>import psutil
<del>
<ide> from glances.plugins.glances_plugin import GlancesPlugin
<ide>
<add>import psutil
<add>
<ide> # SNMP OID
<ide> # percentage of user CPU time: .1.3.6.1.4.1.2021.11.9.0
<ide> # percentages of system CPU time: .1.3.6.1.4.1.2021.11.10.0
<ide><path>glances/plugins/glances_diskio.py
<ide> Glances DiskIO plugin
<ide> """
<ide>
<del>import psutil
<del>
<ide> # Import Glances libs
<ide> from glances.core.glances_timer import getTimeSinceLastUpdate
<ide> from glances.plugins.glances_plugin import GlancesPlugin
<ide>
<add>import psutil
<add>
<ide>
<ide> class Plugin(GlancesPlugin):
<ide> """
<ide><path>glances/plugins/glances_fs.py
<ide> # You should have received a copy of the GNU Lesser General Public License
<ide> # along with this program. If not, see <http://www.gnu.org/licenses/>.
<ide>
<del>import psutil
<del>
<ide> from glances.plugins.glances_plugin import GlancesPlugin
<ide>
<add>import psutil
<add>
<ide> # SNMP OID
<ide> # The snmpd.conf needs to be edited.
<ide> # Add the following to enable it on all disk
<ide><path>glances/plugins/glances_hddtemp.py
<ide> def __init__(self, args=None):
<ide> GlancesPlugin.__init__(self, args=args)
<ide>
<ide> # Init the sensor class
<del> self.glancesgrabhddtemp = glancesGrabHDDTemp()
<add> self.glancesgrabhddtemp = GlancesGrabHDDTemp()
<ide>
<ide> # We do not want to display the stat in a dedicated area
<ide> # The HDD temp is displayed within the sensors plugin
<ide> def update(self):
<ide> return self.stats
<ide>
<ide>
<del>class glancesGrabHDDTemp:
<add>class GlancesGrabHDDTemp(object):
<ide> """
<ide> Get hddtemp stats using a socket connection
<ide> """
<ide><path>glances/plugins/glances_mem.py
<ide> Glances virtual memory plugin
<ide> """
<ide>
<del>import psutil
<del>
<ide> from glances.plugins.glances_plugin import GlancesPlugin
<ide>
<add>import psutil
<add>
<ide> # SNMP OID
<ide> # Total RAM in machine: .1.3.6.1.4.1.2021.4.5.0
<ide> # Total RAM used: .1.3.6.1.4.1.2021.4.6.0
<ide><path>glances/plugins/glances_memswap.py
<ide> Glances swap memory plugin
<ide> """
<ide>
<del>import psutil
<del>
<ide> from glances.plugins.glances_plugin import GlancesPlugin
<ide>
<add>import psutil
<add>
<ide> # SNMP OID
<ide> # Total Swap Size: .1.3.6.1.4.1.2021.4.3.0
<ide> # Available Swap Space: .1.3.6.1.4.1.2021.4.4.0
<ide><path>glances/plugins/glances_monitor.py
<ide> # along with this program. If not, see <http://www.gnu.org/licenses/>.
<ide>
<ide> # Import Glances lib
<del>from glances.core.glances_monitor_list import monitorList as glancesMonitorList
<add>from glances.core.glances_monitor_list import MonitorList as glancesMonitorList
<ide> from glances.plugins.glances_plugin import GlancesPlugin
<ide>
<ide>
<ide><path>glances/plugins/glances_network.py
<ide> Glances Network interface plugin
<ide> """
<ide>
<del># Import system libs
<del>import psutil
<del>
<del># Import Glances lib
<ide> from glances.core.glances_timer import getTimeSinceLastUpdate
<ide> from glances.plugins.glances_plugin import GlancesPlugin
<ide>
<add>import psutil
<add>
<ide> # SNMP OID
<ide> # http://www.net-snmp.org/docs/mibs/interfaces.html
<ide> # Dict key = interface_name
<ide> def msg_curse(self, args=None):
<ide> Return the dict to displayoid in the curse interface
<ide> """
<ide>
<del> #!!! TODO: Add alert on network interface bitrate
<add> # !!! TODO: Add alert on network interface bitrate
<ide>
<ide> # Init the return message
<ide> ret = []
<ide><path>glances/plugins/glances_percpu.py
<ide> CPU stats (per cpu)
<ide> """
<ide>
<del># Check for psutil already done in the glances_core script
<del>import psutil
<del>
<ide> # Import Glances libs
<ide> from glances.plugins.glances_plugin import GlancesPlugin
<ide>
<add># Check for psutil already done in the glances_core script
<add>import psutil
<add>
<ide>
<ide> class Plugin(GlancesPlugin):
<ide> """
<ide><path>glances/plugins/glances_plugin.py
<ide> def msg_curse(self, args):
<ide> def get_stats_display(self, args=None):
<ide> # Return a dict with all the information needed to display the stat
<ide> # key | description
<del> #----------------------------
<add> # ----------------------------
<ide> # display | Display the stat (True or False)
<ide> # msgdict | Message to display (list of dict [{ 'msg': msg, 'decoration': decoration } ... ])
<ide> # column | column number
<ide><path>glances/plugins/glances_psutilversion.py
<ide> # You should have received a copy of the GNU Lesser General Public License
<ide> # along with this program. If not, see <http://www.gnu.org/licenses/>.
<ide>
<del>from psutil import __version__ as __psutil_version
<del>
<ide> from glances.plugins.glances_plugin import GlancesPlugin
<ide>
<add>from psutil import __version__ as __psutil_version
<add>
<ide>
<ide> class Plugin(GlancesPlugin):
<ide> """
<ide><path>glances/plugins/glances_sensors.py
<ide> def __init__(self, args=None):
<ide> GlancesPlugin.__init__(self, args=args)
<ide>
<ide> # Init the sensor class
<del> self.glancesgrabsensors = glancesGrabSensors()
<add> self.glancesgrabsensors = GlancesGrabSensors()
<ide>
<ide> # Instance for the HDDTemp Plugin in order to display the hard disks temperatures
<ide> self.hddtemp_plugin = HddTempPlugin()
<ide> def msg_curse(self, args=None):
<ide> return ret
<ide>
<ide>
<del>class glancesGrabSensors:
<add>class GlancesGrabSensors(object):
<ide> """
<ide> Get sensors stats using the PySensors library
<ide> """
<ide><path>glances/plugins/glances_system.py
<ide> snmp_oid = {'hostname': '1.3.6.1.2.1.1.5.0',
<ide> 'os_name': '1.3.6.1.2.1.1.1.0'}
<ide>
<add>
<ide> class Plugin(GlancesPlugin):
<ide> """
<ide> Glances' Host/System Plugin
<ide><path>glances/plugins/glances_uptime.py
<ide> # Import system libs
<ide> from datetime import datetime, timedelta
<ide>
<del># Check for psutil already done in the glances_core script
<del>import psutil
<del>
<ide> # Import Glances libs
<ide> from glances.plugins.glances_plugin import GlancesPlugin
<ide>
<add># Check for psutil already done in the glances_core script
<add>import psutil
<add>
<ide> # SNMP OID
<ide> snmp_oid = {'_uptime': '1.3.6.1.2.1.1.3.0'}
<ide>
<add>
<ide> class Plugin(GlancesPlugin):
<ide> """
<ide> Glances' Uptime Plugin | 31 |
Javascript | Javascript | add strict equalities in src/shared/fonts_utils.js | 42e541a67181ba8a92ad071b16302374fcf9084e | <ide><path>src/shared/fonts_utils.js
<ide> function readCharset(aStream, aCharstrings) {
<ide> sid = aStream.getByte() << 8 | aStream.getByte();
<ide> charset[CFFStrings[sid]] = readCharstringEncoding(aCharstrings[i]);
<ide> }
<del> } else if (format == 1) {
<add> } else if (format === 1) {
<ide> for (i = 1; i < count + 1; i++) {
<ide> var first = aStream.getByte();
<ide> first = (first << 8) | aStream.getByte();
<ide> function readCharstringEncoding(aString) {
<ide>
<ide> var count = aString.length;
<ide> for (var i = 0; i < count; ) {
<del> var value = aString[i++];
<add> var value = aString[i++] | 0;
<ide> var token = null;
<ide>
<ide> if (value < 0) {
<ide> continue;
<ide> } else if (value <= 11) {
<ide> token = CFFEncodingMap[value];
<del> } else if (value == 12) {
<add> } else if (value === 12) {
<ide> token = CFFEncodingMap[value][aString[i++]];
<ide> } else if (value <= 18) {
<ide> token = CFFEncodingMap[value];
<ide> function readCharstringEncoding(aString) {
<ide> token = CFFEncodingMap[value];
<ide> } else if (value <= 27) {
<ide> token = CFFEncodingMap[value];
<del> } else if (value == 28) {
<add> } else if (value === 28) {
<ide> token = aString[i++] << 8 | aString[i++];
<ide> } else if (value <= 31) {
<ide> token = CFFEncodingMap[value];
<ide> function readCharstringEncoding(aString) {
<ide> token = (value - 247) * 256 + aString[i++] + 108;
<ide> } else if (value < 255) {
<ide> token = -(value - 251) * 256 - aString[i++] - 108;
<del> } else {// value == 255
<add> } else { // value === 255
<ide> token = aString[i++] << 24 | aString[i++] << 16 |
<ide> aString[i++] << 8 | aString[i];
<ide> }
<ide> function readFontDictData(aString, aMap) {
<ide>
<ide> var count = aString.length;
<ide> for (var i = 0; i < count; i) {
<del> var value = aString[i++];
<add> var value = aString[i++] | 0;
<ide> var token = null;
<ide>
<del> if (value == 12) {
<add> if (value === 12) {
<ide> token = aMap[value][aString[i++]];
<del> } else if (value == 28) {
<add> } else if (value === 28) {
<ide> token = aString[i++] << 8 | aString[i++];
<del> } else if (value == 29) {
<add> } else if (value === 29) {
<ide> token = aString[i++] << 24 |
<ide> aString[i++] << 16 |
<ide> aString[i++] << 8 |
<ide> aString[i++];
<del> } else if (value == 30) {
<add> } else if (value === 30) {
<ide> token = '';
<ide> var parsed = false;
<ide> while (!parsed) {
<ide> function readFontDictData(aString, aMap) {
<ide> token = (value - 247) * 256 + aString[i++] + 108;
<ide> } else if (value <= 254) {
<ide> token = -(value - 251) * 256 - aString[i++] - 108;
<del> } else if (value == 255) {
<add> } else if (value === 255) {
<ide> error('255 is not a valid DICT command');
<ide> }
<ide>
<ide> function readFontIndexData(aStream, aIsByte) {
<ide> }
<ide>
<ide> dump('Found ' + count + ' objects at offsets :' +
<del> offsets + ' (offsize: ' + offsize + ')');
<add> offsets + ' (offsize: ' + offsize + ')');
<ide>
<ide> // Now extract the objects
<ide> var relativeOffset = aStream.pos;
<ide> var Type2Parser = function type2Parser(aFilePath) {
<ide> var charsetEntry = font.get('charset');
<ide> if (charsetEntry === 0) {
<ide> error('Need to support CFFISOAdobeCharset');
<del> } else if (charsetEntry == 1) {
<add> } else if (charsetEntry === 1) {
<ide> error('Need to support CFFExpert');
<del> } else if (charsetEntry == 2) {
<add> } else if (charsetEntry === 2) {
<ide> error('Need to support CFFExpertSubsetCharset');
<ide> } else {
<ide> aStream.pos = charsetEntry; | 1 |
Python | Python | update gyp to 828ce09 | cb5da7b443513627436a276ea4249779930d4648 | <ide><path>tools/gyp/pylib/gyp/common.py
<ide> def close(self):
<ide> return Writer()
<ide>
<ide>
<add>def EnsureDirExists(path):
<add> """Make sure the directory for |path| exists."""
<add> try:
<add> os.makedirs(os.path.dirname(path))
<add> except OSError:
<add> pass
<add>
<add>
<ide> def GetFlavor(params):
<ide> """Returns |params.flavor| if it's set, the system's default flavor else."""
<ide> flavors = {
<ide><path>tools/gyp/pylib/gyp/generator/android.py
<ide> def Write(self, qualified_target, relative_target, base_path, output_filename,
<ide> spec, configs: gyp info
<ide> part_of_all: flag indicating this target is part of 'all'
<ide> """
<del> make.ensure_directory_exists(output_filename)
<add> gyp.common.EnsureDirExists(output_filename)
<ide>
<ide> self.fp = open(output_filename, 'w')
<ide>
<ide> def CalculateMakefilePath(build_file, base_name):
<ide> makefile_path = os.path.join(options.toplevel_dir, makefile_name)
<ide> assert not options.generator_output, (
<ide> 'The Android backend does not support options.generator_output.')
<del> make.ensure_directory_exists(makefile_path)
<add> gyp.common.EnsureDirExists(makefile_path)
<ide> root_makefile = open(makefile_path, 'w')
<ide>
<ide> root_makefile.write(header)
<ide><path>tools/gyp/pylib/gyp/generator/cmake.py
<ide> def NormjoinPath(base_path, rel_path):
<ide> return os.path.normpath(os.path.join(base_path, rel_path))
<ide>
<ide>
<del>def EnsureDirectoryExists(path):
<del> """Python version of 'mkdir -p'."""
<del> dirPath = os.path.dirname(path)
<del> if dirPath and not os.path.exists(dirPath):
<del> os.makedirs(dirPath)
<del>
<del>
<ide> def CMakeStringEscape(a):
<ide> """Escapes the string 'a' for use inside a CMake string.
<ide>
<ide> def GenerateOutputForConfig(target_list, target_dicts, data,
<ide> toplevel_build = os.path.join(options.toplevel_dir, build_dir)
<ide>
<ide> output_file = os.path.join(toplevel_build, 'CMakeLists.txt')
<del> EnsureDirectoryExists(output_file)
<add> gyp.common.EnsureDirExists(output_file)
<ide>
<ide> output = open(output_file, 'w')
<ide> output.write('cmake_minimum_required(VERSION 2.8.8 FATAL_ERROR)\n')
<ide><path>tools/gyp/pylib/gyp/generator/eclipse.py
<ide> def GenerateOutputForConfig(target_list, target_dicts, data, params,
<ide> shared_intermediate_dirs = [os.path.join(toplevel_build, 'obj', 'gen'),
<ide> os.path.join(toplevel_build, 'gen')]
<ide>
<del> if not os.path.exists(toplevel_build):
<del> os.makedirs(toplevel_build)
<del> out = open(os.path.join(toplevel_build, 'eclipse-cdt-settings.xml'), 'w')
<add> out_name = os.path.join(toplevel_build, 'eclipse-cdt-settings.xml')
<add> gyp.common.EnsureDirExists(out_name)
<add> out = open(out_name, 'w')
<ide>
<ide> out.write('<?xml version="1.0" encoding="UTF-8"?>\n')
<ide> out.write('<cdtprojectproperties>\n')
<ide><path>tools/gyp/pylib/gyp/generator/make.py
<ide> def CalculateGeneratorInputInfo(params):
<ide> }
<ide>
<ide>
<del>def ensure_directory_exists(path):
<del> dir = os.path.dirname(path)
<del> if dir and not os.path.exists(dir):
<del> os.makedirs(dir)
<del>
<del>
<ide> # The .d checking code below uses these functions:
<ide> # wildcard, sort, foreach, shell, wordlist
<ide> # wildcard can handle spaces, the rest can't.
<ide> def Write(self, qualified_target, base_path, output_filename, spec, configs,
<ide> spec, configs: gyp info
<ide> part_of_all: flag indicating this target is part of 'all'
<ide> """
<del> ensure_directory_exists(output_filename)
<add> gyp.common.EnsureDirExists(output_filename)
<ide>
<ide> self.fp = open(output_filename, 'w')
<ide>
<ide> def WriteSubMake(self, output_filename, makefile_path, targets, build_dir):
<ide> targets: list of "all" targets for this sub-project
<ide> build_dir: build output directory, relative to the sub-project
<ide> """
<del> ensure_directory_exists(output_filename)
<add> gyp.common.EnsureDirExists(output_filename)
<ide> self.fp = open(output_filename, 'w')
<ide> self.fp.write(header)
<ide> # For consistency with other builders, put sub-project build output in the
<ide> def CalculateMakefilePath(build_file, base_name):
<ide> make_global_settings += (
<ide> 'ifneq (,$(filter $(origin %s), undefined default))\n' % key)
<ide> # Let gyp-time envvars win over global settings.
<del> if key in os.environ:
<del> value = os.environ[key]
<add> env_key = key.replace('.', '_') # CC.host -> CC_host
<add> if env_key in os.environ:
<add> value = os.environ[env_key]
<ide> make_global_settings += ' %s = %s\n' % (key, value)
<ide> make_global_settings += 'endif\n'
<ide> else:
<ide> def CalculateMakefilePath(build_file, base_name):
<ide>
<ide> header_params['make_global_settings'] = make_global_settings
<ide>
<del> ensure_directory_exists(makefile_path)
<add> gyp.common.EnsureDirExists(makefile_path)
<ide> root_makefile = open(makefile_path, 'w')
<ide> root_makefile.write(SHARED_HEADER % header_params)
<ide> # Currently any versions have the same effect, but in future the behavior
<ide><path>tools/gyp/pylib/gyp/generator/msvs.py
<ide> import gyp.MSVSVersion as MSVSVersion
<ide> from gyp.common import GypError
<ide>
<add># TODO: Remove once bots are on 2.7, http://crbug.com/241769
<add>def _import_OrderedDict():
<add> import collections
<add> try:
<add> return collections.OrderedDict
<add> except AttributeError:
<add> import gyp.ordered_dict
<add> return gyp.ordered_dict.OrderedDict
<add>OrderedDict = _import_OrderedDict()
<add>
<ide>
<ide> # Regular expression for validating Visual Studio GUIDs. If the GUID
<ide> # contains lowercase hex letters, MSVS will be fine. However,
<ide> def _ConvertSourcesToFilterHierarchy(sources, prefix=None, excluded=None,
<ide> if not prefix: prefix = []
<ide> result = []
<ide> excluded_result = []
<del> folders = collections.OrderedDict()
<ide> # Gather files into the final result, excluded, or folders.
<ide> for s in sources:
<ide> if len(s) == 1:
<ide> def _ConvertSourcesToFilterHierarchy(sources, prefix=None, excluded=None,
<ide> else:
<ide> result.append(filename)
<ide> else:
<del> if not folders.get(s[0]):
<del> folders[s[0]] = []
<del> folders[s[0]].append(s[1:])
<add> contents = _ConvertSourcesToFilterHierarchy([s[1:]], prefix + [s[0]],
<add> excluded=excluded,
<add> list_excluded=list_excluded)
<add> contents = MSVSProject.Filter(s[0], contents=contents)
<add> result.append(contents)
<ide> # Add a folder for excluded files.
<ide> if excluded_result and list_excluded:
<ide> excluded_folder = MSVSProject.Filter('_excluded_files',
<ide> contents=excluded_result)
<ide> result.append(excluded_folder)
<del> # Populate all the folders.
<del> for f in folders:
<del> contents = _ConvertSourcesToFilterHierarchy(folders[f], prefix=prefix + [f],
<del> excluded=excluded,
<del> list_excluded=list_excluded)
<del> contents = MSVSProject.Filter(f, contents=contents)
<del> result.append(contents)
<del>
<ide> return result
<ide>
<ide>
<ide> def _GenerateMSVSProject(project, options, version, generator_flags):
<ide> generator_flags: dict of generator-specific flags.
<ide> """
<ide> spec = project.spec
<del> vcproj_dir = os.path.dirname(project.path)
<del> if vcproj_dir and not os.path.exists(vcproj_dir):
<del> os.makedirs(vcproj_dir)
<add> gyp.common.EnsureDirExists(project.path)
<ide>
<ide> platforms = _GetUniquePlatforms(spec)
<ide> p = MSVSProject.Writer(project.path, version, spec['target_name'],
<ide> def _GenerateMSBuildProject(project, options, version, generator_flags):
<ide> spec = project.spec
<ide> configurations = spec['configurations']
<ide> project_dir, project_file_name = os.path.split(project.path)
<del> msbuildproj_dir = os.path.dirname(project.path)
<del> if msbuildproj_dir and not os.path.exists(msbuildproj_dir):
<del> os.makedirs(msbuildproj_dir)
<add> gyp.common.EnsureDirExists(project.path)
<ide> # Prepare list of sources and excluded sources.
<ide> gyp_path = _NormalizedSource(project.build_file)
<ide> relative_path_of_gyp_file = gyp.common.RelativePath(gyp_path, project_dir)
<ide><path>tools/gyp/pylib/gyp/generator/ninja.py
<ide> def WriteLinkForArch(self, ninja_file, spec, config_name, config,
<ide> elif self.flavor == 'win':
<ide> manifest_name = self.GypPathToUniqueOutput(
<ide> self.ComputeOutputFileName(spec))
<del> ldflags, manifest_files = self.msvs_settings.GetLdflags(config_name,
<del> self.GypPathToNinja, self.ExpandSpecial, manifest_name, is_executable)
<add> ldflags, intermediate_manifest, manifest_files = \
<add> self.msvs_settings.GetLdflags(config_name, self.GypPathToNinja,
<add> self.ExpandSpecial, manifest_name,
<add> is_executable, self.toplevel_build)
<ide> ldflags = env_ldflags + ldflags
<ide> self.WriteVariableList(ninja_file, 'manifests', manifest_files)
<add> implicit_deps = implicit_deps.union(manifest_files)
<add> if intermediate_manifest:
<add> self.WriteVariableList(
<add> ninja_file, 'intermediatemanifest', [intermediate_manifest])
<ide> command_suffix = _GetWinLinkRuleNameSuffix(
<del> self.msvs_settings.IsEmbedManifest(config_name),
<del> self.msvs_settings.IsLinkIncremental(config_name))
<add> self.msvs_settings.IsEmbedManifest(config_name))
<ide> def_file = self.msvs_settings.GetDefFile(self.GypPathToNinja)
<ide> if def_file:
<ide> implicit_deps.add(def_file)
<ide> def CalculateGeneratorInputInfo(params):
<ide>
<ide> def OpenOutput(path, mode='w'):
<ide> """Open |path| for writing, creating directories if necessary."""
<del> try:
<del> os.makedirs(os.path.dirname(path))
<del> except OSError:
<del> pass
<add> gyp.common.EnsureDirExists(path)
<ide> return open(path, mode)
<ide>
<ide>
<ide> class MEMORYSTATUSEX(ctypes.Structure):
<ide> return 1
<ide>
<ide>
<del>def _GetWinLinkRuleNameSuffix(embed_manifest, link_incremental):
<add>def _GetWinLinkRuleNameSuffix(embed_manifest):
<ide> """Returns the suffix used to select an appropriate linking rule depending on
<del> whether the manifest embedding and/or incremental linking is enabled."""
<del> suffix = ''
<del> if embed_manifest:
<del> suffix += '_embed'
<del> if link_incremental:
<del> suffix += '_inc'
<del> return suffix
<add> whether the manifest embedding is enabled."""
<add> return '_embed' if embed_manifest else ''
<ide>
<ide>
<del>def _AddWinLinkRules(master_ninja, embed_manifest, link_incremental):
<add>def _AddWinLinkRules(master_ninja, embed_manifest):
<ide> """Adds link rules for Windows platform to |master_ninja|."""
<ide> def FullLinkCommand(ldcmd, out, binary_type):
<del> """Returns a one-liner written for cmd.exe to handle multiphase linker
<del> operations including manifest file generation. The command will be
<del> structured as follows:
<del> cmd /c (linkcmd1 a b) && (linkcmd2 x y) && ... &&
<del> if not "$manifests"=="" ((manifestcmd1 a b) && (manifestcmd2 x y) && ... )
<del> Note that $manifests becomes empty when no manifest file is generated."""
<del> link_commands = ['%(ldcmd)s',
<del> 'if exist %(out)s.manifest del %(out)s.manifest']
<del> mt_cmd = ('%(python)s gyp-win-tool manifest-wrapper'
<del> ' $arch $mt -nologo -manifest $manifests')
<del> if embed_manifest and not link_incremental:
<del> # Embed manifest into a binary. If incremental linking is enabled,
<del> # embedding is postponed to the re-linking stage (see below).
<del> mt_cmd += ' -outputresource:%(out)s;%(resname)s'
<del> else:
<del> # Save manifest as an external file.
<del> mt_cmd += ' -out:%(out)s.manifest'
<del> manifest_commands = [mt_cmd]
<del> if link_incremental:
<del> # There is no point in generating separate rule for the case when
<del> # incremental linking is enabled, but manifest embedding is disabled.
<del> # In that case the basic rule should be used (e.g. 'link').
<del> # See also implementation of _GetWinLinkRuleNameSuffix().
<del> assert embed_manifest
<del> # Make .rc file out of manifest, compile it to .res file and re-link.
<del> manifest_commands += [
<del> ('%(python)s gyp-win-tool manifest-to-rc $arch %(out)s.manifest'
<del> ' %(out)s.manifest.rc %(resname)s'),
<del> '%(python)s gyp-win-tool rc-wrapper $arch $rc %(out)s.manifest.rc',
<del> '%(ldcmd)s %(out)s.manifest.res']
<del> cmd = 'cmd /c %s && if not "$manifests"=="" (%s)' % (
<del> ' && '.join(['(%s)' % c for c in link_commands]),
<del> ' && '.join(['(%s)' % c for c in manifest_commands]))
<ide> resource_name = {
<ide> 'exe': '1',
<ide> 'dll': '2',
<ide> }[binary_type]
<del> return cmd % {'python': sys.executable,
<del> 'out': out,
<del> 'ldcmd': ldcmd,
<del> 'resname': resource_name}
<del>
<del> rule_name_suffix = _GetWinLinkRuleNameSuffix(embed_manifest, link_incremental)
<add> return '%(python)s gyp-win-tool link-with-manifests $arch %(embed)s ' \
<add> '%(out)s "%(ldcmd)s" %(resname)s $mt $rc "$intermediatemanifest" ' \
<add> '$manifests' % {
<add> 'python': sys.executable,
<add> 'out': out,
<add> 'ldcmd': ldcmd,
<add> 'resname': resource_name,
<add> 'embed': embed_manifest }
<add> rule_name_suffix = _GetWinLinkRuleNameSuffix(embed_manifest)
<ide> dlldesc = 'LINK%s(DLL) $dll' % rule_name_suffix.upper()
<ide> dllcmd = ('%s gyp-win-tool link-wrapper $arch '
<ide> '$ld /nologo $implibflag /DLL /OUT:$dll '
<ide> def GenerateOutputForConfig(target_list, target_dicts, data, params,
<ide> sys.executable),
<ide> rspfile='$out.rsp',
<ide> rspfile_content='$in_newline $libflags')
<del> _AddWinLinkRules(master_ninja, embed_manifest=True, link_incremental=True)
<del> _AddWinLinkRules(master_ninja, embed_manifest=True, link_incremental=False)
<del> _AddWinLinkRules(master_ninja, embed_manifest=False, link_incremental=False)
<del> # Do not generate rules for embed_manifest=False and link_incremental=True
<del> # because in that case rules for (False, False) should be used (see
<del> # implementation of _GetWinLinkRuleNameSuffix()).
<add> _AddWinLinkRules(master_ninja, embed_manifest=True)
<add> _AddWinLinkRules(master_ninja, embed_manifest=False)
<ide> else:
<ide> master_ninja.rule(
<ide> 'objc',
<ide><path>tools/gyp/pylib/gyp/input.py
<ide> def ExpandVariables(input, phase, variables, build_file):
<ide> rel_build_file_dir = build_file_dir
<ide> qualified_out_dir = generator_filelist_paths['qualified_out_dir']
<ide> path = os.path.join(qualified_out_dir, rel_build_file_dir, replacement)
<del> if not os.path.isdir(os.path.dirname(path)):
<del> os.makedirs(os.path.dirname(path))
<add> gyp.common.EnsureDirExists(path)
<ide>
<ide> replacement = gyp.common.RelativePath(path, build_file_dir)
<ide> f = gyp.common.WriteOnDiff(path)
<ide><path>tools/gyp/pylib/gyp/msvs_emulation.py
<ide> def GetPGDName(self, config, expand_special):
<ide> return output_file
<ide>
<ide> def GetLdflags(self, config, gyp_to_build_path, expand_special,
<del> manifest_base_name, is_executable):
<add> manifest_base_name, is_executable, build_dir):
<ide> """Returns the flags that need to be added to link commands, and the
<ide> manifest files."""
<ide> config = self._TargetConfig(config)
<ide> def GetLdflags(self, config, gyp_to_build_path, expand_special,
<ide> ld('DataExecutionPrevention',
<ide> map={'1': ':NO', '2': ''}, prefix='/NXCOMPAT')
<ide> ld('OptimizeReferences', map={'1': 'NOREF', '2': 'REF'}, prefix='/OPT:')
<add> ld('ForceSymbolReferences', prefix='/INCLUDE:')
<ide> ld('EnableCOMDATFolding', map={'1': 'NOICF', '2': 'ICF'}, prefix='/OPT:')
<ide> ld('LinkTimeCodeGeneration',
<ide> map={'1': '', '2': ':PGINSTRUMENT', '3': ':PGOPTIMIZE',
<ide> def GetLdflags(self, config, gyp_to_build_path, expand_special,
<ide> ldflags.append('/NXCOMPAT')
<ide>
<ide> have_def_file = filter(lambda x: x.startswith('/DEF:'), ldflags)
<del> manifest_flags, manifest_files = self._GetLdManifestFlags(
<del> config, manifest_base_name, gyp_to_build_path,
<del> is_executable and not have_def_file)
<add> manifest_flags, intermediate_manifest, manifest_files = \
<add> self._GetLdManifestFlags(config, manifest_base_name, gyp_to_build_path,
<add> is_executable and not have_def_file, build_dir)
<ide> ldflags.extend(manifest_flags)
<del> return ldflags, manifest_files
<add> return ldflags, intermediate_manifest, manifest_files
<ide>
<ide> def _GetLdManifestFlags(self, config, name, gyp_to_build_path,
<del> allow_isolation):
<del> """Returns the set of flags that need to be added to the link to generate
<del> a default manifest, as well as the list of all the manifest files to be
<del> merged by the manifest tool."""
<add> allow_isolation, build_dir):
<add> """Returns a 3-tuple:
<add> - the set of flags that need to be added to the link to generate
<add> a default manifest
<add> - the intermediate manifest that the linker will generate that should be
<add> used to assert it doesn't add anything to the merged one.
<add> - the list of all the manifest files to be merged by the manifest tool and
<add> included into the link."""
<ide> generate_manifest = self._Setting(('VCLinkerTool', 'GenerateManifest'),
<ide> config,
<ide> default='true')
<ide> if generate_manifest != 'true':
<ide> # This means not only that the linker should not generate the intermediate
<ide> # manifest but also that the manifest tool should do nothing even when
<ide> # additional manifests are specified.
<del> return ['/MANIFEST:NO'], []
<add> return ['/MANIFEST:NO'], [], []
<ide>
<ide> output_name = name + '.intermediate.manifest'
<ide> flags = [
<ide> '/MANIFEST',
<ide> '/ManifestFile:' + output_name,
<ide> ]
<ide>
<add> # Instead of using the MANIFESTUAC flags, we generate a .manifest to
<add> # include into the list of manifests. This allows us to avoid the need to
<add> # do two passes during linking. The /MANIFEST flag and /ManifestFile are
<add> # still used, and the intermediate manifest is used to assert that the
<add> # final manifest we get from merging all the additional manifest files
<add> # (plus the one we generate here) isn't modified by merging the
<add> # intermediate into it.
<add>
<add> # Always NO, because we generate a manifest file that has what we want.
<add> flags.append('/MANIFESTUAC:NO')
<add>
<ide> config = self._TargetConfig(config)
<ide> enable_uac = self._Setting(('VCLinkerTool', 'EnableUAC'), config,
<ide> default='true')
<add> manifest_files = []
<add> generated_manifest_outer = \
<add>"<?xml version='1.0' encoding='UTF-8' standalone='yes'?>" \
<add>"<assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'>%s" \
<add>"</assembly>"
<ide> if enable_uac == 'true':
<ide> execution_level = self._Setting(('VCLinkerTool', 'UACExecutionLevel'),
<ide> config, default='0')
<ide> def _GetLdManifestFlags(self, config, name, gyp_to_build_path,
<ide>
<ide> ui_access = self._Setting(('VCLinkerTool', 'UACUIAccess'), config,
<ide> default='false')
<del> flags.append('''/MANIFESTUAC:"level='%s' uiAccess='%s'"''' %
<del> (execution_level_map[execution_level], ui_access))
<add>
<add> inner = '''
<add><trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<add> <security>
<add> <requestedPrivileges>
<add> <requestedExecutionLevel level='%s' uiAccess='%s' />
<add> </requestedPrivileges>
<add> </security>
<add></trustInfo>''' % (execution_level_map[execution_level], ui_access)
<ide> else:
<del> flags.append('/MANIFESTUAC:NO')
<add> inner = ''
<add>
<add> generated_manifest_contents = generated_manifest_outer % inner
<add> generated_name = name + '.generated.manifest'
<add> # Need to join with the build_dir here as we're writing it during
<add> # generation time, but we return the un-joined version because the build
<add> # will occur in that directory. We only write the file if the contents
<add> # have changed so that simply regenerating the project files doesn't
<add> # cause a relink.
<add> build_dir_generated_name = os.path.join(build_dir, generated_name)
<add> gyp.common.EnsureDirExists(build_dir_generated_name)
<add> f = gyp.common.WriteOnDiff(build_dir_generated_name)
<add> f.write(generated_manifest_contents)
<add> f.close()
<add> manifest_files = [generated_name]
<ide>
<ide> if allow_isolation:
<ide> flags.append('/ALLOWISOLATION')
<ide>
<del> manifest_files = [output_name]
<ide> manifest_files += self._GetAdditionalManifestFiles(config,
<ide> gyp_to_build_path)
<del> return flags, manifest_files
<add> return flags, output_name, manifest_files
<ide>
<ide> def _GetAdditionalManifestFiles(self, config, gyp_to_build_path):
<ide> """Gets additional manifest files that are added to the default one
<ide> def IsUseLibraryDependencyInputs(self, config):
<ide> def IsEmbedManifest(self, config):
<ide> """Returns whether manifest should be linked into binary."""
<ide> config = self._TargetConfig(config)
<del> embed = self._Setting(('VCManifestTool', 'EmbedManifest'), config)
<add> embed = self._Setting(('VCManifestTool', 'EmbedManifest'), config,
<add> default='true')
<ide> return embed == 'true'
<ide>
<ide> def IsLinkIncremental(self, config):
<ide><path>tools/gyp/pylib/gyp/ordered_dict.py
<add># Unmodified from http://code.activestate.com/recipes/576693/
<add># other than to add MIT license header (as specified on page, but not in code).
<add># Linked from Python documentation here:
<add># http://docs.python.org/2/library/collections.html#collections.OrderedDict
<add>#
<add># This should be deleted once Py2.7 is available on all bots, see
<add># http://crbug.com/241769.
<add>#
<add># Copyright (c) 2009 Raymond Hettinger.
<add>#
<add># Permission is hereby granted, free of charge, to any person obtaining a copy
<add># of this software and associated documentation files (the "Software"), to deal
<add># in the Software without restriction, including without limitation the rights
<add># to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
<add># copies of the Software, and to permit persons to whom the Software is
<add># furnished to do so, subject to the following conditions:
<add>#
<add># The above copyright notice and this permission notice shall be included in
<add># all copies or substantial portions of the Software.
<add>#
<add># THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
<add># IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
<add># FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
<add># AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
<add># LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
<add># OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
<add># THE SOFTWARE.
<add>
<add># Backport of OrderedDict() class that runs on Python 2.4, 2.5, 2.6, 2.7 and pypy.
<add># Passes Python2.7's test suite and incorporates all the latest updates.
<add>
<add>try:
<add> from thread import get_ident as _get_ident
<add>except ImportError:
<add> from dummy_thread import get_ident as _get_ident
<add>
<add>try:
<add> from _abcoll import KeysView, ValuesView, ItemsView
<add>except ImportError:
<add> pass
<add>
<add>
<add>class OrderedDict(dict):
<add> 'Dictionary that remembers insertion order'
<add> # An inherited dict maps keys to values.
<add> # The inherited dict provides __getitem__, __len__, __contains__, and get.
<add> # The remaining methods are order-aware.
<add> # Big-O running times for all methods are the same as for regular dictionaries.
<add>
<add> # The internal self.__map dictionary maps keys to links in a doubly linked list.
<add> # The circular doubly linked list starts and ends with a sentinel element.
<add> # The sentinel element never gets deleted (this simplifies the algorithm).
<add> # Each link is stored as a list of length three: [PREV, NEXT, KEY].
<add>
<add> def __init__(self, *args, **kwds):
<add> '''Initialize an ordered dictionary. Signature is the same as for
<add> regular dictionaries, but keyword arguments are not recommended
<add> because their insertion order is arbitrary.
<add>
<add> '''
<add> if len(args) > 1:
<add> raise TypeError('expected at most 1 arguments, got %d' % len(args))
<add> try:
<add> self.__root
<add> except AttributeError:
<add> self.__root = root = [] # sentinel node
<add> root[:] = [root, root, None]
<add> self.__map = {}
<add> self.__update(*args, **kwds)
<add>
<add> def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
<add> 'od.__setitem__(i, y) <==> od[i]=y'
<add> # Setting a new item creates a new link which goes at the end of the linked
<add> # list, and the inherited dictionary is updated with the new key/value pair.
<add> if key not in self:
<add> root = self.__root
<add> last = root[0]
<add> last[1] = root[0] = self.__map[key] = [last, root, key]
<add> dict_setitem(self, key, value)
<add>
<add> def __delitem__(self, key, dict_delitem=dict.__delitem__):
<add> 'od.__delitem__(y) <==> del od[y]'
<add> # Deleting an existing item uses self.__map to find the link which is
<add> # then removed by updating the links in the predecessor and successor nodes.
<add> dict_delitem(self, key)
<add> link_prev, link_next, key = self.__map.pop(key)
<add> link_prev[1] = link_next
<add> link_next[0] = link_prev
<add>
<add> def __iter__(self):
<add> 'od.__iter__() <==> iter(od)'
<add> root = self.__root
<add> curr = root[1]
<add> while curr is not root:
<add> yield curr[2]
<add> curr = curr[1]
<add>
<add> def __reversed__(self):
<add> 'od.__reversed__() <==> reversed(od)'
<add> root = self.__root
<add> curr = root[0]
<add> while curr is not root:
<add> yield curr[2]
<add> curr = curr[0]
<add>
<add> def clear(self):
<add> 'od.clear() -> None. Remove all items from od.'
<add> try:
<add> for node in self.__map.itervalues():
<add> del node[:]
<add> root = self.__root
<add> root[:] = [root, root, None]
<add> self.__map.clear()
<add> except AttributeError:
<add> pass
<add> dict.clear(self)
<add>
<add> def popitem(self, last=True):
<add> '''od.popitem() -> (k, v), return and remove a (key, value) pair.
<add> Pairs are returned in LIFO order if last is true or FIFO order if false.
<add>
<add> '''
<add> if not self:
<add> raise KeyError('dictionary is empty')
<add> root = self.__root
<add> if last:
<add> link = root[0]
<add> link_prev = link[0]
<add> link_prev[1] = root
<add> root[0] = link_prev
<add> else:
<add> link = root[1]
<add> link_next = link[1]
<add> root[1] = link_next
<add> link_next[0] = root
<add> key = link[2]
<add> del self.__map[key]
<add> value = dict.pop(self, key)
<add> return key, value
<add>
<add> # -- the following methods do not depend on the internal structure --
<add>
<add> def keys(self):
<add> 'od.keys() -> list of keys in od'
<add> return list(self)
<add>
<add> def values(self):
<add> 'od.values() -> list of values in od'
<add> return [self[key] for key in self]
<add>
<add> def items(self):
<add> 'od.items() -> list of (key, value) pairs in od'
<add> return [(key, self[key]) for key in self]
<add>
<add> def iterkeys(self):
<add> 'od.iterkeys() -> an iterator over the keys in od'
<add> return iter(self)
<add>
<add> def itervalues(self):
<add> 'od.itervalues -> an iterator over the values in od'
<add> for k in self:
<add> yield self[k]
<add>
<add> def iteritems(self):
<add> 'od.iteritems -> an iterator over the (key, value) items in od'
<add> for k in self:
<add> yield (k, self[k])
<add>
<add> def update(*args, **kwds):
<add> '''od.update(E, **F) -> None. Update od from dict/iterable E and F.
<add>
<add> If E is a dict instance, does: for k in E: od[k] = E[k]
<add> If E has a .keys() method, does: for k in E.keys(): od[k] = E[k]
<add> Or if E is an iterable of items, does: for k, v in E: od[k] = v
<add> In either case, this is followed by: for k, v in F.items(): od[k] = v
<add>
<add> '''
<add> if len(args) > 2:
<add> raise TypeError('update() takes at most 2 positional '
<add> 'arguments (%d given)' % (len(args),))
<add> elif not args:
<add> raise TypeError('update() takes at least 1 argument (0 given)')
<add> self = args[0]
<add> # Make progressively weaker assumptions about "other"
<add> other = ()
<add> if len(args) == 2:
<add> other = args[1]
<add> if isinstance(other, dict):
<add> for key in other:
<add> self[key] = other[key]
<add> elif hasattr(other, 'keys'):
<add> for key in other.keys():
<add> self[key] = other[key]
<add> else:
<add> for key, value in other:
<add> self[key] = value
<add> for key, value in kwds.items():
<add> self[key] = value
<add>
<add> __update = update # let subclasses override update without breaking __init__
<add>
<add> __marker = object()
<add>
<add> def pop(self, key, default=__marker):
<add> '''od.pop(k[,d]) -> v, remove specified key and return the corresponding value.
<add> If key is not found, d is returned if given, otherwise KeyError is raised.
<add>
<add> '''
<add> if key in self:
<add> result = self[key]
<add> del self[key]
<add> return result
<add> if default is self.__marker:
<add> raise KeyError(key)
<add> return default
<add>
<add> def setdefault(self, key, default=None):
<add> 'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
<add> if key in self:
<add> return self[key]
<add> self[key] = default
<add> return default
<add>
<add> def __repr__(self, _repr_running={}):
<add> 'od.__repr__() <==> repr(od)'
<add> call_key = id(self), _get_ident()
<add> if call_key in _repr_running:
<add> return '...'
<add> _repr_running[call_key] = 1
<add> try:
<add> if not self:
<add> return '%s()' % (self.__class__.__name__,)
<add> return '%s(%r)' % (self.__class__.__name__, self.items())
<add> finally:
<add> del _repr_running[call_key]
<add>
<add> def __reduce__(self):
<add> 'Return state information for pickling'
<add> items = [[k, self[k]] for k in self]
<add> inst_dict = vars(self).copy()
<add> for k in vars(OrderedDict()):
<add> inst_dict.pop(k, None)
<add> if inst_dict:
<add> return (self.__class__, (items,), inst_dict)
<add> return self.__class__, (items,)
<add>
<add> def copy(self):
<add> 'od.copy() -> a shallow copy of od'
<add> return self.__class__(self)
<add>
<add> @classmethod
<add> def fromkeys(cls, iterable, value=None):
<add> '''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S
<add> and values equal to v (which defaults to None).
<add>
<add> '''
<add> d = cls()
<add> for key in iterable:
<add> d[key] = value
<add> return d
<add>
<add> def __eq__(self, other):
<add> '''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive
<add> while comparison to a regular mapping is order-insensitive.
<add>
<add> '''
<add> if isinstance(other, OrderedDict):
<add> return len(self)==len(other) and self.items() == other.items()
<add> return dict.__eq__(self, other)
<add>
<add> def __ne__(self, other):
<add> return not self == other
<add>
<add> # -- the following methods are only used in Python 2.7 --
<add>
<add> def viewkeys(self):
<add> "od.viewkeys() -> a set-like object providing a view on od's keys"
<add> return KeysView(self)
<add>
<add> def viewvalues(self):
<add> "od.viewvalues() -> an object providing a view on od's values"
<add> return ValuesView(self)
<add>
<add> def viewitems(self):
<add> "od.viewitems() -> a set-like object providing a view on od's items"
<add> return ItemsView(self)
<add>
<ide><path>tools/gyp/pylib/gyp/win_tool.py
<ide> import re
<ide> import shutil
<ide> import subprocess
<add>import string
<ide> import sys
<ide>
<ide> BASE_DIR = os.path.dirname(os.path.abspath(__file__))
<ide> def ExecLinkWrapper(self, arch, *args):
<ide> print line
<ide> return link.returncode
<ide>
<add> def ExecLinkWithManifests(self, arch, embed_manifest, out, ldcmd, resname,
<add> mt, rc, intermediate_manifest, *manifests):
<add> """A wrapper for handling creating a manifest resource and then executing
<add> a link command."""
<add> # The 'normal' way to do manifests is to have link generate a manifest
<add> # based on gathering dependencies from the object files, then merge that
<add> # manifest with other manifests supplied as sources, convert the merged
<add> # manifest to a resource, and then *relink*, including the compiled
<add> # version of the manifest resource. This breaks incremental linking, and
<add> # is generally overly complicated. Instead, we merge all the manifests
<add> # provided (along with one that includes what would normally be in the
<add> # linker-generated one, see msvs_emulation.py), and include that into the
<add> # first and only link. We still tell link to generate a manifest, but we
<add> # only use that to assert that our simpler process did not miss anything.
<add> variables = {
<add> 'python': sys.executable,
<add> 'arch': arch,
<add> 'out': out,
<add> 'ldcmd': ldcmd,
<add> 'resname': resname,
<add> 'mt': mt,
<add> 'rc': rc,
<add> 'intermediate_manifest': intermediate_manifest,
<add> 'manifests': ' '.join(manifests),
<add> }
<add> add_to_ld = ''
<add> if manifests:
<add> subprocess.check_call(
<add> '%(python)s gyp-win-tool manifest-wrapper %(arch)s %(mt)s -nologo '
<add> '-manifest %(manifests)s -out:%(out)s.manifest' % variables)
<add> if embed_manifest == 'True':
<add> subprocess.check_call(
<add> '%(python)s gyp-win-tool manifest-to-rc %(arch)s %(out)s.manifest'
<add> ' %(out)s.manifest.rc %(resname)s' % variables)
<add> subprocess.check_call(
<add> '%(python)s gyp-win-tool rc-wrapper %(arch)s %(rc)s '
<add> '%(out)s.manifest.rc' % variables)
<add> add_to_ld = ' %(out)s.manifest.res' % variables
<add> subprocess.check_call(ldcmd + add_to_ld)
<add>
<add> # Run mt.exe on the theoretically complete manifest we generated, merging
<add> # it with the one the linker generated to confirm that the linker
<add> # generated one does not add anything. This is strictly unnecessary for
<add> # correctness, it's only to verify that e.g. /MANIFESTDEPENDENCY was not
<add> # used in a #pragma comment.
<add> if manifests:
<add> # Merge the intermediate one with ours to .assert.manifest, then check
<add> # that .assert.manifest is identical to ours.
<add> subprocess.check_call(
<add> '%(python)s gyp-win-tool manifest-wrapper %(arch)s %(mt)s -nologo '
<add> '-manifest %(out)s.manifest %(intermediate_manifest)s '
<add> '-out:%(out)s.assert.manifest' % variables)
<add> assert_manifest = '%(out)s.assert.manifest' % variables
<add> our_manifest = '%(out)s.manifest' % variables
<add> # Load and normalize the manifests. mt.exe sometimes removes whitespace,
<add> # and sometimes doesn't unfortunately.
<add> with open(our_manifest, 'rb') as our_f:
<add> with open(assert_manifest, 'rb') as assert_f:
<add> our_data = our_f.read().translate(None, string.whitespace)
<add> assert_data = assert_f.read().translate(None, string.whitespace)
<add> if our_data != assert_data:
<add> os.unlink(out)
<add> def dump(filename):
<add> sys.stderr.write('%s\n-----\n' % filename)
<add> with open(filename, 'rb') as f:
<add> sys.stderr.write(f.read() + '\n-----\n')
<add> dump(intermediate_manifest)
<add> dump(our_manifest)
<add> dump(assert_manifest)
<add> sys.stderr.write(
<add> 'Linker generated manifest "%s" added to final manifest "%s" '
<add> '(result in "%s"). '
<add> 'Were /MANIFEST switches used in #pragma statements? ' % (
<add> intermediate_manifest, our_manifest, assert_manifest))
<add> return 1
<add>
<ide> def ExecManifestWrapper(self, arch, *args):
<ide> """Run manifest tool with environment set. Strip out undesirable warning
<ide> (some XML blocks are recognized by the OS loader, but not the manifest
<ide><path>tools/gyp/pylib/gyp/xcode_emulation.py
<ide> def _GetStdout(self, cmdlist):
<ide> return out.rstrip('\n')
<ide>
<ide> def _GetSdkVersionInfoItem(self, sdk, infoitem):
<del> return self._GetStdout(['xcodebuild', '-version', '-sdk', sdk, infoitem])
<add> # xcodebuild requires Xcode and can't run on Command Line Tools-only
<add> # systems from 10.7 onward.
<add> # Since the CLT has no SDK paths anyway, returning None is the
<add> # most sensible route and should still do the right thing.
<add> try:
<add> return self._GetStdout(['xcodebuild', '-version', '-sdk', sdk, infoitem])
<add> except:
<add> pass
<ide>
<ide> def _SdkRoot(self, configname):
<ide> if configname is None:
<ide> def GetCflags(self, configname, arch=None):
<ide> cflags = []
<ide>
<ide> sdk_root = self._SdkPath()
<del> if 'SDKROOT' in self._Settings():
<add> if 'SDKROOT' in self._Settings() and sdk_root:
<ide> cflags.append('-isysroot %s' % sdk_root)
<ide>
<ide> if self._Test('CLANG_WARN_CONSTANT_CONVERSION', 'YES', default='NO'):
<ide> def GetCflags(self, configname, arch=None):
<ide>
<ide> cflags += self._Settings().get('WARNING_CFLAGS', [])
<ide>
<add> if sdk_root:
<add> framework_root = sdk_root
<add> else:
<add> framework_root = ''
<ide> config = self.spec['configurations'][self.configname]
<ide> framework_dirs = config.get('mac_framework_dirs', [])
<ide> for directory in framework_dirs:
<del> cflags.append('-F' + directory.replace('$(SDKROOT)', sdk_root))
<add> cflags.append('-F' + directory.replace('$(SDKROOT)', framework_root))
<ide>
<ide> self.configname = None
<ide> return cflags
<ide> def GetLdflags(self, configname, product_dir, gyp_to_build_path, arch=None):
<ide>
<ide> self._AppendPlatformVersionMinFlags(ldflags)
<ide>
<del> if 'SDKROOT' in self._Settings():
<add> if 'SDKROOT' in self._Settings() and self._SdkPath():
<ide> ldflags.append('-isysroot ' + self._SdkPath())
<ide>
<ide> for library_path in self._Settings().get('LIBRARY_SEARCH_PATHS', []):
<ide> def GetLdflags(self, configname, product_dir, gyp_to_build_path, arch=None):
<ide> for rpath in self._Settings().get('LD_RUNPATH_SEARCH_PATHS', []):
<ide> ldflags.append('-Wl,-rpath,' + rpath)
<ide>
<add> sdk_root = self._SdkPath()
<add> if not sdk_root:
<add> sdk_root = ''
<ide> config = self.spec['configurations'][self.configname]
<ide> framework_dirs = config.get('mac_framework_dirs', [])
<ide> for directory in framework_dirs:
<del> ldflags.append('-F' + directory.replace('$(SDKROOT)', self._SdkPath()))
<add> ldflags.append('-F' + directory.replace('$(SDKROOT)', sdk_root))
<ide>
<ide> self.configname = None
<ide> return ldflags
<ide> def _GetIOSCodeSignIdentityKey(self, settings):
<ide> ['security', 'find-identity', '-p', 'codesigning', '-v'])
<ide> for line in output.splitlines():
<ide> if identity in line:
<del> assert identity not in XcodeSettings._codesigning_key_cache, (
<del> "Multiple codesigning identities for identity: %s" % identity)
<del> XcodeSettings._codesigning_key_cache[identity] = line.split()[1]
<add> fingerprint = line.split()[1]
<add> cache = XcodeSettings._codesigning_key_cache
<add> assert identity not in cache or fingerprint == cache[identity], (
<add> "Multiple codesigning fingerprints for identity: %s" % identity)
<add> XcodeSettings._codesigning_key_cache[identity] = fingerprint
<ide> return XcodeSettings._codesigning_key_cache.get(identity, '')
<ide>
<ide> def AddImplicitPostbuilds(self, configname, output, output_binary,
<ide> def _AdjustLibrary(self, library, config_name=None):
<ide> l = '-l' + m.group(1)
<ide> else:
<ide> l = library
<del> return l.replace('$(SDKROOT)', self._SdkPath(config_name))
<add>
<add> sdk_root = self._SdkPath(config_name)
<add> if not sdk_root:
<add> sdk_root = ''
<add> return l.replace('$(SDKROOT)', sdk_root)
<ide>
<ide> def AdjustLibraries(self, libraries, config_name=None):
<ide> """Transforms entries like 'Cocoa.framework' in libraries into entries like
<ide> def AdjustLibraries(self, libraries, config_name=None):
<ide> def _BuildMachineOSBuild(self):
<ide> return self._GetStdout(['sw_vers', '-buildVersion'])
<ide>
<add> # This method ported from the logic in Homebrew's CLT version check
<add> def _CLTVersion(self):
<add> # pkgutil output looks like
<add> # package-id: com.apple.pkg.CLTools_Executables
<add> # version: 5.0.1.0.1.1382131676
<add> # volume: /
<add> # location: /
<add> # install-time: 1382544035
<add> # groups: com.apple.FindSystemFiles.pkg-group com.apple.DevToolsBoth.pkg-group com.apple.DevToolsNonRelocatableShared.pkg-group
<add> STANDALONE_PKG_ID = "com.apple.pkg.DeveloperToolsCLILeo"
<add> FROM_XCODE_PKG_ID = "com.apple.pkg.DeveloperToolsCLI"
<add> MAVERICKS_PKG_ID = "com.apple.pkg.CLTools_Executables"
<add>
<add> regex = re.compile('version: (?P<version>.+)')
<add> for key in [MAVERICKS_PKG_ID, STANDALONE_PKG_ID, FROM_XCODE_PKG_ID]:
<add> try:
<add> output = self._GetStdout(['/usr/sbin/pkgutil', '--pkg-info', key])
<add> return re.search(regex, output).groupdict()['version']
<add> except:
<add> continue
<add>
<ide> def _XcodeVersion(self):
<ide> # `xcodebuild -version` output looks like
<ide> # Xcode 4.6.3
<ide> def _XcodeVersion(self):
<ide> # BuildVersion: 10M2518
<ide> # Convert that to '0463', '4H1503'.
<ide> if len(XcodeSettings._xcode_version_cache) == 0:
<del> version_list = self._GetStdout(['xcodebuild', '-version']).splitlines()
<add> try:
<add> version_list = self._GetStdout(['xcodebuild', '-version']).splitlines()
<add> # In some circumstances xcodebuild exits 0 but doesn't return
<add> # the right results; for example, a user on 10.7 or 10.8 with
<add> # a bogus path set via xcode-select
<add> # In that case this may be a CLT-only install so fall back to
<add> # checking that version.
<add> if len(version_list) < 2:
<add> raise GypError, "xcodebuild returned unexpected results"
<add> except:
<add> version = self._CLTVersion()
<add> if version:
<add> version = re.match('(\d\.\d\.?\d*)', version).groups()[0]
<add> else:
<add> raise GypError, "No Xcode or CLT version detected!"
<add> # The CLT has no build information, so we return an empty string.
<add> version_list = [version, '']
<ide> version = version_list[0]
<ide> build = version_list[-1]
<ide> # Be careful to convert "4.2" to "0420":
<ide> version = version.split()[-1].replace('.', '')
<ide> version = (version + '0' * (3 - len(version))).zfill(4)
<del> build = build.split()[-1]
<add> if build:
<add> build = build.split()[-1]
<ide> XcodeSettings._xcode_version_cache = (version, build)
<ide> return XcodeSettings._xcode_version_cache
<ide>
<ide> def _DefaultSdkRoot(self):
<ide> default_sdk_root = XcodeSettings._sdk_root_cache.get(default_sdk_path)
<ide> if default_sdk_root:
<ide> return default_sdk_root
<del> all_sdks = self._GetStdout(['xcodebuild', '-showsdks'])
<add> try:
<add> all_sdks = self._GetStdout(['xcodebuild', '-showsdks'])
<add> except:
<add> # If xcodebuild fails, there will be no valid SDKs
<add> return ''
<ide> for line in all_sdks.splitlines():
<ide> items = line.split()
<ide> if len(items) >= 3 and items[-2] == '-sdk': | 12 |
Text | Text | add changes for 1.4.5 | 1d18e60ef7776c53716622c18f6a127284a58d92 | <ide><path>CHANGELOG.md
<add><a name="1.4.5"></a>
<add># 1.4.5 permanent-internship (2015-08-28)
<add>
<add>
<add>## Bug Fixes
<add>
<add>- **$animate:** `$animate.enabled(false)` should disable animations on $animateCss as well
<add> ([c3d5e33e](https://github.com/angular/angular.js/commit/c3d5e33e18bd9e423e2d0678e85564fad1dba99f),
<add> [#12696](https://github.com/angular/angular.js/issues/12696), [#12685](https://github.com/angular/angular.js/issues/12685))
<add>- **$animateCss:**
<add> - do not throw errors when a closing timeout is fired on a removed element
<add> ([2f6b6fb7](https://github.com/angular/angular.js/commit/2f6b6fb7a1dee0ff97c5d2959b927347eeda6e8b),
<add> [#12650](https://github.com/angular/angular.js/issues/12650))
<add> - fix parse errors on older Android WebViews
<add> ([1cc9c9ca](https://github.com/angular/angular.js/commit/1cc9c9ca9d9698356ea541517b3d06ce6556c01d),
<add> [#12610](https://github.com/angular/angular.js/issues/12610))
<add> - properly handle cancellation timeouts for follow-up animations
<add> ([d8816731](https://github.com/angular/angular.js/commit/d88167318d1c69f0dbd2101c05955eb450c34fd5),
<add> [#12490](https://github.com/angular/angular.js/issues/12490), [#12359](https://github.com/angular/angular.js/issues/12359))
<add> - ensure failed animations clear the internal cache
<add> ([0a75a3db](https://github.com/angular/angular.js/commit/0a75a3db6ef265389c8c955981c2fe67bb4f7769),
<add> [#12214](https://github.com/angular/angular.js/issues/12214), [#12518](https://github.com/angular/angular.js/issues/12518), [#12381](https://github.com/angular/angular.js/issues/12381))
<add> - the transitions options delay value should be applied before class application
<add> ([0c81e9fd](https://github.com/angular/angular.js/commit/0c81e9fd25285dd757db98d458919776a1fb62fc),
<add> [#12584](https://github.com/angular/angular.js/issues/12584))
<add>- **ngAnimate:**
<add> - use requestAnimationFrame to space out child animations
<add> ([ea8016c4](https://github.com/angular/angular.js/commit/ea8016c4c8f55bc021549f342618ed869998e335),
<add> [#12669](https://github.com/angular/angular.js/issues/12669), [#12594](https://github.com/angular/angular.js/issues/12594), [#12655](https://github.com/angular/angular.js/issues/12655), [#12631](https://github.com/angular/angular.js/issues/12631), [#12612](https://github.com/angular/angular.js/issues/12612), [#12187](https://github.com/angular/angular.js/issues/12187))
<add> - only buffer rAF requests within the animation runners
<add> ([dc48aadd](https://github.com/angular/angular.js/commit/dc48aadd26bbf1797c1c408f63ffde99d67414a9),
<add> [#12280](https://github.com/angular/angular.js/issues/12280))
<add>- **ngModel:** validate pattern against the viewValue
<add> ([0e001084](https://github.com/angular/angular.js/commit/0e001084ffff8674efad289d37cb16cc4e46b50a),
<add> [#12344](https://github.com/angular/angular.js/issues/12344))
<add>- **ngResources:** support IPv6 URLs
<add> ([b643f0d3](https://github.com/angular/angular.js/commit/b643f0d3223a627ef813f0777524e25d2dd95371),
<add> [#12512](https://github.com/angular/angular.js/issues/12512), [#12532](https://github.com/angular/angular.js/issues/12532))
<add>
<add>
<add>## Breaking Changes
<add>
<add>- **ngModel:** due to [0e001084](https://github.com/angular/angular.js/commit/0e001084ffff8674efad289d37cb16cc4e46b50a),
<add>
<add>
<add>The `ngPattern` and `pattern` directives will validate the regex
<add>against the `viewValue` of `ngModel`, i.e. the value of the model
<add>before the $parsers are applied. Previously, the modelValue
<add>(the result of the $parsers) was validated.
<add>
<add>This fixes issues where `input[date]` and `input[number]` cannot
<add>be validated because the viewValue string is parsed into
<add>`Date` and `Number` respectively (starting with Angular 1.3).
<add>It also brings the directives in line with HTML5 constraint
<add>validation, which validates against the input value.
<add>
<add>This change is unlikely to cause applications to fail, because even
<add>in Angular 1.2, the value that was validated by pattern could have
<add>been manipulated by the $parsers, as all validation was done
<add>inside this pipeline.
<add>
<add>If you rely on the pattern being validated against the modelValue,
<add>you must create your own validator directive that overwrites
<add>the built-in pattern validator:
<add>
<add>```js
<add>.directive('patternModelOverwrite', function patternModelOverwriteDirective() {
<add> return {
<add> restrict: 'A',
<add> require: '?ngModel',
<add> priority: 1,
<add> compile: function() {
<add> var regexp, patternExp;
<add>
<add> return {
<add> pre: function(scope, elm, attr, ctrl) {
<add> if (!ctrl) return;
<add>
<add> attr.$observe('pattern', function(regex) {
<add> /**
<add> * The built-in directive will call our overwritten validator
<add> * (see below). We just need to update the regex.
<add> * The preLink fn guaranetees our observer is called first.
<add> */
<add> if (isString(regex) && regex.length > 0) {
<add> regex = new RegExp('^' + regex + '$');
<add> }
<add>
<add> if (regex && !regex.test) {
<add> //The built-in validator will throw at this point
<add> return;
<add> }
<add>
<add> regexp = regex || undefined;
<add> });
<add>
<add> },
<add> post: function(scope, elm, attr, ctrl) {
<add> if (!ctrl) return;
<add>
<add> regexp, patternExp = attr.ngPattern || attr.pattern;
<add>
<add> //The postLink fn guarantees we overwrite the built-in pattern validator
<add> ctrl.$validators.pattern = function(value) {
<add> return ctrl.$isEmpty(value) ||
<add> isUndefined(regexp) ||
<add> regexp.test(value);
<add> };
<add> }
<add> };
<add> }
<add> };
<add>});
<add>```
<add>
<add>
<ide> <a name="1.3.18"></a>
<ide> # 1.3.18 collective-penmanship (2015-08-18)
<ide> | 1 |
Ruby | Ruby | expand output excluded by quiet | 700e2f19f108ab3b354d939352921952247be6b2 | <ide><path>Library/Homebrew/cmd/update-report.rb
<ide> def output_update_report
<ide> EOS
<ide> end
<ide>
<del> return if new_tag.blank? || new_tag == old_tag
<add> return if new_tag.blank? || new_tag == old_tag || args.quiet?
<ide>
<ide> puts
<ide> ohai "Homebrew was updated to version #{new_tag}"
<ide> def output_update_report
<ide> More detailed release notes are available on the Homebrew Blog:
<ide> #{Formatter.url("https://brew.sh/blog/#{new_tag}")}
<ide> EOS
<del> elsif !args.quiet?
<add> else
<ide> puts <<~EOS
<ide> The changelog can be found at:
<ide> #{Formatter.url("https://github.com/Homebrew/brew/releases/tag/#{new_tag}")} | 1 |
Javascript | Javascript | remove trivial test | 2acaa41e34b6b363a0b4c35fb192f9f1a73f9286 | <ide><path>spec/config-file-spec.js
<ide> describe('ConfigFile', () => {
<ide> })
<ide> })
<ide> })
<del>
<del> describe('updating the config', () => {
<del> it('persists the data to the file', async () => {
<del> configFile = new ConfigFile(filePath)
<del> subscription = await configFile.watch()
<del> await configFile.update({foo: 'bar'})
<del> expect(fs.readFileSync(filePath, 'utf8')).toBe('foo: "bar"\n')
<del> })
<del> })
<ide> })
<ide>
<ide> function writeFileSync (filePath, content, seconds = 2) { | 1 |
Text | Text | use strong_params in example | 760662de868c0311f2e40a5e6f8982a521a3d990 | <ide><path>guides/source/engines.md
<ide> The form will be making a `POST` request to `/posts/:post_id/comments`, which wi
<ide> ```ruby
<ide> def create
<ide> @post = Post.find(params[:post_id])
<del> @comment = @post.comments.create(params[:comment])
<add> @comment = @post.comments.create(comment_params)
<ide> flash[:notice] = "Comment has been created!"
<ide> redirect_to posts_path
<ide> end
<add>
<add>private
<add>def comment_params
<add> params.require(:comment).permit(:text)
<add>end
<ide> ```
<ide>
<ide> This is the final part required to get the new comment form working. Displaying the comments however, is not quite right yet. If you were to create a comment right now you would see this error: | 1 |
Ruby | Ruby | remove dead code." | e3dcf7776ab5854cf7e0e28527cc70b79aec2c60 | <ide><path>Library/Homebrew/cmd/test-bot.rb
<ide> def resolve_test_tap
<ide> end
<ide> end
<ide>
<add> if git_url = ENV["UPSTREAM_GIT_URL"] || ENV["GIT_URL"]
<add> # Also can get tap from Jenkins GIT_URL.
<add> url_path = git_url.sub(%r{^https?://github\.com/}, "").chomp("/")
<add> begin
<add> tap = Tap.fetch(tap)
<add> return tap unless tap.core_formula_repository?
<add> rescue
<add> end
<add> end
<add>
<ide> # return nil means we are testing core repo.
<ide> end
<ide> | 1 |
Go | Go | rewrite docker rmi | 795ed6b1e511fa6713fbc9ea4e8569aab15b98ff | <ide><path>api/client.go
<ide> func (cli *DockerCli) CmdPort(args ...string) error {
<ide> // 'docker rmi IMAGE' removes all images with the name IMAGE
<ide> func (cli *DockerCli) CmdRmi(args ...string) error {
<ide> cmd := cli.Subcmd("rmi", "IMAGE [IMAGE...]", "Remove one or more images")
<add> force := cmd.Bool([]string{"f", "-force"}, false, "Force")
<ide> if err := cmd.Parse(args); err != nil {
<ide> return nil
<ide> }
<ide> func (cli *DockerCli) CmdRmi(args ...string) error {
<ide> return nil
<ide> }
<ide>
<add> v := url.Values{}
<add> if *force {
<add> v.Set("force", "1")
<add> }
<add>
<ide> var encounteredError error
<ide> for _, name := range cmd.Args() {
<del> body, _, err := readBody(cli.call("DELETE", "/images/"+name, nil, false))
<add> body, _, err := readBody(cli.call("DELETE", "/images/"+name+"?"+v.Encode(), nil, false))
<ide> if err != nil {
<ide> fmt.Fprintf(cli.err, "%s\n", err)
<ide> encounteredError = fmt.Errorf("Error: failed to remove one or more images")
<ide><path>api/server.go
<ide> func deleteImages(eng *engine.Engine, version float64, w http.ResponseWriter, r
<ide> }
<ide> var job = eng.Job("image_delete", vars["name"])
<ide> streamJSON(job, w, false)
<del> job.SetenvBool("autoPrune", version > 1.1)
<add> job.Setenv("force", r.Form.Get("force"))
<ide>
<ide> return job.Run()
<ide> }
<ide><path>integration/api_test.go
<ide> func TestGetEnabledCors(t *testing.T) {
<ide>
<ide> func TestDeleteImages(t *testing.T) {
<ide> eng := NewTestEngine(t)
<add> //we expect errors, so we disable stderr
<add> eng.Stderr = ioutil.Discard
<ide> defer mkRuntimeFromEngine(eng, t).Nuke()
<ide>
<ide> initialImages := getImages(eng, t, true, "")
<ide><path>integration/commands_test.go
<ide> func TestContainerOrphaning(t *testing.T) {
<ide> buildSomething(template2, imageName)
<ide>
<ide> // remove the second image by name
<del> resp, err := srv.DeleteImage(imageName, true)
<add> resp := engine.NewTable("", 0)
<add> if err := srv.DeleteImage(imageName, resp, true, false); err == nil {
<add> t.Fatal("Expected error, got none")
<add> }
<ide>
<ide> // see if we deleted the first image (and orphaned the container)
<ide> for _, i := range resp.Data {
<ide><path>integration/server_test.go
<ide> func TestImageTagImageDelete(t *testing.T) {
<ide> t.Errorf("Expected %d images, %d found", nExpected, nActual)
<ide> }
<ide>
<del> if _, err := srv.DeleteImage("utest/docker:tag2", true); err != nil {
<add> if err := srv.DeleteImage("utest/docker:tag2", engine.NewTable("", 0), true, false); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<ide> func TestImageTagImageDelete(t *testing.T) {
<ide> t.Errorf("Expected %d images, %d found", nExpected, nActual)
<ide> }
<ide>
<del> if _, err := srv.DeleteImage("utest:5000/docker:tag3", true); err != nil {
<add> if err := srv.DeleteImage("utest:5000/docker:tag3", engine.NewTable("", 0), true, false); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<ide> func TestImageTagImageDelete(t *testing.T) {
<ide> nExpected = len(initialImages.Data[0].GetList("RepoTags")) + 1
<ide> nActual = len(images.Data[0].GetList("RepoTags"))
<ide>
<del> if _, err := srv.DeleteImage("utest:tag1", true); err != nil {
<add> if err := srv.DeleteImage("utest:tag1", engine.NewTable("", 0), true, false); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<ide> func TestRmi(t *testing.T) {
<ide> t.Fatalf("Expected 2 new images, found %d.", images.Len()-initialImages.Len())
<ide> }
<ide>
<del> _, err = srv.DeleteImage(imageID, true)
<del> if err != nil {
<add> if err = srv.DeleteImage(imageID, engine.NewTable("", 0), true, false); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<ide> func TestDeleteTagWithExistingContainers(t *testing.T) {
<ide> }
<ide>
<ide> // Try to remove the tag
<del> imgs, err := srv.DeleteImage("utest:tag1", true)
<del> if err != nil {
<add> imgs := engine.NewTable("", 0)
<add> if err := srv.DeleteImage("utest:tag1", imgs, true, false); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<ide><path>server.go
<ide> package docker
<ide>
<ide> import (
<ide> "encoding/json"
<del> "errors"
<ide> "fmt"
<ide> "github.com/dotcloud/docker/archive"
<ide> "github.com/dotcloud/docker/auth"
<ide> func (srv *Server) ContainerDestroy(job *engine.Job) engine.Status {
<ide> return engine.StatusOK
<ide> }
<ide>
<del>var ErrImageReferenced = errors.New("Image referenced by a repository")
<del>
<del>func (srv *Server) deleteImageAndChildren(id string, imgs *engine.Table, byParents map[string][]*Image) error {
<del> // If the image is referenced by a repo, do not delete
<del> if len(srv.runtime.repositories.ByID()[id]) != 0 {
<del> return ErrImageReferenced
<del> }
<del> // If the image is not referenced but has children, go recursive
<del> referenced := false
<del> for _, img := range byParents[id] {
<del> if err := srv.deleteImageAndChildren(img.ID, imgs, byParents); err != nil {
<del> if err != ErrImageReferenced {
<del> return err
<del> }
<del> referenced = true
<del> }
<del> }
<del> if referenced {
<del> return ErrImageReferenced
<del> }
<del>
<del> // If the image is not referenced and has no children, remove it
<del> byParents, err := srv.runtime.graph.ByParent()
<del> if err != nil {
<del> return err
<del> }
<del> if len(byParents[id]) == 0 && srv.canDeleteImage(id) == nil {
<del> if err := srv.runtime.repositories.DeleteAll(id); err != nil {
<del> return err
<del> }
<del> err := srv.runtime.graph.Delete(id)
<del> if err != nil {
<del> return err
<del> }
<del> out := &engine.Env{}
<del> out.Set("Deleted", id)
<del> imgs.Add(out)
<del> srv.LogEvent("delete", id, "")
<del> return nil
<del> }
<del> return nil
<del>}
<del>
<del>func (srv *Server) deleteImageParents(img *Image, imgs *engine.Table) error {
<del> if img.Parent != "" {
<del> parent, err := srv.runtime.graph.Get(img.Parent)
<del> if err != nil {
<del> return err
<del> }
<del> byParents, err := srv.runtime.graph.ByParent()
<del> if err != nil {
<del> return err
<del> }
<del> // Remove all children images
<del> if err := srv.deleteImageAndChildren(img.Parent, imgs, byParents); err != nil {
<del> return err
<del> }
<del> return srv.deleteImageParents(parent, imgs)
<del> }
<del> return nil
<del>}
<del>
<del>func (srv *Server) DeleteImage(name string, autoPrune bool) (*engine.Table, error) {
<add>func (srv *Server) DeleteImage(name string, imgs *engine.Table, first, force bool) error {
<ide> var (
<ide> repoName, tag string
<ide> img, err = srv.runtime.repositories.LookupImage(name)
<del> imgs = engine.NewTable("", 0)
<ide> tags = []string{}
<ide> )
<ide>
<ide> if err != nil {
<del> return nil, fmt.Errorf("No such image: %s", name)
<del> }
<del>
<del> // FIXME: What does autoPrune mean ?
<del> if !autoPrune {
<del> if err := srv.runtime.graph.Delete(img.ID); err != nil {
<del> return nil, fmt.Errorf("Cannot delete image %s: %s", name, err)
<del> }
<del> return nil, nil
<add> return fmt.Errorf("No such image: %s", name)
<ide> }
<ide>
<ide> if !strings.Contains(img.ID, name) {
<ide> repoName, tag = utils.ParseRepositoryTag(name)
<add> if tag == "" {
<add> tag = DEFAULTTAG
<add> }
<ide> }
<ide>
<del> // If we have a repo and the image is not referenced anywhere else
<del> // then just perform an untag and do not validate.
<del> //
<del> // i.e. only validate if we are performing an actual delete and not
<del> // an untag op
<del> if repoName != "" && len(srv.runtime.repositories.ByID()[img.ID]) == 1 {
<del> // Prevent deletion if image is used by a container
<del> if err := srv.canDeleteImage(img.ID); err != nil {
<del> return nil, err
<del> }
<add> byParents, err := srv.runtime.graph.ByParent()
<add> if err != nil {
<add> return err
<ide> }
<ide>
<ide> //If delete by id, see if the id belong only to one repository
<ide> func (srv *Server) DeleteImage(name string, autoPrune bool) (*engine.Table, erro
<ide> if parsedTag != "" {
<ide> tags = append(tags, parsedTag)
<ide> }
<del> } else if repoName != parsedRepo {
<add> } else if repoName != parsedRepo && !force {
<ide> // the id belongs to multiple repos, like base:latest and user:test,
<ide> // in that case return conflict
<del> return nil, fmt.Errorf("Conflict, cannot delete image %s because it is tagged in multiple repositories", utils.TruncateID(img.ID))
<add> return fmt.Errorf("Conflict, cannot delete image %s because it is tagged in multiple repositories, use -f to force", name)
<ide> }
<ide> }
<ide> } else {
<ide> func (srv *Server) DeleteImage(name string, autoPrune bool) (*engine.Table, erro
<ide> for _, tag := range tags {
<ide> tagDeleted, err := srv.runtime.repositories.Delete(repoName, tag)
<ide> if err != nil {
<del> return nil, err
<add> return err
<ide> }
<ide> if tagDeleted {
<ide> out := &engine.Env{}
<del> out.Set("Untagged", img.ID)
<add> out.Set("Untagged", repoName+":"+tag)
<ide> imgs.Add(out)
<ide> srv.LogEvent("untag", img.ID, "")
<ide> }
<ide> }
<del>
<del> if len(srv.runtime.repositories.ByID()[img.ID]) == 0 {
<del> if err := srv.deleteImageAndChildren(img.ID, imgs, nil); err != nil {
<del> if err != ErrImageReferenced {
<del> return imgs, err
<add> tags = srv.runtime.repositories.ByID()[img.ID]
<add> if (len(tags) <= 1 && repoName == "") || len(tags) == 0 {
<add> if len(byParents[img.ID]) == 0 {
<add> if err := srv.canDeleteImage(img.ID); err != nil {
<add> return err
<add> }
<add> if err := srv.runtime.repositories.DeleteAll(img.ID); err != nil {
<add> return err
<ide> }
<del> } else if err := srv.deleteImageParents(img, imgs); err != nil {
<del> if err != ErrImageReferenced {
<del> return imgs, err
<add> err := srv.runtime.graph.Delete(img.ID)
<add> if err != nil {
<add> return err
<ide> }
<add> out := &engine.Env{}
<add> out.Set("Deleted", img.ID)
<add> imgs.Add(out)
<add> srv.LogEvent("delete", img.ID, "")
<add> if img.Parent != "" {
<add> err := srv.DeleteImage(img.Parent, imgs, false, force)
<add> if first {
<add> return err
<add> }
<add>
<add> }
<add>
<ide> }
<ide> }
<del> return imgs, nil
<add> return nil
<ide> }
<ide>
<ide> func (srv *Server) ImageDelete(job *engine.Job) engine.Status {
<ide> if n := len(job.Args); n != 1 {
<ide> return job.Errorf("Usage: %s IMAGE", job.Name)
<ide> }
<del>
<del> imgs, err := srv.DeleteImage(job.Args[0], job.GetenvBool("autoPrune"))
<del> if err != nil {
<add> var imgs = engine.NewTable("", 0)
<add> if err := srv.DeleteImage(job.Args[0], imgs, true, job.GetenvBool("force")); err != nil {
<ide> return job.Error(err)
<ide> }
<ide> if len(imgs.Data) == 0 { | 6 |
Javascript | Javascript | prevent fallback when not ff extension | c0cfb486213d37820327f9c8042ca8d36e157fd9 | <ide><path>web/viewer.js
<ide> var PDFView = {
<ide> }
<ide> },
<ide>
<del> fallback: function pdfViewDownload() {
<add> fallback: function pdfViewFallback() {
<add> if (!PDFJS.isFirefoxExtension)
<add> return;
<ide> // Only trigger the fallback once so we don't spam the user with messages
<ide> // for one PDF.
<ide> if (this.fellback) | 1 |
PHP | PHP | fix nested entity expansion | 23c860682b8d826cd8903171e065e9c1e01e7bb0 | <ide><path>src/Controller/Component/RequestHandlerComponent.php
<ide> public function startup(Event $event)
<ide> public function convertXml($xml)
<ide> {
<ide> try {
<del> $xml = Xml::build($xml, ['readFile' => false]);
<del> if (isset($xml->data)) {
<del> return Xml::toArray($xml->data);
<add> $xml = Xml::build($xml, ['return' => 'domdocument', 'readFile' => false]);
<add> // We might not get child nodes if there are nested inline entities.
<add> if ($xml->childNodes->length > 0) {
<add> return Xml::toArray($xml);
<ide> }
<ide>
<del> return Xml::toArray($xml);
<add> return [];
<ide> } catch (XmlException $e) {
<ide> return [];
<ide> }
<ide><path>src/Utility/Xml.php
<ide> protected static function _loadXml($input, $options)
<ide> $xml = new SimpleXMLElement($input, $flags);
<ide> } else {
<ide> $xml = new DOMDocument();
<del> $xml->loadXML($input);
<add> $xml->loadXML($input, $flags);
<ide> }
<ide> } catch (Exception $e) {
<ide> $xml = null;
<ide><path>tests/TestCase/Controller/Component/RequestHandlerComponentTest.php
<ide> public function testStartupIgnoreFileAsXml()
<ide> $this->assertEquals([], $this->Controller->request->data);
<ide> }
<ide>
<add> /**
<add> * Test that input xml is parsed
<add> *
<add> * @return void
<add> */
<add> public function testStartupConvertXmlDataWrapper()
<add> {
<add> $xml = <<<XML
<add><?xml version="1.0" encoding="utf-8"?>
<add><data>
<add><article id="1" title="first"></article>
<add></data>
<add>XML;
<add> $this->Controller->request = new ServerRequest(['input' => $xml]);
<add> $this->Controller->request->env('REQUEST_METHOD', 'POST');
<add> $this->Controller->request->env('CONTENT_TYPE', 'application/xml');
<add>
<add> $event = new Event('Controller.startup', $this->Controller);
<add> $this->RequestHandler->startup($event);
<add> $expected = [
<add> 'data' => [
<add> 'article' => [
<add> '@id' => 1,
<add> '@title' => 'first'
<add> ]
<add> ]
<add> ];
<add> $this->assertEquals($expected, $this->Controller->request->data);
<add> }
<add>
<add> /**
<add> * Test that input xml is parsed
<add> *
<add> * @return void
<add> */
<add> public function testStartupConvertXmlElements()
<add> {
<add> $xml = <<<XML
<add><?xml version="1.0" encoding="utf-8"?>
<add><article>
<add> <id>1</id>
<add> <title>first</title>
<add></article>
<add>XML;
<add> $this->Controller->request = new ServerRequest(['input' => $xml]);
<add> $this->Controller->request->env('REQUEST_METHOD', 'POST');
<add> $this->Controller->request->env('CONTENT_TYPE', 'application/xml');
<add>
<add> $event = new Event('Controller.startup', $this->Controller);
<add> $this->RequestHandler->startup($event);
<add> $expected = [
<add> 'article' => [
<add> 'id' => 1,
<add> 'title' => 'first'
<add> ]
<add> ];
<add> $this->assertEquals($expected, $this->Controller->request->data);
<add> }
<add>
<add> /**
<add> * Test that input xml is parsed
<add> *
<add> * @return void
<add> */
<add> public function testStartupConvertXmlIgnoreEntities()
<add> {
<add> $xml = <<<XML
<add><?xml version="1.0" encoding="UTF-8"?>
<add><!DOCTYPE item [
<add> <!ENTITY item "item">
<add> <!ENTITY item1 "&item;&item;&item;&item;&item;&item;">
<add> <!ENTITY item2 "&item1;&item1;&item1;&item1;&item1;&item1;&item1;&item1;&item1;">
<add> <!ENTITY item3 "&item2;&item2;&item2;&item2;&item2;&item2;&item2;&item2;&item2;">
<add> <!ENTITY item4 "&item3;&item3;&item3;&item3;&item3;&item3;&item3;&item3;&item3;">
<add> <!ENTITY item5 "&item4;&item4;&item4;&item4;&item4;&item4;&item4;&item4;&item4;">
<add> <!ENTITY item6 "&item5;&item5;&item5;&item5;&item5;&item5;&item5;&item5;&item5;">
<add> <!ENTITY item7 "&item6;&item6;&item6;&item6;&item6;&item6;&item6;&item6;&item6;">
<add> <!ENTITY item8 "&item7;&item7;&item7;&item7;&item7;&item7;&item7;&item7;&item7;">
<add>]>
<add><item>
<add> <description>&item8;</description>
<add></item>
<add>XML;
<add> $this->Controller->request = new ServerRequest(['input' => $xml]);
<add> $this->Controller->request->env('REQUEST_METHOD', 'POST');
<add> $this->Controller->request->env('CONTENT_TYPE', 'application/xml');
<add>
<add> $event = new Event('Controller.startup', $this->Controller);
<add> $this->RequestHandler->startup($event);
<add> $this->assertEquals([], $this->Controller->request->data);
<add> }
<add>
<ide> /**
<ide> * Test mapping a new type and having startup process it.
<ide> * | 3 |
Ruby | Ruby | take care not to mix in public methods | d99b4ec57f07005211bad7c0b6605b03f811c865 | <ide><path>actionpack/lib/action_controller/test_case.rb
<ide> def clean_backtrace(&block)
<ide> #
<ide> # The exception is stored in the exception accessor for further inspection.
<ide> module RaiseActionExceptions
<del> attr_accessor :exception
<add> protected
<add> attr_accessor :exception
<ide>
<del> def rescue_action_without_handler(e)
<del> self.exception = e
<del>
<del> if request.remote_addr == "0.0.0.0"
<del> raise(e)
<del> else
<del> super(e)
<add> def rescue_action_without_handler(e)
<add> self.exception = e
<add>
<add> if request.remote_addr == "0.0.0.0"
<add> raise(e)
<add> else
<add> super(e)
<add> end
<ide> end
<del> end
<ide> end
<ide>
<ide> setup :setup_controller_request_and_response | 1 |
Text | Text | add changelog entry for [ci skip] | c352e064bc1baa6b558147dfb177ee3e3d8605e5 | <ide><path>activerecord/CHANGELOG.md
<add>* `rake railties:install:migrations` respects the order of railties.
<add>
<add> *Arun Agrawal*
<add>
<ide> * Fix redefine a has_and_belongs_to_many inside inherited class
<ide> Fixing regression case, where redefining the same has_an_belongs_to_many
<ide> definition into a subclass would raise. | 1 |
Go | Go | use strslice from pkg/stringutils | 17999c70c39e14a474e69ce10de05a66258e2a5b | <ide><path>runconfig/hostconfig.go
<ide> import (
<ide> "strings"
<ide>
<ide> "github.com/docker/docker/pkg/nat"
<add> "github.com/docker/docker/pkg/stringutils"
<ide> "github.com/docker/docker/pkg/ulimit"
<ide> )
<ide>
<ide> func NewLxcConfig(values []KeyValuePair) *LxcConfig {
<ide> return &LxcConfig{values}
<ide> }
<ide>
<del>// CapList represents the list of capabilities of the container.
<del>type CapList struct {
<del> caps []string
<del>}
<del>
<del>// MarshalJSON marshals (or serializes) the CapList into JSON.
<del>func (c *CapList) MarshalJSON() ([]byte, error) {
<del> if c == nil {
<del> return []byte{}, nil
<del> }
<del> return json.Marshal(c.Slice())
<del>}
<del>
<del>// UnmarshalJSON unmarshals (or deserializes) the specified byte slices
<del>// from JSON to a CapList.
<del>func (c *CapList) UnmarshalJSON(b []byte) error {
<del> if len(b) == 0 {
<del> return nil
<del> }
<del>
<del> var caps []string
<del> if err := json.Unmarshal(b, &caps); err != nil {
<del> var s string
<del> if err := json.Unmarshal(b, &s); err != nil {
<del> return err
<del> }
<del> caps = append(caps, s)
<del> }
<del> c.caps = caps
<del>
<del> return nil
<del>}
<del>
<del>// Len returns the number of specific kernel capabilities.
<del>func (c *CapList) Len() int {
<del> if c == nil {
<del> return 0
<del> }
<del> return len(c.caps)
<del>}
<del>
<del>// Slice returns the specific capabilities into a slice of KeyValuePair.
<del>func (c *CapList) Slice() []string {
<del> if c == nil {
<del> return nil
<del> }
<del> return c.caps
<del>}
<del>
<del>// NewCapList creates a CapList from a slice of string.
<del>func NewCapList(caps []string) *CapList {
<del> return &CapList{caps}
<del>}
<del>
<ide> // HostConfig the non-portable Config structure of a container.
<ide> // Here, "non-portable" means "dependent of the host we are running on".
<ide> // Portable information *should* appear in Config.
<ide> type HostConfig struct {
<del> Binds []string // List of volume bindings for this container
<del> ContainerIDFile string // File (path) where the containerId is written
<del> LxcConf *LxcConfig // Additional lxc configuration
<del> Memory int64 // Memory limit (in bytes)
<del> MemorySwap int64 // Total memory usage (memory + swap); set `-1` to disable swap
<del> KernelMemory int64 // Kernel memory limit (in bytes)
<del> CPUShares int64 `json:"CpuShares"` // CPU shares (relative weight vs. other containers)
<del> CPUPeriod int64 `json:"CpuPeriod"` // CPU CFS (Completely Fair Scheduler) period
<del> CpusetCpus string // CpusetCpus 0-2, 0,1
<del> CpusetMems string // CpusetMems 0-2, 0,1
<del> CPUQuota int64 `json:"CpuQuota"` // CPU CFS (Completely Fair Scheduler) quota
<del> BlkioWeight int64 // Block IO weight (relative weight vs. other containers)
<del> OomKillDisable bool // Whether to disable OOM Killer or not
<del> MemorySwappiness *int64 // Tuning container memory swappiness behaviour
<del> Privileged bool // Is the container in privileged mode
<del> PortBindings nat.PortMap // Port mapping between the exposed port (container) and the host
<del> Links []string // List of links (in the name:alias form)
<del> PublishAllPorts bool // Should docker publish all exposed port for the container
<del> DNS []string `json:"Dns"` // List of DNS server to lookup
<del> DNSSearch []string `json:"DnsSearch"` // List of DNSSearch to look for
<del> ExtraHosts []string // List of extra hosts
<del> VolumesFrom []string // List of volumes to take from other container
<del> Devices []DeviceMapping // List of devices to map inside the container
<del> NetworkMode NetworkMode // Network namespace to use for the container
<del> IpcMode IpcMode // IPC namespace to use for the container
<del> PidMode PidMode // PID namespace to use for the container
<del> UTSMode UTSMode // UTS namespace to use for the container
<del> CapAdd *CapList // List of kernel capabilities to add to the container
<del> CapDrop *CapList // List of kernel capabilities to remove from the container
<del> GroupAdd []string // List of additional groups that the container process will run as
<del> RestartPolicy RestartPolicy // Restart policy to be used for the container
<del> SecurityOpt []string // List of string values to customize labels for MLS systems, such as SELinux.
<del> ReadonlyRootfs bool // Is the container root filesystem in read-only
<del> Ulimits []*ulimit.Ulimit // List of ulimits to be set in the container
<del> LogConfig LogConfig // Configuration of the logs for this container
<del> CgroupParent string // Parent cgroup.
<del> ConsoleSize [2]int // Initial console size on Windows
<add> Binds []string // List of volume bindings for this container
<add> ContainerIDFile string // File (path) where the containerId is written
<add> LxcConf *LxcConfig // Additional lxc configuration
<add> Memory int64 // Memory limit (in bytes)
<add> MemorySwap int64 // Total memory usage (memory + swap); set `-1` to disable swap
<add> KernelMemory int64 // Kernel memory limit (in bytes)
<add> CPUShares int64 `json:"CpuShares"` // CPU shares (relative weight vs. other containers)
<add> CPUPeriod int64 `json:"CpuPeriod"` // CPU CFS (Completely Fair Scheduler) period
<add> CpusetCpus string // CpusetCpus 0-2, 0,1
<add> CpusetMems string // CpusetMems 0-2, 0,1
<add> CPUQuota int64 `json:"CpuQuota"` // CPU CFS (Completely Fair Scheduler) quota
<add> BlkioWeight int64 // Block IO weight (relative weight vs. other containers)
<add> OomKillDisable bool // Whether to disable OOM Killer or not
<add> MemorySwappiness *int64 // Tuning container memory swappiness behaviour
<add> Privileged bool // Is the container in privileged mode
<add> PortBindings nat.PortMap // Port mapping between the exposed port (container) and the host
<add> Links []string // List of links (in the name:alias form)
<add> PublishAllPorts bool // Should docker publish all exposed port for the container
<add> DNS []string `json:"Dns"` // List of DNS server to lookup
<add> DNSSearch []string `json:"DnsSearch"` // List of DNSSearch to look for
<add> ExtraHosts []string // List of extra hosts
<add> VolumesFrom []string // List of volumes to take from other container
<add> Devices []DeviceMapping // List of devices to map inside the container
<add> NetworkMode NetworkMode // Network namespace to use for the container
<add> IpcMode IpcMode // IPC namespace to use for the container
<add> PidMode PidMode // PID namespace to use for the container
<add> UTSMode UTSMode // UTS namespace to use for the container
<add> CapAdd *stringutils.StrSlice // List of kernel capabilities to add to the container
<add> CapDrop *stringutils.StrSlice // List of kernel capabilities to remove from the container
<add> GroupAdd []string // List of additional groups that the container process will run as
<add> RestartPolicy RestartPolicy // Restart policy to be used for the container
<add> SecurityOpt []string // List of string values to customize labels for MLS systems, such as SELinux.
<add> ReadonlyRootfs bool // Is the container root filesystem in read-only
<add> Ulimits []*ulimit.Ulimit // List of ulimits to be set in the container
<add> LogConfig LogConfig // Configuration of the logs for this container
<add> CgroupParent string // Parent cgroup.
<add> ConsoleSize [2]int // Initial console size on Windows
<ide> }
<ide>
<ide> // DecodeHostConfig creates a HostConfig based on the specified Reader.
<ide><path>runconfig/hostconfig_test.go
<ide> package runconfig
<ide>
<ide> import (
<ide> "bytes"
<del> "encoding/json"
<ide> "fmt"
<ide> "io/ioutil"
<ide> "testing"
<ide> func TestDecodeHostConfig(t *testing.T) {
<ide> }
<ide> }
<ide> }
<del>
<del>func TestCapListUnmarshalSliceAndString(t *testing.T) {
<del> var cl *CapList
<del> cap0, err := json.Marshal([]string{"CAP_SOMETHING"})
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> if err := json.Unmarshal(cap0, &cl); err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> slice := cl.Slice()
<del> if len(slice) != 1 {
<del> t.Fatalf("expected 1 element after unmarshal: %q", slice)
<del> }
<del>
<del> if slice[0] != "CAP_SOMETHING" {
<del> t.Fatalf("expected `CAP_SOMETHING`, got: %q", slice[0])
<del> }
<del>
<del> cap1, err := json.Marshal("CAP_SOMETHING")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> if err := json.Unmarshal(cap1, &cl); err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> slice = cl.Slice()
<del> if len(slice) != 1 {
<del> t.Fatalf("expected 1 element after unmarshal: %q", slice)
<del> }
<del>
<del> if slice[0] != "CAP_SOMETHING" {
<del> t.Fatalf("expected `CAP_SOMETHING`, got: %q", slice[0])
<del> }
<del>}
<ide><path>runconfig/parse.go
<ide> func Parse(cmd *flag.FlagSet, args []string) (*Config, *HostConfig, *flag.FlagSe
<ide> PidMode: pidMode,
<ide> UTSMode: utsMode,
<ide> Devices: deviceMappings,
<del> CapAdd: NewCapList(flCapAdd.GetAll()),
<del> CapDrop: NewCapList(flCapDrop.GetAll()),
<add> CapAdd: stringutils.NewStrSlice(flCapAdd.GetAll()...),
<add> CapDrop: stringutils.NewStrSlice(flCapDrop.GetAll()...),
<ide> GroupAdd: flGroupAdd.GetAll(),
<ide> RestartPolicy: restartPolicy,
<ide> SecurityOpt: flSecurityOpt.GetAll(), | 3 |
Java | Java | fix issue with obtaining websocketcontainer | d20dabf1fbcc77f152d0334a30fc30c1aa7d053a | <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/server/endpoint/ServerEndpointExporter.java
<ide> import org.springframework.context.ApplicationContext;
<ide> import org.springframework.context.ApplicationContextAware;
<ide> import org.springframework.util.Assert;
<del>import org.springframework.util.ClassUtils;
<ide> import org.springframework.util.ReflectionUtils;
<ide>
<ide> /**
<ide> */
<ide> public class ServerEndpointExporter implements InitializingBean, BeanPostProcessor, ApplicationContextAware {
<ide>
<del> private static final boolean isServletApiPresent =
<del> ClassUtils.isPresent("javax.servlet.ServletContext", ServerEndpointExporter.class.getClassLoader());
<del>
<ide> private static Log logger = LogFactory.getLog(ServerEndpointExporter.class);
<ide>
<ide>
<ide> public void setApplicationContext(ApplicationContext applicationContext) {
<ide> }
<ide>
<ide> protected ServerContainer getServerContainer() {
<del> if (isServletApiPresent) {
<del> try {
<del> Method getter = ReflectionUtils.findMethod(this.applicationContext.getClass(), "getServletContext");
<del> Object servletContext = getter.invoke(this.applicationContext);
<ide>
<del> Method attrMethod = ReflectionUtils.findMethod(servletContext.getClass(), "getAttribute", String.class);
<del> return (ServerContainer) attrMethod.invoke(servletContext, "javax.websocket.server.ServerContainer");
<del> }
<del> catch (Exception ex) {
<del> throw new IllegalStateException(
<del> "Failed to get javax.websocket.server.ServerContainer via ServletContext attribute", ex);
<del> }
<add> Class<?> servletContextClass;
<add> try {
<add> servletContextClass = Class.forName("javax.servlet.ServletContext");
<add> }
<add> catch (Throwable e) {
<add> return null;
<add> }
<add>
<add> try {
<add> Method getter = ReflectionUtils.findMethod(this.applicationContext.getClass(), "getServletContext");
<add> Object servletContext = getter.invoke(this.applicationContext);
<add> Method attrMethod = ReflectionUtils.findMethod(servletContextClass, "getAttribute", String.class);
<add> return (ServerContainer) attrMethod.invoke(servletContext, "javax.websocket.server.ServerContainer");
<add> }
<add> catch (Exception ex) {
<add> throw new IllegalStateException(
<add> "Failed to get javax.websocket.server.ServerContainer via ServletContext attribute", ex);
<ide> }
<del> return null;
<ide> }
<ide>
<ide> @Override | 1 |
Javascript | Javascript | invalidate element on parent and children | f7b3c0b1b098d1cf106a5fe5be2ef4dbd5c241d0 | <ide><path>packages/ember-views/lib/views/container_view.js
<ide> Ember.ContainerView.states = {
<ide> view.domManager.prepend(view, buffer.string());
<ide> }
<ide> childView.transitionTo('inDOM');
<del> childView.invalidateRecursively('element');
<add> childView.propertyDidChange('element');
<ide> childView._notifyDidInsertElement();
<ide> }
<ide> previous = childView;
<ide><path>packages/ember-views/tests/views/container_view_test.js
<ide> test("should be able to modify childViews then rerender again the ContainerView
<ide> equal(two.count, 1, 'rendered child only once');
<ide> equal(container.$().text(), 'onetwo');
<ide> });
<add>
<add>test("should invalidate `element` on itself and childViews when being rendered by ensureChildrenAreInDOM", function () {
<add> var root = Ember.ContainerView.create(),
<add> view = Ember.View.create({ template: function() {} }),
<add> container = Ember.ContainerView.create({ childViews: ['child'], child: view });
<add>
<add> Ember.run(function() {
<add> root.appendTo('#qunit-fixture');
<add> });
<add>
<add> Ember.run(function() {
<add> root.get('childViews').pushObject(container);
<add>
<add> // Get the parent and child's elements to cause them to be cached as null
<add> container.get('element');
<add> view.get('element');
<add> });
<add>
<add> ok(!!container.get('element'), "Parent's element should have been recomputed after being rendered");
<add> ok(!!view.get('element'), "Child's element should have been recomputed after being rendered");
<add>}); | 2 |
Python | Python | reintroduce failing siamese test | 52dbeb1f26bac4272e35a8bb578f16cc584c3721 | <ide><path>tests/keras/test_graph_model.py
<ide> def test_siamese_1():
<ide> new_graph = model_from_yaml(yaml_str)
<ide>
<ide>
<del># def test_siamese_2():
<del># # Note: not working. TODO: fix it.
<del># graph = Graph()
<del># graph.add_input(name='input1', input_shape=(32,))
<del># graph.add_input(name='input2', input_shape=(32,))
<del>
<del># graph.add_shared_node(Dense(4), name='shared',
<del># inputs=['input1', 'input2'],
<del># outputs=['shared_output1', 'shared_output2'])
<del># graph.add_node(Dense(4), name='dense1', input='shared_output1')
<del># graph.add_node(Dense(4), name='dense2', input='shared_output2')
<del>
<del># graph.add_output(name='output1', inputs=['dense1', 'dense2'],
<del># merge_mode='sum')
<del># graph.compile('rmsprop', {'output1': 'mse'})
<del>
<del># graph.fit({'input1': X_train_graph,
<del># 'input2': X2_train_graph,
<del># 'output1': y_train_graph},
<del># nb_epoch=10)
<del># out = graph.predict({'input1': X_test_graph,
<del># 'input2': X2_test_graph})
<del># assert(type(out == dict))
<del># assert(len(out) == 1)
<del>
<del># loss = graph.test_on_batch({'input1': X_test_graph,
<del># 'input2': X2_test_graph,
<del># 'output1': y_test_graph})
<del># loss = graph.train_on_batch({'input1': X_test_graph,
<del># 'input2': X2_test_graph,
<del># 'output1': y_test_graph})
<del># loss = graph.evaluate({'input1': X_test_graph,
<del># 'input2': X2_test_graph,
<del># 'output1': y_test_graph})
<del># # test serialization
<del># config = graph.get_config()
<del># new_graph = Graph.from_config(config)
<del>
<del># graph.summary()
<del># json_str = graph.to_json()
<del># new_graph = model_from_json(json_str)
<del>
<del># yaml_str = graph.to_yaml()
<del># new_graph = model_from_yaml(yaml_str)
<add>def test_siamese_2():
<add> graph = Graph()
<add> graph.add_input(name='input1', input_shape=(32,))
<add> graph.add_input(name='input2', input_shape=(32,))
<add>
<add> graph.add_shared_node(Dense(4), name='shared',
<add> inputs=['input1', 'input2'],
<add> outputs=['shared_output1', 'shared_output2'])
<add> graph.add_node(Dense(4), name='dense1', input='shared_output1')
<add> graph.add_node(Dense(4), name='dense2', input='shared_output2')
<add>
<add> graph.add_output(name='output1', inputs=['dense1', 'dense2'],
<add> merge_mode='sum')
<add> graph.compile('rmsprop', {'output1': 'mse'})
<add>
<add> graph.fit({'input1': X_train_graph,
<add> 'input2': X2_train_graph,
<add> 'output1': y_train_graph},
<add> nb_epoch=10)
<add> out = graph.predict({'input1': X_test_graph,
<add> 'input2': X2_test_graph})
<add> assert(type(out == dict))
<add> assert(len(out) == 1)
<add>
<add> loss = graph.test_on_batch({'input1': X_test_graph,
<add> 'input2': X2_test_graph,
<add> 'output1': y_test_graph})
<add> loss = graph.train_on_batch({'input1': X_test_graph,
<add> 'input2': X2_test_graph,
<add> 'output1': y_test_graph})
<add> loss = graph.evaluate({'input1': X_test_graph,
<add> 'input2': X2_test_graph,
<add> 'output1': y_test_graph})
<add> # test serialization
<add> config = graph.get_config()
<add> new_graph = Graph.from_config(config)
<add>
<add> graph.summary()
<add> json_str = graph.to_json()
<add> new_graph = model_from_json(json_str)
<add>
<add> yaml_str = graph.to_yaml()
<add> new_graph = model_from_yaml(yaml_str)
<ide>
<ide>
<ide> def test_2o_1i_save_weights(): | 1 |
Python | Python | raise error for negative 'num' in linspace | 43d4aa5de8a991fa40c9976280cef5b4b080a806 | <ide><path>numpy/core/function_base.py
<ide> def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None):
<ide> evenly spaced samples, so that `stop` is excluded. Note that the step
<ide> size changes when `endpoint` is False.
<ide> num : int, optional
<del> Number of samples to generate. Default is 50.
<add> Number of samples to generate. Default is 50. Must be non-negative.
<ide> endpoint : bool, optional
<ide> If True, `stop` is the last sample. Otherwise, it is not included.
<ide> Default is True.
<ide> def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None):
<ide>
<ide> """
<ide> num = int(num)
<add> if num < 0:
<add> raise ValueError("Number of samples, %s, must be non-negative." % num)
<ide> div = (num - 1) if endpoint else num
<ide>
<ide> # Convert float/complex array scalars to float, gh-3504
<ide><path>numpy/core/tests/test_function_base.py
<ide> def test_basic(self):
<ide> assert_(y[-1] == 10)
<ide> y = linspace(2, 10, endpoint=0)
<ide> assert_(y[-1] < 10)
<add> assert_raises(ValueError, linspace, 0, 10, num=-1)
<ide>
<ide> def test_corner(self):
<ide> y = list(linspace(0, 1, 1)) | 2 |
Python | Python | move matrix tests in testing to matrixlib | 4819af522b547719c3b8c50ef01fa738704e1690 | <ide><path>numpy/matrixlib/tests/test_interaction.py
<ide> """
<ide> from __future__ import division, absolute_import, print_function
<ide>
<add>import textwrap
<ide> import warnings
<ide>
<ide> import numpy as np
<ide> from numpy.testing import (assert_, assert_equal, assert_raises,
<ide> assert_raises_regex, assert_array_equal,
<del> assert_almost_equal)
<add> assert_almost_equal, assert_array_almost_equal)
<ide>
<ide>
<ide> def test_fancy_indexing():
<ide> def test_matrix_builder(self):
<ide>
<ide> assert_equal(actual, expected)
<ide> assert_equal(type(actual), type(expected))
<add>
<add>
<add>def test_array_equal_error_message_matrix():
<add> # 2018-04-29: moved here from testing.tests.test_utils.
<add> try:
<add> assert_equal(np.array([1, 2]), np.matrix([1, 2]))
<add> except AssertionError as e:
<add> msg = str(e)
<add> msg2 = msg.replace("shapes (2L,), (1L, 2L)", "shapes (2,), (1, 2)")
<add> msg_reference = textwrap.dedent("""\
<add>
<add> Arrays are not equal
<add>
<add> (shapes (2,), (1, 2) mismatch)
<add> x: array([1, 2])
<add> y: matrix([[1, 2]])""")
<add> try:
<add> assert_equal(msg, msg_reference)
<add> except AssertionError:
<add> assert_equal(msg2, msg_reference)
<add> else:
<add> raise AssertionError("Did not raise")
<add>
<add>
<add>def test_array_almost_equal_matrix():
<add> # Matrix slicing keeps things 2-D, while array does not necessarily.
<add> # See gh-8452.
<add> # 2018-04-29: moved here from testing.tests.test_utils.
<add> m1 = np.matrix([[1., 2.]])
<add> m2 = np.matrix([[1., np.nan]])
<add> m3 = np.matrix([[1., -np.inf]])
<add> m4 = np.matrix([[np.nan, np.inf]])
<add> m5 = np.matrix([[1., 2.], [np.nan, np.inf]])
<add> for assert_func in assert_array_almost_equal, assert_almost_equal:
<add> for m in m1, m2, m3, m4, m5:
<add> assert_func(m, m)
<add> a = np.array(m)
<add> assert_func(a, m)
<add> assert_func(m, a)
<ide><path>numpy/testing/tests/test_utils.py
<ide> def test_complex(self):
<ide>
<ide> def test_error_message(self):
<ide> try:
<del> self._assert_func(np.array([1, 2]), np.matrix([1, 2]))
<add> self._assert_func(np.array([1, 2]), np.array([[1, 2]]))
<ide> except AssertionError as e:
<ide> msg = str(e)
<ide> msg2 = msg.replace("shapes (2L,), (1L, 2L)", "shapes (2,), (1, 2)")
<ide> def test_error_message(self):
<ide>
<ide> (shapes (2,), (1, 2) mismatch)
<ide> x: array([1, 2])
<del> y: matrix([[1, 2]])""")
<add> y: array([[1, 2]])""")
<ide> try:
<ide> assert_equal(msg, msg_reference)
<ide> except AssertionError:
<ide> def test_subclass(self):
<ide> self._assert_func(b, a)
<ide> self._assert_func(b, b)
<ide>
<del> def test_matrix(self):
<del> # Matrix slicing keeps things 2-D, while array does not necessarily.
<del> # See gh-8452.
<del> m1 = np.matrix([[1., 2.]])
<del> m2 = np.matrix([[1., np.nan]])
<del> m3 = np.matrix([[1., -np.inf]])
<del> m4 = np.matrix([[np.nan, np.inf]])
<del> m5 = np.matrix([[1., 2.], [np.nan, np.inf]])
<del> for m in m1, m2, m3, m4, m5:
<del> self._assert_func(m, m)
<del> a = np.array(m)
<del> self._assert_func(a, m)
<del> self._assert_func(m, a)
<del>
<ide> def test_subclass_that_cannot_be_bool(self):
<ide> # While we cannot guarantee testing functions will always work for
<ide> # subclasses, the tests should ideally rely only on subclasses having
<ide> def test_error_message(self):
<ide> # remove anything that's not the array string
<ide> assert_equal(str(e).split('%)\n ')[1], b)
<ide>
<del> def test_matrix(self):
<del> # Matrix slicing keeps things 2-D, while array does not necessarily.
<del> # See gh-8452.
<del> m1 = np.matrix([[1., 2.]])
<del> m2 = np.matrix([[1., np.nan]])
<del> m3 = np.matrix([[1., -np.inf]])
<del> m4 = np.matrix([[np.nan, np.inf]])
<del> m5 = np.matrix([[1., 2.], [np.nan, np.inf]])
<del> for m in m1, m2, m3, m4, m5:
<del> self._assert_func(m, m)
<del> a = np.array(m)
<del> self._assert_func(a, m)
<del> self._assert_func(m, a)
<del>
<ide> def test_subclass_that_cannot_be_bool(self):
<ide> # While we cannot guarantee testing functions will always work for
<ide> # subclasses, the tests should ideally rely only on subclasses having | 2 |
Javascript | Javascript | fix incorrect sethidden(hidden) docs description | cb67d16aee38fcaefbce0bdd3d004efee2726ff9 | <ide><path>Libraries/Components/StatusBar/StatusBar.js
<ide> class StatusBar extends React.Component {
<ide>
<ide> /**
<ide> * Show or hide the status bar
<del> * @param hidden The dialog's title.
<add> * @param hidden Hide the status bar.
<ide> * @param animation Optional animation when
<ide> * changing the status bar hidden property.
<ide> */ | 1 |
PHP | PHP | remove fetch mode option | 770c41552f07c75450c72099b8feedbd428888fe | <ide><path>config/database.php
<ide>
<ide> return [
<ide>
<del> /*
<del> |--------------------------------------------------------------------------
<del> | PDO Fetch Style
<del> |--------------------------------------------------------------------------
<del> |
<del> | By default, database results will be returned as instances of the PHP
<del> | stdClass object; however, you may desire to retrieve records in an
<del> | array format for simplicity. Here you can tweak the fetch style.
<del> |
<del> */
<del>
<del> 'fetch' => PDO::FETCH_OBJ,
<del>
<ide> /*
<ide> |--------------------------------------------------------------------------
<ide> | Default Database Connection Name | 1 |
Ruby | Ruby | add env.refurbish_args helper | 0ec7e3928734cab72e29e5e5dc6ebf558f18312b | <ide><path>Library/Homebrew/extend/ENV/std.rb
<ide> def make_jobs
<ide> Hardware::CPU.cores
<ide> end
<ide> end
<add>
<add> # This method does nothing in stdenv since there's no arg refurbishment
<add> def refurbish_args; end
<ide> end
<ide><path>Library/Homebrew/extend/ENV/super.rb
<ide> def libstdcxx
<ide> end
<ide> end
<ide>
<add> def refurbish_args
<add> append 'HOMEBREW_CCCFG', "O", ''
<add> end
<add>
<ide> # m32 on superenv does not add any CC flags. It prevents "-m32" from being erased.
<ide> def m32
<ide> append 'HOMEBREW_CCCFG', "3", '' | 2 |
Javascript | Javascript | fix the event handler when legend is disabled | a94885e32d611723f35393726dac93872e1b1a74 | <ide><path>src/core/core.controller.js
<ide> module.exports = function(Chart) {
<ide>
<ide> eventHandler: function(e) {
<ide> var me = this;
<add> var legend = me.legend;
<add> var tooltip = me.tooltip;
<ide> var hoverOptions = me.options.hover;
<ide>
<ide> // Buffer any update calls so that renders do not occur
<ide> me._bufferedRender = true;
<ide> me._bufferedRequest = null;
<ide>
<ide> var changed = me.handleEvent(e);
<del> changed |= me.legend.handleEvent(e);
<del> changed |= me.tooltip.handleEvent(e);
<add> changed |= legend && legend.handleEvent(e);
<add> changed |= tooltip && tooltip.handleEvent(e);
<ide>
<ide> var bufferedRequest = me._bufferedRequest;
<ide> if (bufferedRequest) { | 1 |
PHP | PHP | add comment for test | 5efddd11c83a1497c8c3e93179ee4a0f38253f44 | <ide><path>lib/Cake/Test/Case/Routing/Route/CakeRouteTest.php
<ide> public function testMatchWithNamedParametersAndPassedArgs() {
<ide> $this->assertFalse($result);
<ide> }
<ide>
<add>/**
<add> * Ensure that named parameters are urldecoded
<add> *
<add> * @return void
<add> */
<ide> public function testParseNamedParametersUrlDecode() {
<ide> Router::connectNamed(true);
<ide> $route = new CakeRoute('/:controller/:action/*', array('plugin' => null)); | 1 |
Ruby | Ruby | fix counter cache setting in belongs-to proxy | 966c276d6071f8c331f75820f8c2f30d1bba02b2 | <ide><path>activerecord/lib/active_record/associations/belongs_to_association.rb
<ide> def replace(record)
<ide> else
<ide> raise_on_type_mismatch(record)
<ide>
<del> if counter_cache_name && @owner[counter_cache_name] && [email protected]_record?
<add> if counter_cache_name && [email protected]_record?
<ide> @reflection.klass.increment_counter(counter_cache_name, record.id)
<ide> @reflection.klass.decrement_counter(counter_cache_name, @owner[@reflection.primary_key_name]) if @owner[@reflection.primary_key_name]
<ide> end | 1 |
Python | Python | fix typo in local_task_job | 77412ac6ea3486673d5e2340d10b355e12317fc0 | <ide><path>airflow/jobs/local_task_job.py
<ide> def signal_handler(signum, frame):
<ide> time_since_last_heartbeat = (timezone.utcnow() - self.latest_heartbeat).total_seconds()
<ide> if time_since_last_heartbeat > heartbeat_time_limit:
<ide> Stats.incr('local_task_job_prolonged_heartbeat_failure', 1, 1)
<del> self.log.error("Heartbeat time limited exceeded!")
<add> self.log.error("Heartbeat time limit exceeded!")
<ide> raise AirflowException("Time since last heartbeat({:.2f}s) "
<ide> "exceeded limit ({}s)."
<ide> .format(time_since_last_heartbeat, | 1 |
Javascript | Javascript | remove refs to old css experiment | d650da0623f57b899a7fc89b10d6632daf2058dd | <ide><path>examples/with-react-md/next.config.js
<del>module.exports = {
<del> experimental: { css: true },
<del>}
<ide><path>examples/z-experimental-refresh/next.config.js
<del>module.exports = {
<del> experimental: {
<del> reactRefresh: true,
<del> },
<del>}
<ide><path>test/acceptance/next.config.js
<del>module.exports = {
<del> experimental: {
<del> reactRefresh: true,
<del> },
<del>}
<ide><path>test/integration/config/next.config.js
<ide> module.exports = withCSS(
<ide> // Make sure entries are not getting disposed.
<ide> maxInactiveAge: 1000 * 60 * 60,
<ide> },
<del> experimental: { css: true },
<ide> poweredByHeader: false,
<ide> cssModules: true,
<ide> serverRuntimeConfig: {
<ide><path>test/integration/css-features/fixtures/next.config.js
<del>module.exports = { experimental: { css: true } }
<ide><path>test/integration/css-fixtures/custom-configuration-legacy/next.config.js
<ide> module.exports = withCSS({
<ide> // Make sure entries are not getting disposed.
<ide> maxInactiveAge: 1000 * 60 * 60,
<ide> },
<del> experimental: {
<del> css: true,
<del> },
<ide> webpack(cfg) {
<ide> cfg.devtool = 'source-map'
<ide> return cfg
<ide><path>test/integration/legacy-sass/next.config.js
<ide> const withSass = require('@zeit/next-sass')
<del>module.exports = withSass({ experimental: { reactRefresh: true } })
<add>module.exports = withSass()
<ide><path>test/integration/production-config/next.config.js
<ide> module.exports = withCSS(
<ide> // Make sure entries are not getting disposed.
<ide> maxInactiveAge: 1000 * 60 * 60,
<ide> },
<del> experimental: { css: true },
<ide> webpack(config) {
<ide> // When next-css is `npm link`ed we have to solve loaders from the project root
<ide> const nextLocation = path.join( | 8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.