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 |
|---|---|---|---|---|---|
PHP | PHP | add support for newqueryforrestoration from queues | 54b2cb66de5ea72a4cd392caf473dc94006401f1 | <ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide> public function newQueryWithoutScope($scope)
<ide> return $builder->withoutGlobalScope($scope);
<ide> }
<ide>
<add> /**
<add> * Get a new query to restore one or more models by the queueable IDs.
<add> *
<add> * @param array|int $ids
<add> *
<add> * @return \Illuminate\Database\Eloquent\Builder
<add> */
<add> public function newQueryForRestoration($ids)
<add> {
<add> if (is_array($ids)) {
<add> return $this->newQueryWithoutScopes()->whereIn(
<add> $this->getQualifiedKeyName(),
<add> $ids
<add> );
<add> }
<add>
<add> return $this->newQueryWithoutScopes()->whereKey($ids);
<add> }
<add>
<ide> /**
<ide> * Create a new Eloquent query builder for the model.
<ide> *
<ide><path>src/Illuminate/Queue/SerializesAndRestoresModelIdentifiers.php
<ide> protected function getRestoredPropertyValue($value)
<ide> return $value;
<ide> }
<ide>
<add> $model = (new $value->class)->setConnection($value->connection);
<add>
<ide> return is_array($value->id)
<del> ? $this->restoreCollection($value)
<del> : $this->getQueryForModelRestoration((new $value->class)->setConnection($value->connection))
<del> ->useWritePdo()->findOrFail($value->id);
<add> ? $this->restoreCollection($value)
<add> : $this->getQueryForModelRestoration($model, $value->id)
<add> ->useWritePdo()->firstOrFail();
<ide> }
<ide>
<ide> /**
<ide> protected function restoreCollection($value)
<ide>
<ide> $model = (new $value->class)->setConnection($value->connection);
<ide>
<del> return $this->getQueryForModelRestoration($model)->useWritePdo()
<del> ->whereIn($model->getQualifiedKeyName(), $value->id)->get();
<add> return $this->getQueryForModelRestoration($model, $value->id)
<add> ->useWritePdo()->get();
<ide> }
<ide>
<ide> /**
<ide> * Get the query for restoration.
<ide> *
<ide> * @param \Illuminate\Database\Eloquent\Model $model
<add> * @param array|int $ids
<ide> * @return \Illuminate\Database\Eloquent\Builder
<ide> */
<del> protected function getQueryForModelRestoration($model)
<add> protected function getQueryForModelRestoration($model, $ids)
<ide> {
<del> return $model->newQueryWithoutScopes();
<add> return $model->newQueryForRestoration($ids);
<ide> }
<ide> } | 2 |
Javascript | Javascript | bring horizon example up-to-date | eb15be6325fba5333629af74ad9f561bf6cc4505 | <ide><path>examples/horizon/horizon.js
<del>var w = 960,
<del> h = 40;
<add>var width = 960,
<add> height = 40;
<ide>
<ide> var chart = horizonChart()
<del> .width(w)
<del> .height(h)
<add> .width(width)
<add> .height(height)
<ide> .bands(5)
<ide> .mode("offset")
<ide> .interpolate("basis");
<ide>
<ide> var svg = d3.select("#chart").append("svg")
<del> .attr("width", w)
<del> .attr("height", h);
<add> .attr("width", width)
<add> .attr("height", height);
<ide>
<ide> d3.json("unemployment.json", function(data) {
<ide>
<ide> function horizonChart() {
<ide> interpolate = "linear", // or basis, monotone, step-before, etc.
<ide> x = horizonX,
<ide> y = horizonY,
<del> w = 960,
<del> h = 40,
<add> width = 960,
<add> height = 40,
<ide> nextId = 0,
<ide> area = d3.svg.area(),
<ide> duration = 0;
<ide> function horizonChart() {
<ide> });
<ide>
<ide> // Compute the new x- and y-scales.
<del> var x1 = d3.scale.linear().domain([xMin, xMax]).range([0, w]),
<del> y1 = d3.scale.linear().domain([0, yMax]).range([0, h * bands]);
<add> var x1 = d3.scale.linear().domain([xMin, xMax]).range([0, width]),
<add> y1 = d3.scale.linear().domain([0, yMax]).range([0, height * bands]);
<ide>
<ide> // Retrieve the old scales, if this is an update.
<ide> if (this.__chart__) {
<ide> function horizonChart() {
<ide> defsEnter.append("svg:clipPath")
<ide> .attr("id", "horizon_clip" + id)
<ide> .append("svg:rect")
<del> .attr("width", w)
<del> .attr("height", h);
<add> .attr("width", width)
<add> .attr("height", height);
<ide>
<ide> defs.select("rect").transition()
<ide> .duration(duration)
<del> .attr("width", w)
<del> .attr("height", h);
<add> .attr("width", width)
<add> .attr("height", height);
<ide>
<ide> // The area path is rendered with our resuable d3.svg.area.
<ide> defsEnter.append("svg:path")
<ide> .attr("id", "horizon_path" + id)
<ide> .attr("d", area
<ide> .interpolate(interpolate)
<ide> .x(function(d) { return x0(d[0]); })
<del> .y0(h * bands)
<del> .y1(function(d) { return h * bands - y0(d[1]); }))
<add> .y0(height * bands)
<add> .y1(function(d) { return height * bands - y0(d[1]); }))
<ide> .transition()
<ide> .duration(duration)
<ide> .attr("d", area
<ide> .x(function(d) { return x1(d[0]); })
<del> .y1(function(d) { return h * bands - y1(d[1]); }));
<add> .y1(function(d) { return height * bands - y1(d[1]); }));
<ide>
<ide> defs.select("path").transition()
<ide> .duration(duration)
<ide> function horizonChart() {
<ide>
<ide> // Define the transform function based on the mode.
<ide> var transform = mode == "offset"
<del> ? function(d) { return "translate(0," + (d + (d < 0) - bands) * h + ")"; }
<del> : function(d) { return (d < 0 ? "scale(1,-1)" : "") + "translate(0," + (d - bands) * h + ")"; };
<add> ? function(d) { return "translate(0," + (d + (d < 0) - bands) * height + ")"; }
<add> : function(d) { return (d < 0 ? "scale(1,-1)" : "") + "translate(0," + (d - bands) * height + ")"; };
<ide>
<ide> // Instantiate each copy of the path with different transforms.
<ide> var u = g.select("g").selectAll("use")
<ide> function horizonChart() {
<ide> };
<ide>
<ide> horizon.width = function(x) {
<del> if (!arguments.length) return w;
<del> w = +x;
<add> if (!arguments.length) return width;
<add> width = +x;
<ide> return horizon;
<ide> };
<ide>
<ide> horizon.height = function(x) {
<del> if (!arguments.length) return h;
<del> h = +x;
<add> if (!arguments.length) return height;
<add> height = +x;
<ide> return horizon;
<ide> };
<ide> | 1 |
Ruby | Ruby | canonicalize `input` in `initialize` | 3ff9c5335d8c397c2257a4e59c49ad095074b73e | <ide><path>Library/Homebrew/cask/lib/hbc/system_command.rb
<ide> def initialize(executable, args: [], sudo: false, input: [], print_stdout: false
<ide> @executable = executable
<ide> @args = args
<ide> @sudo = sudo
<del> @input = input
<add> @input = [*input]
<ide> @print_stdout = print_stdout
<ide> @print_stderr = print_stderr
<ide> @must_succeed = must_succeed
<ide> def each_output_line(&b)
<ide> end
<ide>
<ide> def write_input_to(raw_stdin)
<del> [*input].each(&raw_stdin.method(:print))
<add> input.each(&raw_stdin.method(:write))
<ide> end
<ide>
<ide> def each_line_from(sources) | 1 |
Text | Text | fix spelling of associations | c5c4fc155b49bcf5c99cd7f453153d98c13810d1 | <ide><path>guides/source/active_record_migrations.md
<ide> add_belongs_to :taggings, :taggable, polymorphic: true
<ide> ```
<ide>
<ide> The polymorphic option will create two columns on the taggings table which can
<del>be used for polymorphic assocations: `taggable_type` and `taggable_id`.
<add>be used for polymorphic associations: `taggable_type` and `taggable_id`.
<ide>
<ide> A foreign key can be created with the the `foreign_key` option.
<ide> | 1 |
Python | Python | improve system tests for cloud build | 49abce52178c81954f8a25608f70ffe02fcf7b19 | <ide><path>airflow/providers/google/cloud/example_dags/example_cloud_build.py
<ide> GCP_PROJECT_ID = os.environ.get("GCP_PROJECT_ID", "example-project")
<ide>
<ide> GCP_SOURCE_ARCHIVE_URL = os.environ.get("GCP_CLOUD_BUILD_ARCHIVE_URL", "gs://example-bucket/file")
<del>GCP_SOURCE_REPOSITORY_NAME = os.environ.get("GCP_CLOUD_BUILD_REPOSITORY_NAME", "")
<add>GCP_SOURCE_REPOSITORY_NAME = os.environ.get("GCP_CLOUD_BUILD_REPOSITORY_NAME", "repository-name")
<ide>
<ide> GCP_SOURCE_ARCHIVE_URL_PARTS = urlparse(GCP_SOURCE_ARCHIVE_URL)
<ide> GCP_SOURCE_BUCKET_NAME = GCP_SOURCE_ARCHIVE_URL_PARTS.netloc
<ide><path>tests/providers/google/cloud/operators/test_cloud_build_operator_system.py
<ide> class CloudBuildExampleDagsSystemTest(GoogleSystemTest):
<ide> """
<ide> helper = GCPCloudBuildTestHelper()
<ide>
<del> @provide_gcp_context(GCP_CLOUD_BUILD_KEY)
<add> @provide_gcp_context(GCP_CLOUD_BUILD_KEY, project_id=GoogleSystemTest._project_id())
<ide> def setUp(self):
<ide> super().setUp()
<ide> self.helper.create_repository_and_bucket()
<ide> def setUp(self):
<ide> def test_run_example_dag(self):
<ide> self.run_dag("example_gcp_cloud_build", CLOUD_DAG_FOLDER)
<ide>
<del> @provide_gcp_context(GCP_CLOUD_BUILD_KEY)
<add> @provide_gcp_context(GCP_CLOUD_BUILD_KEY, project_id=GoogleSystemTest._project_id())
<ide> def tearDown(self):
<ide> self.helper.delete_bucket()
<ide> self.helper.delete_docker_images()
<ide><path>tests/providers/google/cloud/operators/test_cloud_build_system_helper.py
<ide> from tests.providers.google.cloud.utils.gcp_authenticator import GCP_CLOUD_BUILD_KEY, GcpAuthenticator
<ide> from tests.utils.logging_command_executor import LoggingCommandExecutor
<ide>
<del>GCE_INSTANCE = os.environ.get("GCE_INSTANCE", "testinstance")
<ide> GCP_PROJECT_ID = os.environ.get("GCP_PROJECT_ID", "example-project")
<ide> GCP_ARCHIVE_URL = os.environ.get("GCP_CLOUD_BUILD_ARCHIVE_URL", "gs://example-bucket/source-code.tar.gz")
<ide> GCP_ARCHIVE_URL_PARTS = urlparse(GCP_ARCHIVE_URL)
<ide> def create_repository_and_bucket(self):
<ide> self.execute_cmd(["gcloud", "source", "repos", "create", GCP_REPOSITORY_NAME])
<ide> self.execute_cmd(["git", "init"], cwd=tmp_dir)
<ide> self.execute_cmd(["git", "config", "user.email", "bot@example.com"], cwd=tmp_dir)
<del> self.execute_cmd(["git", "config", "user.name", "system-test"])
<add> self.execute_cmd(["git", "config", "user.name", "system-test"], cwd=tmp_dir)
<ide> self.execute_cmd(
<ide> ["git", "config", "credential.https://source.developers.google.com.helper", "gcloud.sh"],
<ide> cwd=tmp_dir,
<ide> def create_repository_and_bucket(self):
<ide> GCP_PROJECT_ID, GCP_REPOSITORY_NAME
<ide> )
<ide> self.execute_cmd(["git", "remote", "add", "origin", repo_url], cwd=tmp_dir)
<del> self.execute_cmd(["git", "push", "origin", "master"], cwd=tmp_dir)
<add> self.execute_cmd(["git", "push", "--force", "origin", "master"], cwd=tmp_dir)
<ide>
<ide> def delete_repo(self):
<ide> """Delete repository in Google Cloud Source Repository service"""
<ide> def delete_repo(self):
<ide> def delete_bucket(self):
<ide> """Delete bucket in Google Cloud Storage service"""
<ide>
<del> self.execute_cmd(["gsutil", "rb", "gs://{}".format(GCP_BUCKET_NAME)])
<add> self.execute_cmd(["gsutil", "rm", "-r", "gs://{}".format(GCP_BUCKET_NAME)])
<ide>
<ide> def delete_docker_images(self):
<ide> """Delete images in Google Cloud Container Registry"""
<ide>
<ide> repo_image_name = "gcr.io/{}/{}".format(GCP_PROJECT_ID, GCP_REPOSITORY_NAME)
<del> self.execute_cmd(["gcloud", "container", "images", "delete", repo_image_name])
<add> self.execute_cmd(["gcloud", "container", "images", "delete", "--quiet", repo_image_name])
<ide> bucket_image_name = "gcr.io/{}/{}".format(GCP_PROJECT_ID, GCP_BUCKET_NAME)
<del> self.execute_cmd(["gcloud", "container", "images", "delete", bucket_image_name])
<add> self.execute_cmd(["gcloud", "container", "images", "delete", "--quiet", bucket_image_name])
<ide>
<ide>
<ide> if __name__ == "__main__": | 3 |
Javascript | Javascript | remove getmaxviews() from multiview | f1936dc7af6bbcb34725e497f604d77f4039dea8 | <ide><path>src/renderers/WebGLRenderer.js
<ide> function WebGLRenderer( parameters ) {
<ide>
<ide> if ( capabilities.multiview ) {
<ide>
<del> multiview.attachRenderTarget( camera );
<add> multiview.attachCamera( camera );
<ide>
<ide> }
<ide>
<ide><path>src/renderers/webgl/WebGLCapabilities.js
<ide> function WebGLCapabilities( gl, extensions, parameters ) {
<ide> var maxSamples = isWebGL2 ? gl.getParameter( gl.MAX_SAMPLES ) : 0;
<ide>
<ide> var multiviewExt = extensions.get( 'OVR_multiview2' );
<del> var multiview = isWebGL2 && ( !! multiviewExt ) && !gl.getContextAttributes().antialias;
<add> var multiview = isWebGL2 && ( !! multiviewExt ) && ! gl.getContextAttributes().antialias;
<ide> var maxMultiviewViews = multiview ? gl.getParameter( multiviewExt.MAX_VIEWS_OVR ) : 0;
<ide>
<ide> return {
<ide><path>src/renderers/webgl/WebGLMultiview.js
<ide> function WebGLMultiview( renderer, gl ) {
<ide> var renderTarget, currentRenderTarget;
<ide> var mat3, mat4, cameraArray, renderSize;
<ide>
<del> function getMaxViews() {
<del>
<del> return capabilities.maxMultiviewViews;
<del>
<del> }
<del>
<ide> function getCameraArray( camera ) {
<ide>
<ide> if ( camera.isArrayCamera ) return camera.cameras;
<ide> function WebGLMultiview( renderer, gl ) {
<ide>
<ide> }
<ide>
<del> function attachRenderTarget( camera ) {
<add> function attachCamera( camera ) {
<ide>
<ide> if ( ! isMultiviewCompatible( camera ) ) return;
<ide>
<ide> function WebGLMultiview( renderer, gl ) {
<ide> mat3 = [];
<ide> cameraArray = [];
<ide>
<del> for ( var i = 0; i < getMaxViews(); i ++ ) {
<add> var maxViews = capabilities.maxMultiviewViews;
<add>
<add> for ( var i = 0; i < maxViews; i ++ ) {
<ide>
<ide> mat4[ i ] = new Matrix4();
<ide> mat3[ i ] = new Matrix3();
<ide> function WebGLMultiview( renderer, gl ) {
<ide> }
<ide>
<ide>
<del> this.attachRenderTarget = attachRenderTarget;
<add> this.attachCamera = attachCamera;
<ide> this.detachRenderTarget = detachRenderTarget;
<ide> this.updateCameraProjectionMatricesUniform = updateCameraProjectionMatricesUniform;
<ide> this.updateCameraViewMatricesUniform = updateCameraViewMatricesUniform;
<ide><path>src/renderers/webgl/WebGLProgram.js
<ide> import { WebGLUniforms } from './WebGLUniforms.js';
<ide> import { WebGLShader } from './WebGLShader.js';
<ide> import { ShaderChunk } from '../shaders/ShaderChunk.js';
<ide> import { NoToneMapping, AddOperation, MixOperation, MultiplyOperation, EquirectangularRefractionMapping, CubeRefractionMapping, SphericalReflectionMapping, EquirectangularReflectionMapping, CubeUVRefractionMapping, CubeUVReflectionMapping, CubeReflectionMapping, PCFSoftShadowMap, PCFShadowMap, VSMShadowMap, ACESFilmicToneMapping, CineonToneMapping, Uncharted2ToneMapping, ReinhardToneMapping, LinearToneMapping, GammaEncoding, RGBDEncoding, RGBM16Encoding, RGBM7Encoding, RGBEEncoding, sRGBEncoding, LinearEncoding, LogLuvEncoding } from '../../constants.js';
<del>import { WebGLMultiviewRenderTarget } from '../WebGLMultiviewRenderTarget.js';
<ide>
<ide> var programIdCount = 0;
<ide>
<ide> function WebGLProgram( renderer, extensions, code, material, shader, parameters,
<ide> var prefixVertex, prefixFragment;
<ide>
<ide> var renderTarget = renderer.getRenderTarget();
<del> var numMultiviewViews = renderTarget instanceof WebGLMultiviewRenderTarget ? renderTarget.numViews : 0;
<add> var numMultiviewViews = renderTarget && renderTarget.isWebGLMultiviewRenderTarget ? renderTarget.numViews : 0;
<ide>
<ide> if ( material.isRawShaderMaterial ) {
<ide> | 4 |
Javascript | Javascript | fix error when trying to reload page from worker | 0ddddf46b5eda704bea70c2704693c2bf9d4dd44 | <ide><path>hot/dev-server.js
<ide> if (module.hot) {
<ide> if (["abort", "fail"].indexOf(status) >= 0) {
<ide> log(
<ide> "warning",
<del> "[HMR] Cannot apply update. Need to do a full reload!"
<add> `[HMR] Cannot apply update. ${(
<add> typeof window !== "undefined"
<add> ? "Need to do a full reload!"
<add> : "Please reload manually!"
<add> )}`
<ide> );
<ide> log("warning", "[HMR] " + log.formatError(err));
<del> window.location.reload();
<add> if (typeof window !== "undefined") {
<add> window.location.reload();
<add> }
<ide> } else {
<ide> log("warning", "[HMR] Update failed: " + log.formatError(err));
<ide> } | 1 |
Java | Java | update copyright date | 9f7a94058a4bbc967fe47bfe6a82d88cb3feddfb | <ide><path>spring-aop/src/main/java/org/aopalliance/intercept/Joinpoint.java
<ide> /*
<del> * Copyright 2002-2016 the original author or authors.
<add> * Copyright 2002-2021 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><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/RequestPredicate.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2021 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><path>spring-webmvc/src/main/java/org/springframework/web/servlet/function/RequestPredicate.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2021 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><path>spring-websocket/src/main/java/org/springframework/web/socket/adapter/standard/ConvertingEncoderDecoderSupport.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 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. | 4 |
Javascript | Javascript | add mockingbot to showcase | da9e9e709b42a8875d38977c4ae37c88de92b084 | <ide><path>website/src/react-native/showcase.js
<ide> var apps = [
<ide> link: 'https://itunes.apple.com/us/app/yazboz-batak-esli-batak-okey/id1048620855?ls=1&mt=8',
<ide> author: 'Melih Mucuk',
<ide> },
<add> {
<add> name: 'MockingBot',
<add> icon: 'https://s3.cn-north-1.amazonaws.com.cn/modao/downloads/images/MockingBot175.png',
<add> link: 'https://itunes.apple.com/cn/app/mockingbot/id1050565468?l=en&mt=8',
<add> author: 'YuanYi Zhang (@mockingbot)',
<add> },
<ide> ];
<ide>
<ide> var AppList = React.createClass({ | 1 |
Ruby | Ruby | remove gem setup for stackprof | d4b88b1b55eb9505fac9f2aaab10b59d25f5bab2 | <ide><path>Library/Homebrew/brew.rb
<ide> # frozen_string_literal: true
<ide>
<ide> if ENV["HOMEBREW_STACKPROF"]
<del> require_relative "utils/gems"
<del> Homebrew.setup_gem_environment!
<ide> require "stackprof"
<ide> StackProf.start(mode: :wall, raw: true)
<ide> end | 1 |
Python | Python | use super instead | 7f2ebd8560adc3cfc1f430eada250385c3c633c5 | <ide><path>libcloud/test/compute/test_elasticstack.py
<ide> ElasticStackBaseConnection,
<ide> ElasticStackBaseNodeDriver as ElasticStack)
<ide> from libcloud.compute.drivers.elastichosts import \
<del> (ElasticHostsBaseNodeDriver as ElasticHosts)
<add> (ElasticHostsNodeDriver as ElasticHosts)
<ide> from libcloud.compute.drivers.skalicloud import \
<ide> (SkaliCloudNodeDriver as SkaliCloud)
<ide> from libcloud.compute.drivers.serverlove import \
<ide> def setUp(self):
<ide> images = self.driver.list_images()
<ide> self.image = [i for i in images if \
<ide> i.id == '38df0986-4d85-4b76-b502-3878ffc80161'][0]
<del>
<del> ElasticStackTestCase.setUp(self)
<del> unittest.TestCase.setUp(self)
<add> super(ElasticHostsTestCase, self).setUp()
<ide>
<ide>
<ide> class SkaliCloudTestCase(ElasticStackTestCase, unittest.TestCase):
<ide> def setUp(self):
<ide> images = self.driver.list_images()
<ide> self.image = [i for i in images if \
<ide> i.id == '90aa51f2-15c0-4cff-81ee-e93aa20b9468'][0]
<del>
<del> ElasticStackTestCase.setUp(self)
<del> unittest.TestCase.setUp(self)
<add> super(SkaliCloudTestCase, self).setUp()
<ide>
<ide>
<ide> class ServerLoveTestCase(ElasticStackTestCase, unittest.TestCase):
<ide> def setUp(self):
<ide> images = self.driver.list_images()
<ide> self.image = [i for i in images if \
<ide> i.id == '679f5f44-0be7-4745-a658-cccd4334c1aa'][0]
<del>
<del> ElasticStackTestCase.setUp(self)
<del> unittest.TestCase.setUp(self)
<add> super(ServerLoveTestCase, self).setUp()
<ide>
<ide>
<ide> class ElasticStackMockHttp(MockHttp): | 1 |
Ruby | Ruby | fix usage of `homebrew_load_path` | 18e46b3ec2068310a133f183564f41d183995346 | <ide><path>Library/Homebrew/brew.rb
<ide> HOMEBREW_LIBRARY_PATH = Pathname.new(__FILE__).realpath.parent
<ide>
<ide> require "English"
<del>unless $LOAD_PATH.include?(HOMEBREW_LIBRARY_PATH.to_s)
<del> $LOAD_PATH.unshift(HOMEBREW_LIBRARY_PATH.to_s)
<del>end
<ide>
<ide> unless $LOAD_PATH.include?("#{HOMEBREW_LIBRARY_PATH}/cask/lib")
<ide> $LOAD_PATH.unshift("#{HOMEBREW_LIBRARY_PATH}/cask/lib")
<ide> end
<ide>
<add>unless $LOAD_PATH.include?(HOMEBREW_LIBRARY_PATH.to_s)
<add> $LOAD_PATH.unshift(HOMEBREW_LIBRARY_PATH.to_s)
<add>end
<add>
<ide> require "global"
<ide>
<ide> begin
<ide><path>Library/Homebrew/config.rb
<ide> end
<ide>
<ide> # Load path used by standalone scripts to access the Homebrew code base
<del>HOMEBREW_LOAD_PATH = HOMEBREW_LIBRARY_PATH
<add>HOMEBREW_LOAD_PATH = [
<add> HOMEBREW_LIBRARY_PATH,
<add> HOMEBREW_LIBRARY_PATH/"cask/lib",
<add>].join(File::PATH_SEPARATOR)
<ide><path>Library/Homebrew/dev-cmd/ruby.rb
<ide> module Homebrew
<ide> module_function
<ide>
<ide> def ruby
<del> exec ENV["HOMEBREW_RUBY_PATH"], "-I#{HOMEBREW_LIBRARY_PATH}", "-rglobal", "-rdev-cmd/irb", *ARGV
<add> exec ENV["HOMEBREW_RUBY_PATH"], "-I", HOMEBREW_LOAD_PATH, "-rglobal", "-rdev-cmd/irb", *ARGV
<ide> end
<ide> end
<ide><path>Library/Homebrew/test/spec_helper.rb
<ide> require "rubocop/rspec/support"
<ide> require "find"
<ide>
<del>$LOAD_PATH.unshift(File.expand_path("#{ENV["HOMEBREW_LIBRARY"]}/Homebrew"))
<ide> $LOAD_PATH.unshift(File.expand_path("#{ENV["HOMEBREW_LIBRARY"]}/Homebrew/cask/lib"))
<add>$LOAD_PATH.unshift(File.expand_path("#{ENV["HOMEBREW_LIBRARY"]}/Homebrew"))
<ide> $LOAD_PATH.unshift(File.expand_path("#{ENV["HOMEBREW_LIBRARY"]}/Homebrew/test/support/lib"))
<ide>
<ide> require "global"
<ide><path>Library/Homebrew/test/support/helper/spec/shared_context/integration_test.rb
<ide> def brew(*args)
<ide> @ruby_args ||= begin
<ide> ruby_args = [
<ide> "-W0",
<del> "-I", "#{HOMEBREW_LIBRARY_PATH}/test/support/lib",
<del> "-I", HOMEBREW_LIBRARY_PATH.to_s,
<del> "-I", "#{HOMEBREW_LIBRARY_PATH}/cask/lib",
<add> "-I", HOMEBREW_LOAD_PATH,
<ide> "-rconfig"
<ide> ]
<ide> if ENV["HOMEBREW_TESTS_COVERAGE"]
<ide><path>Library/Homebrew/test/support/lib/config.rb
<ide> # Paths pointing into the Homebrew code base that persist across test runs
<ide> HOMEBREW_LIBRARY_PATH = Pathname.new(File.expand_path("../../..", __dir__))
<ide> HOMEBREW_SHIMS_PATH = HOMEBREW_LIBRARY_PATH.parent+"Homebrew/shims"
<del>HOMEBREW_LOAD_PATH = [File.expand_path(__dir__), HOMEBREW_LIBRARY_PATH].join(":")
<add>HOMEBREW_LOAD_PATH = [
<add> File.expand_path(__dir__),
<add> HOMEBREW_LIBRARY_PATH,
<add> HOMEBREW_LIBRARY_PATH.join("cask/lib"),
<add>].join(File::PATH_SEPARATOR)
<ide>
<ide> # Paths redirected to a temporary directory and wiped at the end of the test run
<ide> HOMEBREW_PREFIX = Pathname.new(TEST_TMPDIR).join("prefix") | 6 |
Ruby | Ruby | fix a routing test. reorganize middleware tests | 609849a0f10ce37d96444f0359ce325b01d916ca | <ide><path>railties/test/application/middleware/best_practices_test.rb
<add>require 'isolation/abstract_unit'
<add>
<add>module ApplicationTests
<add> class BestPracticesTest < Test::Unit::TestCase
<add> include ActiveSupport::Testing::Isolation
<add>
<add> def setup
<add> build_app
<add> boot_rails
<add> require 'rack/test'
<add> extend Rack::Test::Methods
<add> simple_controller
<add> end
<add>
<add> test "simple controller in production mode returns best standards" do
<add> get '/foo'
<add> assert_equal "IE=Edge,chrome=1", last_response.headers["X-UA-Compatible"]
<add> end
<add>
<add> test "simple controller in development mode leaves out Chrome" do
<add> app("development")
<add> get "/foo"
<add> assert_equal "IE=Edge", last_response.headers["X-UA-Compatible"]
<add> end
<add> end
<add>end
<ide><path>railties/test/application/middleware/cache_test.rb
<ide> def setup
<ide> extend Rack::Test::Methods
<ide> end
<ide>
<del> def app(env = "production")
<del> old_env = ENV["RAILS_ENV"]
<del>
<del> @app ||= begin
<del> ENV["RAILS_ENV"] = env
<del> require "#{app_path}/config/environment"
<del> Rails.application
<del> end
<del> ensure
<del> ENV["RAILS_ENV"] = old_env
<del> end
<del>
<ide> def simple_controller
<ide> controller :expires, <<-RUBY
<ide> class ExpiresController < ApplicationController
<ide><path>railties/test/application/middleware/remote_ip_test.rb
<add>require 'isolation/abstract_unit'
<add>
<add>module ApplicationTests
<add> class RemoteIpTest < Test::Unit::TestCase
<add> include ActiveSupport::Testing::Isolation
<add>
<add> def setup
<add> build_app
<add> boot_rails
<add> FileUtils.rm_rf "#{app_path}/config/environments"
<add> end
<add>
<add> def app
<add> @app ||= Rails.application
<add> end
<add>
<add> def remote_ip(env = {})
<add> remote_ip = nil
<add> env = Rack::MockRequest.env_for("/").merge(env).merge!(
<add> 'action_dispatch.show_exceptions' => false,
<add> 'action_dispatch.secret_token' => 'b3c631c314c0bbca50c1b2843150fe33'
<add> )
<add>
<add> endpoint = Proc.new do |e|
<add> remote_ip = ActionDispatch::Request.new(e).remote_ip
<add> [200, {}, ["Hello"]]
<add> end
<add>
<add> Rails.application.middleware.build(endpoint).call(env)
<add> remote_ip
<add> end
<add>
<add> test "remote_ip works" do
<add> make_basic_app
<add> assert_equal "1.1.1.1", remote_ip("REMOTE_ADDR" => "1.1.1.1")
<add> end
<add>
<add> test "checks IP spoofing by default" do
<add> make_basic_app
<add> assert_raises(ActionDispatch::RemoteIp::IpSpoofAttackError) do
<add> remote_ip("HTTP_X_FORWARDED_FOR" => "1.1.1.1", "HTTP_CLIENT_IP" => "1.1.1.2")
<add> end
<add> end
<add>
<add> test "can disable IP spoofing check" do
<add> make_basic_app do |app|
<add> app.config.action_dispatch.ip_spoofing_check = false
<add> end
<add>
<add> assert_nothing_raised(ActionDispatch::RemoteIp::IpSpoofAttackError) do
<add> assert_equal "1.1.1.2", remote_ip("HTTP_X_FORWARDED_FOR" => "1.1.1.1", "HTTP_CLIENT_IP" => "1.1.1.2")
<add> end
<add> end
<add>
<add> test "the user can set trusted proxies" do
<add> make_basic_app do |app|
<add> app.config.action_dispatch.trusted_proxies = /^4\.2\.42\.42$/
<add> end
<add>
<add> assert_equal "1.1.1.1", remote_ip("REMOTE_ADDR" => "4.2.42.42,1.1.1.1")
<add> end
<add> end
<add>end
<ide><path>railties/test/application/middleware/sendfile_test.rb
<add>require 'isolation/abstract_unit'
<add>
<add>module ApplicationTests
<add> class SendfileTest < Test::Unit::TestCase
<add> include ActiveSupport::Testing::Isolation
<add>
<add> def setup
<add> build_app
<add> boot_rails
<add> FileUtils.rm_rf "#{app_path}/config/environments"
<add> end
<add>
<add> def app
<add> @app ||= Rails.application
<add> end
<add>
<add> define_method :simple_controller do
<add> class ::OmgController < ActionController::Base
<add> def index
<add> send_file __FILE__
<add> end
<add> end
<add> end
<add>
<add> # x_sendfile_header middleware
<add> test "config.action_dispatch.x_sendfile_header defaults to ''" do
<add> make_basic_app
<add> simple_controller
<add>
<add> get "/"
<add> assert_equal File.read(__FILE__), last_response.body
<add> end
<add>
<add> test "config.action_dispatch.x_sendfile_header can be set" do
<add> make_basic_app do |app|
<add> app.config.action_dispatch.x_sendfile_header = "X-Sendfile"
<add> end
<add>
<add> simple_controller
<add>
<add> get "/"
<add> assert_equal File.expand_path(__FILE__), last_response.headers["X-Sendfile"]
<add> end
<add>
<add> test "config.action_dispatch.x_sendfile_header is sent to Rack::Sendfile" do
<add> make_basic_app do |app|
<add> app.config.action_dispatch.x_sendfile_header = 'X-Lighttpd-Send-File'
<add> end
<add>
<add> simple_controller
<add>
<add> get "/"
<add> assert_equal File.expand_path(__FILE__), last_response.headers["X-Lighttpd-Send-File"]
<add> end
<add> end
<add>end
<ide><path>railties/test/application/middleware_test.rb
<ide> def app
<ide> assert_equal "Rack::Config", middleware.first
<ide> end
<ide>
<del> # x_sendfile_header middleware
<del> test "config.action_dispatch.x_sendfile_header defaults to ''" do
<del> make_basic_app
<del>
<del> class ::OmgController < ActionController::Base
<del> def index
<del> send_file __FILE__
<del> end
<del> end
<del>
<del> get "/"
<del> assert_equal File.read(__FILE__), last_response.body
<del> end
<del>
<del> test "config.action_dispatch.x_sendfile_header can be set" do
<del> make_basic_app do |app|
<del> app.config.action_dispatch.x_sendfile_header = "X-Sendfile"
<del> end
<del>
<del> class ::OmgController < ActionController::Base
<del> def index
<del> send_file __FILE__
<del> end
<del> end
<del>
<del> get "/"
<del> assert_equal File.expand_path(__FILE__), last_response.headers["X-Sendfile"]
<del> end
<del>
<del> test "config.action_dispatch.x_sendfile_header is sent to Rack::Sendfile" do
<del> make_basic_app do |app|
<del> app.config.action_dispatch.x_sendfile_header = 'X-Lighttpd-Send-File'
<del> end
<del>
<del> class ::OmgController < ActionController::Base
<del> def index
<del> send_file __FILE__
<del> end
<del> end
<del>
<del> get "/"
<del> assert_equal File.expand_path(__FILE__), last_response.headers["X-Lighttpd-Send-File"]
<del> end
<del>
<del> # remote_ip tests
<del> test "remote_ip works" do
<del> make_basic_app
<del> assert_equal "1.1.1.1", remote_ip("REMOTE_ADDR" => "1.1.1.1")
<del> end
<del>
<del> test "checks IP spoofing by default" do
<del> make_basic_app
<del> assert_raises(ActionDispatch::RemoteIp::IpSpoofAttackError) do
<del> remote_ip("HTTP_X_FORWARDED_FOR" => "1.1.1.1", "HTTP_CLIENT_IP" => "1.1.1.2")
<del> end
<del> end
<del>
<del> test "can disable IP spoofing check" do
<del> make_basic_app do |app|
<del> app.config.action_dispatch.ip_spoofing_check = false
<del> end
<del>
<del> assert_nothing_raised(ActionDispatch::RemoteIp::IpSpoofAttackError) do
<del> assert_equal "1.1.1.2", remote_ip("HTTP_X_FORWARDED_FOR" => "1.1.1.1", "HTTP_CLIENT_IP" => "1.1.1.2")
<del> end
<del> end
<del>
<del> test "the user can set trusted proxies" do
<del> make_basic_app do |app|
<del> app.config.action_dispatch.trusted_proxies = /^4\.2\.42\.42$/
<del> end
<del>
<del> assert_equal "1.1.1.1", remote_ip("REMOTE_ADDR" => "4.2.42.42,1.1.1.1")
<del> end
<del>
<ide> test "show exceptions middleware filter backtrace before logging" do
<ide> my_middleware = Struct.new(:app) do
<ide> def call(env)
<ide> def boot!
<ide> def middleware
<ide> AppTemplate::Application.middleware.map(&:klass).map(&:name)
<ide> end
<del>
<del> def remote_ip(env = {})
<del> remote_ip = nil
<del> env = Rack::MockRequest.env_for("/").merge(env).merge!(
<del> 'action_dispatch.show_exceptions' => false,
<del> 'action_dispatch.secret_token' => 'b3c631c314c0bbca50c1b2843150fe33'
<del> )
<del>
<del> endpoint = Proc.new do |e|
<del> remote_ip = ActionDispatch::Request.new(e).remote_ip
<del> [200, {}, ["Hello"]]
<del> end
<del>
<del> Rails.application.middleware.build(endpoint).call(env)
<del> remote_ip
<del> end
<ide> end
<ide> end
<ide><path>railties/test/application/routing_test.rb
<ide> def setup
<ide> extend Rack::Test::Methods
<ide> end
<ide>
<del> def app(env = "production")
<del> old_env = ENV["RAILS_ENV"]
<del>
<del> @app ||= begin
<del> ENV["RAILS_ENV"] = env
<del> require "#{app_path}/config/environment"
<del> Rails.application
<del> end
<del> ensure
<del> ENV["RAILS_ENV"] = old_env
<del> end
<del>
<del> def simple_controller
<del> controller :foo, <<-RUBY
<del> class FooController < ApplicationController
<del> def index
<del> render :text => "foo"
<del> end
<del> end
<del> RUBY
<del>
<del> app_file 'config/routes.rb', <<-RUBY
<del> AppTemplate::Application.routes.draw do
<del> match ':controller(/:action)'
<del> end
<del> RUBY
<del> end
<del>
<ide> test "rails/info/properties in development" do
<ide> app("development")
<ide> get "/rails/info/properties"
<ide> def index
<ide> assert_equal 'foo', last_response.body
<ide> end
<ide>
<del> test "simple controller in production mode returns best standards" do
<del> simple_controller
<del>
<del> get '/foo'
<del> assert_equal "IE=Edge,chrome=1", last_response.headers["X-UA-Compatible"]
<del> end
<del>
<del> test "simple controller in development mode leaves out Chrome" do
<del> simple_controller
<del> app("development")
<del>
<del> get "/foo"
<del> assert_equal "IE=Edge", last_response.headers["X-UA-Compatible"]
<del> end
<del>
<ide> test "simple controller with helper" do
<ide> controller :foo, <<-RUBY
<ide> class FooController < ApplicationController
<ide> def index
<ide> assert_equal 'admin::foo', last_response.body
<ide> end
<ide>
<del> def test_reloads_appended_route_blocks
<add> test "routes appending blocks" do
<ide> app_file 'config/routes.rb', <<-RUBY
<ide> AppTemplate::Application.routes.draw do
<ide> match ':controller#:action'
<ide> def baz
<ide> test 'routes are loaded just after initialization' do
<ide> require "#{app_path}/config/application"
<ide>
<del> app_file 'config/routes.rb', <<-RUBY
<del> InitializeRackApp = lambda { |env| [200, {}, ["InitializeRackApp"]] }
<add> # Create the rack app just inside after initialize callback
<add> ActiveSupport.on_load(:after_initialize) do
<add> ::InitializeRackApp = lambda { |env| [200, {}, ["InitializeRackApp"]] }
<add> end
<ide>
<del> AppTemplate::Application.routes.draw do
<add> app_file 'config/routes.rb', <<-RUBY
<add> AppTemplate::Application.routes.draw do |map|
<ide> match 'foo', :to => ::InitializeRackApp
<ide> end
<ide> RUBY
<ide> def baz
<ide> assert_equal "InitializeRackApp", last_response.body
<ide> end
<ide>
<del> test 'resource routing with irrigular inflection' do
<add> test 'resource routing with irregular inflection' do
<ide> app_file 'config/initializers/inflection.rb', <<-RUBY
<ide> ActiveSupport::Inflector.inflections do |inflect|
<ide> inflect.irregular 'yazi', 'yazilar'
<ide><path>railties/test/isolation/abstract_unit.rb
<ide> def rails_root
<ide> end
<ide>
<ide> module Rack
<add> def app(env = "production")
<add> old_env = ENV["RAILS_ENV"]
<add> @app ||= begin
<add> ENV["RAILS_ENV"] = env
<add> require "#{app_path}/config/environment"
<add> Rails.application
<add> end
<add> ensure
<add> ENV["RAILS_ENV"] = old_env
<add> end
<add>
<ide> def extract_body(response)
<ide> "".tap do |body|
<ide> response[2].each {|chunk| body << chunk }
<ide> def make_basic_app
<ide> extend ::Rack::Test::Methods
<ide> end
<ide>
<add> def simple_controller
<add> controller :foo, <<-RUBY
<add> class FooController < ApplicationController
<add> def index
<add> render :text => "foo"
<add> end
<add> end
<add> RUBY
<add>
<add> app_file 'config/routes.rb', <<-RUBY
<add> AppTemplate::Application.routes.draw do
<add> match ':controller(/:action)'
<add> end
<add> RUBY
<add> end
<add>
<ide> class Bukkit
<ide> attr_reader :path
<ide> | 7 |
Java | Java | fix minor issue in stomp broker relay | 1fa4a7d34f56b85753fb38f54a4bc6d5f1c837db | <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandler.java
<ide> public class StompBrokerRelayMessageHandler extends AbstractBrokerMessageHandler
<ide> static {
<ide> SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(SimpMessageType.HEARTBEAT);
<ide> HEARTBEAT_MESSAGE = MessageBuilder.withPayload(new byte[] {'\n'}).setHeaders(headers).build();
<add> EMPTY_TASK.run();
<ide> }
<ide>
<ide> | 1 |
Java | Java | reset pointerevents on null value | 866ac173318bd5518b5ed78c2e3da764436be39a | <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewManager.java
<ide> public void setHitSlop(final ReactViewGroup view, @Nullable ReadableMap hitSlop)
<ide>
<ide> @ReactProp(name = ViewProps.POINTER_EVENTS)
<ide> public void setPointerEvents(ReactViewGroup view, @Nullable String pointerEventsStr) {
<del> if (pointerEventsStr != null) {
<add> if (pointerEventsStr == null) {
<add> view.setPointerEvents(PointerEvents.AUTO);
<add> } else {
<ide> PointerEvents pointerEvents =
<ide> PointerEvents.valueOf(pointerEventsStr.toUpperCase(Locale.US).replace("-", "_"));
<ide> view.setPointerEvents(pointerEvents); | 1 |
PHP | PHP | fix error in marshalling belongstomany relations | 85aecb628f2cdd4452f681f1125f54907e2b1395 | <ide><path>src/ORM/Marshaller.php
<ide> public function many(array $data, array $include = []) {
<ide> * @return array An array of built entities.
<ide> */
<ide> protected function _belongsToMany(Association $assoc, array $data, $include = []) {
<del> $hasIds = isset($data['_ids']);
<add> $hasIds = array_key_exists('_ids', $data);
<ide> if ($hasIds && is_array($data['_ids'])) {
<ide> return $this->_loadBelongsToMany($assoc, $data['_ids']);
<ide> }
<ide> protected function _mergeAssociation($original, $assoc, $value, $include) {
<ide> * @return mixed
<ide> */
<ide> protected function _mergeBelongsToMany($original, $assoc, $value, $include) {
<del> if (isset($value['_ids']) && is_array($value['_ids'])) {
<add> $hasIds = array_key_exists('_ids', $value);
<add> if ($hasIds && is_array($value['_ids'])) {
<ide> return $this->_loadBelongsToMany($assoc, $value['_ids']);
<ide> }
<add> if ($hasIds) {
<add> return [];
<add> }
<ide>
<ide> if (!in_array('_joinData', $include) && !isset($include['_joinData'])) {
<ide> return $this->mergeMany($original, $value, $include);
<ide><path>tests/TestCase/ORM/MarshallerTest.php
<ide> public function testOneGenerateBelongsToManyEntitiesFromIds() {
<ide> ];
<ide> $marshall = new Marshaller($this->articles);
<ide> $result = $marshall->one($data, ['Tags']);
<add> $this->assertCount(0, $result->tags);
<ide>
<add> $data = [
<add> 'title' => 'Haz tags',
<add> 'body' => 'Some content here',
<add> 'tags' => ['_ids' => false]
<add> ];
<add> $result = $marshall->one($data, ['Tags']);
<add> $this->assertCount(0, $result->tags);
<add>
<add> $data = [
<add> 'title' => 'Haz tags',
<add> 'body' => 'Some content here',
<add> 'tags' => ['_ids' => null]
<add> ];
<add> $result = $marshall->one($data, ['Tags']);
<ide> $this->assertCount(0, $result->tags);
<ide>
<ide> $data = [
<ide> public function testMergeBelongsToManyEntitiesFromIds() {
<ide> $this->assertInstanceOf('Cake\ORM\Entity', $result->tags[2]);
<ide> }
<ide>
<add>/**
<add> * Tests that merging data to an entity containing belongsToMany and _ids
<add> * will ignore empty values.
<add> *
<add> * @return void
<add> */
<add> public function testMergeBelongsToManyEntitiesFromIdsEmptyValue() {
<add> $entity = new Entity([
<add> 'title' => 'Haz tags',
<add> 'body' => 'Some content here',
<add> 'tags' => [
<add> new Entity(['id' => 1, 'name' => 'Cake']),
<add> new Entity(['id' => 2, 'name' => 'PHP'])
<add> ]
<add> ]);
<add>
<add> $data = [
<add> 'title' => 'Haz moar tags',
<add> 'tags' => ['_ids' => '']
<add> ];
<add> $entity->accessible('*', true);
<add> $marshall = new Marshaller($this->articles);
<add> $result = $marshall->merge($entity, $data, ['Tags']);
<add> $this->assertCount(0, $result->tags);
<add>
<add> $data = [
<add> 'title' => 'Haz moar tags',
<add> 'tags' => ['_ids' => false]
<add> ];
<add> $result = $marshall->merge($entity, $data, ['Tags']);
<add> $this->assertCount(0, $result->tags);
<add>
<add> $data = [
<add> 'title' => 'Haz moar tags',
<add> 'tags' => ['_ids' => null]
<add> ];
<add> $result = $marshall->merge($entity, $data, ['Tags']);
<add> $this->assertCount(0, $result->tags);
<add> }
<add>
<ide> /**
<ide> * Test merging the _joinData entity for belongstomany associations.
<ide> * | 2 |
Python | Python | remove test dependency from testapikerberos | d43bb75367c7907dde48118d2757cfeb4df04d0b | <ide><path>tests/www/api/experimental/test_kerberos_endpoints.py
<ide> import pytest
<ide>
<ide> from airflow.api.auth.backend.kerberos_auth import CLIENT_AUTH
<add>from airflow.models import DagBag
<ide> from airflow.www import app as application
<ide> from tests.test_utils.config import conf_vars
<add>from tests.test_utils.db import clear_db_dags
<ide>
<ide> KRB5_KTNAME = os.environ.get("KRB5_KTNAME")
<ide>
<ide>
<ide> @pytest.mark.integration("kerberos")
<ide> class TestApiKerberos(unittest.TestCase):
<add> @classmethod
<add> def setUpClass(cls):
<add> dagbag = DagBag(include_examples=True)
<add> for dag in dagbag.dags.values():
<add> dag.sync_to_db()
<add>
<ide> @conf_vars({
<ide> ("api", "auth_backend"): "airflow.api.auth.backend.kerberos_auth",
<ide> ("kerberos", "keytab"): KRB5_KTNAME,
<ide> })
<ide> def setUp(self):
<ide> self.app = application.create_app(testing=True)
<ide>
<add> @classmethod
<add> def tearDownClass(cls) -> None:
<add> clear_db_dags()
<add>
<ide> def test_trigger_dag(self):
<ide> with self.app.test_client() as client:
<ide> url_template = '/api/experimental/dags/{}/dag_runs' | 1 |
Javascript | Javascript | add spatula to showcase | e8e8e8acdc5442a6dd478b82911607307d069371 | <ide><path>website/src/react-native/showcase.js
<ide> var apps = [
<ide> linkAppStore: 'https://itunes.apple.com/cn/app/hong-bei-bang-hai-liang-hong/id1007812319?mt=8',
<ide> author: 'Hongbeibang'
<ide> },
<add> {
<add> name: 'Spatula',
<add> icon: 'https://lh3.googleusercontent.com/26xtcDsloLCAOpqgH_87sDxaSJsLuSN--oj-z5Frcdsaq4ta2GQlktF5ktTNWrRHyqo=w300-rw',
<add> linkAppStore: 'https://itunes.apple.com/us/app/spatula/id1090496189?ls=1&mt=8',
<add> linkPlayStore: 'https://play.google.com/store/apps/details?id=com.usespatula',
<add> author: 'Kushal Dave'
<add> }
<ide> ];
<ide>
<ide> var AppList = React.createClass({ | 1 |
Python | Python | add documentation for diagonal | bae04d1cd9af556303091bc34d20a6d72e5d7aae | <ide><path>numpy/add_newdocs.py
<ide>
<ide>
<ide> add_newdoc('numpy.core.multiarray','lexsort',
<del> """lexsort(keys=, axis=-1) -> array of indices. argsort with list of keys.
<del>
<del> Return an array of indices similar to argsort, except the sorting is
<del> done using the provided sorting keys. First the sort is done using
<del> key[0], then the resulting list of indices is further manipulated by
<del> sorting on key[1], and so forth. The result is a sort on multiple
<del> keys. If the keys represented columns of a spreadsheet, for example,
<del> this would sort using multiple columns (the last key being used for the
<del> primary sort order, the second-to-last key for the secondary sort order,
<del> and so on). The keys argument must be a sequence of things that can be
<del> converted to arrays of the same shape.
<add> """lexsort(keys=, axis=-1) -> array of indices. Argsort with list of keys.
<add>
<add> Perform an indirect sort using a list of keys. The first key is sorted,
<add> then the second, and so on through the list of keys. At each step the
<add> previous order is preserved when equal keys are encountered. The result is
<add> a sort on multiple keys. If the keys represented columns of a spreadsheet,
<add> for example, this would sort using multiple columns (the last key being
<add> used for the primary sort order, the second-to-last key for the secondary
<add> sort order, and so on). The keys argument must be a sequence of things
<add> that can be converted to arrays of the same shape.
<add>
<add> :Parameters:
<add>
<add> a : array type
<add> Array containing values that the returned indices should sort.
<add>
<add> axis : integer
<add> Axis to be indirectly sorted. None indicates that the flattened
<add> array should be used. Default is -1.
<add>
<add> :Returns:
<add>
<add> indices : integer array
<add> Array of indices that sort the keys along the specified axis. The
<add> array has the same shape as the keys.
<add>
<add> :SeeAlso:
<add>
<add> - argsort : indirect sort
<add> - sort : inplace sort
<ide>
<ide> """)
<ide>
<ide> add_newdoc('numpy.core.multiarray', 'ndarray', ('argsort',
<ide> """a.argsort(axis=-1, kind='quicksort', order=None) -> indices
<ide>
<del> Return array of indices that sort a along the given axis.
<add> Perform an indirect sort along the given axis using the algorithm specified
<add> by the kind keyword. It returns an array of indices of the same shape as
<add> 'a' that index data along the given axis in sorted order.
<ide>
<del> Keyword arguments:
<add> :Parameters:
<ide>
<del> axis -- axis to be indirectly sorted (default -1)
<del> kind -- sorting algorithm (default 'quicksort')
<del> Possible values: 'quicksort', 'mergesort', or 'heapsort'
<del> order -- If a has fields defined, then the order keyword can be the
<del> field name to sort on or a list (or tuple) of field names
<del> to indicate the order that fields should be used to define
<del> the sort.
<add> axis : integer
<add> Axis to be indirectly sorted. None indicates that the flattened
<add> array should be used. Default is -1.
<ide>
<del> Returns: array of indices that sort a along the specified axis.
<add> kind : string
<add> Sorting algorithm to use. Possible values are 'quicksort',
<add> 'mergesort', or 'heapsort'. Default is 'quicksort'.
<ide>
<del> This method executes an indirect sort along the given axis using the
<del> algorithm specified by the kind keyword. It returns an array of indices of
<del> the same shape as 'a' that index data along the given axis in sorted order.
<add> order : list type or None
<add> When a is an array with fields defined, this argument specifies
<add> which fields to compare first, second, etc. Not all fields need be
<add> specified.
<add>
<add> :Returns:
<add>
<add> indices : integer array
<add> Array of indices that sort 'a' along the specified axis.
<add>
<add> :SeeAlso:
<add>
<add> - lexsort : indirect stable sort with multiple keys
<add> - sort : inplace sort
<add>
<add> :Notes:
<add> ------
<ide>
<ide> The various sorts are characterized by average speed, worst case
<ide> performance, need for work space, and whether they are stable. A stable
<ide> |'heapsort' | 3 | O(n*log(n)) | 0 | no |
<ide> |------------------------------------------------------|
<ide>
<del> All the sort algorithms make temporary copies of the data when the sort is
<del> not along the last axis. Consequently, sorts along the last axis are faster
<del> and use less space than sorts along other axis.
<add> All the sort algorithms make temporary copies of the data when the sort is not
<add> along the last axis. Consequently, sorts along the last axis are faster and use
<add> less space than sorts along other axis.
<ide>
<ide> """))
<ide>
<ide>
<ide>
<ide> add_newdoc('numpy.core.multiarray', 'ndarray', ('diagonal',
<del> """a.diagonal(offset=0, axis1=0, axis2=1)
<add> """a.diagonal(offset=0, axis1=0, axis2=1) -> diagonals
<add>
<add> If a is 2-d, return the diagonal of self with the given offset, i.e., the
<add> collection of elements of the form a[i,i+offset]. If a is n-d with n > 2,
<add> then the axes specified by axis1 and axis2 are used to determine the 2-d
<add> subarray whose diagonal is returned. The shape of the resulting array can
<add> be determined by removing axis1 and axis2 and appending an index to the
<add> right equal to the size of the resulting diagonals.
<add>
<add> :Parameters:
<add> offset : integer
<add> Offset of the diagonal from the main diagonal. Can be both positive
<add> and negative. Defaults to main diagonal.
<add> axis1 : integer
<add> Axis to be used as the first axis of the 2-d subarrays from which
<add> the diagonals should be taken. Defaults to first index.
<add> axis2 : integer
<add> Axis to be used as the second axis of the 2-d subarrays from which
<add> the diagonals should be taken. Defaults to second index.
<add>
<add> :Returns:
<add> array_of_diagonals : same type as original array
<add> If a is 2-d, then a 1-d array containing the diagonal is returned.
<add> If a is n-d, n > 2, then an array of diagonals is returned.
<add>
<add> :SeeAlso:
<add> - diag : matlab workalike for 1-d and 2-d arrays.
<add> - diagflat : creates diagonal arrays
<add> - trace : sum along diagonals
<add>
<add> Examples
<add> --------
<add>
<add> >>> a = arange(4).reshape(2,2)
<add> >>> a
<add> array([[0, 1],
<add> [2, 3]])
<add> >>> a.diagonal()
<add> array([0, 3])
<add> >>> a.diagonal(1)
<add> array([1])
<add>
<add> >>> a = arange(8).reshape(2,2,2)
<add> >>> a
<add> array([[[0, 1],
<add> [2, 3]],
<add>
<add> [[4, 5],
<add> [6, 7]]])
<add> >>> a.diagonal(0,-2,-1)
<add> array([[0, 3],
<add> [4, 7]])
<ide>
<ide> """))
<ide>
<ide>
<ide> Returns the average of the array elements. The average is taken over the
<ide> flattened array by default, otherwise over the specified axis.
<del>
<add>
<ide> :Parameters:
<add>
<ide> axis : integer
<ide> Axis along which the means are computed. The default is
<ide> to compute the standard deviation of the flattened array.
<add>
<ide> dtype : type
<ide> Type to use in computing the means. For arrays of
<ide> integer type the default is float32, for arrays of float types it
<ide> is the same as the array type.
<add>
<ide> out : ndarray
<ide> Alternative output array in which to place the result. It must have
<ide> the same shape as the expected output but the type will be cast if
<ide> necessary.
<ide>
<ide> :Returns:
<add>
<ide> mean : The return type varies, see above.
<ide> A new array holding the result is returned unless out is specified,
<ide> in which case a reference to out is returned.
<ide>
<ide> :SeeAlso:
<add>
<ide> - var : variance
<ide> - std : standard deviation
<ide>
<ide> Notes
<ide> -----
<add>
<ide> The mean is the sum of the elements along the axis divided by the
<ide> number of elements.
<ide>
<ide>
<ide> Return a new array from this one. The new array must have the same number
<ide> of elements as self. Also always returns a view or raises a ValueError if
<del> that is impossible.;
<add> that is impossible.
<ide>
<ide> """))
<ide>
<ide> add_newdoc('numpy.core.multiarray', 'ndarray', ('searchsorted',
<ide> """a.searchsorted(v, side='left') -> index array.
<ide>
<del> Required arguments:
<del> v -- array of keys to be searched for in a.
<del>
<del> Keyword arguments:
<del> side -- {'left', 'right'}, (default 'left').
<del>
<del> Returns:
<del> index array with the same shape as keys.
<del>
<del> The array to be searched must be 1-D and is assumed to be sorted in
<del> ascending order.
<del>
<del> The method call
<add> Find the indices into a sorted array such that if the corresponding keys in
<add> v were inserted before the indices the order of a would be preserved. If
<add> side='left', then the first such index is returned. If side='right', then
<add> the last such index is returned. If there is no such index because the key
<add> is out of bounds, then the length of a is returned, i.e., the key would
<add> need to be appended. The returned index array has the same shape as v.
<ide>
<del> a.searchsorted(v, side='left')
<add> :Parameters:
<ide>
<del> returns an index array with the same shape as v such that for each value i
<del> in the index and the corresponding key in v the following holds:
<add> v : array or list type
<add> Array of keys to be searched for in a.
<ide>
<del> a[j] < key <= a[i] for all j < i,
<add> side : string
<add> Possible values are : 'left', 'right'. Default is 'left'. Return
<add> the first or last index where the key could be inserted.
<ide>
<del> If such an index does not exist, a.size() is used. Consequently, i is the
<del> index of the first item in 'a' that is >= key. If the key were to be
<del> inserted into a in the slot before the index i, then the order of a would
<del> be preserved and i would be the smallest index with that property.
<add> :Returns:
<ide>
<del> The method call
<add> indices : integer array
<add> The returned array has the same shape as v.
<ide>
<del> a.searchsorted(v, side='right')
<add> :SeeAlso:
<ide>
<del> returns an index array with the same shape as v such that for each value i
<del> in the index and the corresponding key in v the following holds:
<add> - sort
<add> - histogram
<ide>
<del> a[j] <= key < a[i] for all j < i,
<add> :Notes:
<add> -------
<ide>
<del> If such an index does not exist, a.size() is used. Consequently, i is the
<del> index of the first item in 'a' that is > key. If the key were to be
<del> inserted into a in the slot before the index i, then the order of a would
<del> be preserved and i would be the largest index with that property.
<add> The array a must be 1-d and is assumed to be sorted in ascending order.
<add> Searchsorted uses binary search to find the required insertion points.
<ide>
<ide> """))
<ide>
<ide> add_newdoc('numpy.core.multiarray', 'ndarray', ('sort',
<ide> """a.sort(axis=-1, kind='quicksort', order=None) -> None.
<ide>
<del> Sort a along the given axis.
<add> Perform an inplace sort along the given axis using the algorithm specified
<add> by the kind keyword.
<ide>
<del> Keyword arguments:
<add> :Parameters:
<ide>
<del> axis -- axis to be sorted (default -1)
<del> kind -- sorting algorithm (default 'quicksort')
<del> Possible values: 'quicksort', 'mergesort', or 'heapsort'.
<del> order -- If a has fields defined, then the order keyword can be the
<del> field name to sort on or a list (or tuple) of field names
<del> to indicate the order that fields should be used to define
<del> the sort.
<add> axis : integer
<add> Axis to be sorted along. None indicates that the flattened array
<add> should be used. Default is -1.
<add>
<add> kind : string
<add> Sorting algorithm to use. Possible values are 'quicksort',
<add> 'mergesort', or 'heapsort'. Default is 'quicksort'.
<ide>
<del> Returns: None.
<add> order : list type or None
<add> When a is an array with fields defined, this argument specifies
<add> which fields to compare first, second, etc. Not all fields need be
<add> specified.
<add>
<add> :Returns:
<ide>
<del> This method sorts 'a' in place along the given axis using the algorithm
<del> specified by the kind keyword.
<add> None
<ide>
<del> The various sorts may characterized by average speed, worst case
<add> :SeeAlso:
<add>
<add> - argsort : indirect sort
<add> - lexsort : indirect stable sort on multiple keys
<add> - searchsorted : find keys in sorted array
<add>
<add> :Notes:
<add> ------
<add>
<add> The various sorts are characterized by average speed, worst case
<ide> performance, need for work space, and whether they are stable. A stable
<del> sort keeps items with the same key in the same relative order and is most
<del> useful when used with argsort where the key might differ from the items
<del> being sorted. The three available algorithms have the following properties:
<add> sort keeps items with the same key in the same relative order. The three
<add> available algorithms have the following properties:
<ide>
<ide> |------------------------------------------------------|
<ide> | kind | speed | worst case | work space | stable|
<ide> |'heapsort' | 3 | O(n*log(n)) | 0 | no |
<ide> |------------------------------------------------------|
<ide>
<del> All the sort algorithms make temporary copies of the data when the sort is
<del> not along the last axis. Consequently, sorts along the last axis are faster
<del> and use less space than sorts along other axis.
<add> All the sort algorithms make temporary copies of the data when the sort is not
<add> along the last axis. Consequently, sorts along the last axis are faster and use
<add> less space than sorts along other axis.
<ide>
<ide> """))
<ide>
<ide> flattened array by default, otherwise over the specified axis.
<ide>
<ide> :Parameters:
<add>
<ide> axis : integer
<ide> Axis along which the standard deviation is computed. The default is
<ide> to compute the standard deviation of the flattened array.
<add>
<ide> dtype : type
<ide> Type to use in computing the standard deviation. For arrays of
<ide> integer type the default is float32, for arrays of float types it
<ide> is the same as the array type.
<add>
<ide> out : ndarray
<ide> Alternative output array in which to place the result. It must have
<ide> the same shape as the expected output but the type will be cast if
<ide> necessary.
<ide>
<ide> :Returns:
<add>
<ide> standard deviation : The return type varies, see above.
<ide> A new array holding the result is returned unless out is specified,
<ide> in which case a reference to out is returned.
<ide>
<ide> :SeeAlso:
<add>
<ide> - var : variance
<ide> - mean : average
<ide>
<ide> otherwise over the specified axis.
<ide>
<ide> :Parameters:
<add>
<ide> axis : integer
<ide> Axis along which the variance is computed. The default is to
<ide> compute the variance of the flattened array.
<add>
<ide> dtype : type
<ide> Type to use in computing the variance. For arrays of integer type
<ide> the default is float32, for arrays of float types it is the same as
<ide> the array type.
<add>
<ide> out : ndarray
<ide> Alternative output array in which to place the result. It must have
<ide> the same shape as the expected output but the type will be cast if
<ide> necessary.
<ide>
<ide> :Returns:
<add>
<ide> variance : The return type varies, see above.
<ide> A new array holding the result is returned unless out is specified,
<ide> in which case a reference to out is returned.
<ide>
<ide> :SeeAlso:
<add>
<ide> - std : standard deviation
<ide> - mean: average
<ide>
<ide> Type can be either a new sub-type object or a data-descriptor object
<ide>
<ide> """))
<del>
<ide><path>numpy/core/defmatrix.py
<ide> def mean(self, axis=None, out=None):
<ide> the flattened array by default, otherwise over the specified axis.
<ide>
<ide> :Parameters:
<add>
<ide> axis : integer
<ide> Axis along which the means are computed. The default is
<ide> to compute the standard deviation of the flattened array.
<add>
<ide> dtype : type
<ide> Type to use in computing the means. For arrays of integer type
<ide> the default is float32, for arrays of float types it is the
<ide> same as the array type.
<add>
<ide> out : ndarray
<ide> Alternative output array in which to place the result. It must
<ide> have the same shape as the expected output but the type will be
<ide> cast if necessary.
<ide>
<ide> :Returns:
<add>
<ide> mean : The return type varies, see above.
<ide> A new array holding the result is returned unless out is
<ide> specified, in which case a reference to out is returned.
<ide>
<ide> :SeeAlso:
<add>
<ide> - var : variance
<ide> - std : standard deviation
<ide>
<ide> Notes
<ide> -----
<add>
<ide> The mean is the sum of the elements along the axis divided by the
<ide> number of elements.
<ide>
<ide> def std(self, axis=None, dtype=None, out=None):
<ide> flattened array by default, otherwise over the specified axis.
<ide>
<ide> :Parameters:
<add>
<ide> axis : integer
<ide> Axis along which the standard deviation is computed. The
<ide> default is to compute the standard deviation of the flattened
<ide> array.
<add>
<ide> dtype : type
<ide> Type to use in computing the standard deviation. For arrays of
<ide> integer type the default is float32, for arrays of float types
<ide> it is the same as the array type.
<add>
<ide> out : ndarray
<ide> Alternative output array in which to place the result. It must
<ide> have the same shape as the expected output but the type will be
<ide> cast if necessary.
<ide>
<ide> :Returns:
<add>
<ide> standard deviation : The return type varies, see above.
<ide> A new array holding the result is returned unless out is
<ide> specified, in which case a reference to out is returned.
<ide>
<ide> :SeeAlso:
<add>
<ide> - var : variance
<ide> - mean : average
<ide>
<ide> def var(self, axis=None, dtype=None, out=None):
<ide> default, otherwise over the specified axis.
<ide>
<ide> :Parameters:
<add>
<ide> axis : integer
<ide> Axis along which the variance is computed. The default is to
<ide> compute the variance of the flattened array.
<add>
<ide> dtype : type
<ide> Type to use in computing the variance. For arrays of integer
<ide> type the default is float32, for arrays of float types it is
<ide> the same as the array type.
<add>
<ide> out : ndarray
<ide> Alternative output array in which to place the result. It must
<ide> have the same shape as the expected output but the type will be
<ide> cast if necessary.
<ide>
<ide> :Returns:
<add>
<ide> variance : depends, see above
<ide> A new array holding the result is returned unless out is
<ide> specified, in which case a reference to out is returned.
<ide>
<ide> :SeeAlso:
<add>
<ide> - std : standard deviation
<ide> - mean : average
<ide>
<ide><path>numpy/core/fromnumeric.py
<ide> def _wrapit(obj, method, *args, **kwds):
<ide> result = wrap(result)
<ide> return result
<ide>
<add>
<ide> def take(a, indices, axis=None, out=None, mode='raise'):
<ide> """Return an array with values pulled from the given array at the given
<ide> indices.
<ide> def take(a, indices, axis=None, out=None, mode='raise'):
<ide> The indices of the values to extract.
<ide> - `axis` : None or int, optional (default=None)
<ide> The axis over which to select values. None signifies that the operation
<del> should be performed over the flattened array.
<add> should be performed over the flattened array.
<ide> - `out` : array, optional
<ide> If provided, the result will be inserted into this array. It should be
<ide> of the appropriate shape and dtype.
<ide> def take(a, indices, axis=None, out=None, mode='raise'):
<ide> return _wrapit(a, 'take', indices, axis, out, mode)
<ide> return take(indices, axis, out, mode)
<ide>
<add>
<ide> # not deprecated --- copy if necessary, view otherwise
<ide> def reshape(a, newshape, order='C'):
<ide> """Return an array that uses the data of the given array, but with a new
<ide> def reshape(a, newshape, order='C'):
<ide> return _wrapit(a, 'reshape', newshape, order=order)
<ide> return reshape(newshape, order=order)
<ide>
<add>
<ide> def choose(a, choices, out=None, mode='raise'):
<ide> """Use an index array to construct a new array from a set of choices.
<ide>
<ide> def choose(a, choices, out=None, mode='raise'):
<ide> numpy.ndarray.choose() is the equivalent method.
<ide>
<ide> :Example:
<del> >>> choices = [[0, 1, 2, 3], [10, 11, 12, 13],
<add> >>> choices = [[0, 1, 2, 3], [10, 11, 12, 13],
<ide> ... [20, 21, 22, 23], [30, 31, 32, 33]]
<ide> >>> choose([2, 3, 1, 0], choices)
<ide> array([20, 31, 12, 3])
<ide> >>> choose([2, 4, 1, 0], choices, mode='clip')
<ide> array([20, 31, 12, 3])
<ide> >>> choose([2, 4, 1, 0], choices, mode='wrap')
<ide> array([20, 1, 12, 3])
<del>
<add>
<ide> """
<ide> try:
<ide> choose = a.choose
<ide> except AttributeError:
<ide> return _wrapit(a, 'choose', choices, out=out, mode=mode)
<ide> return choose(choices, out=out, mode=mode)
<ide>
<add>
<ide> def repeat(a, repeats, axis=None):
<ide> """Repeat elements of an array.
<ide>
<ide> def repeat(a, repeats, axis=None):
<ide> array([0, 0, 1, 1, 2, 2])
<ide> >>> repeat([0, 1, 2], [2, 3, 4])
<ide> array([0, 0, 1, 1, 1, 2, 2, 2, 2])
<del>
<add>
<ide> """
<ide> try:
<ide> repeat = a.repeat
<ide> except AttributeError:
<ide> return _wrapit(a, 'repeat', repeats, axis)
<ide> return repeat(repeats, axis)
<ide>
<add>
<ide> def put (a, ind, v, mode='raise'):
<ide> """put(a, ind, v) results in a[n] = v[n] for all n in ind
<ide> If v is shorter than mask it will be repeated as necessary.
<ide> def put (a, ind, v, mode='raise'):
<ide> """
<ide> return a.put(ind, v, mode)
<ide>
<add>
<ide> def swapaxes(a, axis1, axis2):
<ide> """swapaxes(a, axis1, axis2) returns array a with axis1 and axis2
<ide> interchanged.
<ide> def swapaxes(a, axis1, axis2):
<ide> return _wrapit(a, 'swapaxes', axis1, axis2)
<ide> return swapaxes(axis1, axis2)
<ide>
<add>
<ide> def transpose(a, axes=None):
<ide> """transpose(a, axes=None) returns a view of the array with
<ide> dimensions permuted according to axes. If axes is None
<ide> def transpose(a, axes=None):
<ide> return _wrapit(a, 'transpose', axes)
<ide> return transpose(axes)
<ide>
<add>
<ide> def sort(a, axis=-1, kind='quicksort', order=None):
<del> """Returns copy of 'a' sorted along the given axis.
<add> """Return copy of 'a' sorted along the given axis.
<ide>
<del> Keyword arguments:
<add> Perform an inplace sort along the given axis using the algorithm specified
<add> by the kind keyword.
<add>
<add> :Parameters:
<add>
<add> a : array type
<add> Array to be sorted.
<add>
<add> axis : integer
<add> Axis to be sorted along. None indicates that the flattened array
<add> should be used. Default is -1.
<add>
<add> kind : string
<add> Sorting algorithm to use. Possible values are 'quicksort',
<add> 'mergesort', or 'heapsort'. Default is 'quicksort'.
<add>
<add> order : list type or None
<add> When a is an array with fields defined, this argument specifies
<add> which fields to compare first, second, etc. Not all fields need be
<add> specified.
<add>
<add> :Returns:
<ide>
<del> axis -- axis to be sorted (default -1). Can be None
<del> to indicate that a flattened and sorted array should
<del> be returned (the array method does not support this).
<del> kind -- sorting algorithm (default 'quicksort')
<del> Possible values: 'quicksort', 'mergesort', or 'heapsort'.
<del> order -- For an array with fields defined, this argument allows
<del> specification of which fields to compare first, second,
<del> etc. Not all fields need be specified.
<add> sorted array : type is unchanged.
<ide>
<add> :SeeAlso:
<ide>
<del> Returns: None.
<add> - argsort : indirect sort
<add> - lexsort : indirect stable sort on multiple keys
<add> - searchsorted : find keys in sorted array
<ide>
<del> This method sorts 'a' in place along the given axis using the algorithm
<del> specified by the kind keyword.
<add> :Notes:
<add> ------
<ide>
<del> The various sorts may characterized by average speed, worst case
<add> The various sorts are characterized by average speed, worst case
<ide> performance, need for work space, and whether they are stable. A stable
<del> sort keeps items with the same key in the same relative order and is most
<del> useful when used with argsort where the key might differ from the items
<del> being sorted. The three available algorithms have the following properties:
<add> sort keeps items with the same key in the same relative order. The three
<add> available algorithms have the following properties:
<ide>
<ide> |------------------------------------------------------|
<ide> | kind | speed | worst case | work space | stable|
<ide> def sort(a, axis=-1, kind='quicksort', order=None):
<ide> |'heapsort' | 3 | O(n*log(n)) | 0 | no |
<ide> |------------------------------------------------------|
<ide>
<del> All the sort algorithms make temporary copies of the data when the sort is
<del> not along the last axis. Consequently, sorts along the last axis are faster
<del> and use less space than sorts along other axis.
<add> All the sort algorithms make temporary copies of the data when the sort is not
<add> along the last axis. Consequently, sorts along the last axis are faster and use
<add> less space than sorts along other axis.
<ide>
<ide> """
<ide> if axis is None:
<ide> def sort(a, axis=-1, kind='quicksort', order=None):
<ide> a.sort(axis, kind, order)
<ide> return a
<ide>
<add>
<ide> def argsort(a, axis=-1, kind='quicksort', order=None):
<ide> """Returns array of indices that index 'a' in sorted order.
<ide>
<del> Keyword arguments:
<add> Perform an indirect sort along the given axis using the algorithm specified
<add> by the kind keyword. It returns an array of indices of the same shape as
<add> 'a' that index data along the given axis in sorted order.
<add>
<add> :Parameters:
<add>
<add> a : array type
<add> Array containing values that the returned indices should sort.
<add>
<add> axis : integer
<add> Axis to be indirectly sorted. None indicates that the flattened
<add> array should be used. Default is -1.
<add>
<add> kind : string
<add> Sorting algorithm to use. Possible values are 'quicksort',
<add> 'mergesort', or 'heapsort'. Default is 'quicksort'.
<ide>
<del> axis -- axis to be indirectly sorted (default -1)
<del> Can be None to indicate return indices into the
<del> flattened array.
<del> kind -- sorting algorithm (default 'quicksort')
<del> Possible values: 'quicksort', 'mergesort', or 'heapsort'
<del> order -- For an array with fields defined, this argument allows
<del> specification of which fields to compare first, second,
<del> etc. Not all fields need be specified.
<add> order : list type or None
<add> When a is an array with fields defined, this argument specifies
<add> which fields to compare first, second, etc. Not all fields need be
<add> specified.
<add>
<add> :Returns:
<add>
<add> indices : integer array
<add> Array of indices that sort 'a' along the specified axis.
<add>
<add> :SeeAlso:
<ide>
<del> Returns: array of indices that sort 'a' along the specified axis.
<add> - lexsort : indirect stable sort with multiple keys
<add> - sort : inplace sort
<ide>
<del> This method executes an indirect sort along the given axis using the
<del> algorithm specified by the kind keyword. It returns an array of indices of
<del> the same shape as 'a' that index data along the given axis in sorted order.
<add> :Notes:
<add> ------
<ide>
<ide> The various sorts are characterized by average speed, worst case
<ide> performance, need for work space, and whether they are stable. A stable
<ide> def argsort(a, axis=-1, kind='quicksort', order=None):
<ide> return _wrapit(a, 'argsort', axis, kind, order)
<ide> return argsort(axis, kind, order)
<ide>
<add>
<ide> def argmax(a, axis=None):
<ide> """argmax(a,axis=None) returns the indices to the maximum value of the
<ide> 1-D arrays along the given axis.
<ide> def argmax(a, axis=None):
<ide> return _wrapit(a, 'argmax', axis)
<ide> return argmax(axis)
<ide>
<add>
<ide> def argmin(a, axis=None):
<ide> """argmin(a,axis=None) returns the indices to the minimum value of the
<ide> 1-D arrays along the given axis.
<ide> def argmin(a, axis=None):
<ide> return _wrapit(a, 'argmin', axis)
<ide> return argmin(axis)
<ide>
<del>def searchsorted(a, v, side='left'):
<del> """-> index array. Inserting v[i] before a[index[i]] maintains a in order.
<del>
<del> Required arguments:
<del> a -- sorted 1-D array to be searched.
<del> v -- array of keys to be searched for in a.
<del>
<del> Keyword arguments:
<del> side -- {'left', 'right'}, default('left').
<ide>
<del> Returns:
<del> array of indices with the same shape as v.
<add>def searchsorted(a, v, side='left'):
<add> """Returns indices where keys in v should be inserted to maintain order.
<ide>
<del> The array to be searched must be 1-D and is assumed to be sorted in
<del> ascending order.
<add> Find the indices into a sorted array such that if the corresponding keys in
<add> v were inserted before the indices the order of a would be preserved. If
<add> side='left', then the first such index is returned. If side='right', then
<add> the last such index is returned. If there is no such index because the key
<add> is out of bounds, then the length of a is returned, i.e., the key would
<add> need to be appended. The returned index array has the same shape as v.
<ide>
<del> The function call
<add> :Parameters:
<ide>
<del> searchsorted(a, v, side='left')
<add> a : array
<add> 1-d array sorted in ascending order.
<ide>
<del> returns an index array with the same shape as v such that for each value i
<del> in the index and the corresponding key in v the following holds:
<add> v : array or list type
<add> Array of keys to be searched for in a.
<ide>
<del> a[j] < key <= a[i] for all j < i,
<add> side : string
<add> Possible values are : 'left', 'right'. Default is 'left'. Return
<add> the first or last index where the key could be inserted.
<ide>
<del> If such an index does not exist, a.size() is used. Consequently, i is the
<del> index of the first item in 'a' that is >= key. If the key were to be
<del> inserted into a in the slot before the index i, then the order of a would
<del> be preserved and i would be the smallest index with that property.
<add> :Returns:
<ide>
<del> The function call
<add> indices : integer array
<add> Array of insertion points with the same shape as v.
<ide>
<del> searchsorted(a, v, side='right')
<add> :SeeAlso:
<ide>
<del> returns an index array with the same shape as v such that for each value i
<del> in the index and the corresponding key in v the following holds:
<add> - sort
<add> - histogram
<ide>
<del> a[j] <= key < a[i] for all j < i,
<add> :Notes:
<add> -------
<ide>
<del> If such an index does not exist, a.size() is used. Consequently, i is the
<del> index of the first item in 'a' that is > key. If the key were to be
<del> inserted into a in the slot before the index i, then the order of a would
<del> be preserved and i would be the largest index with that property.
<add> The array a must be 1-d and is assumed to be sorted in ascending order.
<add> Searchsorted uses binary search to find the required insertion points.
<ide>
<ide> """
<ide> try:
<ide> def searchsorted(a, v, side='left'):
<ide> return _wrapit(a, 'searchsorted', v, side)
<ide> return searchsorted(v, side)
<ide>
<add>
<ide> def resize(a, new_shape):
<ide> """resize(a,new_shape) returns a new array with the specified shape.
<ide> The original array's total size can be any size. It
<ide> def resize(a, new_shape):
<ide>
<ide> return reshape(a, new_shape)
<ide>
<add>
<ide> def squeeze(a):
<ide> "Returns a with any ones from the shape of a removed"
<ide> try:
<ide> def squeeze(a):
<ide> return _wrapit(a, 'squeeze')
<ide> return squeeze()
<ide>
<add>
<ide> def diagonal(a, offset=0, axis1=0, axis2=1):
<del> """diagonal(a, offset=0, axis1=0, axis2=1) returns the given diagonals
<del> defined by the last two dimensions of the array.
<add> """Return specified diagonals. Uses first two indices by default.
<add>
<add> If a is 2-d, return the diagonal of self with the given offset, i.e., the
<add> collection of elements of the form a[i,i+offset]. If a is n-d with n > 2,
<add> then the axes specified by axis1 and axis2 are used to determine the 2-d
<add> subarray whose diagonal is returned. The shape of the resulting array can be
<add> determined by removing axis1 and axis2 and appending an index to the right
<add> equal to the size of the resulting diagonals.
<add>
<add> :Parameters:
<add> offset : integer
<add> Offset of the diagonal from the main diagonal. Can be both positive
<add> and negative. Defaults to main diagonal.
<add> axis1 : integer
<add> Axis to be used as the first axis of the 2-d subarrays from which
<add> the diagonals should be taken. Defaults to first axis.
<add> axis2 : integer
<add> Axis to be used as the second axis of the 2-d subarrays from which
<add> the diagonals should be taken. Defaults to second axis.
<add>
<add> :Returns:
<add> array_of_diagonals : same type as original array
<add> If a is 2-d, then a 1-d array containing the diagonal is returned.
<add> If a is n-d, n > 2, then an array of diagonals is returned.
<add>
<add> :SeeAlso:
<add> - diag : matlab workalike for 1-d and 2-d arrays
<add> - diagflat : creates diagonal arrays
<add> - trace : sum along diagonals
<add>
<add> Examples
<add> --------
<add>
<add> >>> a = arange(4).reshape(2,2)
<add> >>> a
<add> array([[0, 1],
<add> [2, 3]])
<add> >>> a.diagonal()
<add> array([0, 3])
<add> >>> a.diagonal(1)
<add> array([1])
<add>
<add> >>> a = arange(8).reshape(2,2,2)
<add> >>> a
<add> array([[[0, 1],
<add> [2, 3]],
<add>
<add> [[4, 5],
<add> [6, 7]]])
<add> >>> a.diagonal(0,-2,-1)
<add> array([[0, 3],
<add> [4, 7]])
<add>
<ide> """
<ide> return asarray(a).diagonal(offset, axis1, axis2)
<ide>
<add>
<ide> def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None):
<ide> """trace(a,offset=0, axis1=0, axis2=1) returns the sum along diagonals
<ide> (defined by the last two dimenions) of the array.
<ide> def mean(a, axis=None, dtype=None, out=None):
<ide> flattened array by default, otherwise over the specified axis.
<ide>
<ide> :Parameters:
<add>
<ide> axis : integer
<ide> Axis along which the means are computed. The default is
<ide> to compute the standard deviation of the flattened array.
<add>
<ide> dtype : type
<ide> Type to use in computing the means. For arrays of
<ide> integer type the default is float32, for arrays of float types it
<ide> is the same as the array type.
<add>
<ide> out : ndarray
<ide> Alternative output array in which to place the result. It must have
<ide> the same shape as the expected output but the type will be cast if
<ide> necessary.
<ide>
<ide> :Returns:
<add>
<ide> mean : The return type varies, see above.
<ide> A new array holding the result is returned unless out is specified,
<ide> in which case a reference to out is returned.
<ide>
<ide> :SeeAlso:
<add>
<ide> - var : variance
<ide> - std : standard deviation
<ide>
<ide> Notes
<ide> -----
<add>
<ide> The mean is the sum of the elements along the axis divided by the
<ide> number of elements.
<ide>
<ide> def std(a, axis=None, dtype=None, out=None):
<ide> flattened array by default, otherwise over the specified axis.
<ide>
<ide> :Parameters:
<add>
<ide> axis : integer
<ide> Axis along which the standard deviation is computed. The default is
<ide> to compute the standard deviation of the flattened array.
<add>
<ide> dtype : type
<ide> Type to use in computing the standard deviation. For arrays of
<ide> integer type the default is float32, for arrays of float types it
<ide> is the same as the array type.
<add>
<ide> out : ndarray
<ide> Alternative output array in which to place the result. It must have
<ide> the same shape as the expected output but the type will be cast if
<ide> necessary.
<ide>
<ide> :Returns:
<add>
<ide> standard deviation : The return type varies, see above.
<ide> A new array holding the result is returned unless out is specified,
<ide> in which case a reference to out is returned.
<ide>
<ide> :SeeAlso:
<add>
<ide> - var : variance
<ide> - mean : average
<ide>
<ide> def var(a, axis=None, dtype=None, out=None):
<ide> otherwise over the specified axis.
<ide>
<ide> :Parameters:
<add>
<ide> axis : integer
<ide> Axis along which the variance is computed. The default is to
<ide> compute the variance of the flattened array.
<add>
<ide> dtype : type
<ide> Type to use in computing the variance. For arrays of integer type
<ide> the default is float32, for arrays of float types it is the same as
<ide> the array type.
<add>
<ide> out : ndarray
<ide> Alternative output array in which to place the result. It must have
<ide> the same shape as the expected output but the type will be cast if
<ide> necessary.
<ide>
<ide> :Returns:
<add>
<ide> variance : depends, see above
<ide> A new array holding the result is returned unless out is specified,
<ide> in which case a reference to out is returned.
<ide>
<ide> :SeeAlso:
<add>
<ide> - std : standard deviation
<ide> - mean : average
<ide> | 3 |
Javascript | Javascript | avoid unnecessary lookup | 489224ba8557837c9bd59e52220d7ec822ac4be0 | <ide><path>src/ngAnimate/animateQueue.js
<ide> var $$AnimateQueueProvider = ['$animateProvider', function($animateProvider) {
<ide> bool = animationsEnabled = !!element;
<ide> } else {
<ide> var node = getDomNode(element);
<del> var recordExists = disabledElementsLookup.get(node);
<ide>
<ide> if (argCount === 1) {
<ide> // (element) - Element getter
<del> bool = !recordExists;
<add> bool = !disabledElementsLookup.get(node);
<ide> } else {
<ide> // (element, bool) - Element setter
<ide> disabledElementsLookup.put(node, !bool); | 1 |
Java | Java | improve support for mono<responseentity<?>> | c43040287253bda3e9710759eb722fb54c1e9cc0 | <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/result/AbstractHandlerResultHandler.java
<ide> import java.util.List;
<ide> import java.util.Optional;
<ide> import java.util.Set;
<add>import java.util.function.Supplier;
<ide>
<ide> import org.springframework.core.MethodParameter;
<ide> import org.springframework.core.Ordered;
<ide> public int getOrder() {
<ide> * Select the best media type for the current request through a content
<ide> * negotiation algorithm.
<ide> * @param exchange the current request
<del> * @param producibleTypes the media types that can be produced for the current request
<add> * @param producibleTypesSupplier the media types that can be produced for the current request
<ide> * @return the selected media type or {@code null}
<ide> */
<del> protected MediaType selectMediaType(ServerWebExchange exchange, List<MediaType> producibleTypes) {
<add> protected MediaType selectMediaType(ServerWebExchange exchange,
<add> Supplier<List<MediaType>> producibleTypesSupplier) {
<ide>
<ide> List<MediaType> acceptableTypes = getAcceptableTypes(exchange);
<del> producibleTypes = getProducibleTypes(exchange, producibleTypes);
<add> List<MediaType> producibleTypes = getProducibleTypes(exchange, producibleTypesSupplier);
<ide>
<ide> Set<MediaType> compatibleMediaTypes = new LinkedHashSet<>();
<ide> for (MediaType acceptable : acceptableTypes) {
<ide> private List<MediaType> getAcceptableTypes(ServerWebExchange exchange) {
<ide> }
<ide>
<ide> @SuppressWarnings("unchecked")
<del> private List<MediaType> getProducibleTypes(ServerWebExchange exchange, List<MediaType> mediaTypes) {
<add> private List<MediaType> getProducibleTypes(ServerWebExchange exchange,
<add> Supplier<List<MediaType>> producibleTypesSupplier) {
<add>
<ide> Optional<Object> optional = exchange.getAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE);
<ide> if (optional.isPresent()) {
<ide> Set<MediaType> set = (Set<MediaType>) optional.get();
<ide> return new ArrayList<>(set);
<ide> }
<del> return mediaTypes;
<add> return producibleTypesSupplier.get();
<ide> }
<ide>
<ide> private MediaType selectMoreSpecificMediaType(MediaType acceptable, MediaType producible) {
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/result/method/annotation/AbstractMessageWriterResultHandler.java
<ide> public List<HttpMessageWriter<?>> getMessageWriters() {
<ide> @SuppressWarnings("unchecked")
<ide> protected Mono<Void> writeBody(Object body, MethodParameter bodyParameter, ServerWebExchange exchange) {
<ide>
<del> ResolvableType bodyType = ResolvableType.forMethodParameter(bodyParameter);
<del> ReactiveAdapter adapter = getAdapterRegistry().getAdapterFrom(bodyType.resolve(), body);
<add> ResolvableType valueType = ResolvableType.forMethodParameter(bodyParameter);
<add> Class<?> valueClass = valueType.resolve();
<add> ReactiveAdapter adapter = getAdapterRegistry().getAdapterFrom(valueClass, body);
<ide>
<ide> Publisher<?> publisher;
<ide> ResolvableType elementType;
<ide> if (adapter != null) {
<ide> publisher = adapter.toPublisher(body);
<ide> elementType = adapter.getDescriptor().isNoValue() ?
<ide> ResolvableType.forClass(Void.class) :
<del> bodyType.getGeneric(0);
<add> valueType.getGeneric(0);
<ide> }
<ide> else {
<ide> publisher = Mono.justOrEmpty(body);
<del> elementType = bodyType;
<add> elementType = (valueClass == null && body != null ? ResolvableType.forInstance(body) : valueType);
<ide> }
<ide>
<ide> if (void.class == elementType.getRawClass() || Void.class == elementType.getRawClass()) {
<ide> return Mono.from((Publisher<Void>) publisher)
<ide> .doOnSubscribe(sub -> updateResponseStatus(bodyParameter, exchange));
<ide> }
<ide>
<del> List<MediaType> producibleTypes = getProducibleMediaTypes(elementType);
<del> if (producibleTypes.isEmpty()) {
<del> return Mono.error(new IllegalStateException(
<del> "No converter for return value type: " + elementType));
<del> }
<del>
<ide> ServerHttpRequest request = exchange.getRequest();
<ide> ServerHttpResponse response = exchange.getResponse();
<del> MediaType bestMediaType = selectMediaType(exchange, producibleTypes);
<add> MediaType bestMediaType = selectMediaType(exchange, () -> getProducibleMediaTypes(elementType));
<ide> if (bestMediaType != null) {
<ide> for (HttpMessageWriter<?> messageWriter : getMessageWriters()) {
<ide> if (messageWriter.canWrite(elementType, bestMediaType)) {
<ide> Mono<Void> bodyWriter = (messageWriter instanceof ServerHttpMessageWriter ?
<ide> ((ServerHttpMessageWriter<?>) messageWriter).write((Publisher) publisher,
<del> bodyType, elementType, bestMediaType, request, response, Collections.emptyMap()) :
<add> valueType, elementType, bestMediaType, request, response, Collections.emptyMap()) :
<ide> messageWriter.write((Publisher) publisher, elementType,
<ide> bestMediaType, response, Collections.emptyMap()));
<ide> return bodyWriter.doOnSubscribe(sub -> updateResponseStatus(bodyParameter, exchange));
<ide> }
<ide> }
<ide> }
<add> else {
<add> if (getProducibleMediaTypes(elementType).isEmpty()) {
<add> return Mono.error(new IllegalStateException(
<add> "No converter for return value type: " + elementType));
<add> }
<add> }
<ide>
<del> return Mono.error(new NotAcceptableStatusException(producibleTypes));
<add> return Mono.error(new NotAcceptableStatusException(getProducibleMediaTypes(elementType)));
<ide> }
<ide>
<ide> private List<MediaType> getProducibleMediaTypes(ResolvableType elementType) {
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/result/view/ViewResolutionResultHandler.java
<ide> private Mono<? extends Void> resolveAndRender(String viewName, Locale locale,
<ide> views.addAll(getDefaultViews());
<ide>
<ide> List<MediaType> producibleTypes = getProducibleMediaTypes(views);
<del> MediaType bestMediaType = selectMediaType(exchange, producibleTypes);
<add> MediaType bestMediaType = selectMediaType(exchange, () -> producibleTypes);
<ide>
<ide> if (bestMediaType != null) {
<ide> for (View view : views) {
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/result/HandlerResultHandlerTests.java
<ide> public void setUp() throws Exception {
<ide> public void usesContentTypeResolver() throws Exception {
<ide> TestResultHandler resultHandler = new TestResultHandler(new FixedContentTypeResolver(IMAGE_GIF));
<ide> List<MediaType> mediaTypes = Arrays.asList(IMAGE_JPEG, IMAGE_GIF, IMAGE_PNG);
<del> MediaType actual = resultHandler.selectMediaType(this.exchange, mediaTypes);
<add> MediaType actual = resultHandler.selectMediaType(this.exchange, () -> mediaTypes);
<ide>
<ide> assertEquals(IMAGE_GIF, actual);
<ide> }
<ide> public void producibleMediaTypesRequestAttribute() throws Exception {
<ide> this.exchange.getAttributes().put(PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, producible);
<ide>
<ide> List<MediaType> mediaTypes = Arrays.asList(IMAGE_JPEG, IMAGE_GIF, IMAGE_PNG);
<del> MediaType actual = resultHandler.selectMediaType(this.exchange, mediaTypes);
<add> MediaType actual = resultHandler.selectMediaType(this.exchange, () -> mediaTypes);
<ide>
<ide> assertEquals(IMAGE_GIF, actual);
<ide> }
<ide> public void sortsByQuality() throws Exception {
<ide> this.request.setHeader("Accept", "text/plain; q=0.5, application/json");
<ide>
<ide> List<MediaType> mediaTypes = Arrays.asList(TEXT_PLAIN, APPLICATION_JSON_UTF8);
<del> MediaType actual = this.resultHandler.selectMediaType(this.exchange, mediaTypes);
<add> MediaType actual = this.resultHandler.selectMediaType(this.exchange, () -> mediaTypes);
<ide>
<ide> assertEquals(APPLICATION_JSON_UTF8, actual);
<ide> }
<ide> public void charsetFromAcceptHeader() throws Exception {
<ide> MediaType text8859 = MediaType.parseMediaType("text/plain;charset=ISO-8859-1");
<ide> MediaType textUtf8 = MediaType.parseMediaType("text/plain;charset=UTF-8");
<ide> this.request.getHeaders().setAccept(Collections.singletonList(text8859));
<del> MediaType actual = this.resultHandler.selectMediaType(this.exchange, Collections.singletonList(textUtf8));
<add> MediaType actual = this.resultHandler.selectMediaType(this.exchange,
<add> () -> Collections.singletonList(textUtf8));
<ide>
<ide> assertEquals(text8859, actual);
<ide> }
<ide>
<ide> @Test // SPR-12894
<ide> public void noConcreteMediaType() throws Exception {
<ide> List<MediaType> producible = Collections.singletonList(ALL);
<del> MediaType actual = this.resultHandler.selectMediaType(this.exchange, producible);
<add> MediaType actual = this.resultHandler.selectMediaType(this.exchange, () -> producible);
<ide>
<ide> assertEquals(APPLICATION_OCTET_STREAM, actual);
<ide> }
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/annotation/MessageWriterResultHandlerTests.java
<ide> import org.springframework.core.codec.CharSequenceEncoder;
<ide> import org.springframework.core.io.ClassPathResource;
<ide> import org.springframework.core.io.Resource;
<del>import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.core.io.buffer.support.DataBufferTestUtils;
<ide> import org.springframework.http.HttpMethod;
<ide> import org.springframework.http.codec.EncoderHttpMessageWriter;
<ide> import org.springframework.http.codec.HttpMessageWriter;
<ide> import org.springframework.http.codec.ResourceHttpMessageWriter;
<ide> import org.springframework.http.codec.json.Jackson2JsonEncoder;
<ide> import org.springframework.http.codec.xml.Jaxb2XmlEncoder;
<add>import org.springframework.http.server.reactive.ServerHttpRequest;
<ide> import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
<ide> import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
<del>import org.springframework.http.server.reactive.ServerHttpRequest;
<ide> import org.springframework.util.ObjectUtils;
<ide> import org.springframework.web.reactive.accept.RequestedContentTypeResolver;
<ide> import org.springframework.web.reactive.accept.RequestedContentTypeResolverBuilder;
<ide> private static class ParentClass {
<ide> public ParentClass() {
<ide> }
<ide>
<del> public ParentClass(String parentProperty) {
<add> ParentClass(String parentProperty) {
<ide> this.parentProperty = parentProperty;
<ide> }
<ide>
<ide> public Foo(String parentProperty) {
<ide> @JsonTypeName("bar")
<ide> private static class Bar extends ParentClass {
<ide>
<del> public Bar(String parentProperty) {
<add> Bar(String parentProperty) {
<ide> super(parentProperty);
<ide> }
<ide> }
<ide> private static class SimpleBean implements Identifiable {
<ide>
<ide> private String name;
<ide>
<del> public SimpleBean(Long id, String name) {
<add> SimpleBean(Long id, String name) {
<ide> this.id = id;
<ide> this.name = name;
<ide> }
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/annotation/ResponseEntityResultHandlerTests.java
<ide> import java.time.temporal.ChronoUnit;
<ide> import java.util.ArrayList;
<ide> import java.util.Arrays;
<add>import java.util.Collections;
<ide> import java.util.List;
<ide> import java.util.concurrent.CompletableFuture;
<ide>
<ide> import org.springframework.core.ResolvableType;
<ide> import org.springframework.core.codec.ByteBufferEncoder;
<ide> import org.springframework.core.codec.CharSequenceEncoder;
<del>import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.core.io.buffer.support.DataBufferTestUtils;
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.HttpMethod;
<ide> import org.springframework.http.HttpStatus;
<add>import org.springframework.http.MediaType;
<ide> import org.springframework.http.ResponseEntity;
<ide> import org.springframework.http.codec.EncoderHttpMessageWriter;
<ide> import org.springframework.http.codec.HttpMessageWriter;
<ide> import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
<ide> import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
<ide> import org.springframework.util.ObjectUtils;
<add>import org.springframework.web.reactive.HandlerMapping;
<ide> import org.springframework.web.reactive.HandlerResult;
<ide> import org.springframework.web.reactive.accept.RequestedContentTypeResolver;
<ide> import org.springframework.web.reactive.accept.RequestedContentTypeResolverBuilder;
<ide> public void handleReturnValueChangedETagAndLastModified() throws Exception {
<ide> assertConditionalResponse(HttpStatus.OK, "body", newEtag, oneMinAgo);
<ide> }
<ide>
<add> @Test // SPR-14877
<add> public void handleMonoWithWildcardBodyType() throws Exception {
<add>
<add> this.exchange.getAttributes().put(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE,
<add> Collections.singleton(MediaType.APPLICATION_JSON));
<add>
<add> HandlerResult result = new HandlerResult(new TestController(), Mono.just(ok().body("body")),
<add> ResolvableMethod.onClass(TestController.class)
<add> .name("monoResponseEntityWildcard")
<add> .resolveReturnType());
<add>
<add> this.resultHandler.handleResult(this.exchange, result).block(Duration.ofSeconds(5));
<add>
<add> assertEquals(HttpStatus.OK, this.response.getStatusCode());
<add> assertResponseBody("\"body\"");
<add> }
<add>
<ide>
<ide> private void testHandle(Object returnValue, ResolvableType type) {
<ide> HandlerResult result = handlerResult(returnValue, type);
<ide> private static class TestController {
<ide> String string() { return null; }
<ide>
<ide> Completable completable() { return null; }
<add>
<add> Mono<ResponseEntity<?>> monoResponseEntityWildcard() { return null; }
<add>
<ide> }
<ide>
<ide> } | 6 |
Javascript | Javascript | add console toggle | b5cbff9d54bcdc4797366414e78871c384f5e878 | <ide><path>threejs/resources/threejs-lessons-helper.js
<ide> });
<ide> var numLinesRemaining = 100;
<ide> var added = false;
<add> const toggle = document.createElement('div');
<add> let show = false;
<add> Object.assign(toggle.style, {
<add> position: 'absolute',
<add> right: 0,
<add> bottom: 0,
<add> background: '#EEE',
<add> 'max-height': '2ex',
<add> });
<add> toggle.addEventListener('click', showHideConsole);
<add>
<add> function showHideConsole() {
<add> show = !show;
<add> toggle.textContent = show ? '☒' : '☐';
<add> parent.style.display = show ? '' : 'none';
<add> }
<add> showHideConsole();
<ide>
<ide> function addLine(type, str) {
<ide> var div = document.createElement('div'); | 1 |
Java | Java | add the ability to attach data to a java cssnode | e0fc8c0ea03c6f0b24dd1d23adb84ac522c397ed | <ide><path>ReactAndroid/src/main/java/com/facebook/csslayout/CSSNode.java
<ide> private enum LayoutState {
<ide> private @Nullable MeasureFunction mMeasureFunction = null;
<ide> private LayoutState mLayoutState = LayoutState.DIRTY;
<ide> private boolean mIsTextNode = false;
<add> private Object mData;
<ide>
<ide> @Override
<ide> public void init() {
<ide> public void setOverflow(CSSOverflow overflow) {
<ide> }
<ide> }
<ide>
<add> @Override
<add> public void setData(Object data) {
<add> mData = data;
<add> }
<add>
<add> @Override
<add> public Object getData() {
<add> return mData;
<add> }
<add>
<ide> /**
<ide> * Resets this instance to its default state. This method is meant to be used when
<ide> * recycling {@link CSSNode} instances.
<ide><path>ReactAndroid/src/main/java/com/facebook/csslayout/CSSNodeAPI.java
<ide> void measure(
<ide> void setDefaultPadding(int spacingType, float padding);
<ide> CSSOverflow getOverflow();
<ide> void setOverflow(CSSOverflow overflow);
<add> void setData(Object data);
<add> Object getData();
<ide> void init();
<ide> void reset();
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/csslayout/CSSNodeJNI.java
<ide> public class CSSNodeJNI implements CSSNodeAPI<CSSNodeJNI> {
<ide> private List<CSSNodeJNI> mChildren;
<ide> private MeasureFunction mMeasureFunction;
<ide> private int mNativePointer;
<add> private Object mData;
<ide>
<ide> private void assertNativeInstance() {
<ide> if (mNativePointer == 0) {
<ide> public boolean isMeasureDefined() {
<ide> public boolean valuesEqual(float f1, float f2) {
<ide> return FloatUtil.floatsEqual(f1, f2);
<ide> }
<add>
<add> @Override
<add> public void setData(Object data) {
<add> mData = data;
<add> }
<add>
<add> @Override
<add> public Object getData() {
<add> return mData;
<add> }
<ide> } | 3 |
Ruby | Ruby | check method existence rather than ruby version | fdaea3189d490c585c5752f4a0423dcfb972d5fd | <ide><path>Library/Homebrew/test/testing_env.rb
<ide> module Test::Unit::Assertions
<ide> def assert_empty(obj, msg=nil)
<ide> assert_respond_to(obj, :empty?, msg)
<ide> assert(obj.empty?, msg)
<del> end if RUBY_VERSION.to_f <= 1.8
<add> end unless method_defined?(:assert_empty)
<ide> end
<ide>
<ide> class Test::Unit::TestCase | 1 |
Python | Python | fix warning when using xcomarg dependencies | d77f0563b403ae9e1a92e8e9e998a1142bb6f359 | <ide><path>airflow/models/baseoperator.py
<ide> def apply_defaults(self: BaseOperator, *args: Any, **kwargs: Any) -> Any:
<ide> # Store the args passed to init -- we need them to support task.map serialzation!
<ide> self._BaseOperator__init_kwargs.update(kwargs) # type: ignore
<ide>
<del> if not instantiated_from_mapped:
<del> # Set upstream task defined by XComArgs passed to template fields of the operator.
<add> # Set upstream task defined by XComArgs passed to template fields of the operator.
<add> # BUT: only do this _ONCE_, not once for each class in the hierarchy
<add> if not instantiated_from_mapped and func == self.__init__.__wrapped__: # type: ignore[misc]
<ide> self.set_xcomargs_dependencies()
<ide> # Mark instance as instantiated.
<ide> self._BaseOperator__instantiated = True
<ide><path>tests/decorators/test_python.py
<ide> def down(a, b):
<ide> assert len(decision.schedulable_tis) == 1 # "down"
<ide> decision.schedulable_tis[0].run(session=session)
<ide> assert result == "'example' None"
<add>
<add>
<add>@pytest.mark.filterwarnings("error")
<add>def test_no_warnings(reset_logging_config, caplog):
<add> @task_decorator
<add> def some_task():
<add> return 1
<add>
<add> @task_decorator
<add> def other(x):
<add> ...
<add>
<add> with DAG(dag_id='test', start_date=DEFAULT_DATE, schedule=None):
<add> other(some_task())
<add> assert caplog.messages == [] | 2 |
Text | Text | update active storage guide to match recent prs | a3de68b66b28f5a38e303815a7ff77786d0cda43 | <ide><path>guides/source/active_storage_overview.md
<ide> files to Active Record objects. It comes with a local disk-based service for
<ide> development and testing and supports mirroring files to subordinate services for
<ide> backups and migrations.
<ide>
<del>Using Active Storage, an application can transform image uploads with
<del>[ImageMagick](https://www.imagemagick.org), generate image representations of
<del>non-image uploads like PDFs and videos, and extract metadata from arbitrary
<del>files.
<add>Using Active Storage, an application can transform image uploads or generate image
<add>representations of non-image uploads like PDFs and videos, and extract metadata from
<add>arbitrary files.
<ide>
<ide> ## Setup
<ide>
<ide> Analyzing Files
<ide>
<ide> Active Storage analyzes files once they've been uploaded by queuing a job in Active Job. Analyzed files will store additional information in the metadata hash, including `analyzed: true`. You can check whether a blob has been analyzed by calling [`analyzed?`][] on it.
<ide>
<del>Image analysis provides `width` and `height` attributes. Video analysis provides these, as well as `duration`, `angle`, and `display_aspect_ratio`.
<del>Audio analysis provides `duration` and `bit_rate` attributes.
<add>Image analysis provides `width` and `height` attributes. Video analysis provides these, as well as `duration`, `angle`, `display_aspect_ratio`, and `video` and `audio` booleans to indicate the presence of those channels. Audio analysis provides `duration` and `bit_rate` attributes.
<ide>
<del>Analysis requires the `mini_magick` gem. Audio/Video analysis also requires the [FFmpeg](https://www.ffmpeg.org/) library, which you must include separately.
<add>Image analysis requires either the `mini_magick` gem and the ImageMagick library, or the `ruby-vips` gem and the libvips library. Note that the libraries are not included in the gems, and must be installed separately.
<add>
<add>Audio/Video analysis requires [FFmpeg](https://www.ffmpeg.org/), which must also be installed separately.
<ide>
<ide> [`analyzed?`]: https://api.rubyonrails.org/classes/ActiveStorage/Blob/Analyzable.html#method-i-analyzed-3F
<ide> | 1 |
Ruby | Ruby | allow disabling of shallow clone | 7eec2d8b5a06ce40a079e2edf1d68ca1df75b70a | <ide><path>Library/Homebrew/download_strategy.rb
<ide> class GitDownloadStrategy < VCSDownloadStrategy
<ide> %r{http://llvm\.org},
<ide> ]
<ide>
<add> def initialize name, resources
<add> super
<add> @shallow = resource.specs.fetch(:shallow) { true }
<add> end
<add>
<ide> def cache_tag; "git" end
<ide>
<ide> def fetch
<ide> def stage
<ide>
<ide> private
<ide>
<add> def shallow_clone?
<add> @shallow && support_depth?
<add> end
<add>
<ide> def support_depth?
<ide> @ref_type != :revision && SHALLOW_CLONE_WHITELIST.any? { |rx| rx === @url }
<ide> end
<ide> def submodules?
<ide>
<ide> def clone_args
<ide> args = %w{clone}
<del> args << '--depth' << '1' if support_depth?
<add> args << '--depth' << '1' if shallow_clone?
<ide>
<ide> case @ref_type
<ide> when :branch, :tag then args << '--branch' << @ref | 1 |
Ruby | Ruby | remove redundant spacing | abd4c699d1f64be9794bcf28409c3a133322fc2c | <ide><path>Library/Homebrew/extend/pathname.rb
<ide> def default_stat
<ide> end
<ide> private :default_stat
<ide>
<del>
<ide> # @private
<ide> def cp_path_sub(pattern, replacement)
<ide> raise "#{self} does not exist" unless self.exist?
<ide> def rmdir_if_possible
<ide> false
<ide> end
<ide>
<del>
<ide> # @private
<ide> def version
<ide> require "version" | 1 |
Text | Text | fix the links | d7ce4e89d375de18088f918d5d05ee1ee070a293 | <ide><path>official/mnist/README.md
<ide> APIs.
<ide> ## Setup
<ide>
<ide> To begin, you'll simply need the latest version of TensorFlow installed.
<del>First make sure you've [added the models folder to your Python path](official/README.md#running-the-models).
<add>First make sure you've [added the models folder to your Python path](/official/README.md#running-the-models).
<ide>
<ide> Then to train the model, run the following:
<ide>
<ide><path>official/resnet/README.md
<ide> Please proceed according to which dataset you would like to train/evaluate on:
<ide> ### Setup
<ide>
<ide> You simply need to have the latest version of TensorFlow installed.
<del>First make sure you've [added the models folder to your Python path](official/README.md#running-the-models).
<add>First make sure you've [added the models folder to your Python path](/official/README.md#running-the-models).
<ide>
<ide> Then download and extract the CIFAR-10 data from Alex's website, specifying the location with the `--data_dir` flag. Run the following:
<ide>
<ide><path>official/wide_deep/README.md
<ide> The input function for the `Estimator` uses `tf.contrib.data.TextLineDataset`, w
<ide> The `Estimator` and `Dataset` APIs are both highly encouraged for fast development and efficient training.
<ide>
<ide> ## Running the code
<del>First make sure you've [added the models folder to your Python path](official/README.md#running-the-models).
<add>First make sure you've [added the models folder to your Python path](/official/README.md#running-the-models).
<ide>
<ide> ### Setup
<ide> The [Census Income Data Set](https://archive.ics.uci.edu/ml/datasets/Census+Income) that this sample uses for training is hosted by the [UC Irvine Machine Learning Repository](https://archive.ics.uci.edu/ml/datasets/). We have provided a script that downloads and cleans the necessary files. | 3 |
Ruby | Ruby | use public_send in extract_values_from_collection | a9764dcc07cf9d6280b313da734d98e096b7d122 | <ide><path>actionview/lib/action_view/helpers/form_options_helper.rb
<ide> def extract_selected_and_disabled(selected)
<ide> def extract_values_from_collection(collection, value_method, selected)
<ide> if selected.is_a?(Proc)
<ide> collection.map do |element|
<del> element.send(value_method) if selected.call(element)
<add> element.public_send(value_method) if selected.call(element)
<ide> end.compact
<ide> else
<ide> selected | 1 |
Javascript | Javascript | speed key validation (by over 9000) | 0c59c57d66d83481795408cd7697c46a3a7dbf9a | <ide><path>src/core/ReactComponent.js
<ide> var invariant = require('invariant');
<ide> var keyMirror = require('keyMirror');
<ide> var merge = require('merge');
<ide>
<del>/**
<del> * Props key that determines if a component's key was already validated.
<del> * @private
<del> */
<del>var IS_KEY_VALIDATED = '{is.key.validated}';
<del>
<ide> /**
<ide> * Every React component is in one of these life cycles.
<ide> */
<ide> var ownerHasWarned = {};
<ide> * @param {ReactComponent} component Component that requires a key.
<ide> */
<ide> function validateExplicitKey(component) {
<del> if (component[IS_KEY_VALIDATED] || component.props.key != null) {
<add> if (component.__keyValidated__ || component.props.key != null) {
<ide> return;
<ide> }
<del> component[IS_KEY_VALIDATED] = true;
<add> component.__keyValidated__ = true;
<ide>
<ide> // We can't provide friendly warnings for top level components.
<ide> if (!ReactCurrentOwner.current) {
<ide> function validateChildKeys(component) {
<ide> }
<ide> } else if (ReactComponent.isValidComponent(component)) {
<ide> // This component was passed in a valid location.
<del> component[IS_KEY_VALIDATED] = true;
<add> component.__keyValidated__ = true;
<ide> }
<ide> }
<ide> | 1 |
Ruby | Ruby | add secure token generator | 5cca205114280bcbf9b43134ff396f1ac47b5071 | <ide><path>activerecord/lib/rails/generators/active_record/migration/templates/create_table_migration.rb
<ide> def change
<ide> <% attributes.each do |attribute| -%>
<ide> <% if attribute.password_digest? -%>
<ide> t.string :password_digest<%= attribute.inject_options %>
<add><% elsif attribute.token? -%>
<add> t.string :<%= attribute.name %><%= attribute.inject_options %>
<ide> <% else -%>
<ide> t.<%= attribute.type %> :<%= attribute.name %><%= attribute.inject_options %>
<ide> <% end -%>
<ide> def change
<ide> t.timestamps
<ide> <% end -%>
<ide> end
<add><% attributes.select(&:token?).each do |attribute| -%>
<add> add_index :<%= table_name %>, :<%= attribute.index_name %><%= attribute.inject_index_options %>, unique: true
<add><% end -%>
<ide> <% attributes_with_index.each do |attribute| -%>
<ide> add_index :<%= table_name %>, :<%= attribute.index_name %><%= attribute.inject_index_options %>
<ide> <% end -%>
<ide><path>activerecord/lib/rails/generators/active_record/migration/templates/migration.rb
<ide> def change
<ide> <% attributes.each do |attribute| -%>
<ide> <%- if attribute.reference? -%>
<ide> add_reference :<%= table_name %>, :<%= attribute.name %><%= attribute.inject_options %>
<add> <%- elsif attribute.token? -%>
<add> add_column :<%= table_name %>, :<%= attribute.name %>, :string<%= attribute.inject_options %>
<add> add_index :<%= table_name %>, :<%= attribute.index_name %><%= attribute.inject_index_options %>, unique: true
<ide> <%- else -%>
<ide> add_column :<%= table_name %>, :<%= attribute.name %>, :<%= attribute.type %><%= attribute.inject_options %>
<ide> <%- if attribute.has_index? -%>
<ide><path>activerecord/lib/rails/generators/active_record/model/templates/model.rb
<ide> class <%= class_name %> < <%= parent_class_name.classify %>
<ide> <% attributes.select(&:reference?).each do |attribute| -%>
<ide> belongs_to :<%= attribute.name %><%= ', polymorphic: true' if attribute.polymorphic? %><%= ', required: true' if attribute.required? %>
<ide> <% end -%>
<add><% attributes.select(&:token?).each do |attribute| -%>
<add> has_secure_token<% if attribute.name != "token" %> :<%= attribute.name %><% end %>
<add><% end -%>
<ide> <% if attributes.any?(&:password_digest?) -%>
<ide> has_secure_password
<ide> <% end -%>
<ide><path>railties/lib/rails/generators/generated_attribute.rb
<ide> def has_uniq_index?
<ide> end
<ide>
<ide> def password_digest?
<del> name == 'password' && type == :digest
<add> name == 'password' && type == :digest
<add> end
<add>
<add> def token?
<add> type == :token
<ide> end
<ide>
<ide> def inject_options
<ide><path>railties/test/generators/migration_generator_test.rb
<ide> def test_create_table_migration_with_singular_table_name
<ide> end
<ide> end
<ide>
<add> def test_create_table_migration_with_token_option
<add> run_generator ["create_users", "token:token", "auth_token:token"]
<add> assert_migration "db/migrate/create_users.rb" do |content|
<add> assert_method :change, content do |change|
<add> assert_match(/create_table :users/, change)
<add> assert_match(/ t\.string :token/, change)
<add> assert_match(/ t\.string :auth_token/, change)
<add> assert_match(/add_index :users, :token, unique: true/, change)
<add> assert_match(/add_index :users, :auth_token, unique: true/, change)
<add> end
<add> end
<add> end
<add>
<add> def test_add_migration_with_token_option
<add> migration = "add_token_to_users"
<add> run_generator [migration, "auth_token:token"]
<add> assert_migration "db/migrate/#{migration}.rb" do |content|
<add> assert_method :change, content do |change|
<add> assert_match(/add_column :users, :auth_token, :string/, change)
<add> assert_match(/add_index :users, :auth_token, unique: true/, change)
<add> end
<add> end
<add> end
<add>
<ide> private
<ide>
<ide> def with_singular_table_name
<ide><path>railties/test/generators/model_generator_test.rb
<ide> def test_foreign_key_is_skipped_for_polymorphic_references
<ide> end
<ide> end
<ide>
<add> def test_token_option_adds_has_secure_token
<add> run_generator ["user", "token:token", "auth_token:token"]
<add> expected_file = <<-FILE.strip_heredoc
<add> class User < ActiveRecord::Base
<add> has_secure_token
<add> has_secure_token :auth_token
<add> end
<add> FILE
<add> assert_file "app/models/user.rb", expected_file
<add> end
<add>
<ide> private
<ide> def assert_generated_fixture(path, parsed_contents)
<ide> fixture_file = File.new File.expand_path(path, destination_root) | 6 |
Python | Python | change the way to store the value in the history | fd23868c4b5940b384be2046579f6ea9eafb65fa | <ide><path>glances/attribute.py
<ide> #
<ide> # This file is part of Glances.
<ide> #
<del># Copyright (C) 2015 Nicolargo <nicolas@nicolargo.com>
<add># Copyright (C) 2016 Nicolargo <nicolas@nicolargo.com>
<ide> #
<ide> # Glances is free software; you can redistribute it and/or modify
<ide> # it under the terms of the GNU Lesser General Public License as published by
<ide>
<ide> """Attribute class."""
<ide>
<del>from time import time
<add>from datetime import datetime
<ide>
<ide>
<ide> class GlancesAttribute(object):
<ide>
<del> def __init__(self, name, description='', history_max_size=None, is_rate=False):
<add> def __init__(self, name, description='', history_max_size=None):
<ide> """Init the attribute
<ide> name: Attribute name (string)
<ide> description: Attribute human reading description (string)
<ide> history_max_size: Maximum size of the history list (default is no limit)
<del> is_rate: If True then the value is manage like a rate (store timestamp in the history)
<add>
<add> History is stored as a list for tuple: [(date, value), ...]
<ide> """
<ide> self._name = name
<ide> self._description = description
<ide> self._value = None
<ide> self._history_max_size = history_max_size
<ide> self._history = []
<del> self.is_rate = is_rate
<ide>
<ide> def __repr__(self):
<ide> return self.value
<ide> def description(self, new_description):
<ide> """
<ide> @property
<ide> def value(self):
<del> if self.is_rate:
<del> if self.history_len() > 0:
<del> return (self._value[1] - self.history_value()[1]) / (self._value[0] - self.history_value()[0])
<del> else:
<del> return None
<add> if self.history_len() > 0:
<add> return (self._value[1] - self.history_value()[1]) / (self._value[0] - self.history_value()[0])
<ide> else:
<del> return self._value
<add> return None
<ide>
<ide> @value.setter
<ide> def value(self, new_value):
<ide> """Set a value.
<del> If self.is_rate is True, store a tuple with (<timestamp>, value)
<del> else, store directly the value (wathever type is it)
<add> Value is a tuple: (<timestamp>, <new_value>)
<ide> """
<del> if self.is_rate:
<del> new_value = (time(), new_value)
<del> if self._value is not None:
<del> self.history_add(self._value)
<del> self._value = new_value
<add> self._value = (datetime.now(), new_value)
<add> self.history_add(self._value)
<ide>
<ide> """
<ide> Properties for the attribute history
<ide> def history_value(self, pos=1):
<ide> def history_mean(self, nb=5):
<ide> """Return the mean on the <nb> values in the history.
<ide> """
<del> if self.is_rate:
<del> h_sum = map(sum, zip(*self._history[-nb:]))
<del> return h_sum[1] / float(self._history[-1][0] - self._history[-nb][0])
<del> else:
<del> return sum(self._history[-nb:]) / float(nb)
<add> h_sum = map(sum, zip(*self._history[-nb:]))
<add> return h_sum[1] / float(self._history[-1][0] - self._history[-nb][0])
<ide><path>glances/exports/graph.py
<ide> def generate_graph(self, stats):
<ide> plt.ylabel(self.get_graph_yunit(i, pre_label=''))
<ide> # Curves
<ide> plt.grid(True)
<del> plt.plot_date(h['date'], h[i['name']],
<add> # Points are stored as tuple (date, value)
<add> x, y = zip(*h[i['name']])
<add> plt.plot_date(x, y,
<ide> fmt='', drawstyle='default', linestyle='-',
<ide> color=self.get_graph_color(i),
<ide> xdate=True, ydate=False)
<ide> def generate_graph(self, stats):
<ide> index_item += 1
<ide> plt.subplot(
<ide> len(stats_history_filtered), 1, index_item)
<add> # Legend
<ide> plt.ylabel(self.get_graph_yunit(i, pre_label=k))
<add> # Curves
<ide> plt.grid(True)
<del> plt.plot_date(h['date'], h[k],
<add> # Points are stored as tuple (date, value)
<add> x, y = zip(*h[k])
<add> plt.plot_date(x, y,
<ide> fmt='', drawstyle='default', linestyle='-',
<ide> color=self.get_graph_color(i),
<ide> xdate=True, ydate=False)
<ide><path>glances/history.py
<ide> class GlancesHistory(object):
<ide>
<ide> """This class manage a dict of GlancesAttribute
<ide> - key: stats name
<del> - GlancesAttribute: history value"""
<add> - value: GlancesAttribute"""
<ide>
<ide> def __init__(self):
<ide> """
<ide> def __init__(self):
<ide>
<ide> def add(self, key, value,
<ide> description='',
<del> history_max_size=None,
<del> is_rate=False):
<add> history_max_size=None):
<ide> """Add an new item (key, value) to the current history."""
<ide> if key not in self.stats_history:
<ide> self.stats_history[key] = GlancesAttribute(key,
<ide> description=description,
<del> history_max_size=history_max_size,
<del> is_rate=is_rate)
<add> history_max_size=history_max_size)
<ide> self.stats_history[key].value = value
<ide>
<ide> def reset(self):
<ide><path>glances/plugins/glances_plugin.py
<ide> def update_stats_history(self, item_name=''):
<ide> if (self.stats and self.args is not None and
<ide> self.args.export_graph and
<ide> self.get_items_history_list() is not None):
<del> self.stats_history.add('date', datetime.now())
<add> # self.stats_history.add('date', datetime.now())
<ide> for i in self.get_items_history_list():
<ide> if isinstance(self.stats, list):
<ide> # Stats is a list of data | 4 |
Python | Python | fix download.py for glove vectors | 5a5c7192a58b26837d375ad683d59622c73d267f | <ide><path>spacy/download.py
<ide> def download(lang, force=False, fail_on_exist=True):
<ide> sputnik.purge(about.__title__, about.__version__)
<ide>
<ide> try:
<del> sputnik.package(about.__title__, about.__version__, about.__models__[lang])
<add> sputnik.package(about.__title__, about.__version__,
<add> about.__models__.get(lang, lang))
<ide> if fail_on_exist:
<ide> print("Model already installed. Please run 'python -m "
<ide> "spacy.%s.download --force' to reinstall." % lang, file=sys.stderr)
<ide> sys.exit(0)
<ide> except (PackageNotFoundException, CompatiblePackageNotFoundException):
<ide> pass
<ide>
<del> package = sputnik.install(about.__title__, about.__version__, about.__models__[lang])
<add> package = sputnik.install(about.__title__, about.__version__,
<add> about.__models__.get(lang, lang))
<ide>
<ide> try:
<del> sputnik.package(about.__title__, about.__version__, about.__models__[lang])
<add> sputnik.package(about.__title__, about.__version__,
<add> about.__models__.get(lang, lang))
<ide> except (PackageNotFoundException, CompatiblePackageNotFoundException):
<ide> print("Model failed to install. Please run 'python -m "
<ide> "spacy.%s.download --force'." % lang, file=sys.stderr) | 1 |
PHP | PHP | extract some classes for router | b208a4fc3b35da167a2dcb9b581d9e072d20ec92 | <ide><path>src/Illuminate/Routing/MiddlewareNameResolver.php
<add><?php
<add>
<add>namespace Illuminate\Routing;
<add>
<add>use Closure;
<add>
<add>class MiddlewareNameResolver
<add>{
<add> /**
<add> * Resolve the middleware name to a class name(s) preserving passed parameters.
<add> *
<add> * @param string $name
<add> * @param array $map
<add> * @param array $middlewareGroups
<add> * @return string|array
<add> */
<add> public static function resolve($name, $map, $middlewareGroups)
<add> {
<add> // When the middleware is simply a Closure, we will return this Closure instance
<add> // directly so that Closures can be registered as middleware inline, which is
<add> // convenient on occasions when the developers are experimenting with them.
<add> if ($name instanceof Closure) {
<add> return $name;
<add> } elseif (isset($map[$name]) && $map[$name] instanceof Closure) {
<add> return $map[$name];
<add>
<add> // If the middleware is the name of a middleware group, we will return the array
<add> // of middlewares that belong to the group. This allows developers to group a
<add> // set of middleware under single keys that can be conveniently referenced.
<add> } elseif (isset($middlewareGroups[$name])) {
<add> return static::parseMiddlewareGroup(
<add> $name, $map, $middlewareGroups
<add> );
<add>
<add> // Finally, when the middleware is simply a string mapped to a class name the
<add> // middleware name will get parsed into the full class name and parameters
<add> // which may be run using the Pipeline which accepts this string format.
<add> } else {
<add> list($name, $parameters) = array_pad(explode(':', $name, 2), 2, null);
<add>
<add> return (isset($map[$name]) ? $map[$name] : $name).
<add> (! is_null($parameters) ? ':'.$parameters : '');
<add> }
<add> }
<add>
<add> /**
<add> * Parse the middleware group and format it for usage.
<add> *
<add> * @param string $name
<add> * @param array $middlewareGroups
<add> * @return array
<add> */
<add> protected static function parseMiddlewareGroup($name, $map, $middlewareGroups)
<add> {
<add> $results = [];
<add>
<add> foreach ($middlewareGroups[$name] as $middleware) {
<add> // If the middleware is another middleware group we will pull in the group and
<add> // merge its middleware into the results. This allows groups to conveniently
<add> // reference other groups without needing to repeat all their middlewares.
<add> if (isset($middlewareGroups[$middleware])) {
<add> $results = array_merge($results, static::parseMiddlewareGroup(
<add> $middleware, $map, $middlewareGroups
<add> ));
<add>
<add> continue;
<add> }
<add>
<add> list($middleware, $parameters) = array_pad(
<add> explode(':', $middleware, 2), 2, null
<add> );
<add>
<add> // If this middleware is actually a route middleware, we will extract the full
<add> // class name out of the middleware list now. Then we'll add the parameters
<add> // back onto this class' name so the pipeline will properly extract them.
<add> if (isset($map[$middleware])) {
<add> $middleware = $map[$middleware];
<add> }
<add>
<add> $results[] = $middleware.($parameters ? ':'.$parameters : '');
<add> }
<add>
<add> return $results;
<add> }
<add>}
<ide><path>src/Illuminate/Routing/RouteGroup.php
<add><?php
<add>
<add>namespace Illuminate\Routing;
<add>
<add>use Illuminate\Support\Arr;
<add>
<add>class RouteGroup
<add>{
<add> /**
<add> * Merge route groups into a new array.
<add> *
<add> * @param array $new
<add> * @param array $old
<add> * @return array
<add> */
<add> public static function merge($new, $old)
<add> {
<add> if (isset($new['domain'])) {
<add> unset($old['domain']);
<add> }
<add>
<add> $new = array_merge(static::formatAs($new, $old), [
<add> 'namespace' => static::formatNamespace($new, $old),
<add> 'prefix' => static::formatPrefix($new, $old),
<add> 'where' => static::formatWhere($new, $old),
<add> ]);
<add>
<add> return array_merge_recursive(Arr::except(
<add> $old, ['namespace', 'prefix', 'where', 'as']
<add> ), $new);
<add> }
<add>
<add> /**
<add> * Format the namespace for the new group attributes.
<add> *
<add> * @param array $new
<add> * @param array $old
<add> * @return string|null
<add> */
<add> protected static function formatNamespace($new, $old)
<add> {
<add> if (isset($new['namespace'])) {
<add> return isset($old['namespace'])
<add> ? trim($old['namespace'], '\\').'\\'.trim($new['namespace'], '\\')
<add> : trim($new['namespace'], '\\');
<add> }
<add>
<add> return isset($old['namespace']) ? $old['namespace'] : null;
<add> }
<add>
<add> /**
<add> * Format the prefix for the new group attributes.
<add> *
<add> * @param array $new
<add> * @param array $old
<add> * @return string|null
<add> */
<add> protected static function formatPrefix($new, $old)
<add> {
<add> $old = Arr::get($old, 'prefix');
<add>
<add> return isset($new['prefix']) ? trim($old, '/').'/'.trim($new['prefix'], '/') : $old;
<add> }
<add>
<add> /**
<add> * Format the "wheres" for the new group attributes.
<add> *
<add> * @param array $new
<add> * @param array $old
<add> * @return array
<add> */
<add> protected static function formatWhere($new, $old)
<add> {
<add> return array_merge(
<add> isset($old['where']) ? $old['where'] : [],
<add> isset($new['where']) ? $new['where'] : []
<add> );
<add> }
<add>
<add> /**
<add> * Format the "as" clause of the new group attributes.
<add> *
<add> * @param array $new
<add> * @param array $old
<add> * @return array
<add> */
<add> protected static function formatAs($new, $old)
<add> {
<add> if (isset($old['as'])) {
<add> $new['as'] = $old['as'].Arr::get($new, 'as', '');
<add> }
<add>
<add> return $new;
<add> }
<add>}
<ide><path>src/Illuminate/Routing/Router.php
<ide> public function group(array $attributes, $routes)
<ide> array_pop($this->groupStack);
<ide> }
<ide>
<del> /**
<del> * Load the provided routes.
<del> *
<del> * @param \Closure|string $routes
<del> * @return void
<del> */
<del> protected function loadRoutes($routes)
<del> {
<del> if ($routes instanceof Closure) {
<del> $routes($this);
<del> } else {
<del> $router = $this;
<del>
<del> require $routes;
<del> }
<del> }
<del>
<ide> /**
<ide> * Update the group stack with the given attributes.
<ide> *
<ide> protected function loadRoutes($routes)
<ide> protected function updateGroupStack(array $attributes)
<ide> {
<ide> if (! empty($this->groupStack)) {
<del> $attributes = $this->mergeGroup($attributes, end($this->groupStack));
<add> $attributes = RouteGroup::merge($attributes, end($this->groupStack));
<ide> }
<ide>
<ide> $this->groupStack[] = $attributes;
<ide> protected function updateGroupStack(array $attributes)
<ide> */
<ide> public function mergeWithLastGroup($new)
<ide> {
<del> return $this->mergeGroup($new, end($this->groupStack));
<del> }
<del>
<del> /**
<del> * Merge the given group attributes.
<del> *
<del> * @param array $new
<del> * @param array $old
<del> * @return array
<del> */
<del> public static function mergeGroup($new, $old)
<del> {
<del> $new['namespace'] = static::formatUsesPrefix($new, $old);
<del>
<del> $new['prefix'] = static::formatGroupPrefix($new, $old);
<del>
<del> if (isset($new['domain'])) {
<del> unset($old['domain']);
<del> }
<del>
<del> $new['where'] = array_merge(
<del> isset($old['where']) ? $old['where'] : [],
<del> isset($new['where']) ? $new['where'] : []
<del> );
<del>
<del> if (isset($old['as'])) {
<del> $new['as'] = $old['as'].(isset($new['as']) ? $new['as'] : '');
<del> }
<del>
<del> return array_merge_recursive(Arr::except($old, ['namespace', 'prefix', 'where', 'as']), $new);
<add> return RouteGroup::merge($new, end($this->groupStack));
<ide> }
<ide>
<ide> /**
<del> * Format the uses prefix for the new group attributes.
<del> *
<del> * @param array $new
<del> * @param array $old
<del> * @return string|null
<del> */
<del> protected static function formatUsesPrefix($new, $old)
<del> {
<del> if (isset($new['namespace'])) {
<del> return isset($old['namespace'])
<del> ? trim($old['namespace'], '\\').'\\'.trim($new['namespace'], '\\')
<del> : trim($new['namespace'], '\\');
<del> }
<del>
<del> return isset($old['namespace']) ? $old['namespace'] : null;
<del> }
<del>
<del> /**
<del> * Format the prefix for the new group attributes.
<add> * Load the provided routes.
<ide> *
<del> * @param array $new
<del> * @param array $old
<del> * @return string|null
<add> * @param \Closure|string $routes
<add> * @return void
<ide> */
<del> protected static function formatGroupPrefix($new, $old)
<add> protected function loadRoutes($routes)
<ide> {
<del> $oldPrefix = isset($old['prefix']) ? $old['prefix'] : null;
<add> if ($routes instanceof Closure) {
<add> $routes($this);
<add> } else {
<add> $router = $this;
<ide>
<del> if (isset($new['prefix'])) {
<del> return trim($oldPrefix, '/').'/'.trim($new['prefix'], '/');
<add> require $routes;
<ide> }
<del>
<del> return $oldPrefix;
<ide> }
<ide>
<ide> /**
<ide> protected function createRoute($methods, $uri, $action)
<ide> return $route;
<ide> }
<ide>
<add> /**
<add> * Determine if the action is routing to a controller.
<add> *
<add> * @param array $action
<add> * @return bool
<add> */
<add> protected function actionReferencesController($action)
<add> {
<add> if (! $action instanceof Closure) {
<add> return is_string($action) || (isset($action['uses']) && is_string($action['uses']));
<add> }
<add>
<add> return false;
<add> }
<add>
<add> /**
<add> * Add a controller based route action to the action array.
<add> *
<add> * @param array|string $action
<add> * @return array
<add> */
<add> protected function convertToControllerAction($action)
<add> {
<add> if (is_string($action)) {
<add> $action = ['uses' => $action];
<add> }
<add>
<add> // Here we'll merge any group "uses" statement if necessary so that the action
<add> // has the proper clause for this property. Then we can simply set the name
<add> // of the controller on the action and return the action array for usage.
<add> if (! empty($this->groupStack)) {
<add> $action['uses'] = $this->prependGroupNamespace($action['uses']);
<add> }
<add>
<add> // Here we will set this controller name on the action array just so we always
<add> // have a copy of it for reference if we need it. This can be used while we
<add> // search for a controller name or do some other type of fetch operation.
<add> $action['controller'] = $action['uses'];
<add>
<add> return $action;
<add> }
<add>
<add> /**
<add> * Prepend the last group namespace onto the use clause.
<add> *
<add> * @param string $class
<add> * @return string
<add> */
<add> protected function prependGroupNamespace($class)
<add> {
<add> $group = end($this->groupStack);
<add>
<add> return isset($group['namespace']) && strpos($class, '\\') !== 0
<add> ? $group['namespace'].'\\'.$class : $class;
<add> }
<add>
<ide> /**
<ide> * Create a new Route object.
<ide> *
<ide> protected function prefix($uri)
<ide> */
<ide> protected function addWhereClausesToRoute($route)
<ide> {
<del> $where = isset($route->getAction()['where']) ? $route->getAction()['where'] : [];
<del>
<del> $route->where(array_merge($this->patterns, $where));
<add> $route->where(array_merge(
<add> $this->patterns, isset($route->getAction()['where']) ? $route->getAction()['where'] : []
<add> ));
<ide>
<ide> return $route;
<ide> }
<ide> protected function addWhereClausesToRoute($route)
<ide> */
<ide> protected function mergeGroupAttributesIntoRoute($route)
<ide> {
<del> $action = $this->mergeWithLastGroup($route->getAction());
<del>
<del> $route->setAction($action);
<del> }
<del>
<del> /**
<del> * Determine if the action is routing to a controller.
<del> *
<del> * @param array $action
<del> * @return bool
<del> */
<del> protected function actionReferencesController($action)
<del> {
<del> if ($action instanceof Closure) {
<del> return false;
<del> }
<del>
<del> return is_string($action) || (isset($action['uses']) && is_string($action['uses']));
<del> }
<del>
<del> /**
<del> * Add a controller based route action to the action array.
<del> *
<del> * @param array|string $action
<del> * @return array
<del> */
<del> protected function convertToControllerAction($action)
<del> {
<del> if (is_string($action)) {
<del> $action = ['uses' => $action];
<del> }
<del>
<del> // Here we'll merge any group "uses" statement if necessary so that the action
<del> // has the proper clause for this property. Then we can simply set the name
<del> // of the controller on the action and return the action array for usage.
<del> if (! empty($this->groupStack)) {
<del> $action['uses'] = $this->prependGroupUses($action['uses']);
<del> }
<del>
<del> // Here we will set this controller name on the action array just so we always
<del> // have a copy of it for reference if we need it. This can be used while we
<del> // search for a controller name or do some other type of fetch operation.
<del> $action['controller'] = $action['uses'];
<del>
<del> return $action;
<del> }
<del>
<del> /**
<del> * Prepend the last group uses onto the use clause.
<del> *
<del> * @param string $uses
<del> * @return string
<del> */
<del> protected function prependGroupUses($uses)
<del> {
<del> $group = end($this->groupStack);
<del>
<del> return isset($group['namespace']) && strpos($uses, '\\') !== 0 ? $group['namespace'].'\\'.$uses : $uses;
<add> $route->setAction($this->mergeWithLastGroup($route->getAction()));
<ide> }
<ide>
<ide> /**
<ide> public function dispatchToRoute(Request $request)
<ide> return $this->prepareResponse($request, $response);
<ide> }
<ide>
<add> /**
<add> * Find the route matching a given request.
<add> *
<add> * @param \Illuminate\Http\Request $request
<add> * @return \Illuminate\Routing\Route
<add> */
<add> protected function findRoute($request)
<add> {
<add> $this->current = $route = $this->routes->match($request);
<add>
<add> $this->container->instance('Illuminate\Routing\Route', $route);
<add>
<add> return $route;
<add> }
<add>
<ide> /**
<ide> * Run the given route within a Stack "onion" instance.
<ide> *
<ide> protected function runRouteWithinStack(Route $route, Request $request)
<ide> }
<ide>
<ide> /**
<del> * Gather the middleware for the given route.
<add> * Gather the middleware for the given route with resolved class names.
<ide> *
<ide> * @param \Illuminate\Routing\Route $route
<ide> * @return array
<ide> */
<ide> public function gatherRouteMiddleware(Route $route)
<ide> {
<ide> $middleware = collect($route->gatherMiddleware())->map(function ($name) {
<del> return (array) $this->resolveMiddlewareClassName($name);
<add> return (array) MiddlewareNameResolver::resolve($name, $this->middleware, $this->middlewareGroups);
<ide> })->flatten();
<ide>
<ide> return $this->sortMiddleware($middleware);
<ide> }
<ide>
<del> /**
<del> * Resolve the middleware name to a class name(s) preserving passed parameters.
<del> *
<del> * @param string $name
<del> * @return string|array
<del> */
<del> public function resolveMiddlewareClassName($name)
<del> {
<del> $map = $this->middleware;
<del>
<del> // When the middleware is simply a Closure, we will return this Closure instance
<del> // directly so that Closures can be registered as middleware inline, which is
<del> // convenient on occasions when the developers are experimenting with them.
<del> if ($name instanceof Closure) {
<del> return $name;
<del> } elseif (isset($map[$name]) && $map[$name] instanceof Closure) {
<del> return $map[$name];
<del>
<del> // If the middleware is the name of a middleware group, we will return the array
<del> // of middlewares that belong to the group. This allows developers to group a
<del> // set of middleware under single keys that can be conveniently referenced.
<del> } elseif (isset($this->middlewareGroups[$name])) {
<del> return $this->parseMiddlewareGroup($name);
<del>
<del> // Finally, when the middleware is simply a string mapped to a class name the
<del> // middleware name will get parsed into the full class name and parameters
<del> // which may be run using the Pipeline which accepts this string format.
<del> } else {
<del> list($name, $parameters) = array_pad(explode(':', $name, 2), 2, null);
<del>
<del> return (isset($map[$name]) ? $map[$name] : $name).
<del> (! is_null($parameters) ? ':'.$parameters : '');
<del> }
<del> }
<del>
<del> /**
<del> * Parse the middleware group and format it for usage.
<del> *
<del> * @param string $name
<del> * @return array
<del> */
<del> protected function parseMiddlewareGroup($name)
<del> {
<del> $results = [];
<del>
<del> foreach ($this->middlewareGroups[$name] as $middleware) {
<del> // If the middleware is another middleware group we will pull in the group and
<del> // merge its middleware into the results. This allows groups to conveniently
<del> // reference other groups without needing to repeat all their middlewares.
<del> if (isset($this->middlewareGroups[$middleware])) {
<del> $results = array_merge(
<del> $results, $this->parseMiddlewareGroup($middleware)
<del> );
<del>
<del> continue;
<del> }
<del>
<del> list($middleware, $parameters) = array_pad(
<del> explode(':', $middleware, 2), 2, null
<del> );
<del>
<del> // If this middleware is actually a route middleware, we will extract the full
<del> // class name out of the middleware list now. Then we'll add the parameters
<del> // back onto this class' name so the pipeline will properly extract them.
<del> if (isset($this->middleware[$middleware])) {
<del> $middleware = $this->middleware[$middleware];
<del> }
<del>
<del> $results[] = $middleware.($parameters ? ':'.$parameters : '');
<del> }
<del>
<del> return $results;
<del> }
<del>
<ide> /**
<ide> * Sort the given middleware by priority.
<ide> *
<ide> protected function sortMiddleware(Collection $middlewares)
<ide> }
<ide>
<ide> /**
<del> * Find the route matching a given request.
<add> * Create a response instance from the given value.
<ide> *
<del> * @param \Illuminate\Http\Request $request
<del> * @return \Illuminate\Routing\Route
<add> * @param \Symfony\Component\HttpFoundation\Request $request
<add> * @param mixed $response
<add> * @return \Illuminate\Http\Response
<ide> */
<del> protected function findRoute($request)
<add> public function prepareResponse($request, $response)
<ide> {
<del> $this->current = $route = $this->routes->match($request);
<del>
<del> $this->container->instance('Illuminate\Routing\Route', $route);
<add> if ($response instanceof PsrResponseInterface) {
<add> $response = (new HttpFoundationFactory)->createResponse($response);
<add> } elseif (! $response instanceof SymfonyResponse) {
<add> $response = new Response($response);
<add> }
<ide>
<del> return $route;
<add> return $response->prepare($request);
<ide> }
<ide>
<ide> /**
<ide> public function bind($key, $binder)
<ide> $this->binders[str_replace('-', '_', $key)] = $binder;
<ide> }
<ide>
<del> /**
<del> * Get the binding callback for a given binding.
<del> *
<del> * @param string $key
<del> * @return \Closure|null
<del> */
<del> public function getBindingCallback($key)
<del> {
<del> if (isset($this->binders[$key = str_replace('-', '_', $key)])) {
<del> return $this->binders[$key];
<del> }
<del> }
<del>
<ide> /**
<ide> * Create a class based binding using the IoC container.
<ide> *
<ide> public function createClassBinding($binding)
<ide> };
<ide> }
<ide>
<add> /**
<add> * Get the binding callback for a given binding.
<add> *
<add> * @param string $key
<add> * @return \Closure|null
<add> */
<add> public function getBindingCallback($key)
<add> {
<add> if (isset($this->binders[$key = str_replace('-', '_', $key)])) {
<add> return $this->binders[$key];
<add> }
<add> }
<add>
<add> /**
<add> * Get the global "where" patterns.
<add> *
<add> * @return array
<add> */
<add> public function getPatterns()
<add> {
<add> return $this->patterns;
<add> }
<add>
<ide> /**
<ide> * Set a global where pattern on all routes.
<ide> *
<ide> public function patterns($patterns)
<ide> }
<ide> }
<ide>
<del> /**
<del> * Create a response instance from the given value.
<del> *
<del> * @param \Symfony\Component\HttpFoundation\Request $request
<del> * @param mixed $response
<del> * @return \Illuminate\Http\Response
<del> */
<del> public function prepareResponse($request, $response)
<del> {
<del> if ($response instanceof PsrResponseInterface) {
<del> $response = (new HttpFoundationFactory)->createResponse($response);
<del> } elseif (! $response instanceof SymfonyResponse) {
<del> $response = new Response($response);
<del> }
<del>
<del> return $response->prepare($request);
<del> }
<del>
<ide> /**
<ide> * Determine if the router currently has a group stack.
<ide> *
<ide> public function setRoutes(RouteCollection $routes)
<ide> $this->container->instance('routes', $this->routes);
<ide> }
<ide>
<del> /**
<del> * Get the global "where" patterns.
<del> *
<del> * @return array
<del> */
<del> public function getPatterns()
<del> {
<del> return $this->patterns;
<del> }
<del>
<ide> /**
<ide> * Dynamically handle calls into the router instance.
<ide> *
<ide><path>tests/Routing/RoutingRouteTest.php
<ide> use Illuminate\Routing\Router;
<ide> use Illuminate\Events\Dispatcher;
<ide> use Illuminate\Routing\Controller;
<add>use Illuminate\Routing\RouteGroup;
<ide> use Illuminate\Container\Container;
<ide> use Illuminate\Database\Eloquent\Model;
<ide> use Illuminate\Auth\Middleware\Authorize;
<ide> public function testModelBindingThroughIOC()
<ide> public function testGroupMerging()
<ide> {
<ide> $old = ['prefix' => 'foo/bar/'];
<del> $this->assertEquals(['prefix' => 'foo/bar/baz', 'namespace' => null, 'where' => []], Router::mergeGroup(['prefix' => 'baz'], $old));
<add> $this->assertEquals(['prefix' => 'foo/bar/baz', 'namespace' => null, 'where' => []], RouteGroup::merge(['prefix' => 'baz'], $old));
<ide>
<ide> $old = ['domain' => 'foo'];
<del> $this->assertEquals(['domain' => 'baz', 'prefix' => null, 'namespace' => null, 'where' => []], Router::mergeGroup(['domain' => 'baz'], $old));
<add> $this->assertEquals(['domain' => 'baz', 'prefix' => null, 'namespace' => null, 'where' => []], RouteGroup::merge(['domain' => 'baz'], $old));
<ide>
<ide> $old = ['as' => 'foo.'];
<del> $this->assertEquals(['as' => 'foo.bar', 'prefix' => null, 'namespace' => null, 'where' => []], Router::mergeGroup(['as' => 'bar'], $old));
<add> $this->assertEquals(['as' => 'foo.bar', 'prefix' => null, 'namespace' => null, 'where' => []], RouteGroup::merge(['as' => 'bar'], $old));
<ide>
<ide> $old = ['where' => ['var1' => 'foo', 'var2' => 'bar']];
<ide> $this->assertEquals(['prefix' => null, 'namespace' => null, 'where' => [
<ide> 'var1' => 'foo', 'var2' => 'baz', 'var3' => 'qux',
<del> ]], Router::mergeGroup(['where' => ['var2' => 'baz', 'var3' => 'qux']], $old));
<add> ]], RouteGroup::merge(['where' => ['var2' => 'baz', 'var3' => 'qux']], $old));
<ide>
<ide> $old = [];
<ide> $this->assertEquals(['prefix' => null, 'namespace' => null, 'where' => [
<ide> 'var1' => 'foo', 'var2' => 'bar',
<del> ]], Router::mergeGroup(['where' => ['var1' => 'foo', 'var2' => 'bar']], $old));
<add> ]], RouteGroup::merge(['where' => ['var1' => 'foo', 'var2' => 'bar']], $old));
<ide> }
<ide>
<ide> public function testRouteGrouping() | 4 |
Text | Text | update readme to link to previous versions | 0447fda26d4276a92f01b13c341f0b785c346ea3 | <ide><path>README.md
<ide> CDN: https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.0.0/Chart.js
<ide>
<ide> ## Documentation
<ide>
<del>You can find documentation at [www.chartjs.org/docs](http://www.chartjs.org/docs). The markdown files that build the site are available under `/docs`. Please note - in some of the json examples of configuration you might notice some liquid tags - this is just for the generating the site html, please disregard.
<add>You can find documentation at [www.chartjs.org/docs](http://www.chartjs.org/docs). The markdown files that build the site are available under `/docs`. Previous version documentation is available at [www.chartjs.org/docs/#notes-previous-versions](http://www.chartjs.org/docs/#notes-previous-versions).
<ide>
<ide> ## Contributing
<ide> | 1 |
Javascript | Javascript | remove stray @private comments | 824e176a84f1ce986cff94b9b12809049c9b4738 | <ide><path>src/layout/tree.js
<ide> d3.layout.tree = function() {
<ide> return a;
<ide> }
<ide>
<del> /** @private */
<ide> function nextLeft(v) {
<ide> return v.children ? v.children[0] : v.thread;
<ide> }
<ide> d3.layout.tree = function() {
<ide> firstWalk(root);
<ide> secondWalk(root, -root.prelim, 0);
<ide>
<del> /** @private Returns the angle of the given node. */
<add> /** Returns the angle of the given node. */
<ide> function midAngle(n) {
<ide> return (orient === "radial") ? n.breadth / depth : 0;
<ide> } | 1 |
Python | Python | use explicit reexports for numpy.typing objects | 8b8bbdfa5b5331811841176f64470521a890a7c0 | <ide><path>numpy/typing/__init__.py
<ide> class _8Bit(_16Bit): ... # type: ignore[misc]
<ide> _VoidLike,
<ide> )
<ide> from ._shape import _Shape, _ShapeLike
<del>from ._dtype_like import _SupportsDType, _VoidDTypeLike, DTypeLike
<add>from ._dtype_like import _SupportsDType, _VoidDTypeLike, DTypeLike as DTypeLike
<ide> from ._array_like import (
<del> ArrayLike,
<add> ArrayLike as ArrayLike,
<ide> _ArrayLike,
<ide> _NestedSequence,
<ide> _SupportsArray, | 1 |
Mixed | Javascript | adjust types for getrandomvalues | b8de7aa4c2731883121bd7dcd19ec116f685eaa0 | <ide><path>doc/api/webcrypto.md
<ide> Provides access to the `SubtleCrypto` API.
<ide> added: v15.0.0
<ide> -->
<ide>
<del>* `typedArray` {Buffer|TypedArray|DataView|ArrayBuffer}
<del>* Returns: {Buffer|TypedArray|DataView|ArrayBuffer} Returns `typedArray`.
<add>* `typedArray` {Buffer|TypedArray}
<add>* Returns: {Buffer|TypedArray}
<ide>
<ide> Generates cryptographically strong random values. The given `typedArray` is
<ide> filled with random values, and a reference to `typedArray` is returned.
<ide>
<add>The given `typedArray` must be an integer-based instance of {TypedArray},
<add>i.e. `Float32Array` and `Float64Array` are not accepted.
<add>
<ide> An error will be thrown if the given `typedArray` is larger than 65,536 bytes.
<ide>
<ide> ### `crypto.randomUUID()`
<ide><path>lib/internal/crypto/random.js
<ide> const {
<ide> const {
<ide> isArrayBufferView,
<ide> isAnyArrayBuffer,
<add> isTypedArray,
<ide> isFloat32Array,
<ide> isFloat64Array,
<ide> } = require('internal/util/types');
<ide> function onJobDone(buf, callback, error) {
<ide> // not allowed to exceed 65536 bytes, and can only
<ide> // be an integer-type TypedArray.
<ide> function getRandomValues(data) {
<del> if (!isArrayBufferView(data) ||
<add> if (!isTypedArray(data) ||
<ide> isFloat32Array(data) ||
<ide> isFloat64Array(data)) {
<ide> // Ordinarily this would be an ERR_INVALID_ARG_TYPE. However,
<ide><path>test/parallel/test-webcrypto-random.js
<ide> const { getRandomValues } = require('crypto').webcrypto;
<ide> undefined, null, '', 1, {}, [],
<ide> new Float32Array(1),
<ide> new Float64Array(1),
<add> new DataView(new ArrayBuffer(1)),
<ide> ].forEach((i) => {
<ide> assert.throws(
<ide> () => getRandomValues(i),
<ide> const intTypedConstructors = [
<ide> Uint8Array,
<ide> Uint16Array,
<ide> Uint32Array,
<add> Uint8ClampedArray,
<ide> BigInt64Array,
<ide> BigUint64Array,
<ide> ];
<ide> for (const ctor of intTypedConstructors) {
<ide> {
<ide> const buf = new Uint16Array(10);
<ide> const before = Buffer.from(buf).toString('hex');
<del> getRandomValues(new DataView(buf.buffer));
<add> getRandomValues(buf);
<ide> const after = Buffer.from(buf).toString('hex');
<ide> assert.notStrictEqual(before, after);
<ide> } | 3 |
Go | Go | pass extra file to child process as status handler | 3b9d88210e763bebdfd7badb6ed3fd507d0f6513 | <ide><path>daemon/networkdriver/portmapper/proxy.go
<ide> type proxyCommand struct {
<ide>
<ide> // execProxy is the reexec function that is registered to start the userland proxies
<ide> func execProxy() {
<add> f := os.NewFile(3, "signal-parent")
<ide> host, container := parseHostContainerAddrs()
<ide>
<ide> p, err := proxy.NewProxy(host, container)
<ide> if err != nil {
<del> os.Stdout.WriteString("1\n")
<del> fmt.Fprint(os.Stderr, err)
<add> fmt.Fprintf(f, "1\n%s", err)
<add> f.Close()
<ide> os.Exit(1)
<ide> }
<ide> go handleStopSignals(p)
<del> os.Stdout.WriteString("0\n")
<add> fmt.Fprint(f, "0\n")
<add> f.Close()
<ide>
<ide> // Run will block until the proxy stops
<ide> p.Run()
<ide> func NewProxyCommand(proto string, hostIP net.IP, hostPort int, containerIP net.
<ide> }
<ide>
<ide> func (p *proxyCommand) Start() error {
<del> stdout, err := p.cmd.StdoutPipe()
<add> r, w, err := os.Pipe()
<ide> if err != nil {
<del> return err
<del> }
<del> defer stdout.Close()
<del> stderr, err := p.cmd.StderrPipe()
<del> if err != nil {
<del> return err
<add> return fmt.Errorf("proxy unable to open os.Pipe %s", err)
<ide> }
<del> defer stderr.Close()
<add> defer r.Close()
<add> p.cmd.ExtraFiles = []*os.File{w}
<ide> if err := p.cmd.Start(); err != nil {
<ide> return err
<ide> }
<add> w.Close()
<ide>
<ide> errchan := make(chan error, 1)
<ide> go func() {
<ide> buf := make([]byte, 2)
<del> stdout.Read(buf)
<add> r.Read(buf)
<ide>
<ide> if string(buf) != "0\n" {
<del> errStr, _ := ioutil.ReadAll(stderr)
<add> errStr, _ := ioutil.ReadAll(r)
<ide> errchan <- fmt.Errorf("Error starting userland proxy: %s", errStr)
<ide> return
<ide> }
<ide><path>integration-cli/docker_cli_run_test.go
<ide> func TestRunPortInUse(t *testing.T) {
<ide> logDone("run - fail if port already in use")
<ide> }
<ide>
<add>// https://github.com/docker/docker/issues/8428
<add>func TestRunPortProxy(t *testing.T) {
<add> defer deleteAllContainers()
<add>
<add> port := "12345"
<add> cmd := exec.Command(dockerBinary, "run", "-p", port+":80", "busybox", "true")
<add>
<add> out, _, err := runCommandWithOutput(cmd)
<add> if err != nil {
<add> t.Fatalf("Failed to run and bind port %s, output: %s, error: %s", port, out, err)
<add> }
<add>
<add> // connect for 10 times here. This will trigger 10 EPIPES in the child
<add> // process and kill it when it writes to a closed stdout/stderr
<add> for i := 0; i < 10; i++ {
<add> net.Dial("tcp", fmt.Sprintf("0.0.0.0:%s", port))
<add> }
<add>
<add> listPs := exec.Command("sh", "-c", "ps ax | grep docker")
<add> out, _, err = runCommandWithOutput(listPs)
<add> if err != nil {
<add> t.Errorf("list docker process failed with output %s, error %s", out, err)
<add> }
<add> if strings.Contains(out, "docker <defunct>") {
<add> t.Errorf("Unexpected defunct docker process")
<add> }
<add> if !strings.Contains(out, "docker-proxy -proto tcp -host-ip 0.0.0.0 -host-port 12345") {
<add> t.Errorf("Failed to find docker-proxy process, got %s", out)
<add> }
<add>
<add> logDone("run - proxy should work with unavailable port")
<add>}
<add>
<ide> // Regression test for #7792
<ide> func TestRunMountOrdering(t *testing.T) {
<ide> tmpDir, err := ioutil.TempDir("", "docker_nested_mount_test") | 2 |
PHP | PHP | change "stirng" to "string" | c633877a8a82b341127bf13a4b4cd7ea0bf9b176 | <ide><path>src/Illuminate/Contracts/Queue/Queue.php
<ide> public function later($delay, $job, $data = '', $queue = null);
<ide> /**
<ide> * Push a new job onto the queue.
<ide> *
<del> * @param stirng $queue
<add> * @param string $queue
<ide> * @param string $job
<ide> * @param mixed $data
<ide> * @return mixed
<ide><path>src/Illuminate/Queue/Queue.php
<ide> abstract class Queue {
<ide> /**
<ide> * Push a new job onto the queue.
<ide> *
<del> * @param stirng $queue
<add> * @param string $queue
<ide> * @param string $job
<ide> * @param mixed $data
<ide> * @return mixed | 2 |
Ruby | Ruby | fix broken link | 227975110317b144988b0c5656b338292462f863 | <ide><path>Library/Homebrew/formula.rb
<ide> # @see SharedEnvExtension
<ide> # @see FileUtils
<ide> # @see Pathname
<del># @see http://www.rubydoc.info/github/Homebrew/brew/file/docs/Formula-Cookbook.md Formula Cookbook
<add># @see https://github.com/Homebrew/brew/blob/master/docs/Formula-Cookbook.md Formula Cookbook
<ide> # @see https://github.com/styleguide/ruby Ruby Style Guide
<ide> #
<ide> # <pre>class Wget < Formula | 1 |
Python | Python | add mask support to new recurrent layers | 5b6f56a0407bd73fe4b0193191885113da1e3e5d | <ide><path>keras/layers/recurrent.py
<ide> def get_config(self):
<ide>
<ide>
<ide>
<del>class JZS1(Layer):
<add>class JZS1(Recurrent):
<ide> '''
<ide> Evolved recurrent neural network architectures from the evaluation of thousands
<ide> of models, serving as alternatives to LSTMs and GRUs. See Jozefowicz et al. 2015.
<ide> def _step(self,
<ide> xz_t, xr_t, xh_t, mask_tm1,
<ide> h_tm1,
<ide> u_r, u_h):
<add> h_mask_tm1 = mask_tm1 * h_tm1
<ide> z = self.inner_activation(xz_t)
<del> r = self.inner_activation(xr_t + T.dot(h_tm1, u_r))
<del> hh_t = self.activation(xh_t + T.dot(r * h_tm1, u_h))
<del> h_t = hh_t * z + h_tm1 * (1 - z)
<add> r = self.inner_activation(xr_t + T.dot(h_mask_tm1, u_r))
<add> hh_t = self.activation(xh_t + T.dot(r * h_mask_tm1, u_h))
<add> h_t = hh_t * z + h_mask_tm1 * (1 - z)
<ide> return h_t
<ide>
<ide> def get_output(self, train):
<ide> X = self.get_input(train)
<del> X = X.dimshuffle((1, 0, 2))
<ide> padded_mask = self.get_padded_shuffled_mask(train, X, pad=1)
<add> X = X.dimshuffle((1, 0, 2))
<ide>
<ide> x_z = T.dot(X, self.W_z) + self.b_z
<ide> x_r = T.dot(X, self.W_r) + self.b_r
<ide> x_h = T.tanh(T.dot(X, self.Pmat)) + self.b_h
<ide> outputs, updates = theano.scan(
<ide> self._step,
<del> sequences=[x_z, x_r, x_h, padded_mask],
<add> sequences=[x_z, x_r, x_h, padded_mask],
<ide> outputs_info=T.unbroadcast(alloc_zeros_matrix(X.shape[1], self.output_dim), 1),
<ide> non_sequences=[self.U_r, self.U_h],
<ide> truncate_gradient=self.truncate_gradient
<ide> def get_config(self):
<ide>
<ide>
<ide>
<del>class JZS2(Layer):
<add>class JZS2(Recurrent):
<ide> '''
<ide> Evolved recurrent neural network architectures from the evaluation of thousands
<ide> of models, serving as alternatives to LSTMs and GRUs. See Jozefowicz et al. 2015.
<ide> def __init__(self, input_dim, output_dim=128,
<ide> self.set_weights(weights)
<ide>
<ide> def _step(self,
<del> xz_t, xr_t, xh_t,
<add> xz_t, xr_t, xh_t, mask_tm1,
<ide> h_tm1,
<ide> u_z, u_r, u_h):
<del> z = self.inner_activation(xz_t + T.dot(h_tm1, u_z))
<del> r = self.inner_activation(xr_t + T.dot(h_tm1, u_r))
<del> hh_t = self.activation(xh_t + T.dot(r * h_tm1, u_h))
<del> h_t = hh_t * z + h_tm1 * (1 - z)
<add> h_mask_tm1 = mask_tm1 * h_tm1
<add> z = self.inner_activation(xz_t + T.dot(h_mask_tm1, u_z))
<add> r = self.inner_activation(xr_t + T.dot(h_mask_tm1, u_r))
<add> hh_t = self.activation(xh_t + T.dot(r * h_mask_tm1, u_h))
<add> h_t = hh_t * z + h_mask_tm1 * (1 - z)
<ide> return h_t
<ide>
<ide> def get_output(self, train):
<del> X = self.get_input(train)
<add> X = self.get_input(train)
<add> padded_mask = self.get_padded_shuffled_mask(train, X, pad=1)
<ide> X = X.dimshuffle((1, 0, 2))
<ide>
<ide> x_z = T.dot(X, self.W_z) + self.b_z
<ide> x_r = T.dot(X, self.Pmat) + self.b_r
<ide> x_h = T.dot(X, self.W_h) + self.b_h
<ide> outputs, updates = theano.scan(
<ide> self._step,
<del> sequences=[x_z, x_r, x_h],
<add> sequences=[x_z, x_r, x_h, padded_mask],
<ide> outputs_info=T.unbroadcast(alloc_zeros_matrix(X.shape[1], self.output_dim), 1),
<ide> non_sequences=[self.U_z, self.U_r, self.U_h],
<ide> truncate_gradient=self.truncate_gradient
<ide> def get_config(self):
<ide>
<ide>
<ide>
<del>class JZS3(Layer):
<add>class JZS3(Recurrent):
<ide> '''
<ide> Evolved recurrent neural network architectures from the evaluation of thousands
<ide> of models, serving as alternatives to LSTMs and GRUs. See Jozefowicz et al. 2015.
<ide> def __init__(self, input_dim, output_dim=128,
<ide> self.set_weights(weights)
<ide>
<ide> def _step(self,
<del> xz_t, xr_t, xh_t,
<add> xz_t, xr_t, xh_t, mask_tm1,
<ide> h_tm1,
<ide> u_z, u_r, u_h):
<del> z = self.inner_activation(xz_t + T.dot(T.tanh(h_tm1), u_z))
<del> r = self.inner_activation(xr_t + T.dot(h_tm1, u_r))
<del> hh_t = self.activation(xh_t + T.dot(r * h_tm1, u_h))
<del> h_t = hh_t * z + h_tm1 * (1 - z)
<add> h_mask_tm1 = mask_tm1 * h_tm1
<add> z = self.inner_activation(xz_t + T.dot(T.tanh(h_mask_tm1), u_z))
<add> r = self.inner_activation(xr_t + T.dot(h_mask_tm1, u_r))
<add> hh_t = self.activation(xh_t + T.dot(r * h_mask_tm1, u_h))
<add> h_t = hh_t * z + h_mask_tm1 * (1 - z)
<ide> return h_t
<ide>
<ide> def get_output(self, train):
<del> X = self.get_input(train)
<add> X = self.get_input(train)
<add> padded_mask = self.get_padded_shuffled_mask(train, X, pad=1)
<ide> X = X.dimshuffle((1, 0, 2))
<ide>
<ide> x_z = T.dot(X, self.W_z) + self.b_z
<ide> x_r = T.dot(X, self.W_r) + self.b_r
<ide> x_h = T.dot(X, self.W_h) + self.b_h
<ide> outputs, updates = theano.scan(
<ide> self._step,
<del> sequences=[x_z, x_r, x_h],
<add> sequences=[x_z, x_r, x_h, padded_mask],
<ide> outputs_info=T.unbroadcast(alloc_zeros_matrix(X.shape[1], self.output_dim), 1),
<ide> non_sequences=[self.U_z, self.U_r, self.U_h],
<ide> truncate_gradient=self.truncate_gradient | 1 |
Javascript | Javascript | fix borderexample crash on out of tree platforms | ffcaef64e4041f0ebbbede979af0ae816ceee571 | <ide><path>packages/rn-tester/js/examples/Border/BorderExample.js
<ide> const styles = StyleSheet.create({
<ide> },
<ide> border15: {
<ide> borderWidth: 10,
<del> borderColor: PlatformColor(
<del> 'systemGray4',
<del> '@android:color/holo_orange_dark',
<del> ),
<add> borderColor: Platform.select({
<add> ios: PlatformColor('systemGray4'),
<add> android: PlatformColor('@android:color/holo_orange_dark'),
<add> windows: PlatformColor('SystemAccentColorDark1'),
<add> default: 'black',
<add> }),
<ide> },
<ide> border16: {
<ide> borderWidth: 10, | 1 |
Javascript | Javascript | run tests in the examples build script | 8cbd405e90f9abc58d45c9cad9adc018daf62bf1 | <ide><path>examples/buildAll.js
<ide> var exampleDirs = fs.readdirSync(__dirname).filter((file) => {
<ide> // Ordering is important here. `npm install` must come first.
<ide> var cmdArgs = [
<ide> { cmd: 'npm', args: ['install'] },
<del> { cmd: 'webpack', args: ['index.js'] }
<add> { cmd: 'webpack', args: ['index.js'] },
<add> { cmd: 'npm', args: ['test'] }
<ide> ];
<ide>
<ide> for (let dir of exampleDirs) { | 1 |
Text | Text | replace spurious whitespace | f82f68a2efd4a89514fbc9f41ed943f5c5693409 | <ide><path>guides/source/classic_to_zeitwerk_howto.md
<ide> Rails.autoloaders.each do |autoloader|
<ide> end
<ide> ```
<ide>
<del>With that in place, the check passes :
<add>With that in place, the check passes!
<ide>
<ide> ```
<ide> % bin/rails zeitwerk:check | 1 |
Python | Python | fix conll converter option | 4188beda871b1e40eb8d02b8a787b6878c89717e | <ide><path>spacy/cli/convert.py
<ide> CONVERTERS = {
<ide> "conllubio": conllu_to_docs,
<ide> "conllu": conllu_to_docs,
<del> "conll": conllu_to_docs,
<add> "conll": conll_ner_to_docs,
<ide> "ner": conll_ner_to_docs,
<ide> "iob": iob_to_docs,
<ide> "json": json_to_docs, | 1 |
Javascript | Javascript | allow strings for ports on net.server.listen | d5214b3627fb317349736757263c86804a057149 | <ide><path>lib/net.js
<ide> function doConnect (socket, port, host) {
<ide> };
<ide> }
<ide>
<del>function isPort (x) { return parseInt(x) >= 0; }
<add>function toPort (x) { return (x = Number(x)) >= 0 ? x : false }
<ide>
<ide>
<ide> // var stream = new Stream();
<ide> Stream.prototype.connect = function () {
<ide>
<ide> self._connecting = true; // set false in doConnect
<ide>
<del> if (isPort(arguments[0])) {
<add> var port = toPort(arguments[0])
<add> if (port === false) {
<add> // UNIX
<add> self.fd = socket('unix');
<add> self.type = 'unix';
<add>
<add> setImplmentationMethods(this);
<add> doConnect(self, arguments[0]);
<add> } else {
<ide> // TCP
<del> var port = arguments[0];
<ide> dns.lookup(arguments[1], function (err, ip, addressType) {
<ide> if (err) {
<ide> self.emit('error', err);
<ide> Stream.prototype.connect = function () {
<ide> doConnect(self, port, ip);
<ide> }
<ide> });
<del> } else {
<del> // UNIX
<del> self.fd = socket('unix');
<del> self.type = 'unix';
<del>
<del> setImplmentationMethods(this);
<del> doConnect(self, arguments[0]);
<ide> }
<ide> };
<ide>
<ide> Server.prototype.listen = function () {
<ide> self.addListener('listening', lastArg);
<ide> }
<ide>
<del> if (!isPort(arguments[0])) {
<add> var port = toPort(arguments[0])
<add> if (port === false) {
<ide> // the first argument specifies a path
<ide> self.fd = socket('unix');
<ide> self.type = 'unix';
<ide> Server.prototype.listen = function () {
<ide> // The port can be found with server.address()
<ide> self.type = 'tcp4';
<ide> self.fd = socket(self.type);
<del> bind(self.fd, arguments[0]);
<add> bind(self.fd, port);
<ide> process.nextTick(function () {
<ide> self._doListen();
<ide> });
<ide> } else {
<ide> // the first argument is the port, the second an IP
<del> var port = arguments[0];
<ide> dns.lookup(arguments[1], function (err, ip, addressType) {
<ide> if (err) {
<ide> self.emit('error', err); | 1 |
PHP | PHP | remove unused use statements | 21b01491d7a551187f4b27b59e1cc3c7cb70e6c9 | <ide><path>tests/TestCase/TestSuite/TestFixtureTest.php
<ide> use Cake\Core\Configure;
<ide> use Cake\Datasource\ConnectionManager;
<ide> use Cake\Log\Log;
<del>use Cake\Model\Model;
<ide> use Cake\TestSuite\Fixture\TestFixture;
<ide> use Cake\TestSuite\TestCase;
<ide> use Cake\Utility\ClassRegistry;
<ide><path>tests/TestCase/View/Helper/HtmlHelperTest.php
<ide> use Cake\Core\Plugin;
<ide> use Cake\Filesystem\File;
<ide> use Cake\Filesystem\Folder;
<del>use Cake\Model\Model;
<ide> use Cake\Network\Request;
<ide> use Cake\Routing\Router;
<ide> use Cake\TestSuite\TestCase; | 2 |
PHP | PHP | reduce number of mocks used in hasmany tests | 1d9f83c4f0a270ddf68c5b444a456135876ea847 | <ide><path>tests/TestCase/ORM/Association/BelongsToTest.php
<ide> public function testAttachToNoFields()
<ide> public function testAttachToMultiPrimaryKey()
<ide> {
<ide> $this->company->primaryKey(['id', 'tenant_id']);
<del> // $query = $this->getMock('\Cake\ORM\Query', ['join', 'select'], [null, null]);
<ide> $config = [
<ide> 'foreignKey' => ['company_id', 'company_tenant_id'],
<ide> 'sourceTable' => $this->client, | 1 |
Python | Python | add support for customdata | bc0217ec8199852082e265d24b5e29c7e1da8d26 | <ide><path>libcloud/compute/drivers/azure_arm.py
<ide> http://azure.microsoft.com/en-us/services/virtual-machines/
<ide> """
<ide>
<add>import base64
<ide> import binascii
<ide> import os
<ide> import time
<ide> def create_node(self,
<ide> ex_network=None,
<ide> ex_subnet=None,
<ide> ex_nic=None,
<del> ex_tags={}):
<add> ex_tags={},
<add> ex_customdata=""):
<ide> """Create a new node instance. This instance will be started
<ide> automatically.
<ide>
<ide> def create_node(self,
<ide> node on the given network) or `ex_nic` (to supply the NIC explicitly).
<ide> :type ex_network: ``str``
<ide>
<del> :param ex_network: If ex_network is provided, the subnet of the
<add> :param ex_subnet: If ex_network is provided, the subnet of the
<ide> virtual network the node will be attached to. Optional, default
<ide> is the "default" subnet.
<ide> :type ex_subnet: ``str``
<ide> def create_node(self,
<ide> :param ex_tags: Optional tags to associate with this node.
<ide> :type ex_tags: ``dict``
<ide>
<add> :param ex_customdata: Custom data that will be placed in the file /var/lib/waagent/CustomData
<add> https://azure.microsoft.com/en-us/documentation/articles/virtual-machines-how-to-inject-custom-data/
<add> :type ex_customdata: ``str``
<add>
<ide> :return: The newly created node.
<ide> :rtype: :class:`.Node`
<ide>
<ide> def create_node(self,
<ide> },
<ide> "storageProfile": storageProfile,
<ide> "osProfile": {
<del> "computerName": name
<add> "computerName": name,
<add> "customData": base64.b64encode(ex_customdata)
<ide> },
<ide> "networkProfile": {
<ide> "networkInterfaces": [ | 1 |
Javascript | Javascript | add vector-effect to svg whitelist | 9268c1a7101e10d812d200eefacbf80bb6226ec0 | <ide><path>src/renderers/dom/shared/SVGDOMPropertyConfig.js
<ide> var ATTRS = {
<ide> vIdeographic: 'v-ideographic',
<ide> vMathematical: 'v-mathematical',
<ide> values: 0,
<add> vectorEffect: 'vector-effect',
<ide> version: 0,
<ide> vertAdvY: 'vert-adv-y',
<ide> vertOriginX: 'vert-origin-x', | 1 |
Ruby | Ruby | add new line after donate message | da4bf679def7fee08f3856c35130a90ed8ea240a | <ide><path>Library/Homebrew/cmd/update-report.rb
<ide> def output_update_report
<ide>
<ide> if Settings.read("donationmessage") != "true" && !args.quiet?
<ide> ohai "Homebrew is run entirely by unpaid volunteers. Please consider donating:"
<del> puts " #{Formatter.url("https://github.com/Homebrew/brew#donations")}\n"
<add> puts " #{Formatter.url("https://github.com/Homebrew/brew#donations")}\n\n"
<ide>
<ide> # Consider the message possibly missed if not a TTY.
<ide> Settings.write "donationmessage", true if $stdout.tty? | 1 |
Javascript | Javascript | fix some typos in comments and variable names | eaffcfa9206645edfc8cce2e2382071d75cccdd7 | <ide><path>web/debugger.js
<ide> var FontInspector = (function FontInspectorClosure() {
<ide> }
<ide> }
<ide> return {
<del> // Poperties/functions needed by PDFBug.
<add> // Properties/functions needed by PDFBug.
<ide> id: 'FontInspector',
<ide> name: 'Font Inspector',
<ide> panel: null,
<ide> var StepperManager = (function StepperManagerClosure() {
<ide> var stepperChooser = null;
<ide> var breakPoints = {};
<ide> return {
<del> // Poperties/functions needed by PDFBug.
<add> // Properties/functions needed by PDFBug.
<ide> id: 'Stepper',
<ide> name: 'Stepper',
<ide> panel: null,
<ide> var StepperManager = (function StepperManagerClosure() {
<ide> var Stepper = (function StepperClosure() {
<ide> function Stepper(panel, pageIndex, initialBreakPoints) {
<ide> this.panel = panel;
<del> this.len;
<add> this.len = 0;
<ide> this.breakPoint = 0;
<ide> this.nextBreakPoint = null;
<ide> this.pageIndex = pageIndex;
<ide> var Stepper = (function StepperClosure() {
<ide> headerRow.appendChild(c('th', 'fn'));
<ide> headerRow.appendChild(c('th', 'args'));
<ide>
<add> var self = this;
<ide> for (var i = 0; i < IRQueue.fnArray.length; i++) {
<ide> var line = c('tr');
<ide> line.className = 'line';
<ide> var Stepper = (function StepperClosure() {
<ide> cbox.type = 'checkbox';
<ide> cbox.className = 'points';
<ide> cbox.checked = checked;
<del> var self = this;
<ide> cbox.onclick = (function(x) {
<ide> return function() {
<ide> if (this.checked)
<ide> var Stepper = (function StepperClosure() {
<ide> callback();
<ide> break;
<ide> }
<del> }
<add> };
<ide> dom.addEventListener('keydown', listener, false);
<ide> self.goTo(idx);
<ide> },
<ide> var Stats = (function Stats() {
<ide> return false;
<ide> }
<ide> return {
<del> // Poperties/functions needed by PDFBug.
<add> // Properties/functions needed by PDFBug.
<ide> id: 'Stats',
<ide> name: 'Stats',
<ide> panel: null,
<ide> var PDFBug = (function PDFBugClosure() {
<ide>
<ide> // Initialize all the debugging tools.
<ide> var tools = this.tools;
<add> var self = this;
<ide> for (var i = 0; i < tools.length; ++i) {
<ide> var tool = tools[i];
<ide> var panel = document.createElement('div');
<ide> var panelButton = document.createElement('button');
<ide> panelButton.textContent = tool.name;
<del> var self = this;
<ide> panelButton.addEventListener('click', (function(selected) {
<ide> return function(event) {
<ide> event.preventDefault();
<ide><path>web/viewer.js
<ide> var PDFView = {
<ide> // }
<ide> // );
<ide> // },
<del>// noData // Error ocurred try downloading with just the url.
<add>// noData // Error occurred try downloading with just the url.
<ide> // );
<ide> //#endif
<ide> },
<ide> var PDFView = {
<ide> search: function pdfViewStartSearch() {
<ide> // Limit this function to run every <SEARCH_TIMEOUT>ms.
<ide> var SEARCH_TIMEOUT = 250;
<del> var lastSeach = this.lastSearch;
<add> var lastSearch = this.lastSearch;
<ide> var now = Date.now();
<del> if (lastSeach && (now - lastSeach) < SEARCH_TIMEOUT) {
<add> if (lastSearch && (now - lastSearch) < SEARCH_TIMEOUT) {
<ide> if (!this.searchTimer) {
<ide> this.searchTimer = setTimeout(function resumeSearch() {
<ide> PDFView.search();
<ide> },
<del> SEARCH_TIMEOUT - (now - lastSeach)
<add> SEARCH_TIMEOUT - (now - lastSearch)
<ide> );
<ide> }
<ide> return; | 2 |
Python | Python | use initialized memory for count_nonzero benchmark | 6a4858cc1b416bbff014d520a2725cbc25e7d7c4 | <ide><path>benchmarks/benchmarks/bench_core.py
<ide> class CountNonzero(Benchmark):
<ide> ]
<ide>
<ide> def setup(self, numaxes, size, dtype):
<del> self.x = np.empty(shape=(
<del> numaxes, size), dtype=dtype)
<add> self.x = np.arange(numaxes * size).reshape(numaxes, size)
<add> self.x = (self.x % 3).astype(dtype)
<ide>
<ide> def time_count_nonzero(self, numaxes, size, dtype):
<ide> np.count_nonzero(self.x) | 1 |
Ruby | Ruby | update markdown renderer to be more flexible | 0867fcdb5a0d6b38a6326914984ad9d02c52dd0e | <ide><path>guides/rails_guides/markdown.rb
<ide> def initialize(view, layout)
<ide> @view = view
<ide> @layout = layout
<ide> @index_counter = Hash.new(0)
<add> @raw_header = ''
<ide> end
<ide>
<ide> def render(body)
<del> @raw_header, _, @raw_body = body.partition(/^\-{40,}$/).map(&:strip)
<add> @raw_body = body
<add> extract_raw_header_and_body
<ide> generate_header
<ide> generate_title
<ide> generate_body
<ide> def engine
<ide> })
<ide> end
<ide>
<add> def extract_raw_header_and_body
<add> if @raw_body =~ /^\-{40,}$/
<add> @raw_header, _, @raw_body = @raw_body.partition(/^\-{40,}$/).map(&:strip)
<add> end
<add> end
<add>
<ide> def generate_body
<ide> @body = engine.render(@raw_body)
<ide> end
<ide> def generate_header
<ide>
<ide> def generate_structure
<ide> @raw_index = ''
<del> @body = Nokogiri::HTML(@body).tap do |doc|
<del> hierarchy = []
<del>
<del> doc.at('body').children.each do |node|
<del> if node.name =~ /^h[3-6]$/
<del> case node.name
<del> when 'h3'
<del> hierarchy = [node]
<del> node[:id] = dom_id(hierarchy)
<del> @raw_index += "1. [#{node.text}](##{node[:id]})\n"
<del> when 'h4'
<del> hierarchy = hierarchy[0, 1] + [node]
<del> node[:id] = dom_id(hierarchy)
<del> @raw_index += " * [#{node.text}](##{node[:id]})\n"
<del> when 'h5'
<del> hierarchy = hierarchy[0, 2] + [node]
<del> node[:id] = dom_id(hierarchy)
<del> when 'h6'
<del> hierarchy = hierarchy[0, 3] + [node]
<del> node[:id] = dom_id(hierarchy)
<del> end
<add> if @body.present?
<add> @body = Nokogiri::HTML(@body).tap do |doc|
<add> hierarchy = []
<add>
<add> doc.at('body').children.each do |node|
<add> if node.name =~ /^h[3-6]$/
<add> case node.name
<add> when 'h3'
<add> hierarchy = [node]
<add> node[:id] = dom_id(hierarchy)
<add> @raw_index += "1. [#{node.text}](##{node[:id]})\n"
<add> when 'h4'
<add> hierarchy = hierarchy[0, 1] + [node]
<add> node[:id] = dom_id(hierarchy)
<add> @raw_index += " * [#{node.text}](##{node[:id]})\n"
<add> when 'h5'
<add> hierarchy = hierarchy[0, 2] + [node]
<add> node[:id] = dom_id(hierarchy)
<add> when 'h6'
<add> hierarchy = hierarchy[0, 3] + [node]
<add> node[:id] = dom_id(hierarchy)
<add> end
<ide>
<del> node.inner_html = "#{node_index(hierarchy)} #{node.text}"
<add> node.inner_html = "#{node_index(hierarchy)} #{node.text}"
<add> end
<ide> end
<del> end
<del> end.to_html
<add> end.to_html
<add> end
<ide> end
<ide>
<ide> def generate_index
<del> @index = Nokogiri::HTML(engine.render(@raw_index)).tap do |doc|
<del> doc.at('ol')[:class] = 'chapters'
<del> end.to_html
<del>
<del> @index = <<-INDEX.html_safe
<del> <div id="subCol">
<del> <h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
<del> #{@index}
<del> </div>
<del> INDEX
<add> if @raw_index.present?
<add> @index = Nokogiri::HTML(engine.render(@raw_index)).tap do |doc|
<add> doc.at('ol')[:class] = 'chapters'
<add> end.to_html
<add>
<add> @index = <<-INDEX.html_safe
<add> <div id="subCol">
<add> <h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
<add> #{@index}
<add> </div>
<add> INDEX
<add> end
<ide> end
<ide>
<ide> def generate_title
<del> @title = "Ruby on Rails Guides: #{Nokogiri::HTML(@header).at(:h2).text}".html_safe
<add> if heading = Nokogiri::HTML(@header).at(:h2)
<add> @title = "Ruby on Rails Guides: #{heading.text}".html_safe
<add> else
<add> @title = "Ruby on Rails Guides"
<add> end
<ide> end
<ide>
<ide> def node_index(hierarchy)
<ide> def node_index(hierarchy)
<ide> def render_page
<ide> @view.content_for(:header_section) { @header }
<ide> @view.content_for(:page_title) { @title }
<del> @view.content_for(:index_section) { @index.html_safe }
<add> @view.content_for(:index_section) { @index }
<ide> @view.render(:layout => @layout, :text => @body)
<ide> end
<ide> end | 1 |
Text | Text | add 2.8.0-beta.4 to changelog.md | 518669ed061f2809737e359f86458447a1c55b13 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### 2.8.0-beta.4 (August 29, 2016)
<add>
<add>- [#14123](https://github.com/emberjs/ember.js/pull/14123) [BUGFIX] Avoid rerendering outlet state during router destruction.
<add>- [#14077](https://github.com/emberjs/ember.js/pull/14077) [BUGFIX] Update route-recognizer.
<add>- [#14087](https://github.com/emberjs/ember.js/pull/14087) [BUGFIX] Check that route handler exists before triggering actions.
<add>- [#14106](https://github.com/emberjs/ember.js/pull/14106) [BUGFIX] Avoid assertion when `id=` is provided to tagless components.
<add>- [#14110](https://github.com/emberjs/ember.js/pull/14110) [BUGFIX] Fix issues with revalidation during teardown.
<add>- [#14117](https://github.com/emberjs/ember.js/pull/14117) [BUGFIX] Call ArrayProxy's content change hooks
<add>- [#14135](https://github.com/emberjs/ember.js/pull/14135) [BUGFIX] Fix issues around Engine setup and teardown.
<add>- [#14140](https://github.com/emberjs/ember.js/pull/14140) [BUGFIX] Ensure component injections happen in engine instances.
<add>
<add>
<ide> ### 2.8.0-beta.3 (August 15, 2016)
<ide>
<ide> - [#14009](https://github.com/emberjs/ember.js/pull/14009) [BUGFIX] Fix usage of `role` when used in `attributeBindings`. | 1 |
Python | Python | add a predict method for sentence_prediction task | ad1661831dda900e457f3beb448049c358f8b175 | <ide><path>official/nlp/tasks/sentence_prediction.py
<ide> # limitations under the License.
<ide> # ==============================================================================
<ide> """Sentence prediction (classification) task."""
<add>from typing import List, Union
<add>
<ide> from absl import logging
<ide> import dataclasses
<ide> import numpy as np
<add>import orbit
<ide> from scipy import stats
<ide> from sklearn import metrics as sklearn_metrics
<ide> import tensorflow as tf
<ide> def initialize(self, model):
<ide> status.expect_partial().assert_existing_objects_matched()
<ide> logging.info('Finished loading pretrained checkpoint from %s',
<ide> ckpt_dir_or_file)
<add>
<add>
<add>def predict(task: SentencePredictionTask, params: cfg.DataConfig,
<add> model: tf.keras.Model) -> List[Union[int, float]]:
<add> """Predicts on the input data.
<add>
<add> Args:
<add> task: A `SentencePredictionTask` object.
<add> params: A `cfg.DataConfig` object.
<add> model: A keras.Model.
<add>
<add> Returns:
<add> A list of predictions with length of `num_examples`. For regression task,
<add> each element in the list is the predicted score; for classification task,
<add> each element is the predicted class id.
<add> """
<add> is_regression = task.task_config.model.num_classes == 1
<add>
<add> @tf.function
<add> def predict_step(iterator):
<add> """Predicts on distributed devices."""
<add>
<add> def _replicated_step(inputs):
<add> """Replicated prediction calculation."""
<add> x, _ = inputs
<add> outputs = task.inference_step(x, model)
<add> if is_regression:
<add> return outputs
<add> else:
<add> return tf.argmax(outputs, axis=-1)
<add>
<add> outputs = tf.distribute.get_strategy().run(
<add> _replicated_step, args=(next(iterator),))
<add> return tf.nest.map_structure(
<add> tf.distribute.get_strategy().experimental_local_results, outputs)
<add>
<add> def reduce_fn(state, outputs):
<add> """Concatenates model's outputs."""
<add> for per_replica_batch_predictions in outputs:
<add> state.extend(per_replica_batch_predictions)
<add> return state
<add>
<add> loop_fn = orbit.utils.create_loop_fn(predict_step)
<add> dataset = orbit.utils.make_distributed_dataset(tf.distribute.get_strategy(),
<add> task.build_inputs, params)
<add> # Set `num_steps` to -1 to exhaust the dataset.
<add> predictions = loop_fn(
<add> iter(dataset), num_steps=-1, state=[], reduce_fn=reduce_fn)
<add> return predictions
<ide><path>official/nlp/tasks/sentence_prediction_test.py
<ide> import os
<ide>
<ide> from absl.testing import parameterized
<add>import numpy as np
<ide> import tensorflow as tf
<ide>
<ide> from official.nlp.bert import configs
<ide> from official.nlp.tasks import sentence_prediction
<ide>
<ide>
<add>def _create_fake_dataset(output_path, seq_length, num_classes, num_examples):
<add> """Creates a fake dataset."""
<add> writer = tf.io.TFRecordWriter(output_path)
<add>
<add> def create_int_feature(values):
<add> return tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))
<add>
<add> def create_float_feature(values):
<add> return tf.train.Feature(float_list=tf.train.FloatList(value=list(values)))
<add>
<add> for _ in range(num_examples):
<add> features = {}
<add> input_ids = np.random.randint(100, size=(seq_length))
<add> features["input_ids"] = create_int_feature(input_ids)
<add> features["input_mask"] = create_int_feature(np.ones_like(input_ids))
<add> features["segment_ids"] = create_int_feature(np.ones_like(input_ids))
<add> features["segment_ids"] = create_int_feature(np.ones_like(input_ids))
<add>
<add> if num_classes == 1:
<add> features["label_ids"] = create_float_feature([np.random.random()])
<add> else:
<add> features["label_ids"] = create_int_feature(
<add> [np.random.random_integers(0, num_classes - 1, size=())])
<add>
<add> tf_example = tf.train.Example(features=tf.train.Features(feature=features))
<add> writer.write(tf_example.SerializeToString())
<add> writer.close()
<add>
<add>
<ide> class SentencePredictionTaskTest(tf.test.TestCase, parameterized.TestCase):
<ide>
<ide> def setUp(self):
<ide> def test_task_with_hub(self):
<ide> train_data=self._train_data_config)
<ide> self._run_task(config)
<ide>
<add> @parameterized.named_parameters(("classification", 5), ("regression", 1))
<add> def test_prediction(self, num_classes):
<add> task_config = sentence_prediction.SentencePredictionConfig(
<add> model=self.get_model_config(num_classes=num_classes),
<add> train_data=self._train_data_config)
<add> task = sentence_prediction.SentencePredictionTask(task_config)
<add> model = task.build_model()
<add>
<add> test_data_path = os.path.join(self.get_temp_dir(), "test.tf_record")
<add> seq_length = 16
<add> num_examples = 100
<add> _create_fake_dataset(
<add> test_data_path,
<add> seq_length=seq_length,
<add> num_classes=num_classes,
<add> num_examples=num_examples)
<add>
<add> test_data_config = (
<add> sentence_prediction_dataloader.SentencePredictionDataConfig(
<add> input_path=test_data_path,
<add> seq_length=seq_length,
<add> is_training=False,
<add> label_type="int" if num_classes > 1 else "float",
<add> global_batch_size=16,
<add> drop_remainder=False))
<add>
<add> predictions = sentence_prediction.predict(task, test_data_config, model)
<add> self.assertLen(predictions, num_examples)
<add>
<ide>
<ide> if __name__ == "__main__":
<ide> tf.test.main() | 2 |
Python | Python | fix doctest error with empty output | 316d1f4ec9e033b21062b8f2dcdddeef01d7a889 | <ide><path>numpy/testing/noseclasses.py
<ide> def configure(self, options, config):
<ide> self.doctest_tests = True
<ide> self.finder = NumpyDocTestFinder()
<ide> self.parser = doctest.DocTestParser()
<add> self.doctest_result_var = None # default in npd.Doctest
<ide> if self.enabled:
<ide> # Pull standard doctest out of plugin list; there's no reason to run
<ide> # both. In practice the Unplugger plugin above would cover us when
<ide> def loadTestsFromModule(self, module):
<ide>
<ide> yield NumpyDocTestCase(test,
<ide> optionflags=optionflags,
<del> checker=NumpyOutputChecker())
<add> checker=NumpyOutputChecker(),
<add> result_var = self.doctest_result_var)
<ide>
<ide>
<ide> # Add an afterContext method to nose.plugins.doctests.Doctest in order
<ide><path>numpy/testing/tests/test_doctesting.py
<ide> def check_whitespace_enabled():
<ide> 7
<ide> '''
<ide>
<add>def check_empty_output():
<add> """ Check that no output does not cause an error.
<add>
<add> This is related to nose bug 445; the numpy plugin changed the
<add> doctest-result-variable default and therefore hit this bug:
<add> http://code.google.com/p/python-nose/issues/detail?id=445
<add>
<add> >>> a = 10
<add> """
<add>
<add>def check_skip():
<add> """ Check skip directive
<add>
<add> The test below should not run
<add>
<add> >>> 1/0 #doctest: +SKIP
<add> """
<add>
<ide>
<ide> if __name__ == '__main__':
<ide> # Run tests outside numpy test rig | 2 |
Javascript | Javascript | reset renderstate when bailing out | a53f5cc22eab9617a1d5473e16ce872c7158edef | <ide><path>packages/react-reconciler/src/ReactFiberBeginWork.js
<ide> function beginWork(
<ide> const didSuspendBefore =
<ide> (current.effectTag & DidCapture) !== NoEffect;
<ide>
<del> const childExpirationTime = workInProgress.childExpirationTime;
<del> if (childExpirationTime < renderExpirationTime) {
<add> const hasChildWork =
<add> workInProgress.childExpirationTime >= renderExpirationTime;
<add>
<add> if (didSuspendBefore) {
<add> if (hasChildWork) {
<add> // If something was in fallback state last time, and we have all the
<add> // same children then we're still in progressive loading state.
<add> // Something might get unblocked by state updates or retries in the
<add> // tree which will affect the tail. So we need to use the normal
<add> // path to compute the correct tail.
<add> return updateSuspenseListComponent(
<add> current,
<add> workInProgress,
<add> renderExpirationTime,
<add> );
<add> }
<ide> // If none of the children had any work, that means that none of
<ide> // them got retried so they'll still be blocked in the same way
<ide> // as before. We can fast bail out.
<del> pushSuspenseContext(workInProgress, suspenseStackCursor.current);
<del> if (didSuspendBefore) {
<del> workInProgress.effectTag |= DidCapture;
<del> }
<del> return null;
<del> }
<del>
<del> if (didSuspendBefore) {
<del> // If something was in fallback state last time, and we have all the
<del> // same children then we're still in progressive loading state.
<del> // Something might get unblocked by state updates or retries in the
<del> // tree which will affect the tail. So we need to use the normal
<del> // path to compute the correct tail.
<del> return updateSuspenseListComponent(
<del> current,
<del> workInProgress,
<del> renderExpirationTime,
<del> );
<add> workInProgress.effectTag |= DidCapture;
<ide> }
<ide>
<ide> // If nothing suspended before and we're rendering the same children,
<ide> function beginWork(
<ide> renderState.tail = null;
<ide> }
<ide> pushSuspenseContext(workInProgress, suspenseStackCursor.current);
<del> break;
<add>
<add> if (hasChildWork) {
<add> break;
<add> } else {
<add> // If none of the children had any work, that means that none of
<add> // them got retried so they'll still be blocked in the same way
<add> // as before. We can fast bail out.
<add> return null;
<add> }
<ide> }
<ide> }
<ide> return bailoutOnAlreadyFinishedWork(
<ide><path>packages/react-reconciler/src/__tests__/ReactSuspenseList-test.internal.js
<ide> describe('ReactSuspenseList', () => {
<ide> </Fragment>,
<ide> );
<ide> });
<add>
<add> it('can do unrelated adjacent updates', async () => {
<add> let updateAdjacent;
<add> function Adjacent() {
<add> let [text, setText] = React.useState('-');
<add> updateAdjacent = setText;
<add> return <Text text={text} />;
<add> }
<add>
<add> function Foo() {
<add> return (
<add> <div>
<add> <SuspenseList revealOrder="forwards">
<add> <Text text="A" />
<add> <Text text="B" />
<add> </SuspenseList>
<add> <Adjacent />
<add> </div>
<add> );
<add> }
<add>
<add> ReactNoop.render(<Foo />);
<add>
<add> expect(Scheduler).toFlushAndYield(['A', 'B', '-']);
<add>
<add> expect(ReactNoop).toMatchRenderedOutput(
<add> <div>
<add> <span>A</span>
<add> <span>B</span>
<add> <span>-</span>
<add> </div>,
<add> );
<add>
<add> // Update the row adjacent to the list
<add> ReactNoop.act(() => updateAdjacent('C'));
<add>
<add> expect(Scheduler).toHaveYielded(['C']);
<add>
<add> expect(ReactNoop).toMatchRenderedOutput(
<add> <div>
<add> <span>A</span>
<add> <span>B</span>
<add> <span>C</span>
<add> </div>,
<add> );
<add> });
<ide> }); | 2 |
PHP | PHP | remove redundant import | 43e7a8755f88ebd4b22476f180724339bd73db4e | <ide><path>src/Error/ErrorTrap.php
<ide> namespace Cake\Error;
<ide>
<ide> use Cake\Core\InstanceConfigTrait;
<del>use Cake\Error\ErrorRendererInterface;
<ide> use Cake\Error\Renderer\ConsoleRenderer;
<ide> use Cake\Error\Renderer\HtmlRenderer;
<ide> use Closure; | 1 |
Text | Text | add distilbert to supported models | 50d1ce411f6aed961e0c214cf96025e20053cbc3 | <ide><path>examples/language-modeling/README.md
<ide>
<ide> Based on the script [`run_language_modeling.py`](https://github.com/huggingface/transformers/blob/master/examples/language-modeling/run_language_modeling.py).
<ide>
<del>Fine-tuning (or training from scratch) the library models for language modeling on a text dataset for GPT, GPT-2, BERT and RoBERTa (DistilBERT
<del>to be added soon). GPT and GPT-2 are fine-tuned using a causal language modeling (CLM) loss while BERT and RoBERTa
<add>Fine-tuning (or training from scratch) the library models for language modeling on a text dataset for GPT, GPT-2, BERT, DistilBERT and RoBERTa. GPT and GPT-2 are fine-tuned using a causal language modeling (CLM) loss while BERT, DistilBERT and RoBERTa
<ide> are fine-tuned using a masked language modeling (MLM) loss.
<ide>
<ide> Before running the following example, you should get a file that contains text on which the language model will be
<ide> python run_language_modeling.py \
<ide> This takes about half an hour to train on a single K80 GPU and about one minute for the evaluation to run. It reaches
<ide> a score of ~20 perplexity once fine-tuned on the dataset.
<ide>
<del>### RoBERTa/BERT and masked language modeling
<add>### RoBERTa/BERT/DistilBERT and masked language modeling
<ide>
<ide> The following example fine-tunes RoBERTa on WikiText-2. Here too, we're using the raw WikiText-2. The loss is different
<ide> as BERT/RoBERTa have a bidirectional mechanism; we're therefore using the same loss that was used during their | 1 |
PHP | PHP | fix code style | 73051cc50e28f83b3609a6bdbc774643e10ea43a | <ide><path>src/View/Helper/FormHelper.php
<ide> protected function _extractValidValueSources(array $sources): array
<ide> */
<ide> public function setValueSources($sources)
<ide> {
<del> $this->_valueSources = $this->_extractValidValueSources((array) $sources);
<add> $this->_valueSources = $this->_extractValidValueSources((array)$sources);
<ide>
<ide> return $this;
<ide> } | 1 |
PHP | PHP | update userfactory password in line with | 9db658d6d1dde21dfe243bbed9450f242858ec8c | <ide><path>database/factories/UserFactory.php
<ide> return [
<ide> 'name' => $faker->name,
<ide> 'email' => $faker->unique()->safeEmail,
<del> 'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
<add> 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
<ide> 'remember_token' => str_random(10),
<ide> ];
<ide> }); | 1 |
Python | Python | remove redundant argument to range(). | c2268794ab638dd1c4f85b67b582ceb08acfe3c1 | <ide><path>examples/conv_filter_visualization.py
<ide> def normalize(x):
<ide>
<ide>
<ide> kept_filters = []
<del>for filter_index in range(0, 200):
<add>for filter_index in range(200):
<ide> # we only scan through the first 200 filters,
<ide> # but there are actually 512 of them
<ide> print('Processing filter %d' % filter_index)
<ide><path>examples/image_ocr.py
<ide> def get_batch(self, index, size, train):
<ide> input_length = np.zeros([size, 1])
<ide> label_length = np.zeros([size, 1])
<ide> source_str = []
<del> for i in range(0, size):
<add> for i in range(size):
<ide> # Mix in some blank inputs. This seems to be important for
<ide> # achieving translational invariance
<ide> if train and i > size - 4:
<ide> def show_edit_distance(self, num):
<ide> word_batch = next(self.text_img_gen)[0]
<ide> num_proc = min(word_batch['the_input'].shape[0], num_left)
<ide> decoded_res = decode_batch(self.test_func, word_batch['the_input'][0:num_proc])
<del> for j in range(0, num_proc):
<add> for j in range(num_proc):
<ide> edit_dist = editdistance.eval(decoded_res[j], word_batch['source_str'][j])
<ide> mean_ed += float(edit_dist)
<ide> mean_norm_ed += float(edit_dist) / len(word_batch['source_str'][j])
<ide><path>keras/backend/cntk_backend.py
<ide> def dot(x, y):
<ide> y_shape = int_shape(y)
<ide> if len(y_shape) > 2:
<ide> permutation = [len(y_shape) - 2]
<del> permutation += list(range(0, len(y_shape) - 2))
<add> permutation += list(range(len(y_shape) - 2))
<ide> permutation += [len(y_shape) - 1]
<ide> y = C.transpose(y, perm=permutation)
<ide> return C.times(x, y, len(y_shape) - 1)
<ide><path>keras/backend/tensorflow_backend.py
<ide> def range_less_than(_, current_input):
<ide> initializer=init, parallel_iterations=1)
<ide> dense_mask = dense_mask[:, 0, :]
<ide>
<del> label_array = tf.reshape(tf.tile(tf.range(0, label_shape[1]), num_batches_tns),
<add> label_array = tf.reshape(tf.tile(tf.range(label_shape[1]), num_batches_tns),
<ide> label_shape)
<ide> label_ind = tf.boolean_mask(label_array, dense_mask)
<ide>
<del> batch_array = tf.transpose(tf.reshape(tf.tile(tf.range(0, label_shape[0]),
<add> batch_array = tf.transpose(tf.reshape(tf.tile(tf.range(label_shape[0]),
<ide> max_num_labels_tns), reverse(label_shape, 0)))
<ide> batch_ind = tf.boolean_mask(batch_array, dense_mask)
<ide> indices = tf.transpose(tf.reshape(concatenate([batch_ind, label_ind], axis=0), [2, -1]))
<ide><path>keras/engine/training.py
<ide> def _make_batches(size, batch_size):
<ide> """
<ide> num_batches = int(np.ceil(size / float(batch_size)))
<ide> return [(i * batch_size, min(size, (i + 1) * batch_size))
<del> for i in range(0, num_batches)]
<add> for i in range(num_batches)]
<ide>
<ide>
<ide> def _slice_arrays(arrays, start=None, stop=None):
<ide><path>tests/keras/backend/backend_test.py
<ide> def test_in_top_k(self):
<ide> targets = np.random.randint(num_classes, size=batch_size, dtype='int32')
<ide>
<ide> # (k == 0 or k > num_classes) does not raise an error but just return an unmeaningful tensor.
<del> for k in range(0, num_classes + 1):
<add> for k in range(num_classes + 1):
<ide> z_list = [b.eval(b.in_top_k(b.variable(predictions, dtype='float32'),
<ide> b.variable(targets, dtype='int32'), k))
<ide> for b in [KTH, KTF]] | 6 |
PHP | PHP | update the move logic | 07ffe2fcd8fb31225336f09bab7dc214f04854ac | <ide><path>lib/Cake/Console/Command/UpgradeShell.php
<ide> class UpgradeShell extends Shell {
<ide>
<ide> protected $_files = array();
<add>
<ide> protected $_paths = array();
<ide>
<add> protected $_map = array(
<add> 'Controller' => 'Controller',
<add> 'Component' => 'Controller/Component',
<add> 'Model' => 'Model',
<add> 'Behavior' => 'Model/Behavior',
<add> 'Datasource' => 'Model/Datasource',
<add> 'Dbo' => 'Model/Datasource/Database',
<add> 'View' => 'View',
<add> 'Helper' => 'View/Helper',
<add> 'Shell' => 'Console/Command',
<add> 'Task' => 'Console/Command/Task',
<add> 'Case' => 'tests/Case',
<add> 'Fixture' => 'tests/Fixture',
<add> );
<add>
<ide> /**
<ide> * Shell startup, prints info message about dry run.
<ide> *
<ide> function startup() {
<ide> if ($this->params['dry-run']) {
<ide> $this->out('<warning>Dry-run mode enabled!</warning>', 1, Shell::QUIET);
<ide> }
<add> if ($this->params['git'] && !is_dir('.git')) {
<add> $this->out('<warning>No git repository detected!</warning>', 1, Shell::QUIET);
<add> }
<ide> }
<ide>
<add>/**
<add> * Run all upgrade steps one at a time
<add> *
<add> * @access public
<add> * @return void
<add> */
<ide> function all() {
<ide> foreach($this->OptionParser->subcommands() as $command) {
<ide> $name = $command->name();
<ide> function all() {
<ide> }
<ide> }
<ide>
<add>/**
<add> * Move files and folders to their new homes
<add> *
<add> * Moves folders containing files which cannot necessarily be autodetected (libs and templates)
<add> * and then looks for all php files except vendors, and moves them to where Cake 2.0 expects
<add> * to find them.
<add> *
<add> * @access public
<add> * @return void
<add> */
<ide> function locations() {
<add> $cwd = getcwd();
<add>
<add> if (is_dir('plugins')) {
<add>
<add> $Folder = new Folder('plugins');
<add> list($plugins) = $Folder->read();
<add> foreach($plugins as $plugin) {
<add> chdir($cwd . DS . 'plugins' . DS . $plugin);
<add> $this->locations();
<add> }
<add> $this->_files = array();
<add> chdir($cwd);
<add> }
<add>
<ide> $moves = array(
<del> 'controllers' . DS . 'components' => 'Controller' . DS . 'Component',
<del> 'controllers' => 'Controller',
<ide> 'libs' => 'Lib',
<del> 'models' . DS . 'behaviors' => 'Model' . DS . 'Behavior',
<del> 'models' . DS . 'datasources' => 'Model' . DS . 'Datasource',
<del> 'models' => 'Model',
<del> 'tests' . DS . 'cases' => 'tests' . DS . 'Case',
<del> 'tests' . DS . 'fixtures' => 'tests' . DS . 'Fixture',
<ide> 'vendors' . DS . 'shells' . DS . 'templates' => 'Console' . DS . 'templates',
<del> 'vendors' . DS . 'shells' . DS . 'tasks' => 'Console' . DS . 'Command' . DS . 'Task',
<del> 'vendors' . DS . 'shells' => 'Console' . DS . 'Command',
<del> 'views' . DS . 'helpers' => 'View' . DS . 'Helper',
<del> 'views' => 'View'
<ide> );
<del>
<ide> foreach($moves as $old => $new) {
<ide> if (is_dir($old)) {
<ide> $this->out("Moving $old to $new");
<del> $Folder = new Folder($old);
<del> $Folder->move($new);
<add> if (!$this->params['dry-run']) {
<add> $Folder = new Folder($old);
<add> $Folder->move($new);
<add> }
<add> if ($this->params['git']) {
<add> exec('git mv -f ' . escapeshellarg($old) . ' ' . escapeshellarg($new));
<add> }
<ide> }
<ide> }
<add> $sourceDirs = array(
<add> '.' => array('recursive' => false),
<add> 'Console',
<add> 'Controller',
<add> 'controllers',
<add> 'Lib' => array('checkFolder' => false),
<add> 'Model',
<add> 'models',
<add> 'tests',
<add> 'View',
<add> 'views',
<add> 'vendors/shells',
<add> );
<ide>
<del> foreach($moves as $new) {
<del> $this->_filesMatchClass($new);
<add> $defaultOptions = array(
<add> 'recursive' => true,
<add> 'checkFolder' => true,
<add> );
<add> foreach($sourceDirs as $dir => $options) {
<add> if (is_numeric($dir)) {
<add> $dir = $options;
<add> $options = array();
<add> }
<add> $options = array_merge($defaultOptions, $options);
<add> $this->_movePhpFiles($dir, $options);
<ide> }
<ide> }
<ide>
<ide> public function configure() {
<ide> $this->_filesRegexpUpdate($patterns);
<ide> }
<ide>
<del> protected function _filesMatchClass($path) {
<add>/**
<add> * Move application php files to where they now should be
<add> *
<add> * Find all php files in the folder (honoring recursive) and determine where cake expects the file to be
<add> * If the file is not exactly where cake expects it - move it.
<add> *
<add> * @param mixed $path
<add> * @param mixed $options array(recursive, checkFolder)
<add> * @access protected
<add> * @return void
<add> */
<add> protected function _movePhpFiles($path, $options) {
<add> if (!is_dir($path)) {
<add> return;
<add> }
<add>
<ide> $paths = $this->_paths;
<del> $this->_paths = array($path);
<ide>
<add> $this->_paths = array($path);
<ide> $this->_files = array();
<del> $this->_findFiles('php');
<del> foreach ($this->_files as $file) {
<add> if ($options['recursive']) {
<add> $this->_findFiles('php');
<add> } else {
<add> $this->_files = scandir($path);
<add> foreach($this->_files as $i => $file) {
<add> if (strlen($file) < 5 || substr($file, -4) !== '.php') {
<add> unset($this->_files[$i]);
<add> }
<add> }
<add> }
<add>
<add> $cwd = getcwd();
<add> foreach ($this->_files as &$file) {
<add> $file = $cwd . DS . $file;
<add>
<ide> $contents = file_get_contents($file);
<del> preg_match('@class (\S*) @', $contents, $match);
<add> preg_match('@class (\S*) .*{@', $contents, $match);
<ide> if (!$match) {
<ide> continue;
<ide> }
<ide>
<ide> $class = $match[1];
<ide>
<del> $filename = basename($file);
<del> if ($filename === $class . '.php') {
<add> preg_match('@([A-Z][^A-Z]*)$@', $class, $match);
<add> if ($match) {
<add> $type = $match[1];
<add> } else {
<add> $type = 'unknown';
<add> }
<add>
<add> preg_match('@^.*[\\\/]plugins[\\\/](.*?)[\\\/]@', $file, $match);
<add> $base = $cwd . DS;
<add> $plugin = false;
<add> if ($match) {
<add> $base = $match[0];
<add> $plugin = $match[1];
<add> }
<add>
<add> if ($options['checkFolder'] && !empty($this->_map[$type])) {
<add> $folder = str_replace('/', DS, $this->_map[$type]);
<add> $new = $base . $folder . DS . $class . '.php';
<add> } else {
<add> $new = dirname($file) . DS . $class . '.php';
<add> }
<add>
<add> if ($file === $new) {
<ide> continue;
<ide> }
<ide>
<del> $new = dirname($file);
<del> if ($new) {
<del> $new .= DS;
<add> $dir = dirname($new);
<add> if (!is_dir($dir)) {
<add> new Folder($dir, true);
<ide> }
<del> $new .= $class . '.php';
<ide>
<ide> $this->out('Moving ' . $file . ' to ' . $new, 1, Shell::VERBOSE);
<del> rename($file, $new);
<add> if (!$this->params['dry-run']) {
<add> if ($this->params['git']) {
<add> exec('git mv -f ' . escapeshellarg($file) . ' ' . escapeshellarg($new));
<add> } else {
<add> rename($file, $new);
<add> }
<add> }
<ide> }
<ide>
<ide> $this->_paths = $paths;
<ide> function getOptionParser() {
<ide> 'help' => __('The extension(s) to search. A pipe delimited list, or a preg_match compatible subpattern'),
<ide> 'default' => 'php|ctp|thtml|inc|tpl'
<ide> ),
<add> 'git'=> array(
<add> 'help' => __('use git command for moving files around.'),
<add> 'default' => 0
<add> ),
<ide> 'dry-run'=> array(
<ide> 'short' => 'd',
<ide> 'help' => __('Dry run the update, no files will actually be modified.'), | 1 |
Javascript | Javascript | fix coding style in test/unit/font_spec.js | 6489a80dd0b9ea5cfb499b4a0559d08d3f5f9d29 | <ide><path>test/unit/font_spec.js
<ide> describe('font', function() {
<ide> var line = '';
<ide> for (var i = 0, ii = bytes.length; i < ii; ++i) {
<ide> var b = bytes[i].toString(16);
<del> if (b.length < 2)
<add> if (b.length < 2) {
<ide> b = '0' + b;
<add> }
<ide> line += b.toString(16);
<ide> }
<ide> return line;
<ide> describe('font', function() {
<ide> fontData.push(parseInt(hex, 16));
<ide> }
<ide> var bytes = new Uint8Array(fontData);
<del> fontData = {getBytes: function() { return bytes; }};
<add> fontData = {
<add> getBytes: function() {
<add> return bytes;
<add> }
<add> };
<ide>
<ide> function bytesToString(bytesArray) {
<ide> var str = '';
<del> for (var i = 0, ii = bytesArray.length; i < ii; i++)
<add> for (var i = 0, ii = bytesArray.length; i < ii; i++) {
<ide> str += String.fromCharCode(bytesArray[i]);
<add> }
<ide> return str;
<ide> }
<ide>
<ide> describe('font', function() {
<ide>
<ide> index = new CFFIndex();
<ide> var longName = [];
<del> for (var i = 0; i < 129; i++)
<add> for (var i = 0; i < 129; i++) {
<ide> longName.push(0);
<add> }
<ide> index.add(longName);
<ide> names = parser.parseNameIndex(index);
<ide> expect(names[0].length).toEqual(127); | 1 |
PHP | PHP | add constructor injection for the eventmanager | 5a90c3dec2056e45e0dd8763f0575ac0b97455fb | <ide><path>src/Http/ActionDispatcher.php
<ide> class ActionDispatcher
<ide> * Constructor
<ide> *
<ide> * @param \Cake\Http\ControllerFactory $factory A controller factory instance.
<add> * @param \Cake\Event\EventManager $eventManager An event manager if you want to inject one.
<ide> */
<del> public function __construct($factory = null)
<add> public function __construct($factory = null, $eventManager = null)
<ide> {
<add> if ($eventManager) {
<add> $this->eventManager($eventManager);
<add> }
<add>
<ide> // Compatibility with DispatcherFilters.
<ide> foreach (DispatcherFactory::filters() as $filter) {
<ide> $this->addFilter($filter);
<ide><path>tests/TestCase/Http/ActionDispatcherTest.php
<ide> public function tearDown()
<ide> DispatcherFactory::clear();
<ide> }
<ide>
<add> /**
<add> * Ensure the constructor args end up on the right protected properties.
<add> *
<add> * @return void
<add> */
<add> public function testConstructorArgs()
<add> {
<add> $factory = $this->getMock('Cake\Http\ControllerFactory');
<add> $events = $this->getMock('Cake\Event\EventManager');
<add> $dispatcher = new ActionDispatcher($factory, $events);
<add>
<add> $this->assertAttributeSame($events, '_eventManager', $dispatcher);
<add> $this->assertAttributeSame($factory, 'factory', $dispatcher);
<add> }
<add>
<ide> /**
<ide> * Ensure that filters connected to the DispatcherFactory are
<ide> * also applied | 2 |
PHP | PHP | remove unused use statements | cb5757acb1da0ba8d837213f1d182d508eddb9e8 | <ide><path>src/Illuminate/Encryption/Encrypter.php
<ide> namespace Illuminate\Encryption;
<ide>
<ide> use RuntimeException;
<del>use Illuminate\Support\Str;
<ide> use Illuminate\Contracts\Encryption\EncryptException;
<ide> use Illuminate\Contracts\Encryption\DecryptException;
<ide> use Illuminate\Contracts\Encryption\Encrypter as EncrypterContract;
<ide><path>src/Illuminate/Encryption/McryptEncrypter.php
<ide> namespace Illuminate\Encryption;
<ide>
<ide> use Exception;
<del>use Illuminate\Support\Str;
<ide> use Illuminate\Contracts\Encryption\DecryptException;
<ide> use Illuminate\Contracts\Encryption\Encrypter as EncrypterContract;
<ide>
<ide><path>src/Illuminate/Http/ResponseTrait.php
<ide>
<ide> namespace Illuminate\Http;
<ide>
<del>use Symfony\Component\HttpFoundation\Cookie;
<del>
<ide> trait ResponseTrait
<ide> {
<ide> /** | 3 |
Text | Text | add upgrade guide for middleware. | eb55af1cfefd30fd86735df769231bfbc90990a9 | <ide><path>errors/middleware-upgrade-guide.md
<add># Middleware Upgrade Guide
<add>
<add>As we work on improving Middleware for General Availability (GA), we've made some changes to the Middleware APIs (and how you define Middleware in your application) based on your feedback.
<add>
<add>This upgrade guide will help you understand the changes and how to migrate your existing Middleware to the new API. The guide is for Next.js developers who:
<add>
<add>- Currently use the beta Next.js Middleware features
<add>- Choose to upgrade to the next stable version of Next.js (`v12.2`)
<add>
<add>You can start upgrading your Middleware usage today with the latest canary release (`npm i next@canary`).
<add>
<add>## Using Next.js Middleware on Vercel
<add>
<add>If you're using Next.js on Vercel, your existing deploys using Middleware will continue to work, and you can continue to deploy your site using Middleware. When you upgrade your site to the next stable version of Next.js (`v12.2`), you will need to follow this upgrade guide to update your Middleware.
<add>
<add>## Breaking changes
<add>
<add>1. [No Nested Middleware](#no-nested-middleware)
<add>2. [No Response Body](#no-response-body)
<add>3. [Cookies API Revamped](#cookies-api-revamped)
<add>4. [New User-Agent Helper](#new-user-agent-helper)
<add>5. [No More Page Match Data](#no-more-page-match-data)
<add>6. [Executing Middleware on Internal Next.js Requests](#executing-middleware-on-internal-nextjs-requests)
<add>
<add>## No Nested Middleware
<add>
<add>### Summary of changes
<add>
<add>- Define a single Middleware file at the root of your project
<add>- No need to prefix the file with an underscore
<add>- A custom matcher can be used to define matching routes using an exported config object
<add>
<add>### Explanation
<add>
<add>Previously, you could create a `_middleware.ts` file under the `pages` directory at any level. Middleware execution was based on the file path where it was created. Beta customers found this route matching confusing. For example:
<add>
<add>- Middleware in `pages/dashboard/_middleware.ts`
<add>- Middleware in `pages/dashboard/users/_middleware.ts`
<add>- A request to `/dashboard/users/*` **would match both.**
<add>
<add>Based on customer feedback, we have replaced this API with a single root Middleware.
<add>
<add>### How to upgrade
<add>
<add>You should declare **one single Middleware file** in your application, which should be located at the root of the project directory (**not** inside of the `pages` directory), and named **without** an `_` prefix. Your Middleware file can still have either a `.ts` or `.js` extension.
<add>
<add>Middleware will be invoked for **every route in the app**, and a custom matcher can be used to define matching filters. The following is an example for a Middleware that triggers for `/about/*` and `/dashboard/:path*`, the custom matcher is defined in an exported config object:
<add>
<add>```typescript
<add>// middleware.ts
<add>import { NextResponse } from 'next/server'
<add>import type { NextRequest } from 'next/server'
<add>
<add>export function middleware(request: NextRequest) {
<add> return NextResponse.rewrite(new URL('/about-2', request.url))
<add>}
<add>
<add>// Supports both a single string value or an array of matchers
<add>export const config = {
<add> matcher: ['/about/:path*', '/dashboard/:path*'],
<add>}
<add>```
<add>
<add>While the config option is preferred since it doesn't get invoked on every request, you can also use conditional statements to only run the Middleware when it matches specific paths. One advantage of using conditionals is defining explicit ordering for when Middleware executes. The following example shows how you can merge two previously nested Middleware:
<add>
<add>```typescript
<add>// <root>/middleware.js
<add>import type { NextRequest } from 'next/server'
<add>
<add>export function middleware(request: NextRequest) {
<add> if (request.nextUrl.pathname.startsWith('/about')) {
<add> // This logic is only applied to /about
<add> }
<add>
<add> if (request.nextUrl.pathname.startsWith('/dashboard')) {
<add> // This logic is only applied to /dashboard
<add> }
<add>}
<add>```
<add>
<add>## No Response Body
<add>
<add>### Summary of changes
<add>
<add>- Middleware can no longer respond with a body
<add>- If your Middleware _does_ respond with a body, a runtime error will be thrown
<add>- Migrate to using `rewrites`/`redirects` to pages/APIs handling a response
<add>
<add>### Explanation
<add>
<add>To help ensure security, we are removing the ability to send response bodies in Middleware. This ensures that Middleware is only used to `rewrite`, `redirect`, or modify the incoming request (e.g. [setting cookies](#cookies-api-revamped)).
<add>
<add>The following patterns will no longer work:
<add>
<add>```js
<add>new Response('a text value')
<add>new Response(streamOrBuffer)
<add>new Response(JSON.stringify(obj), { headers: 'application/json' })
<add>NextResponse.json()
<add>```
<add>
<add>### How to upgrade
<add>
<add>For cases where Middleware is used to respond (such as authorization), you should migrate to use `rewrites`/`redirects` to pages that show an authorization error, login forms, or to an API Route.
<add>
<add>#### Before
<add>
<add>```typescript
<add>// pages/_middleware.ts
<add>import { NextResponse } from 'next/server'
<add>import type { NextRequest } from 'next/server'
<add>import { isAuthValid } from './lib/auth'
<add>
<add>export function middleware(request: NextRequest) {
<add> // Example function to validate auth
<add> if (isAuthValid(req)) {
<add> return NextResponse.next()
<add> }
<add>
<add> return NextResponse.json({ message: 'Auth required' }, { status: 401 })
<add>}
<add>```
<add>
<add>#### After
<add>
<add>```typescript
<add>// middleware.ts
<add>import { NextResponse } from 'next/server'
<add>import type { NextRequest } from 'next/server'
<add>import { isAuthValid } from './lib/auth'
<add>
<add>export function middleware(request: NextRequest) {
<add> // Example function to validate auth
<add> if (isAuthValid(req)) {
<add> return NextResponse.next()
<add> }
<add>
<add> const loginUrl = new URL('/login', request.url)
<add> loginUrl.searchParams.set('from', request.nextUrl.pathname)
<add>
<add> return NextResponse.redirect(loginUrl)
<add>}
<add>```
<add>
<add>## Cookies API Revamped
<add>
<add>### Summary of changes
<add>
<add>| Added | Removed |
<add>| ----------------------- | ------------- |
<add>| `cookie.set` | `cookie` |
<add>| `cookie.delete` | `clearCookie` |
<add>| `cookie.getWithOptions` | `cookies` |
<add>
<add>### Explanation
<add>
<add>Based on beta feedback, we are changing the Cookies API in `NextRequest` and `NextResponse` to align more to a `get`/`set` model. The `Cookies` API extends Map, including methods like [entries](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/entries) and [values](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/entries).
<add>
<add>### How to upgrade
<add>
<add>`NextResponse` now has a `cookies` instance with:
<add>
<add>- `cookie.delete`
<add>- `cookie.set`
<add>- `cookie.getWithOptions`
<add>
<add>As well as other extended methods from `Map`.
<add>
<add>#### Before
<add>
<add>```javascript
<add>import { NextResponse } from 'next/server'
<add>import type { NextRequest } from 'next/server'
<add>
<add>export function middleware(request: NextRequest) {
<add> // create an instance of the class to access the public methods. This uses `next()`,
<add> // you could use `redirect()` or `rewrite()` as well
<add> let response = NextResponse.next()
<add> // get the cookies from the request
<add> let cookieFromRequest = request.cookies['my-cookie']
<add> // set the `cookie`
<add> response.cookie('hello', 'world')
<add> // set the `cookie` with options
<add> const cookieWithOptions = response.cookie('hello', 'world', {
<add> path: '/',
<add> maxAge: 1000 * 60 * 60 * 24 * 7,
<add> httpOnly: true,
<add> sameSite: 'strict',
<add> domain: 'example.com',
<add> })
<add> // clear the `cookie`
<add> response.clearCookie('hello')
<add>
<add> return response
<add>}
<add>```
<add>
<add>#### After
<add>
<add>```typescript
<add>// middleware.ts
<add>export function middleware() {
<add> const response = new NextResponse()
<add>
<add> // set a cookie
<add> response.cookies.set('vercel', 'fast')
<add>
<add> // set another cookie with options
<add> response.cookies.set('nextjs', 'awesome', { path: '/test' })
<add>
<add> // get all the details of a cookie
<add> const {value, options} = response.cookies.getWithOptions('vercel')
<add> console.log(value) // => 'fast'
<add> console.log(options) // => { Path: '/test' }
<add>
<add> // deleting a cookie will mark it as expired
<add> response.cookies.delete('vercel')
<add>
<add> // clear all cookies means mark all of them as expired
<add> response.cookies.clear()
<add>}
<add>```
<add>## New User-Agent Helper
<add>
<add>### Summary of changes
<add>
<add>- Accessing the user agent is no longer available on the request object
<add>- We've added a new `userAgent` helper to reduce Middleware size by `17kb`
<add>
<add>### Explanation
<add>
<add>To help reduce the size of your Middleware, we have extracted the user agent from the request object and created a new helper `userAgent`.
<add>
<add>The helper is imported from `next/server` and allows you to opt in to using the user agent. The helper gives you access to the same properties that were available from the request object.
<add>
<add>### How to upgrade
<add>
<add>- Import the `userAgent` helper from `next/server`
<add>- Destructure the properties you need to work with
<add>
<add>#### Before
<add>
<add>```typescript
<add>// middleware.ts
<add>import { NextRequest, NextResponse } from 'next/server'
<add>
<add>export function middleware(request: NextRequest) {
<add> const url = request.nextUrl
<add> const viewport = request.ua.device.type === 'mobile' ? 'mobile' : 'desktop'
<add> url.searchParams.set('viewport', viewport)
<add> return NextResponse.rewrites(url)
<add>}
<add>```
<add>
<add>#### After
<add>
<add>```typescript
<add>// middleware.ts
<add>import { NextRequest, NextResponse, userAgent } from 'next/server'
<add>
<add>export function middleware(request: NextRequest) {
<add> const url = request.nextUrl
<add> const { device } = userAgent(request)
<add> const viewport = device.type === 'mobile' ? 'mobile' : 'desktop'
<add> url.searchParams.set('viewport', viewport)
<add> return NextResponse.rewrites(url)
<add>}
<add>```
<add>
<add>## No More Page Match Data
<add>
<add>### Summary of changes
<add>
<add>- Use [`URLPattern`](https://developer.mozilla.org/en-US/docs/Web/API/URLPattern) to check if a Middleware is being invoked for a certain page match
<add>
<add>### Explanation
<add>
<add>Currently, Middleware estimates whether you are serving an asset of a Page based on the Next.js routes manifest (internal configuration). This value is surfaced through `request.page`.
<add>
<add>To make page and asset matching more accurate, we are now using the web standard `URLPattern` API.
<add>
<add>### How to upgrade
<add>
<add>Use [`URLPattern`](https://developer.mozilla.org/en-US/docs/Web/API/URLPattern) to check if a Middleware is being invoked for a certain page match.
<add>
<add>#### Before
<add>
<add>```typescript
<add>// middleware.ts
<add>import { NextResponse } from 'next/server'
<add>import type { NextRequest } from 'next/server'
<add>
<add>export function middleware(request: NextRequest) {
<add> const { params } = event.request.page
<add> const { locale, slug } = params
<add>
<add> if (locale && slug) {
<add> const { search, protocol, host } = request.nextUrl
<add> const url = new URL(`${protocol}//${locale}.${host}/${slug}${search}`)
<add> return NextResponse.redirect(url)
<add> }
<add>}
<add>```
<add>
<add>#### After
<add>
<add>```typescript
<add>// middleware.ts
<add>import { NextResponse } from 'next/server'
<add>import type { NextRequest } from 'next/server'
<add>
<add>const PATTERNS = [
<add> [
<add> new URLPattern({ pathname: '/:locale/:slug' }),
<add> ({ pathname }) => pathname.groups,
<add> ],
<add>]
<add>
<add>const params = (url) => {
<add> const input = url.split('?')[0]
<add> let result = {}
<add>
<add> for (const [pattern, handler] of PATTERNS) {
<add> const patternResult = pattern.exec(input)
<add> if (patternResult !== null && 'pathname' in patternResult) {
<add> result = handler(patternResult)
<add> break
<add> }
<add> }
<add> return result
<add>}
<add>
<add>export function middleware(request: NextRequest) {
<add> const { locale, slug } = params(request.url)
<add>
<add> if (locale && slug) {
<add> const { search, protocol, host } = request.nextUrl
<add> const url = new URL(`${protocol}//${locale}.${host}/${slug}${search}`)
<add> return NextResponse.redirect(url)
<add> }
<add>}
<add>```
<add>
<add>## Executing Middleware on Internal Next.js Requests
<add>
<add>### Summary of changes
<add>
<add>- Middleware will be executed for _all_ requests, including `_next`
<add>
<add>### Explanation
<add>
<add>Prior to Next.js `v12.2`, Middleware was not executed for `_next` requests.
<add>
<add>For cases where Middleware is used for authorization, you should migrate to use `rewrites`/`redirects` to Pages that show an authorization error, login forms, or to an API Route.
<add>
<add>See [No Reponse Body](#no-response-body) for an example of how to migrate to use `rewrites`/`redirects`. | 1 |
Text | Text | add closing quotes to local setup | 0e4a1408f8f452503eb5e759f2bd4ab37adee628 | <ide><path>docs/how-to-setup-freecodecamp-locally.md
<ide> A quick reference to the commands that you will need when working locally.
<ide> | `npm run docker:seed` | Parse all the challenge markdown files and inserts them into MongoDB. |
<ide> | `npm run docker:develop` | Start the freeCodeCamp API Server and Client Applications. |
<ide> | `npm run docker:test:init` | Bootstrap the test container, necessary for testing in docker. |
<del>| `npm run docker:test -- -c "npm run test` | Run all JS tests in the system, including client, server, lint and challenge tests. |
<del>| `npm run docker:test -- -c "npm run test:curriculum` | Run the curriculum test suite. |
<del>| `npm run docker:test -- -c "npm run test:client` | Run the client test suite. |
<del>| `npm run docker:test -- -c "npm run test:server` | Run the server test suite. |
<add>| `npm run docker:test -- -c "npm run test"` | Run all JS tests in the system, including client, server, lint and challenge tests. |
<add>| `npm run docker:test -- -c "npm run test:curriculum"` | Run the curriculum test suite. |
<add>| `npm run docker:test -- -c "npm run test:client"` | Run the client test suite. |
<add>| `npm run docker:test -- -c "npm run test:server"` | Run the server test suite. |
<ide> | `npm run docker:clean` | Uninstall all dependencies and cleans up caches. |
<ide>
<ide> **Local Build:** | 1 |
Ruby | Ruby | remove needless test order config | 02b4ba64615f7fb69975ff57d89ee7fa7c8bb45a | <ide><path>railties/test/isolation/abstract_unit.rb
<ide> def build_app(options = {})
<ide> config.eager_load = false
<ide> config.session_store :cookie_store, key: "_myapp_session"
<ide> config.active_support.deprecation = :log
<del> config.active_support.test_order = :random
<ide> config.action_controller.allow_forgery_protection = false
<ide> config.log_level = :info
<ide> RUBY
<ide> def self.name; "RailtiesTestApp"; end
<ide> @app.config.eager_load = false
<ide> @app.config.session_store :cookie_store, key: "_myapp_session"
<ide> @app.config.active_support.deprecation = :log
<del> @app.config.active_support.test_order = :random
<ide> @app.config.log_level = :info
<ide>
<ide> yield @app if block_given? | 1 |
Python | Python | optimize np.isin for integer arrays | cedba623b110caf83f46edfa38cb4fbc0191e285 | <ide><path>numpy/lib/arraysetops.py
<ide> def in1d(ar1, ar2, assume_unique=False, invert=False):
<ide> # Ensure that iteration through object arrays yields size-1 arrays
<ide> if ar2.dtype == object:
<ide> ar2 = ar2.reshape(-1, 1)
<add> # Check if we can use a fast integer algorithm:
<add> integer_arrays = (np.issubdtype(ar1.dtype, np.integer) and
<add> np.issubdtype(ar2.dtype, np.integer))
<add>
<add> if integer_arrays:
<add> ar2_min = np.min(ar2)
<add> ar2_max = np.max(ar2)
<add> ar2_range = ar2_max - ar2_min
<add> ar2_size = ar2.size
<add>
<add> # Optimal performance is for approximately
<add> # log10(size) > (log10(range) - 2.27) / 0.927, see discussion on
<add> # https://github.com/numpy/numpy/pull/12065
<add> optimal_parameters = (
<add> np.log10(ar2_size + 1) >
<add> ((np.log10(ar2_range + 1) - 2.27) / 0.927)
<add> )
<add>
<add> if optimal_parameters:
<add>
<add> if invert:
<add> outgoing_array = np.ones_like(ar1, dtype=np.bool_)
<add> else:
<add> outgoing_array = np.zeros_like(ar1, dtype=np.bool_)
<add>
<add> # Make elements 1 where the integer exists in ar2
<add> if invert:
<add> isin_helper_ar = np.ones(ar2_range + 1, dtype=np.bool_)
<add> isin_helper_ar[ar2 - ar2_min] = 0
<add> else:
<add> isin_helper_ar = np.zeros(ar2_range + 1, dtype=np.bool_)
<add> isin_helper_ar[ar2 - ar2_min] = 1
<add>
<add> # Mask out elements we know won't work
<add> basic_mask = (ar1 <= ar2_max) & (ar1 >= ar2_min)
<add> outgoing_array[basic_mask] = isin_helper_ar[ar1[basic_mask] -
<add> ar2_min]
<add>
<add> return outgoing_array
<add>
<ide>
<ide> # Check if one of the arrays may contain arbitrary objects
<ide> contains_object = ar1.dtype.hasobject or ar2.dtype.hasobject | 1 |
Go | Go | fix dockernetworksuite not being run | 5c891ea9ca9084e81429395d99fdad451d2cffaf | <ide><path>integration-cli/check_test.go
<ide> func TestDockerExternalVolumeSuite(t *testing.T) {
<ide> func TestDockerNetworkSuite(t *testing.T) {
<ide> ensureTestEnvSetup(t)
<ide> testRequires(t, DaemonIsLinux)
<del> suite.Run(t, &DockerExternalVolumeSuite{ds: &DockerSuite{}})
<add> suite.Run(t, &DockerNetworkSuite{ds: &DockerSuite{}})
<ide> }
<ide>
<ide> func TestDockerHubPullSuite(t *testing.T) { | 1 |
Go | Go | preserve order of environment variables | b426741c1504d45d0e1dd6d76ec5144bd95aa480 | <ide><path>cli/command/service/update.go
<ide> func updateLabels(flags *pflag.FlagSet, field *map[string]string) {
<ide> }
<ide>
<ide> func updateEnvironment(flags *pflag.FlagSet, field *[]string) {
<del> envSet := map[string]string{}
<del> for _, v := range *field {
<del> envSet[envKey(v)] = v
<del> }
<ide> if flags.Changed(flagEnvAdd) {
<add> envSet := map[string]string{}
<add> for _, v := range *field {
<add> envSet[envKey(v)] = v
<add> }
<add>
<ide> value := flags.Lookup(flagEnvAdd).Value.(*opts.ListOpts)
<ide> for _, v := range value.GetAll() {
<ide> envSet[envKey(v)] = v
<ide> }
<del> }
<ide>
<del> *field = []string{}
<del> for _, v := range envSet {
<del> *field = append(*field, v)
<add> *field = []string{}
<add> for _, v := range envSet {
<add> *field = append(*field, v)
<add> }
<ide> }
<ide>
<ide> toRemove := buildToRemoveSet(flags, flagEnvRemove) | 1 |
Ruby | Ruby | initialize subscriptions as early as possible | 449b3ca7b08c000c05100cc909fc29cbc9f365ee | <ide><path>lib/action_cable/server.rb
<ide>
<ide> module ActionCable
<ide> class Server < Cramp::Websocket
<del> on_start :initialize_subscriptions
<ide> on_data :received_data
<ide> on_finish :cleanup_subscriptions
<ide>
<ide> def register_channels(*channel_classes)
<ide> end
<ide> end
<ide>
<del> def initialize_subscriptions
<add> def initialize(*)
<ide> @subscriptions = {}
<add>
<add> super
<ide> end
<ide>
<ide> def received_data(data) | 1 |
Go | Go | trim the splited builder lines | 4ebec08add53bd9b3e10c331168daa6579ebd6db | <ide><path>builder.go
<ide> func (builder *Builder) Build(dockerfile io.Reader, stdout io.Writer) (*Image, e
<ide> if len(tmp) != 2 {
<ide> return nil, fmt.Errorf("Invalid Dockerfile format")
<ide> }
<del> instruction := tmp[0]
<del> arguments := tmp[1]
<add> instruction := strings.Trim(tmp[0], " ")
<add> arguments := strings.Trim(tmp[1], " ")
<ide> switch strings.ToLower(instruction) {
<ide> case "from":
<ide> fmt.Fprintf(stdout, "FROM %s\n", arguments)
<ide> func (builder *Builder) Build(dockerfile io.Reader, stdout io.Writer) (*Image, e
<ide> if len(tmp) != 2 {
<ide> return nil, fmt.Errorf("Invalid INSERT format")
<ide> }
<del> sourceUrl := tmp[0]
<del> destPath := tmp[1]
<add> sourceUrl := strings.Trim(tmp[0], "")
<add> destPath := strings.Trim(tmp[1], " ")
<ide> fmt.Fprintf(stdout, "COPY %s to %s in %s\n", sourceUrl, destPath, base.ShortId())
<ide>
<ide> file, err := Download(sourceUrl, stdout) | 1 |
PHP | PHP | use finfo better | 5dee28d4f2cddfefede4f4048499353e5f5d7474 | <ide><path>src/Filesystem/File.php
<ide> */
<ide> namespace Cake\Filesystem;
<ide>
<add>use finfo;
<add>
<ide> /**
<ide> * Convenience class for reading, writing and appending to files.
<ide> *
<ide> public function mime()
<ide> if (!$this->exists()) {
<ide> return false;
<ide> }
<del> if (function_exists('finfo_open')) {
<del> $finfo = finfo_open(FILEINFO_MIME);
<del> $finfo = finfo_file($finfo, $this->pwd());
<del> if (!$finfo) {
<add> if (class_exists('finfo')) {
<add> $finfo = new finfo(FILEINFO_MIME);
<add> $type = $finfo->file($this->pwd());
<add> if (!$type) {
<ide> return false;
<ide> }
<del> list($type) = explode(';', $finfo);
<add> list($type) = explode(';', $type);
<ide> return $type;
<ide> }
<ide> if (function_exists('mime_content_type')) { | 1 |
Ruby | Ruby | add missing spdx require | cea6bf6efe52c318a4e33ec2f4fd0374db34b090 | <ide><path>Library/Homebrew/formula.rb
<ide> require "tab"
<ide> require "mktemp"
<ide> require "find"
<add>require "utils/spdx"
<ide>
<ide> # A formula provides instructions and metadata for Homebrew to install a piece
<ide> # of software. Every Homebrew formula is a {Formula}. | 1 |
PHP | PHP | add missing parameter tag | fe8cb5b178bdc383eb4fb1d466578d581359eb65 | <ide><path>src/Validation/Validation.php
<ide> public static function ascii($value)
<ide> * the basic multilingual plane. Defaults to false.
<ide> *
<ide> * @param string $value The value to check
<add> * @param array $options An array of options. See above for the supported options.
<ide> * @return bool
<ide> */
<ide> public static function utf8($value, array $options = []) | 1 |
Javascript | Javascript | convert the hand tool to a class | b0aca31de8e34badca5b70272857bc658b61b5e1 | <ide><path>web/app.js
<ide> var PDFViewerApplication = {
<ide>
<ide> this.overlayManager = OverlayManager;
<ide>
<del> HandTool.initialize({
<add> this.handTool = new HandTool({
<ide> container: container,
<ide> toggleHandTool: document.getElementById('toggleHandTool')
<ide> });
<del> this.handTool = HandTool;
<ide>
<ide> this.pdfDocumentProperties = new PDFDocumentProperties({
<ide> overlayName: 'documentPropertiesOverlay',
<ide> window.addEventListener('keydown', function keydown(evt) {
<ide>
<ide> case 72: // 'h'
<ide> if (!isViewerInPresentationMode) {
<del> HandTool.toggle();
<add> PDFViewerApplication.handTool.toggle();
<ide> }
<ide> break;
<ide> case 82: // 'r'
<ide><path>web/hand_tool.js
<ide> var GrabToPan = grabToPan.GrabToPan;
<ide> var Preferences = preferences.Preferences;
<ide> var SecondaryToolbar = secondaryToolbar.SecondaryToolbar;
<ide>
<del>var HandTool = {
<del> initialize: function handToolInitialize(options) {
<del> var toggleHandTool = options.toggleHandTool;
<add>/**
<add> * @typedef {Object} HandToolOptions
<add> * @property {HTMLDivElement} container - The document container.
<add> * @property {HTMLButtonElement} toggleHandTool - The button element for
<add> * toggling the hand tool.
<add> */
<add>
<add>/**
<add> * @class
<add> */
<add>var HandTool = (function HandToolClosure() {
<add> /**
<add> * @constructs HandTool
<add> * @param {HandToolOptions} options
<add> */
<add> function HandTool(options) {
<add> this.container = options.container;
<add> this.toggleHandTool = options.toggleHandTool;
<add>
<add> this.wasActive = false;
<add>
<ide> this.handTool = new GrabToPan({
<del> element: options.container,
<add> element: this.container,
<ide> onActiveChanged: function(isActive) {
<del> if (!toggleHandTool) {
<add> if (!this.toggleHandTool) {
<ide> return;
<ide> }
<ide> if (isActive) {
<del> toggleHandTool.title =
<add> this.toggleHandTool.title =
<ide> mozL10n.get('hand_tool_disable.title', null, 'Disable hand tool');
<del> toggleHandTool.firstElementChild.textContent =
<add> this.toggleHandTool.firstElementChild.textContent =
<ide> mozL10n.get('hand_tool_disable_label', null, 'Disable hand tool');
<ide> } else {
<del> toggleHandTool.title =
<add> this.toggleHandTool.title =
<ide> mozL10n.get('hand_tool_enable.title', null, 'Enable hand tool');
<del> toggleHandTool.firstElementChild.textContent =
<add> this.toggleHandTool.firstElementChild.textContent =
<ide> mozL10n.get('hand_tool_enable_label', null, 'Enable hand tool');
<ide> }
<del> }
<add> }.bind(this)
<ide> });
<del> if (toggleHandTool) {
<del> toggleHandTool.addEventListener('click', this.toggle.bind(this), false);
<add>
<add> if (this.toggleHandTool) {
<add> this.toggleHandTool.addEventListener('click', this.toggle.bind(this));
<ide>
<ide> window.addEventListener('localized', function (evt) {
<ide> Preferences.get('enableHandToolOnLoad').then(function resolved(value) {
<ide> var HandTool = {
<ide> }
<ide> }.bind(this));
<ide> }
<del> },
<add> }
<ide>
<del> toggle: function handToolToggle() {
<del> this.handTool.toggle();
<del> SecondaryToolbar.close();
<del> },
<add> HandTool.prototype = {
<add> /**
<add> * @return {boolean}
<add> */
<add> get isActive() {
<add> return !!this.handTool.active;
<add> },
<ide>
<del> enterPresentationMode: function handToolEnterPresentationMode() {
<del> if (this.handTool.active) {
<del> this.wasActive = true;
<del> this.handTool.deactivate();
<del> }
<del> },
<add> toggle: function HandTool_toggle() {
<add> this.handTool.toggle();
<add> SecondaryToolbar.close();
<add> },
<add>
<add> enterPresentationMode: function HandTool_enterPresentationMode() {
<add> if (this.isActive) {
<add> this.wasActive = true;
<add> this.handTool.deactivate();
<add> }
<add> },
<ide>
<del> exitPresentationMode: function handToolExitPresentationMode() {
<del> if (this.wasActive) {
<del> this.wasActive = null;
<del> this.handTool.activate();
<add> exitPresentationMode: function HandTool_exitPresentationMode() {
<add> if (this.wasActive) {
<add> this.wasActive = false;
<add> this.handTool.activate();
<add> }
<ide> }
<del> }
<del>};
<add> };
<add>
<add> return HandTool;
<add>})();
<ide>
<ide> exports.HandTool = HandTool;
<ide> })); | 2 |
Python | Python | add tutorials and examples for the new optimizer | f4dbe9e55f2fd28ec7ff9ba8b5958141c5ffef2f | <ide><path>keras/optimizer_experimental/optimizer.py
<ide> def compute_gradients(self, loss, var_list, tape=None):
<ide> and return the value to minimize.
<ide> var_list: list or tuple of `Variable` objects to update to minimize
<ide> `loss`.
<del> tape: (Optional) `tf.GradientTape`.
<add> tape: (Optional) `tf.GradientTape`. If `loss` is provided as a `Tensor`,
<add> the tape that computed the `loss` must be provided.
<ide>
<ide> Returns:
<ide> A list of (gradient, variable) pairs. Variable is always present, but
<ide> gradient can be `None`.
<ide> """
<add> if not callable(loss) and tape is None:
<add> raise ValueError("`tape` is required when a `Tensor` loss is passed. "
<add> f"Received: loss={loss}, tape={tape}.")
<ide> if tape is None:
<ide> tape = tf.GradientTape()
<ide> if callable(loss):
<ide> class Optimizer(_BaseOptimizer):
<ide> overwrite the model variable by its stored moving average. If None, we
<ide> do not overwrite model variables in the middle of training, and users
<ide> need to explicitly overwrite the model variable by calling
<del> `finalize_variable_update()`.
<add> `finalize_variable_values()`.
<ide> jit_compile: bool, default to False. If True, the optimizer will use XLA
<ide> acceleration. `jit_compile` can only be False when using Parameter
<ide> Server Strategy.
<ide> **kwargs: keyword arguments only used for backward compatibility with
<ide> `optimizer_v2.OptimizerV2`. Any new code using
<ide> `optimizer_experimental.Optimizer` should leave this parameter empty.
<add>
<add> ### Usage
<add>
<add> ```python
<add> # Create an optimizer with the desired parameters.
<add> opt = tf.keras.optimizers.experimental.SGD(learning_rate=0.1)
<add> var1, var2 = tf.Variable(1.0), tf.Variable(2.0)
<add> # `loss` is a callable that takes no argument and returns the value
<add> # to minimize.
<add> loss = lambda: 3 * var1 * var1 + 2 * var2 * var2
<add> # Call minimize to update the list of variables.
<add> opt.minimize(loss, var_list=[var1, var2])
<add> ```
<add>
<add> ### Processing gradients before applying them
<add>
<add> Calling `minimize()` takes care of both computing the gradients and
<add> applying them to the variables. If you want to process the gradients
<add> before applying them you can instead use the optimizer in three steps:
<add>
<add> 1. Compute the gradients with `tf.GradientTape`.
<add> 2. Process the gradients as you wish.
<add> 3. Apply the processed gradients with `apply_gradients()`.
<add>
<add> Example:
<add>
<add> ```python
<add> # Create an optimizer.
<add> opt = tf.keras.optimizers.experimental.SGD(learning_rate=0.1)
<add> var1, var2 = tf.Variable(1.0), tf.Variable(2.0)
<add>
<add> # Compute the gradients for a list of variables.
<add> with tf.GradientTape() as tape:
<add> loss = 3 * var1 * var1 + 2 * var2 * var2
<add> grads = tape.gradient(loss, [var1, var2])
<add>
<add> # Process the gradients.
<add> grads[0] = grads[0] + 1
<add>
<add> # Ask the optimizer to apply the gradients on variables.
<add> opt.apply_gradients(zip(grads, [var1, var2]))
<add> ```
<add>
<add> ### Dynamic learning rate
<add>
<add> Dynamic learning rate can be achieved by setting learning rate as a built-in
<add> or customized `tf.keras.optimizers.schedules.LearningRateSchedule`.
<add>
<add> Example:
<add>
<add> >>> var = tf.Variable(np.random.random(size=(1,)))
<add> >>> learning_rate = tf.keras.optimizers.schedules.ExponentialDecay(
<add> ... initial_learning_rate=.01, decay_steps=20, decay_rate=.1)
<add> >>> opt = tf.keras.optimizers.experimental.SGD(learning_rate=learning_rate)
<add> >>> loss = lambda: 3 * var
<add> >>> opt.minimize(loss, var_list=[var])
<add> <tf.Variable...
<add>
<add> ### Gradients clipping
<add>
<add> Users can clip the gradients before applying to variables by setting
<add> `clipnorm`, `clipvalue` and `global_clipnorm`. Notice that `clipnorm` and
<add> `global_clipnorm` can only have one being set.
<add>
<add> Example:
<add>
<add> >>> opt = tf.keras.optimizers.experimental.SGD(learning_rate=1, clipvalue=1)
<add> >>> var1, var2 = tf.Variable(2.0), tf.Variable(2.0)
<add> >>> with tf.GradientTape() as tape:
<add> ... loss = 2 * var1 + 2 * var2
<add> >>> grads = tape.gradient(loss, [var1, var2])
<add> >>> print([grads[0].numpy(), grads[1].numpy()])
<add> [2.0., 2.0]
<add> >>> opt.apply_gradients(zip(grads, [var1, var2]))
<add> >>> # Without clipping, we should get [0, 0], but as gradients are clipped to
<add> >>> # have max value 1, we get [1.0, 1.0].
<add> >>> print([var1.numpy(), var2.numpy()])
<add> [1.0, 1.0]
<add>
<add> ### Using exponential moving average.
<add>
<add> Empirically it has been found that using the exponential moving average (EMA)
<add> of the trained parameters of a deep network achieves a better performance than
<add> using its trained parameters directly. Keras optimizers allows users to
<add> compute this moving average and overwrite the model variables at desired time.
<add>
<add> Example:
<add>
<add> ```python
<add> # Create an SGD optimizer with EMA on. `ema_momentum` controls the decay rate
<add> # of the moving average. `ema_momentum=1` means no decay and the stored moving
<add> # average is always model variable's initial value before training. Reversely,
<add> # `ema_momentum=0` is equivalent to not using EMA. `ema_overwrite_frequency=3`
<add> # means every 3 iterations, we overwrite the trainable variables with their
<add> # moving average values.
<add> opt = tf.keras.optimizers.experimental.SGD(
<add> learning_rate=1,
<add> use_ema=True,
<add> ema_momentum=0.5,
<add> ema_overwrite_frequency=3)
<add> var1, var2 = tf.Variable(2.0), tf.Variable(2.0)
<add> with tf.GradientTape() as tape:
<add> loss = var1 + var2
<add> grads = tape.gradient(loss, [var1, var2])
<add> # First iteration: [var1, var2] = [1.0, 1.0]
<add> opt.apply_gradients(zip(grads, [var1, var2]))
<add> print([var1, var2])
<add>
<add> # Second iteration: [var1, var2] = [0.0, 0.0]
<add> opt.apply_gradients(zip(grads, [var1, var2]))
<add> print([var1, var2])
<add>
<add> # Third iteration, without EMA, we should see [var1, var2] = [-1.0, -1.0],
<add> # but overwriting results in [var1, var2] = [-0.125, -0.125]. The full
<add> # calculation for the moving average of var1 is:
<add> # var1=2*0.5**3+1*(1-0.5)*0.5**2+0*(1-0.5)*0.5**1+(-1)*(1-0.5)=-0.125.
<add> opt.apply_gradients(zip(grads, [var1, var2]))
<add> print([var1, var2])
<add>
<add> ```
<add> When optimizer is constructed with `use_ema=True`, in custom training loop,
<add> users can explicitly call `finalize_variable_values()` to overwrite trainable
<add> variables with their EMA values. `finalize_variable_values()` is by default
<add> called at the end of `model.fit()`.
<add>
<add> ### Use with `tf.distribute.Strategy`
<add>
<add> This optimizer class is `tf.distribute.Strategy` aware, which means it
<add> automatically sums gradients across all replicas. To aggregate gradients
<add> yourself, call `apply_gradients` with `skip_aggregate_gradients` set to True.
<add> This is useful if you need to process aggregated gradients.
<add>
<add> ```python
<add> # This example is not runnable, it consists of dummy code for simple tutorial.
<add> strategy = tf.distribute.experimental.TPUStrategy()
<add>
<add> with strategy.scope():
<add> opt = tf.keras.optimizers.experimental.SGD()
<add> model = magic_function_that_returns_model()
<add> gradients = magic_function_that_returns_gradients()
<add> # Custom logic to aggregate gradients.
<add> gradients = strategy.reduce("SUM", gradients, axis=None)
<add> opt.apply_gradients(zip(gradients, model.trainable_variables),
<add> skip_aggregate_gradients=True)
<add> ```
<add>
<ide> """
<ide>
<ide> def __init__(self,
<ide><path>keras/optimizer_experimental/optimizer_test.py
<ide> def testSetLearningRate(self):
<ide> optimizer.learning_rate = 2.0
<ide>
<ide> def testMovingAverageOptimizer(self):
<del> # We set polyak averaging with ema_momentum = 1 so that the
<del> # moving average is always the original value of the variables.
<del> optimizer = adam_new.Adam(
<del> use_ema=True, ema_momentum=1, ema_overwrite_frequency=2)
<del> x = tf.Variable([1.0, 2.0], dtype=tf.float32)
<del> x_origin = tf.Variable(x)
<del> grads = tf.convert_to_tensor([1.0, 2.0])
<del> # First iteration, we store the moving average, and do not do overriding.
<del> optimizer.apply_gradients(zip([grads], [x]))
<del> self.assertAllEqual(optimizer._model_variables_moving_average[0], x_origin)
<del> self.assertNotAllEqual(x, x_origin)
<del>
<del> # Second iteration, we store the moving average, and override model vars.
<del> optimizer.apply_gradients(zip([grads], [x]))
<del> self.assertAllEqual(x, x_origin)
<add> optimizer = sgd_new.SGD(
<add> learning_rate=1,
<add> use_ema=True,
<add> ema_momentum=0.5,
<add> ema_overwrite_frequency=3)
<add>
<add> var1, var2 = tf.Variable(2.0), tf.Variable(2.0)
<add> with tf.GradientTape() as tape:
<add> loss = var1 + var2
<add> grads = tape.gradient(loss, [var1, var2])
<add> # First iteration: [var1, var2] = [1.0, 1.0]
<add> optimizer.apply_gradients(zip(grads, [var1, var2]))
<add> self.assertAllEqual([var1.numpy(), var2.numpy()], [1.0, 1.0])
<add>
<add> # Second iteration: [var1, var2] = [0.0, 0.0]
<add> optimizer.apply_gradients(zip(grads, [var1, var2]))
<add> self.assertAllEqual([var1.numpy(), var2.numpy()], [0.0, 0.0])
<add>
<add> # Third iteration, without EMA, we should see [var1, var2] = [-1.0, -1.0],
<add> # but overwriting results in [var1, var2] = [-0.125, -0.125].
<add> optimizer.apply_gradients(zip(grads, [var1, var2]))
<add> self.assertAllEqual([var1.numpy(), var2.numpy()], [-0.125, -0.125])
<ide>
<ide> def testGetAndFromConfig(self):
<ide> optimizer = adam_new.Adam( | 2 |
PHP | PHP | fix some formatting issues | 29198f4c1f5bbf0c800e760436e9d13ce5c9fe89 | <ide><path>src/Illuminate/Foundation/Auth/ResetsPasswords.php
<ide> trait ResetsPasswords
<ide> {
<ide> use RedirectsUsers;
<ide>
<del> /**
<del> * Get the broker to be used during resetting the password.
<del> *
<del> * @return string|null
<del> */
<del> public function getBroker()
<del> {
<del> return property_exists($this, 'broker') ? $this->broker : null;
<del> }
<del>
<del> /**
<del> * Get the guard to be used during authentication.
<del> *
<del> * @return string|null
<del> */
<del> protected function getGuard()
<del> {
<del> return property_exists($this, 'guard') ? $this->guard : null;
<del> }
<del>
<ide> /**
<ide> * Display the form to request a password reset link.
<ide> *
<ide> public function sendResetLinkEmail(Request $request)
<ide> {
<ide> $this->validate($request, ['email' => 'required|email']);
<ide>
<del> $response = Password::broker($this->getBroker())->sendResetLink($request->only('email'), function (Message $message) {
<add> $broker = $this->getBroker();
<add>
<add> $response = Password::broker($broker)->sendResetLink($request->only('email'), function (Message $message) {
<ide> $message->subject($this->getEmailSubject());
<ide> });
<ide>
<ide> public function reset(Request $request)
<ide> 'email', 'password', 'password_confirmation', 'token'
<ide> );
<ide>
<del> $response = Password::broker($this->getBroker())->reset($credentials, function ($user, $password) {
<add> $broker = $this->getBroker();
<add>
<add> $response = Password::broker($broker)->reset($credentials, function ($user, $password) {
<ide> $this->resetPassword($user, $password);
<ide> });
<ide>
<ide> protected function getResetFailureResponse(Request $request, $response)
<ide> ->withInput($request->only('email'))
<ide> ->withErrors(['email' => trans($response)]);
<ide> }
<add>
<add> /**
<add> * Get the broker to be used during password reset.
<add> *
<add> * @return string|null
<add> */
<add> public function getBroker()
<add> {
<add> return property_exists($this, 'broker') ? $this->broker : null;
<add> }
<add>
<add> /**
<add> * Get the guard to be used during password reset.
<add> *
<add> * @return string|null
<add> */
<add> protected function getGuard()
<add> {
<add> return property_exists($this, 'guard') ? $this->guard : null;
<add> }
<ide> } | 1 |
Go | Go | skip some tests for e2e | f089a1df393228085c4895b8db0fa95128173398 | <ide><path>integration-cli/docker_api_build_test.go
<ide> import (
<ide> )
<ide>
<ide> func (s *DockerSuite) TestBuildAPIDockerFileRemote(c *check.C) {
<del> testRequires(c, NotUserNamespace)
<add> // E2E: Requires built httpserver.
<add> testRequires(c, NotUserNamespace, NotE2E)
<add>
<ide> var testD string
<ide> if testEnv.DaemonPlatform() == "windows" {
<ide> testD = `FROM busybox
<ide> RUN find /tmp/`
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildAPIRemoteTarballContext(c *check.C) {
<add> // E2E: Requires built httpserver.
<add> testRequires(c, NotE2E)
<add>
<ide> buffer := new(bytes.Buffer)
<ide> tw := tar.NewWriter(buffer)
<ide> defer tw.Close()
<ide> func (s *DockerSuite) TestBuildAPIRemoteTarballContext(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildAPIRemoteTarballContextWithCustomDockerfile(c *check.C) {
<add> // E2E: Requires built httpserver.
<add> testRequires(c, NotE2E)
<add>
<ide> buffer := new(bytes.Buffer)
<ide> tw := tar.NewWriter(buffer)
<ide> defer tw.Close()
<ide> RUN echo 'right'
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildAPILowerDockerfile(c *check.C) {
<add> // E2E: Requires built httpserver.
<add> testRequires(c, NotE2E)
<ide> git := fakegit.New(c, "repo", map[string]string{
<ide> "dockerfile": `FROM busybox
<ide> RUN echo from dockerfile`,
<ide> RUN echo from dockerfile`,
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildAPIBuildGitWithF(c *check.C) {
<add> // E2E: Test requires go and contrib source.
<add> testRequires(c, NotE2E)
<add>
<ide> git := fakegit.New(c, "repo", map[string]string{
<ide> "baz": `FROM busybox
<ide> RUN echo from baz`,
<ide> RUN echo from Dockerfile`,
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildAPIDoubleDockerfile(c *check.C) {
<del> testRequires(c, UnixCli) // dockerfile overwrites Dockerfile on Windows
<add> // E2E: Requires built httpserver.
<add> testRequires(c, UnixCli, NotE2E) // dockerfile overwrites Dockerfile on Windows
<ide> git := fakegit.New(c, "repo", map[string]string{
<ide> "Dockerfile": `FROM busybox
<ide> RUN echo from Dockerfile`,
<ide> func (s *DockerRegistrySuite) TestBuildCopyFromForcePull(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildAddRemoteNoDecompress(c *check.C) {
<add> // E2E: Requires built httpserver.
<add> testRequires(c, NotE2E)
<add>
<ide> buffer := new(bytes.Buffer)
<ide> tw := tar.NewWriter(buffer)
<ide> dt := []byte("contents")
<ide><path>integration-cli/docker_api_containers_test.go
<ide> func (s *DockerSuite) TestPutContainerArchiveErrSymlinkInVolumeToReadOnlyRootfs(
<ide> }
<ide>
<ide> func (s *DockerSuite) TestContainerAPIGetContainersJSONEmpty(c *check.C) {
<add> // E2E: Test assumes no other containers running.
<add> testRequires(c, NotE2E)
<add>
<ide> cli, err := client.NewEnvClient()
<ide> c.Assert(err, checker.IsNil)
<ide> defer cli.Close()
<ide><path>integration-cli/docker_api_images_test.go
<ide> func (s *DockerSuite) TestAPIImagesHistory(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestAPIImagesImportBadSrc(c *check.C) {
<del> testRequires(c, Network)
<add> // E2E: Test runs local HTTP server.
<add> testRequires(c, Network, NotE2E)
<ide>
<ide> server := httptest.NewServer(http.NewServeMux())
<ide> defer server.Close()
<ide><path>integration-cli/docker_cli_attach_unix_test.go
<ide> func (s *DockerSuite) TestAttachDetach(c *check.C) {
<ide> c.Assert(running, checker.Equals, "true", check.Commentf("expected container to still be running"))
<ide>
<ide> go func() {
<del> dockerCmd(c, "kill", id)
<add> dockerCmdWithResult("kill", id)
<ide> }()
<ide>
<ide> select {
<ide> func (s *DockerSuite) TestAttachDetachTruncatedID(c *check.C) {
<ide> c.Assert(running, checker.Equals, "true", check.Commentf("expected container to still be running"))
<ide>
<ide> go func() {
<del> dockerCmd(c, "kill", id)
<add> dockerCmdWithResult("kill", id)
<ide> }()
<ide>
<ide> select {
<ide><path>integration-cli/docker_cli_build_test.go
<ide> ONBUILD ENTRYPOINT ["echo"]`))
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildCacheAdd(c *check.C) {
<del> testRequires(c, DaemonIsLinux) // Windows doesn't have httpserver image yet
<add> // E2E: Requires built httpserver.
<add> testRequires(c, DaemonIsLinux, NotE2E) // Windows doesn't have httpserver image yet
<ide> name := "testbuildtwoimageswithadd"
<ide> server := fakestorage.New(c, "", fakecontext.WithFiles(map[string]string{
<ide> "robots.txt": "hello",
<ide> func (s *DockerSuite) TestBuildCacheAdd(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildLastModified(c *check.C) {
<add> // E2E: Requires built httpserver.
<add> testRequires(c, NotE2E)
<add>
<ide> // Temporary fix for #30890. TODO @jhowardmsft figure out what
<ide> // has changed in the master busybox image.
<ide> testRequires(c, DaemonIsLinux)
<ide> RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio'
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildCopyAddMultipleFiles(c *check.C) {
<del> testRequires(c, DaemonIsLinux) // Linux specific test
<add> // E2E: Requires built httpserver.
<add> testRequires(c, DaemonIsLinux, NotE2E) // Linux specific test
<ide> server := fakestorage.New(c, "", fakecontext.WithFiles(map[string]string{
<ide> "robots.txt": "hello",
<ide> }))
<ide> RUN find "test6" "C:/test dir/test_file6"`
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildCopyWildcard(c *check.C) {
<add> // E2E: Requires built httpserver.
<add> testRequires(c, NotE2E)
<add>
<ide> name := "testcopywildcard"
<ide> server := fakestorage.New(c, "", fakecontext.WithFiles(map[string]string{
<ide> "robots.txt": "hello",
<ide> func (s *DockerSuite) TestBuildAddCurrentDirWithoutCache(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildAddRemoteFileWithAndWithoutCache(c *check.C) {
<add> // E2E: Requires built httpserver.
<add> testRequires(c, NotE2E)
<add>
<ide> name := "testbuildaddremotefilewithcache"
<ide> server := fakestorage.New(c, "", fakecontext.WithFiles(map[string]string{
<ide> "baz": "hello",
<ide> func (s *DockerSuite) TestBuildAddRemoteFileWithAndWithoutCache(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildAddRemoteFileMTime(c *check.C) {
<add> // E2E: Requires built httpserver.
<add> testRequires(c, NotE2E)
<add>
<ide> name := "testbuildaddremotefilemtime"
<ide> name2 := name + "2"
<ide> name3 := name + "3"
<ide> func (s *DockerSuite) TestBuildAddRemoteFileMTime(c *check.C) {
<ide>
<ide> // FIXME(vdemeester) this really seems to test the same thing as before (combined)
<ide> func (s *DockerSuite) TestBuildAddLocalAndRemoteFilesWithAndWithoutCache(c *check.C) {
<add> // E2E: Requires built httpserver.
<add> testRequires(c, NotE2E)
<add>
<ide> name := "testbuildaddlocalandremotefilewithcache"
<ide> server := fakestorage.New(c, "", fakecontext.WithFiles(map[string]string{
<ide> "baz": "hello",
<ide> func (s *DockerSuite) TestBuildFromGitWithF(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildFromRemoteTarball(c *check.C) {
<add> // E2E: Requires built httpserver.
<add> testRequires(c, NotE2E)
<add>
<ide> name := "testbuildfromremotetarball"
<ide>
<ide> buffer := new(bytes.Buffer)
<ide> func (s *DockerSuite) TestBuildFromMixedcaseDockerfile(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildFromURLWithF(c *check.C) {
<add> // E2E: Requires built httpserver.
<add> testRequires(c, NotE2E)
<add>
<ide> server := fakestorage.New(c, "", fakecontext.WithFiles(map[string]string{"baz": `FROM busybox
<ide> RUN echo from baz
<ide> COPY * /tmp/
<ide><path>integration-cli/docker_cli_build_unix_test.go
<ide> import (
<ide> )
<ide>
<ide> func (s *DockerSuite) TestBuildResourceConstraintsAreUsed(c *check.C) {
<del> testRequires(c, cpuCfsQuota)
<add> // E2E: Test assumes no other containers running.
<add> testRequires(c, cpuCfsQuota, NotE2E)
<ide> name := "testbuildresourceconstraints"
<ide>
<ide> ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(`
<ide><path>integration-cli/docker_cli_network_unix_test.go
<ide> func (s *DockerNetworkSuite) TestDockerNetworkLsDefault(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestNetworkLsFormat(c *check.C) {
<del> testRequires(c, DaemonIsLinux)
<add> // E2E: Test assumes only default networks.
<add> testRequires(c, DaemonIsLinux, NotE2E)
<ide> out, _ := dockerCmd(c, "network", "ls", "--format", "{{.Name}}")
<ide> lines := strings.Split(strings.TrimSpace(string(out)), "\n")
<ide>
<ide> func (s *DockerSuite) TestNetworkLsFormat(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestNetworkLsFormatDefaultFormat(c *check.C) {
<del> testRequires(c, DaemonIsLinux)
<add> // E2E: Test assumes only default networks.
<add> testRequires(c, DaemonIsLinux, NotE2E)
<ide>
<ide> config := `{
<ide> "networksFormat": "{{ .Name }} default"
<ide><path>integration-cli/docker_cli_ps_test.go
<ide> func (s *DockerSuite) TestPsRightTagName(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestPsLinkedWithNoTrunc(c *check.C) {
<add> // E2E: Test assumes no other containers.
<ide> // Problematic on Windows as it doesn't support links as of Jan 2016
<del> testRequires(c, DaemonIsLinux)
<add> testRequires(c, DaemonIsLinux, NotE2E)
<ide> runSleepingContainer(c, "--name=first")
<ide> runSleepingContainer(c, "--name=second", "--link=first:first")
<ide>
<ide> func (s *DockerSuite) TestPsNamesMultipleTime(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestPsFormatHeaders(c *check.C) {
<add> // E2E: Test assumes no other containers.
<add> testRequires(c, NotE2E)
<add>
<ide> // make sure no-container "docker ps" still prints the header row
<ide> out, _ := dockerCmd(c, "ps", "--format", "table {{.ID}}")
<ide> c.Assert(out, checker.Equals, "CONTAINER ID\n", check.Commentf(`Expected 'CONTAINER ID\n', got %v`, out)) | 8 |
Ruby | Ruby | make use of the inherited initializer | a5f57a7ef2af05ac1f7b919040e10c1b21de8e56 | <ide><path>actionpack/lib/action_dispatch/routing/mapper.rb
<ide> class SingletonResource < Resource #:nodoc:
<ide> DEFAULT_ACTIONS = [:show, :create, :update, :destroy, :new, :edit]
<ide>
<ide> def initialize(entities, options)
<add> super
<add>
<ide> @as = nil
<del> @name = entities.to_s
<del> @path = (options[:path] || @name).to_s
<ide> @controller = (options[:controller] || plural).to_s
<ide> @as = options[:as]
<del> @options = options
<ide> end
<ide>
<ide> def plural | 1 |
Ruby | Ruby | exclude hardlinks from mach_o_files | 3e5e14a59580325faf397b48d62a52f0013a17f2 | <ide><path>Library/Homebrew/keg_relocate.rb
<ide> def find_dylib(bad_name)
<ide> end
<ide>
<ide> def mach_o_files
<add> hardlinks = Set.new
<ide> mach_o_files = []
<ide> path.find do |pn|
<add> # if we've already processed a file, ignore its hardlinks (which have the same dev ID and inode)
<add> # this prevents relocations from being performed on a binary more than once
<add> next unless hardlinks.add? [pn.stat.dev, pn.stat.ino]
<ide> next if pn.symlink? || pn.directory?
<ide> mach_o_files << pn if pn.dylib? || pn.mach_o_bundle? || pn.mach_o_executable?
<ide> end | 1 |
Python | Python | add test cases for it, update docstring | 0eb48647e520ed61fa5f473f3b540be9885c3861 | <ide><path>libcloud/compute/drivers/gce.py
<ide> def _build_service_accounts_gce_list(self, service_accounts=None,
<ide> accepts the aliases defined in
<ide> 'gcloud compute'.
<ide>
<del> :type service_accounts: ``list`` of ``dict`` or None
<add> :type service_accounts: ``list`` of ``dict``, ``None`` or an empty
<add> list. ``None` means use a default service
<add> account and an empty list indicates no
<add> service account.
<ide>
<ide> :return: list of dictionaries usable in the GCE API.
<ide> :rtype: ``list`` of ``dict``
<ide><path>libcloud/test/compute/test_gce.py
<ide> def setUp(self):
<ide> def test_default_scopes(self):
<ide> self.assertIsNone(self.driver.scopes)
<ide>
<add> def test_default_service_account(self):
<add> result = self.driver._build_service_accounts_gce_list(service_accounts=None)
<add> self.assertEqual(result, [
<add> {'email': 'default',
<add> 'scopes': ['https://www.googleapis.com/auth/devstorage.read_only']
<add> }
<add> ])
<add>
<add> def test_no_service_account(self):
<add> result = self.driver._build_service_accounts_gce_list(service_accounts=[])
<add> self.assertEqual(result, [])
<add>
<ide> def test_timestamp_to_datetime(self):
<ide> timestamp1 = '2013-06-26T10:05:19.340-07:00'
<ide> datetime1 = datetime.datetime(2013, 6, 26, 17, 5, 19) | 2 |
Javascript | Javascript | replace double quotes with single quotes | e64c9ba077a13a5e493543a7041a090960528595 | <ide><path>packages/ember-application/lib/system/application.js
<ide> import LinkToComponent from 'ember-routing-views/views/link';
<ide> import RoutingService from 'ember-routing/services/routing';
<ide> import ContainerDebugAdapter from 'ember-extension-support/container_debug_adapter';
<ide> import { _loaded } from 'ember-runtime/system/lazy_load';
<del>import RegistryProxy from "ember-runtime/mixins/registry_proxy";
<add>import RegistryProxy from 'ember-runtime/mixins/registry_proxy';
<ide> import environment from 'ember-metal/environment';
<ide>
<ide> function props(obj) {
<ide> var Application = Namespace.extend(RegistryProxy, {
<ide> this._runInitializer('initializers', function(name, initializer) {
<ide> Ember.assert('No application initializer named \'' + name + '\'', !!initializer);
<ide> if (initializer.initialize.length === 2) {
<del> Ember.deprecate("The `initialize` method for Application initializer '" + name + "' should take only one argument - `App`, an instance of an `Application`.");
<add> Ember.deprecate('The `initialize` method for Application initializer \'' + name + '\' should take only one argument - `App`, an instance of an `Application`.');
<ide> initializer.initialize(App.__registry__, App);
<ide> } else {
<ide> initializer.initialize(App);
<ide><path>packages/ember-application/tests/system/initializers_test.js
<ide> QUnit.test('initializers require proper \'name\' and \'initialize\' properties',
<ide> });
<ide> });
<ide>
<del>QUnit.test("initializers are passed an App", function() {
<add>QUnit.test('initializers are passed an App', function() {
<ide> var MyApplication = Application.extend();
<ide>
<ide> MyApplication.initializer({
<ide> name: 'initializer',
<ide> initialize(App) {
<del> ok(App instanceof Application, "initialize is passed an Application");
<add> ok(App instanceof Application, 'initialize is passed an Application');
<ide> }
<ide> });
<ide>
<ide> QUnit.test('initializers should be executed in their own context', function() {
<ide> });
<ide> });
<ide>
<del>QUnit.test("initializers should throw a deprecation warning when receiving a second argument", function() {
<add>QUnit.test('initializers should throw a deprecation warning when receiving a second argument', function() {
<ide> expect(1);
<ide>
<ide> var MyApplication = Application.extend();
<ide><path>packages/ember-application/tests/system/reset_test.js
<ide> QUnit.test('With ember-data like initializer and constant', function() {
<ide> };
<ide>
<ide> Application.initializer({
<del> name: "store",
<add> name: 'store',
<ide> initialize(application) {
<ide> application.unregister('store:main');
<ide> application.register('store:main', application.Store);
<ide><path>packages/ember/tests/default_initializers_test.js
<ide> QUnit.test('Default objects are registered', function(assert) {
<ide> App.instanceInitializer({
<ide> name: 'test',
<ide> initialize(instance) {
<del> assert.strictEqual(instance.resolveRegistration("component:-text-field"), TextField, "TextField was registered");
<del> assert.strictEqual(instance.resolveRegistration("component:-checkbox"), Checkbox, "Checkbox was registered");
<add> assert.strictEqual(instance.resolveRegistration('component:-text-field'), TextField, 'TextField was registered');
<add> assert.strictEqual(instance.resolveRegistration('component:-checkbox'), Checkbox, 'Checkbox was registered');
<ide> }
<ide> });
<ide> | 4 |
Go | Go | fix typo in api/types/client.go | c8fd28f12e501c3ba1bea9d380a38f4af8319a41 | <ide><path>api/types/client.go
<ide> type ImageBuildOptions struct {
<ide> Dockerfile string
<ide> Ulimits []*units.Ulimit
<ide> // See the parsing of buildArgs in api/server/router/build/build_routes.go
<del> // for an explaination of why BuildArgs needs to use *string instead of
<add> // for an explanation of why BuildArgs needs to use *string instead of
<ide> // just a string
<ide> BuildArgs map[string]*string
<ide> AuthConfigs map[string]AuthConfig | 1 |
Javascript | Javascript | improve long buffer test | 3e9f636b648e334d7d25fa848f89df024ed563b6 | <ide><path>lib/buffer.js
<ide> function Buffer (subject, encoding, offset) {
<ide> return new Buffer(subject, encoding, offset);
<ide> }
<ide>
<del> var length, type;
<add> var type;
<ide>
<ide> // Are we slicing?
<ide> if (typeof offset === 'number') {
<ide> function Buffer (subject, encoding, offset) {
<ide> // Find the length
<ide> switch (type = typeof subject) {
<ide> case 'number':
<del> length = subject;
<add> this.length = subject;
<ide> break;
<ide>
<ide> case 'string':
<del> length = Buffer.byteLength(subject, encoding);
<add> this.length = Buffer.byteLength(subject, encoding);
<ide> break;
<ide>
<ide> case 'object': // Assume object is an array
<del> length = subject.length;
<add> this.length = subject.length;
<ide> break;
<ide>
<ide> default:
<ide> throw new Error("First argument need to be an number, array or string.");
<ide> }
<ide>
<del> this.length = length;
<del>
<del> if (length > Buffer.poolSize) {
<add> if (this.length > Buffer.poolSize) {
<ide> // Big buffer, just alloc one.
<ide> this.parent = new SlowBuffer(subject, encoding);
<ide> this.offset = 0;
<ide>
<ide> } else {
<ide> // Small buffer.
<del> if (!pool || pool.length - pool.used < length) allocPool();
<add> if (!pool || pool.length - pool.used < this.length) allocPool();
<ide> this.parent = pool;
<ide> this.offset = pool.used;
<del> pool.used += length;
<add> pool.used += this.length;
<ide>
<ide> // Do we need to write stuff?
<ide> if (type !== 'number') {
<ide> // Assume object is an array
<ide> if (type === 'object') {
<del> for (var i = 0; i < length; i++) {
<add> for (var i = 0; i < this.length; i++) {
<ide> this.parent[i + this.offset] = subject[i];
<ide> }
<ide> } else {
<ide><path>test/simple/test-buffer.js
<ide> assert.equal(dot.toString('base64'), '//4uAA==');
<ide>
<ide>
<ide> // Creating buffers larger than pool size.
<add>l = Buffer.poolSize + 5;
<ide> s = ""
<del>for (i = 0; i < Buffer.poolSize + 5; i++) {
<add>for (i = 0; i < l; i++) {
<ide> s += "h";
<ide> }
<del>b = Buffer(s);
<del>sb = b.toString();
<del>assert.equal(sb, s);
<del>
<del>
<del>
<ide>
<add>b = Buffer(s);
<ide>
<add>for (i = 0; l; i++) {
<add> assert.equal("h".charCodeAt(i), b[i], "index " + i + " is not 'h' it was " + b[i]);
<add>}
<ide>
<add>sb = b.toString();
<add>assert.equal(sb.length, s.length);
<add>assert.equal(sb, s); | 2 |
Javascript | Javascript | use $animate.$$setclassimmediately to save code | c44fc6d811e3b6fd4deae90c2a02bed19210190c | <ide><path>src/ng/animate.js
<ide> var $AnimateProvider = ['$provide', function($provide) {
<ide> return defer.promise;
<ide> }
<ide>
<del> function resolveElementClasses(element, cache) {
<add> function resolveElementClasses(element, classes) {
<ide> var toAdd = [], toRemove = [];
<ide>
<ide> var hasClasses = createMap();
<ide> forEach((element.attr('class') || '').split(/\s+/), function(className) {
<ide> hasClasses[className] = true;
<ide> });
<ide>
<del> forEach(cache.classes, function(status, className) {
<add> forEach(classes, function(status, className) {
<ide> var hasClass = hasClasses[className];
<ide>
<ide> // If the most recent class manipulation (via $animate) was to remove the class, and the
<ide> var $AnimateProvider = ['$provide', function($provide) {
<ide> * @param {string} remove the CSS class which will be removed from the element
<ide> * @return {Promise} the animation callback promise
<ide> */
<del> setClass : function(element, add, remove, runSynchronously) {
<add> setClass : function(element, add, remove) {
<ide> var self = this;
<ide> var STORAGE_KEY = '$$animateClasses';
<ide> var createdCache = false;
<ide> element = jqLite(element);
<ide>
<del> if (runSynchronously) {
<del> // TODO(@caitp/@matsko): Remove undocumented `runSynchronously` parameter, and always
<del> // perform DOM manipulation asynchronously or in postDigest.
<del> self.$$addClassImmediately(element, add);
<del> self.$$removeClassImmediately(element, remove);
<del> return asyncPromise();
<del> }
<del>
<ide> var cache = element.data(STORAGE_KEY);
<ide> if (!cache) {
<ide> cache = {
<ide> var $AnimateProvider = ['$provide', function($provide) {
<ide> var cache = element.data(STORAGE_KEY);
<ide> element.removeData(STORAGE_KEY);
<ide>
<del> var classes = cache && resolveElementClasses(element, cache);
<del>
<del> if (classes) {
<del> if (classes[0]) self.$$addClassImmediately(element, classes[0]);
<del> if (classes[1]) self.$$removeClassImmediately(element, classes[1]);
<add> // in the event that the element is removed before postDigest
<add> // is run then the cache will be undefined and there will be
<add> // no need anymore to add or remove and of the element classes
<add> if (cache) {
<add> var classes = resolveElementClasses(element, cache.classes);
<add> if (classes) {
<add> self.$$setClassImmediately(element, classes[0], classes[1]);
<add> }
<ide> }
<ide>
<ide> done();
<ide> var $AnimateProvider = ['$provide', function($provide) {
<ide> return cache.promise;
<ide> },
<ide>
<add> $$setClassImmediately : function(element, add, remove) {
<add> add && this.$$addClassImmediately(element, add);
<add> remove && this.$$removeClassImmediately(element, remove);
<add> return asyncPromise();
<add> },
<add>
<ide> enabled : noop,
<ide> cancel : noop
<ide> };
<ide><path>src/ngAnimate/animate.js
<ide> angular.module('ngAnimate', ['ng'])
<ide> // TODO(@caitp/@matsko): Don't use private/undocumented API here --- we should not be
<ide> // changing the DOM synchronously in this case. The `true` parameter must eventually be
<ide> // removed.
<del> return $delegate.setClass(element, add, remove, true);
<add> return $delegate.$$setClassImmediately(element, add, remove);
<ide> }
<ide>
<ide> // we're using a combined array for both the add and remove | 2 |
Ruby | Ruby | fix version parsing on urls with no extensions | e865cee3d33e38485a46e1b88f8aa9466f31633f | <ide><path>Library/Homebrew/test/test_versions.rb
<ide> def test_opam_version
<ide> assert_version_detected "1.0.2",
<ide> "https://opam.ocaml.org/archives/easy-format.1.0.2+opam.tar.gz"
<ide> end
<add>
<add> def test_waf_version
<add> assert_version_detected "1.8.12", "https://waf.io/waf-1.8.12"
<add> end
<ide> end
<ide><path>Library/Homebrew/version.rb
<ide> def self._parse(spec)
<ide> m = /[-_]((?:\d+\.)*\d\.\d+-(?:p|rc|RC)?\d+)(?:[-._](?:bin|dist|stable|src|sources))?$/.match(stem)
<ide> return m.captures.first unless m.nil?
<ide>
<add> # URL with no extension e.g. https://waf.io/waf-1.8.12
<add> m = /-((?:\d+\.)*\d+)$/.match(spec_s)
<add> return m.captures.first unless m.nil?
<add>
<ide> # e.g. lame-398-1
<ide> m = /-((?:\d)+-\d)/.match(stem)
<ide> return m.captures.first unless m.nil? | 2 |
Text | Text | add use of alt text "line 15" | f44afe49acff00f5a2dcee60e61558308ed7ab02 | <ide><path>guide/english/html/tutorials/images-in-html/index.md
<ide> title: Images in HTML
<ide> ---
<ide>
<del>
<ide> ## Introduction
<ide>
<ide> You can define images by using the `<img>` tag. It does not have a closing tag since it can contain only attributes.
<ide> To insert an image you define the source and an alternative text wich is displayed when the image can not be rendered.
<ide>
<ide> `src` - This attribute provides the url to image present either on your desktop/laptop or to be included from some other website. Remember the link provided should not be broken otherwise the image will not be produced on your webpage.
<ide>
<del>`alt` - This attribute is used to overcome the problem of broken image or incapability of your browser to not being able to produce image on webpage. This attribute as name suggests provide "alternative" to image which is some text describing the image.
<add>`alt` - This attribute is used to overcome the problem of broken image or incapability of your browser to not being able to produce image on webpage. This attribute as name suggests provide "alternative" to image which is some text describing the image. It is also used by screen reader applications to read the web page content, which is very helpful for visually impaired users.
<ide>
<ide> ### Example
<ide> | 1 |
Javascript | Javascript | hoist require.resolve for performance reasons | 35547246f9aa62d155074a75292ba7c1892156aa | <ide><path>lib/NodeStuffPlugin.js
<ide> const ModuleDependency = require("./dependencies/ModuleDependency");
<ide> /** @typedef {import("./DependencyTemplates")} DependencyTemplates */
<ide> /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
<ide>
<add>const moduleBuildin = require.resolve("../buildin/module.js");
<add>const harmonyModuleBuildin = require.resolve("../buildin/harmony-module.js");
<add>
<ide> class NodeStuffPlugin {
<ide> constructor(options) {
<ide> this.options = options;
<ide> class NodeStuffPlugin {
<ide> const dep = new ModuleDecoratorDependency(
<ide> getModulePath(
<ide> parser.state.module.context,
<del> require.resolve(
<del> isHarmony
<del> ? "../buildin/harmony-module.js"
<del> : "../buildin/module.js"
<del> )
<add> isHarmony ? harmonyModuleBuildin : moduleBuildin
<ide> ),
<ide> parser.state.module,
<ide> expr.range
<ide><path>lib/dependencies/SystemPlugin.js
<ide> const {
<ide> } = require("../JavascriptParserHelpers");
<ide> const WebpackError = require("../WebpackError");
<ide> const ProvidedDependency = require("./ProvidedDependency");
<add>const systemBuildin = require.resolve("../../buildin/system");
<ide>
<ide> class SystemPlugin {
<ide> constructor(options) {
<ide> class SystemPlugin {
<ide>
<ide> parser.hooks.expression.for("System").tap("SystemPlugin", expr => {
<ide> const dep = new ProvidedDependency(
<del> getModulePath(
<del> parser.state.module.context,
<del> require.resolve("../../buildin/system")
<del> ),
<add> getModulePath(parser.state.module.context, systemBuildin),
<ide> "System",
<ide> null,
<ide> expr.range | 2 |
Text | Text | update stackoverflow link | fa5e8485abcc1a85af04aae42fd1045baeaeeb97 | <ide><path>CONTRIBUTING.md
<ide> Please report unacceptable behavior to spring-code-of-conduct@pivotal.io.
<ide> #### Discuss
<ide>
<ide> If you have a question, check Stack Overflow using
<del>[this list of tags](https://spring.io/questions), organized by Spring project.
<add>[this list of tags](https://stackoverflow.com/questions/tagged/spring+or+spring-mvc+or+spring-aop+or+spring-jdbc+or+spring-transactions+or+spring-annotations+or+spring-jms+or+spring-el+or+spring-test+or+spring+or+spring-remoting+or+spring-orm+or+spring-jmx+or+spring-cache+or+spring-webflux?tab=Newest).
<ide> Find an existing discussion, or start a new one if necessary.
<ide>
<ide> If you believe there is an issue, search through | 1 |
Python | Python | handle image_embeds in viltmodel | 7f7300856d62f1d27332d8b893280ecb234601d0 | <ide><path>src/transformers/models/vilt/modeling_vilt.py
<ide> def _set_gradient_checkpointing(self, module, value=False):
<ide> is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
<ide> model's internal embedding lookup matrix.
<ide>
<del> image_embeds (`torch.FloatTensor` of shape `(batch_size, num_patches, hidden_size)`, *optional*):
<add> image_embeds (`torch.FloatTensor` of shape `(batch_size, num_images, num_patches, hidden_size)`, *optional*):
<ide> Optionally, instead of passing `pixel_values`, you can choose to directly pass an embedded representation.
<ide> This is useful if you want more control over how to convert `pixel_values` into patch embeddings.
<ide>
<ide> def forward(
<ide> else:
<ide> raise ValueError("You have to specify either input_ids or inputs_embeds")
<ide>
<del> batch_size, seq_length = input_shape
<add> text_batch_size, seq_length = input_shape
<ide> device = input_ids.device if input_ids is not None else inputs_embeds.device
<ide>
<ide> if attention_mask is None:
<del> attention_mask = torch.ones(((batch_size, seq_length)), device=device)
<add> attention_mask = torch.ones(((text_batch_size, seq_length)), device=device)
<ide>
<del> if pixel_values is None:
<del> raise ValueError("You have to specify pixel_values")
<add> if pixel_values is not None and image_embeds is not None:
<add> raise ValueError("You cannot specify both pixel_values and image_embeds at the same time")
<add> elif pixel_values is None and image_embeds is None:
<add> raise ValueError("You have to specify either pixel_values or image_embeds")
<ide>
<del> batch_size, num_channels, height, width = pixel_values.shape
<add> image_batch_size = pixel_values.shape[0] if pixel_values is not None else image_embeds.shape[0]
<add> if image_batch_size != text_batch_size:
<add> raise ValueError("The text inputs and image inputs need to have the same batch size")
<ide> if pixel_mask is None:
<del> pixel_mask = torch.ones(((batch_size, height, width)), device=device)
<add> pixel_mask = torch.ones((image_batch_size, self.config.image_size, self.config.image_size), device=device)
<ide>
<ide> # Prepare head mask if needed
<ide> # 1.0 in head_mask indicate we keep the head
<ide> def forward(
<ide> )
<ide> return_dict = return_dict if return_dict is not None else self.config.use_return_dict
<ide>
<del> if pixel_values.ndim == 4:
<add> if pixel_values is not None and pixel_values.ndim == 4:
<ide> # add dummy num_images dimension
<ide> pixel_values = pixel_values.unsqueeze(1)
<ide>
<del> num_images = pixel_values.shape[1]
<add> if image_embeds is not None and image_embeds.ndim == 3:
<add> # add dummy num_images dimension
<add> image_embeds = image_embeds.unsqueeze(1)
<add>
<add> num_images = pixel_values.shape[1] if pixel_values is not None else None
<add> if num_images is None:
<add> num_images = image_embeds.shape[1] if image_embeds is not None else None
<ide> if num_images != self.config.num_images:
<ide> raise ValueError(
<ide> "Make sure to match the number of images in the model with the number of images in the input."
<ide> def forward(
<ide> input_ids,
<ide> attention_mask=attention_mask,
<ide> token_type_ids=token_type_ids,
<del> pixel_values=pixel_values[:, i, :, :, :],
<add> pixel_values=pixel_values[:, i, :, :, :] if pixel_values is not None else None,
<ide> pixel_mask=pixel_mask[:, i, :, :] if pixel_mask is not None else None,
<ide> head_mask=head_mask,
<ide> inputs_embeds=inputs_embeds,
<del> image_embeds=image_embeds,
<add> image_embeds=image_embeds[:, i, :, :] if image_embeds is not None else None,
<ide> image_token_type_idx=i + 1,
<ide> output_attentions=output_attentions,
<ide> output_hidden_states=output_hidden_states, | 1 |
Go | Go | propagate getcontainer error from event processor | 54e30a62d3ca39c912c8e291e80cfbf80860d607 | <ide><path>daemon/monitor.go
<ide> package daemon // import "github.com/docker/docker/daemon"
<ide>
<ide> import (
<ide> "context"
<del> "errors"
<del> "fmt"
<ide> "runtime"
<ide> "strconv"
<ide> "time"
<ide> import (
<ide> "github.com/docker/docker/container"
<ide> libcontainerdtypes "github.com/docker/docker/libcontainerd/types"
<ide> "github.com/docker/docker/restartmanager"
<add> "github.com/pkg/errors"
<ide> "github.com/sirupsen/logrus"
<ide> )
<ide>
<ide> func (daemon *Daemon) setStateCounter(c *container.Container) {
<ide> // ProcessEvent is called by libcontainerd whenever an event occurs
<ide> func (daemon *Daemon) ProcessEvent(id string, e libcontainerdtypes.EventType, ei libcontainerdtypes.EventInfo) error {
<ide> c, err := daemon.GetContainer(id)
<del> if c == nil || err != nil {
<del> return fmt.Errorf("no such container: %s", id)
<add> if err != nil {
<add> return errors.Wrapf(err, "could not find container %s", id)
<ide> }
<ide>
<ide> switch e { | 1 |
Text | Text | fix typo in n-api introduction | eb32e383d89d5f0757129127d9983756b5202a12 | <ide><path>doc/api/n-api.md
<ide>
<ide> N-API (pronounced N as in the letter, followed by API)
<ide> is an API for building native Addons. It is independent from
<del>the underlying JavaScript runtime (ex V8) and is maintained as part of
<add>the underlying JavaScript runtime (for example, V8) and is maintained as part of
<ide> Node.js itself. This API will be Application Binary Interface (ABI) stable
<ide> across versions of Node.js. It is intended to insulate Addons from
<ide> changes in the underlying JavaScript engine and allow modules | 1 |
Javascript | Javascript | remove some useless assignments | 366aaf57faa31a694f55d1e9c76765f2d396aaa1 | <ide><path>lib/events.js
<ide> function _addListener(target, type, listener, prepend) {
<ide>
<ide> if (existing === undefined) {
<ide> // Optimize the case of one listener. Don't need the extra array object.
<del> existing = events[type] = listener;
<add> events[type] = listener;
<ide> ++target._eventsCount;
<ide> } else {
<ide> if (typeof existing === 'function') {
<ide><path>lib/internal/readline.js
<ide> function* emitKeys(stream) {
<ide> s += (ch = yield);
<ide>
<ide> if (ch >= '0' && ch <= '9') {
<del> s += (ch = yield);
<add> s += yield;
<ide> }
<ide> }
<ide>
<ide><path>lib/net.js
<ide> function afterConnect(status, handle, req, readable, writable) {
<ide> return;
<ide> }
<ide>
<del> // Update handle if it was wrapped
<del> // TODO(indutny): assert that the handle is actually an ancestor of old one
<del> handle = self._handle;
<del>
<ide> debug('afterConnect');
<ide>
<ide> assert(self.connecting); | 3 |
Python | Python | pass value directly to last_modified | 7c271401b284e6fcc2040fffe317342e2a17a902 | <ide><path>flask/helpers.py
<ide> def send_file(filename_or_fp, mimetype=None, as_attachment=False,
<ide> (default), this value is set by
<ide> :meth:`~Flask.get_send_file_max_age` of
<ide> :data:`~flask.current_app`.
<del> :param last_modified: the Datetime object representing timestamp for when
<del> the input file was last modified.
<add> :param last_modified: set the ``Last-Modified`` header to this value,
<add> a :class:`~datetime.datetime` or timestamp.
<add> If a file was passed, this overrides its mtime.
<ide> """
<ide> mtime = None
<ide> if isinstance(filename_or_fp, string_types):
<ide> def send_file(filename_or_fp, mimetype=None, as_attachment=False,
<ide> rv = current_app.response_class(data, mimetype=mimetype, headers=headers,
<ide> direct_passthrough=True)
<ide>
<del> # if we know the file modification date, we can store it as
<del> # the time of the last modification.
<ide> if last_modified is not None:
<del> if PY2:
<del> rv.last_modified = int(last_modified.strftime("%s"))
<del> else:
<del> rv.last_modified = last_modified.timestamp()
<add> rv.last_modified = last_modified
<ide> elif mtime is not None:
<del> rv.last_modified = int(mtime)
<add> rv.last_modified = mtime
<ide>
<ide> rv.cache_control.public = True
<ide> if cache_timeout is None:
<ide><path>tests/test_helpers.py
<ide> def test_send_file_xsendfile(self, catch_deprecation_warnings):
<ide>
<ide> def test_send_file_last_modified(self):
<ide> app = flask.Flask(__name__)
<del> with app.test_request_context():
<del> dtm = datetime.datetime.now()
<del> rv = flask.send_file('static/index.html', last_modified=dtm)
<del> if PY2:
<del> assert rv.last_modified == int(dtm.strftime("%s"))
<del> else:
<del> assert rv.last_modified == dtm.timestamp()
<del> rv.close()
<add> last_modified = datetime.datetime(1999, 1, 1)
<add>
<add> @app.route('/')
<add> def index():
<add> return flask.send_file(StringIO("party like it's"), last_modified=last_modified)
<add>
<add> c = app.test_client()
<add> rv = c.get('/')
<add> assert rv.last_modified == last_modified
<ide>
<ide> def test_send_file_object(self):
<ide> app = flask.Flask(__name__) | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.