content_type stringclasses 8 values | main_lang stringclasses 7 values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
Ruby | Ruby | fix typo in test_arch_for_command | fe25e4f7ec27ba66ad6eab2e26c9567e2419cc81 | <ide><path>Library/Homebrew/test/test_utils.rb
<ide> def test_arch_for_command
<ide> if `sw_vers -productVersion` =~ /10\.(\d+)/ and $1.to_i >= 7
<ide> assert_equal 2, arches.length
<ide> assert arches.include?(:x86_64)
<del> elsif `sw_vers -productVersion` =~ /10\.(\d+)/ and $1.to_i = 6
<add> elsif `sw_vers -productVersion` =~ /10\.(\d+)/ and $1.to_i == 6
<ide> assert_equal 3, arches.length
<ide> assert arches.include?(:x86_64)
<ide> assert arches.include?(:ppc7400) | 1 |
Javascript | Javascript | extract getdevserverurl into reusable module | 7e100ac7a225bd5f03dc97a828f414b9f862e1ff | <ide><path>Libraries/Inspector/ElementProperties.js
<ide> var Text = require('Text');
<ide> var TouchableHighlight = require('TouchableHighlight');
<ide> var TouchableWithoutFeedback = require('TouchableWithoutFeedback');
<ide> var View = require('View');
<del>var {SourceCode} = require('NativeModules');
<ide> var {fetch} = require('fetch');
<ide>
<ide> var flattenStyle = require('flattenStyle');
<ide> var mapWithSeparator = require('mapWithSeparator');
<add>var getDevServer = require('getDevServer');
<ide>
<ide> var ElementProperties = React.createClass({
<ide> propTypes: {
<ide> var ElementProperties = React.createClass({
<ide> },
<ide>
<ide> _openFile: function(fileName: string, lineNumber: number) {
<del> var match = SourceCode.scriptURL && SourceCode.scriptURL.match(/^https?:\/\/.*?\//);
<del> var baseURL = match ? match[0] : 'http://localhost:8081/';
<del>
<del> fetch(baseURL + 'open-stack-frame', {
<add> fetch(getDevServer().url + 'open-stack-frame', {
<ide> method: 'POST',
<ide> body: JSON.stringify({file: fileName, lineNumber}),
<ide> });
<ide><path>Libraries/JavaScriptAppEngine/Initialization/ExceptionsManager.js
<ide> function reportException(e: Error, isFatal: bool) {
<ide> }
<ide>
<ide> function symbolicateAndUpdateStack(id, message, stack) {
<add> const getDevServer = require('getDevServer');
<ide> const {fetch} = require('fetch');
<del> const {SourceCode, ExceptionsManager} = require('NativeModules');
<del> const match = SourceCode.scriptURL && SourceCode.scriptURL.match(/^https?:\/\/.*?\//);
<del> const endpoint = (match && match[0] : 'http://localhost:8081/') + 'symbolicate';
<add> const {ExceptionsManager} = require('NativeModules');
<add> const devServer = getDevServer();
<add> if (!devServer.bundleLoadedFromServer) {
<add> return;
<add> }
<ide>
<del> fetch(endpoint, { method: 'POST', body: JSON.stringify({stack}) })
<add> fetch(devServer.url + 'symbolicate', { method: 'POST', body: JSON.stringify({stack}) })
<ide> .then(response => response.json())
<ide> .then(response =>
<ide> ExceptionsManager.updateExceptionMessage(message, response.stack, id))
<ide><path>Libraries/JavaScriptAppEngine/Initialization/getDevServer.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @providesModule getDevServer
<add> * @flow
<add> */
<add>'use strict';
<add>
<add>const {SourceCode} = require('NativeModules');
<add>
<add>let _cachedDevServerURL: ?string;
<add>const FALLBACK = 'http://localhost:8081/';
<add>
<add>type DevServerInfo = {
<add> url: string;
<add> bundleLoadedFromServer: boolean;
<add>};
<add>
<add>/**
<add> * Many RN development tools rely on the development server (packager) running
<add> * @return URL to packager with trailing slash
<add> */
<add>function getDevServer(): DevServerInfo {
<add> if (_cachedDevServerURL === undefined) {
<add> const match = SourceCode.scriptURL && SourceCode.scriptURL.match(/^https?:\/\/.*?\//);
<add> _cachedDevServerURL = match ? match[0] : null;
<add> }
<add>
<add> return {
<add> url: _cachedDevServerURL || FALLBACK,
<add> bundleLoadedFromServer: _cachedDevServerURL !== null,
<add> };
<add>}
<add>
<add>module.exports = getDevServer; | 3 |
Text | Text | fix minor typo in dgram.md | 771b2901daae2e4389d157c18bb0f6674a0a19a4 | <ide><path>doc/api/dgram.md
<ide> Note that specifying both a `'listening'` event listener and passing a
<ide> useful.
<ide>
<ide> The `options` object may contain an additional `exclusive` property that is
<del>use when using `dgram.Socket` objects with the [`cluster`] module. When
<add>used when using `dgram.Socket` objects with the [`cluster`] module. When
<ide> `exclusive` is set to `false` (the default), cluster workers will use the same
<ide> underlying socket handle allowing connection handling duties to be shared.
<ide> When `exclusive` is `true`, however, the handle is not shared and attempted | 1 |
Javascript | Javascript | fix comment support in sortedhtml helper | 86b33eb3f1360a4cefb5ebf522b6649f9c55db55 | <ide><path>test/BinderSpec.js
<ide> describe('Binder', function() {
<ide> $rootScope.$apply();
<ide> expect(sortedHtml(form)).toBe(
<ide> '<ul>' +
<del> '<#comment></#comment>' +
<add> '<!-- ngRepeat: item in model.items -->' +
<ide> '<li ng-bind="item.a" ng-repeat="item in model.items">A</li>' +
<ide> '<li ng-bind="item.a" ng-repeat="item in model.items">B</li>' +
<ide> '</ul>');
<ide> describe('Binder', function() {
<ide> $rootScope.$apply();
<ide> expect(sortedHtml(form)).toBe(
<ide> '<ul>' +
<del> '<#comment></#comment>' +
<add> '<!-- ngRepeat: item in model.items -->' +
<ide> '<li ng-bind="item.a" ng-repeat="item in model.items">C</li>' +
<ide> '<li ng-bind="item.a" ng-repeat="item in model.items">A</li>' +
<ide> '<li ng-bind="item.a" ng-repeat="item in model.items">B</li>' +
<ide> describe('Binder', function() {
<ide> $rootScope.$apply();
<ide> expect(sortedHtml(form)).toBe(
<ide> '<ul>' +
<del> '<#comment></#comment>' +
<add> '<!-- ngRepeat: item in model.items -->' +
<ide> '<li ng-bind="item.a" ng-repeat="item in model.items">A</li>' +
<ide> '<li ng-bind="item.a" ng-repeat="item in model.items">B</li>' +
<ide> '</ul>');
<ide> describe('Binder', function() {
<ide> $rootScope.$apply();
<ide> expect(sortedHtml(element)).toBe(
<ide> '<ul>' +
<del> '<#comment></#comment>' +
<add> '<!-- ngRepeat: item in model.items -->' +
<ide> '<li ng-repeat="item in model.items"><span ng-bind="item.a">A</span></li>' +
<ide> '</ul>');
<ide> }));
<ide> describe('Binder', function() {
<ide>
<ide> expect(sortedHtml(element)).toBe(
<ide> '<div>'+
<del> '<#comment></#comment>'+
<add> '<!-- ngRepeat: m in model -->' +
<ide> '<div name="a" ng-repeat="m in model">'+
<del> '<#comment></#comment>'+
<add> '<!-- ngRepeat: i in m.item -->' +
<ide> '<ul name="a1" ng-repeat="i in m.item"></ul>'+
<ide> '<ul name="a2" ng-repeat="i in m.item"></ul>'+
<ide> '</div>'+
<ide> '<div name="b" ng-repeat="m in model">'+
<del> '<#comment></#comment>'+
<add> '<!-- ngRepeat: i in m.item -->' +
<ide> '<ul name="b1" ng-repeat="i in m.item"></ul>'+
<ide> '<ul name="b2" ng-repeat="i in m.item"></ul>'+
<ide> '</div>' +
<ide> describe('Binder', function() {
<ide> expect(d1.hasClass('o')).toBeTruthy();
<ide> expect(d2.hasClass('e')).toBeTruthy();
<ide> expect(sortedHtml(element)).toBe(
<del> '<div><#comment></#comment>' +
<add> '<div>' +
<add> '<!-- ngRepeat: i in [0,1] -->' +
<ide> '<div class="o" ng-class-even="\'e\'" ng-class-odd="\'o\'" ng-repeat="i in [0,1]"></div>' +
<del> '<div class="e" ng-class-even="\'e\'" ng-class-odd="\'o\'" ng-repeat="i in [0,1]"></div></div>');
<add> '<div class="e" ng-class-even="\'e\'" ng-class-odd="\'o\'" ng-repeat="i in [0,1]"></div>' +
<add> '</div>');
<ide> }));
<ide>
<ide> it('BindStyle', inject(function($rootScope, $compile) {
<ide> describe('Binder', function() {
<ide> $rootScope.$apply();
<ide> expect(sortedHtml(element)).toBe(
<ide> '<ul>' +
<del> '<#comment></#comment>' +
<add> '<!-- ngRepeat: (k,v) in {a:0,b:1} -->' +
<ide> '<li ng-bind=\"k + v\" ng-repeat="(k,v) in {a:0,b:1}">a0</li>' +
<ide> '<li ng-bind=\"k + v\" ng-repeat="(k,v) in {a:0,b:1}">b1</li>' +
<ide> '</ul>');
<ide><path>test/testabilityPatch.js
<ide> function dealoc(obj) {
<ide> function sortedHtml(element, showNgClass) {
<ide> var html = "";
<ide> forEach(jqLite(element), function toString(node) {
<add>
<ide> if (node.nodeName == "#text") {
<ide> html += node.nodeValue.
<ide> replace(/&(\w+[&;\W])?/g, function(match, entity){return entity?match:'&';}).
<ide> replace(/</g, '<').
<ide> replace(/>/g, '>');
<add> } else if (node.nodeName == "#comment") {
<add> html += '<!--' + node.nodeValue + '-->';
<ide> } else {
<ide> html += '<' + (node.nodeName || '?NOT_A_NODE?').toLowerCase();
<ide> var attributes = node.attributes || []; | 2 |
Javascript | Javascript | exclude initial proto from benchmark | b6726ebf176c2ff923360bf233fabd9aa1f936bd | <ide><path>benchmarks/suites/views/template_view.js
<ide> before(function() {
<ide> App.View = Ember.View.extend({
<ide> template: Ember.Handlebars.compile("{{view}}")
<ide> });
<add>
<add> App.View.create().destroy();
<ide> });
<ide>
<ide> after(function() { | 1 |
Python | Python | fix indent typo | b313bebf41374c2271b39128501ea0ed1a11fb0e | <ide><path>airflow/www/app.py
<ide> def tree(self):
<ide> else:
<ide> base_date = dateutil.parser.parse(base_date)
<ide>
<del> start_date = dag.start_date
<add> start_date = dag.start_date
<ide> if not start_date:
<ide> start_date = dag.default_args['start_date']
<ide> | 1 |
Javascript | Javascript | fix mispelled hook | 3e6aaf9b670941e415e076a65ab8ec572d75f8e1 | <ide><path>lib/web/JsonpMainTemplatePlugin.js
<ide> class JsonpMainTemplatePlugin {
<ide> mainTemplate.hooks.jsonpScript = new SyncWaterfallHook(["source", "chunk", "hash"]);
<ide> }
<ide>
<del> mainTemplate.hooks.localVar.tap("JsonpMainTemplatePlugin", (source, chunk) => {
<add> mainTemplate.hooks.localVars.tap("JsonpMainTemplatePlugin", (source, chunk) => {
<ide> if(needChunkLoadingCode(chunk)) {
<ide> return Template.asString([
<ide> source, | 1 |
Ruby | Ruby | move private methods to the private visibility | 338750393d0f19b193f0ead26adff2b9f586ec18 | <ide><path>actionmailer/lib/action_mailer/base.rb
<ide> def mail(headers = {}, &block)
<ide> message
<ide> end
<ide>
<del> # This and #instrument_name is for caching instrument
<del> def instrument_payload(key)
<del> {
<del> mailer: mailer_name,
<del> key: key
<del> }
<del> end
<del>
<del> def instrument_name
<del> "action_mailer"
<del> end
<del>
<ide> protected
<ide>
<ide> # Used by #mail to set the content type of the message.
<ide> def insert_part(container, response, charset)
<ide> container.add_part(part)
<ide> end
<ide>
<add> # This and #instrument_name is for caching instrument
<add> def instrument_payload(key)
<add> {
<add> mailer: mailer_name,
<add> key: key
<add> }
<add> end
<add>
<add> def instrument_name
<add> "action_mailer"
<add> end
<add>
<ide> ActiveSupport.run_load_hooks(:action_mailer, self)
<ide> end
<ide> end
<ide><path>actionpack/lib/action_controller/caching.rb
<ide> module Caching
<ide> include AbstractController::Caching
<ide> end
<ide>
<del> def instrument_payload(key)
<del> {
<del> controller: controller_name,
<del> action: action_name,
<del> key: key
<del> }
<del> end
<add> private
<ide>
<del> def instrument_name
<del> "action_controller"
<del> end
<add> def instrument_payload(key)
<add> {
<add> controller: controller_name,
<add> action: action_name,
<add> key: key
<add> }
<add> end
<add>
<add> def instrument_name
<add> "action_controller"
<add> end
<ide> end
<ide> end | 2 |
PHP | PHP | add docs for route names | 8a7aecf99d7d61c722d00e153f848a5fc267b72b | <ide><path>lib/Cake/Routing/Route/Route.php
<ide> class Route {
<ide> /**
<ide> * Constructor for a Route
<ide> *
<add> * Using $options['_name'] a specific name can be given to a route.
<add> * Otherwise a route name will be generated.
<add> *
<ide> * @param string $template Template string with parameter placeholders
<ide> * @param array $defaults Array of defaults for the route.
<ide> * @param array $options Array of additional options for the Route
<ide> public function __construct($template, $defaults = array(), $options = array())
<ide> $this->template = $template;
<ide> $this->defaults = (array)$defaults;
<ide> $this->options = (array)$options;
<add> if (isset($this->options['_name'])) {
<add> $this->_name = $this->options['_name'];
<add> }
<ide> }
<ide>
<ide> /**
<ide> protected function _writeRoute() {
<ide> * @return string.
<ide> */
<ide> public function getName() {
<del> if (empty($this->_name)) {
<add> if (!empty($this->_name)) {
<add> return $this->_name;
<add> }
<add> if (!$this->compiled()) {
<ide> $this->compile();
<ide> }
<ide> $name = '';
<ide><path>lib/Cake/Routing/RouteCollection.php
<ide> public function promote($which) {
<ide> array_unshift($this->_routes, $route);
<ide> return true;
<ide> }
<add>
<ide> }
<ide><path>lib/Cake/Routing/Router.php
<ide> public static function resourceMap($resourceMap = null) {
<ide> * Shows connecting a route with custom route parameters as well as providing patterns for those parameters.
<ide> * Patterns for routing parameters do not need capturing groups, as one will be added for each route params.
<ide> *
<del> * $options offers four 'special' keys. `pass`, `persist` and `routeClass`
<del> * have special meaning in the $options array.
<del> *
<del> * `pass` is used to define which of the routed parameters should be shifted into the pass array. Adding a
<del> * parameter to pass will remove it from the regular route array. Ex. `'pass' => array('slug')`
<del> *
<del> * `persist` is used to define which route parameters should be automatically included when generating
<del> * new urls. You can override persistent parameters by redefining them in a url or remove them by
<del> * setting the parameter to `false`. Ex. `'persist' => array('lang')`
<del> *
<del> * `routeClass` is used to extend and change how individual routes parse requests and handle reverse routing,
<del> * via a custom routing class. Ex. `'routeClass' => 'SlugRoute'`
<add> * $options offers several 'special' keys that have special meaning in the $options array.
<add> *
<add> * - `pass` is used to define which of the routed parameters should be shifted into the pass array. Adding a
<add> * parameter to pass will remove it from the regular route array. Ex. `'pass' => array('slug')`
<add> * - `persist` is used to define which route parameters should be automatically included when generating
<add> * new urls. You can override persistent parameters by redefining them in a url or remove them by
<add> * setting the parameter to `false`. Ex. `'persist' => array('lang')`
<add> * - `routeClass` is used to extend and change how individual routes parse requests and handle reverse routing,
<add> * via a custom routing class. Ex. `'routeClass' => 'SlugRoute'`
<add> * - `_name` Used to define a specific name for routes. This can be used to optimize reverse routing lookups.
<add> * If undefined a name will be generated for each connected route.
<ide> *
<ide> * @param string $route A string describing the template of the route
<ide> * @param array $defaults An array describing the default route parameters. These parameters will be used by default
<ide><path>lib/Cake/Test/TestCase/Routing/Route/RouteTest.php
<ide> public function testParseTrailingUTF8() {
<ide> * @return void
<ide> */
<ide> public function testGetName() {
<add> $route = new Route('/foo/bar', array(), array('_name' => 'testing'));
<add> $this->assertEquals('testing', $route->getName());
<add>
<ide> $route = new Route('/:controller/:action');
<ide> $this->assertEquals('_controller::_action', $route->getName());
<ide> | 4 |
Java | Java | introduce property rx3.scheduler.use-nanotime | 171c84677739d63ef778b8893db845ac7abc81e6 | <ide><path>src/main/java/io/reactivex/rxjava3/core/Scheduler.java
<ide> * interface which can grant access to the original or hooked {@code Runnable}, thus, a repeated {@code RxJavaPlugins.onSchedule}
<ide> * can detect the earlier hook and not apply a new one over again.
<ide> * <p>
<del> * The default implementation of {@link #now(TimeUnit)} and {@link Worker#now(TimeUnit)} methods to return current
<del> * {@link System#currentTimeMillis()} value in the desired time unit. Custom {@code Scheduler} implementations can override this
<add> * The default implementation of {@link #now(TimeUnit)} and {@link Worker#now(TimeUnit)} methods to return current {@link System#currentTimeMillis()}
<add> * value in the desired time unit, unless {@code rx3.scheduler.use-nanotime} (boolean) is set. When the property is set to
<add> * {@code true}, the method uses {@link System#nanoTime()} as its basis instead. Custom {@code Scheduler} implementations can override this
<ide> * to provide specialized time accounting (such as virtual time to be advanced programmatically).
<ide> * Note that operators requiring a {@code Scheduler} may rely on either of the {@code now()} calls provided by
<ide> * {@code Scheduler} or {@code Worker} respectively, therefore, it is recommended they represent a logically
<ide> * All methods on the {@code Scheduler} and {@code Worker} classes should be thread safe.
<ide> */
<ide> public abstract class Scheduler {
<add> /**
<add> * Value representing whether to use {@link System#nanoTime()}, or default as clock for {@link #now(TimeUnit)}
<add> * and {@link Scheduler.Worker#now(TimeUnit)}
<add> * <p>
<add> * Associated system parameter:
<add> * <ul>
<add> * <li>{@code rx3.scheduler.use-nanotime}, boolean, default {@code false}
<add> * </ul>
<add> */
<add> static boolean IS_DRIFT_USE_NANOTIME = Boolean.getBoolean("rx3.scheduler.use-nanotime");
<add>
<add> /**
<add> * Returns the current clock time depending on state of {@link Scheduler#IS_DRIFT_USE_NANOTIME} in given {@code unit}
<add> * <p>
<add> * By default {@link System#currentTimeMillis()} will be used as the clock. When the property is set
<add> * {@link System#nanoTime()} will be used.
<add> * <p>
<add> * @param unit the time unit
<add> * @return the 'current time' in given unit
<add> * @throws NullPointerException if {@code unit} is {@code null}
<add> */
<add> static long computeNow(TimeUnit unit) {
<add> if(!IS_DRIFT_USE_NANOTIME) {
<add> return unit.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS);
<add> }
<add> return unit.convert(System.nanoTime(), TimeUnit.NANOSECONDS);
<add> }
<add>
<ide> /**
<ide> * The tolerance for a clock drift in nanoseconds where the periodic scheduler will rebase.
<ide> * <p>
<ide> public static long clockDriftTolerance() {
<ide> * @since 2.0
<ide> */
<ide> public long now(@NonNull TimeUnit unit) {
<del> return unit.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS);
<add> return computeNow(unit);
<ide> }
<ide>
<ide> /**
<ide> public <S extends Scheduler & Disposable> S when(@NonNull Function<Flowable<Flow
<ide> * track the individual {@code Runnable} tasks while they are waiting to be executed (with or without delay) so that
<ide> * {@link #dispose()} can prevent their execution or potentially interrupt them if they are currently running.
<ide> * <p>
<del> * The default implementation of the {@link #now(TimeUnit)} method returns current
<del> * {@link System#currentTimeMillis()} value in the desired time unit. Custom {@code Worker} implementations can override this
<add> * The default implementation of the {@link #now(TimeUnit)} method returns current {@link System#currentTimeMillis()}
<add> * value in the desired time unit, unless {@code rx3.scheduler.use-nanotime} (boolean) is set. When the property is set to
<add> * {@code true}, the method uses {@link System#nanoTime()} as its basis instead. Custom {@code Worker} implementations can override this
<ide> * to provide specialized time accounting (such as virtual time to be advanced programmatically).
<ide> * Note that operators requiring a scheduler may rely on either of the {@code now()} calls provided by
<ide> * {@code Scheduler} or {@code Worker} respectively, therefore, it is recommended they represent a logically
<ide> public Disposable schedulePeriodically(@NonNull Runnable run, final long initial
<ide> * @since 2.0
<ide> */
<ide> public long now(@NonNull TimeUnit unit) {
<del> return unit.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS);
<add> return computeNow(unit);
<ide> }
<ide>
<ide> /**
<ide><path>src/main/java/io/reactivex/rxjava3/schedulers/Schedulers.java
<ide> * <li>{@code rx3.single-priority} (int): sets the thread priority of the {@link #single()} {@code Scheduler}, default is {@link Thread#NORM_PRIORITY}</li>
<ide> * <li>{@code rx3.purge-enabled} (boolean): enables periodic purging of all {@code Scheduler}'s backing thread pools, default is {@code false}</li>
<ide> * <li>{@code rx3.purge-period-seconds} (int): specifies the periodic purge interval of all {@code Scheduler}'s backing thread pools, default is 1 second</li>
<add> * <li>{@code rx3.scheduler.use-nanotime} (boolean): {@code true} instructs {@code Scheduler} to use {@link System#nanoTime()} for {@link Scheduler#now(TimeUnit)},
<add> * instead of default {@link System#currentTimeMillis()} ({@code false})</li>
<ide> * </ul>
<ide> */
<ide> public final class Schedulers {
<ide><path>src/test/java/io/reactivex/rxjava3/core/SchedulerTest.java
<ide> package io.reactivex.rxjava3.core;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<add>import static org.junit.Assert.assertFalse;
<add>import static org.junit.Assert.assertTrue;
<ide>
<add>import org.junit.After;
<ide> import org.junit.Test;
<ide>
<add>import java.util.concurrent.TimeUnit;
<add>
<ide> public class SchedulerTest {
<add> private static final String DRIFT_USE_NANOTIME = "rx3.scheduler.use-nanotime";
<add>
<add> @After
<add> public void cleanup() {
<add> // reset value to default in order to not influence other tests
<add> Scheduler.IS_DRIFT_USE_NANOTIME = false;
<add> }
<add>
<add> @Test
<add> public void driftUseNanoTimeNotSetByDefault() {
<add> assertFalse(Scheduler.IS_DRIFT_USE_NANOTIME);
<add> assertFalse(Boolean.getBoolean(DRIFT_USE_NANOTIME));
<add> }
<add>
<add> @Test
<add> public void computeNow_currentTimeMillis() {
<add> TimeUnit unit = TimeUnit.MILLISECONDS;
<add> assertTrue(isInRange(System.currentTimeMillis(), Scheduler.computeNow(unit), unit, 250, TimeUnit.MILLISECONDS));
<add> }
<add>
<add> @Test
<add> public void computeNow_nanoTime() {
<add> TimeUnit unit = TimeUnit.NANOSECONDS;
<add> Scheduler.IS_DRIFT_USE_NANOTIME = true;
<add>
<add> assertFalse(isInRange(System.currentTimeMillis(), Scheduler.computeNow(unit), unit, 250, TimeUnit.MILLISECONDS));
<add> assertTrue(isInRange(System.nanoTime(), Scheduler.computeNow(unit), TimeUnit.NANOSECONDS, 250, TimeUnit.MILLISECONDS));
<add> }
<add>
<add> private boolean isInRange(long start, long stop, TimeUnit source, long maxDiff, TimeUnit diffUnit) {
<add> long diff = Math.abs(stop - start);
<add> return diffUnit.convert(diff, source) <= maxDiff;
<add> }
<ide>
<ide> @Test
<ide> public void clockDriftCalculation() { | 3 |
Javascript | Javascript | avoid copy of data | 4d1e913f48f33da2ae4fcceb07607efac240ece8 | <ide><path>lib/serialization/FileMiddleware.js
<ide> const deserialize = async (middleware, name, readFile) => {
<ide> let contentItemLength = contentItem.length;
<ide> let contentPosition = 0;
<ide> if (contentItemLength === 0) throw new Error("Empty file " + name);
<add> const nextContent = () => {
<add> contentsIndex++;
<add> contentItem = contents[contentsIndex];
<add> contentItemLength = contentItem.length;
<add> contentPosition = 0;
<add> };
<ide> const ensureData = n => {
<ide> if (contentPosition === contentItemLength) {
<del> contentsIndex++;
<del> contentItem = contents[contentsIndex];
<del> contentItemLength = contentItem.length;
<del> contentPosition = 0;
<add> nextContent();
<ide> }
<ide> while (contentItemLength - contentPosition < n) {
<ide> const remaining = contentItem.slice(contentPosition);
<ide> const deserialize = async (middleware, name, readFile) => {
<ide> contentPosition += 4;
<ide> return value;
<ide> };
<del> const readSlice = (l, clone) => {
<add> const readSlice = l => {
<ide> ensureData(l);
<ide> if (contentPosition === 0 && contentItemLength === l) {
<ide> const result = contentItem;
<ide> if (contentsIndex + 1 < contents.length) {
<del> contentsIndex++;
<del> contentItem = contents[contentsIndex];
<del> contentItemLength = contentItem.length;
<del> contentPosition = 0;
<add> nextContent();
<ide> } else {
<ide> contentPosition = l;
<ide> }
<ide> return result;
<ide> }
<ide> const result = contentItem.slice(contentPosition, contentPosition + l);
<ide> contentPosition += l;
<del> return clone ? Buffer.from(result) : result;
<add> // we clone the buffer here to allow the original content to be garbage collected
<add> return l * 2 < contentItem.buffer.byteLength ? Buffer.from(result) : result;
<ide> };
<ide> const version = readUInt32LE();
<ide> if (version !== VERSION) {
<ide> const deserialize = async (middleware, name, readFile) => {
<ide> for (let i = 0; i < sectionCount; i++) {
<ide> lengths.push(readInt32LE());
<ide> }
<del> const result = lengths.map(length => {
<add> const result = [];
<add> for (let length of lengths) {
<ide> if (length < 0) {
<del> // we clone the buffer here to allow the original content to be garbage collected
<del> const clone = readSlice(-length, true);
<del> const size = Number(clone.readBigUInt64LE(0));
<del> const nameBuffer = clone.slice(8);
<add> const slice = readSlice(-length);
<add> const size = Number(slice.readBigUInt64LE(0));
<add> const nameBuffer = slice.slice(8);
<ide> const name = nameBuffer.toString();
<del> return SerializerMiddleware.createLazy(
<del> memorize(() => deserialize(middleware, name, readFile)),
<del> middleware,
<del> {
<del> name,
<del> size
<del> },
<del> clone
<add> result.push(
<add> SerializerMiddleware.createLazy(
<add> memorize(() => deserialize(middleware, name, readFile)),
<add> middleware,
<add> {
<add> name,
<add> size
<add> },
<add> slice
<add> )
<ide> );
<ide> } else {
<del> return readSlice(length, false);
<add> if (contentPosition === contentItemLength) {
<add> nextContent();
<add> } else if (contentPosition !== 0) {
<add> if (length <= contentItemLength - contentPosition) {
<add> result.push(
<add> contentItem.slice(contentPosition, contentPosition + length)
<add> );
<add> contentPosition += length;
<add> length = 0;
<add> } else {
<add> result.push(contentItem.slice(contentPosition));
<add> length -= contentItemLength - contentPosition;
<add> contentPosition = contentItemLength;
<add> }
<add> } else {
<add> if (length >= contentItemLength) {
<add> result.push(contentItem);
<add> length -= contentItemLength;
<add> contentPosition = contentItemLength;
<add> } else {
<add> result.push(contentItem.slice(0, length));
<add> contentPosition += length;
<add> length = 0;
<add> }
<add> }
<add> while (length > 0) {
<add> nextContent();
<add> if (length >= contentItemLength) {
<add> result.push(contentItem);
<add> length -= contentItemLength;
<add> contentPosition = contentItemLength;
<add> } else {
<add> result.push(contentItem.slice(0, length));
<add> contentPosition += length;
<add> length = 0;
<add> }
<add> }
<ide> }
<del> });
<add> }
<ide> return result;
<ide> };
<ide> | 1 |
Python | Python | add test for creating m2ms | a758c9c1866559ab5dbf4a7705c07e8532dcd253 | <ide><path>django/db/migrations/operations/models.py
<ide> class CreateModel(Operation):
<ide> """
<ide>
<ide> def __init__(self, name, fields, options=None, bases=None):
<del> self.name = name.lower()
<add> self.name = name
<ide> self.fields = fields
<ide> self.options = options or {}
<ide> self.bases = bases or (models.Model,)
<ide> class DeleteModel(Operation):
<ide> """
<ide>
<ide> def __init__(self, name):
<del> self.name = name.lower()
<add> self.name = name
<ide>
<ide> def state_forwards(self, app_label, state):
<ide> del state.models[app_label, self.name.lower()]
<ide> class AlterModelTable(Operation):
<ide> """
<ide>
<ide> def __init__(self, name, table):
<del> self.name = name.lower()
<add> self.name = name
<ide> self.table = table
<ide>
<ide> def state_forwards(self, app_label, state):
<ide> class AlterUniqueTogether(Operation):
<ide> """
<ide>
<ide> def __init__(self, name, unique_together):
<del> self.name = name.lower()
<add> self.name = name
<ide> self.unique_together = set(tuple(cons) for cons in unique_together)
<ide>
<ide> def state_forwards(self, app_label, state):
<ide> class AlterIndexTogether(Operation):
<ide> """
<ide>
<ide> def __init__(self, name, index_together):
<del> self.name = name.lower()
<add> self.name = name
<ide> self.index_together = set(tuple(cons) for cons in index_together)
<ide>
<ide> def state_forwards(self, app_label, state):
<ide><path>tests/migrations/test_autodetector.py
<ide> def test_new_model(self):
<ide> # Right action?
<ide> action = migration.operations[0]
<ide> self.assertEqual(action.__class__.__name__, "CreateModel")
<del> self.assertEqual(action.name, "author")
<add> self.assertEqual(action.name, "Author")
<ide>
<ide> def test_old_model(self):
<ide> "Tests deletion of old models"
<ide> def test_old_model(self):
<ide> # Right action?
<ide> action = migration.operations[0]
<ide> self.assertEqual(action.__class__.__name__, "DeleteModel")
<del> self.assertEqual(action.name, "author")
<add> self.assertEqual(action.name, "Author")
<ide>
<ide> def test_add_field(self):
<ide> "Tests autodetection of new fields"
<ide><path>tests/migrations/test_operations.py
<ide> class OperationTests(MigrationTestBase):
<ide> both forwards and backwards.
<ide> """
<ide>
<del> def set_up_test_model(self, app_label):
<add> def set_up_test_model(self, app_label, second_model=False):
<ide> """
<ide> Creates a test model state and database table.
<ide> """
<ide> # Make the "current" state
<del> creation = migrations.CreateModel(
<add> operations = [migrations.CreateModel(
<ide> "Pony",
<ide> [
<ide> ("id", models.AutoField(primary_key=True)),
<ide> ("pink", models.IntegerField(default=3)),
<ide> ("weight", models.FloatField()),
<ide> ],
<del> )
<add> )]
<add> if second_model:
<add> operations.append(migrations.CreateModel("Stable", [("id", models.AutoField(primary_key=True))]))
<ide> project_state = ProjectState()
<del> creation.state_forwards(app_label, project_state)
<add> for operation in operations:
<add> operation.state_forwards(app_label, project_state)
<ide> # Set up the database
<ide> with connection.schema_editor() as editor:
<del> creation.database_forwards(app_label, editor, ProjectState(), project_state)
<add> for operation in operations:
<add> operation.database_forwards(app_label, editor, ProjectState(), project_state)
<ide> return project_state
<ide>
<ide> def test_create_model(self):
<ide> def test_create_model(self):
<ide> project_state = ProjectState()
<ide> new_state = project_state.clone()
<ide> operation.state_forwards("test_crmo", new_state)
<del> self.assertEqual(new_state.models["test_crmo", "pony"].name, "pony")
<add> self.assertEqual(new_state.models["test_crmo", "pony"].name, "Pony")
<ide> self.assertEqual(len(new_state.models["test_crmo", "pony"].fields), 2)
<ide> # Test the database alteration
<ide> self.assertTableNotExists("test_crmo_pony")
<ide> def test_add_field(self):
<ide> operation.database_backwards("test_adfl", editor, new_state, project_state)
<ide> self.assertColumnNotExists("test_adfl_pony", "height")
<ide>
<add> def test_add_field_m2m(self):
<add> """
<add> Tests the AddField operation with a ManyToManyField.
<add> """
<add> project_state = self.set_up_test_model("test_adflmm", second_model=True)
<add> # Test the state alteration
<add> operation = migrations.AddField("Pony", "stables", models.ManyToManyField("Stable"))
<add> new_state = project_state.clone()
<add> operation.state_forwards("test_adflmm", new_state)
<add> self.assertEqual(len(new_state.models["test_adflmm", "pony"].fields), 4)
<add> # Test the database alteration
<add> self.assertTableNotExists("test_adflmm_pony_stables")
<add> with connection.schema_editor() as editor:
<add> operation.database_forwards("test_adflmm", editor, project_state, new_state)
<add> self.assertTableExists("test_adflmm_pony_stables")
<add> self.assertColumnNotExists("test_adflmm_pony", "stables")
<add> # And test reversal
<add> with connection.schema_editor() as editor:
<add> operation.database_backwards("test_adflmm", editor, new_state, project_state)
<add> self.assertTableNotExists("test_adflmm_pony_stables")
<add>
<ide> def test_remove_field(self):
<ide> """
<ide> Tests the RemoveField operation. | 3 |
Text | Text | remove extra word | 831850029422cb3d78e395ce091b1e2a115b5400 | <ide><path>share/doc/homebrew/Gems,-Eggs-and-Perl-Modules.md
<ide> without sudo. You should add this to your path. See the caveats in the
<ide>
<ide> ### With system’s Ruby
<ide>
<del>To make Ruby install install to `/usr/local`, we need to add
<add>To make Ruby install to `/usr/local`, we need to add
<ide> `gem: -n/usr/local/bin` to your `~/.gemrc`. It’s YAML…so do it manually
<ide> or use this:
<ide> | 1 |
Python | Python | update error type | 73baaf330ae8c8420a44f7803394f55c343e9e1c | <ide><path>spacy/tests/test_cli.py
<ide> import pytest
<add>from click import NoSuchOption
<add>
<ide> from spacy.gold import docs_to_json, biluo_tags_from_offsets
<ide> from spacy.gold.converters import iob2docs, conll_ner2docs, conllu2docs
<ide> from spacy.lang.en import English
<ide> def test_parse_config_overrides(args, expected):
<ide> [["--foo"], ["--x.foo", "bar", "--baz"], ["--x.foo", "bar", "baz"], ["x.foo"]],
<ide> )
<ide> def test_parse_config_overrides_invalid(args):
<del> with pytest.raises(SystemExit):
<add> with pytest.raises(NoSuchOption):
<ide> parse_config_overrides(args)
<ide>
<ide> | 1 |
Python | Python | add ability to set userdata | 94b0b047568cb3de72bd85911e5b8d21ed914d28 | <ide><path>libcloud/drivers/ec2.py
<ide> def create_node(self, **kwargs):
<ide> try: params['KeyName'] = kwargs['keyname']
<ide> except KeyError: pass
<ide>
<add> try: params['UserData'] = base64.b64encode(kwargs['userdata'])
<add> except KeyError: pass
<add>
<ide> object = self.connection.request('/', params=params).object
<ide> nodes = self._to_nodes(object, 'instancesSet/item')
<ide> | 1 |
PHP | PHP | use method on app | dd60e0dcc8059f700cc4c3c0679b1a13d0fae252 | <ide><path>src/Illuminate/Foundation/Support/Providers/EventServiceProvider.php
<ide> public function discoverEvents()
<ide> protected function discoverEventsWithin()
<ide> {
<ide> return [
<del> app_path('Listeners'),
<add> $this->app->path('Listeners'),
<ide> ];
<ide> }
<ide> } | 1 |
Javascript | Javascript | improve debug output in trace-events test | 75e91659887012f743aa4487d6d4ce3d765c028a | <ide><path>test/parallel/test-trace-events-fs-sync.js
<ide> const common = require('../common');
<ide> const assert = require('assert');
<ide> const cp = require('child_process');
<ide> const fs = require('fs');
<add>const util = require('util');
<ide>
<ide> if (!common.isMainThread)
<ide> common.skip('process.chdir is not available in Workers');
<ide> for (const tr in tests) {
<ide> const proc = cp.spawnSync(process.execPath,
<ide> [ '--trace-events-enabled',
<ide> '--trace-event-categories', 'node.fs.sync',
<del> '-e', tests[tr] ]);
<add> '-e', tests[tr] ],
<add> { encoding: 'utf8' });
<ide> // Some AIX versions don't support futimes or utimes, so skip.
<ide> if (common.isAIX && proc.status !== 0 && tr === 'fs.sync.futimes') {
<ide> continue;
<ide> for (const tr in tests) {
<ide> }
<ide>
<ide> // Make sure the operation is successful.
<del> assert.strictEqual(proc.status, 0, tr + ': ' + proc.stderr);
<add> assert.strictEqual(proc.status, 0, `${tr}:\n${util.inspect(proc)}`);
<ide>
<ide> // Confirm that trace log file is created.
<ide> assert(common.fileExists(traceFile)); | 1 |
Text | Text | add item to changelog | d20af235980575703d23a7635d2634d37a22bb71 | <ide><path>CHANGELOG.md
<ide> Starting with 16.1.0, we will no longer be publishing new releases on Bower. You
<ide> * Fix `form.reset()` to respect `defaultValue` on uncontrolled `<select>`. ([@aweary](https://github.com/aweary) in [#11057](https://github.com/facebook/react/pull/11057))
<ide> * Fix `<textarea>` placeholder not rendering on IE11. ([@gaearon](https://github.com/gaearon) in [#11177](https://github.com/facebook/react/pull/11177))
<ide> * Fix a crash rendering into shadow root. ([@gaearon](https://github.com/gaearon) in [#11037](https://github.com/facebook/react/pull/11037))
<add>* Fix false positive warning about hydrating mixed case SVG tags. ([@gaearon](http://github.com/gaearon) in [#11174](https://github.com/facebook/react/pull/11174))
<ide> * Suppress the new unknown tag warning for `<dialog>` element. ([@gaearon](http://github.com/gaearon) in [#11035](https://github.com/facebook/react/pull/11035))
<ide> * Warn about function child no more than once. ([@andreysaleba](https://github.com/andreysaleba) in [#11120](https://github.com/facebook/react/pull/11120))
<ide> * Warn about nested updates no more than once. ([@anushreesubramani](https://github.com/anushreesubramani) in [#11113](https://github.com/facebook/react/pull/11113)) | 1 |
PHP | PHP | add method to parse compact route string | 4af4d16287060474e6dabe099703d82d7ed80215 | <ide><path>src/Routing/RouteBuilder.php
<ide> protected static function parseDefaults($defaults): array
<ide> return $defaults;
<ide> }
<ide>
<del> $regex = '/(?:(?<plugin>[a-zA-Z0-9\/]*)\.)?(?<prefix>[a-zA-Z0-9\/]*?)' .
<del> '(?:\/)?(?<controller>[a-zA-Z0-9]*):{2}(?<action>[a-zA-Z0-9_]*)/i';
<del>
<del> if (preg_match($regex, $defaults, $matches)) {
<del> foreach ($matches as $key => $value) {
<del> // Remove numeric keys and empty values.
<del> if (is_int($key) || $value === '' || $value === '::') {
<del> unset($matches[$key]);
<del> }
<del> }
<del> $length = count($matches);
<add> return self::parseShortString($defaults);
<add> }
<ide>
<del> if (isset($matches['prefix'])) {
<del> $matches['prefix'] = strtolower($matches['prefix']);
<del> }
<add> /**
<add> * Parse the short string
<add> *
<add> * String examples:
<add> * - Bookmarks::view
<add> * - Admin/Bookmarks::view
<add> * - Cms.Articles::edit
<add> * - Vendor/Cms.Management/Admin/Articles::view
<add> *
<add> * @param string $routeString Short string in [Plugin.][Prefix/]Controller::action format
<add> * @return string[]
<add> */
<add> public static function parseShortString(string $routeString): array
<add> {
<add> $regex = '#^
<add> (?:(?<plugin>[a-z0-9]+(?:/[a-z0-9]+)*)\.)?
<add> (?:(?<prefix>[a-z0-9]+(?:/[a-z0-9]+)*)/)?
<add> (?<controller>[a-z0-9]+)
<add> ::
<add> (?<action>[a-z0-9_]+)
<add> $#ix';
<add>
<add> if (!preg_match($regex, $routeString, $matches)) {
<add> throw new RuntimeException("Could not parse `{$routeString}` route short string.");
<add> }
<ide>
<del> if ($length >= 2 || $length <= 4) {
<del> return $matches;
<del> }
<add> $defaults = [];
<add>
<add> if ($matches['plugin'] !== '') {
<add> $defaults['plugin'] = $matches['plugin'];
<add> }
<add> if ($matches['prefix'] !== '') {
<add> $defaults['prefix'] = strtolower($matches['prefix']);
<ide> }
<del> throw new RuntimeException("Could not parse `{$defaults}` route destination string.");
<add> $defaults['controller'] = $matches['controller'];
<add> $defaults['action'] = $matches['action'];
<add>
<add> return $defaults;
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Routing/RouteBuilderTest.php
<ide> public function testConnectShortStringPluginPrefix()
<ide> $this->assertEquals($url, '/' . $this->collection->match($expected, []));
<ide> }
<ide>
<add> /**
<add> * Test parseShortString() with valid strings
<add> *
<add> * @return void
<add> */
<add> public function testParseShortString()
<add> {
<add> $expected = [
<add> 'controller' => 'Bookmarks',
<add> 'action' => 'view',
<add> ];
<add> $this->assertSame($expected, RouteBuilder::parseShortString('Bookmarks::view'));
<add>
<add> $expected = [
<add> 'prefix' => 'admin',
<add> 'controller' => 'Bookmarks',
<add> 'action' => 'view',
<add> ];
<add> $this->assertSame($expected, RouteBuilder::parseShortString('Admin/Bookmarks::view'));
<add>
<add> $expected = [
<add> 'plugin' => 'Cms',
<add> 'controller' => 'Articles',
<add> 'action' => 'edit',
<add> ];
<add> $this->assertSame($expected, RouteBuilder::parseShortString('Cms.Articles::edit'));
<add>
<add> $expected = [
<add> 'plugin' => 'Vendor/Cms',
<add> 'prefix' => 'management/admin',
<add> 'controller' => 'Articles',
<add> 'action' => 'view',
<add> ];
<add> $this->assertSame($expected, RouteBuilder::parseShortString('Vendor/Cms.Management/Admin/Articles::view'));
<add> }
<add>
<add> /**
<add> * @return array
<add> */
<add> public function invalidShortStringsProvider()
<add> {
<add> return [
<add> ['view'],
<add> ['Bookmarks:view'],
<add> ['Bookmarks/view'],
<add> ['Vendor\Cms.Articles::edit'],
<add> ['Vendor//Cms.Articles::edit'],
<add> ['Cms./Articles::edit'],
<add> ['Cms./Admin/Articles::edit'],
<add> ['Cms.Admin//Articles::edit'],
<add> ['Vendor\Cms.Management\Admin\Articles::edit'],
<add> ];
<add> }
<add>
<add> /**
<add> * Test parseShortString() with invalid strings
<add> *
<add> * @param string $value
<add> * @return void
<add> * @dataProvider invalidShortStringsProvider
<add> */
<add> public function testParseShortInvalidString(string $value)
<add> {
<add> $this->expectException(RuntimeException::class);
<add> $this->expectExceptionMessage('Could not parse');
<add>
<add> RouteBuilder::parseShortString($value);
<add> }
<add>
<ide> /**
<ide> * Test if a route name already exist
<ide> * | 2 |
Javascript | Javascript | expose registry as ember.registry | 14be80cc6af1ed4cc203cb8b1f6a200f7cf3e400 | <ide><path>packages/ember-runtime/lib/main.js
<ide> import Namespace from 'ember-runtime/system/namespace';
<ide> import EmberObject from 'ember-runtime/system/object';
<ide> import TrackedArray from 'ember-runtime/system/tracked_array';
<ide> import SubArray from 'ember-runtime/system/subarray';
<del>import { Container } from "ember-runtime/system/container";
<add>import { Container, Registry } from "ember-runtime/system/container";
<ide> import ArrayProxy from 'ember-runtime/system/array_proxy';
<ide> import ObjectProxy from 'ember-runtime/system/object_proxy';
<ide> import CoreObject from 'ember-runtime/system/core_object';
<ide> Ember.Object = EmberObject;
<ide> Ember.TrackedArray = TrackedArray;
<ide> Ember.SubArray = SubArray;
<ide> Ember.Container = Container;
<add>Ember.Registry = Registry;
<ide> Ember.Namespace = Namespace;
<ide> Ember.Enumerable = Enumerable;
<ide> Ember.ArrayProxy = ArrayProxy; | 1 |
Python | Python | fix downstream rendering in webui | 479d6220b7d0c93d5ad6a7d53d875e777287342b | <ide><path>airflow/www/views.py
<ide> def graph(self, session=None):
<ide> def get_downstream(task):
<ide> for downstream_task in task.downstream_list:
<ide> edge = {
<del> 'source_id': downstream_task.task_id,
<add> 'source_id': task.task_id,
<ide> 'target_id': downstream_task.task_id,
<ide> }
<ide> if edge not in edges: | 1 |
Java | Java | restore state field in abstractserverhttpresponse | d4446c79b659d1230bdd8caf3f233de5c39ce127 | <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/AbstractServerHttpResponse.java
<ide>
<ide> import java.util.ArrayList;
<ide> import java.util.List;
<add>import java.util.concurrent.atomic.AtomicReference;
<ide> import java.util.function.Supplier;
<ide> import java.util.stream.Collectors;
<ide>
<ide> */
<ide> public abstract class AbstractServerHttpResponse implements ServerHttpResponse {
<ide>
<add> /**
<add> * COMMITTING -> COMMITTED is the period after doCommit is called but before
<add> * the response status and headers have been applied to the underlying
<add> * response during which time pre-commit actions can still make changes to
<add> * the response status and headers.
<add> */
<add> private enum State {NEW, COMMITTING, COMMITTED};
<add>
<add>
<ide> private final Log logger = LogFactory.getLog(getClass());
<ide>
<ide> private final DataBufferFactory dataBufferFactory;
<ide> public abstract class AbstractServerHttpResponse implements ServerHttpResponse {
<ide>
<ide> private final MultiValueMap<String, ResponseCookie> cookies;
<ide>
<del> private volatile boolean committed;
<add> private final AtomicReference<State> state = new AtomicReference<>(State.NEW);
<ide>
<ide> private final List<Supplier<? extends Mono<Void>>> commitActions = new ArrayList<>(4);
<ide>
<ide> public final DataBufferFactory bufferFactory() {
<ide> @Override
<ide> public boolean setStatusCode(HttpStatus statusCode) {
<ide> Assert.notNull(statusCode);
<del> if (this.committed) {
<add> if (this.state.get() == State.COMMITTED) {
<ide> if (logger.isDebugEnabled()) {
<ide> logger.debug("Can't set the status " + statusCode.toString() +
<ide> " because the HTTP response has already been committed");
<ide> public HttpStatus getStatusCode() {
<ide>
<ide> @Override
<ide> public HttpHeaders getHeaders() {
<del> return (this.committed ? HttpHeaders.readOnlyHttpHeaders(this.headers) : this.headers);
<add> return (this.state.get() == State.COMMITTED ?
<add> HttpHeaders.readOnlyHttpHeaders(this.headers) : this.headers);
<ide> }
<ide>
<ide> @Override
<ide> public MultiValueMap<String, ResponseCookie> getCookies() {
<del> return (this.committed ? CollectionUtils.unmodifiableMultiValueMap(this.cookies) : this.cookies);
<add> return (this.state.get() == State.COMMITTED ?
<add> CollectionUtils.unmodifiableMultiValueMap(this.cookies) : this.cookies);
<ide> }
<ide>
<ide> @Override
<ide> protected Mono<Void> doCommit() {
<ide> * @return a completion publisher
<ide> */
<ide> protected Mono<Void> doCommit(Supplier<? extends Mono<Void>> writeAction) {
<del> if (this.committed) {
<add> if (!this.state.compareAndSet(State.NEW, State.COMMITTING)) {
<ide> if (logger.isDebugEnabled()) {
<ide> logger.debug("Can't set the status " + statusCode.toString() +
<ide> " because the HTTP response has already been committed");
<ide> }
<ide> return Mono.empty();
<ide> }
<ide>
<del> this.committed = true;
<del>
<ide> this.commitActions.add(() -> {
<ide> applyStatusCode();
<ide> applyHeaders();
<ide> applyCookies();
<add> this.state.set(State.COMMITTED);
<ide> return Mono.empty();
<ide> });
<ide>
<ide><path>spring-web/src/test/java/org/springframework/http/server/reactive/ServerHttpResponseTests.java
<ide> import static junit.framework.TestCase.assertTrue;
<ide> import static org.junit.Assert.assertEquals;
<ide> import static org.junit.Assert.assertFalse;
<del>import static org.junit.Assert.assertNull;
<ide> import static org.junit.Assert.assertSame;
<ide>
<ide> /**
<ide> public void beforeCommitWithComplete() throws Exception {
<ide> assertEquals("c", new String(response.body.get(2).asByteBuffer().array(), StandardCharsets.UTF_8));
<ide> }
<ide>
<del> @Test
<del> public void beforeCommitActionWithError() throws Exception {
<del> TestServerHttpResponse response = new TestServerHttpResponse();
<del> IllegalStateException error = new IllegalStateException("boo");
<del> response.beforeCommit(() -> Mono.error(error));
<del> response.writeWith(Flux.just(wrap("a"), wrap("b"), wrap("c"))).block();
<del>
<del> assertTrue("beforeCommit action errors should be ignored", response.statusCodeWritten);
<del> assertTrue("beforeCommit action errors should be ignored", response.headersWritten);
<del> assertTrue("beforeCommit action errors should be ignored", response.cookiesWritten);
<del> assertNull(response.getCookies().get("ID"));
<del>
<del> assertEquals(3, response.body.size());
<del> assertEquals("a", new String(response.body.get(0).asByteBuffer().array(), StandardCharsets.UTF_8));
<del> assertEquals("b", new String(response.body.get(1).asByteBuffer().array(), StandardCharsets.UTF_8));
<del> assertEquals("c", new String(response.body.get(2).asByteBuffer().array(), StandardCharsets.UTF_8));
<del> }
<del>
<ide> @Test
<ide> public void beforeCommitActionWithSetComplete() throws Exception {
<ide> ResponseCookie cookie = ResponseCookie.from("ID", "123").build(); | 2 |
Python | Python | update the `dtype` typing tests | 322c917b0cfc7d4a65e7ab198e81afc14778738e | <ide><path>numpy/typing/tests/data/fail/dtype.py
<ide> class Test2:
<ide> "field2": (int, 3),
<ide> }
<ide> )
<del>
<del>np.dtype[np.float64](np.int64) # E: Argument 1 to "dtype" has incompatible type
<ide><path>numpy/typing/tests/data/reveal/dtype.py
<add>import ctypes as ct
<ide> import numpy as np
<ide>
<ide> dtype_U: np.dtype[np.str_]
<ide> reveal_type(np.dtype(bool)) # E: numpy.dtype[numpy.bool_]
<ide> reveal_type(np.dtype(str)) # E: numpy.dtype[numpy.str_]
<ide> reveal_type(np.dtype(bytes)) # E: numpy.dtype[numpy.bytes_]
<add>reveal_type(np.dtype(object)) # E: numpy.dtype[numpy.object_]
<add>
<add># ctypes
<add>reveal_type(np.dtype(ct.c_double)) # E: numpy.dtype[{double}]
<add>reveal_type(np.dtype(ct.c_longlong)) # E: numpy.dtype[{longlong}]
<add>reveal_type(np.dtype(ct.c_uint32)) # E: numpy.dtype[{uint32}]
<add>reveal_type(np.dtype(ct.c_bool)) # E: numpy.dtype[numpy.bool_]
<add>reveal_type(np.dtype(ct.c_char)) # E: numpy.dtype[numpy.bytes_]
<add>reveal_type(np.dtype(ct.py_object)) # E: numpy.dtype[numpy.object_]
<ide>
<ide> # Special case for None
<ide> reveal_type(np.dtype(None)) # E: numpy.dtype[{double}] | 2 |
Ruby | Ruby | convert stream broadcasting to a string | 046e32656efa989a112e9870d8aa25a49f944204 | <ide><path>actioncable/lib/action_cable/channel/streams.rb
<ide> module Streams
<ide> # Start streaming from the named <tt>broadcasting</tt> pubsub queue. Optionally, you can pass a <tt>callback</tt> that'll be used
<ide> # instead of the default of just transmitting the updates straight to the subscriber.
<ide> def stream_from(broadcasting, callback = nil)
<add> broadcasting = String(broadcasting)
<ide> # Don't send the confirmation until pubsub#subscribe is successful
<ide> defer_subscription_confirmation!
<ide>
<ide><path>actioncable/test/channel/stream_test.rb
<ide> def send_confirmation
<ide> end
<ide> end
<ide>
<add> class SymbolChannel < ActionCable::Channel::Base
<add> def subscribed
<add> stream_from :channel
<add> end
<add> end
<add>
<ide> test "streaming start and stop" do
<ide> run_in_eventmachine do
<ide> connection = TestConnection.new
<ide> def send_confirmation
<ide> end
<ide> end
<ide>
<add> test "stream from non-string channel" do
<add> run_in_eventmachine do
<add> connection = TestConnection.new
<add> connection.expects(:pubsub).returns mock().tap { |m| m.expects(:subscribe).with("channel", kind_of(Proc), kind_of(Proc)).returns stub_everything(:pubsub) }
<add> channel = SymbolChannel.new connection, ""
<add>
<add> connection.expects(:pubsub).returns mock().tap { |m| m.expects(:unsubscribe) }
<add> channel.unsubscribe_from_channel
<add> end
<add> end
<add>
<ide> test "stream_for" do
<ide> run_in_eventmachine do
<ide> connection = TestConnection.new | 2 |
Python | Python | remove unused import statement in keras dir | 1c460e1e08ab2ff65678ca0d3b97b578e5afd931 | <ide><path>keras/datasets/cifar.py
<ide> from __future__ import absolute_import
<ide> import sys
<ide> from six.moves import cPickle
<del>from six.moves import range
<ide>
<ide>
<ide> def load_batch(fpath, label_key='labels'):
<ide><path>keras/wrappers/scikit_learn.py
<ide> import copy
<ide> import inspect
<ide> import types
<del>import numpy as np
<ide>
<ide> from ..utils.np_utils import to_categorical
<ide> from ..models import Sequential | 2 |
Text | Text | add pathstream to inthewild.md | 7ecca7036bbeab93f5be6c45fd05df0584d89430 | <ide><path>INTHEWILD.md
<ide> Currently, **officially** using Airflow:
<ide> 1. [Pandora Media](https://www.pandora.com/) [[@Acehaidrey](https://github.com/Acehaidrey) & [@wolfier](https://github.com/wolfier)]
<ide> 1. [Paradigma Digital](https://www.paradigmadigital.com/) [[@paradigmadigital](https://github.com/paradigmadigital)]
<ide> 1. [Paraná Banco](https://paranabanco.com.br/) [[@lopesdiego12](https://github.com/lopesdiego12/)]
<add>1. [Pathstream](https://pathstream.com) [[@pJackDanger](https://github.com/JackDanger)]
<ide> 1. [PayFit](https://payfit.com) [[@pcorbel](https://github.com/pcorbel)]
<ide> 1. [PAYMILL](https://www.paymill.com/) [[@paymill](https://github.com/paymill) & [@matthiashuschle](https://github.com/matthiashuschle)]
<ide> 1. [PayPal](https://www.paypal.com/) [[@r39132](https://github.com/r39132) & [@jhsenjaliya](https://github.com/jhsenjaliya)] | 1 |
Java | Java | allow non-public @transactional test methods | df7b24b8e771abbbebdb034fb436d37812329689 | <ide><path>spring-test/src/main/java/org/springframework/test/context/transaction/TransactionalTestExecutionListener.java
<ide> public class TransactionalTestExecutionListener extends AbstractTestExecutionLis
<ide> @SuppressWarnings("deprecation")
<ide> private static final TransactionConfigurationAttributes defaultTxConfigAttributes = new TransactionConfigurationAttributes();
<ide>
<del> protected final TransactionAttributeSource attributeSource = new AnnotationTransactionAttributeSource();
<add> // Do not require @Transactional test methods to be public.
<add> protected final TransactionAttributeSource attributeSource = new AnnotationTransactionAttributeSource(false);
<ide>
<ide> @SuppressWarnings("deprecation")
<ide> private TransactionConfigurationAttributes configurationAttributes;
<ide><path>spring-test/src/test/java/org/springframework/test/context/testng/AnnotationConfigTransactionalTestNGSpringContextTests.java
<ide> void setUp() throws Exception {
<ide> }
<ide>
<ide> @Test
<del> public void modifyTestDataWithinTransaction() {
<add> void modifyTestDataWithinTransaction() {
<ide> assertInTransaction(true);
<ide> assertAddPerson(JANE);
<ide> assertAddPerson(SUE);
<ide><path>spring-test/src/test/java/org/springframework/test/context/testng/ConcreteTransactionalTestNGSpringContextTests.java
<ide> void setUp() throws Exception {
<ide> }
<ide>
<ide> @Test
<del> public void modifyTestDataWithinTransaction() {
<add> void modifyTestDataWithinTransaction() {
<ide> assertInTransaction(true);
<ide> assertAddPerson(JANE);
<ide> assertAddPerson(SUE); | 3 |
Python | Python | add a patch to support python 2.7 | ed8a0f6ad4780178e78c07a86b973fccec9c7d24 | <ide><path>celery/bin/base.py
<ide> from celery.exceptions import CDeprecationWarning, CPendingDeprecationWarning
<ide> from celery.five import (getfullargspec, items, long_t,
<ide> python_2_unicode_compatible, string, string_t,
<del> text_t)
<add> text_t, PY2)
<ide> from celery.platforms import EX_FAILURE, EX_OK, EX_USAGE, isatty
<ide> from celery.utils import imports, term, text
<ide> from celery.utils.functional import dictfilter
<ide> def execute_from_commandline(self, argv=None):
<ide> try:
<ide> argv = self.setup_app_from_commandline(argv)
<ide> except ModuleNotFoundError as e:
<del> self.on_error(UNABLE_TO_LOAD_APP_MODULE_NOT_FOUND.format(e.name))
<add> # In Python 2.7 and below, there is no name instance for exceptions
<add> # TODO: Remove this once we drop support for Python 2.7
<add> if PY2:
<add> package_name = e.message.replace("No module named ", "")
<add> else:
<add> package_name = e.name
<add> self.on_error(UNABLE_TO_LOAD_APP_MODULE_NOT_FOUND.format(package_name))
<ide> return EX_FAILURE
<ide> except AttributeError as e:
<ide> msg = e.args[0].capitalize() | 1 |
Javascript | Javascript | add protections against malformed data | 3d05eee0ea40f70d06f51cbfa7d1c0316cc557da | <ide><path>common/app/routes/challenges/utils.js
<ide> import { compose } from 'redux';
<ide> import { bonfire, html, js } from '../../utils/challengeTypes';
<add>import protect from '../../utils/empty-protector';
<ide>
<ide> export function encodeScriptTags(value) {
<ide> return value
<ide> export function loggerToStr(args) {
<ide> .reduce((str, arg) => str + arg + '\n', '');
<ide> }
<ide>
<del>export function getFirstChallenge(
<del> { superBlock, block, challenge },
<del> result
<del>) {
<del> return challenge[
<del> block[
<del> superBlock[
<del> result[0]
<del> ].blocks[0]
<del> ].challenges[0]
<del> ];
<del>}
<del>
<ide> export function getNextChallenge(
<ide> current,
<ide> entities,
<ide> export function getMouse(e, [dx, dy]) {
<ide> return [pageX - dx, pageY - dy];
<ide> }
<ide>
<del>const emptyProtector = {
<del> blocks: [],
<del> challenges: []
<del>};
<del>// protect against malformed data
<del>function protect(block) {
<del> // if no block or block has no challenges or blocks
<del> // use protector
<del> if (!block || !(block.challenges || block.blocks)) {
<del> return emptyProtector;
<del> }
<del> return block;
<del>}
<del>
<ide> // interface Node {
<ide> // isHidden: Boolean,
<ide> // children: Void|[ ...Node ],
<ide><path>common/app/utils/empty-protector.js
<add>const emptyProtector = {
<add> blocks: [],
<add> challenges: []
<add>};
<add>// protect against malformed map data
<add>// protect(block: { challenges: [], block: [] }|Void) => block|emptyProtector
<add>export default function protect(block) {
<add> // if no block or block has no challenges or blocks
<add> if (!block || !(block.challenges || block.blocks)) {
<add> return emptyProtector;
<add> }
<add> return block;
<add>}
<ide><path>common/utils/get-first-challenge.js
<add>import emptyProtector from '../app/utils/empty-protector';
<add>
<add>export function checkMapData(
<add> {
<add> entities: {
<add> challenge,
<add> block,
<add> superBlock,
<add> challengeIdToName
<add> },
<add> result
<add> }
<add>) {
<add> if (
<add> !challenge ||
<add> !block ||
<add> !superBlock ||
<add> !challengeIdToName ||
<add> !result ||
<add> !result.length
<add> ) {
<add> throw new Error(
<add> 'entities not found, db may not be properly seeded. Crashing hard'
<add> );
<add> }
<add>}
<add>// getFirstChallenge(
<add>// map: {
<add>// entities: { challenge: Object, block: Object, superBlock: Object },
<add>// result: [...superBlockDashedName: String]
<add>// }
<add>// ) => Challenge|Void
<add>export function getFirstChallenge({
<add> entities: { superBlock, block, challenge },
<add> result
<add>}) {
<add> return challenge[
<add> emptyProtector(block[
<add> emptyProtector(superBlock[
<add> result[0]
<add> ]).blocks[0]
<add> ]).challenges[0]
<add> ];
<add>}
<ide><path>server/boot/challenge.js
<ide> import _ from 'lodash';
<del>// import { Observable, Scheduler } from 'rx';
<ide> import debug from 'debug';
<ide> import accepts from 'accepts';
<add>import dedent from 'dedent';
<ide>
<ide> import { ifNoUserSend } from '../utils/middleware';
<ide> import { cachedMap } from '../utils/map';
<ide> import createNameIdMap from '../../common/utils/create-name-id-map';
<add>import {
<add> checkMapData,
<add> getFirstChallenge
<add>} from '../../common/utils/get-first-challenge';
<ide>
<ide> const log = debug('fcc:boot:challenges');
<ide>
<ide> export default function(app) {
<ide> result,
<ide> entities: createNameIdMap(entities)
<ide> }))
<del> .map(({
<del> result,
<del> entities: {
<del> challenge: challengeMap,
<del> block: blockMap,
<del> superBlock: superBlockMap,
<del> challengeIdToName
<del> }
<del> }) => {
<add> .map(map => {
<add> checkMapData(map);
<add> const {
<add> entities: { challenge: challengeMap, challengeIdToName }
<add> } = map;
<ide> let finalChallenge;
<ide> const dashedName = challengeIdToName[user && user.currentChallengeId];
<ide> finalChallenge = challengeMap[dashedName];
<del> if (
<del> !challengeMap ||
<del> !blockMap ||
<del> !superBlockMap ||
<del> !result ||
<del> !result.length
<del> ) {
<del> throw new Error(
<del> 'entities not found, db may not be properly seeded. Crashing hard'
<del> );
<del> }
<ide> // redirect to first challenge
<ide> if (!finalChallenge) {
<del> finalChallenge = challengeMap[
<del> block[
<del> superBlockMap[
<del> result[0]
<del> ].blocks[0]
<del> ].challenges[0]
<del> ];
<add> finalChallenge = getFirstChallenge(map);
<ide> }
<ide> const { block, dashedName: finalDashedName } = finalChallenge || {};
<add> if (!finalDashedName || !block) {
<add> // this should normally not be hit if database is properly seeded
<add> console.error(new Error(dedent`
<add> Attemped to find '${dashedName}'
<add> from '${user && user.currentChallengeId || 'no challenge id found'}'
<add> but came up empty.
<add> db may not be properly seeded.
<add> `));
<add> if (dashedName) {
<add> // attempt to find according to dashedName
<add> return `/challenges/${dashedName}`;
<add> } else {
<add> return null;
<add> }
<add> }
<ide> return `/challenges/${block}/${finalDashedName}`;
<ide> })
<ide> .subscribe( | 4 |
PHP | PHP | reduce duplication in test case | 8800d7bdec1a2a08999ca7932a3b830a0ec79c6d | <ide><path>lib/Cake/Test/Case/View/Helper/TextHelperTest.php
<ide> public function testAutoLinkEscape() {
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide>
<add>/**
<add> * Data provider for autoLinking
<add> */
<add> public static function autoLinkProvider() {
<add> return array(
<add> array(
<add> 'This is a test text',
<add> 'This is a test text',
<add> ),
<add> array(
<add> 'This is a test that includes (www.cakephp.org)',
<add> 'This is a test that includes (<a href="http://www.cakephp.org">www.cakephp.org</a>)',
<add> ),
<add> array(
<add> 'This is a test that includes www.cakephp.org:8080',
<add> 'This is a test that includes <a href="http://www.cakephp.org:8080">www.cakephp.org:8080</a>',
<add> ),
<add> array(
<add> 'This is a test that includes http://de.wikipedia.org/wiki/Kanton_(Schweiz)#fragment',
<add> 'This is a test that includes <a href="http://de.wikipedia.org/wiki/Kanton_(Schweiz)#fragment">http://de.wikipedia.org/wiki/Kanton_(Schweiz)#fragment</a>',
<add> ),
<add> array(
<add> 'This is a test that includes www.wikipedia.org/wiki/Kanton_(Schweiz)#fragment',
<add> 'This is a test that includes <a href="http://www.wikipedia.org/wiki/Kanton_(Schweiz)#fragment">www.wikipedia.org/wiki/Kanton_(Schweiz)#fragment</a>',
<add> ),
<add> array(
<add> 'This is a test that includes http://example.com/test.php?foo=bar text',
<add> 'This is a test that includes <a href="http://example.com/test.php?foo=bar">http://example.com/test.php?foo=bar</a> text',
<add> ),
<add> array(
<add> 'This is a test that includes www.example.com/test.php?foo=bar text',
<add> 'This is a test that includes <a href="http://www.example.com/test.php?foo=bar">www.example.com/test.php?foo=bar</a> text',
<add> ),
<add> array(
<add> 'Text with a partial www.cakephp.org URL',
<add> 'Text with a partial <a href="http://www.cakephp.org">www.cakephp.org</a> URL',
<add> ),
<add> array(
<add> 'Text with a partial WWW.cakephp.org URL',
<add> 'Text with a partial <a href="http://WWW.cakephp.org">WWW.cakephp.org</a> URL',
<add> ),
<add> array(
<add> 'Text with a partial WWW.cakephp.org ©, URL',
<add> 'Text with a partial <a href="http://WWW.cakephp.org">WWW.cakephp.org</a> &copy, URL',
<add> ),
<add> array(
<add> 'Text with a url www.cot.ag/cuIb2Q and more',
<add> 'Text with a url <a href="http://www.cot.ag/cuIb2Q">www.cot.ag/cuIb2Q</a> and more',
<add> ),
<add> array(
<add> 'Text with a url http://www.does--not--work.com and more',
<add> 'Text with a url <a href="http://www.does--not--work.com">http://www.does--not--work.com</a> and more',
<add> ),
<add> array(
<add> 'Text with a url http://www.not--work.com and more',
<add> 'Text with a url <a href="http://www.not--work.com">http://www.not--work.com</a> and more',
<add> ),
<add> );
<add> }
<add>
<ide> /**
<ide> * testAutoLinkUrls method
<ide> *
<add> * @dataProvider autoLinkProvider
<ide> * @return void
<ide> */
<del> public function testAutoLinkUrls() {
<del> $text = 'This is a test text';
<del> $expected = 'This is a test text';
<del> $result = $this->Text->autoLinkUrls($text);
<del> $this->assertEquals($expected, $result);
<del>
<del> $text = 'This is a test that includes (www.cakephp.org)';
<del> $expected = 'This is a test that includes (<a href="http://www.cakephp.org">www.cakephp.org</a>)';
<del> $result = $this->Text->autoLinkUrls($text);
<del> $this->assertEquals($expected, $result);
<del>
<del> $text = 'This is a test that includes www.cakephp.org:8080';
<del> $expected = 'This is a test that includes <a href="http://www.cakephp.org:8080">www.cakephp.org:8080</a>';
<add> public function testAutoLinkUrls($text, $expected) {
<ide> $result = $this->Text->autoLinkUrls($text);
<ide> $this->assertEquals($expected, $result);
<add> }
<ide>
<del> $text = 'This is a test that includes http://de.wikipedia.org/wiki/Kanton_(Schweiz)#fragment';
<del> $expected = 'This is a test that includes <a href="http://de.wikipedia.org/wiki/Kanton_(Schweiz)#fragment">http://de.wikipedia.org/wiki/Kanton_(Schweiz)#fragment</a>';
<del> $result = $this->Text->autoLinkUrls($text);
<del> $this->assertEquals($expected, $result);
<del>
<del> $text = 'This is a test that includes www.wikipedia.org/wiki/Kanton_(Schweiz)#fragment';
<del> $expected = 'This is a test that includes <a href="http://www.wikipedia.org/wiki/Kanton_(Schweiz)#fragment">www.wikipedia.org/wiki/Kanton_(Schweiz)#fragment</a>';
<del> $result = $this->Text->autoLinkUrls($text);
<del> $this->assertEquals($expected, $result);
<del>
<del> $text = 'This is a test that includes http://example.com/test.php?foo=bar text';
<del> $expected = 'This is a test that includes <a href="http://example.com/test.php?foo=bar">http://example.com/test.php?foo=bar</a> text';
<del> $result = $this->Text->autoLinkUrls($text);
<del> $this->assertEquals($expected, $result);
<del>
<del> $text = 'This is a test that includes www.example.com/test.php?foo=bar text';
<del> $expected = 'This is a test that includes <a href="http://www.example.com/test.php?foo=bar">www.example.com/test.php?foo=bar</a> text';
<del> $result = $this->Text->autoLinkUrls($text);
<del> $this->assertEquals($expected, $result);
<del>
<del> $text = 'Text with a partial www.cakephp.org URL';
<del> $expected = 'Text with a partial <a href="http://www.cakephp.org"\s*>www.cakephp.org</a> URL';
<del> $result = $this->Text->autoLinkUrls($text);
<del> $this->assertRegExp('#^' . $expected . '$#', $result);
<del>
<add>/**
<add> * Test the options for autoLinkUrls
<add> *
<add> * @return void
<add> */
<add> public function testAutoLinkUrlsOptions() {
<ide> $text = 'Text with a partial www.cakephp.org URL';
<ide> $expected = 'Text with a partial <a href="http://www.cakephp.org" \s*class="link">www.cakephp.org</a> URL';
<ide> $result = $this->Text->autoLinkUrls($text, array('class' => 'link'));
<ide> $this->assertRegExp('#^' . $expected . '$#', $result);
<ide>
<del> $text = 'Text with a partial WWW.cakephp.org URL';
<del> $expected = 'Text with a partial <a href="http://WWW.cakephp.org"\s*>WWW.cakephp.org</a> URL';
<del> $result = $this->Text->autoLinkUrls($text);
<del> $this->assertRegExp('#^' . $expected . '$#', $result);
<del>
<ide> $text = 'Text with a partial WWW.cakephp.org © URL';
<ide> $expected = 'Text with a partial <a href="http://WWW.cakephp.org"\s*>WWW.cakephp.org</a> © URL';
<ide> $result = $this->Text->autoLinkUrls($text, array('escape' => false));
<ide> $this->assertRegExp('#^' . $expected . '$#', $result);
<del>
<del> $text = 'Text with a url www.cot.ag/cuIb2Q and more';
<del> $expected = 'Text with a url <a href="http://www.cot.ag/cuIb2Q">www.cot.ag/cuIb2Q</a> and more';
<del> $result = $this->Text->autoLinkUrls($text);
<del> $this->assertEquals($expected, $result);
<del>
<del> $text = 'Text with a url http://www.does--not--work.com and more';
<del> $expected = 'Text with a url <a href="http://www.does--not--work.com">http://www.does--not--work.com</a> and more';
<del> $result = $this->Text->autoLinkUrls($text);
<del> $this->assertEquals($expected, $result);
<del>
<del> $text = 'Text with a url http://www.not--work.com and more';
<del> $expected = 'Text with a url <a href="http://www.not--work.com">http://www.not--work.com</a> and more';
<del> $result = $this->Text->autoLinkUrls($text);
<del> $this->assertEquals($expected, $result);
<ide> }
<ide>
<ide> /** | 1 |
Javascript | Javascript | use common.port to determine debugger port | 937662b03e55b639792d7b635f80fb82db5a6044 | <ide><path>test/simple/test-debugger-client.js
<ide> var common = require('../common');
<ide> var assert = require('assert');
<ide> var debug = require('_debugger');
<ide>
<add>var debugPort = common.PORT + 1337;
<add>debug.port = debugPort;
<ide> var spawn = require('child_process').spawn;
<ide>
<ide> setTimeout(function() {
<ide> var script = 'setTimeout(function () { console.log("blah"); });' +
<ide> var nodeProcess;
<ide>
<ide> function doTest(cb, done) {
<del> nodeProcess = spawn(process.execPath, ['-e', script]);
<add> var args = ['--debug=' + debugPort, '-e', script];
<add> nodeProcess = spawn(process.execPath, args);
<ide>
<ide> nodeProcess.stdout.once('data', function(c) {
<ide> console.log('>>> new node process: %d', nodeProcess.pid); | 1 |
PHP | PHP | add basic implementation of form\schema | ae69a8054e76c918a42068e4b9e0ccc4700d3b5f | <ide><path>src/Form/Schema.php
<add><?php
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * For full copyright and license information, please see the LICENSE.txt
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> * @link http://cakephp.org CakePHP(tm) Project
<add> * @since 3.0.0
<add> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\Form;
<add>
<add>/**
<add> * Contains the schema information for Form instances.
<add> */
<add>class Schema {
<add>
<add> protected $_fields = [];
<add>
<add> protected $_fieldDefaults = [
<add> 'type' => null,
<add> 'length' => null,
<add> 'required' => false,
<add> ];
<add>
<add> public function addField($name, $attrs) {
<add> $attrs = array_intersect_key($attrs, $this->_fieldDefaults);
<add> $this->_fields[$name] = $attrs + $this->_fieldDefaults;
<add> return $this;
<add> }
<add>
<add> public function removeField($name) {
<add> unset($this->_fields[$name]);
<add> return $this;
<add> }
<add>
<add> public function fields() {
<add> return array_keys($this->_fields);
<add> }
<add>
<add> public function field($name) {
<add> if (!isset($this->_fields[$name])) {
<add> return null;
<add> }
<add> return $this->_fields[$name];
<add> }
<add>}
<ide><path>tests/TestCase/Form/SchemaTest.php
<add><?php
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * For full copyright and license information, please see the LICENSE.txt
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> * @link http://cakephp.org CakePHP(tm) Project
<add> * @since 3.0.0
<add> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\Test\TestCase\Form;
<add>
<add>use Cake\Form\Schema;
<add>use Cake\TestSuite\TestCase;
<add>
<add>/**
<add> * Form schema test case.
<add> */
<add>class SchemaTest extends TestCase {
<add>
<add>/**
<add> * test adding fields.
<add> *
<add> * @return void
<add> */
<add> public function testAddingFields() {
<add> $schema = new Schema();
<add>
<add> $res = $schema->addField('name', ['type' => 'string']);
<add> $this->assertSame($schema, $res, 'Should be chainable');
<add>
<add> $this->assertEquals(['name'], $schema->fields());
<add> $res = $schema->field('name');
<add> $expected = ['type' => 'string', 'length' => null, 'required' => false];
<add> $this->assertEquals($expected, $res);
<add> }
<add>
<add>/**
<add> * test adding field whitelist attrs
<add> *
<add> * @return void
<add> */
<add> public function testAddingFieldsWhitelist() {
<add> $schema = new Schema();
<add>
<add> $schema->addField('name', ['derp' => 'derp', 'type' => 'string']);
<add> $expected = ['type' => 'string', 'length' => null, 'required' => false];
<add> $this->assertEquals($expected, $schema->field('name'));
<add> }
<add>
<add>/**
<add> * Test removing fields.
<add> *
<add> * @return void
<add> */
<add> public function testRemovingFields() {
<add> $schema = new Schema();
<add>
<add> $schema->addField('name', ['type' => 'string']);
<add> $this->assertEquals(['name'], $schema->fields());
<add>
<add> $res = $schema->removeField('name');
<add> $this->assertSame($schema, $res, 'Should be chainable');
<add> $this->assertEquals([], $schema->fields());
<add> $this->assertNull($schema->field('name'));
<add> }
<add>
<add>} | 2 |
Javascript | Javascript | append feature to 'features'. update tests | 7caa2fc1a703988532c61ffba17879f5d3d52520 | <ide><path>src/js/control-bar/mute-toggle.js
<ide> vjs.MuteToggle = vjs.Button.extend({
<ide> player.on('volumechange', vjs.bind(this, this.update));
<ide>
<ide> // hide mute toggle if the current tech doesn't support volume control
<del> if (player.tech && player.tech['volumeControl'] === false) {
<add> if (player.tech && player.tech['volumeControlFeature'] === false) {
<ide> this.addClass('vjs-hidden');
<ide> }
<ide> player.on('loadstart', vjs.bind(this, function(){
<del> if (player.tech['volumeControl'] === false) {
<add> if (player.tech['volumeControlFeature'] === false) {
<ide> this.addClass('vjs-hidden');
<ide> } else {
<ide> this.removeClass('vjs-hidden');
<ide><path>src/js/control-bar/playback-rate-menu-button.js
<ide> vjs.PlaybackRateMenuButton.prototype.onClick = function(){
<ide>
<ide> vjs.PlaybackRateMenuButton.prototype.playbackRateSupported = function(){
<ide> return this.player().tech
<del> && this.player().tech['playbackRate']
<add> && this.player().tech['playbackRateFeature']
<ide> && this.player().options()['playbackRates']
<ide> && this.player().options()['playbackRates'].length > 0
<ide> ;
<ide><path>src/js/control-bar/volume-control.js
<ide> vjs.VolumeControl = vjs.Component.extend({
<ide> vjs.Component.call(this, player, options);
<ide>
<ide> // hide volume controls when they're not supported by the current tech
<del> if (player.tech && player.tech['volumeControl'] === false) {
<add> if (player.tech && player.tech['volumeControlFeature'] === false) {
<ide> this.addClass('vjs-hidden');
<ide> }
<ide> player.on('loadstart', vjs.bind(this, function(){
<del> if (player.tech['volumeControl'] === false) {
<add> if (player.tech['volumeControlFeature'] === false) {
<ide> this.addClass('vjs-hidden');
<ide> } else {
<ide> this.removeClass('vjs-hidden');
<ide><path>src/js/control-bar/volume-menu-button.js
<ide> vjs.VolumeMenuButton = vjs.MenuButton.extend({
<ide> player.on('volumechange', vjs.bind(this, this.update));
<ide>
<ide> // hide mute toggle if the current tech doesn't support volume control
<del> if (player.tech && player.tech.volumeControl === false) {
<add> if (player.tech && player.tech['volumeControlFeature'] === false) {
<ide> this.addClass('vjs-hidden');
<ide> }
<ide> player.on('loadstart', vjs.bind(this, function(){
<del> if (player.tech.volumeControl === false) {
<add> if (player.tech['volumeControlFeature'] === false) {
<ide> this.addClass('vjs-hidden');
<ide> } else {
<ide> this.removeClass('vjs-hidden');
<ide><path>src/js/exports.js
<ide> goog.exportSymbol('videojs.CaptionsButton', vjs.CaptionsButton);
<ide> goog.exportSymbol('videojs.ChaptersButton', vjs.ChaptersButton);
<ide>
<ide> goog.exportSymbol('videojs.MediaTechController', vjs.MediaTechController);
<del>goog.exportProperty(vjs.MediaTechController.prototype, 'volumeControl', vjs.MediaTechController.prototype.volumeControl);
<del>goog.exportProperty(vjs.MediaTechController.prototype, 'fullscreenResize', vjs.MediaTechController.prototype.fullscreenResize);
<del>goog.exportProperty(vjs.MediaTechController.prototype, 'progressEvents', vjs.MediaTechController.prototype.progressEvents);
<del>goog.exportProperty(vjs.MediaTechController.prototype, 'timeupdateEvents', vjs.MediaTechController.prototype.timeupdateEvents);
<add>goog.exportProperty(vjs.MediaTechController.prototype, 'volumeControlFeature', vjs.MediaTechController.prototype.volumeControlFeature);
<add>goog.exportProperty(vjs.MediaTechController.prototype, 'fullscreenResizeFeature', vjs.MediaTechController.prototype.fullscreenResizeFeature);
<add>goog.exportProperty(vjs.MediaTechController.prototype, 'playbackRateFeature', vjs.MediaTechController.prototype.playbackRateFeature);
<add>goog.exportProperty(vjs.MediaTechController.prototype, 'progressEventsFeature', vjs.MediaTechController.prototype.progressEventsFeature);
<add>goog.exportProperty(vjs.MediaTechController.prototype, 'timeupdateEventsFeature', vjs.MediaTechController.prototype.timeupdateEventsFeature);
<ide> goog.exportProperty(vjs.MediaTechController.prototype, 'setPoster', vjs.MediaTechController.prototype.setPoster);
<ide>
<ide>
<ide><path>src/js/media/html5.js
<ide> vjs.Html5 = vjs.MediaTechController.extend({
<ide> /** @constructor */
<ide> init: function(player, options, ready){
<ide> // volume cannot be changed from 1 on iOS
<del> this['volumeControl'] = vjs.Html5.canControlVolume();
<add> this['volumeControlFeature'] = vjs.Html5.canControlVolume();
<ide>
<ide> // just in case; or is it excessively...
<del> this['playbackRate'] = vjs.Html5.canControlPlaybackRate();
<add> this['playbackRateFeature'] = vjs.Html5.canControlPlaybackRate();
<ide>
<ide> // In iOS, if you move a video element in the DOM, it breaks video playback.
<ide> this['movingMediaElementInDOM'] = !vjs.IS_IOS;
<ide>
<ide> // HTML video is able to automatically resize when going to fullscreen
<del> this['fullscreenResize'] = true;
<add> this['fullscreenResizeFeature'] = true;
<ide>
<ide> // HTML video supports progress events
<ide> this.features['progressEvents'] = true;
<ide><path>src/js/media/media.js
<ide> vjs.MediaTechController = vjs.Component.extend({
<ide> /** @constructor */
<ide> init: function(player, options, ready){
<ide> options = options || {};
<del>
<ide> // we don't want the tech to report user activity automatically.
<ide> // This is done manually in addControlsListeners
<ide> options.reportTouchActivity = false;
<ide> vjs.MediaTechController.prototype.setCurrentTime = function() {
<ide> */
<ide> vjs.MediaTechController.prototype.setPoster = function(){};
<ide>
<del>vjs.MediaTechController.prototype[ 'volumeControl' ] = true;
<add>vjs.MediaTechController.prototype['volumeControlFeature'] = true;
<ide>
<ide> // Resizing plugins using request fullscreen reloads the plugin
<del>vjs.MediaTechController.prototype[ 'fullscreenResize' ] = false;
<del>vjs.MediaTechController.prototype[ 'playbackRate' ] = false;
<add>vjs.MediaTechController.prototype['fullscreenResizeFeature'] = false;
<add>vjs.MediaTechController.prototype['playbackRateFeature'] = false;
<ide>
<ide> // Optional events that we can manually mimic with timers
<ide> // currently not triggered by video-js-swf
<del>vjs.MediaTechController.prototype[ 'progressEvents' ] = false;
<del>vjs.MediaTechController.prototype[ 'timeupdateEvents' ] = false;
<add>vjs.MediaTechController.prototype['progressEventsFeature'] = false;
<add>vjs.MediaTechController.prototype['timeupdateEventsFeature'] = false;
<ide>
<ide> vjs.media = {};
<ide><path>src/js/player.js
<ide> vjs.Player.prototype.playbackRate = function(rate) {
<ide> return this;
<ide> }
<ide>
<del> if (this.tech && this.tech['playbackRate']) {
<add> if (this.tech && this.tech['playbackRateFeature']) {
<ide> return this.techGet('playbackRate');
<ide> } else {
<ide> return 1.0;
<ide><path>test/unit/controls.js
<ide> test('should hide volume control if it\'s not supported', function(){
<ide> language: noop,
<ide> languages: noop,
<ide> tech: {
<del> features: {
<del> 'volumeControl': false
<del> }
<add> 'volumeControlFeature': false
<ide> },
<ide> volume: function(){},
<ide> muted: function(){},
<ide> test('should test and toggle volume control on `loadstart`', function(){
<ide> return false;
<ide> },
<ide> tech: {
<del> features: {
<del> 'volumeControl': true
<del> }
<add> 'volumeControlFeature': true
<ide> },
<ide> reportUserActivity: function(){}
<ide> };
<ide> test('should test and toggle volume control on `loadstart`', function(){
<ide> ok(muteToggle.el().className.indexOf('vjs-hidden') < 0,
<ide> 'muteToggle is hidden initially');
<ide>
<del> player.tech.features['volumeControl'] = false;
<add> player.tech['volumeControlFeature'] = false;
<ide> for (i = 0; i < listeners.length; i++) {
<ide> listeners[i]();
<ide> }
<ide> test('should test and toggle volume control on `loadstart`', function(){
<ide> ok(muteToggle.el().className.indexOf('vjs-hidden') >= 0,
<ide> 'muteToggle does not hide itself');
<ide>
<del> player.tech.features['volumeControl'] = true;
<add> player.tech['volumeControlFeature'] = true;
<ide> for (i = 0; i < listeners.length; i++) {
<ide> listeners[i]();
<ide> }
<ide><path>test/unit/mediafaker.js
<ide> vjs.MediaFaker.prototype.muted = function(){ return false; };
<ide> vjs.MediaFaker.prototype.pause = function(){ return false; };
<ide> vjs.MediaFaker.prototype.paused = function(){ return true; };
<ide> vjs.MediaFaker.prototype.supportsFullScreen = function(){ return false; };
<del>vjs.MediaFaker.prototype.features = {};
<ide> vjs.MediaFaker.prototype.buffered = function(){ return {}; };
<ide> vjs.MediaFaker.prototype.duration = function(){ return {}; };
<ide> | 10 |
PHP | PHP | fix invalid method use and missing cast | 3268b467ef93638eca80cf3ad9d47ea10b1487da | <ide><path>src/Command/CacheClearCommand.php
<ide> public function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionPar
<ide> */
<ide> public function execute(Arguments $args, ConsoleIo $io): ?int
<ide> {
<del> $name = $args->getArgument('engine');
<add> $name = (string)$args->getArgument('engine');
<ide> try {
<ide> $io->out("Clearing {$name}");
<ide>
<ide> $engine = Cache::pool($name);
<ide> Cache::clear($name);
<ide> if ($engine instanceof ApcuEngine) {
<del> $io->warn("ApcuEngine detected: Cleared {$name} CLI cache successfully " .
<add> $io->warning("ApcuEngine detected: Cleared {$name} CLI cache successfully " .
<ide> "but {$name} web cache must be cleared separately.");
<ide> } elseif ($engine instanceof WincacheEngine) {
<del> $io->warn("WincacheEngine detected: Cleared {$name} CLI cache successfully " .
<add> $io->warning("WincacheEngine detected: Cleared {$name} CLI cache successfully " .
<ide> "but {$name} web cache must be cleared separately.");
<ide> } else {
<ide> $io->out("<success>Cleared {$name} cache</success>"); | 1 |
Javascript | Javascript | add some verification code to tls.connect() | 5138992f3c275a1bab1593c7468c08f1f24e96bb | <ide><path>lib/tls.js
<ide> exports.connect = function(port /* host, options, cb */) {
<ide> socket.connect(port, host);
<ide>
<ide> pair.on('secure', function() {
<del> console.log('client cleartext.getPeerCertificate(): %j',
<del> cleartext.getPeerCertificate());
<del> console.log('client cleartext.getCipher(): %j',
<del> cleartext.getCipher());
<add> var verifyError = pair._ssl.verifyError();
<ide>
<del> if (cb) {
<del> cb(cleartext);
<add> if (verifyError) {
<add> cleartext.authorized = false;
<add> cleartext.authorizationError = verifyError;
<add> } else {
<add> cleartext.authorized = true;
<ide> }
<add>
<add> if (cb) cb();
<ide> });
<ide>
<ide> return cleartext;
<ide><path>test/disabled/tls-client.js
<ide> var options = {
<ide> };
<ide>
<ide>
<del>var s = tls.connect(443, "google.com", options, function() {
<del> console.error("CONNECTED");
<add>var s = tls.connect(443, "joyent.com", options, function() {
<add> if (!s.authorized) {
<add> console.error("CONNECTED: " + s.authorizationError);
<add> s.destroy();
<add> return;
<add> }
<ide> s.pipe(process.stdout);
<ide> process.openStdin().pipe(s);
<ide> }); | 2 |
Javascript | Javascript | remove unnecessary test flags | e7658471d3d98f13783794277c62f61936706fc7 | <ide><path>test/parallel/test-buffer-of-no-deprecation.js
<del>// Flags: --pending-deprecation --no-warnings
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<ide><path>test/parallel/test-util-inspect.js
<ide> // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
<ide> // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<ide> // USE OR OTHER DEALINGS IN THE SOFTWARE.
<del>
<del>// Flags: --expose-internals
<ide> 'use strict';
<ide> const common = require('../common');
<ide> const assert = require('assert');
<ide><path>test/parallel/test-v8-deserialize-buffer.js
<del>// Flags: --pending-deprecation --no-warnings
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<ide><path>test/parallel/test-v8-serdes.js
<del>// Flags: --expose-gc --expose-internals
<add>// Flags: --expose-internals
<ide>
<ide> 'use strict';
<ide> | 4 |
Javascript | Javascript | remove range from moduledecoratordependency | 8a996186a006a38a65a4a09bf067eed7881ef3b9 | <ide><path>lib/NodeStuffPlugin.js
<ide> class NodeStuffPlugin {
<ide> parser.state.module.context,
<ide> isHarmony ? harmonyModuleBuildin : moduleBuildin
<ide> ),
<del> parser.state.module,
<del> expr.range
<add> parser.state.module
<ide> );
<ide> dep.loc = expr.loc;
<ide> parser.state.module.addDependency(dep);
<ide><path>lib/dependencies/ModuleDecoratorDependency.js
<ide> const ModuleDependency = require("./ModuleDependency");
<ide> /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
<ide>
<ide> class ModuleDecoratorDependency extends ModuleDependency {
<del> constructor(request, originModule, range) {
<add> constructor(request, originModule) {
<ide> super(request);
<ide> this.originModule = originModule;
<del> this.range = range;
<ide> }
<ide> }
<ide> | 2 |
Javascript | Javascript | increase specificity in dgram test | 73f219fb978e337d1764359d40afaad38630aa30 | <ide><path>test/parallel/test-dgram-membership.js
<ide> const setup = () => {
<ide> const socket = setup();
<ide> socket.close(common.mustCall(() => {
<ide> assert.throws(() => { socket.addMembership(multicastAddress); },
<del> /Not running/);
<add> /^Error: Not running$/);
<ide> }));
<ide> }
<ide>
<ide> const setup = () => {
<ide> const socket = setup();
<ide> socket.close(common.mustCall(() => {
<ide> assert.throws(() => { socket.dropMembership(multicastAddress); },
<del> /Not running/);
<add> /^Error: Not running$/);
<ide> }));
<ide> }
<ide>
<ide> // addMembership() with no argument should throw
<ide> {
<ide> const socket = setup();
<ide> assert.throws(() => { socket.addMembership(); },
<del> /multicast address must be specified/);
<add> /^Error: multicast address must be specified$/);
<ide> socket.close();
<ide> }
<ide>
<ide> // dropMembership() with no argument should throw
<ide> {
<ide> const socket = setup();
<ide> assert.throws(() => { socket.dropMembership(); },
<del> /multicast address must be specified/);
<add> /^Error: multicast address must be specified$/);
<ide> socket.close();
<ide> }
<ide>
<ide> const setup = () => {
<ide> const socket = setup();
<ide> assert.throws(
<ide> () => { socket.dropMembership(multicastAddress); },
<del> /EADDRNOTAVAIL/
<add> /^Error: dropMembership EADDRNOTAVAIL$/
<ide> );
<ide> socket.close();
<ide> } | 1 |
Text | Text | add performanceobserver `buffered` document | 497e5f85175faf78758f84f9198ac3c615bfaf4d | <ide><path>doc/api/perf_hooks.md
<ide> Disconnects the `PerformanceObserver` instance from all notifications.
<ide> <!-- YAML
<ide> added: v8.5.0
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/39297
<add> description: Updated to conform to Performance Timeline Level 2. The
<add> buffered option has been added back.
<ide> - version: v16.0.0
<ide> pr-url: https://github.com/nodejs/node/pull/37136
<ide> description: Updated to conform to User Timing Level 3. The
<ide> changes:
<ide> * `entryTypes` {string[]} An array of strings identifying the types of
<ide> {PerformanceEntry} instances the observer is interested in. If not
<ide> provided an error will be thrown.
<add> * `buffered` {boolean} If true, the observer callback is called with a
<add> list global `PerformanceEntry` buffered entries. If false, only
<add> `PerformanceEntry`s created after the time point are sent to the
<add> observer callback. **Default:** `false`.
<ide>
<ide> Subscribes the {PerformanceObserver} instance to notifications of new
<ide> {PerformanceEntry} instances identified either by `options.entryTypes` | 1 |
PHP | PHP | fix some tests. cast migrations to objects | 8f3126acb7a41781f8563e08def06eb4656798a7 | <ide><path>src/Illuminate/Database/Migrations/Migrator.php
<ide> public function rollback($pretend = false)
<ide> // and properly reverse the entire database schema operation that ran.
<ide> foreach ($migrations as $migration)
<ide> {
<del> $this->runDown($migration, $pretend);
<add> $this->runDown((object) $migration, $pretend);
<ide> }
<ide>
<ide> return count($migrations);
<ide><path>src/Illuminate/Routing/Generators/stubs/destroy.php
<ide> /**
<ide> * Remove the specified resource from storage.
<ide> *
<del> * @param int $id
<add> * @param int $id
<ide> * @return Response
<ide> */
<ide> public function destroy($id)
<ide><path>src/Illuminate/Routing/Generators/stubs/edit.php
<ide> /**
<ide> * Show the form for editing the specified resource.
<ide> *
<del> * @param int $id
<add> * @param int $id
<ide> * @return Response
<ide> */
<ide> public function edit($id)
<ide><path>src/Illuminate/Routing/Generators/stubs/show.php
<ide> /**
<ide> * Display the specified resource.
<ide> *
<del> * @param int $id
<add> * @param int $id
<ide> * @return Response
<ide> */
<ide> public function show($id)
<ide><path>src/Illuminate/Routing/Generators/stubs/update.php
<ide> /**
<ide> * Update the specified resource in storage.
<ide> *
<del> * @param int $id
<add> * @param int $id
<ide> * @return Response
<ide> */
<ide> public function update($id)
<ide><path>tests/Routing/fixtures/controller.php
<ide> public function store()
<ide> /**
<ide> * Display the specified resource.
<ide> *
<add> * @param int $id
<ide> * @return Response
<ide> */
<ide> public function show($id)
<ide> public function show($id)
<ide> /**
<ide> * Show the form for editing the specified resource.
<ide> *
<add> * @param int $id
<ide> * @return Response
<ide> */
<ide> public function edit($id)
<ide> public function edit($id)
<ide> /**
<ide> * Update the specified resource in storage.
<ide> *
<add> * @param int $id
<ide> * @return Response
<ide> */
<ide> public function update($id)
<ide> public function update($id)
<ide> /**
<ide> * Remove the specified resource from storage.
<ide> *
<add> * @param int $id
<ide> * @return Response
<ide> */
<ide> public function destroy($id)
<ide><path>tests/Routing/fixtures/except_controller.php
<ide> public function store()
<ide> /**
<ide> * Show the form for editing the specified resource.
<ide> *
<add> * @param int $id
<ide> * @return Response
<ide> */
<ide> public function edit($id)
<ide> public function edit($id)
<ide> /**
<ide> * Update the specified resource in storage.
<ide> *
<add> * @param int $id
<ide> * @return Response
<ide> */
<ide> public function update($id)
<ide> public function update($id)
<ide> /**
<ide> * Remove the specified resource from storage.
<ide> *
<add> * @param int $id
<ide> * @return Response
<ide> */
<ide> public function destroy($id)
<ide><path>tests/Routing/fixtures/only_controller.php
<ide> public function index()
<ide> /**
<ide> * Display the specified resource.
<ide> *
<add> * @param int $id
<ide> * @return Response
<ide> */
<ide> public function show($id) | 8 |
Javascript | Javascript | add support to catch-all parameters in routes | 7eafbb98c64c0dc079d7d3ec589f1270b7f6fea5 | <ide><path>src/ng/route.js
<ide> function $RouteProvider(){
<ide> * `$location.path` will be updated to add or drop the trailing slash to exactly match the
<ide> * route definition.
<ide> *
<del> * `path` can contain named groups starting with a colon (`:name`). All characters up to the
<del> * next slash are matched and stored in `$routeParams` under the given `name` when the route
<del> * matches.
<add> * * `path` can contain named groups starting with a colon (`:name`). All characters up
<add> * to the next slash are matched and stored in `$routeParams` under the given `name`
<add> * when the route matches.
<add> * * `path` can contain named groups starting with a star (`*name`). All characters are
<add> * eagerly stored in `$routeParams` under the given `name` when the route matches.
<add> *
<add> * For example, routes like `/color/:color/largecode/*largecode/edit` will match
<add> * `/color/brown/largecode/code/with/slashs/edit` and extract:
<add> *
<add> * * `color: brown`
<add> * * `largecode: code/with/slashs`.
<add> *
<ide> *
<ide> * @param {Object} route Mapping information to be assigned to `$route.current` on route
<ide> * match.
<ide> function $RouteProvider(){
<ide> // regex only once and then reuse it
<ide>
<ide> // Escape regexp special characters.
<del> when = '^' + when.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&") + '$';
<add> when = '^' + when.replace(/[-\/\\^$:*+?.()|[\]{}]/g, "\\$&") + '$';
<ide> var regex = '',
<ide> params = [],
<ide> dst = {};
<ide>
<del> var re = /:(\w+)/g,
<add> var re = /\\([:*])(\w+)/g,
<ide> paramMatch,
<ide> lastMatchedIndex = 0;
<ide>
<ide> while ((paramMatch = re.exec(when)) !== null) {
<ide> // Find each :param in `when` and replace it with a capturing group.
<ide> // Append all other sections of when unchanged.
<ide> regex += when.slice(lastMatchedIndex, paramMatch.index);
<del> regex += '([^\\/]*)';
<del> params.push(paramMatch[1]);
<add> switch(paramMatch[1]) {
<add> case ':':
<add> regex += '([^\\/]*)';
<add> break;
<add> case '*':
<add> regex += '(.*)';
<add> break;
<add> }
<add> params.push(paramMatch[2]);
<ide> lastMatchedIndex = re.lastIndex;
<ide> }
<ide> // Append trailing path part.
<ide><path>test/ng/routeSpec.js
<ide> describe('$route', function() {
<ide> });
<ide> });
<ide>
<add> it('should route and fire change event when catch-all params are used', function() {
<add> var log = '',
<add> lastRoute,
<add> nextRoute;
<add>
<add> module(function($routeProvider) {
<add> $routeProvider.when('/Book1/:book/Chapter/:chapter/*highlight/edit',
<add> {controller: noop, templateUrl: 'Chapter.html'});
<add> $routeProvider.when('/Book2/:book/*highlight/Chapter/:chapter',
<add> {controller: noop, templateUrl: 'Chapter.html'});
<add> $routeProvider.when('/Blank', {});
<add> });
<add> inject(function($route, $location, $rootScope) {
<add> $rootScope.$on('$routeChangeStart', function(event, next, current) {
<add> log += 'before();';
<add> expect(current).toBe($route.current);
<add> lastRoute = current;
<add> nextRoute = next;
<add> });
<add> $rootScope.$on('$routeChangeSuccess', function(event, current, last) {
<add> log += 'after();';
<add> expect(current).toBe($route.current);
<add> expect(lastRoute).toBe(last);
<add> expect(nextRoute).toBe(current);
<add> });
<add>
<add> $location.path('/Book1/Moby/Chapter/Intro/one/edit').search('p=123');
<add> $rootScope.$digest();
<add> $httpBackend.flush();
<add> expect(log).toEqual('before();after();');
<add> expect($route.current.params).toEqual({book:'Moby', chapter:'Intro', highlight:'one', p:'123'});
<add>
<add> log = '';
<add> $location.path('/Blank').search('ignore');
<add> $rootScope.$digest();
<add> expect(log).toEqual('before();after();');
<add> expect($route.current.params).toEqual({ignore:true});
<add>
<add> log = '';
<add> $location.path('/Book1/Moby/Chapter/Intro/one/two/edit').search('p=123');
<add> $rootScope.$digest();
<add> expect(log).toEqual('before();after();');
<add> expect($route.current.params).toEqual({book:'Moby', chapter:'Intro', highlight:'one/two', p:'123'});
<add>
<add> log = '';
<add> $location.path('/Book2/Moby/one/two/Chapter/Intro').search('p=123');
<add> $rootScope.$digest();
<add> expect(log).toEqual('before();after();');
<add> expect($route.current.params).toEqual({book:'Moby', chapter:'Intro', highlight:'one/two', p:'123'});
<add>
<add> log = '';
<add> $location.path('/NONE');
<add> $rootScope.$digest();
<add> expect(log).toEqual('before();after();');
<add> expect($route.current).toEqual(null);
<add> });
<add> });
<ide>
<ide> it('should not change route when location is canceled', function() {
<ide> module(function($routeProvider) { | 2 |
PHP | PHP | remove old method | f4fd485846df1e75435c8097499c2266ba356cd0 | <ide><path>src/Illuminate/Foundation/Application.php
<ide> public function flush()
<ide> $this->loadedProviders = [];
<ide> }
<ide>
<del> /**
<del> * Get the used kernel object.
<del> *
<del> * @return \Illuminate\Contracts\Console\Kernel|\Illuminate\Contracts\Http\Kernel
<del> */
<del> protected function getKernel()
<del> {
<del> $kernelContract = $this->runningInConsole()
<del> ? 'Illuminate\Contracts\Console\Kernel'
<del> : 'Illuminate\Contracts\Http\Kernel';
<del>
<del> return $this->make($kernelContract);
<del> }
<del>
<ide> /**
<ide> * Get the application namespace.
<ide> * | 1 |
Text | Text | move previous events to the end | 3d6d641a8cd16d658c99fe83e62de4ca89df593b | <ide><path>docs/community/conferences.md
<ide> redirect_from: "docs/conferences.html"
<ide>
<ide> ## Upcoming Conferences
<ide>
<del>### React London 2017
<del>March 28th at the [QEII Centre, London](http://qeiicentre.london/)
<del>
<del>[Website](http://react.london/)
<del>
<del>### React Amsterdam 2017
<del>April 21st in Amsterdam, The Netherlands
<del>
<del>[Website](https://react.amsterdam) - [Twitter](https://twitter.com/reactamsterdam)
<del>
<ide> ### ReactEurope 2017
<ide> May 18th & 19th in Paris, France
<ide>
<ide> January 20-21 in Dornbirn, Austria
<ide> March 13-14 in Santa Clara, CA
<ide>
<ide> [Website](http://conf.reactjs.org/)
<add>
<add>### React London 2017
<add>March 28th at the [QEII Centre, London](http://qeiicentre.london/)
<add>
<add>[Website](http://react.london/)
<add>
<add>### React Amsterdam 2017
<add>April 21st in Amsterdam, The Netherlands
<add>
<add>[Website](https://react.amsterdam) - [Twitter](https://twitter.com/reactamsterdam) | 1 |
Javascript | Javascript | use safer id for init func | 96f7ba8d8fcf98e03c5320b813fb4a9369457ca2 | <ide><path>lib/WebAssemblyGenerator.js
<ide> function compose(...fns) {
<ide>
<ide> // Utility functions
<ide> const isGlobalImport = moduleImport => moduleImport.descr.type === "GlobalType";
<del>const initFuncId = t.identifier("__init__");
<add>const initFuncId = t.identifier("__webpack_init__");
<ide>
<ide> /**
<ide> * Removes the start instruction
<ide><path>lib/wasm/WasmModuleTemplatePlugin.js
<ide> class WasmModuleTemplatePlugin {
<ide> '"use strict";',
<ide> "// Instantiate WebAssembly module",
<ide> "var instance = __webpack_require__.w[module.i]",
<del> `instance.exports.__init__(${initParams})`,
<add> `instance.exports.__webpack_init__(${initParams})`,
<ide> "// export exports from WebAssembly module",
<ide> // TODO rewrite this to getters depending on exports to support circular dependencies
<ide> generateExports() | 2 |
PHP | PHP | fix double / issue in extracttask | 4103fe14a29f9d997d18b9293f00ed86acbbc47c | <ide><path>lib/Cake/Console/Command/Task/ExtractTask.php
<ide> public function execute() {
<ide> } else {
<ide> $message = __d('cake_console', "What is the path you would like to output?\n[Q]uit", $this->_paths[0] . DS . 'Locale');
<ide> while (true) {
<del> $response = $this->in($message, null, $this->_paths[0] . DS . 'Locale');
<add> $response = $this->in($message, null, rtrim($this->_paths[0], DS) . DS . 'Locale');
<ide> if (strtoupper($response) === 'Q') {
<ide> $this->out(__d('cake_console', 'Extract Aborted'));
<ide> $this->_stop();
<ide> public function execute() {
<ide> if (empty($this->_files)) {
<ide> $this->_searchFiles();
<ide> }
<add> $this->_output = rtrim($this->_output, DS) . DS;
<ide> $this->_extract();
<ide> }
<ide> | 1 |
Python | Python | support handlers with and without context | e8c0766568cb20a5357c5e6823283f0c187b35b8 | <ide><path>rest_framework/views.py
<ide> Provides an APIView class that is the base of all views in REST framework.
<ide> """
<ide> from __future__ import unicode_literals
<add>import inspect
<ide>
<ide> from django.core.exceptions import PermissionDenied
<ide> from django.http import Http404
<ide> def handle_exception(self, exc):
<ide> else:
<ide> exc.status_code = status.HTTP_403_FORBIDDEN
<ide>
<del> context = self.get_renderer_context()
<del> response = self.settings.EXCEPTION_HANDLER(exc, context)
<add> exception_handler = self.settings.EXCEPTION_HANDLER
<add>
<add> if 'context' in inspect.getargspec(exception_handler).args:
<add> context = self.get_renderer_context()
<add> response = exception_handler(exc, context)
<add> else:
<add> response = exception_handler(exc)
<ide>
<ide> if response is None:
<ide> raise
<ide><path>tests/test_views.py
<ide> from rest_framework import status
<ide> from rest_framework.decorators import api_view
<ide> from rest_framework.response import Response
<add>from rest_framework.request import Request
<ide> from rest_framework.settings import api_settings
<ide> from rest_framework.test import APIRequestFactory
<ide> from rest_framework.views import APIView
<ide> class TestCustomExceptionHandler(TestCase):
<ide> def setUp(self):
<ide> self.DEFAULT_HANDLER = api_settings.EXCEPTION_HANDLER
<ide>
<del> def exception_handler(exc, context=None):
<del> self.assertTrue('args' in context)
<del> self.assertTrue('kwargs' in context)
<del> self.assertTrue('request' in context)
<del> self.assertTrue('view' in context)
<del>
<add> def exception_handler(exc):
<ide> return Response('Error!', status=status.HTTP_400_BAD_REQUEST)
<ide>
<ide> api_settings.EXCEPTION_HANDLER = exception_handler
<ide> def test_function_based_view_exception_handler(self):
<ide> expected = 'Error!'
<ide> self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
<ide> self.assertEqual(response.data, expected)
<add>
<add> def test_context_exception_handler(self):
<add> def exception_handler(exc, context=None):
<add> self.assertEqual(context['args'], ())
<add> self.assertEqual(context['kwargs'], {})
<add> self.assertTrue(isinstance(context['request'], Request))
<add> self.assertTrue(isinstance(context['view'], ErrorView))
<add>
<add> return Response('Error!', status=status.HTTP_400_BAD_REQUEST)
<add>
<add> api_settings.EXCEPTION_HANDLER = exception_handler
<add>
<add> view = ErrorView.as_view()
<add>
<add> request = factory.get('/', content_type='application/json')
<add> response = view(request)
<add> expected = 'Error!'
<add> self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
<add> self.assertEqual(response.data, expected) | 2 |
Text | Text | fix bad links in docs. fixes | d900541021982b20ad975598229bca059589e5d5 | <ide><path>docs/tips/17-children-undefined.md
<ide> var App = React.createClass({
<ide> React.render(<App></App>, mountNode);
<ide> ```
<ide>
<del>For a more sophisticated example, refer to the last example on the [front page](/).
<add>To access your own subcomponents (the `span`s), place [refs](/react/docs/more-about-refs.html) on them.
<ide><path>docs/tips/19-dangerously-set-inner-html.md
<ide> The point being that if you unintentionally do say `<div dangerouslySetInnerHTML
<ide>
<ide> This functionality is mainly provided for cooperation with DOM string manipulation libraries, so the HTML provided must be well-formed (ie., pass XML validation).
<ide>
<del>For a more complete usage example, refer to the last example on the [front page](/).
<add>For a more complete usage example, refer to the last example on the [front page](/react/). | 2 |
Go | Go | add integration test | c4c92e66cdb9fa4c141b4fa4872af37037e1bbe2 | <ide><path>integration-cli/docker_cli_run_test.go
<ide> func TestVolumeWithSymlink(t *testing.T) {
<ide> logDone("run - volume with symlink")
<ide> }
<ide>
<add>// Tests that a volume path that has a symlink exists in a container mounting it with `--volumes-from`.
<add>func TestVolumesFromSymlinkPath(t *testing.T) {
<add> buildCmd := exec.Command(dockerBinary, "build", "-t", "docker-test-volumesfromsymlinkpath", "-")
<add> buildCmd.Stdin = strings.NewReader(`FROM busybox
<add> RUN mkdir /baz && ln -s /baz /foo
<add> VOLUME ["/foo/bar"]`)
<add> buildCmd.Dir = workingDirectory
<add> err := buildCmd.Run()
<add> if err != nil {
<add> t.Fatalf("could not build 'docker-test-volumesfromsymlinkpath': %v", err)
<add> }
<add>
<add> cmd := exec.Command(dockerBinary, "run", "--name", "test-volumesfromsymlinkpath", "docker-test-volumesfromsymlinkpath")
<add> exitCode, err := runCommand(cmd)
<add> if err != nil || exitCode != 0 {
<add> t.Fatalf("[run] (volume) err: %v, exitcode: %d", err, exitCode)
<add> }
<add>
<add> cmd = exec.Command(dockerBinary, "run", "--volumes-from", "test-volumesfromsymlinkpath", "busybox", "sh", "-c", "ls /foo | grep -q bar")
<add> exitCode, err = runCommand(cmd)
<add> if err != nil || exitCode != 0 {
<add> t.Fatalf("[run] err: %v, exitcode: %d", err, exitCode)
<add> }
<add>
<add> deleteImages("docker-test-volumesfromsymlinkpath")
<add> deleteAllContainers()
<add>
<add> logDone("run - volumes-from symlink path")
<add>}
<add>
<ide> func TestExitCode(t *testing.T) {
<ide> cmd := exec.Command(dockerBinary, "run", "busybox", "/bin/sh", "-c", "exit 72")
<ide> | 1 |
PHP | PHP | fix lint errors | 520789f6d34caf72f2bbd0fdce9138b2ba8b2012 | <ide><path>Cake/Cache/Engine/MemcachedEngine.php
<ide> public function init($settings = array()) {
<ide> /**
<ide> * Settings the memcached instance
<ide> *
<del> * @throws CacheException when the Memcached extension is not built with the desired serializer engine
<add> * @throws Cake\Error\Exception when the Memcached extension is not built with the desired serializer engine
<ide> */
<ide> protected function _setOptions() {
<ide> $this->_Memcached->setOption(\Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
<ide><path>Cake/Test/TestCase/Console/Command/CompletionShellTest.php
<ide> * @since CakePHP v 2.5
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<del>namespace Cake\Console\Command;
<add>namespace Cake\Test\TestCase\Console\Command;
<ide>
<ide> use Cake\Console\Command\CompletionShell;
<ide> use Cake\Console\Command\Task\CommandTask;
<del>use Cake\Console\ConsoleOutput;
<ide> use Cake\Console\ConsoleInput;
<add>use Cake\Console\ConsoleOutput;
<ide> use Cake\Console\Shell;
<ide> use Cake\Core\Plugin;
<ide> use Cake\TestSuite\TestCase; | 2 |
Python | Python | fix gradient in fine_tune | 335fa8b05cb1367de462973416a8889a77270e3a | <ide><path>spacy/_ml.py
<ide> def fine_tune_fwd(docs_tokvecs, drop=0.):
<ide> lengths)
<ide>
<ide> def fine_tune_bwd(d_output, sgd=None):
<del> bp_vecs(d_output, sgd=sgd)
<add> bp_vecs([d_o * model.d_mix[0] for d_o in d_output], sgd=sgd)
<ide> flat_grad = model.ops.flatten(d_output)
<ide> model.d_mix[1] += flat_tokvecs.dot(flat_grad.T).sum()
<ide> model.d_mix[0] += flat_vecs.dot(flat_grad.T).sum()
<ide> sgd(model._mem.weights, model._mem.gradient, key=model.id)
<del> return d_output
<add> return [d_o * model.d_mix[1] for d_o in d_output]
<ide> return output, fine_tune_bwd
<ide> model = wrap(fine_tune_fwd, embedding)
<ide> model.mix = model._mem.add((model.id, 'mix'), (2,))
<del> model.mix.fill(1.)
<add> model.mix.fill(0.5)
<ide> model.d_mix = model._mem.add_gradient((model.id, 'd_mix'), (model.id, 'mix'))
<ide> return model
<ide> | 1 |
Javascript | Javascript | allow disabling of inactivity timeout | 98edeccb3fd2d444bd895f6932edd156ca49a10f | <ide><path>src/js/player.js
<ide> vjs.Player.prototype.listenForUserActivity = function(){
<ide> // Clear any existing inactivity timeout to start the timer over
<ide> clearTimeout(inactivityTimeout);
<ide>
<del> // In X seconds, if no more activity has occurred the user will be
<del> // considered inactive
<del> inactivityTimeout = setTimeout(vjs.bind(this, function() {
<del> // Protect against the case where the inactivityTimeout can trigger just
<del> // before the next user activity is picked up by the activityCheck loop
<del> // causing a flicker
<del> if (!this.userActivity_) {
<del> this.userActive(false);
<del> }
<del> }), this.options()['inactivityTimeout']);
<add> var timeout = this.options()['inactivityTimeout'];
<add> if (timeout > 0) {
<add> // In <timeout> milliseconds, if no more activity has occurred the
<add> // user will be considered inactive
<add> inactivityTimeout = setTimeout(vjs.bind(this, function () {
<add> // Protect against the case where the inactivityTimeout can trigger just
<add> // before the next user activity is picked up by the activityCheck loop
<add> // causing a flicker
<add> if (!this.userActivity_) {
<add> this.userActive(false);
<add> }
<add> }), timeout);
<add> }
<ide> }
<ide> }), 250);
<ide> | 1 |
Go | Go | fix the since and before filter behavior | b41dba58a01855e0d222bd6c14af9874c298c154 | <ide><path>daemon/list.go
<ide> type listContext struct {
<ide> filters filters.Args
<ide> // exitAllowed is a list of exit codes allowed to filter with
<ide> exitAllowed []int
<add>
<add> // FIXME Remove this for 1.12 as --since and --before are deprecated
<add> // beforeContainer is a filter to ignore containers that appear before the one given
<add> beforeContainer *container.Container
<add> // sinceContainer is a filter to stop the filtering when the iterator arrive to the given container
<add> sinceContainer *container.Container
<add>
<ide> // beforeFilter is a filter to ignore containers that appear before the one given
<ide> // this is used for --filter=before= and --before=, the latter is deprecated.
<ide> beforeFilter *container.Container
<ide> func (daemon *Daemon) foldFilter(config *types.ContainerListOptions) (*listConte
<ide> }
<ide>
<ide> var beforeContFilter, sinceContFilter *container.Container
<add> // FIXME remove this for 1.12 as --since and --before are deprecated
<add> var beforeContainer, sinceContainer *container.Container
<add>
<ide> err = psFilters.WalkValues("before", func(value string) error {
<ide> beforeContFilter, err = daemon.GetContainer(value)
<ide> return err
<ide> func (daemon *Daemon) foldFilter(config *types.ContainerListOptions) (*listConte
<ide> })
<ide> }
<ide>
<del> if config.Before != "" && beforeContFilter == nil {
<del> beforeContFilter, err = daemon.GetContainer(config.Before)
<add> // FIXME remove this for 1.12 as --since and --before are deprecated
<add> if config.Before != "" {
<add> beforeContainer, err = daemon.GetContainer(config.Before)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide> }
<ide>
<del> if config.Since != "" && sinceContFilter == nil {
<del> sinceContFilter, err = daemon.GetContainer(config.Since)
<add> // FIXME remove this for 1.12 as --since and --before are deprecated
<add> if config.Since != "" {
<add> sinceContainer, err = daemon.GetContainer(config.Since)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide> func (daemon *Daemon) foldFilter(config *types.ContainerListOptions) (*listConte
<ide> ancestorFilter: ancestorFilter,
<ide> images: imagesFilter,
<ide> exitAllowed: filtExited,
<add> beforeContainer: beforeContainer,
<add> sinceContainer: sinceContainer,
<ide> beforeFilter: beforeContFilter,
<ide> sinceFilter: sinceContFilter,
<ide> ContainerListOptions: config,
<ide> func (daemon *Daemon) foldFilter(config *types.ContainerListOptions) (*listConte
<ide> // It also decides if the iteration should be stopped or not.
<ide> func includeContainerInList(container *container.Container, ctx *listContext) iterationAction {
<ide> // Do not include container if it's stopped and we're not filters
<del> if !container.Running && !ctx.All && ctx.Limit <= 0 && ctx.beforeFilter == nil && ctx.sinceFilter == nil {
<add> // FIXME remove the ctx.beforContainer part of the condition for 1.12 as --since and --before are deprecated
<add> if !container.Running && !ctx.All && ctx.Limit <= 0 && ctx.beforeContainer == nil && ctx.sinceContainer == nil {
<ide> return excludeContainer
<ide> }
<ide>
<ide> func includeContainerInList(container *container.Container, ctx *listContext) it
<ide> return excludeContainer
<ide> }
<ide>
<add> // FIXME remove this for 1.12 as --since and --before are deprecated
<add> if ctx.beforeContainer != nil {
<add> if container.ID == ctx.beforeContainer.ID {
<add> ctx.beforeContainer = nil
<add> }
<add> return excludeContainer
<add> }
<add>
<add> // FIXME remove this for 1.12 as --since and --before are deprecated
<add> if ctx.sinceContainer != nil {
<add> if container.ID == ctx.sinceContainer.ID {
<add> return stopIteration
<add> }
<add> }
<add>
<ide> // Do not include container if it's in the list before the filter container.
<ide> // Set the filter container to nil to include the rest of containers after this one.
<ide> if ctx.beforeFilter != nil {
<ide><path>integration-cli/docker_cli_ps_test.go
<ide> func (s *DockerSuite) TestPsListContainersBase(c *check.C) {
<ide> out, _ = dockerCmd(c, "ps")
<ide> c.Assert(assertContainerList(out, []string{fourthID, secondID, firstID}), checker.Equals, true, check.Commentf("RUNNING: Container list is not in the correct order: \n%s", out))
<ide>
<del> // from here all flag '-a' is ignored
<del>
<ide> // limit
<ide> out, _ = dockerCmd(c, "ps", "-n=2", "-a")
<ide> expected := []string{fourthID, thirdID}
<ide> func (s *DockerSuite) TestPsListContainersBase(c *check.C) {
<ide> // filter since
<ide> out, _ = dockerCmd(c, "ps", "-f", "since="+firstID, "-a")
<ide> expected = []string{fourthID, thirdID, secondID}
<del> c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("SINCE & ALL: Container list is not in the correct order: \n%s", out))
<add> c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("SINCE filter & ALL: Container list is not in the correct order: \n%s", out))
<ide>
<ide> out, _ = dockerCmd(c, "ps", "-f", "since="+firstID)
<del> c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("SINCE: Container list is not in the correct order: \n%s", out))
<add> expected = []string{fourthID, secondID}
<add> c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("SINCE filter: Container list is not in the correct order: \n%s", out))
<ide>
<ide> // filter before
<del> out, _ = dockerCmd(c, "ps", "-f", "before="+thirdID, "-a")
<del> expected = []string{secondID, firstID}
<del> c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("BEFORE & ALL: Container list is not in the correct order: \n%s", out))
<add> out, _ = dockerCmd(c, "ps", "-f", "before="+fourthID, "-a")
<add> expected = []string{thirdID, secondID, firstID}
<add> c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("BEFORE filter & ALL: Container list is not in the correct order: \n%s", out))
<ide>
<del> out, _ = dockerCmd(c, "ps", "-f", "before="+thirdID)
<del> c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("BEFORE: Container list is not in the correct order: \n%s", out))
<add> out, _ = dockerCmd(c, "ps", "-f", "before="+fourthID)
<add> expected = []string{secondID, firstID}
<add> c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("BEFORE filter: Container list is not in the correct order: \n%s", out))
<ide>
<ide> // filter since & before
<ide> out, _ = dockerCmd(c, "ps", "-f", "since="+firstID, "-f", "before="+fourthID, "-a")
<ide> expected = []string{thirdID, secondID}
<del> c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("SINCE, BEFORE & ALL: Container list is not in the correct order: \n%s", out))
<add> c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("SINCE filter, BEFORE filter & ALL: Container list is not in the correct order: \n%s", out))
<ide>
<ide> out, _ = dockerCmd(c, "ps", "-f", "since="+firstID, "-f", "before="+fourthID)
<del> c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("SINCE, BEFORE: Container list is not in the correct order: \n%s", out))
<add> expected = []string{secondID}
<add> c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("SINCE filter, BEFORE filter: Container list is not in the correct order: \n%s", out))
<ide>
<ide> // filter since & limit
<ide> out, _ = dockerCmd(c, "ps", "-f", "since="+firstID, "-n=2", "-a")
<ide> expected = []string{fourthID, thirdID}
<ide>
<del> c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("SINCE, LIMIT & ALL: Container list is not in the correct order: \n%s", out))
<add> c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("SINCE filter, LIMIT & ALL: Container list is not in the correct order: \n%s", out))
<ide>
<ide> out, _ = dockerCmd(c, "ps", "-f", "since="+firstID, "-n=2")
<del> c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("SINCE, LIMIT: Container list is not in the correct order: \n%s", out))
<add> c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("SINCE filter, LIMIT: Container list is not in the correct order: \n%s", out))
<ide>
<ide> // filter before & limit
<ide> out, _ = dockerCmd(c, "ps", "-f", "before="+fourthID, "-n=1", "-a")
<ide> expected = []string{thirdID}
<del> c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("BEFORE, LIMIT & ALL: Container list is not in the correct order: \n%s", out))
<add> c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("BEFORE filter, LIMIT & ALL: Container list is not in the correct order: \n%s", out))
<ide>
<ide> out, _ = dockerCmd(c, "ps", "-f", "before="+fourthID, "-n=1")
<del> c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("BEFORE, LIMIT: Container list is not in the correct order: \n%s", out))
<add> c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("BEFORE filter, LIMIT: Container list is not in the correct order: \n%s", out))
<ide>
<ide> // filter since & filter before & limit
<ide> out, _ = dockerCmd(c, "ps", "-f", "since="+firstID, "-f", "before="+fourthID, "-n=1", "-a")
<ide> expected = []string{thirdID}
<del> c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("SINCE, BEFORE, LIMIT & ALL: Container list is not in the correct order: \n%s", out))
<add> c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("SINCE filter, BEFORE filter, LIMIT & ALL: Container list is not in the correct order: \n%s", out))
<ide>
<ide> out, _ = dockerCmd(c, "ps", "-f", "since="+firstID, "-f", "before="+fourthID, "-n=1")
<del> c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("SINCE, BEFORE, LIMIT: Container list is not in the correct order: \n%s", out))
<add> c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("SINCE filter, BEFORE filter, LIMIT: Container list is not in the correct order: \n%s", out))
<add>
<add>}
<add>
<add>// FIXME remove this for 1.12 as --since and --before are deprecated
<add>func (s *DockerSuite) TestPsListContainersDeprecatedSinceAndBefore(c *check.C) {
<add> out, _ := runSleepingContainer(c, "-d")
<add> firstID := strings.TrimSpace(out)
<add>
<add> out, _ = runSleepingContainer(c, "-d")
<add> secondID := strings.TrimSpace(out)
<add>
<add> // not long running
<add> out, _ = dockerCmd(c, "run", "-d", "busybox", "true")
<add> thirdID := strings.TrimSpace(out)
<add>
<add> out, _ = runSleepingContainer(c, "-d")
<add> fourthID := strings.TrimSpace(out)
<add>
<add> // make sure the second is running
<add> c.Assert(waitRun(secondID), checker.IsNil)
<add>
<add> // make sure third one is not running
<add> dockerCmd(c, "wait", thirdID)
<add>
<add> // make sure the forth is running
<add> c.Assert(waitRun(fourthID), checker.IsNil)
<add>
<add> // since
<add> out, _ = dockerCmd(c, "ps", "--since="+firstID, "-a")
<add> expected := []string{fourthID, thirdID, secondID}
<add> c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("SINCE & ALL: Container list is not in the correct order: %v \n%s", expected, out))
<add>
<add> out, _ = dockerCmd(c, "ps", "--since="+firstID)
<add> c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("SINCE: Container list is not in the correct order: %v \n%s", expected, out))
<add>
<add> // before
<add> out, _ = dockerCmd(c, "ps", "--before="+thirdID, "-a")
<add> expected = []string{secondID, firstID}
<add> c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("BEFORE & ALL: Container list is not in the correct order: %v \n%s", expected, out))
<add>
<add> out, _ = dockerCmd(c, "ps", "--before="+thirdID)
<add> c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("BEFORE: Container list is not in the correct order: %v \n%s", expected, out))
<add>
<add> // since & before
<add> out, _ = dockerCmd(c, "ps", "--since="+firstID, "--before="+fourthID, "-a")
<add> expected = []string{thirdID, secondID}
<add> c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("SINCE, BEFORE & ALL: Container list is not in the correct order: %v \n%s", expected, out))
<add>
<add> out, _ = dockerCmd(c, "ps", "--since="+firstID, "--before="+fourthID)
<add> c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("SINCE, BEFORE: Container list is not in the correct order: %v \n%s", expected, out))
<add>
<add> // since & limit
<add> out, _ = dockerCmd(c, "ps", "--since="+firstID, "-n=2", "-a")
<add> expected = []string{fourthID, thirdID}
<add> c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("SINCE, LIMIT & ALL: Container list is not in the correct order: %v \n%s", expected, out))
<add>
<add> out, _ = dockerCmd(c, "ps", "--since="+firstID, "-n=2")
<add> c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("SINCE, LIMIT: Container list is not in the correct order: %v \n%s", expected, out))
<add>
<add> // before & limit
<add> out, _ = dockerCmd(c, "ps", "--before="+fourthID, "-n=1", "-a")
<add> expected = []string{thirdID}
<add> c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("BEFORE, LIMIT & ALL: Container list is not in the correct order: %v \n%s", expected, out))
<add>
<add> out, _ = dockerCmd(c, "ps", "--before="+fourthID, "-n=1")
<add> c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("BEFORE, LIMIT: Container list is not in the correct order: %v \n%s", expected, out))
<add>
<add> // since & before & limit
<add> out, _ = dockerCmd(c, "ps", "--since="+firstID, "--before="+fourthID, "-n=1", "-a")
<add> expected = []string{thirdID}
<add> c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("SINCE, BEFORE, LIMIT & ALL: Container list is not in the correct order: %v \n%s", expected, out))
<ide>
<ide> }
<ide>
<ide> func assertContainerList(out string, expected []string) bool {
<ide> lines := strings.Split(strings.Trim(out, "\n "), "\n")
<add> // FIXME remove this for 1.12 as --since and --before are deprecated
<add> // This is here to remove potential Warning: lines (printed out with deprecated flags)
<add> for i := 0; i < 2; i++ {
<add> if strings.Contains(lines[0], "Warning:") {
<add> lines = lines[1:]
<add> }
<add> }
<add>
<ide> if len(lines)-1 != len(expected) {
<ide> return false
<ide> } | 2 |
Go | Go | remove unneeded code | ab868ad79c631b2606b479edf12d287b986c72d4 | <ide><path>daemon/commit.go
<ide> func (daemon *Daemon) Commit(container *Container, c *ContainerCommitConfig) (*i
<ide> }()
<ide>
<ide> // Create a new image from the container's base layers + a new layer from container changes
<del> var (
<del> containerID, parentImageID string
<del> containerConfig *runconfig.Config
<del> )
<del>
<del> if container != nil {
<del> containerID = container.ID
<del> parentImageID = container.ImageID
<del> containerConfig = container.Config
<del> }
<del>
<del> img, err := daemon.graph.Create(rwTar, containerID, parentImageID, c.Comment, c.Author, containerConfig, c.Config)
<add> img, err := daemon.graph.Create(rwTar, container.ID, container.ImageID, c.Comment, c.Author, container.Config, c.Config)
<ide> if err != nil {
<ide> return nil, err
<ide> } | 1 |
Text | Text | fix small typo in 11-advanced-performance.md | 4fe1b5984913b1556538e436875988540c19b4cb | <ide><path>docs/docs/11-advanced-performance.md
<ide> Here's a subtree of components. For each one is indicated what `shouldComponentU
<ide>
<ide> <figure><img src="/react/img/docs/should-component-update.png" /></figure>
<ide>
<del>In the example above, since `shouldComponentUpdate` returned `false` for the subtree rooted at C2, React had no need to generate the new virtual DOM, and therefore, it neither needed to reconcile the DOM. Note that React didn't even had to invoke `shouldComponentUpdate` on C4 and C5.
<add>In the example above, since `shouldComponentUpdate` returned `false` for the subtree rooted at C2, React had no need to generate the new virtual DOM, and therefore, it neither needed to reconcile the DOM. Note that React didn't even have to invoke `shouldComponentUpdate` on C4 and C5.
<ide>
<ide> For C1 and C3 `shouldComponentUpdate` returned `true`, so React had to go down to the leaves and check them. For C6 it returned `true`; since the virtual DOMs weren't equivalent it had to reconcile the DOM.
<ide> The last interesting case is C8. For this node React had to compute the virtual DOM, but since it was equal to the old one, it didn't have to reconcile it's DOM. | 1 |
PHP | PHP | use ellipsis character in pagination helper | 7bc0d4e826ed15e876c61b7f8c329c99f5419079 | <ide><path>src/View/Helper/PaginatorHelper.php
<ide> class PaginatorHelper extends Helper
<ide> 'last' => '<li class="last"><a href="{{url}}">{{text}}</a></li>',
<ide> 'number' => '<li><a href="{{url}}">{{text}}</a></li>',
<ide> 'current' => '<li class="active"><a href="">{{text}}</a></li>',
<del> 'ellipsis' => '<li class="ellipsis">...</li>',
<add> 'ellipsis' => '<li class="ellipsis">…</li>',
<ide> 'sort' => '<a href="{{url}}">{{text}}</a>',
<ide> 'sortAsc' => '<a class="asc" href="{{url}}">{{text}}</a>',
<ide> 'sortDesc' => '<a class="desc" href="{{url}}">{{text}}</a>', | 1 |
Ruby | Ruby | fix variable reference | aac0e4a87873e998699bf68967127ec3f3632fd1 | <ide><path>Library/Homebrew/cmd/test-bot.rb
<ide> def formula formula_name
<ide> if formula.devel && formula.stable? && !ARGV.include?('--HEAD') \
<ide> && satisfied_requirements?(formula, :devel)
<ide> test "brew", "fetch", "--retry", "--devel", *formula_fetch_options
<del> run_as_not_developer { test "brew", "install", "--devel", "--verbose", dependent.name }
<add> run_as_not_developer { test "brew", "install", "--devel", "--verbose", canonical_formula_name }
<ide> devel_install_passed = steps.last.passed?
<ide> test "brew", "audit", "--devel", *audit_args
<ide> if devel_install_passed | 1 |
Ruby | Ruby | extract path building to a method | 0e26271456a772de5ce4c4c78cce3a275bcb89a8 | <ide><path>actionpack/lib/action_dispatch/http/url.rb
<ide> def url_for(options)
<ide> raise ArgumentError, 'Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true'
<ide> end
<ide>
<add> if options[:only_path]
<add> path_for options
<add> else
<add> protocol = options[:protocol]
<add> port = options[:port]
<add> build_host_url(host, port, protocol, options, path_for(options))
<add> end
<add> end
<add>
<add> def path_for(options)
<ide> result = options[:script_name].to_s.chomp("/")
<ide> result << options[:path].to_s
<ide>
<ide> result = add_trailing_slash(result) if options[:trailing_slash]
<ide>
<ide> result = add_params options, result
<del> result = add_anchor options, result
<del>
<del> if options[:only_path]
<del> result
<del> else
<del> protocol = options[:protocol]
<del> port = options[:port]
<del> build_host_url(host, port, protocol, options, result)
<del> end
<add> add_anchor options, result
<ide> end
<ide>
<ide> private | 1 |
Java | Java | add tests for messagebodyclienthttpresponsewrapper | 417bce8be5e32ae43c2e3b25de1e24cd03c71e93 | <ide><path>spring-web/src/test/java/org/springframework/web/client/MessageBodyClientHttpResponseWrapperTests.java
<add>/*
<add> * Copyright 2002-2021 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>package org.springframework.web.client;
<add>
<add>import org.junit.jupiter.api.Test;
<add>import org.springframework.http.HttpHeaders;
<add>import org.springframework.http.HttpStatus;
<add>import org.springframework.http.client.ClientHttpResponse;
<add>
<add>import static org.assertj.core.api.Assertions.assertThat;
<add>import static org.mockito.BDDMockito.given;
<add>import static org.mockito.Mockito.mock;
<add>
<add>import java.io.ByteArrayInputStream;
<add>import java.io.IOException;
<add>import java.io.InputStream;
<add>
<add>/**
<add> * Unit tests for {MessageBodyClientHttpResponseWrapper}.
<add> *
<add> * @author Yin-Jui Liao
<add> */
<add>class MessageBodyClientHttpResponseWrapperTests {
<add>
<add> private final ClientHttpResponse response = mock(ClientHttpResponse.class);
<add>
<add> @Test
<add> void testMessageBodyNotExist() throws IOException {
<add> given(response.getBody()).willReturn(null);
<add> MessageBodyClientHttpResponseWrapper responseWrapper = new MessageBodyClientHttpResponseWrapper(response);
<add> assertThat(responseWrapper.hasEmptyMessageBody()).isTrue();
<add> }
<add>
<add> @Test
<add> void testMessageBodyExist() throws IOException {
<add> String body = "Accepted request";
<add> InputStream stream = new ByteArrayInputStream(body.getBytes());
<add> given(response.getBody()).willReturn(stream);
<add> MessageBodyClientHttpResponseWrapper responseWrapper = new MessageBodyClientHttpResponseWrapper(response);
<add> assertThat(responseWrapper.hasEmptyMessageBody()).isFalse();
<add> }
<add>} | 1 |
Ruby | Ruby | handle regex not finding anything | 6db1b0abd869c091a889c5342203599a3291d3eb | <ide><path>Library/Homebrew/utils/curl.rb
<ide> def curl_download(*args, to: nil, **options)
<ide> supports_partial_download = http_status.to_i == 206 # Partial Content
<ide> if supports_partial_download &&
<ide> destination.exist? &&
<del> destination.size == %r{^.*Content-Range: bytes \d+-\d+/(\d+)\r\n.*$}m.match(headers)[1].to_i
<add> destination.size == %r{^.*Content-Range: bytes \d+-\d+/(\d+)\r\n.*$}m.match(headers)&.[](1)&.to_i
<ide> return # We've already downloaded all the bytes
<ide> end
<ide> | 1 |
Python | Python | remove unused import | 5605d687019dc55e594d4e227747c72bebb71a3c | <ide><path>numpy/array_api/_array_object.py
<ide> from ._dtypes import (_all_dtypes, _boolean_dtypes, _integer_dtypes,
<ide> _integer_or_boolean_dtypes, _floating_dtypes, _numeric_dtypes)
<ide>
<del>from typing import TYPE_CHECKING, Any, Optional, Tuple, Union
<add>from typing import TYPE_CHECKING, Optional, Tuple, Union
<ide> if TYPE_CHECKING:
<ide> from ._typing import PyCapsule, Device, Dtype
<ide> | 1 |
Python | Python | move ftphook to contrib folder | 813279859c7d47877e5dfd180e640413ab8559e9 | <ide><path>airflow/contrib/hooks/__init__.py
<add>'''
<add>Imports the hooks dynamically while keeping the package API clean,
<add>abstracting the underlying modules
<add>'''
<add>from airflow.utils import import_module_attrs as _import_module_attrs
<add>
<add>_hooks = {
<add> 'ftp_hook': ['FTPHook'],
<add>}
<add>
<add>_import_module_attrs(globals(), _hooks)
<ide><path>airflow/contrib/hooks/ftp_hook.py
<add>import datetime
<add>import ftplib
<add>import logging
<add>import os.path
<add>from airflow.hooks.base_hook import BaseHook
<add>from past.builtins import basestring
<add>
<add>
<add>def mlsd(conn, path="", facts=[]):
<add> '''
<add> BACKPORT FROM PYTHON3 FTPLIB
<add>
<add> List a directory in a standardized format by using MLSD
<add> command (RFC-3659). If path is omitted the current directory
<add> is assumed. "facts" is a list of strings representing the type
<add> of information desired (e.g. ["type", "size", "perm"]).
<add>
<add> Return a generator object yielding a tuple of two elements
<add> for every file found in path.
<add> First element is the file name, the second one is a dictionary
<add> including a variable number of "facts" depending on the server
<add> and whether "facts" argument has been provided.
<add> '''
<add> if facts:
<add> conn.sendcmd("OPTS MLST " + ";".join(facts) + ";")
<add> if path:
<add> cmd = "MLSD %s" % path
<add> else:
<add> cmd = "MLSD"
<add> lines = []
<add> conn.retrlines(cmd, lines.append)
<add> for line in lines:
<add> facts_found, _, name = line.rstrip(ftplib.CRLF).partition(' ')
<add> entry = {}
<add> for fact in facts_found[:-1].split(";"):
<add> key, _, value = fact.partition("=")
<add> entry[key.lower()] = value
<add> yield (name, entry)
<add>
<add>
<add>class FTPHook(BaseHook):
<add>
<add> """
<add> Interact with FTP.
<add>
<add> Errors that may occur throughout but should be handled
<add> downstream.
<add> """
<add>
<add> def __init__(self, ftp_conn_id='ftp_default'):
<add> self.ftp_conn_id = ftp_conn_id
<add> self.conn = None
<add>
<add> def get_conn(self):
<add> """
<add> Returns a FTP connection object
<add> """
<add> if self.conn is None:
<add> params = self.get_connection(self.ftp_conn_id)
<add> self.conn = ftplib.FTP(params.host, params.login, params.password)
<add>
<add> return self.conn
<add>
<add> def close_conn(self):
<add> """
<add> Closes the connection. An error will occur if the
<add> connection wasnt ever opened.
<add> """
<add> conn = self.conn
<add> conn.quit()
<add>
<add> def describe_directory(self, path):
<add> """
<add> Returns a dictionary of {filename: {attributes}} for all files
<add> on the remote system (where the MLSD command is supported).
<add>
<add> :param path: full path to the remote directory
<add> :type path: str
<add> """
<add> conn = self.get_conn()
<add> conn.cwd(path)
<add> try:
<add> # only works in Python 3
<add> files = dict(conn.mlsd())
<add> except AttributeError:
<add> files = dict(mlsd(conn))
<add> return files
<add>
<add> def list_directory(self, path, nlst=False):
<add> """
<add> Returns a list of files on the remote system.
<add>
<add> :param path: full path to the remote directory to list
<add> :type path: str
<add> """
<add> conn = self.get_conn()
<add> conn.cwd(path)
<add>
<add> files = conn.nlst()
<add> return files
<add>
<add> def create_directory(self, path):
<add> """
<add> Creates a directory on the remote system.
<add>
<add> :param path: full path to the remote directory to create
<add> :type path: str
<add> """
<add> conn = self.get_conn()
<add> conn.mkd(path)
<add>
<add> def delete_directory(self, path):
<add> """
<add> Deletes a directory on the remote system.
<add>
<add> :param path: full path to the remote directory to delete
<add> :type path: str
<add> """
<add> conn = self.get_conn()
<add> conn.rmd(path)
<add>
<add> def retrieve_file(self, remote_full_path, local_full_path_or_buffer):
<add> """
<add> Transfers the remote file to a local location.
<add>
<add> If local_full_path_or_buffer is a string path, the file will be put
<add> at that location; if it is a file-like buffer, the file will
<add> be written to the buffer but not closed.
<add>
<add> :param remote_full_path: full path to the remote file
<add> :type remote_full_path: str
<add> :param local_full_path_or_buffer: full path to the local file or a
<add> file-like buffer
<add> :type local_full_path: str or file-like buffer
<add> """
<add> conn = self.get_conn()
<add>
<add> is_path = isinstance(local_full_path_or_buffer, basestring)
<add>
<add> if is_path:
<add> output_handle = open(local_full_path_or_buffer, 'wb')
<add> else:
<add> output_handle = local_full_path_or_buffer
<add>
<add> remote_path, remote_file_name = os.path.split(remote_full_path)
<add> conn.cwd(remote_path)
<add> logging.info('Retrieving file from FTP: {}'.format(remote_full_path))
<add> conn.retrbinary('RETR %s' % remote_file_name, output_handle.write)
<add> logging.info('Finished etrieving file from FTP: {}'.format(
<add> remote_full_path))
<add>
<add> if is_path:
<add> output_handle.close()
<add>
<add> def store_file(self, remote_full_path, local_full_path_or_buffer):
<add> """
<add> Transfers a local file to the remote location.
<add>
<add> If local_full_path_or_buffer is a string path, the file will be read
<add> from that location; if it is a file-like buffer, the file will
<add> be read from the buffer but not closed.
<add>
<add> :param remote_full_path: full path to the remote file
<add> :type remote_full_path: str
<add> :param local_full_path_or_buffer: full path to the local file or a
<add> file-like buffer
<add> :type local_full_path_or_buffer: str or file-like buffer
<add> """
<add> conn = self.get_conn()
<add>
<add> is_path = isinstance(local_full_path_or_buffer, basestring)
<add>
<add> if is_path:
<add> input_handle = open(local_full_path_or_buffer, 'rb')
<add> else:
<add> input_handle = local_full_path_or_buffer
<add> remote_path, remote_file_name = os.path.split(remote_full_path)
<add> conn.cwd(remote_path)
<add> conn.storbinary('STOR %s' % remote_file_name, input_handle)
<add>
<add> if is_path:
<add> input_handle.close()
<add>
<add> def delete_file(self, path):
<add> """
<add> Removes a file on the FTP Server
<add>
<add> :param path: full path to the remote file
<add> :type path: str
<add> """
<add> conn = self.get_conn()
<add> conn.delete(path)
<add>
<add> def get_mod_time(self, path):
<add> conn = self.get_conn()
<add> ftp_mdtm = conn.sendcmd('MDTM ' + path)
<add> return datetime.datetime.strptime(ftp_mdtm[4:], '%Y%m%d%H%M%S')
<ide><path>airflow/hooks/__init__.py
<ide> }
<ide>
<ide> _import_module_attrs(globals(), _hooks)
<add>from airflow.contrib.hooks import *
<ide>
<ide>
<ide> def integrate_plugins(): | 3 |
Javascript | Javascript | use an unref'd timer to fix delay in exit | 16b59cbc74c8fe2f8b30f3af4c2f885b7bfb6030 | <ide><path>lib/http.js
<ide> var util = require('util');
<ide> var net = require('net');
<ide> var Stream = require('stream');
<add>var timers = require('timers');
<ide> var url = require('url');
<ide> var EventEmitter = require('events').EventEmitter;
<ide> var FreeList = require('freelist').FreeList;
<ide> function utcDate() {
<ide> if (!dateCache) {
<ide> var d = new Date();
<ide> dateCache = d.toUTCString();
<del> setTimeout(function() {
<del> dateCache = undefined;
<del> }, 1000 - d.getMilliseconds());
<add> timers.enroll(utcDate, 1000 - d.getMilliseconds());
<add> timers._unrefActive(utcDate);
<ide> }
<ide> return dateCache;
<ide> }
<add>utcDate._onTimeout = function() {
<add> dateCache = undefined;
<add>};
<ide>
<ide>
<ide> /* Abstract base class for ServerRequest and ClientResponse. */
<ide><path>test/simple/test-http-exit-delay.js
<add>// Copyright Joyent, Inc. and other Node contributors.
<add>//
<add>// Permission is hereby granted, free of charge, to any person obtaining a
<add>// copy of this software and associated documentation files (the
<add>// "Software"), to deal in the Software without restriction, including
<add>// without limitation the rights to use, copy, modify, merge, publish,
<add>// distribute, sublicense, and/or sell copies of the Software, and to permit
<add>// persons to whom the Software is furnished to do so, subject to the
<add>// following conditions:
<add>//
<add>// The above copyright notice and this permission notice shall be included
<add>// in all copies or substantial portions of the Software.
<add>//
<add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
<add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
<add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
<add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
<add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
<add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<add>// USE OR OTHER DEALINGS IN THE SOFTWARE.
<add>
<add>var assert = require('assert');
<add>var common = require('../common.js');
<add>var http = require('http');
<add>
<add>var start;
<add>var server = http.createServer(function(req, res) {
<add> req.resume();
<add> req.on('end', function() {
<add> res.end('Success');
<add> });
<add>
<add> server.close(function() {
<add> start = process.hrtime();
<add> });
<add>});
<add>
<add>server.listen(common.PORT, 'localhost', function() {
<add> var interval_id = setInterval(function() {
<add> if (new Date().getMilliseconds() > 100)
<add> return;
<add>
<add> var req = http.request({
<add> 'host': 'localhost',
<add> 'port': common.PORT,
<add> 'agent': false,
<add> 'method': 'PUT'
<add> });
<add>
<add> req.end('Test');
<add> clearInterval(interval_id);
<add> }, 10);
<add>});
<add>
<add>process.on('exit', function() {
<add> var d = process.hrtime(start);
<add> assert.equal(d[0], 0);
<add> assert(d[1] / 1e9 < 0.03);
<add> console.log('ok');
<add>}); | 2 |
Text | Text | add changelog entry for 4d858b3f2a | 2b17c114eb01c20ea76b9765eb206fb1c3157a43 | <ide><path>railties/CHANGELOG.md
<add>* `Rails.application.config_for` merges shared configuration deeply.
<add>
<add> ```yaml
<add> # config/example.yml
<add> shared:
<add> foo:
<add> bar:
<add> baz: 1
<add> development:
<add> foo:
<add> bar:
<add> qux: 2
<add> ```
<add>
<add> ```ruby
<add> # Previously
<add> Rails.application.config_for(:example)[:foo][:bar] #=> { qux: 2 }
<add>
<add> # Now
<add> Rails.application.config_for(:example)[:foo][:bar] #=> { baz: 1, qux: 2 }
<add> ```
<add>
<add> *Yuhei Kiriyama*
<add>
<ide> * Remove access to values in nested hashes returned by `Rails.application.config_for` via String keys.
<ide>
<ide> ```yaml | 1 |
Javascript | Javascript | rewrite mousewheel hack using d3 | 6c5a1a3b0ebd53a08751bbfec6b7f8252ae0211c | <ide><path>d3.behavior.js
<ide> d3.behavior.zoom = function() {
<ide> // mousewheel events are totally broken!
<ide> // https://bugs.webkit.org/show_bug.cgi?id=40441
<ide> // not only that, but Chrome and Safari differ in re. to acceleration!
<del> var inner = document.createElement("div"),
<del> outer = document.createElement("div");
<del> outer.style.visibility = "hidden";
<del> outer.style.top = "0px";
<del> outer.style.height = "0px";
<del> outer.style.width = "0px";
<del> outer.style.overflowY = "scroll";
<del> inner.style.height = "2000px";
<del> outer.appendChild(inner);
<del> document.body.appendChild(outer);
<add>
<add> var outer = d3.select("body").append("div")
<add> .style("visibility", "hidden")
<add> .style("position", "absolute")
<add> .style("top", "-3000px")
<add> .style("height", 0)
<add> .style("overflow-y", "scroll")
<add> .append("div")
<add> .style("height", "2000px")
<add> .node().parentNode;
<ide>
<ide> function mousewheel(d, i) {
<ide> var e = d3.event;
<ide><path>d3.behavior.min.js
<del>(function(){d3.behavior={},d3.behavior.zoom=function(){function m(e,f){function i(a,b){var c=a.__domain||(a.__domain=a.domain()),d=a.range().map(function(a){return(a-b)/h});a.domain(c).domain(d.map(a.invert))}var g=d3.event,h=Math.pow(2,c);d3.event={scale:h,translate:[a,b],transform:function(c,d){c&&i(c,a),d&&i(d,b)}};try{for(var j=0,k=d.length;j<k;j++)d[j].call(this,e,f)}finally{d3.event=g}}function l(d,e){var g=d3.event;if(!f){var h=d3.svg.mouse(this.nearestViewportElement||this);f={x0:a,y0:b,z0:c,x1:a-h[0],y1:b-h[1]}}if(g.type==="dblclick")c=g.shiftKey?Math.ceil(c-1):Math.floor(c+1);else{var i=g.wheelDelta||-g.detail;if(i){try{k.scrollTop=1e3,k.dispatchEvent(g),i=1e3-k.scrollTop}catch(j){}i*=.005}c+=i}var l=Math.pow(2,c-f.z0)-1;a=f.x0+f.x1*l,b=f.y0+f.y1*l,m.call(this,d,e)}function i(){e&&(h(),e=null)}function h(){f=null,e&&(a=d3.event.clientX+e.x0,b=d3.event.clientY+e.y0,m.call(e.target,e.data,e.index))}function g(c,d){e={x0:a-d3.event.clientX,y0:b-d3.event.clientY,target:this,data:c,index:d},d3.event.preventDefault(),window.focus()}function f(){var a=this.on("mousedown",g).on("mousewheel",l).on("DOMMouseScroll",l).on("dblclick",l);d3.select(window).on("mousemove",h).on("mouseup",i)}var a=0,b=0,c=0,d=[],e,f,j=document.createElement("div"),k=document.createElement("div");k.style.visibility="hidden",k.style.top="0px",k.style.height="0px",k.style.width="0px",k.style.overflowY="scroll",j.style.height="2000px",k.appendChild(j),document.body.appendChild(k),f.on=function(a,b){a=="zoom"&&d.push(b);return f};return f}})()
<ide>\ No newline at end of file
<add>(function(){d3.behavior={},d3.behavior.zoom=function(){function l(e,f){function i(a,b){var c=a.__domain||(a.__domain=a.domain()),d=a.range().map(function(a){return(a-b)/h});a.domain(c).domain(d.map(a.invert))}var g=d3.event,h=Math.pow(2,c);d3.event={scale:h,translate:[a,b],transform:function(c,d){c&&i(c,a),d&&i(d,b)}};try{for(var j=0,k=d.length;j<k;j++)d[j].call(this,e,f)}finally{d3.event=g}}function k(d,e){var g=d3.event;if(!f){var h=d3.svg.mouse(this.nearestViewportElement||this);f={x0:a,y0:b,z0:c,x1:a-h[0],y1:b-h[1]}}if(g.type==="dblclick")c=g.shiftKey?Math.ceil(c-1):Math.floor(c+1);else{var i=g.wheelDelta||-g.detail;if(i){try{j.scrollTop=1e3,j.dispatchEvent(g),i=1e3-j.scrollTop}catch(k){}i*=.005}c+=i}var m=Math.pow(2,c-f.z0)-1;a=f.x0+f.x1*m,b=f.y0+f.y1*m,l.call(this,d,e)}function i(){e&&(h(),e=null)}function h(){f=null,e&&(a=d3.event.clientX+e.x0,b=d3.event.clientY+e.y0,l.call(e.target,e.data,e.index))}function g(c,d){e={x0:a-d3.event.clientX,y0:b-d3.event.clientY,target:this,data:c,index:d},d3.event.preventDefault(),window.focus()}function f(){var a=this.on("mousedown",g).on("mousewheel",k).on("DOMMouseScroll",k).on("dblclick",k);d3.select(window).on("mousemove",h).on("mouseup",i)}var a=0,b=0,c=0,d=[],e,f,j=d3.select("body").append("div").style("visibility","hidden").style("position","absolute").style("top","-3000px").style("height",0).style("overflow-y","scroll").append("div").style("height","2000px").node().parentNode;f.on=function(a,b){a=="zoom"&&d.push(b);return f};return f}})()
<ide>\ No newline at end of file
<ide><path>src/behavior/zoom.js
<ide> d3.behavior.zoom = function() {
<ide> // mousewheel events are totally broken!
<ide> // https://bugs.webkit.org/show_bug.cgi?id=40441
<ide> // not only that, but Chrome and Safari differ in re. to acceleration!
<del> var inner = document.createElement("div"),
<del> outer = document.createElement("div");
<del> outer.style.visibility = "hidden";
<del> outer.style.top = "0px";
<del> outer.style.height = "0px";
<del> outer.style.width = "0px";
<del> outer.style.overflowY = "scroll";
<del> inner.style.height = "2000px";
<del> outer.appendChild(inner);
<del> document.body.appendChild(outer);
<add>
<add> var outer = d3.select("body").append("div")
<add> .style("visibility", "hidden")
<add> .style("position", "absolute")
<add> .style("top", "-3000px")
<add> .style("height", 0)
<add> .style("overflow-y", "scroll")
<add> .append("div")
<add> .style("height", "2000px")
<add> .node().parentNode;
<ide>
<ide> function mousewheel(d, i) {
<ide> var e = d3.event; | 3 |
Text | Text | fix sentence fragment in fs doc | 9f8d0ea6db2ff88422d1df69dbfed1dc766f8dbc | <ide><path>doc/api/fs.md
<ide> the end of the file.
<ide>
<ide> _Note: The behavior of `fs.open()` is platform specific for some flags. As such,
<ide> opening a directory on OS X and Linux with the `'a+'` flag - see example below -
<del>will return an error. Whereas on Windows and FreeBSD a file descriptor will be
<del>returned._
<add>will return an error. In contrast, on Windows and FreeBSD, a file descriptor
<add>will be returned._
<ide>
<ide> ```js
<ide> // OS X and Linux | 1 |
Ruby | Ruby | remove unnecessary usage of formula.canonical_name | 2616127a281b9cf7f15c3fb2cd8536741d0f1b6c | <ide><path>Library/Contributions/cmd/brew-services.rb
<ide> def homebrew!
<ide> end
<ide>
<ide> # Access current service
<del> def service; @service ||= Service.new(Formula.factory(Formula.canonical_name(@formula))) if @formula end
<add> def service; @service ||= Service.new(Formula.factory(@formula)) if @formula end
<ide>
<ide> # Print usage and `exit(...)` with supplied exit code, if code
<ide> # is set to `false`, then exit is ignored.
<ide> def startup_user; ServicesCli.user end
<ide> # Create a new `Service` instance from either a path or label.
<ide> def self.from(path_or_label)
<ide> return nil unless path_or_label =~ /homebrew\.mxcl\.([^\.]+)(\.plist)?\z/
<del> new(Formula.factory(Formula.canonical_name($1))) rescue nil
<add> new(Formula.factory($1)) rescue nil
<ide> end
<ide>
<ide> # Initialize new `Service` instance with supplied formula. | 1 |
PHP | PHP | add ability to set beanstalkd port | 2608084a12f0596f70cf5a91514345e0a661d168 | <ide><path>src/Illuminate/Queue/Connectors/BeanstalkdConnector.php
<ide> class BeanstalkdConnector implements ConnectorInterface {
<ide> */
<ide> public function connect(array $config)
<ide> {
<del> $pheanstalk = new Pheanstalk($config['host']);
<add> $pheanstalk = new Pheanstalk($config['host'], array_get($config, 'port', Pheanstalk::DEFAULT_PORT));
<ide>
<ide> return new BeanstalkdQueue(
<ide> $pheanstalk, $config['queue'], array_get($config, 'ttr', Pheanstalk::DEFAULT_TTR) | 1 |
PHP | PHP | set redis connection names | 4215fd36f269f3b6d27fd453c7503cbde9806621 | <ide><path>src/Illuminate/Redis/Connections/Connection.php
<ide> abstract class Connection
<ide> */
<ide> protected $client;
<ide>
<add> /**
<add> * The Redis connection name.
<add> *
<add> * @var string
<add> */
<add> protected $name;
<add>
<ide> /**
<ide> * Subscribe to a set of given channels for messages.
<ide> *
<ide> public function command($method, array $parameters = [])
<ide> return $this->client->{$method}(...$parameters);
<ide> }
<ide>
<add> /**
<add> * Get the connection name.
<add> *
<add> * @return string
<add> */
<add> public function getName()
<add> {
<add> return $this->name;
<add> }
<add>
<add> /**
<add> * Set the connections name.
<add> *
<add> * @param string $name
<add> * @return void
<add> */
<add> public function setName($name)
<add> {
<add> $this->name = $name;
<add> }
<add>
<ide> /**
<ide> * Pass other method calls down to the underlying client.
<ide> *
<ide><path>src/Illuminate/Redis/RedisManager.php
<ide> public function connection($name = null)
<ide> return $this->connections[$name];
<ide> }
<ide>
<del> return $this->connections[$name] = $this->resolve($name);
<add> $this->connections[$name] = $this->resolve($name);
<add> $this->connections[$name]->setName($name);
<add>
<add> return $this->connections[$name];
<ide> }
<ide>
<ide> /** | 2 |
Ruby | Ruby | fix weird colon output | 55db2f7e114befc57f783d4858c72fc11a91382b | <ide><path>Library/Homebrew/cmd/uses.rb
<ide> def uses
<ide> if f.recursive_dependencies.any? { |dep| dep.name == ff.name }
<ide> uses << f.to_s
<ide> elsif f.recursive_requirements.any? { |req| req.name == ff.name }
<del> uses << ":#{f}"
<add> uses << f.to_s
<ide> end
<ide> else
<ide> if f.deps.any? { |dep| dep.name == ff.name }
<ide> uses << f.to_s
<ide> elsif f.requirements.any? { |req| req.name == ff.name }
<del> uses << ":#{f}"
<add> uses << f.to_s
<ide> end
<ide> end
<ide> end | 1 |
Javascript | Javascript | fix another couple of race conditions in tests | bf73f5c506edf1353a48bb403065d6b45e959c21 | <ide><path>test/core/transition-test-delay.js
<ide> var assert = require("assert");
<ide>
<ide> module.exports = {
<ide> topic: function() {
<del> return d3.select("body").selectAll()
<add> return d3.select("body").html("").selectAll()
<ide> .data(["foo", "bar"])
<ide> .enter().append("div")
<ide> .attr("class", String);
<ide><path>test/core/transition-test-duration.js
<ide> var assert = require("assert");
<ide>
<ide> module.exports = {
<ide> topic: function() {
<del> return d3.select("body").selectAll()
<add> return d3.select("body").html("").selectAll()
<ide> .data(["foo", "bar"])
<ide> .enter().append("div")
<ide> .attr("class", String); | 2 |
Ruby | Ruby | remove `@host` ivar | 3d32a50ca1933ee96abbe5db7ee99617fd0c328c | <ide><path>actionpack/lib/action_controller/metal/request_forgery_protection.rb
<ide> def handle_unverified_request
<ide> request.session = NullSessionHash.new(request.env)
<ide> request.env['action_dispatch.request.flash_hash'] = nil
<ide> request.env['rack.session.options'] = { skip: true }
<del> request.env['action_dispatch.cookies'] = NullCookieJar.build(request)
<add> request.env['action_dispatch.cookies'] = NullCookieJar.build(request, {})
<ide> end
<ide>
<ide> protected
<ide> def exists?
<ide> end
<ide>
<ide> class NullCookieJar < ActionDispatch::Cookies::CookieJar #:nodoc:
<del> def self.build(request)
<del> host = request.host
<del>
<del> new(host, request)
<del> end
<del>
<ide> def write(*)
<ide> # nothing
<ide> end
<ide><path>actionpack/lib/action_dispatch/middleware/cookies.rb
<ide> class CookieJar #:nodoc:
<ide> DOMAIN_REGEXP = /[^.]*\.([^.]*|..\...|...\...)$/
<ide>
<ide> def self.build(req, cookies)
<del> host = req.host
<del> new(host, req).tap do |hash|
<add> new(req).tap do |hash|
<ide> hash.update(cookies)
<ide> end
<ide> end
<ide>
<del> def initialize(host = nil, request)
<add> def initialize(request)
<ide> @set_cookies = {}
<ide> @delete_cookies = {}
<del> @host = host
<ide> @request = request
<ide> @cookies = {}
<ide> @committed = false
<ide> def handle_options(options) #:nodoc:
<ide>
<ide> # if host is not ip and matches domain regexp
<ide> # (ip confirms to domain regexp so we explicitly check for ip)
<del> options[:domain] = if (@host !~ /^[\d.]+$/) && (@host =~ domain_regexp)
<add> options[:domain] = if (@request.host !~ /^[\d.]+$/) && (@request.host =~ domain_regexp)
<ide> ".#{$&}"
<ide> end
<ide> elsif options[:domain].is_a? Array
<ide> # if host matches one of the supplied domains without a dot in front of it
<del> options[:domain] = options[:domain].find {|domain| @host.include? domain.sub(/^\./, '') }
<add> options[:domain] = options[:domain].find {|domain| @request.host.include? domain.sub(/^\./, '') }
<ide> end
<ide> end
<ide> | 2 |
Python | Python | add support for model merging | e82ab0ca50ec5230718e97d0affb2a8573ca52c9 | <ide><path>keras/layers/core.py
<ide> def get_config(self):
<ide> return {"name":self.__class__.__name__}
<ide>
<ide>
<add>class Merge(object):
<add> def __init__(self, models, mode='sum'):
<add> ''' Merge the output of a list of models into a single tensor.
<add> mode: {'sum', 'concat'}
<add> '''
<add> if len(models) < 2:
<add> raise Exception("Please specify two or more input models to merge")
<add> self.mode = mode
<add> self.models = models
<add> self.params = []
<add> self.regularizers = []
<add> self.constraints = []
<add> for m in self.models:
<add> self.params += m.params
<add> self.regularizers += m.regularizers
<add> self.constraints += m.constraints
<add>
<add> def get_output(self, train=False):
<add> if self.mode == 'sum':
<add> s = self.models[0].get_output(train)
<add> for i in range(1, len(self.models)):
<add> s += self.models[i].get_output(train)
<add> return s
<add> elif self.mode == 'concat':
<add> inputs = [self.models[i].get_output(train) for i in range(len(self.models))]
<add> return T.concatenate(inputs, axis=-1)
<add> else:
<add> raise Exception('Unknown merge mode')
<add>
<add> def get_input(self, train=False):
<add> res = []
<add> for i in range(len(self.models)):
<add> o = self.models[i].get_input(train)
<add> if type(o) == list:
<add> res += o
<add> else:
<add> res.append(o)
<add> return res
<add>
<add> def get_weights(self):
<add> weights = []
<add> for m in self.models:
<add> weights += m.get_weights()
<add> return weights
<add>
<add> def set_weights(self, weights):
<add> for i in range(len(self.models)):
<add> nb_param = len(self.models[i].params)
<add> self.models[i].set_weights(weights[:nb_param])
<add> weights = weights[nb_param:]
<add>
<add> def get_config(self):
<add> return {"name":self.__class__.__name__,
<add> "models":[m.get_config() for m in self.models],
<add> "mode":self.mode}
<add>
<add>
<ide> class Dropout(Layer):
<ide> '''
<ide> Hinton's dropout.
<ide><path>keras/models.py
<ide> from . import regularizers
<ide> from . import constraints
<ide> import time, copy
<del>from .utils.generic_utils import Progbar
<add>from .utils.generic_utils import Progbar, printv
<ide> from six.moves import range
<ide>
<ide> def standardize_y(y):
<ide> def ndim_tensor(ndim):
<ide> return T.tensor4()
<ide> return T.matrix()
<ide>
<del>class Sequential(object):
<add>def standardize_X(X):
<add> if type(X) == list:
<add> return X
<add> else:
<add> return [X]
<add>
<add>def slice_X(X, start=None, stop=None):
<add> if type(X) == list:
<add> if hasattr(start, '__len__'):
<add> return [x[start] for x in X]
<add> else:
<add> return [x[start:stop] for x in X]
<add> else:
<add> if hasattr(start, '__len__'):
<add> return X[start]
<add> else:
<add> return X[start:stop]
<add>
<add>
<add>class Model(object):
<add>
<add> def get_output(self, train):
<add> raise NotImplementedError
<add>
<add> def get_input(self, train):
<add> raise NotImplementedError
<add>
<add> def compile(self, optimizer, loss, class_mode="categorical", theano_mode=None):
<add> self.optimizer = optimizers.get(optimizer)
<add> self.loss = objectives.get(loss)
<add>
<add> # input of model
<add> self.X_train = self.get_input(train=True)
<add> self.X_test = self.get_input(train=False)
<add>
<add> self.y_train = self.get_output(train=True)
<add> self.y_test = self.get_output(train=False)
<add>
<add> self.y_train = self.get_output(train=True)
<add> self.y_test = self.get_output(train=False)
<add>
<add> # target of model
<add> self.y = T.zeros_like(self.y_train)
<add>
<add> train_loss = self.loss(self.y, self.y_train)
<add> test_score = self.loss(self.y, self.y_test)
<add>
<add> if class_mode == "categorical":
<add> train_accuracy = T.mean(T.eq(T.argmax(self.y, axis=-1), T.argmax(self.y_train, axis=-1)))
<add> test_accuracy = T.mean(T.eq(T.argmax(self.y, axis=-1), T.argmax(self.y_test, axis=-1)))
<add>
<add> elif class_mode == "binary":
<add> train_accuracy = T.mean(T.eq(self.y, T.round(self.y_train)))
<add> test_accuracy = T.mean(T.eq(self.y, T.round(self.y_test)))
<add> else:
<add> raise Exception("Invalid class mode:" + str(class_mode))
<add> self.class_mode = class_mode
<add>
<add> updates = self.optimizer.get_updates(self.params, self.regularizers, self.constraints, train_loss)
<add>
<add> if type(self.X_train) == list:
<add> train_ins = self.X_train + [self.y]
<add> test_ins = self.X_test + [self.y]
<add> predict_ins = self.X_test
<add> else:
<add> train_ins = [self.X_train, self.y]
<add> test_ins = [self.X_test, self.y]
<add> predict_ins = [self.X_test]
<add>
<add> self._train = theano.function(train_ins, train_loss,
<add> updates=updates, allow_input_downcast=True, mode=theano_mode)
<add> self._train_with_acc = theano.function(train_ins, [train_loss, train_accuracy],
<add> updates=updates, allow_input_downcast=True, mode=theano_mode)
<add> self._predict = theano.function(predict_ins, self.y_test,
<add> allow_input_downcast=True, mode=theano_mode)
<add> self._test = theano.function(test_ins, test_score,
<add> allow_input_downcast=True, mode=theano_mode)
<add> self._test_with_acc = theano.function(test_ins, [test_score, test_accuracy],
<add> allow_input_downcast=True, mode=theano_mode)
<add>
<add>
<add>class Sequential(Model):
<ide> def __init__(self):
<ide> self.layers = []
<del> self.params = []
<del> self.regularizers = []
<del> self.constraints = []
<add> self.params = [] # learnable
<add> self.regularizers = [] # same size as params
<add> self.constraints = [] # same size as params
<add>
<ide>
<ide> def add(self, layer):
<ide> self.layers.append(layer)
<ide> def add(self, layer):
<ide> else:
<ide> self.constraints += [constraints.identity for _ in range(len(layer.params))]
<ide>
<del> def get_output(self, train):
<add>
<add> def get_output(self, train=False):
<ide> return self.layers[-1].get_output(train)
<ide>
<del> def compile(self, optimizer, loss, class_mode="categorical", y_dim_components=1, theano_mode=None):
<del> self.optimizer = optimizers.get(optimizer)
<del> self.loss = objectives.get(loss)
<ide>
<del> # input of model
<add> def get_input(self, train=False):
<ide> if not hasattr(self.layers[0], 'input'):
<ide> for l in self.layers:
<ide> if hasattr(l, 'input'):
<ide> break
<ide> ndim = l.input.ndim
<ide> self.layers[0].input = ndim_tensor(ndim)
<del> self.X = self.layers[0].input
<del>
<del> self.y_train = self.get_output(train=True)
<del> self.y_test = self.get_output(train=False)
<del>
<del> # output of model
<del> self.y = ndim_tensor(y_dim_components+1)
<del>
<del> train_loss = self.loss(self.y, self.y_train)
<del> test_score = self.loss(self.y, self.y_test)
<del>
<del> if class_mode == "categorical":
<del> train_accuracy = T.mean(T.eq(T.argmax(self.y, axis=-1), T.argmax(self.y_train, axis=-1)))
<del> test_accuracy = T.mean(T.eq(T.argmax(self.y, axis=-1), T.argmax(self.y_test, axis=-1)))
<del>
<del> elif class_mode == "binary":
<del> train_accuracy = T.mean(T.eq(self.y, T.round(self.y_train)))
<del> test_accuracy = T.mean(T.eq(self.y, T.round(self.y_test)))
<del> else:
<del> raise Exception("Invalid class mode:" + str(class_mode))
<del> self.class_mode = class_mode
<del>
<del> updates = self.optimizer.get_updates(self.params, self.regularizers, self.constraints, train_loss)
<del>
<del> self._train = theano.function([self.X, self.y], train_loss,
<del> updates=updates, allow_input_downcast=True, mode=theano_mode)
<del> self._train_with_acc = theano.function([self.X, self.y], [train_loss, train_accuracy],
<del> updates=updates, allow_input_downcast=True, mode=theano_mode)
<del> self._predict = theano.function([self.X], self.y_test,
<del> allow_input_downcast=True, mode=theano_mode)
<del> self._test = theano.function([self.X, self.y], test_score,
<del> allow_input_downcast=True, mode=theano_mode)
<del> self._test_with_acc = theano.function([self.X, self.y], [test_score, test_accuracy],
<del> allow_input_downcast=True, mode=theano_mode)
<add> return self.layers[0].get_input(train)
<ide>
<ide>
<ide> def train(self, X, y, accuracy=False):
<add> X = standardize_X(X)
<ide> y = standardize_y(y)
<add> ins = X + [y]
<ide> if accuracy:
<del> return self._train_with_acc(X, y)
<add> return self._train_with_acc(*ins)
<ide> else:
<del> return self._train(X, y)
<add> return self._train(*ins)
<ide>
<ide>
<ide> def test(self, X, y, accuracy=False):
<add> X = standardize_X(X)
<ide> y = standardize_y(y)
<add> ins = X + [y]
<ide> if accuracy:
<del> return self._test_with_acc(X, y)
<add> return self._test_with_acc(*ins)
<ide> else:
<del> return self._test(X, y)
<add> return self._test(*ins)
<ide>
<ide>
<ide> def fit(self, X, y, batch_size=128, nb_epoch=100, verbose=1,
<ide> validation_split=0., validation_data=None, shuffle=True, show_accuracy=False):
<add>
<add> X = standardize_X(X)
<ide> y = standardize_y(y)
<ide>
<ide> do_validation = False
<ide> if validation_data:
<ide> try:
<ide> X_val, y_val = validation_data
<ide> except:
<del> raise Exception("Invalid format for validation data; provide a tuple (X_val, y_val).")
<add> raise Exception("Invalid format for validation data; provide a tuple (X_val, y_val). \
<add> X_val may be a numpy array or a list of numpy arrays depending on your model input.")
<ide> do_validation = True
<add> X_val = standardize_X(X_val)
<ide> y_val = standardize_y(y_val)
<ide> if verbose:
<ide> print("Train on %d samples, validate on %d samples" % (len(y), len(y_val)))
<ide> def fit(self, X, y, batch_size=128, nb_epoch=100, verbose=1,
<ide> # then split X into smaller X and X_val,
<ide> # and split y into smaller y and y_val.
<ide> do_validation = True
<del> split_at = int(len(X) * (1 - validation_split))
<del> (X, X_val) = (X[0:split_at], X[split_at:])
<add> split_at = int(len(y) * (1 - validation_split))
<add> (X, X_val) = (slice_X(X, 0, split_at), slice_X(X, split_at))
<ide> (y, y_val) = (y[0:split_at], y[split_at:])
<ide> if verbose:
<ide> print("Train on %d samples, validate on %d samples" % (len(y), len(y_val)))
<ide> def fit(self, X, y, batch_size=128, nb_epoch=100, verbose=1,
<ide> if show_accuracy:
<ide> history['val_acc'] = []
<ide>
<del> index_array = np.arange(len(X))
<add> index_array = np.arange(len(y))
<ide> for epoch in range(nb_epoch):
<ide> if verbose:
<ide> print('Epoch', epoch)
<del> progbar = Progbar(target=len(X), verbose=verbose)
<add> progbar = Progbar(target=len(y), verbose=verbose)
<ide> if shuffle:
<ide> np.random.shuffle(index_array)
<ide>
<ide> av_loss = 0.
<ide> av_acc = 0.
<ide> seen = 0
<ide>
<del> batches = make_batches(len(X), batch_size)
<add> batches = make_batches(len(y), batch_size)
<ide> for batch_index, (batch_start, batch_end) in enumerate(batches):
<ide> batch_ids = index_array[batch_start:batch_end]
<ide> seen += len(batch_ids)
<del> X_batch = X[batch_ids]
<add> X_batch = slice_X(X, batch_ids)
<ide> y_batch = y[batch_ids]
<ide>
<add> ins = X_batch + [y_batch]
<ide> if show_accuracy:
<del> loss, acc = self._train_with_acc(X_batch, y_batch)
<add> loss, acc = self._train_with_acc(*ins)
<ide> log_values = [('loss', loss), ('acc.', acc)]
<ide> av_loss += loss * len(batch_ids)
<ide> av_acc += acc * len(batch_ids)
<ide> else:
<del> loss = self._train(X_batch, y_batch)
<add> loss = self._train(*ins)
<ide> log_values = [('loss', loss)]
<ide> av_loss += loss * len(batch_ids)
<ide>
<ide> def fit(self, X, y, batch_size=128, nb_epoch=100, verbose=1,
<ide> return history
<ide>
<ide> def predict(self, X, batch_size=128, verbose=1):
<del> batches = make_batches(len(X), batch_size)
<add> X = standardize_X(X)
<add> batches = make_batches(len(X[0]), batch_size)
<ide> if verbose==1:
<del> progbar = Progbar(target=len(X))
<add> progbar = Progbar(target=len(X[0]))
<ide> for batch_index, (batch_start, batch_end) in enumerate(batches):
<del> X_batch = X[batch_start:batch_end]
<del> batch_preds = self._predict(X_batch)
<add> X_batch = slice_X(X, batch_start, batch_end)
<add> batch_preds = self._predict(*X_batch)
<ide>
<ide> if batch_index == 0:
<del> shape = (len(X),) + batch_preds.shape[1:]
<add> shape = (len(X[0]),) + batch_preds.shape[1:]
<ide> preds = np.zeros(shape)
<ide> preds[batch_start:batch_end] = batch_preds
<ide>
<ide> def predict_proba(self, X, batch_size=128, verbose=1):
<ide>
<ide>
<ide> def predict_classes(self, X, batch_size=128, verbose=1):
<del> proba = self.predict_proba(X, batch_size=batch_size, verbose=verbose)
<add> proba = self.predict(X, batch_size=batch_size, verbose=verbose)
<ide> if self.class_mode == "categorical":
<ide> return proba.argmax(axis=-1)
<ide> else:
<ide> return (proba>0.5).astype('int32')
<ide>
<ide>
<ide> def evaluate(self, X, y, batch_size=128, show_accuracy=False, verbose=1):
<add> X = standardize_X(X)
<ide> y = standardize_y(y)
<ide>
<ide> if show_accuracy:
<ide> tot_acc = 0.
<ide> tot_score = 0.
<ide>
<del> batches = make_batches(len(X), batch_size)
<add> batches = make_batches(len(y), batch_size)
<ide> if verbose:
<del> progbar = Progbar(target=len(X), verbose=verbose)
<add> progbar = Progbar(target=len(y), verbose=verbose)
<ide> for batch_index, (batch_start, batch_end) in enumerate(batches):
<del> X_batch = X[batch_start:batch_end]
<add> X_batch = slice_X(X, batch_start, batch_end)
<ide> y_batch = y[batch_start:batch_end]
<ide>
<add> ins = X_batch + [y_batch]
<ide> if show_accuracy:
<del> loss, acc = self._test_with_acc(X_batch, y_batch)
<add> loss, acc = self._test_with_acc(*ins)
<ide> tot_acc += acc
<ide> log_values = [('loss', loss), ('acc.', acc)]
<ide> else:
<del> loss = self._test(X_batch, y_batch)
<add> loss = self._test(*ins)
<ide> log_values = [('loss', loss)]
<ide> tot_score += loss
<ide>
<ide> def evaluate(self, X, y, batch_size=128, show_accuracy=False, verbose=1):
<ide> else:
<ide> return tot_score/len(batches)
<ide>
<del> def describe(self, verbose=1):
<add> def get_config(self, verbose=0):
<ide> layers = []
<ide> for i, l in enumerate(self.layers):
<ide> config = l.get_config()
<ide> layers.append(config)
<del> if verbose:
<del> print('Layer %d: %s' % (i, config.get('name', '?')))
<del> for k, v in config.items():
<del> if k != 'name':
<del> print('... ' + k + ' = ' + str(v))
<add> if verbose:
<add> printv(layers)
<ide> return layers
<ide>
<add> def get_weights(self):
<add> res = []
<add> for l in self.layers:
<add> res += l.get_weights()
<add> return res
<add>
<add> def set_weights(self, weights):
<add> for i in range(len(self.layers)):
<add> nb_param = len(self.layers[i].params)
<add> self.layers[i].set_weights(weights[:nb_param])
<add> weights = weights[nb_param:]
<add>
<ide> def save_weights(self, filepath):
<ide> # Save weights from all layers to HDF5
<ide> import h5py
<ide> def save_weights(self, filepath):
<ide> g.attrs['nb_params'] = len(weights)
<ide> for n, param in enumerate(weights):
<ide> param_name = 'param_{}'.format(n)
<del> param_dset = g.create_dataset(param_name, param.shape, dtype='float64')
<add> param_dset = g.create_dataset(param_name, param.shape, dtype=param.dtype)
<ide> param_dset[:] = param
<del> for k, v in l.get_config().items():
<del> if v is not None:
<del> g.attrs[k] = v
<ide> f.flush()
<ide> f.close()
<ide>
<ide> def load_weights(self, filepath):
<ide> weights = [g['param_{}'.format(p)] for p in range(g.attrs['nb_params'])]
<ide> self.layers[k].set_weights(weights)
<ide> f.close()
<del>
<del>
<add>
<ide>\ No newline at end of file
<ide><path>keras/utils/generic_utils.py
<ide> def get_from_module(identifier, module_params, module_name, instantiate=False):
<ide> def make_tuple(*args):
<ide> return args
<ide>
<add>def printv(v, prefix=''):
<add> if type(v) == dict:
<add> if 'name' in v:
<add> print(prefix + '#' + v['name'])
<add> del v['name']
<add> prefix += '...'
<add> for nk, nv in v.items():
<add> if type(nv) in [dict, list]:
<add> print(prefix + nk + ':')
<add> printv(nv, prefix)
<add> else:
<add> print(prefix + nk + ':' + str(nv))
<add> elif type(v) == list:
<add> prefix += '...'
<add> for i, nv in enumerate(v):
<add> print(prefix + '#' + str(i))
<add> printv(nv, prefix)
<add> else:
<add> prefix += '...'
<add> print(prefix + str(v))
<add>
<ide> class Progbar(object):
<ide> def __init__(self, target, width=30, verbose=1):
<ide> '''
<ide><path>test/test_models.py
<add>from __future__ import absolute_import
<add>from __future__ import print_function
<add>from keras.datasets import mnist
<add>from keras.models import Sequential
<add>from keras.layers.core import Dense, Activation, Merge
<add>from keras.utils import np_utils
<add>import numpy as np
<add>
<add>nb_classes = 10
<add>batch_size = 128
<add>nb_epoch = 1
<add>
<add>max_train_samples = 5000
<add>max_test_samples = 1000
<add>
<add>np.random.seed(1337) # for reproducibility
<add>
<add># the data, shuffled and split between tran and test sets
<add>(X_train, y_train), (X_test, y_test) = mnist.load_data()
<add>
<add>X_train = X_train.reshape(60000,784)[:max_train_samples]
<add>X_test = X_test.reshape(10000,784)[:max_test_samples]
<add>X_train = X_train.astype("float32")
<add>X_test = X_test.astype("float32")
<add>X_train /= 255
<add>X_test /= 255
<add>
<add># convert class vectors to binary class matrices
<add>Y_train = np_utils.to_categorical(y_train, nb_classes)[:max_train_samples]
<add>Y_test = np_utils.to_categorical(y_test, nb_classes)[:max_test_samples]
<add>
<add>#########################
<add># sequential model test #
<add>#########################
<add>print('Test sequential')
<add>model = Sequential()
<add>model.add(Dense(784, 50))
<add>model.add(Activation('relu'))
<add>model.add(Dense(50, 10))
<add>model.add(Activation('softmax'))
<add>
<add>model.compile(loss='categorical_crossentropy', optimizer='rmsprop')
<add>model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=True, verbose=0, validation_data=(X_test, Y_test))
<add>model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=False, verbose=0, validation_data=(X_test, Y_test))
<add>model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=True, verbose=0, validation_split=0.1)
<add>model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=False, verbose=0, validation_split=0.1)
<add>model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=0)
<add>model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=0, shuffle=False)
<add>
<add>score = model.evaluate(X_train, Y_train, verbose=0)
<add>print('score:', score)
<add>if score < 0.25:
<add> raise Exception('Score too low, learning issue.')
<add>preds = model.predict(X_test, verbose=0)
<add>classes = model.predict_classes(X_test, verbose=0)
<add>
<add>model.get_config(verbose=1)
<add>
<add>###################
<add># merge test: sum #
<add>###################
<add>print('Test merge: sum')
<add>left = Sequential()
<add>left.add(Dense(784, 50))
<add>left.add(Activation('relu'))
<add>
<add>right = Sequential()
<add>right.add(Dense(784, 50))
<add>right.add(Activation('relu'))
<add>
<add>model = Sequential()
<add>model.add(Merge([left, right], mode='sum'))
<add>
<add>model.add(Dense(50, 10))
<add>model.add(Activation('softmax'))
<add>
<add>model.compile(loss='categorical_crossentropy', optimizer='rmsprop')
<add>
<add>model.fit([X_train, X_train], Y_train, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=True, verbose=0, validation_data=([X_test, X_test], Y_test))
<add>model.fit([X_train, X_train], Y_train, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=False, verbose=0, validation_data=([X_test, X_test], Y_test))
<add>model.fit([X_train, X_train], Y_train, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=True, verbose=0, validation_split=0.1)
<add>model.fit([X_train, X_train], Y_train, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=False, verbose=0, validation_split=0.1)
<add>model.fit([X_train, X_train], Y_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=0)
<add>model.fit([X_train, X_train], Y_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=0, shuffle=False)
<add>
<add>score = model.evaluate([X_train, X_train], Y_train, verbose=0)
<add>print('score:', score)
<add>if score < 0.22:
<add> raise Exception('Score too low, learning issue.')
<add>preds = model.predict([X_test, X_test], verbose=0)
<add>classes = model.predict_classes([X_test, X_test], verbose=0)
<add>
<add>model.get_config(verbose=1)
<add>
<add>###################
<add># merge test: concat #
<add>###################
<add>print('Test merge: concat')
<add>left = Sequential()
<add>left.add(Dense(784, 50))
<add>left.add(Activation('relu'))
<add>
<add>right = Sequential()
<add>right.add(Dense(784, 50))
<add>right.add(Activation('relu'))
<add>
<add>model = Sequential()
<add>model.add(Merge([left, right], mode='concat'))
<add>
<add>model.add(Dense(50*2, 10))
<add>model.add(Activation('softmax'))
<add>
<add>model.compile(loss='categorical_crossentropy', optimizer='rmsprop')
<add>
<add>model.fit([X_train, X_train], Y_train, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=True, verbose=0, validation_data=([X_test, X_test], Y_test))
<add>model.fit([X_train, X_train], Y_train, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=False, verbose=0, validation_data=([X_test, X_test], Y_test))
<add>model.fit([X_train, X_train], Y_train, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=True, verbose=0, validation_split=0.1)
<add>model.fit([X_train, X_train], Y_train, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=False, verbose=0, validation_split=0.1)
<add>model.fit([X_train, X_train], Y_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=0)
<add>model.fit([X_train, X_train], Y_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=0, shuffle=False)
<add>
<add>score = model.evaluate([X_train, X_train], Y_train, verbose=0)
<add>print('score:', score)
<add>if score < 0.22:
<add> raise Exception('Score too low, learning issue.')
<add>preds = model.predict([X_test, X_test], verbose=0)
<add>classes = model.predict_classes([X_test, X_test], verbose=0)
<add>
<add>model.get_config(verbose=1)
<add>
<add>##########################
<add># test merge recursivity #
<add>##########################
<add>print('Test merge recursivity')
<add>
<add>left = Sequential()
<add>left.add(Dense(784, 50))
<add>left.add(Activation('relu'))
<add>
<add>right = Sequential()
<add>right.add(Dense(784, 50))
<add>right.add(Activation('relu'))
<add>
<add>righter = Sequential()
<add>righter.add(Dense(784, 50))
<add>righter.add(Activation('relu'))
<add>
<add>intermediate = Sequential()
<add>intermediate.add(Merge([left, right], mode='sum'))
<add>intermediate.add(Dense(50, 50))
<add>intermediate.add(Activation('relu'))
<add>
<add>model = Sequential()
<add>model.add(Merge([intermediate, righter], mode='sum'))
<add>
<add>model.add(Dense(50, 10))
<add>model.add(Activation('softmax'))
<add>
<add>model.compile(loss='categorical_crossentropy', optimizer='rmsprop')
<add>
<add>model.fit([X_train, X_train, X_train], Y_train, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=True, verbose=0, validation_data=([X_test, X_test, X_test], Y_test))
<add>model.fit([X_train, X_train, X_train], Y_train, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=False, verbose=0, validation_data=([X_test, X_test, X_test], Y_test))
<add>model.fit([X_train, X_train, X_train], Y_train, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=True, verbose=0, validation_split=0.1)
<add>model.fit([X_train, X_train, X_train], Y_train, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=False, verbose=0, validation_split=0.1)
<add>model.fit([X_train, X_train, X_train], Y_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=0)
<add>model.fit([X_train, X_train, X_train], Y_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=0, shuffle=False)
<add>
<add>score = model.evaluate([X_train, X_train, X_train], Y_train, verbose=0)
<add>print('score:', score)
<add>if score < 0.19:
<add> raise Exception('Score too low, learning issue.')
<add>preds = model.predict([X_test, X_test, X_test], verbose=0)
<add>classes = model.predict_classes([X_test, X_test, X_test], verbose=0)
<add>
<add>model.get_config(verbose=1)
<add>
<add>model.save_weights('temp.h5')
<add>model.load_weights('temp.h5')
<add>
<add>score = model.evaluate([X_train, X_train, X_train], Y_train, verbose=0)
<add>print('score:', score)
<add>
<add>
<add> | 4 |
Text | Text | fix broken tutorial link and change wording | cfe4152b1dba09d95387e62e8bb1f46cdd86c7da | <ide><path>docs/docs/tutorial.md
<ide> var CommentBox = React.createClass({
<ide>
<ide> ### Congrats!
<ide>
<del>You have just built a comment box in a few simple steps. Learn more about React in the [reference](syntax.html) or start hacking! Good luck!
<add>You have just built a comment box in a few simple steps. Learn more about [why to use React](why-react.html), or dive into the [API reference](reference.html) and start hacking! Good luck! | 1 |
Ruby | Ruby | fix typo in docs | b31c2fd0172ca770a4851ea42c91367e7a22cc52 | <ide><path>activerecord/test/cases/connection_adapters/schema_cache_test.rb
<ide> def test_marshal_dump_and_load
<ide> # Populate it.
<ide> cache.add("posts")
<ide>
<del> # Create a new cache by marchal dumping / loading.
<add> # Create a new cache by marshal dumping / loading.
<ide> cache = Marshal.load(Marshal.dump(cache))
<ide>
<ide> assert_no_queries do | 1 |
Javascript | Javascript | add an #each test | 180856b5b6836f5cf95862ba02272722b064fc49 | <ide><path>packages/ember-htmlbars/tests/helpers/each_test.js
<ide> function testEachWithItem(moduleName, useBlockParams) {
<ide> equal(view.$().text(), "controller:people - controller:Steve Holt of Yapp - controller:people - controller:Annabelle of Yapp - ");
<ide> });
<ide>
<add>
<add> QUnit.test("locals in stable loops update when the list is updated", function() {
<add> expect(3);
<add>
<add> var list = [{ key: "adam", name: "Adam" }, { key: "steve", name: "Steve" }];
<add> view = EmberView.create({
<add> queries: list,
<add> template: templateFor('{{#each view.queries key="key" as |query|}}{{query.name}}{{/each}}', true)
<add> });
<add> runAppend(view);
<add> equal(view.$().text(), "AdamSteve");
<add>
<add> run(function() {
<add> list.unshift({ key: "bob", name: "Bob" });
<add> view.set('queries', list);
<add> view.notifyPropertyChange('queries');
<add> });
<add>
<add> equal(view.$().text(), "BobAdamSteve");
<add>
<add> run(function() {
<add> view.set('queries', [{ key: 'bob', name: "Bob" }, { key: 'steve', name: "Steve" }]);
<add> view.notifyPropertyChange('queries');
<add> });
<add>
<add> equal(view.$().text(), "BobSteve");
<add> });
<add>
<ide> if (!useBlockParams) {
<ide> QUnit.test("{{each}} without arguments [DEPRECATED]", function() {
<ide> expect(2); | 1 |
PHP | PHP | improve nested rules in validated data | 0a56560863125853873997013b43f6ab1eeb5c2c | <ide><path>src/Illuminate/Foundation/Http/FormRequest.php
<ide>
<ide> namespace Illuminate\Foundation\Http;
<ide>
<add>use Illuminate\Support\Str;
<ide> use Illuminate\Http\Request;
<ide> use Illuminate\Routing\Redirector;
<ide> use Illuminate\Contracts\Container\Container;
<ide> public function validated()
<ide> $rules = $this->container->call([$this, 'rules']);
<ide>
<ide> return $this->only(collect($rules)->keys()->map(function ($rule) {
<del> return explode('.', $rule)[0];
<add> return Str::contains($rule, '*') ? explode('.', $rule)[0] : $rule;
<ide> })->unique()->toArray());
<ide> }
<ide>
<ide><path>src/Illuminate/Foundation/Providers/FoundationServiceProvider.php
<ide>
<ide> namespace Illuminate\Foundation\Providers;
<ide>
<add>use Illuminate\Support\Str;
<ide> use Illuminate\Http\Request;
<ide> use Illuminate\Support\Facades\URL;
<ide> use Illuminate\Support\AggregateServiceProvider;
<ide> public function registerRequestValidation()
<ide> validator()->validate($this->all(), $rules, ...$params);
<ide>
<ide> return $this->only(collect($rules)->keys()->map(function ($rule) {
<del> return explode('.', $rule)[0];
<add> return Str::contains($rule, '*') ? explode('.', $rule)[0] : $rule;
<ide> })->unique()->toArray());
<ide> });
<ide> }
<ide><path>src/Illuminate/Foundation/Validation/ValidatesRequests.php
<ide>
<ide> namespace Illuminate\Foundation\Validation;
<ide>
<add>use Illuminate\Support\Str;
<ide> use Illuminate\Http\Request;
<ide> use Illuminate\Contracts\Validation\Factory;
<ide> use Illuminate\Validation\ValidationException;
<ide> public function validate(Request $request, array $rules,
<ide> protected function extractInputFromRules(Request $request, array $rules)
<ide> {
<ide> return $request->only(collect($rules)->keys()->map(function ($rule) {
<del> return explode('.', $rule)[0];
<add> return Str::contains($rule, '*') ? explode('.', $rule)[0] : $rule;
<ide> })->unique()->toArray());
<ide> }
<ide>
<ide><path>src/Illuminate/Validation/Validator.php
<ide> public function validate()
<ide> throw new ValidationException($this);
<ide> }
<ide>
<del> $data = collect($this->getData());
<add> $results = [];
<ide>
<del> return $data->only(collect($this->getRules())->keys()->map(function ($rule) {
<del> return explode('.', $rule)[0];
<del> })->unique())->toArray();
<add> $rules = collect($this->getRules())->keys()->map(function ($rule) {
<add> return Str::contains($rule, '*') ? explode('.', $rule)[0] : $rule;
<add> })->unique();
<add>
<add> foreach ($rules as $rule) {
<add> Arr::set($results, $rule, data_get($this->getData(), $rule));
<add> }
<add>
<add> return $results;
<ide> }
<ide>
<ide> /**
<ide><path>tests/Foundation/FoundationFormRequestTest.php
<ide> public function test_validated_method_returns_the_validated_data()
<ide> $this->assertEquals(['name' => 'specified'], $request->validated());
<ide> }
<ide>
<add> public function test_validated_method_returns_the_validated_data_nested_rules()
<add> {
<add> $payload = ['nested' => ['foo' => 'bar', 'baz' => ''], 'array' => [1, 2]];
<add>
<add> $request = $this->createRequest($payload, FoundationTestFormRequestNestedStub::class);
<add>
<add> $request->validateResolved();
<add>
<add> $this->assertEquals(['nested' => ['foo' => 'bar'], 'array' => [1, 2]], $request->validated());
<add> }
<add>
<ide> /**
<ide> * @expectedException \Illuminate\Validation\ValidationException
<ide> */
<ide> public function authorize()
<ide> }
<ide> }
<ide>
<add>class FoundationTestFormRequestNestedStub extends FormRequest
<add>{
<add> public function rules()
<add> {
<add> return ['nested.foo' => 'required', 'array.*' => 'integer'];
<add> }
<add>
<add> public function authorize()
<add> {
<add> return true;
<add> }
<add>}
<add>
<ide> class FoundationTestFormRequestForbiddenStub extends FormRequest
<ide> {
<ide> public function rules()
<ide><path>tests/Validation/ValidationValidatorTest.php
<ide> public function testValidateReturnsValidatedData()
<ide> $this->assertEquals(['first' => 'john', 'preferred' => 'john'], $data);
<ide> }
<ide>
<add> public function testValidateReturnsValidatedDataNestedRules()
<add> {
<add> $post = ['nested' => ['foo' => 'bar', 'baz' => ''], 'array' => [1, 2]];
<add>
<add> $rules = ['nested.foo' => 'required', 'array.*' => 'integer'];
<add>
<add> $v = new Validator($this->getIlluminateArrayTranslator(), $post, $rules);
<add> $v->sometimes('type', 'required', function () {
<add> return false;
<add> });
<add> $data = $v->validate();
<add>
<add> $this->assertEquals(['nested' => ['foo' => 'bar'], 'array' => [1, 2]], $data);
<add> }
<add>
<ide> protected function getTranslator()
<ide> {
<ide> return m::mock('Illuminate\Contracts\Translation\Translator'); | 6 |
Javascript | Javascript | improve test coverage of internal/blob | 1285ac116d4334d1be3ce324591d28ec27bd61b2 | <ide><path>test/parallel/test-blob-buffer-too-large.js
<add>// Flags: --no-warnings
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const { Blob } = require('buffer');
<add>
<add>if (common.isFreeBSD)
<add> common.skip('Oversized buffer make the FreeBSD CI runner crash');
<add>
<add>try {
<add> new Blob([new Uint8Array(0xffffffff), [1]]);
<add>} catch (e) {
<add> if (
<add> e.message === 'Array buffer allocation failed' ||
<add> e.message === 'Invalid typed array length: 4294967295'
<add> ) {
<add> common.skip(
<add> 'Insufficient memory on this platform for oversized buffer test.'
<add> );
<add> } else {
<add> assert.strictEqual(e.code, 'ERR_BUFFER_TOO_LARGE');
<add> }
<add>}
<ide><path>test/parallel/test-blob.js
<ide> assert.throws(() => new Blob({}), {
<ide> const b = new Blob();
<ide> assert.strictEqual(inspect(b, { depth: null }),
<ide> 'Blob { size: 0, type: \'\' }');
<add> assert.strictEqual(inspect(b, { depth: 1 }),
<add> 'Blob { size: 0, type: \'\' }');
<ide> assert.strictEqual(inspect(b, { depth: -1 }), '[Blob]');
<ide> }
<ide>
<ide> assert.throws(() => new Blob({}), {
<ide> });
<ide> }
<ide>
<add>{
<add> assert.throws(() => Reflect.get(Blob.prototype, 'type', {}), {
<add> code: 'ERR_INVALID_THIS',
<add> });
<add> assert.throws(() => Reflect.get(Blob.prototype, 'size', {}), {
<add> code: 'ERR_INVALID_THIS',
<add> });
<add> assert.throws(() => Blob.prototype.slice(Blob.prototype, 0, 1), {
<add> code: 'ERR_INVALID_THIS',
<add> });
<add> assert.throws(() => Blob.prototype.stream.call(), {
<add> code: 'ERR_INVALID_THIS',
<add> });
<add>}
<add>
<add>(async () => {
<add> assert.rejects(async () => Blob.prototype.arrayBuffer.call(), {
<add> code: 'ERR_INVALID_THIS',
<add> });
<add> assert.rejects(async () => Blob.prototype.text.call(), {
<add> code: 'ERR_INVALID_THIS',
<add> });
<add>})().then(common.mustCall());
<add>
<ide> (async () => {
<ide> const blob = new Blob([
<ide> new Uint8Array([0x50, 0x41, 0x53, 0x53]), | 2 |
Javascript | Javascript | remove enablepersistentoffscreenhostcontainer flag | ce13860281f833de8a3296b7a3dad9caced102e9 | <ide><path>packages/react-native-renderer/src/ReactFabricHostConfig.js
<ide> * @flow
<ide> */
<ide>
<del>import type {ReactNodeList, OffscreenMode} from 'shared/ReactTypes';
<ide> import type {ElementRef} from 'react';
<ide> import type {
<ide> HostComponent,
<ide> export function cloneInstance(
<ide> };
<ide> }
<ide>
<del>// TODO: These two methods should be replaced with `createOffscreenInstance` and
<del>// `cloneOffscreenInstance`. I did it this way for now because the offscreen
<del>// instance is stored on an extra HostComponent fiber instead of the
<del>// OffscreenComponent fiber, and I didn't want to add an extra check to the
<del>// generic HostComponent path. Instead we should use the OffscreenComponent
<del>// fiber, but currently Fabric expects a 1:1 correspondence between Fabric
<del>// instances and host fibers, so I'm leaving this optimization for later once
<del>// we can confirm this won't break any downstream expectations.
<del>export function getOffscreenContainerType(): string {
<del> return 'RCTView';
<del>}
<del>
<del>export function getOffscreenContainerProps(
<del> mode: OffscreenMode,
<del> children: ReactNodeList,
<del>): Props {
<del> if (mode === 'hidden') {
<del> return {
<del> children,
<del> style: {display: 'none'},
<del> };
<del> } else {
<del> return {
<del> children,
<del> style: {
<del> flex: 1,
<del> },
<del> };
<del> }
<del>}
<del>
<ide> export function cloneHiddenInstance(
<ide> instance: Instance,
<ide> type: string,
<ide><path>packages/react-noop-renderer/src/createReactNoop.js
<ide> import type {
<ide> TransitionTracingCallbacks,
<ide> } from 'react-reconciler/src/ReactInternalTypes';
<ide> import type {UpdateQueue} from 'react-reconciler/src/ReactUpdateQueue';
<del>import type {ReactNodeList, OffscreenMode} from 'shared/ReactTypes';
<add>import type {ReactNodeList} from 'shared/ReactTypes';
<ide> import type {RootTag} from 'react-reconciler/src/ReactRootTags';
<ide>
<ide> import * as Scheduler from 'scheduler/unstable_mock';
<ide> function createReactNoop(reconciler: Function, useMutation: boolean) {
<ide> container.children = newChildren;
<ide> },
<ide>
<del> getOffscreenContainerType(): string {
<del> return 'offscreen';
<del> },
<del>
<del> getOffscreenContainerProps(
<del> mode: OffscreenMode,
<del> children: ReactNodeList,
<del> ): Props {
<del> return {
<del> hidden: mode === 'hidden',
<del> children,
<del> };
<del> },
<del>
<ide> cloneHiddenInstance(
<ide> instance: Instance,
<ide> type: string,
<ide> function createReactNoop(reconciler: Function, useMutation: boolean) {
<ide>
<ide> function getChildren(root) {
<ide> if (root) {
<del> return useMutation
<del> ? root.children
<del> : removeOffscreenContainersFromChildren(root.children, false);
<add> return root.children;
<ide> } else {
<ide> return null;
<ide> }
<ide> }
<ide>
<ide> function getPendingChildren(root) {
<ide> if (root) {
<del> return useMutation
<del> ? root.children
<del> : removeOffscreenContainersFromChildren(root.pendingChildren, false);
<add> return root.children;
<ide> } else {
<ide> return null;
<ide> }
<ide> }
<ide>
<del> function removeOffscreenContainersFromChildren(children, hideNearestNode) {
<del> // Mutation mode and persistent mode have different outputs for Offscreen
<del> // and Suspense trees. Persistent mode adds an additional host node wrapper,
<del> // whereas mutation mode does not.
<del> //
<del> // This function removes the offscreen host wrappers so that the output is
<del> // consistent. If the offscreen node is hidden, it transfers the hiddenness
<del> // to the child nodes, to mimic how it works in mutation mode. That way our
<del> // tests don't have to fork tree assertions.
<del> //
<del> // So, it takes a tree that looks like this:
<del> //
<del> // <offscreen hidden={true}>
<del> // <span>A</span>
<del> // <span>B</span>
<del> // </offscren>
<del> //
<del> // And turns it into this:
<del> //
<del> // <span hidden={true}>A</span>
<del> // <span hidden={true}>B</span>
<del> //
<del> // We don't mutate the original tree, but instead return a copy.
<del> //
<del> // This function is only used by our test assertions, via the `getChildren`
<del> // and `getChildrenAsJSX` methods.
<del> let didClone = false;
<del> const newChildren = [];
<del> for (let i = 0; i < children.length; i++) {
<del> const child = children[i];
<del> const innerChildren = child.children;
<del> if (innerChildren !== undefined) {
<del> // This is a host instance instance
<del> const instance: Instance = (child: any);
<del> if (instance.type === 'offscreen') {
<del> // This is an offscreen wrapper instance. Remove it from the tree
<del> // and recursively return its children, as if it were a fragment.
<del> didClone = true;
<del> if (instance.text !== null) {
<del> // If this offscreen tree contains only text, we replace it with
<del> // a text child. Related to `shouldReplaceTextContent` feature.
<del> const offscreenTextInstance: TextInstance = {
<del> text: instance.text,
<del> id: instanceCounter++,
<del> parent: instance.parent,
<del> hidden: hideNearestNode || instance.hidden,
<del> context: instance.context,
<del> };
<del> // Hide from unit tests
<del> Object.defineProperty(offscreenTextInstance, 'id', {
<del> value: offscreenTextInstance.id,
<del> enumerable: false,
<del> });
<del> Object.defineProperty(offscreenTextInstance, 'parent', {
<del> value: offscreenTextInstance.parent,
<del> enumerable: false,
<del> });
<del> Object.defineProperty(offscreenTextInstance, 'context', {
<del> value: offscreenTextInstance.context,
<del> enumerable: false,
<del> });
<del> newChildren.push(offscreenTextInstance);
<del> } else {
<del> // Skip the offscreen node and replace it with its children
<del> const offscreenChildren = removeOffscreenContainersFromChildren(
<del> innerChildren,
<del> hideNearestNode || instance.hidden,
<del> );
<del> newChildren.push.apply(newChildren, offscreenChildren);
<del> }
<del> } else {
<del> // This is a regular (non-offscreen) instance. If the nearest
<del> // offscreen boundary is hidden, hide this node.
<del> const hidden = hideNearestNode ? true : instance.hidden;
<del> const clonedChildren = removeOffscreenContainersFromChildren(
<del> instance.children,
<del> // We never need to hide the children of this node, since if we're
<del> // inside a hidden tree, then the hidden style will be applied to
<del> // this node.
<del> false,
<del> );
<del> if (
<del> clonedChildren === instance.children &&
<del> hidden === instance.hidden
<del> ) {
<del> // No changes. Reuse the original instance without cloning.
<del> newChildren.push(instance);
<del> } else {
<del> didClone = true;
<del> const clone: Instance = {
<del> id: instance.id,
<del> type: instance.type,
<del> parent: instance.parent,
<del> children: clonedChildren,
<del> text: instance.text,
<del> prop: instance.prop,
<del> hidden: hideNearestNode ? true : instance.hidden,
<del> context: instance.context,
<del> };
<del> Object.defineProperty(clone, 'id', {
<del> value: clone.id,
<del> enumerable: false,
<del> });
<del> Object.defineProperty(clone, 'parent', {
<del> value: clone.parent,
<del> enumerable: false,
<del> });
<del> Object.defineProperty(clone, 'text', {
<del> value: clone.text,
<del> enumerable: false,
<del> });
<del> Object.defineProperty(clone, 'context', {
<del> value: clone.context,
<del> enumerable: false,
<del> });
<del> newChildren.push(clone);
<del> }
<del> }
<del> } else {
<del> // This is a text instance
<del> const textInstance: TextInstance = (child: any);
<del> if (hideNearestNode) {
<del> didClone = true;
<del> const clone = {
<del> text: textInstance.text,
<del> id: textInstance.id,
<del> parent: textInstance.parent,
<del> hidden: textInstance.hidden || hideNearestNode,
<del> context: textInstance.context,
<del> };
<del> Object.defineProperty(clone, 'id', {
<del> value: clone.id,
<del> enumerable: false,
<del> });
<del> Object.defineProperty(clone, 'parent', {
<del> value: clone.parent,
<del> enumerable: false,
<del> });
<del> Object.defineProperty(clone, 'context', {
<del> value: clone.context,
<del> enumerable: false,
<del> });
<del>
<del> newChildren.push(clone);
<del> } else {
<del> newChildren.push(textInstance);
<del> }
<del> }
<del> }
<del> // There are some tests that assume reference equality, so preserve it
<del> // when possible. Alternatively, we could update the tests to compare the
<del> // ids instead.
<del> return didClone ? newChildren : children;
<del> }
<del>
<ide> function getChildrenAsJSX(root) {
<ide> const children = childToJSX(getChildren(root), null);
<ide> if (children === null) {
<ide><path>packages/react-reconciler/src/ReactFiber.new.js
<ide> import type {RootTag} from './ReactRootTags';
<ide> import type {WorkTag} from './ReactWorkTags';
<ide> import type {TypeOfMode} from './ReactTypeOfMode';
<ide> import type {Lanes} from './ReactFiberLane.new';
<del>import type {SuspenseInstance, Props} from './ReactFiberHostConfig';
<add>import type {SuspenseInstance} from './ReactFiberHostConfig';
<ide> import type {
<ide> OffscreenProps,
<ide> OffscreenInstance,
<ide> import {
<ide> enableTransitionTracing,
<ide> enableDebugTracing,
<ide> } from 'shared/ReactFeatureFlags';
<del>import {
<del> supportsPersistence,
<del> getOffscreenContainerType,
<del>} from './ReactFiberHostConfig';
<ide> import {NoFlags, Placement, StaticMask} from './ReactFiberFlags';
<ide> import {ConcurrentRoot} from './ReactRootTags';
<ide> import {
<ide> export function createFiberFromTypeAndProps(
<ide> return fiber;
<ide> }
<ide>
<del>export function createOffscreenHostContainerFiber(
<del> props: Props,
<del> fiberMode: TypeOfMode,
<del> lanes: Lanes,
<del> key: null | string,
<del>): Fiber {
<del> if (supportsPersistence) {
<del> const type = getOffscreenContainerType();
<del> const fiber = createFiber(HostComponent, props, key, fiberMode);
<del> fiber.elementType = type;
<del> fiber.type = type;
<del> fiber.lanes = lanes;
<del> return fiber;
<del> } else {
<del> // Only implemented in persistent mode
<del> throw new Error('Not implemented.');
<del> }
<del>}
<del>
<ide> export function createFiberFromElement(
<ide> element: ReactElement,
<ide> mode: TypeOfMode,
<ide><path>packages/react-reconciler/src/ReactFiber.old.js
<ide> import type {RootTag} from './ReactRootTags';
<ide> import type {WorkTag} from './ReactWorkTags';
<ide> import type {TypeOfMode} from './ReactTypeOfMode';
<ide> import type {Lanes} from './ReactFiberLane.old';
<del>import type {SuspenseInstance, Props} from './ReactFiberHostConfig';
<add>import type {SuspenseInstance} from './ReactFiberHostConfig';
<ide> import type {
<ide> OffscreenProps,
<ide> OffscreenInstance,
<ide> import {
<ide> enableTransitionTracing,
<ide> enableDebugTracing,
<ide> } from 'shared/ReactFeatureFlags';
<del>import {
<del> supportsPersistence,
<del> getOffscreenContainerType,
<del>} from './ReactFiberHostConfig';
<ide> import {NoFlags, Placement, StaticMask} from './ReactFiberFlags';
<ide> import {ConcurrentRoot} from './ReactRootTags';
<ide> import {
<ide> export function createFiberFromTypeAndProps(
<ide> return fiber;
<ide> }
<ide>
<del>export function createOffscreenHostContainerFiber(
<del> props: Props,
<del> fiberMode: TypeOfMode,
<del> lanes: Lanes,
<del> key: null | string,
<del>): Fiber {
<del> if (supportsPersistence) {
<del> const type = getOffscreenContainerType();
<del> const fiber = createFiber(HostComponent, props, key, fiberMode);
<del> fiber.elementType = type;
<del> fiber.type = type;
<del> fiber.lanes = lanes;
<del> return fiber;
<del> } else {
<del> // Only implemented in persistent mode
<del> throw new Error('Not implemented.');
<del> }
<del>}
<del>
<ide> export function createFiberFromElement(
<ide> element: ReactElement,
<ide> mode: TypeOfMode,
<ide><path>packages/react-reconciler/src/ReactFiberBeginWork.new.js
<ide> import {
<ide> enableLazyContextPropagation,
<ide> enableSuspenseLayoutEffectSemantics,
<ide> enableSchedulingProfiler,
<del> enablePersistentOffscreenHostContainer,
<ide> enableTransitionTracing,
<ide> enableLegacyHidden,
<ide> } from 'shared/ReactFeatureFlags';
<ide> import {
<ide> registerSuspenseInstanceRetry,
<ide> supportsHydration,
<ide> isPrimaryRenderer,
<del> supportsPersistence,
<del> getOffscreenContainerProps,
<ide> } from './ReactFiberHostConfig';
<ide> import type {SuspenseInstance} from './ReactFiberHostConfig';
<ide> import {shouldError, shouldSuspend} from './ReactFiberReconciler';
<ide> import {
<ide> createFiberFromFragment,
<ide> createFiberFromOffscreen,
<ide> createWorkInProgress,
<del> createOffscreenHostContainerFiber,
<ide> isSimpleFunctionComponent,
<ide> } from './ReactFiber.new';
<ide> import {
<ide> import {setWorkInProgressVersion} from './ReactMutableSource.new';
<ide> import {pushCacheProvider, CacheContext} from './ReactFiberCacheComponent.new';
<ide> import {createCapturedValue} from './ReactCapturedValue';
<ide> import {createClassErrorUpdate} from './ReactFiberThrow.new';
<del>import {completeSuspendedOffscreenHostContainer} from './ReactFiberCompleteWork.new';
<ide> import is from 'shared/objectIs';
<ide> import {
<ide> getForksAtLevel,
<ide> function updateOffscreenComponent(
<ide> pushRenderLanes(workInProgress, subtreeRenderLanes);
<ide> }
<ide>
<del> if (enablePersistentOffscreenHostContainer && supportsPersistence) {
<del> // In persistent mode, the offscreen children are wrapped in a host node.
<del> // TODO: Optimize this to use the OffscreenComponent fiber instead of
<del> // an extra HostComponent fiber. Need to make sure this doesn't break Fabric
<del> // or some other infra that expects a HostComponent.
<del> const isHidden =
<del> nextProps.mode === 'hidden' &&
<del> (!enableLegacyHidden || workInProgress.tag !== LegacyHiddenComponent);
<del> const offscreenContainer = reconcileOffscreenHostContainer(
<del> current,
<del> workInProgress,
<del> isHidden,
<del> nextChildren,
<del> renderLanes,
<del> );
<del> return offscreenContainer;
<del> } else {
<del> reconcileChildren(current, workInProgress, nextChildren, renderLanes);
<del> return workInProgress.child;
<del> }
<del>}
<del>
<del>function reconcileOffscreenHostContainer(
<del> currentOffscreen: Fiber | null,
<del> offscreen: Fiber,
<del> isHidden: boolean,
<del> children: any,
<del> renderLanes: Lanes,
<del>) {
<del> const containerProps = getOffscreenContainerProps(
<del> isHidden ? 'hidden' : 'visible',
<del> children,
<del> );
<del> let hostContainer;
<del> if (currentOffscreen === null) {
<del> hostContainer = createOffscreenHostContainerFiber(
<del> containerProps,
<del> offscreen.mode,
<del> renderLanes,
<del> null,
<del> );
<del> } else {
<del> const currentHostContainer = currentOffscreen.child;
<del> if (currentHostContainer === null) {
<del> hostContainer = createOffscreenHostContainerFiber(
<del> containerProps,
<del> offscreen.mode,
<del> renderLanes,
<del> null,
<del> );
<del> hostContainer.flags |= Placement;
<del> } else {
<del> hostContainer = createWorkInProgress(
<del> currentHostContainer,
<del> containerProps,
<del> );
<del> }
<del> }
<del> hostContainer.return = offscreen;
<del> offscreen.child = hostContainer;
<del> return hostContainer;
<add> reconcileChildren(current, workInProgress, nextChildren, renderLanes);
<add> return workInProgress.child;
<ide> }
<ide>
<ide> // Note: These happen to have identical begin phases, for now. We shouldn't hold
<ide> function updateSuspenseFallbackChildren(
<ide> currentPrimaryChildFragment.treeBaseDuration;
<ide> }
<ide>
<del> if (enablePersistentOffscreenHostContainer && supportsPersistence) {
<del> // In persistent mode, the offscreen children are wrapped in a host node.
<del> // We need to complete it now, because we're going to skip over its normal
<del> // complete phase and go straight to rendering the fallback.
<del> const currentOffscreenContainer = currentPrimaryChildFragment.child;
<del> const offscreenContainer: Fiber = (primaryChildFragment.child: any);
<del> const containerProps = getOffscreenContainerProps(
<del> 'hidden',
<del> primaryChildren,
<del> );
<del> offscreenContainer.pendingProps = containerProps;
<del> offscreenContainer.memoizedProps = containerProps;
<del> completeSuspendedOffscreenHostContainer(
<del> currentOffscreenContainer,
<del> offscreenContainer,
<del> );
<del> }
<del>
<ide> // The fallback fiber was added as a deletion during the first pass.
<ide> // However, since we're going to remain on the fallback, we no longer want
<ide> // to delete it.
<ide> function updateSuspenseFallbackChildren(
<ide> currentPrimaryChildFragment,
<ide> primaryChildProps,
<ide> );
<del>
<del> if (enablePersistentOffscreenHostContainer && supportsPersistence) {
<del> // In persistent mode, the offscreen children are wrapped in a host node.
<del> // We need to complete it now, because we're going to skip over its normal
<del> // complete phase and go straight to rendering the fallback.
<del> const currentOffscreenContainer = currentPrimaryChildFragment.child;
<del> if (currentOffscreenContainer !== null) {
<del> const isHidden = true;
<del> const offscreenContainer = reconcileOffscreenHostContainer(
<del> currentPrimaryChildFragment,
<del> primaryChildFragment,
<del> isHidden,
<del> primaryChildren,
<del> renderLanes,
<del> );
<del> offscreenContainer.memoizedProps = offscreenContainer.pendingProps;
<del> completeSuspendedOffscreenHostContainer(
<del> currentOffscreenContainer,
<del> offscreenContainer,
<del> );
<del> }
<del> }
<del>
<ide> // Since we're reusing a current tree, we need to reuse the flags, too.
<ide> // (We don't do this in legacy mode, because in legacy mode we don't re-use
<ide> // the current tree; see previous branch.)
<ide><path>packages/react-reconciler/src/ReactFiberBeginWork.old.js
<ide> import {
<ide> enableLazyContextPropagation,
<ide> enableSuspenseLayoutEffectSemantics,
<ide> enableSchedulingProfiler,
<del> enablePersistentOffscreenHostContainer,
<ide> enableTransitionTracing,
<ide> enableLegacyHidden,
<ide> } from 'shared/ReactFeatureFlags';
<ide> import {
<ide> registerSuspenseInstanceRetry,
<ide> supportsHydration,
<ide> isPrimaryRenderer,
<del> supportsPersistence,
<del> getOffscreenContainerProps,
<ide> } from './ReactFiberHostConfig';
<ide> import type {SuspenseInstance} from './ReactFiberHostConfig';
<ide> import {shouldError, shouldSuspend} from './ReactFiberReconciler';
<ide> import {
<ide> createFiberFromFragment,
<ide> createFiberFromOffscreen,
<ide> createWorkInProgress,
<del> createOffscreenHostContainerFiber,
<ide> isSimpleFunctionComponent,
<ide> } from './ReactFiber.old';
<ide> import {
<ide> import {setWorkInProgressVersion} from './ReactMutableSource.old';
<ide> import {pushCacheProvider, CacheContext} from './ReactFiberCacheComponent.old';
<ide> import {createCapturedValue} from './ReactCapturedValue';
<ide> import {createClassErrorUpdate} from './ReactFiberThrow.old';
<del>import {completeSuspendedOffscreenHostContainer} from './ReactFiberCompleteWork.old';
<ide> import is from 'shared/objectIs';
<ide> import {
<ide> getForksAtLevel,
<ide> function updateOffscreenComponent(
<ide> pushRenderLanes(workInProgress, subtreeRenderLanes);
<ide> }
<ide>
<del> if (enablePersistentOffscreenHostContainer && supportsPersistence) {
<del> // In persistent mode, the offscreen children are wrapped in a host node.
<del> // TODO: Optimize this to use the OffscreenComponent fiber instead of
<del> // an extra HostComponent fiber. Need to make sure this doesn't break Fabric
<del> // or some other infra that expects a HostComponent.
<del> const isHidden =
<del> nextProps.mode === 'hidden' &&
<del> (!enableLegacyHidden || workInProgress.tag !== LegacyHiddenComponent);
<del> const offscreenContainer = reconcileOffscreenHostContainer(
<del> current,
<del> workInProgress,
<del> isHidden,
<del> nextChildren,
<del> renderLanes,
<del> );
<del> return offscreenContainer;
<del> } else {
<del> reconcileChildren(current, workInProgress, nextChildren, renderLanes);
<del> return workInProgress.child;
<del> }
<del>}
<del>
<del>function reconcileOffscreenHostContainer(
<del> currentOffscreen: Fiber | null,
<del> offscreen: Fiber,
<del> isHidden: boolean,
<del> children: any,
<del> renderLanes: Lanes,
<del>) {
<del> const containerProps = getOffscreenContainerProps(
<del> isHidden ? 'hidden' : 'visible',
<del> children,
<del> );
<del> let hostContainer;
<del> if (currentOffscreen === null) {
<del> hostContainer = createOffscreenHostContainerFiber(
<del> containerProps,
<del> offscreen.mode,
<del> renderLanes,
<del> null,
<del> );
<del> } else {
<del> const currentHostContainer = currentOffscreen.child;
<del> if (currentHostContainer === null) {
<del> hostContainer = createOffscreenHostContainerFiber(
<del> containerProps,
<del> offscreen.mode,
<del> renderLanes,
<del> null,
<del> );
<del> hostContainer.flags |= Placement;
<del> } else {
<del> hostContainer = createWorkInProgress(
<del> currentHostContainer,
<del> containerProps,
<del> );
<del> }
<del> }
<del> hostContainer.return = offscreen;
<del> offscreen.child = hostContainer;
<del> return hostContainer;
<add> reconcileChildren(current, workInProgress, nextChildren, renderLanes);
<add> return workInProgress.child;
<ide> }
<ide>
<ide> // Note: These happen to have identical begin phases, for now. We shouldn't hold
<ide> function updateSuspenseFallbackChildren(
<ide> currentPrimaryChildFragment.treeBaseDuration;
<ide> }
<ide>
<del> if (enablePersistentOffscreenHostContainer && supportsPersistence) {
<del> // In persistent mode, the offscreen children are wrapped in a host node.
<del> // We need to complete it now, because we're going to skip over its normal
<del> // complete phase and go straight to rendering the fallback.
<del> const currentOffscreenContainer = currentPrimaryChildFragment.child;
<del> const offscreenContainer: Fiber = (primaryChildFragment.child: any);
<del> const containerProps = getOffscreenContainerProps(
<del> 'hidden',
<del> primaryChildren,
<del> );
<del> offscreenContainer.pendingProps = containerProps;
<del> offscreenContainer.memoizedProps = containerProps;
<del> completeSuspendedOffscreenHostContainer(
<del> currentOffscreenContainer,
<del> offscreenContainer,
<del> );
<del> }
<del>
<ide> // The fallback fiber was added as a deletion during the first pass.
<ide> // However, since we're going to remain on the fallback, we no longer want
<ide> // to delete it.
<ide> function updateSuspenseFallbackChildren(
<ide> currentPrimaryChildFragment,
<ide> primaryChildProps,
<ide> );
<del>
<del> if (enablePersistentOffscreenHostContainer && supportsPersistence) {
<del> // In persistent mode, the offscreen children are wrapped in a host node.
<del> // We need to complete it now, because we're going to skip over its normal
<del> // complete phase and go straight to rendering the fallback.
<del> const currentOffscreenContainer = currentPrimaryChildFragment.child;
<del> if (currentOffscreenContainer !== null) {
<del> const isHidden = true;
<del> const offscreenContainer = reconcileOffscreenHostContainer(
<del> currentPrimaryChildFragment,
<del> primaryChildFragment,
<del> isHidden,
<del> primaryChildren,
<del> renderLanes,
<del> );
<del> offscreenContainer.memoizedProps = offscreenContainer.pendingProps;
<del> completeSuspendedOffscreenHostContainer(
<del> currentOffscreenContainer,
<del> offscreenContainer,
<del> );
<del> }
<del> }
<del>
<ide> // Since we're reusing a current tree, we need to reuse the flags, too.
<ide> // (We don't do this in legacy mode, because in legacy mode we don't re-use
<ide> // the current tree; see previous branch.)
<ide><path>packages/react-reconciler/src/ReactFiberCompleteWork.new.js
<ide> import {
<ide> enableProfilerTimer,
<ide> enableCache,
<ide> enableSuspenseLayoutEffectSemantics,
<del> enablePersistentOffscreenHostContainer,
<ide> enableTransitionTracing,
<ide> } from 'shared/ReactFeatureFlags';
<ide> import {
<ide> if (supportsMutation) {
<ide> if (child !== null) {
<ide> child.return = node;
<ide> }
<del> if (enablePersistentOffscreenHostContainer) {
<del> appendAllChildren(parent, node, false, false);
<del> } else {
<del> appendAllChildren(parent, node, true, true);
<del> }
<add> appendAllChildren(parent, node, true, true);
<ide> } else if (node.child !== null) {
<ide> node.child.return = node;
<ide> node = node.child;
<ide> if (supportsMutation) {
<ide> if (child !== null) {
<ide> child.return = node;
<ide> }
<del> if (enablePersistentOffscreenHostContainer) {
<del> appendAllChildrenToContainer(containerChildSet, node, false, false);
<del> } else {
<del> appendAllChildrenToContainer(containerChildSet, node, true, true);
<del> }
<add> appendAllChildrenToContainer(containerChildSet, node, true, true);
<ide> } else if (node.child !== null) {
<ide> node.child.return = node;
<ide> node = node.child;
<ide> function bubbleProperties(completedWork: Fiber) {
<ide> return didBailout;
<ide> }
<ide>
<del>export function completeSuspendedOffscreenHostContainer(
<del> current: Fiber | null,
<del> workInProgress: Fiber,
<del>) {
<del> // This is a fork of the complete phase for HostComponent. We use it when
<del> // a suspense tree is in its fallback state, because in that case the primary
<del> // tree that includes the offscreen boundary is skipped over without a
<del> // regular complete phase.
<del> //
<del> // We can optimize this path further by inlining the update logic for
<del> // offscreen instances specifically, i.e. skipping the `prepareUpdate` call.
<del> const rootContainerInstance = getRootHostContainer();
<del> const type = workInProgress.type;
<del> const newProps = workInProgress.memoizedProps;
<del> if (current !== null) {
<del> updateHostComponent(
<del> current,
<del> workInProgress,
<del> type,
<del> newProps,
<del> rootContainerInstance,
<del> );
<del> } else {
<del> const currentHostContext = getHostContext();
<del> const instance = createInstance(
<del> type,
<del> newProps,
<del> rootContainerInstance,
<del> currentHostContext,
<del> workInProgress,
<del> );
<del>
<del> appendAllChildren(instance, workInProgress, false, false);
<del>
<del> workInProgress.stateNode = instance;
<del>
<del> // Certain renderers require commit-time effects for initial mount.
<del> // (eg DOM renderer supports auto-focus for certain elements).
<del> // Make sure such renderers get scheduled for later work.
<del> if (
<del> finalizeInitialChildren(
<del> instance,
<del> type,
<del> newProps,
<del> rootContainerInstance,
<del> currentHostContext,
<del> )
<del> ) {
<del> markUpdate(workInProgress);
<del> }
<del>
<del> if (workInProgress.ref !== null) {
<del> // If there is a ref on a host node we need to schedule a callback
<del> markRef(workInProgress);
<del> }
<del> }
<del> bubbleProperties(workInProgress);
<del>}
<del>
<ide> function completeWork(
<ide> current: Fiber | null,
<ide> workInProgress: Fiber,
<ide><path>packages/react-reconciler/src/ReactFiberCompleteWork.old.js
<ide> import {
<ide> enableProfilerTimer,
<ide> enableCache,
<ide> enableSuspenseLayoutEffectSemantics,
<del> enablePersistentOffscreenHostContainer,
<ide> enableTransitionTracing,
<ide> } from 'shared/ReactFeatureFlags';
<ide> import {
<ide> if (supportsMutation) {
<ide> if (child !== null) {
<ide> child.return = node;
<ide> }
<del> if (enablePersistentOffscreenHostContainer) {
<del> appendAllChildren(parent, node, false, false);
<del> } else {
<del> appendAllChildren(parent, node, true, true);
<del> }
<add> appendAllChildren(parent, node, true, true);
<ide> } else if (node.child !== null) {
<ide> node.child.return = node;
<ide> node = node.child;
<ide> if (supportsMutation) {
<ide> if (child !== null) {
<ide> child.return = node;
<ide> }
<del> if (enablePersistentOffscreenHostContainer) {
<del> appendAllChildrenToContainer(containerChildSet, node, false, false);
<del> } else {
<del> appendAllChildrenToContainer(containerChildSet, node, true, true);
<del> }
<add> appendAllChildrenToContainer(containerChildSet, node, true, true);
<ide> } else if (node.child !== null) {
<ide> node.child.return = node;
<ide> node = node.child;
<ide> function bubbleProperties(completedWork: Fiber) {
<ide> return didBailout;
<ide> }
<ide>
<del>export function completeSuspendedOffscreenHostContainer(
<del> current: Fiber | null,
<del> workInProgress: Fiber,
<del>) {
<del> // This is a fork of the complete phase for HostComponent. We use it when
<del> // a suspense tree is in its fallback state, because in that case the primary
<del> // tree that includes the offscreen boundary is skipped over without a
<del> // regular complete phase.
<del> //
<del> // We can optimize this path further by inlining the update logic for
<del> // offscreen instances specifically, i.e. skipping the `prepareUpdate` call.
<del> const rootContainerInstance = getRootHostContainer();
<del> const type = workInProgress.type;
<del> const newProps = workInProgress.memoizedProps;
<del> if (current !== null) {
<del> updateHostComponent(
<del> current,
<del> workInProgress,
<del> type,
<del> newProps,
<del> rootContainerInstance,
<del> );
<del> } else {
<del> const currentHostContext = getHostContext();
<del> const instance = createInstance(
<del> type,
<del> newProps,
<del> rootContainerInstance,
<del> currentHostContext,
<del> workInProgress,
<del> );
<del>
<del> appendAllChildren(instance, workInProgress, false, false);
<del>
<del> workInProgress.stateNode = instance;
<del>
<del> // Certain renderers require commit-time effects for initial mount.
<del> // (eg DOM renderer supports auto-focus for certain elements).
<del> // Make sure such renderers get scheduled for later work.
<del> if (
<del> finalizeInitialChildren(
<del> instance,
<del> type,
<del> newProps,
<del> rootContainerInstance,
<del> currentHostContext,
<del> )
<del> ) {
<del> markUpdate(workInProgress);
<del> }
<del>
<del> if (workInProgress.ref !== null) {
<del> // If there is a ref on a host node we need to schedule a callback
<del> markRef(workInProgress);
<del> }
<del> }
<del> bubbleProperties(workInProgress);
<del>}
<del>
<ide> function completeWork(
<ide> current: Fiber | null,
<ide> workInProgress: Fiber,
<ide><path>packages/react-reconciler/src/ReactFiberHostConfigWithNoPersistence.js
<ide> export const createContainerChildSet = shim;
<ide> export const appendChildToContainerChildSet = shim;
<ide> export const finalizeContainerChildren = shim;
<ide> export const replaceContainerChildren = shim;
<del>export const getOffscreenContainerType = shim;
<del>export const getOffscreenContainerProps = shim;
<ide> export const cloneHiddenInstance = shim;
<ide> export const cloneHiddenTextInstance = shim;
<ide><path>packages/react-reconciler/src/ReactFiberThrow.new.js
<ide> import {
<ide> ForceUpdateForLegacySuspense,
<ide> ForceClientRender,
<ide> } from './ReactFiberFlags';
<del>import {
<del> supportsPersistence,
<del> getOffscreenContainerProps,
<del>} from './ReactFiberHostConfig';
<ide> import {shouldCaptureSuspense} from './ReactFiberSuspenseComponent.new';
<ide> import {NoMode, ConcurrentMode, DebugTracingMode} from './ReactTypeOfMode';
<ide> import {
<ide> enableDebugTracing,
<ide> enableLazyContextPropagation,
<ide> enableUpdaterTracking,
<del> enablePersistentOffscreenHostContainer,
<ide> } from 'shared/ReactFeatureFlags';
<ide> import {createCapturedValue} from './ReactCapturedValue';
<ide> import {
<ide> function markSuspenseBoundaryShouldCapture(
<ide> // all lifecycle effect tags.
<ide> sourceFiber.flags &= ~(LifecycleEffectMask | Incomplete);
<ide>
<del> if (supportsPersistence && enablePersistentOffscreenHostContainer) {
<del> // Another legacy Suspense quirk. In persistent mode, if this is the
<del> // initial mount, override the props of the host container to hide
<del> // its contents.
<del> const currentSuspenseBoundary = suspenseBoundary.alternate;
<del> if (currentSuspenseBoundary === null) {
<del> const offscreenFiber: Fiber = (suspenseBoundary.child: any);
<del> const offscreenContainer = offscreenFiber.child;
<del> if (offscreenContainer !== null) {
<del> const children = offscreenContainer.memoizedProps.children;
<del> const containerProps = getOffscreenContainerProps(
<del> 'hidden',
<del> children,
<del> );
<del> offscreenContainer.pendingProps = containerProps;
<del> offscreenContainer.memoizedProps = containerProps;
<del> }
<del> }
<del> }
<del>
<ide> if (sourceFiber.tag === ClassComponent) {
<ide> const currentSourceFiber = sourceFiber.alternate;
<ide> if (currentSourceFiber === null) {
<ide><path>packages/react-reconciler/src/ReactFiberThrow.old.js
<ide> import {
<ide> ForceUpdateForLegacySuspense,
<ide> ForceClientRender,
<ide> } from './ReactFiberFlags';
<del>import {
<del> supportsPersistence,
<del> getOffscreenContainerProps,
<del>} from './ReactFiberHostConfig';
<ide> import {shouldCaptureSuspense} from './ReactFiberSuspenseComponent.old';
<ide> import {NoMode, ConcurrentMode, DebugTracingMode} from './ReactTypeOfMode';
<ide> import {
<ide> enableDebugTracing,
<ide> enableLazyContextPropagation,
<ide> enableUpdaterTracking,
<del> enablePersistentOffscreenHostContainer,
<ide> } from 'shared/ReactFeatureFlags';
<ide> import {createCapturedValue} from './ReactCapturedValue';
<ide> import {
<ide> function markSuspenseBoundaryShouldCapture(
<ide> // all lifecycle effect tags.
<ide> sourceFiber.flags &= ~(LifecycleEffectMask | Incomplete);
<ide>
<del> if (supportsPersistence && enablePersistentOffscreenHostContainer) {
<del> // Another legacy Suspense quirk. In persistent mode, if this is the
<del> // initial mount, override the props of the host container to hide
<del> // its contents.
<del> const currentSuspenseBoundary = suspenseBoundary.alternate;
<del> if (currentSuspenseBoundary === null) {
<del> const offscreenFiber: Fiber = (suspenseBoundary.child: any);
<del> const offscreenContainer = offscreenFiber.child;
<del> if (offscreenContainer !== null) {
<del> const children = offscreenContainer.memoizedProps.children;
<del> const containerProps = getOffscreenContainerProps(
<del> 'hidden',
<del> children,
<del> );
<del> offscreenContainer.pendingProps = containerProps;
<del> offscreenContainer.memoizedProps = containerProps;
<del> }
<del> }
<del> }
<del>
<ide> if (sourceFiber.tag === ClassComponent) {
<ide> const currentSourceFiber = sourceFiber.alternate;
<ide> if (currentSourceFiber === null) {
<ide><path>packages/react-reconciler/src/forks/ReactFiberHostConfig.custom.js
<ide> export const appendChildToContainerChildSet =
<ide> export const finalizeContainerChildren =
<ide> $$$hostConfig.finalizeContainerChildren;
<ide> export const replaceContainerChildren = $$$hostConfig.replaceContainerChildren;
<del>export const getOffscreenContainerType =
<del> $$$hostConfig.getOffscreenContainerType;
<del>export const getOffscreenContainerProps =
<del> $$$hostConfig.getOffscreenContainerProps;
<ide> export const cloneHiddenInstance = $$$hostConfig.cloneHiddenInstance;
<ide> export const cloneHiddenTextInstance = $$$hostConfig.cloneHiddenTextInstance;
<ide>
<ide><path>packages/shared/ReactFeatureFlags.js
<ide> export const warnAboutDeprecatedLifecycles = true;
<ide> export const enableComponentStackLocations = true;
<ide> export const disableSchedulerTimeoutBasedOnReactExpirationTime = false;
<del>export const enablePersistentOffscreenHostContainer = false;
<ide>
<ide> // -----------------------------------------------------------------------------
<ide> // Land or remove (moderate effort)
<ide><path>packages/shared/forks/ReactFeatureFlags.native-fb-dynamic.js
<ide> * @flow strict
<ide> */
<ide>
<del>import typeof * as ExportsType from './ReactFeatureFlags.native-fb-dynamic';
<del>import typeof * as DynamicFlagsType from 'ReactNativeInternalFeatureFlags';
<add>// NOTE: There are no flags, currently. Uncomment the stuff below if we add one.
<add>
<add>// import typeof * as ExportsType from './ReactFeatureFlags.native-fb-dynamic';
<add>// import typeof * as DynamicFlagsType from 'ReactNativeInternalFeatureFlags';
<ide>
<ide> // In xplat, these flags are controlled by GKs. Because most GKs have some
<ide> // population running in either mode, we should run our tests that way, too,
<ide> import typeof * as DynamicFlagsType from 'ReactNativeInternalFeatureFlags';
<ide> // flag here but it won't be set to `true` in any of our test runs. Need to
<ide> // update the test configuration.
<ide>
<del>export const enablePersistentOffscreenHostContainer = __VARIANT__;
<del>
<del>// Flow magic to verify the exports of this file match the original version.
<del>// eslint-disable-next-line no-unused-vars
<del>type Check<_X, Y: _X, X: Y = _X> = null;
<del>// eslint-disable-next-line no-unused-expressions
<del>(null: Check<ExportsType, DynamicFlagsType>);
<add>// // Flow magic to verify the exports of this file match the original version.
<add>// // eslint-disable-next-line no-unused-vars
<add>// type Check<_X, Y: _X, X: Y = _X> = null;
<add>// // eslint-disable-next-line no-unused-expressions
<add>// (null: Check<ExportsType, DynamicFlagsType>);
<ide><path>packages/shared/forks/ReactFeatureFlags.native-fb.js
<ide> import typeof * as FeatureFlagsType from 'shared/ReactFeatureFlags';
<ide> import typeof * as ExportsType from './ReactFeatureFlags.native-fb';
<ide>
<add>// NOTE: There are no flags, currently. Uncomment the stuff below if we add one.
<ide> // Re-export dynamic flags from the internal module. Intentionally using *
<ide> // because this import is compiled to a `require` call.
<del>import * as dynamicFlags from 'ReactNativeInternalFeatureFlags';
<add>// import * as dynamicFlags from 'ReactNativeInternalFeatureFlags';
<ide>
<ide> // We destructure each value before re-exporting to avoid a dynamic look-up on
<ide> // the exports object every time a flag is read.
<del>export const {enablePersistentOffscreenHostContainer} = dynamicFlags;
<add>// export const {} = dynamicFlags;
<ide>
<ide> // The rest of the flags are static for better dead code elimination.
<ide> export const enableDebugTracing = false;
<ide><path>packages/shared/forks/ReactFeatureFlags.native-oss.js
<ide> export const enableLazyContextPropagation = false;
<ide> export const enableLegacyHidden = false;
<ide> export const enableSyncDefaultUpdates = true;
<ide> export const allowConcurrentByDefault = false;
<del>export const enablePersistentOffscreenHostContainer = false;
<ide> export const enableCustomElementPropertySupport = false;
<ide>
<ide> export const consoleManagedByDevToolsDuringStrictMode = false;
<ide><path>packages/shared/forks/ReactFeatureFlags.test-renderer.js
<ide> export const enableLazyContextPropagation = false;
<ide> export const enableLegacyHidden = false;
<ide> export const enableSyncDefaultUpdates = true;
<ide> export const allowConcurrentByDefault = false;
<del>export const enablePersistentOffscreenHostContainer = false;
<ide> export const enableCustomElementPropertySupport = false;
<ide>
<ide> export const consoleManagedByDevToolsDuringStrictMode = false;
<ide><path>packages/shared/forks/ReactFeatureFlags.test-renderer.native.js
<ide> export const enableLazyContextPropagation = false;
<ide> export const enableLegacyHidden = false;
<ide> export const enableSyncDefaultUpdates = true;
<ide> export const allowConcurrentByDefault = true;
<del>export const enablePersistentOffscreenHostContainer = false;
<ide>
<ide> export const consoleManagedByDevToolsDuringStrictMode = false;
<ide> export const enableServerContext = false;
<ide><path>packages/shared/forks/ReactFeatureFlags.test-renderer.www.js
<ide> export const enableLazyContextPropagation = false;
<ide> export const enableLegacyHidden = false;
<ide> export const enableSyncDefaultUpdates = true;
<ide> export const allowConcurrentByDefault = true;
<del>export const enablePersistentOffscreenHostContainer = false;
<ide> export const enableCustomElementPropertySupport = false;
<ide>
<ide> export const consoleManagedByDevToolsDuringStrictMode = false;
<ide><path>packages/shared/forks/ReactFeatureFlags.testing.js
<ide> export const enableLazyContextPropagation = false;
<ide> export const enableLegacyHidden = false;
<ide> export const enableSyncDefaultUpdates = true;
<ide> export const allowConcurrentByDefault = false;
<del>export const enablePersistentOffscreenHostContainer = false;
<ide> export const enableCustomElementPropertySupport = false;
<ide>
<ide> export const consoleManagedByDevToolsDuringStrictMode = false;
<ide><path>packages/shared/forks/ReactFeatureFlags.testing.www.js
<ide> export const enableLazyContextPropagation = false;
<ide> export const enableLegacyHidden = false;
<ide> export const enableSyncDefaultUpdates = true;
<ide> export const allowConcurrentByDefault = true;
<del>export const enablePersistentOffscreenHostContainer = false;
<ide> export const enableCustomElementPropertySupport = false;
<ide>
<ide> export const consoleManagedByDevToolsDuringStrictMode = false;
<ide><path>packages/shared/forks/ReactFeatureFlags.www-dynamic.js
<ide> export const disableNativeComponentFrames = false;
<ide> export const createRootStrictEffectsByDefault = false;
<ide> export const enableStrictEffects = false;
<ide> export const allowConcurrentByDefault = true;
<del>export const enablePersistentOffscreenHostContainer = false;
<ide> // You probably *don't* want to add more hardcoded ones.
<ide> // Instead, try to add them above with the __VARIANT__ value.
<ide><path>packages/shared/forks/ReactFeatureFlags.www.js
<ide> export const allowConcurrentByDefault = true;
<ide>
<ide> export const deletedTreeCleanUpLevel = 3;
<ide>
<del>export const enablePersistentOffscreenHostContainer = false;
<del>
<ide> export const consoleManagedByDevToolsDuringStrictMode = true;
<ide> export const enableServerContext = true;
<ide>
<ide><path>scripts/flow/xplat.js
<ide> */
<ide>
<ide> declare module 'ReactNativeInternalFeatureFlags' {
<del> declare export var enablePersistentOffscreenHostContainer: boolean;
<ide> } | 24 |
Python | Python | write tensorboard histograms with tensor names | 7ae36d132ab20c6ce7853f89259411458d10227e | <ide><path>keras/callbacks.py
<ide> def _set_model(self, model):
<ide> layers = self.model.layers
<ide> for layer in layers:
<ide> if hasattr(layer, 'W'):
<del> tf.histogram_summary('{}_W'.format(layer), layer.W)
<add> tf.histogram_summary('{}_W'.format(layer.name), layer.W)
<ide> if hasattr(layer, 'b'):
<del> tf.histogram_summary('{}_b'.format(layer), layer.b)
<add> tf.histogram_summary('{}_b'.format(layer.name), layer.b)
<ide> if hasattr(layer, 'output'):
<del> tf.histogram_summary('{}_out'.format(layer),
<add> tf.histogram_summary('{}_out'.format(layer.name),
<ide> layer.output)
<ide> self.merged = tf.merge_all_summaries()
<ide> if self.write_graph: | 1 |
PHP | PHP | update all @deprecated annotations | 67ba9cb40623deeddf6326c9ccff09afc27be447 | <ide><path>lib/Cake/Cache/Engine/MemcacheEngine.php
<ide> * more information.
<ide> *
<ide> * @package Cake.Cache.Engine
<del> * @deprecated You should use the Memcached adapter instead.
<add> * @deprecated 3.0.0 You should use the Memcached adapter instead.
<ide> */
<ide> class MemcacheEngine extends CacheEngine {
<ide>
<ide><path>lib/Cake/Console/Command/ConsoleShell.php
<ide> * Provides a very basic 'interactive' console for CakePHP apps.
<ide> *
<ide> * @package Cake.Console.Command
<del> * @deprecated Deprecated since version 2.4, will be removed in 3.0
<add> * @deprecated 3.0.0 Deprecated since version 2.4, will be removed in 3.0
<ide> */
<ide> class ConsoleShell extends AppShell {
<ide>
<ide><path>lib/Cake/Controller/Component/AclComponent.php
<ide> public function inherit($aro, $aco, $action = "*") {
<ide> * @param array|string|Model $aco ACO The controlled object identifier. See `AclNode::node()` for possible formats
<ide> * @param string $action Action (defaults to *)
<ide> * @return bool Success
<del> * @deprecated Will be removed in 3.0.
<add> * @deprecated 3.0.0 Will be removed in 3.0.
<ide> */
<ide> public function grant($aro, $aco, $action = "*") {
<ide> trigger_error(__d('cake_dev', '%s is deprecated, use %s instead', 'AclComponent::grant()', 'allow()'), E_USER_WARNING);
<ide> public function grant($aro, $aco, $action = "*") {
<ide> * @param array|string|Model $aco ACO The controlled object identifier. See `AclNode::node()` for possible formats
<ide> * @param string $action Action (defaults to *)
<ide> * @return bool Success
<del> * @deprecated Will be removed in 3.0.
<add> * @deprecated 3.0.0 Will be removed in 3.0.
<ide> */
<ide> public function revoke($aro, $aco, $action = "*") {
<ide> trigger_error(__d('cake_dev', '%s is deprecated, use %s instead', 'AclComponent::revoke()', 'deny()'), E_USER_WARNING);
<ide><path>lib/Cake/Controller/Component/Auth/BaseAuthenticate.php
<ide> public function passwordHasher() {
<ide> *
<ide> * @param string $password The plain text password.
<ide> * @return string The hashed form of the password.
<del> * @deprecated Since 2.4. Use a PasswordHasher class instead.
<add> * @deprecated 3.0.0 Since 2.4. Use a PasswordHasher class instead.
<ide> */
<ide> protected function _password($password) {
<ide> return Security::hash($password, null, true);
<ide><path>lib/Cake/Controller/Component/Auth/BlowfishAuthenticate.php
<ide> * @package Cake.Controller.Component.Auth
<ide> * @since CakePHP(tm) v 2.3
<ide> * @see AuthComponent::$authenticate
<del> * @deprecated Since 2.4. Just use FormAuthenticate with 'passwordHasher' setting set to 'Blowfish'
<add> * @deprecated 3.0.0 Since 2.4. Just use FormAuthenticate with 'passwordHasher' setting set to 'Blowfish'
<ide> */
<ide> class BlowfishAuthenticate extends FormAuthenticate {
<ide>
<ide><path>lib/Cake/Controller/Component/AuthComponent.php
<ide> protected function _getUser() {
<ide> *
<ide> * @param string|array $url Optional URL to write as the login redirect URL.
<ide> * @return string Redirect URL
<del> * @deprecated 2.3 Use AuthComponent::redirectUrl() instead
<add> * @deprecated 3.0.0 Since 2.3.0, use AuthComponent::redirectUrl() instead
<ide> */
<ide> public function redirect($url = null) {
<ide> return $this->redirectUrl($url);
<ide> public function constructAuthenticate() {
<ide> *
<ide> * @param string $password Password to hash
<ide> * @return string Hashed password
<del> * @deprecated Since 2.4. Use Security::hash() directly or a password hasher object.
<add> * @deprecated 3.0.0 Since 2.4. Use Security::hash() directly or a password hasher object.
<ide> */
<ide> public static function password($password) {
<ide> return Security::hash($password, null, true);
<ide> public static function password($password) {
<ide> * Check whether or not the current user has data in the session, and is considered logged in.
<ide> *
<ide> * @return bool true if the user is logged in, false otherwise
<del> * @deprecated Since 2.5. Use AuthComponent::user() directly.
<add> * @deprecated 3.0.0 Since 2.5. Use AuthComponent::user() directly.
<ide> */
<ide> public function loggedIn() {
<ide> return (bool)$this->user();
<ide><path>lib/Cake/Controller/Component/EmailComponent.php
<ide> * @package Cake.Controller.Component
<ide> * @link http://book.cakephp.org/2.0/en/core-libraries/components/email.html
<ide> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/email.html
<del> * @deprecated Will be removed in 3.0. Use Network/CakeEmail instead
<add> * @deprecated 3.0.0 Will be removed in 3.0. Use Network/CakeEmail instead
<ide> */
<ide> class EmailComponent extends Component {
<ide>
<ide><path>lib/Cake/Controller/Component/RequestHandlerComponent.php
<ide> public function beforeRender(Controller $controller) {
<ide> * Returns true if the current HTTP request is Ajax, false otherwise
<ide> *
<ide> * @return bool True if call is Ajax
<del> * @deprecated use `$this->request->is('ajax')` instead.
<add> * @deprecated 3.0.0 Use `$this->request->is('ajax')` instead.
<ide> */
<ide> public function isAjax() {
<ide> return $this->request->is('ajax');
<ide> public function isAjax() {
<ide> * Returns true if the current HTTP request is coming from a Flash-based client
<ide> *
<ide> * @return bool True if call is from Flash
<del> * @deprecated use `$this->request->is('flash')` instead.
<add> * @deprecated 3.0.0 Use `$this->request->is('flash')` instead.
<ide> */
<ide> public function isFlash() {
<ide> return $this->request->is('flash');
<ide> public function isFlash() {
<ide> * Returns true if the current request is over HTTPS, false otherwise.
<ide> *
<ide> * @return bool True if call is over HTTPS
<del> * @deprecated use `$this->request->is('ssl')` instead.
<add> * @deprecated 3.0.0 Use `$this->request->is('ssl')` instead.
<ide> */
<ide> public function isSSL() {
<ide> return $this->request->is('ssl');
<ide> public function isWap() {
<ide> * Returns true if the current call a POST request
<ide> *
<ide> * @return bool True if call is a POST
<del> * @deprecated Use $this->request->is('post'); from your controller.
<add> * @deprecated 3.0.0 Use $this->request->is('post'); from your controller.
<ide> */
<ide> public function isPost() {
<ide> return $this->request->is('post');
<ide> public function isPost() {
<ide> * Returns true if the current call a PUT request
<ide> *
<ide> * @return bool True if call is a PUT
<del> * @deprecated Use $this->request->is('put'); from your controller.
<add> * @deprecated 3.0.0 Use $this->request->is('put'); from your controller.
<ide> */
<ide> public function isPut() {
<ide> return $this->request->is('put');
<ide> public function isPut() {
<ide> * Returns true if the current call a GET request
<ide> *
<ide> * @return bool True if call is a GET
<del> * @deprecated Use $this->request->is('get'); from your controller.
<add> * @deprecated 3.0.0 Use $this->request->is('get'); from your controller.
<ide> */
<ide> public function isGet() {
<ide> return $this->request->is('get');
<ide> public function isGet() {
<ide> * Returns true if the current call a DELETE request
<ide> *
<ide> * @return bool True if call is a DELETE
<del> * @deprecated Use $this->request->is('delete'); from your controller.
<add> * @deprecated 3.0.0 Use $this->request->is('delete'); from your controller.
<ide> */
<ide> public function isDelete() {
<ide> return $this->request->is('delete');
<ide> public function getAjaxVersion() {
<ide> * @param string|array $type The Content-type or array of Content-types assigned to the name,
<ide> * i.e. "text/html", or "application/xml"
<ide> * @return void
<del> * @deprecated use `$this->response->type()` instead.
<add> * @deprecated 3.0.0 Use `$this->response->type()` instead.
<ide> */
<ide> public function setContent($name, $type = null) {
<ide> $this->response->type(array($name => $type));
<ide> public function setContent($name, $type = null) {
<ide> * Gets the server name from which this request was referred
<ide> *
<ide> * @return string Server address
<del> * @deprecated use $this->request->referer() from your controller instead
<add> * @deprecated 3.0.0 Use $this->request->referer() from your controller instead
<ide> */
<ide> public function getReferer() {
<ide> return $this->request->referer(false);
<ide> public function getReferer() {
<ide> * @param bool $safe Use safe = false when you think the user might manipulate
<ide> * their HTTP_CLIENT_IP header. Setting $safe = false will also look at HTTP_X_FORWARDED_FOR
<ide> * @return string Client IP address
<del> * @deprecated use $this->request->clientIp() from your, controller instead.
<add> * @deprecated 3.0.0 Use $this->request->clientIp() from your, controller instead.
<ide> */
<ide> public function getClientIP($safe = true) {
<ide> return $this->request->clientIp($safe);
<ide> public function responseType() {
<ide> *
<ide> * @param string|array $cType Either a string content type to map, or an array of types.
<ide> * @return string|array Aliases for the types provided.
<del> * @deprecated Use $this->response->mapType() in your controller instead.
<add> * @deprecated 3.0.0 Use $this->response->mapType() in your controller instead.
<ide> */
<ide> public function mapType($cType) {
<ide> return $this->response->mapType($cType);
<ide><path>lib/Cake/Controller/Component/SecurityComponent.php
<ide> class SecurityComponent extends Component {
<ide> * List of controller actions for which a POST request is required
<ide> *
<ide> * @var array
<del> * @deprecated Use CakeRequest::onlyAllow() instead.
<add> * @deprecated 3.0.0 Use CakeRequest::onlyAllow() instead.
<ide> * @see SecurityComponent::requirePost()
<ide> */
<ide> public $requirePost = array();
<ide> class SecurityComponent extends Component {
<ide> * List of controller actions for which a GET request is required
<ide> *
<ide> * @var array
<del> * @deprecated Use CakeRequest::onlyAllow() instead.
<add> * @deprecated 3.0.0 Use CakeRequest::onlyAllow() instead.
<ide> * @see SecurityComponent::requireGet()
<ide> */
<ide> public $requireGet = array();
<ide> class SecurityComponent extends Component {
<ide> * List of controller actions for which a PUT request is required
<ide> *
<ide> * @var array
<del> * @deprecated Use CakeRequest::onlyAllow() instead.
<add> * @deprecated 3.0.0 Use CakeRequest::onlyAllow() instead.
<ide> * @see SecurityComponent::requirePut()
<ide> */
<ide> public $requirePut = array();
<ide> class SecurityComponent extends Component {
<ide> * List of controller actions for which a DELETE request is required
<ide> *
<ide> * @var array
<del> * @deprecated Use CakeRequest::onlyAllow() instead.
<add> * @deprecated 3.0.0 Use CakeRequest::onlyAllow() instead.
<ide> * @see SecurityComponent::requireDelete()
<ide> */
<ide> public $requireDelete = array();
<ide> class SecurityComponent extends Component {
<ide> * Deprecated property, superseded by unlockedFields.
<ide> *
<ide> * @var array
<del> * @deprecated
<add> * @deprecated 3.0.0 Superseded by unlockedFields.
<ide> * @see SecurityComponent::$unlockedFields
<ide> */
<ide> public $disabledFields = array();
<ide> public function startup(Controller $controller) {
<ide> * Sets the actions that require a POST request, or empty for all actions
<ide> *
<ide> * @return void
<del> * @deprecated Use CakeRequest::onlyAllow() instead.
<add> * @deprecated 3.0.0 Use CakeRequest::onlyAllow() instead.
<ide> * @link http://book.cakephp.org/2.0/en/core-libraries/components/security-component.html#SecurityComponent::requirePost
<ide> */
<ide> public function requirePost() {
<ide> public function requirePost() {
<ide> /**
<ide> * Sets the actions that require a GET request, or empty for all actions
<ide> *
<del> * @deprecated Use CakeRequest::onlyAllow() instead.
<add> * @deprecated 3.0.0 Use CakeRequest::onlyAllow() instead.
<ide> * @return void
<ide> */
<ide> public function requireGet() {
<ide> public function requireGet() {
<ide> /**
<ide> * Sets the actions that require a PUT request, or empty for all actions
<ide> *
<del> * @deprecated Use CakeRequest::onlyAllow() instead.
<add> * @deprecated 3.0.0 Use CakeRequest::onlyAllow() instead.
<ide> * @return void
<ide> */
<ide> public function requirePut() {
<ide> public function requirePut() {
<ide> /**
<ide> * Sets the actions that require a DELETE request, or empty for all actions
<ide> *
<del> * @deprecated Use CakeRequest::onlyAllow() instead.
<add> * @deprecated 3.0.0 Use CakeRequest::onlyAllow() instead.
<ide> * @return void
<ide> */
<ide> public function requireDelete() {
<ide><path>lib/Cake/Controller/Controller.php
<ide> public function shutdownProcess() {
<ide> *
<ide> * @return array Associative array of the HTTP codes as keys, and the message
<ide> * strings as values, or null of the given $code does not exist.
<del> * @deprecated Since 2.4. Will be removed in 3.0. Use CakeResponse::httpCodes().
<add> * @deprecated 3.0.0 Since 2.4. Will be removed in 3.0. Use CakeResponse::httpCodes().
<ide> */
<ide> public function httpCodes($code = null) {
<ide> return $this->response->httpCodes($code);
<ide> protected function _parseBeforeRedirect($response, $url, $status, $exit) {
<ide> *
<ide> * @param string $status The header message that is being set.
<ide> * @return void
<del> * @deprecated Will be removed in 3.0. Use CakeResponse::header().
<add> * @deprecated 3.0.0 Will be removed in 3.0. Use CakeResponse::header().
<ide> */
<ide> public function header($status) {
<ide> $this->response->header($status);
<ide> public function setAction($action) {
<ide> * Returns number of errors in a submitted FORM.
<ide> *
<ide> * @return int Number of errors
<del> * @deprecated This method will be removed in 3.0
<add> * @deprecated 3.0.0 This method will be removed in 3.0
<ide> */
<ide> public function validate() {
<ide> $args = func_get_args();
<ide> public function validate() {
<ide> * `$errors = $this->validateErrors($this->Article, $this->User);`
<ide> *
<ide> * @return array Validation errors, or false if none
<del> * @deprecated This method will be removed in 3.0
<add> * @deprecated 3.0.0 This method will be removed in 3.0
<ide> */
<ide> public function validateErrors() {
<ide> $objects = func_get_args();
<ide> public function referer($default = null, $local = false) {
<ide> *
<ide> * @return void
<ide> * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::disableCache
<del> * @deprecated Will be removed in 3.0. Use CakeResponse::disableCache().
<add> * @deprecated 3.0.0 Will be removed in 3.0. Use CakeResponse::disableCache().
<ide> */
<ide> public function disableCache() {
<ide> $this->response->disableCache();
<ide> public function disableCache() {
<ide> * @param string $layout Layout you want to use, defaults to 'flash'
<ide> * @return void
<ide> * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::flash
<del> * @deprecated Will be removed in 3.0. Use Session::setFlash().
<add> * @deprecated 3.0.0 Will be removed in 3.0. Use Session::setFlash().
<ide> */
<ide> public function flash($message, $url, $pause = 1, $layout = 'flash') {
<ide> $this->autoRender = false;
<ide> public function flash($message, $url, $pause = 1, $layout = 'flash') {
<ide> * @param bool $exclusive If true, and $op is an array, fields not included in $op will not be
<ide> * included in the returned conditions
<ide> * @return array An array of model conditions
<del> * @deprecated Will be removed in 3.0.
<add> * @deprecated 3.0.0 Will be removed in 3.0.
<ide> */
<ide> public function postConditions($data = array(), $op = null, $bool = 'AND', $exclusive = false) {
<ide> if (!is_array($data) || empty($data)) {
<ide> public function beforeScaffold($method) {
<ide> * @param string $method Method name.
<ide> * @return bool
<ide> * @see Controller::beforeScaffold()
<del> * @deprecated Will be removed in 3.0.
<add> * @deprecated 3.0.0 Will be removed in 3.0.
<ide> */
<ide> protected function _beforeScaffold($method) {
<ide> return $this->beforeScaffold($method);
<ide> public function afterScaffoldSave($method) {
<ide> * @param string $method Method name.
<ide> * @return bool
<ide> * @see Controller::afterScaffoldSave()
<del> * @deprecated Will be removed in 3.0.
<add> * @deprecated 3.0.0 Will be removed in 3.0.
<ide> */
<ide> protected function _afterScaffoldSave($method) {
<ide> return $this->afterScaffoldSave($method);
<ide> public function afterScaffoldSaveError($method) {
<ide> * @param string $method Method name.
<ide> * @return bool
<ide> * @see Controller::afterScaffoldSaveError()
<del> * @deprecated Will be removed in 3.0.
<add> * @deprecated 3.0.0 Will be removed in 3.0.
<ide> */
<ide> protected function _afterScaffoldSaveError($method) {
<ide> return $this->afterScaffoldSaveError($method);
<ide> public function scaffoldError($method) {
<ide> * @param string $method Method name.
<ide> * @return bool
<ide> * @see Controller::scaffoldError()
<del> * @deprecated Will be removed in 3.0.
<add> * @deprecated 3.0.0 Will be removed in 3.0.
<ide> */
<ide> protected function _scaffoldError($method) {
<ide> return $this->scaffoldError($method);
<ide><path>lib/Cake/Controller/Scaffold.php
<ide> * scaffolded actions with custom-made ones.
<ide> *
<ide> * @package Cake.Controller
<del> * @deprecated Dynamic scaffolding will be removed and replaced in 3.0
<add> * @deprecated 3.0.0 Dynamic scaffolding will be removed and replaced in 3.0
<ide> */
<ide> class Scaffold {
<ide>
<ide><path>lib/Cake/Core/App.php
<ide> public static function build($paths = array(), $mode = App::PREPEND) {
<ide> * @param string $plugin CamelCased/lower_cased plugin name to find the path of.
<ide> * @return string full path to the plugin.
<ide> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/app.html#App::pluginPath
<del> * @deprecated Use CakePlugin::path() instead.
<add> * @deprecated 3.0.0 Use CakePlugin::path() instead.
<ide> */
<ide> public static function pluginPath($plugin) {
<ide> return CakePlugin::path($plugin);
<ide><path>lib/Cake/Model/BehaviorCollection.php
<ide> public function init($modelName, $behaviors = array()) {
<ide> * @param string $behavior Behavior name.
<ide> * @param array $config Configuration options.
<ide> * @return void
<del> * @deprecated Will be removed in 3.0. Replaced with load().
<add> * @deprecated 3.0.0 Will be removed in 3.0. Replaced with load().
<ide> */
<ide> public function attach($behavior, $config = array()) {
<ide> return $this->load($behavior, $config);
<ide> public function unload($name) {
<ide> *
<ide> * @param string $name Name of behavior
<ide> * @return void
<del> * @deprecated Will be removed in 3.0. Use unload instead.
<add> * @deprecated 3.0.0 Will be removed in 3.0. Use unload instead.
<ide> */
<ide> public function detach($name) {
<ide> return $this->unload($name);
<ide><path>lib/Cake/Network/CakeRequest.php
<ide> public function allowMethod($methods) {
<ide> * @return bool true
<ide> * @throws MethodNotAllowedException
<ide> * @see CakeRequest::allowMethod()
<del> * @deprecated 2.5 Use CakeRequest::allowMethod() instead.
<add> * @deprecated 3.0.0 Since 2.5, use CakeRequest::allowMethod() instead.
<ide> */
<ide> public function onlyAllow($methods) {
<ide> if (!is_array($methods)) {
<ide><path>lib/Cake/Network/Http/HttpResponse.php
<ide> * HTTP Response from HttpSocket.
<ide> *
<ide> * @package Cake.Network.Http
<del> * @deprecated This class is deprecated as it has naming conflicts with pecl/http
<add> * @deprecated 3.0.0 This class is deprecated as it has naming conflicts with pecl/http
<ide> */
<ide> class HttpResponse extends HttpSocketResponse {
<ide>
<ide><path>lib/Cake/TestSuite/CakeTestCase.php
<ide> protected function _assertAttributes($assertions, $string) {
<ide> * @param mixed $result
<ide> * @param mixed $expected
<ide> * @param string $message the text to display if the assertion is not correct
<del> * @deprecated This is a compatiblity wrapper for 1.x. It will be removed in 3.0
<add> * @deprecated 3.0.0 This is a compatiblity wrapper for 1.x. It will be removed in 3.0
<ide> * @return void
<ide> */
<ide> protected static function assertEqual($result, $expected, $message = '') {
<ide> protected static function assertEqual($result, $expected, $message = '') {
<ide> * @param mixed $result
<ide> * @param mixed $expected
<ide> * @param string $message the text to display if the assertion is not correct
<del> * @deprecated This is a compatiblity wrapper for 1.x. It will be removed in 3.0
<add> * @deprecated 3.0.0 This is a compatiblity wrapper for 1.x. It will be removed in 3.0
<ide> * @return void
<ide> */
<ide> protected static function assertNotEqual($result, $expected, $message = '') {
<ide> protected static function assertNotEqual($result, $expected, $message = '') {
<ide> * @param mixed $pattern a regular expression
<ide> * @param string $string the text to be matched
<ide> * @param string $message the text to display if the assertion is not correct
<del> * @deprecated This is a compatiblity wrapper for 1.x. It will be removed in 3.0
<add> * @deprecated 3.0.0 This is a compatiblity wrapper for 1.x. It will be removed in 3.0
<ide> * @return void
<ide> */
<ide> protected static function assertPattern($pattern, $string, $message = '') {
<ide> protected static function assertPattern($pattern, $string, $message = '') {
<ide> * @param mixed $actual
<ide> * @param mixed $expected
<ide> * @param string $message the text to display if the assertion is not correct
<del> * @deprecated This is a compatiblity wrapper for 1.x. It will be removed in 3.0
<add> * @deprecated 3.0.0 This is a compatiblity wrapper for 1.x. It will be removed in 3.0
<ide> * @return void
<ide> */
<ide> protected static function assertIdentical($actual, $expected, $message = '') {
<ide> protected static function assertIdentical($actual, $expected, $message = '') {
<ide> * @param mixed $actual
<ide> * @param mixed $expected
<ide> * @param string $message the text to display if the assertion is not correct
<del> * @deprecated This is a compatiblity wrapper for 1.x. It will be removed in 3.0
<add> * @deprecated 3.0.0 This is a compatiblity wrapper for 1.x. It will be removed in 3.0
<ide> * @return void
<ide> */
<ide> protected static function assertNotIdentical($actual, $expected, $message = '') {
<ide> protected static function assertNotIdentical($actual, $expected, $message = '')
<ide> * @param mixed $pattern a regular expression
<ide> * @param string $string the text to be matched
<ide> * @param string $message the text to display if the assertion is not correct
<del> * @deprecated This is a compatiblity wrapper for 1.x. It will be removed in 3.0
<add> * @deprecated 3.0.0 This is a compatiblity wrapper for 1.x. It will be removed in 3.0
<ide> * @return void
<ide> */
<ide> protected static function assertNoPattern($pattern, $string, $message = '') {
<ide> protected static function assertNoPattern($pattern, $string, $message = '') {
<ide> /**
<ide> * assert no errors
<ide> *
<del> * @deprecated This is a compatiblity wrapper for 1.x. It will be removed in 3.0
<add> * @deprecated 3.0.0 This is a compatiblity wrapper for 1.x. It will be removed in 3.0
<ide> * @return void
<ide> */
<ide> protected function assertNoErrors() {
<ide> protected function assertNoErrors() {
<ide> *
<ide> * @param mixed $expected the name of the Exception or error
<ide> * @param string $message the text to display if the assertion is not correct
<del> * @deprecated This is a compatiblity wrapper for 1.x. It will be removed in 3.0
<add> * @deprecated 3.0.0 This is a compatiblity wrapper for 1.x. It will be removed in 3.0
<ide> * @return void
<ide> */
<ide> protected function expectError($expected = false, $message = '') {
<ide> protected function expectError($expected = false, $message = '') {
<ide> *
<ide> * @param mixed $expected the name of the Exception
<ide> * @param string $message the text to display if the assertion is not correct
<del> * @deprecated This is a compatiblity wrapper for 1.x. It will be removed in 3.0
<add> * @deprecated 3.0.0 This is a compatiblity wrapper for 1.x. It will be removed in 3.0
<ide> * @return void
<ide> */
<ide> protected function expectException($name = 'Exception', $message = '') {
<ide> protected function expectException($name = 'Exception', $message = '') {
<ide> * @param mixed $first
<ide> * @param mixed $second
<ide> * @param string $message the text to display if the assertion is not correct
<del> * @deprecated This is a compatiblity wrapper for 1.x. It will be removed in 3.0
<add> * @deprecated 3.0.0 This is a compatiblity wrapper for 1.x. It will be removed in 3.0
<ide> * @return void
<ide> */
<ide> protected static function assertReference(&$first, &$second, $message = '') {
<ide> protected static function assertReference(&$first, &$second, $message = '') {
<ide> * @param string $object
<ide> * @param string $type
<ide> * @param string $message
<del> * @deprecated This is a compatiblity wrapper for 1.x. It will be removed in 3.0
<add> * @deprecated 3.0.0 This is a compatiblity wrapper for 1.x. It will be removed in 3.0
<ide> * @return void
<ide> */
<ide> protected static function assertIsA($object, $type, $message = '') {
<ide><path>lib/Cake/Utility/Debugger.php
<ide> public static function log($var, $level = LOG_DEBUG, $depth = 3) {
<ide> * @param int $line Line that triggered the error
<ide> * @param array $context Context
<ide> * @return bool true if error was handled
<del> * @deprecated Will be removed in 3.0. This function is superseded by Debugger::outputError().
<add> * @deprecated 3.0.0 Will be removed in 3.0. This function is superseded by Debugger::outputError().
<ide> */
<ide> public static function showError($code, $description, $file = null, $line = null, $context = null) {
<ide> $self = Debugger::getInstance();
<ide> public static function addFormat($format, array $strings) {
<ide> * straight HTML output, or 'txt' for unformatted text.
<ide> * @param array $strings Template strings to be used for the output format.
<ide> * @return string
<del> * @deprecated Use Debugger::outputAs() and Debugger::addFormat(). Will be removed
<add> * @deprecated 3.0.0 Use Debugger::outputAs() and Debugger::addFormat(). Will be removed
<ide> * in 3.0
<ide> */
<ide> public static function output($format = null, $strings = array()) {
<ide><path>lib/Cake/Utility/ObjectCollection.php
<ide> public function enabled($name = null) {
<ide> * returns an array of currently-attached objects
<ide> * @return mixed If $name is specified, returns the boolean status of the corresponding object.
<ide> * Otherwise, returns an array of all attached objects.
<del> * @deprecated Will be removed in 3.0. Use loaded instead.
<add> * @deprecated 3.0.0 Will be removed in 3.0. Use loaded instead.
<ide> */
<ide> public function attached($name = null) {
<ide> return $this->loaded($name);
<ide><path>lib/Cake/Utility/Sanitize.php
<ide> * and all of the above on arrays.
<ide> *
<ide> * @package Cake.Utility
<del> * @deprecated Deprecated since version 2.4
<add> * @deprecated 3.0.0 Deprecated since version 2.4
<ide> */
<ide> class Sanitize {
<ide>
<ide><path>lib/Cake/Utility/Security.php
<ide> class Security {
<ide> /**
<ide> * Get allowed minutes of inactivity based on security level.
<ide> *
<del> * @deprecated Exists for backwards compatibility only, not used by the core
<add> * @deprecated 3.0.0 Exists for backwards compatibility only, not used by the core
<ide> * @return int Allowed inactivity in minutes
<ide> */
<ide> public static function inactiveMins() {
<ide> public static function setCost($cost) {
<ide> * @param string $text Encrypted string to decrypt, normal string to encrypt
<ide> * @param string $key Key to use
<ide> * @return string Encrypted/Decrypted string
<del> * @deprecated Will be removed in 3.0.
<add> * @deprecated 3.0.0 Will be removed in 3.0.
<ide> */
<ide> public static function cipher($text, $key) {
<ide> if (empty($key)) {
<ide><path>lib/Cake/Utility/Set.php
<ide> * Class used for manipulation of arrays.
<ide> *
<ide> * @package Cake.Utility
<del> * @deprecated Will be removed in 3.0. Use Hash instead.
<add> * @deprecated 3.0.0 Will be removed in 3.0. Use Hash instead.
<ide> */
<ide> class Set {
<ide>
<ide><path>lib/Cake/View/Helper.php
<ide> public function __call($method, $params) {
<ide> *
<ide> * @param string $name Name of the property being accessed.
<ide> * @return mixed Helper or property found at $name
<del> * @deprecated Accessing request properties through this method is deprecated and will be removed in 3.0.
<add> * @deprecated 3.0.0 Accessing request properties through this method is deprecated and will be removed in 3.0.
<ide> */
<ide> public function __get($name) {
<ide> if (isset($this->_helperMap[$name]) && !isset($this->{$name})) {
<ide> public function __get($name) {
<ide> * @param string $name Name of the property being accessed.
<ide> * @param mixed $value Value to set.
<ide> * @return void
<del> * @deprecated This method will be removed in 3.0
<add> * @deprecated 3.0.0 This method will be removed in 3.0
<ide> */
<ide> public function __set($name, $value) {
<ide> switch ($name) {
<ide> public function assetTimestamp($path) {
<ide> *
<ide> * @param string|array $output Either an array of strings to clean or a single string to clean.
<ide> * @return string|array cleaned content for output
<del> * @deprecated This method will be removed in 3.0
<add> * @deprecated 3.0.0 This method will be removed in 3.0
<ide> */
<ide> public function clean($output) {
<ide> $this->_reset();
<ide> public function clean($output) {
<ide> * @param string $insertBefore String to be inserted before options.
<ide> * @param string $insertAfter String to be inserted after options.
<ide> * @return string Composed attributes.
<del> * @deprecated This method will be moved to HtmlHelper in 3.0
<add> * @deprecated 3.0.0 This method will be moved to HtmlHelper in 3.0
<ide> */
<ide> protected function _parseAttributes($options, $exclude = null, $insertBefore = ' ', $insertAfter = null) {
<ide> if (!is_string($options)) {
<ide> protected function _parseAttributes($options, $exclude = null, $insertBefore = '
<ide> * @param string $value The value of the attribute to create.
<ide> * @param bool $escape Define if the value must be escaped
<ide> * @return string The composed attribute.
<del> * @deprecated This method will be moved to HtmlHelper in 3.0
<add> * @deprecated 3.0.0 This method will be moved to HtmlHelper in 3.0
<ide> */
<ide> protected function _formatAttribute($key, $value, $escape = true) {
<ide> if (is_array($value)) {
<ide> public function addClass($options = array(), $class = null, $key = 'class') {
<ide> *
<ide> * @param string $str String to be output.
<ide> * @return string
<del> * @deprecated This method will be removed in future versions.
<add> * @deprecated 3.0.0 This method will be removed in future versions.
<ide> */
<ide> public function output($str) {
<ide> return $str;
<ide><path>lib/Cake/View/Helper/PaginatorHelper.php
<ide> public function defaultModel() {
<ide> *
<ide> * @param array $options Options for the counter string. See #options for list of keys.
<ide> * @return string Counter string.
<del> * @deprecated The %page% style placeholders are deprecated.
<ide> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::counter
<ide> */
<ide> public function counter($options = array()) {
<ide><path>lib/Cake/View/MediaView.php
<ide> * }}}
<ide> *
<ide> * @package Cake.View
<del> * @deprecated Deprecated since version 2.3, use CakeResponse::file() instead
<add> * @deprecated 3.0.0 Deprecated since version 2.3, use CakeResponse::file() instead
<ide> */
<ide> class MediaView extends View {
<ide>
<ide><path>lib/Cake/View/ScaffoldView.php
<ide> * ScaffoldView provides specific view file loading features for scaffolded views.
<ide> *
<ide> * @package Cake.View
<del> * @deprecated Dynamic scaffolding will be removed and replaced in 3.0
<add> * @deprecated 3.0.0 Dynamic scaffolding will be removed and replaced in 3.0
<ide> */
<ide> class ScaffoldView extends View {
<ide>
<ide><path>lib/Cake/View/ThemeView.php
<ide> * Stub class for 2.1 Compatibility
<ide> *
<ide> * @package Cake.View
<del> * @deprecated Deprecated since 2.1, use View class instead
<add> * @deprecated 3.0.0 Deprecated since 2.1, use View class instead
<ide> */
<ide> class ThemeView extends View {
<ide>
<ide><path>lib/Cake/View/View.php
<ide> public function getVars() {
<ide> *
<ide> * @param string $var The view var you want the contents of.
<ide> * @return mixed The content of the named var if its set, otherwise null.
<del> * @deprecated Will be removed in 3.0. Use View::get() instead.
<add> * @deprecated 3.0.0 Will be removed in 3.0. Use View::get() instead.
<ide> */
<ide> public function getVar($var) {
<ide> return $this->get($var);
<ide> public function extend($name) {
<ide> * update/replace a script element.
<ide> * @param string $content The content of the script being added, optional.
<ide> * @return void
<del> * @deprecated Will be removed in 3.0. Superseded by blocks functionality.
<add> * @deprecated 3.0.0 Will be removed in 3.0. Superseded by blocks functionality.
<ide> * @see View::start()
<ide> */
<ide> public function addScript($name, $content = null) {
<ide><path>lib/Cake/View/ViewBlock.php
<ide> public function concat($name, $value = null, $mode = ViewBlock::APPEND) {
<ide> * @param string $name Name of the block
<ide> * @param string $value The content for the block.
<ide> * @return void
<del> * @deprecated As of 2.3 use ViewBlock::concat() instead.
<add> * @deprecated 3.0.0 As of 2.3 use ViewBlock::concat() instead.
<ide> */
<ide> public function append($name, $value = null) {
<ide> $this->concat($name, $value);
<ide><path>lib/Cake/basics.php
<ide> function env($key) {
<ide> * @param mixed $expires A valid strtotime string when the data expires.
<ide> * @param string $target The target of the cached data; either 'cache' or 'public'.
<ide> * @return mixed The contents of the temporary file.
<del> * @deprecated Will be removed in 3.0. Please use Cache::write() instead.
<add> * @deprecated 3.0.0 Will be removed in 3.0. Please use Cache::write() instead.
<ide> */
<ide> function cache($path, $data = null, $expires = '+1 day', $target = 'cache') {
<ide> if (Configure::read('Cache.disable')) { | 29 |
Text | Text | find characters with lazy matching | 6cd3466f0be97b214654827eaa4391a406536e6d | <ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/regular-expressions/find-characters-with-lazy-matching.english.md
<ide> In regular expressions, a <code>greedy</code> match finds the longest possible p
<ide> You can apply the regex <code>/t[a-z]*i/</code> to the string <code>"titanic"</code>. This regex is basically a pattern that starts with <code>t</code>, ends with <code>i</code>, and has some letters in between.
<ide> Regular expressions are by default <code>greedy</code>, so the match would return <code>["titani"]</code>. It finds the largest sub-string possible to fit the pattern.
<ide> However, you can use the <code>?</code> character to change it to <code>lazy</code> matching. <code>"titanic"</code> matched against the adjusted regex of <code>/t[a-z]*?i/</code> returns <code>["ti"]</code>.
<add><strong>Note</strong><br>Parsing HTML with regular expressions should be avoided, but pattern matching an HTML string with regular expressions is completely fine.
<ide> </section>
<ide>
<ide> ## Instructions | 1 |
Javascript | Javascript | add required dependency | b152cc8ae2b332c526367ef95982038de4ad7f8f | <ide><path>lib/sproutcore-handlebars/lib/controls/checkbox.js
<ide> require("sproutcore-views/views/view");
<add>require("sproutcore-handlebars/ext");
<ide>
<ide> // TODO: Be explicit in the class documentation that you
<ide> // *MUST* set the value of a checkbox through SproutCore. | 1 |
Javascript | Javascript | create nativemoduleschema and componentschema | 3a75b376cc3c44f9693d99b33046cf76d6fafa89 | <ide><path>packages/react-native-codegen/src/CodegenSchema.js
<ide> export type ComponentShape = $ReadOnly<{|
<ide> |}>;
<ide>
<ide> export type SchemaType = $ReadOnly<{|
<del> modules: $ReadOnly<{
<del> [module: string]: $ReadOnly<{|
<del> components?: $ReadOnly<{[component: string]: ComponentShape, ...}>,
<del> nativeModules?: $ReadOnly<{
<del> [nativeModule: string]: NativeModuleSchema,
<del> ...,
<del> }>,
<del> |}>,
<del> ...,
<del> }>,
<add> modules: $ReadOnly<{|
<add> [moduleName: string]: ComponentSchema | NativeModuleSchema,
<add> |}>,
<add>|}>;
<add>
<add>export type ComponentSchema = $ReadOnly<{|
<add> type: 'Component',
<add> components: $ReadOnly<{|
<add> [componentName: string]: ComponentShape,
<add> |}>,
<ide> |}>;
<ide>
<ide> /**
<ide> * NativeModule Types
<ide> */
<ide> export type NativeModuleSchema = $ReadOnly<{|
<del> // We only support aliases to Objects
<add> type: 'NativeModule',
<ide> aliases: NativeModuleAliasMap,
<add> spec: NativeModuleSpec,
<add> moduleNames: $ReadOnlyArray<string>,
<add>|}>;
<add>
<add>type NativeModuleSpec = $ReadOnly<{|
<ide> properties: $ReadOnlyArray<NativeModulePropertySchema>,
<ide> |}>;
<ide> | 1 |
Mixed | Python | remove jsonp support from core | fe745b96163282e492f17a6b003418b81350333f | <ide><path>docs/api-guide/renderers.md
<ide> using the `APIView` class based views.
<ide> Or, if you're using the `@api_view` decorator with function based views.
<ide>
<ide> @api_view(['GET'])
<del> @renderer_classes((JSONRenderer, JSONPRenderer))
<add> @renderer_classes((JSONRenderer,))
<ide> def user_count_view(request, format=None):
<ide> """
<del> A view that returns the count of active users, in JSON or JSONp.
<add> A view that returns the count of active users in JSON.
<ide> """
<ide> user_count = User.objects.filter(active=True).count()
<ide> content = {'user_count': user_count}
<ide> The default JSON encoding style can be altered using the `UNICODE_JSON` and `COM
<ide>
<ide> **.charset**: `None`
<ide>
<del>## JSONPRenderer
<del>
<del>Renders the request data into `JSONP`. The `JSONP` media type provides a mechanism of allowing cross-domain AJAX requests, by wrapping a `JSON` response in a javascript callback.
<del>
<del>The javascript callback function must be set by the client including a `callback` URL query parameter. For example `http://example.com/api/users?callback=jsonpCallback`. If the callback function is not explicitly set by the client it will default to `'callback'`.
<del>
<del>---
<del>
<del>**Warning**: If you require cross-domain AJAX requests, you should almost certainly be using the more modern approach of [CORS][cors] as an alternative to `JSONP`. See the [CORS documentation][cors-docs] for more details.
<del>
<del>The `jsonp` approach is essentially a browser hack, and is [only appropriate for globally readable API endpoints][jsonp-security], where `GET` requests are unauthenticated and do not require any user permissions.
<del>
<del>---
<del>
<del>**.media_type**: `application/javascript`
<del>
<del>**.format**: `'.jsonp'`
<del>
<del>**.charset**: `utf-8`
<del>
<ide> ## YAMLRenderer
<ide>
<ide> Renders the request data into `YAML`.
<ide> Comma-separated values are a plain-text tabular data format, that can be easily
<ide> [cite]: https://docs.djangoproject.com/en/dev/ref/template-response/#the-rendering-process
<ide> [conneg]: content-negotiation.md
<ide> [browser-accept-headers]: http://www.gethifi.com/blog/browser-rest-http-accept-headers
<del>[rfc4627]: http://www.ietf.org/rfc/rfc4627.txt
<del>[cors]: http://www.w3.org/TR/cors/
<del>[cors-docs]: ../topics/ajax-csrf-cors.md
<del>[jsonp-security]: http://stackoverflow.com/questions/613962/is-jsonp-safe-to-use
<ide> [testing]: testing.md
<ide> [HATEOAS]: http://timelessrepo.com/haters-gonna-hateoas
<ide> [quote]: http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
<ide><path>rest_framework/renderers.py
<ide> def render(self, data, accepted_media_type=None, renderer_context=None):
<ide> return ret
<ide>
<ide>
<del>class JSONPRenderer(JSONRenderer):
<del> """
<del> Renderer which serializes to json,
<del> wrapping the json output in a callback function.
<del> """
<del>
<del> media_type = 'application/javascript'
<del> format = 'jsonp'
<del> callback_parameter = 'callback'
<del> default_callback = 'callback'
<del> charset = 'utf-8'
<del>
<del> def get_callback(self, renderer_context):
<del> """
<del> Determine the name of the callback to wrap around the json output.
<del> """
<del> request = renderer_context.get('request', None)
<del> params = request and request.query_params or {}
<del> return params.get(self.callback_parameter, self.default_callback)
<del>
<del> def render(self, data, accepted_media_type=None, renderer_context=None):
<del> """
<del> Renders into jsonp, wrapping the json output in a callback function.
<del>
<del> Clients may set the callback function name using a query parameter
<del> on the URL, for example: ?callback=exampleCallbackName
<del> """
<del> renderer_context = renderer_context or {}
<del> callback = self.get_callback(renderer_context)
<del> json = super(JSONPRenderer, self).render(data, accepted_media_type,
<del> renderer_context)
<del> return callback.encode(self.charset) + b'(' + json + b');'
<del>
<del>
<ide> class XMLRenderer(BaseRenderer):
<ide> """
<ide> Renderer which serializes to XML.
<ide><path>tests/test_renderers.py
<ide> from rest_framework.response import Response
<ide> from rest_framework.views import APIView
<ide> from rest_framework.renderers import BaseRenderer, JSONRenderer, YAMLRenderer, \
<del> XMLRenderer, JSONPRenderer, BrowsableAPIRenderer
<add> XMLRenderer, BrowsableAPIRenderer
<ide> from rest_framework.parsers import YAMLParser, XMLParser
<ide> from rest_framework.settings import api_settings
<ide> from rest_framework.test import APIRequestFactory
<ide> def get(self, request, **kwargs):
<ide> url(r'^.*\.(?P<format>.+)$', MockView.as_view(renderer_classes=[RendererA, RendererB])),
<ide> url(r'^$', MockView.as_view(renderer_classes=[RendererA, RendererB])),
<ide> url(r'^cache$', MockGETView.as_view()),
<del> url(r'^jsonp/jsonrenderer$', MockGETView.as_view(renderer_classes=[JSONRenderer, JSONPRenderer])),
<del> url(r'^jsonp/nojsonrenderer$', MockGETView.as_view(renderer_classes=[JSONPRenderer])),
<ide> url(r'^parseerror$', MockPOSTView.as_view(renderer_classes=[JSONRenderer, BrowsableAPIRenderer])),
<ide> url(r'^html$', HTMLView.as_view()),
<ide> url(r'^html1$', HTMLView1.as_view()),
<ide> class AsciiJSONRenderer(JSONRenderer):
<ide> self.assertEqual(content, '{"countries":["United Kingdom","France","Espa\\u00f1a"]}'.encode('utf-8'))
<ide>
<ide>
<del>class JSONPRendererTests(TestCase):
<del> """
<del> Tests specific to the JSONP Renderer
<del> """
<del>
<del> urls = 'tests.test_renderers'
<del>
<del> def test_without_callback_with_json_renderer(self):
<del> """
<del> Test JSONP rendering with View JSON Renderer.
<del> """
<del> resp = self.client.get(
<del> '/jsonp/jsonrenderer',
<del> HTTP_ACCEPT='application/javascript'
<del> )
<del> self.assertEqual(resp.status_code, status.HTTP_200_OK)
<del> self.assertEqual(resp['Content-Type'], 'application/javascript; charset=utf-8')
<del> self.assertEqual(
<del> resp.content,
<del> ('callback(%s);' % _flat_repr).encode('ascii')
<del> )
<del>
<del> def test_without_callback_without_json_renderer(self):
<del> """
<del> Test JSONP rendering without View JSON Renderer.
<del> """
<del> resp = self.client.get(
<del> '/jsonp/nojsonrenderer',
<del> HTTP_ACCEPT='application/javascript'
<del> )
<del> self.assertEqual(resp.status_code, status.HTTP_200_OK)
<del> self.assertEqual(resp['Content-Type'], 'application/javascript; charset=utf-8')
<del> self.assertEqual(
<del> resp.content,
<del> ('callback(%s);' % _flat_repr).encode('ascii')
<del> )
<del>
<del> def test_with_callback(self):
<del> """
<del> Test JSONP rendering with callback function name.
<del> """
<del> callback_func = 'myjsonpcallback'
<del> resp = self.client.get(
<del> '/jsonp/nojsonrenderer?callback=' + callback_func,
<del> HTTP_ACCEPT='application/javascript'
<del> )
<del> self.assertEqual(resp.status_code, status.HTTP_200_OK)
<del> self.assertEqual(resp['Content-Type'], 'application/javascript; charset=utf-8')
<del> self.assertEqual(
<del> resp.content,
<del> ('%s(%s);' % (callback_func, _flat_repr)).encode('ascii')
<del> )
<del>
<del>
<ide> if yaml:
<ide> _yaml_repr = 'foo: [bar, baz]\n'
<ide> | 3 |
Text | Text | fix inconsistency in mockcomponent argument name | 31090821446d0eb425bbddd7901c1040a4ceb3a1 | <ide><path>docs/docs/09.4-test-utils.md
<ide> Render a component into a detached DOM node in the document. **This function req
<ide> ### mockComponent
<ide>
<ide> ```javascript
<del>object mockComponent(function componentClass, string? tagName)
<add>object mockComponent(function componentClass, string? mockTagName)
<ide> ```
<ide>
<ide> Pass a mocked component module to this method to augment it with useful methods that allow it to be used as a dummy React component. Instead of rendering as usual, the component will become a simple `<div>` (or other tag if `mockTagName` is provided) containing any provided children. | 1 |
Javascript | Javascript | fix capitalization of github (#902) | c65062599ecad54a1ad5bacd72f65e8f9ef7449b | <ide><path>pages/src/src/Header.js
<ide> var Header = React.createClass({
<ide> </a>
<ide> <a href="docs/" target="_self">Docs</a>
<ide> <a href="http://stackoverflow.com/questions/tagged/immutable.js?sort=votes">Questions</a>
<del> <a href="https://github.com/facebook/immutable-js/">Github</a>
<add> <a href="https://github.com/facebook/immutable-js/">GitHub</a>
<ide> </div>
<ide> </div>
<ide> <div className="coverContainer">
<ide> var Header = React.createClass({
<ide> <div className="miniHeaderContents">
<ide> <a href="docs/" target="_self">Docs</a>
<ide> <a href="http://stackoverflow.com/questions/tagged/immutable.js?sort=votes">Questions</a>
<del> <a href="https://github.com/facebook/immutable-js/">Github</a>
<add> <a href="https://github.com/facebook/immutable-js/">GitHub</a>
<ide> </div>
<ide> </div>
<ide> <div className="synopsis" > | 1 |
Go | Go | remove empty gelf_unsupported.go | 72f5e5e84f402f175ec08964053e1af688dad265 | <ide><path>daemon/logger/gelf/gelf_unsupported.go
<del>// +build !linux
<del>
<del>package gelf | 1 |
Mixed | Python | fix readme and duplicate (#967) | 781b7f86e720b9c5164047e46f2dedd807b9165b | <ide><path>README.md
<ide> We're on [Gitter](https://gitter.im/TheAlgorithms)! Please join us.
<ide>
<ide> - [N Queens](./backtracking/n_queens.py)
<ide> - [Sum Of Subsets](./backtracking/sum_of_subsets.py)
<add>- [All Subsequences](./backtracking/all_subsequences.py)
<add>- [All Permutations](./backtracking/all_permutations.py)
<ide>
<ide> ## Ciphers
<ide>
<ide> We're on [Gitter](https://gitter.im/TheAlgorithms)! Please join us.
<ide> ## Divide And Conquer
<ide>
<ide> - [Max Subarray Sum](./divide_and_conquer/max_subarray_sum.py)
<del>- [Max Sub Array Sum](./divide_and_conquer/max_sub_array_sum.py)
<ide> - [Closest Pair Of Points](./divide_and_conquer/closest_pair_of_points.py)
<ide>
<ide> ## Strings
<ide><path>divide_and_conquer/max_sub_array_sum.py
<del>"""
<del>Given a array of length n, max_sub_array_sum() finds the maximum of sum of contiguous sub-array using divide and conquer method.
<del>
<del>Time complexity : O(n log n)
<del>
<del>Ref : INTRODUCTION TO ALGORITHMS THIRD EDITION (section : 4, sub-section : 4.1, page : 70)
<del>
<del>"""
<del>
<del>
<del>def max_sum_from_start(array):
<del> """ This function finds the maximum contiguous sum of array from 0 index
<del>
<del> Parameters :
<del> array (list[int]) : given array
<del>
<del> Returns :
<del> max_sum (int) : maximum contiguous sum of array from 0 index
<del>
<del> """
<del> array_sum = 0
<del> max_sum = float("-inf")
<del> for num in array:
<del> array_sum += num
<del> if array_sum > max_sum:
<del> max_sum = array_sum
<del> return max_sum
<del>
<del>
<del>def max_cross_array_sum(array, left, mid, right):
<del> """ This function finds the maximum contiguous sum of left and right arrays
<del>
<del> Parameters :
<del> array, left, mid, right (list[int], int, int, int)
<del>
<del> Returns :
<del> (int) : maximum of sum of contiguous sum of left and right arrays
<del>
<del> """
<del>
<del> max_sum_of_left = max_sum_from_start(array[left:mid+1][::-1])
<del> max_sum_of_right = max_sum_from_start(array[mid+1: right+1])
<del> return max_sum_of_left + max_sum_of_right
<del>
<del>
<del>def max_sub_array_sum(array, left, right):
<del> """ This function finds the maximum of sum of contiguous sub-array using divide and conquer method
<del>
<del> Parameters :
<del> array, left, right (list[int], int, int) : given array, current left index and current right index
<del>
<del> Returns :
<del> int : maximum of sum of contiguous sub-array
<del>
<del> """
<del>
<del> # base case: array has only one element
<del> if left == right:
<del> return array[right]
<del>
<del> # Recursion
<del> mid = (left + right) // 2
<del> left_half_sum = max_sub_array_sum(array, left, mid)
<del> right_half_sum = max_sub_array_sum(array, mid + 1, right)
<del> cross_sum = max_cross_array_sum(array, left, mid, right)
<del> return max(left_half_sum, right_half_sum, cross_sum)
<del>
<del>
<del>array = [-2, -5, 6, -2, -3, 1, 5, -6]
<del>array_length = len(array)
<del>print("Maximum sum of contiguous subarray:", max_sub_array_sum(array, 0, array_length - 1))
<del> | 2 |
Javascript | Javascript | drop the @jsx docblock from unit tests | 348af5784207c908e7d074fdad72cb5237a0f78d | <ide><path>src/addons/link/__tests__/LinkedStateMixin-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/addons/link/__tests__/ReactLinkPropTypes-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/addons/transitions/__tests__/ReactCSSTransitionGroup-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/addons/transitions/__tests__/ReactTransitionChildMapping-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/addons/transitions/__tests__/ReactTransitionGroup-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/browser/__tests__/ReactDOM-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/browser/__tests__/ReactWebWorker-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/browser/eventPlugins/__tests__/AnalyticsEventPlugin-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/browser/eventPlugins/__tests__/EnterLeaveEventPlugin-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/browser/server/__tests__/ReactServerRendering-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/browser/ui/__tests__/ReactDOMComponent-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/browser/ui/__tests__/ReactEventListener-test.js
<ide> * limitations under the License.
<ide> *
<ide> * @emails react-core
<del> * @jsx React.DOM
<ide> */
<ide>
<ide> 'use strict';
<ide><path>src/browser/ui/__tests__/ReactMount-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/browser/ui/__tests__/ReactMountDestruction-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/browser/ui/__tests__/ReactRenderDocument-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/browser/ui/dom/__tests__/CSSProperty-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/browser/ui/dom/__tests__/CSSPropertyOperations-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/browser/ui/dom/__tests__/DOMPropertyOperations-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/browser/ui/dom/__tests__/Danger-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide> /*jslint evil: true */
<ide><path>src/browser/ui/dom/__tests__/getNodeForCharacterOffset-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/browser/ui/dom/components/__tests__/ReactDOMButton-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/browser/ui/dom/components/__tests__/ReactDOMInput-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/browser/ui/dom/components/__tests__/ReactDOMSelect-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/browser/ui/dom/components/__tests__/ReactDOMTextarea-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/core/__tests__/ReactBind-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide> /*global global:true*/
<ide><path>src/core/__tests__/ReactComponent-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/core/__tests__/ReactComponentLifeCycle-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/core/__tests__/ReactCompositeComponent-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/core/__tests__/ReactCompositeComponentDOMMinimalism-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/core/__tests__/ReactCompositeComponentError-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/core/__tests__/ReactCompositeComponentMixin-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/core/__tests__/ReactCompositeComponentSpec-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/core/__tests__/ReactCompositeComponentState-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/core/__tests__/ReactElement-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/core/__tests__/ReactIdentity-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/core/__tests__/ReactInstanceHandles-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/core/__tests__/ReactMultiChild-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/core/__tests__/ReactMultiChildReconcile-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/core/__tests__/ReactMultiChildText-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/core/__tests__/ReactPropTransferer-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/core/__tests__/ReactPropTypes-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/core/__tests__/ReactStateSetters-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/core/__tests__/ReactTextComponent-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/core/__tests__/ReactUpdates-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/core/__tests__/refs-destruction-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/core/__tests__/refs-test.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> *
<del> * @jsx React.DOM
<ide> * @emails react-core
<ide> */
<ide>
<ide><path>src/utils/__tests__/ReactChildren-test.js
<ide> * limitations under the License.
<ide> *
<ide> * @emails react-core
<del> * @jsx React.DOM
<ide> */
<ide>
<ide> "use strict";
<ide><path>src/utils/__tests__/accumulateInto-test.js
<ide> * limitations under the License.
<ide> *
<ide> * @emails react-core
<del> * @jsx React.DOM
<ide> */
<ide>
<ide> "use strict";
<ide><path>src/utils/__tests__/cloneWithProps-test.js
<ide> * limitations under the License.
<ide> *
<ide> * @emails react-core
<del> * @jsx React.DOM
<ide> */
<ide>
<ide> "use strict";
<ide><path>src/utils/__tests__/onlyChild-test.js
<ide> * limitations under the License.
<ide> *
<ide> * @emails react-core
<del> * @jsx React.DOM
<ide> */
<ide>
<ide> "use strict";
<ide><path>src/utils/__tests__/sliceChildren-test.js
<ide> * limitations under the License.
<ide> *
<ide> * @emails react-core
<del> * @jsx React.DOM
<ide> */
<ide>
<ide> "use strict";
<ide><path>src/utils/__tests__/traverseAllChildren-test.js
<ide> * limitations under the License.
<ide> *
<ide> * @emails react-core
<del> * @jsx React.DOM
<ide> */
<ide>
<ide> "use strict"; | 52 |
Text | Text | add 2.14.0-beta.1 to the changelog | a787c8274c5290512cc3fdbc60cb9e27938a6674 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<del>### 2.13.0-beta.2 (April 7, 2017)
<add>### 2.14.0-beta.1 (April 27, 2017)
<add>
<add>- [#15015](https://github.com/emberjs/ember.js/pull/15015) Allow mounting routeless engines with a bound engine name
<add>- [#15078](https://github.com/emberjs/ember.js/pull/15078) [DEPRECATION] Deprecate `EventManager#canDispatchToEventManager`.
<add>- [#15085](https://github.com/emberjs/ember.js/pull/15085) Add missing instrumentation for compilation/lookup phase
<add>- [#15150](https://github.com/emberjs/ember.js/pull/15150) [PERF] Cleanup Proxy invalidation tracking.
<add>- [#15168](https://github.com/emberjs/ember.js/pull/15168) [BUGFIX] Ensure that retrying a transition created with `replaceWith` causes a history replacement.
<add>- [#15148](https://github.com/emberjs/ember.js/pull/15148) [BUGFIX] Ensure that using `replace` with `refreshModel` works properly.
<add>- [#15178](https://github.com/emberjs/ember.js/pull/15178) Refactor route to lookup controller for QPs.
<add>- [#15129](https://github.com/emberjs/ember.js/pull/15129) Fix access to service:-document in ember-engines
<add>
<add>
<add>### 2.13.0 (April 27, 2017)
<ide>
<ide> - [#15111](https://github.com/emberjs/ember.js/pull/15111) / [#15029](https://github.com/emberjs/ember.js/pull/15029) [PERF] `factoryFor` should cache when possible.
<ide> - [#14961](https://github.com/emberjs/ember.js/pull/14961) [BUGIX] [Fixes #14925] remove duplicate `/` in pathname
<ide> - [#15065](https://github.com/emberjs/ember.js/pull/15065) [BUGFIX] Guard jQuery access in `setupForTesting`.
<ide> - [#15103](https://github.com/emberjs/ember.js/pull/15103) [BUGFIX] Allow calling `Ember.warn` without test.
<ide> - [#15106](https://github.com/emberjs/ember.js/pull/15106) [DOC] Introduce a more debugging data to warnings about CP dependencies.
<ide> - [#15107](https://github.com/emberjs/ember.js/pull/15107) [PERF] avoid toBoolean conversion when possible (chains).
<del>
<del>### 2.13.0-beta.1 (March 15, 2017)
<del>
<ide> - [#14011](https://github.com/emberjs/ember.js/pull/14011) [FEATURE ember-unique-location-history-state] Implements [RFC #186](https://github.com/emberjs/rfcs/pull/186).
<ide> - [#13231](https://github.com/emberjs/ember.js/pull/13231) [BUGFIX] Fix a bug when using commas in computer property dependent keys.
<ide> - [#14890](https://github.com/emberjs/ember.js/pull/14890) [BUGFIX] Fix a race condition where actions are invoked on destroyed DOM nodes. | 1 |
Python | Python | fix broadcasting in np.cross (solves ) | b9454f50f23516234c325490913224c3a69fb122 | <ide><path>numpy/core/numeric.py
<ide> def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None):
<ide>
<ide> """
<ide> if axis is not None:
<del> axisa, axisb, axisc=(axis,)*3
<del> a = asarray(a).swapaxes(axisa, 0)
<del> b = asarray(b).swapaxes(axisb, 0)
<del> msg = "incompatible dimensions for cross product\n"\
<del> "(dimension must be 2 or 3)"
<del> if (a.shape[0] not in [2, 3]) or (b.shape[0] not in [2, 3]):
<add> axisa, axisb, axisc = (axis,) * 3
<add> a = asarray(a)
<add> b = asarray(b)
<add> # Move working axis to the end of the shape
<add> a = rollaxis(a, axisa, a.ndim)
<add> b = rollaxis(b, axisb, b.ndim)
<add> msg = ("incompatible dimensions for cross product\n"
<add> "(dimension must be 2 or 3)")
<add> if a.shape[-1] not in [2, 3] or b.shape[-1] not in [2, 3]:
<ide> raise ValueError(msg)
<del> if a.shape[0] == 2:
<del> if (b.shape[0] == 2):
<del> cp = a[0]*b[1] - a[1]*b[0]
<add> if a.shape[-1] == 2:
<add> if b.shape[-1] == 2:
<add> cp = a[..., 0]*b[..., 1] - a[..., 1]*b[..., 0]
<ide> if cp.ndim == 0:
<ide> return cp
<ide> else:
<del> return cp.swapaxes(0, axisc)
<add> # This works because we are moving the last axis
<add> return rollaxis(cp, -1, axisc)
<ide> else:
<del> x = a[1]*b[2]
<del> y = -a[0]*b[2]
<del> z = a[0]*b[1] - a[1]*b[0]
<del> elif a.shape[0] == 3:
<del> if (b.shape[0] == 3):
<del> x = a[1]*b[2] - a[2]*b[1]
<del> y = a[2]*b[0] - a[0]*b[2]
<del> z = a[0]*b[1] - a[1]*b[0]
<add> x = a[..., 1]*b[..., 2]
<add> y = -a[..., 0]*b[..., 2]
<add> z = a[..., 0]*b[..., 1] - a[..., 1]*b[..., 0]
<add> elif a.shape[-1] == 3:
<add> if b.shape[-1] == 3:
<add> x = a[..., 1]*b[..., 2] - a[..., 2]*b[..., 1]
<add> y = a[..., 2]*b[..., 0] - a[..., 0]*b[..., 2]
<add> z = a[..., 0]*b[..., 1] - a[..., 1]*b[..., 0]
<ide> else:
<del> x = -a[2]*b[1]
<del> y = a[2]*b[0]
<del> z = a[0]*b[1] - a[1]*b[0]
<del> cp = array([x, y, z])
<add> x = -a[..., 2]*b[..., 1]
<add> y = a[..., 2]*b[..., 0]
<add> z = a[..., 0]*b[..., 1] - a[..., 1]*b[..., 0]
<add> cp = concatenate((x[..., None], y[..., None], z[..., None]), axis=-1)
<ide> if cp.ndim == 1:
<ide> return cp
<ide> else:
<del> return cp.swapaxes(0, axisc)
<del>
<add> # This works because we are moving the last axis
<add> return rollaxis(cp, -1, axisc)
<ide>
<ide> #Use numarray's printing function
<ide> from .arrayprint import array2string, get_printoptions, set_printoptions
<ide><path>numpy/core/tests/test_numeric.py
<ide> def test_roll_empty(self):
<ide> x = np.array([])
<ide> assert_equal(np.roll(x, 1), np.array([]))
<ide>
<add>class TestCross(TestCase):
<add> def test_2x2(self):
<add> u = [1, 2]
<add> v = [3, 4]
<add> z = -2
<add> cp = np.cross(u, v)
<add> assert_equal(cp, z)
<add> cp = np.cross(v, u)
<add> assert_equal(cp, -z)
<add>
<add> def test_2x3(self):
<add> u = [1, 2]
<add> v = [3, 4, 5]
<add> z = np.array([10, -5, -2])
<add> cp = np.cross(u, v)
<add> assert_equal(cp, z)
<add> cp = np.cross(v, u)
<add> assert_equal(cp, -z)
<add>
<add> def test_3x3(self):
<add> u = [1, 2, 3]
<add> v = [4, 5, 6]
<add> z = np.array([-3, 6, -3])
<add> cp = cross(u, v)
<add> assert_equal(cp, z)
<add> cp = np.cross(v, u)
<add> assert_equal(cp, -z)
<add>
<add> def test_broadcasting(self):
<add> # Ticket #2624 (Trac #2032)
<add> u = np.ones((2, 1, 3))
<add> v = np.ones((5, 3))
<add> assert_equal(np.cross(u, v).shape, (2, 5, 3))
<add> u = np.ones((10, 3, 5))
<add> v = np.ones((2, 5))
<add> assert_equal(np.cross(u, v, axisa=1, axisb=0).shape, (10, 5, 3))
<add> u = np.ones((10, 3, 5, 7))
<add> v = np.ones((5, 7, 2))
<add> assert_equal(np.cross(u, v, axisa=1, axisc=2).shape, (10, 5, 3, 7))
<add>
<ide>
<ide> if __name__ == "__main__":
<ide> run_module_suite() | 2 |
Python | Python | add test for 12-byte alignment | d3beaaacb3d28dbc4c6bcf8709857b561b37a8cc | <ide><path>numpy/core/tests/test_multiarray.py
<ide> def check(self, shape, dtype, order, align):
<ide> raise ValueError()
<ide>
<ide> def test_various_alignments(self):
<del> for align in [1, 2, 3, 4, 8, 16, 32, 64, None]:
<add> for align in [1, 2, 3, 4, 8, 12, 16, 32, 64, None]:
<ide> for n in [0, 1, 3, 11]:
<ide> for order in ["C", "F", None]:
<del> for dtype in np.typecodes["All"]:
<add> for dtype in list(np.typecodes["All"]) + ['i4,i4,i4']:
<ide> if dtype == 'O':
<ide> # object dtype can't be misaligned
<ide> continue | 1 |
Text | Text | fix typo 'crsf' and plural of word | 781890b7df88086d9cba07904e53db346ec4a715 | <ide><path>docs/api-guide/testing.md
<ide> If you're using `SessionAuthentication` then you'll need to include a CSRF token
<ide> for any `POST`, `PUT`, `PATCH` or `DELETE` requests.
<ide>
<ide> You can do so by following the same flow that a JavaScript based client would use.
<del>First make a `GET` request in order to obtain a CRSF token, then present that
<add>First, make a `GET` request in order to obtain a CSRF token, then present that
<ide> token in the following request.
<ide>
<ide> For example...
<ide> With careful usage both the `RequestsClient` and the `CoreAPIClient` provide
<ide> the ability to write test cases that can run either in development, or be run
<ide> directly against your staging server or production environment.
<ide>
<del>Using this style to create basic tests of a few core piece of functionality is
<add>Using this style to create basic tests of a few core pieces of functionality is
<ide> a powerful way to validate your live service. Doing so may require some careful
<ide> attention to setup and teardown to ensure that the tests run in a way that they
<ide> do not directly affect customer data. | 1 |
Javascript | Javascript | clarify confusion over "client" in comment | a046ae5ceddcaaf695df60be5dbc9d725beb6f22 | <ide><path>test/parallel/test-tls-socket-default-options.js
<ide> function test(client, callback) {
<ide> }));
<ide> }));
<ide>
<del> // Client doesn't support the 'secureConnect' event, and doesn't error if
<del> // authentication failed. Caller must explicitly check for failure.
<add> // `new TLSSocket` doesn't support the 'secureConnect' event on client side,
<add> // and doesn't error if authentication failed. Caller must explicitly check
<add> // for failure.
<ide> (new tls.TLSSocket(null, client)).connect(pair.server.server.address().port)
<ide> .on('connect', common.mustCall(function() {
<ide> this.end('hello'); | 1 |
Javascript | Javascript | add serialize to amd dependencies | 250fd800a171cac9ab713cbbe1a70a90a348e3dc | <ide><path>src/ajax.js
<ide> define( [
<ide> "./ajax/parseJSON",
<ide> "./ajax/parseXML",
<ide> "./event/trigger",
<del> "./deferred"
<add> "./deferred",
<add> "./serialize" // jQuery.param
<ide> ], function( jQuery, document, rnotwhite, location, nonce, rquery ) {
<ide>
<ide> var | 1 |
Python | Python | tell scons whether we are in bypass mode or not | 680190a475b66b947dc906f76700990acd054498 | <ide><path>numpy/distutils/command/scons.py
<ide> def run(self):
<ide> cmd.append('cxx_opt_path=%s' % protect_path(self.scons_cxxcompiler_path))
<ide>
<ide> cmd.append('include_bootstrap=%s' % dirl_to_str(get_numpy_include_dirs(sconscript)))
<add> cmd.append('bypass=%s' % self.bypass)
<ide> if self.silent:
<ide> if int(self.silent) == 2:
<ide> cmd.append('-Q') | 1 |
Text | Text | fix broken link in dgram doc | 8361c26cd5c1f0ac15437cf46f1bf2439e8d25b1 | <ide><path>doc/api/dgram.md
<ide> and `udp6` sockets). The bound address and port can be retrieved using
<ide> [`Buffer`]: buffer.html
<ide> [`'close'`]: #dgram_event_close
<ide> [`close()`]: #dgram_socket_close_callback
<add>[`cluster`]: cluster.html
<ide> [`dgram.createSocket()`]: #dgram_dgram_createsocket_options_callback
<ide> [`dgram.Socket#bind()`]: #dgram_socket_bind_options_callback
<ide> [`Error`]: errors.html#errors_class_error | 1 |
Ruby | Ruby | remove one more note about deprecated behavior | ca8f8fb0316fe9a2f3a4756a781c9bf4cdcf465c | <ide><path>actionpack/lib/action_controller/base/layouts.rb
<ide> module ActionController
<ide> # hello world
<ide> # // The footer part of this layout
<ide> #
<del> # NOTE: The old notation for rendering the view from a layout was to expose the magic <tt>@content_for_layout</tt> instance
<del> # variable. The preferred notation now is to use <tt>yield</tt>, as documented above.
<del> #
<ide> # == Accessing shared variables
<ide> #
<ide> # Layouts have access to variables specified in the content pages and vice versa. This allows you to have layouts with | 1 |
Python | Python | add dtype conversions of inputs | cf39a723ef4cac328225fd0e3a9b83edac41c2c1 | <ide><path>numpy/core/numeric.py
<ide> def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None):
<ide> dtype = promote_types(a.dtype, b.dtype)
<ide> cp = empty(shape, dtype)
<ide>
<add> # recast arrays as dtype
<add> a = a.astype(dtype)
<add> b = b.astype(dtype)
<add>
<ide> # create local aliases for readability
<ide> a0 = a[..., 0]
<ide> a1 = a[..., 1]
<ide><path>numpy/core/tests/test_numeric.py
<ide> def test_broadcasting_shapes(self):
<ide> for axisc in range(-2, 2):
<ide> assert_equal(np.cross(u, u, axisc=axisc).shape, (3, 4))
<ide>
<add> def test_uint8_int32_mixed_dtypes(self):
<add> # regression test for gh-19138
<add> u = np.array([[195, 8, 9]], np.uint8)
<add> v = np.array([250, 166, 68], np.int32)
<add> z = np.array([[950, 11010, -30370]], dtype=np.int32)
<add> assert_equal(np.cross(v, u), z)
<add> assert_equal(np.cross(u, v), -z)
<add>
<ide>
<ide> def test_outer_out_param():
<ide> arr1 = np.ones((5,)) | 2 |
Ruby | Ruby | get brew style to pass | c7831a457d738d9723231cae77b30b1b22b39dbc | <ide><path>Library/Homebrew/test/cli_parser_spec.rb
<ide> allow(ENV).to receive(:[]).with("HOMEBREW_SWITCH_B").and_return("0")
<ide> allow(ENV).to receive(:[])
<ide> parser.parse(["--switch-b"])
<del> expect(Homebrew.args.switch_a?).to be_falsy
<del> expect(Homebrew.args.switch_b?).to be true
<add> expect(Homebrew.args.switch_a).to be_falsy
<add> expect(Homebrew.args).to be_switch_b
<ide> end
<ide>
<ide> it "raises an exception on constraint violation when both are env vars" do | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.