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
Python
Python
fix _autodiscover_tasks_from_fixups function
a9b1918ac670dd27a55f20ab37c86d8bc8454f3a
<ide><path>celery/app/base.py <ide> def _autodiscover_tasks_from_names(self, packages, related_name): <ide> def _autodiscover_tasks_from_fixups(self, related_name): <ide> return self._autodiscover_tasks_from_names([ <ide> pkg for fixup in self._fixups <del> for pkg in fixup.autodiscover_tasks() <ide> if hasattr(fixup, 'autodiscover_tasks') <add> for pkg in fixup.autodiscover_tasks() <ide> ], related_name=related_name) <ide> <ide> def send_task(self, name, args=None, kwargs=None, countdown=None,
1
Text
Text
add changelog for [ci skip]
34914c6fd7719019ad05ad6024115a91c0adc47b
<ide><path>guides/CHANGELOG.md <add>* New section in Active Record Querying: Understanding The Method Chaining <add> <add> *andreynering* <add> <ide> Please check [4-2-stable](https://github.com/rails/rails/blob/4-2-stable/guides/CHANGELOG.md) for previous changes.
1
Python
Python
fix typo in errors
7961a0a959e6860bc9b2eb9d487a77de84758ae9
<ide><path>spacy/errors.py <ide> class Errors(metaclass=ErrorsWithCodes): <ide> "components, since spans are only views of the Doc. Use Doc and " <ide> "Token attributes (or custom extension attributes) only and remove " <ide> "the following: {attrs}") <del> E181 = ("Received invalid attributes for unkown object {obj}: {attrs}. " <add> E181 = ("Received invalid attributes for unknown object {obj}: {attrs}. " <ide> "Only Doc and Token attributes are supported.") <ide> E182 = ("Received invalid attribute declaration: {attr}\nDid you forget " <ide> "to define the attribute? For example: `{attr}.???`")
1
PHP
PHP
canonicalize locale string
a895c4d995eae8d41103d2f061c9190e38ea1127
<ide><path>src/I18n/PluralRules.php <ide> namespace Cake\I18n; <ide> <ide> use Cake\Core\Exception\CakeException; <add>use Locale; <ide> <ide> /** <ide> * Utility class used to determine the plural number to be used for a variable <del> * base on the locale <add> * base on the locale. <add> * <add> * @internal <ide> */ <ide> class PluralRules <ide> { <ide> class PluralRules <ide> 'pap' => 1, <ide> 'pl' => 11, <ide> 'ps' => 1, <del> 'pt_pt' => 2, <add> 'pt_BR' => 2, <ide> 'pt' => 1, <ide> 'ro' => 12, <ide> 'ru' => 3, <ide> class PluralRules <ide> */ <ide> public static function calculate(string $locale, $n): int <ide> { <del> $locale = strtolower($locale); <add> $locale = Locale::canonicalize($locale); <ide> <ide> if (!isset(static::$_rulesMap[$locale])) { <ide> $locale = explode('_', $locale)[0]; <ide><path>tests/TestCase/I18n/PluralRulesTest.php <ide> public function localesProvider() <ide> ['en_US', 0, 1], <ide> ['en', 1, 0], <ide> ['en_UK', 2, 1], <del> ['pt_BR', 0, 1], <add> ['es-ES', 2, 1], <add> ['pt-br', 0, 0], <ide> ['pt_BR', 1, 0], <ide> ['pt_BR', 2, 1], <ide> ['pt', 0, 1], <ide> ['pt', 1, 0], <ide> ['pt', 2, 1], <del> ['pt_PT', 0, 0], <add> ['pt_PT', 0, 1], <ide> ['pt_PT', 1, 0], <ide> ['pt_PT', 2, 1], <ide> ['fr_FR', 0, 0],
2
PHP
PHP
remove unneeded table name
c18ee4917de589da78813c37a7966b450a89a10c
<ide><path>app/User.php <ide> class User extends Model implements <ide> { <ide> use Authenticatable, Authorizable, CanResetPassword; <ide> <del> /** <del> * The database table used by the model. <del> * <del> * @var string <del> */ <del> protected $table = 'users'; <del> <ide> /** <ide> * The attributes that are mass assignable. <ide> *
1
PHP
PHP
refactor the connector class
e78a5b0ad37d84778a8f26d04f58558bb713d493
<ide><path>system/db/connector.php <ide> private function connect_to_server($config) <ide> { <ide> $dsn = $config->driver.':host='.$config->host.';dbname='.$config->database; <ide> <del> if (isset($config->port)) <del> { <del> $dsn .= ';port='.$config->port; <del> } <add> if (isset($config->port)) $dsn .= ';port='.$config->port; <ide> <ide> $connection = new \PDO($dsn, $config->username, $config->password, $this->options); <ide>
1
Javascript
Javascript
keep track of charscale, wordscale and texthscale
61d517a78076ffc666b7486ace69935f312459d1
<ide><path>pdf.js <ide> var PDFDoc = (function() { <ide> return constructor; <ide> })(); <ide> <del>var IDENTITY_MATRIX = [ 1, 0, 0, 1, 0, 0 ]; <del> <del>// <canvas> contexts store most of the state we need natively. <del>// However, PDF needs a bit more state, which we store here. <del>var CanvasExtraState = (function() { <del> function constructor() { <del> // Are soft masks and alpha values shapes or opacities? <del> this.alphaIsShape = false; <del> this.fontSize = 0.0; <del> this.textMatrix = IDENTITY_MATRIX; <del> this.leading = 0.0; <del> this.colorSpace = null; <del> // Current point (in user coordinates) <del> this.x = 0.0; <del> this.y = 0.0; <del> // Start of text line (in text coordinates) <del> this.lineX = 0.0; <del> this.lineY = 0.0; <del> } <del> constructor.prototype = { <del> }; <del> return constructor; <del>})(); <del> <ide> var Encodings = { <ide> get ExpertEncoding() { <ide> return shadow(this, "ExpertEncoding", [ ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, <ide> var Encodings = { <ide> } <ide> }; <ide> <add>var IDENTITY_MATRIX = [ 1, 0, 0, 1, 0, 0 ]; <add> <add>// <canvas> contexts store most of the state we need natively. <add>// However, PDF needs a bit more state, which we store here. <add>var CanvasExtraState = (function() { <add> function constructor() { <add> // Are soft masks and alpha values shapes or opacities? <add> this.alphaIsShape = false; <add> this.fontSize = 0; <add> this.textMatrix = IDENTITY_MATRIX; <add> this.leading = 0; <add> this.colorSpace = null; <add> // Current point (in user coordinates) <add> this.x = 0; <add> this.y = 0; <add> // Start of text line (in text coordinates) <add> this.lineX = 0; <add> this.lineY = 0; <add> // Character and word spacing <add> this.charSpace = 0; <add> this.wordSpace = 0; <add> this.textHScale = 100; <add> } <add> constructor.prototype = { <add> }; <add> return constructor; <add>})(); <add> <ide> function ScratchCanvas(width, height) { <ide> var canvas = document.createElement("canvas"); <ide> canvas.width = width; <ide> var CanvasGraphics = (function() { <ide> endText: function() { <ide> }, <ide> setCharSpacing: function(spacing) { <del> TODO("character (glyph?) spacing"); <add> this.ctx.charSpacing = spacing; <ide> }, <ide> setWordSpacing: function(spacing) { <del> TODO("word spacing"); <add> this.ctx.wordSpacing = spacing; <ide> }, <ide> setHScale: function(scale) { <del> TODO("horizontal text scale"); <add> this.ctx.textHScale = (scale % 100) * 0.01; <ide> }, <ide> setLeading: function(leading) { <ide> this.current.leading = leading; <ide> var CanvasGraphics = (function() { <ide> this.moveText(0, this.current.leading); <ide> }, <ide> showText: function(text) { <add> // TODO: apply charSpacing, wordSpacing, textHScale <add> <ide> this.ctx.save(); <ide> this.ctx.transform.apply(this.ctx, this.current.textMatrix); <ide> this.ctx.scale(1, -1);
1
Python
Python
fix module path for symbolic_trace example
68a441fa4ce8786e2a19ae8856592536a9f77c3c
<ide><path>src/transformers/utils/fx.py <ide> def symbolic_trace( <ide> <ide> Example:: <ide> <del> from transformers.modeling_fx_utils import symbolic_trace <add> from transformers.utils.fx import symbolic_trace <ide> traced_model = symbolic_trace( <ide> model, <ide> input_names=["input_ids", "attention_mask", "token_type_ids"],
1
Text
Text
add readme entry
09d41a474b9e3a85976b5e00362f6072c0b24fd6
<ide><path>README.md <ide> versions of jQuery. <ide> 2. Run `npm test` to run a basic test suite or run `TEST_SUITE=all npm test` to <ide> run a more comprehensive suite. <ide> <add>## From ember-cli <add> <add>1. ember test --server <add>2. connect the browsers you want <add>3. if phantom didn't connect automatically, you can run `./bin/connect-phantom-to <optional-port>` <add>
1
Javascript
Javascript
add uuid for shader and uniforms
648a85d025925d3a57738887607454c6cde1758f
<ide><path>examples/js/nodes/NodeMaterial.js <ide> THREE.NodeMaterial = function ( vertex, fragment ) { <ide> <ide> THREE.ShaderMaterial.call( this ); <ide> <add> this.defines.UUID = THREE.Math.generateUUID(); <add> <ide> this.vertex = vertex || new THREE.RawNode( new THREE.PositionNode( THREE.PositionNode.PROJECTION ) ); <ide> this.fragment = fragment || new THREE.RawNode( new THREE.ColorNode( 0xFF0000 ) ); <ide> <ide> THREE.NodeMaterial.prototype.build = function ( params ) { <ide> <ide> this.nodes = []; <ide> <del> this.defines = {}; <add> this.defines = { UUID: this.defines.UUID }; <ide> this.uniforms = {}; <ide> this.attributes = {}; <ide> <ide> THREE.NodeMaterial.prototype.createUniform = function ( type, node, ns, needsUpd <ide> <ide> var uniform = new THREE.NodeUniform( { <ide> type: type, <del> name: ns ? ns : 'nVu' + index, <add> name: ns ? ns : 'nVu' + index + '_' + THREE.Math.generateUUID().substr(0, 8), <ide> node: node, <ide> needsUpdate: needsUpdate <ide> } );
1
Javascript
Javascript
update title meta
2959196b356822fedce1f94b5c8887e2d1f0c94c
<ide><path>client/src/components/landing/index.js <ide> export const Landing = ({ page = 'landing' }) => { <ide> return ( <ide> <Fragment> <ide> <Helmet> <del> <title>Learn to code at home | freeCodeCamp.org</title> <add> <title>Learn to Code for Free – Coding Courses for Busy People</title> <ide> </Helmet> <ide> <main className='landing-page'> <ide> <Grid> <ide><path>client/src/pages/learn.js <ide> export const LearnPage = ({ <ide> const hashValue = hashValueSelector(state, hash); <ide> return ( <ide> <LearnLayout> <del> <Helmet title='Learn to code at home | freeCodeCamp.org' /> <add> <Helmet title='Learn to Code for Free – Coding Courses for Busy People' /> <ide> <Grid> <ide> <Intro <ide> complete={complete} <ide><path>cypress/integration/landing.js <ide> const certifications = [ <ide> describe('Landing page', () => { <ide> it('Should render', () => { <ide> cy.visit('/'); <del> cy.title().should('eq', 'Learn to code at home | freeCodeCamp.org'); <add> cy.title().should( <add> 'eq', <add> 'Learn to Code for Free – Coding Courses for Busy People' <add> ); <ide> cy.contains(selectors.callToAction, "Get started (it's free)"); <ide> cy.get(selectors.callToAction).should('have.length', 2); <ide> }); <ide><path>cypress/integration/learn/index.js <ide> describe('Learn Landing page (not logged in)', () => { <ide> it('Should render', () => { <ide> cy.visit(locations.index); <ide> <del> cy.title().should('eq', 'Learn to code at home | freeCodeCamp.org'); <add> cy.title().should( <add> 'eq', <add> 'Learn to Code for Free – Coding Courses for Busy People' <add> ); <ide> }); <ide> <ide> it('Has the correct heading for an unauthenticated User', () => {
4
Javascript
Javascript
replace uimanager with stub for bridgeless rn
2ae43e5aa0c18ec8a8877e077d0975cbc043443b
<ide><path>Libraries/ReactNative/DummyUIManager.js <add>/** <add> * Copyright (c) Facebook, Inc. and its affiliates. <add> * <add> * This source code is licensed under the MIT license found in the <add> * LICENSE file in the root directory of this source tree. <add> * <add> * @flow <add> * @format <add> */ <add>'use strict'; <add> <add>module.exports = { <add> getViewManagerConfig: (viewManagerName: string) => { <add> throw new Error( <add> 'Attempting to get config for view manager ' + viewManagerName, <add> ); <add> }, <add> getConstants: () => ({}), <add> getConstantsForViewManager: (viewManagerName: string) => {}, <add> getDefaultEventTypes: () => [], <add> playTouchSound: () => {}, <add> lazilyLoadView: (name: string) => {}, <add> createView: ( <add> reactTag: ?number, <add> viewName: string, <add> rootTag: number, <add> props: Object, <add> ) => {}, <add> updateView: (reactTag: number, viewName: string, props: Object) => {}, <add> focus: (reactTag: ?number) => {}, <add> blur: (reactTag: ?number) => {}, <add> findSubviewIn: ( <add> reactTag: ?number, <add> point: Array<number>, <add> callback: ( <add> nativeViewTag: number, <add> left: number, <add> top: number, <add> width: number, <add> height: number, <add> ) => void, <add> ) => {}, <add> dispatchViewManagerCommand: ( <add> reactTag: ?number, <add> commandID: number, <add> commandArgs: ?Array<string | number | boolean>, <add> ) => {}, <add> measure: ( <add> reactTag: ?number, <add> callback: ( <add> left: number, <add> top: number, <add> width: number, <add> height: number, <add> pageX: number, <add> pageY: number, <add> ) => void, <add> ) => {}, <add> measureInWindow: ( <add> reactTag: ?number, <add> callback: (x: number, y: number, width: number, height: number) => void, <add> ) => {}, <add> viewIsDescendantOf: ( <add> reactTag: ?number, <add> ancestorReactTag: ?number, <add> callback: (result: Array<boolean>) => void, <add> ) => {}, <add> measureLayout: ( <add> reactTag: ?number, <add> ancestorReactTag: ?number, <add> errorCallback: (error: Object) => void, <add> callback: ( <add> left: number, <add> top: number, <add> width: number, <add> height: number, <add> ) => void, <add> ) => {}, <add> measureLayoutRelativeToParent: ( <add> reactTag: ?number, <add> errorCallback: (error: Object) => void, <add> callback: ( <add> left: number, <add> top: number, <add> width: number, <add> height: number, <add> ) => void, <add> ) => {}, <add> setJSResponder: (reactTag: ?number, blockNativeResponder: boolean) => {}, <add> clearJSResponder: () => {}, <add> configureNextLayoutAnimation: ( <add> config: Object, <add> callback: () => void, <add> errorCallback: (error: Object) => void, <add> ) => {}, <add> removeSubviewsFromContainerWithID: (containerID: number) => {}, <add> replaceExistingNonRootView: (reactTag: ?number, newReactTag: ?number) => {}, <add> setChildren: (containerTag: ?number, reactTags: Array<number>) => {}, <add> manageChildren: ( <add> containerTag: ?number, <add> moveFromIndices: Array<number>, <add> moveToIndices: Array<number>, <add> addChildReactTags: Array<number>, <add> addAtIndices: Array<number>, <add> removeAtIndices: Array<number>, <add> ) => {}, <add> <add> // Android only <add> setLayoutAnimationEnabledExperimental: (enabled: boolean) => {}, <add> sendAccessibilityEvent: (reactTag: ?number, eventType: number) => {}, <add> showPopupMenu: ( <add> reactTag: ?number, <add> items: Array<string>, <add> error: (error: Object) => void, <add> success: (event: string, selected?: number) => void, <add> ) => {}, <add> dismissPopupMenu: () => {}, <add>}; <ide><path>Libraries/ReactNative/PaperUIManager.js <add>/** <add> * Copyright (c) Facebook, Inc. and its affiliates. <add> * <add> * This source code is licensed under the MIT license found in the <add> * LICENSE file in the root directory of this source tree. <add> * <add> * @flow <add> * @format <add> */ <add>'use strict'; <add> <add>const NativeModules = require('../BatchedBridge/NativeModules'); <add>const Platform = require('../Utilities/Platform'); <add>const UIManagerProperties = require('./UIManagerProperties'); <add> <add>const defineLazyObjectProperty = require('../Utilities/defineLazyObjectProperty'); <add> <add>import NativeUIManager from './NativeUIManager'; <add> <add>const viewManagerConfigs = {}; <add> <add>const triedLoadingConfig = new Set(); <add> <add>let NativeUIManagerConstants = {}; <add>let isNativeUIManagerConstantsSet = false; <add>function getConstants(): Object { <add> if (!isNativeUIManagerConstantsSet) { <add> NativeUIManagerConstants = NativeUIManager.getConstants(); <add> isNativeUIManagerConstantsSet = true; <add> } <add> return NativeUIManagerConstants; <add>} <add> <add>const UIManagerJS = { <add> ...NativeUIManager, <add> getConstants(): Object { <add> return getConstants(); <add> }, <add> getViewManagerConfig: function(viewManagerName: string) { <add> if ( <add> viewManagerConfigs[viewManagerName] === undefined && <add> NativeUIManager.getConstantsForViewManager <add> ) { <add> try { <add> viewManagerConfigs[ <add> viewManagerName <add> ] = NativeUIManager.getConstantsForViewManager(viewManagerName); <add> } catch (e) { <add> viewManagerConfigs[viewManagerName] = null; <add> } <add> } <add> <add> const config = viewManagerConfigs[viewManagerName]; <add> if (config) { <add> return config; <add> } <add> <add> // If we're in the Chrome Debugger, let's not even try calling the sync <add> // method. <add> if (!global.nativeCallSyncHook) { <add> return config; <add> } <add> <add> if ( <add> NativeUIManager.lazilyLoadView && <add> !triedLoadingConfig.has(viewManagerName) <add> ) { <add> const result = NativeUIManager.lazilyLoadView(viewManagerName); <add> triedLoadingConfig.add(viewManagerName); <add> if (result.viewConfig) { <add> getConstants()[viewManagerName] = result.viewConfig; <add> lazifyViewManagerConfig(viewManagerName); <add> } <add> } <add> <add> return viewManagerConfigs[viewManagerName]; <add> }, <add>}; <add> <add>// TODO (T45220498): Remove this. <add>// 3rd party libs may be calling `NativeModules.UIManager.getViewManagerConfig()` <add>// instead of `UIManager.getViewManagerConfig()` off UIManager.js. <add>// This is a workaround for now. <add>// $FlowFixMe <add>NativeUIManager.getViewManagerConfig = UIManagerJS.getViewManagerConfig; <add> <add>function lazifyViewManagerConfig(viewName) { <add> const viewConfig = getConstants()[viewName]; <add> if (viewConfig.Manager) { <add> viewManagerConfigs[viewName] = viewConfig; <add> defineLazyObjectProperty(viewConfig, 'Constants', { <add> get: () => { <add> const viewManager = NativeModules[viewConfig.Manager]; <add> const constants = {}; <add> viewManager && <add> Object.keys(viewManager).forEach(key => { <add> const value = viewManager[key]; <add> if (typeof value !== 'function') { <add> constants[key] = value; <add> } <add> }); <add> return constants; <add> }, <add> }); <add> defineLazyObjectProperty(viewConfig, 'Commands', { <add> get: () => { <add> const viewManager = NativeModules[viewConfig.Manager]; <add> const commands = {}; <add> let index = 0; <add> viewManager && <add> Object.keys(viewManager).forEach(key => { <add> const value = viewManager[key]; <add> if (typeof value === 'function') { <add> commands[key] = index++; <add> } <add> }); <add> return commands; <add> }, <add> }); <add> } <add>} <add> <add>/** <add> * Copies the ViewManager constants and commands into UIManager. This is <add> * only needed for iOS, which puts the constants in the ViewManager <add> * namespace instead of UIManager, unlike Android. <add> */ <add>if (Platform.OS === 'ios') { <add> Object.keys(getConstants()).forEach(viewName => { <add> lazifyViewManagerConfig(viewName); <add> }); <add>} else if (getConstants().ViewManagerNames) { <add> // We want to add all the view managers to the UIManager. <add> // However, the way things are set up, the list of view managers is not known at compile time. <add> // As Prepack runs at compile it, it cannot process this loop. <add> // So we wrap it in a special __residual call, which basically tells Prepack to ignore it. <add> let residual = global.__residual <add> ? global.__residual <add> : (_, f, ...args) => f.apply(undefined, args); <add> residual( <add> 'void', <add> (UIManager, defineLazyObjectProperty) => { <add> UIManager.getConstants().ViewManagerNames.forEach(viewManagerName => { <add> defineLazyObjectProperty(UIManager, viewManagerName, { <add> get: () => UIManager.getConstantsForViewManager(viewManagerName), <add> }); <add> }); <add> }, <add> NativeUIManager, <add> defineLazyObjectProperty, <add> ); <add> <add> // As Prepack now no longer knows which properties exactly the UIManager has, <add> // we also tell Prepack that it has only partial knowledge of the UIManager, <add> // so that any accesses to unknown properties along the global code will fail <add> // when Prepack encounters them. <add> if (global.__makePartial) { <add> global.__makePartial(NativeUIManager); <add> } <add>} <add> <add>if (!global.nativeCallSyncHook) { <add> Object.keys(getConstants()).forEach(viewManagerName => { <add> if (!UIManagerProperties.includes(viewManagerName)) { <add> if (!viewManagerConfigs[viewManagerName]) { <add> viewManagerConfigs[viewManagerName] = getConstants()[viewManagerName]; <add> } <add> defineLazyObjectProperty(NativeUIManager, viewManagerName, { <add> get: () => { <add> console.warn( <add> `Accessing view manager configs directly off UIManager via UIManager['${viewManagerName}'] ` + <add> `is no longer supported. Use UIManager.getViewManagerConfig('${viewManagerName}') instead.`, <add> ); <add> <add> return UIManagerJS.getViewManagerConfig(viewManagerName); <add> }, <add> }); <add> } <add> }); <add>} <add> <add>module.exports = UIManagerJS; <ide><path>Libraries/ReactNative/UIManager.js <ide> */ <ide> 'use strict'; <ide> <del>const NativeModules = require('../BatchedBridge/NativeModules'); <del>const Platform = require('../Utilities/Platform'); <del>const UIManagerProperties = require('./UIManagerProperties'); <del> <del>const defineLazyObjectProperty = require('../Utilities/defineLazyObjectProperty'); <del> <del>import NativeUIManager from './NativeUIManager'; <ide> import type {Spec} from './NativeUIManager'; <ide> <del>const viewManagerConfigs = {}; <del> <ide> interface UIManagerJSInterface extends Spec { <ide> +getViewManagerConfig: (viewManagerName: string) => Object; <ide> // The following are not marked read-only due to logic in UIManagerStatTracker. <ide> interface UIManagerJSInterface extends Spec { <ide> ) => void; <ide> } <ide> <del>const triedLoadingConfig = new Set(); <del> <del>let NativeUIManagerConstants = {}; <del>let isNativeUIManagerConstantsSet = false; <del>function getConstants(): Object { <del> if (!isNativeUIManagerConstantsSet) { <del> NativeUIManagerConstants = NativeUIManager.getConstants(); <del> isNativeUIManagerConstantsSet = true; <del> } <del> return NativeUIManagerConstants; <del>} <del> <del>const UIManagerJS: UIManagerJSInterface = { <del> ...NativeUIManager, <del> getConstants(): Object { <del> return getConstants(); <del> }, <del> getViewManagerConfig: function(viewManagerName: string) { <del> if ( <del> viewManagerConfigs[viewManagerName] === undefined && <del> NativeUIManager.getConstantsForViewManager <del> ) { <del> try { <del> viewManagerConfigs[ <del> viewManagerName <del> ] = NativeUIManager.getConstantsForViewManager(viewManagerName); <del> } catch (e) { <del> viewManagerConfigs[viewManagerName] = null; <del> } <del> } <del> <del> const config = viewManagerConfigs[viewManagerName]; <del> if (config) { <del> return config; <del> } <del> <del> // If we're in the Chrome Debugger, let's not even try calling the sync <del> // method. <del> if (!global.nativeCallSyncHook) { <del> return config; <del> } <del> <del> if ( <del> NativeUIManager.lazilyLoadView && <del> !triedLoadingConfig.has(viewManagerName) <del> ) { <del> const result = NativeUIManager.lazilyLoadView(viewManagerName); <del> triedLoadingConfig.add(viewManagerName); <del> if (result.viewConfig) { <del> getConstants()[viewManagerName] = result.viewConfig; <del> lazifyViewManagerConfig(viewManagerName); <del> } <del> } <del> <del> return viewManagerConfigs[viewManagerName]; <del> }, <del>}; <del> <del>// TODO (T45220498): Remove this. <del>// 3rd party libs may be calling `NativeModules.UIManager.getViewManagerConfig()` <del>// instead of `UIManager.getViewManagerConfig()` off UIManager.js. <del>// This is a workaround for now. <del>// $FlowFixMe <del>NativeUIManager.getViewManagerConfig = UIManagerJS.getViewManagerConfig; <del> <del>function lazifyViewManagerConfig(viewName) { <del> const viewConfig = getConstants()[viewName]; <del> if (viewConfig.Manager) { <del> viewManagerConfigs[viewName] = viewConfig; <del> defineLazyObjectProperty(viewConfig, 'Constants', { <del> get: () => { <del> const viewManager = NativeModules[viewConfig.Manager]; <del> const constants = {}; <del> viewManager && <del> Object.keys(viewManager).forEach(key => { <del> const value = viewManager[key]; <del> if (typeof value !== 'function') { <del> constants[key] = value; <del> } <del> }); <del> return constants; <del> }, <del> }); <del> defineLazyObjectProperty(viewConfig, 'Commands', { <del> get: () => { <del> const viewManager = NativeModules[viewConfig.Manager]; <del> const commands = {}; <del> let index = 0; <del> viewManager && <del> Object.keys(viewManager).forEach(key => { <del> const value = viewManager[key]; <del> if (typeof value === 'function') { <del> commands[key] = index++; <del> } <del> }); <del> return commands; <del> }, <del> }); <del> } <del>} <del> <del>/** <del> * Copies the ViewManager constants and commands into UIManager. This is <del> * only needed for iOS, which puts the constants in the ViewManager <del> * namespace instead of UIManager, unlike Android. <del> */ <del>if (Platform.OS === 'ios') { <del> Object.keys(getConstants()).forEach(viewName => { <del> lazifyViewManagerConfig(viewName); <del> }); <del>} else if (getConstants().ViewManagerNames) { <del> // We want to add all the view managers to the UIManager. <del> // However, the way things are set up, the list of view managers is not known at compile time. <del> // As Prepack runs at compile it, it cannot process this loop. <del> // So we wrap it in a special __residual call, which basically tells Prepack to ignore it. <del> let residual = global.__residual <del> ? global.__residual <del> : (_, f, ...args) => f.apply(undefined, args); <del> residual( <del> 'void', <del> (UIManager, defineLazyObjectProperty) => { <del> UIManager.getConstants().ViewManagerNames.forEach(viewManagerName => { <del> defineLazyObjectProperty(UIManager, viewManagerName, { <del> get: () => UIManager.getConstantsForViewManager(viewManagerName), <del> }); <del> }); <del> }, <del> NativeUIManager, <del> defineLazyObjectProperty, <del> ); <del> <del> // As Prepack now no longer knows which properties exactly the UIManager has, <del> // we also tell Prepack that it has only partial knowledge of the UIManager, <del> // so that any accesses to unknown properties along the global code will fail <del> // when Prepack encounters them. <del> if (global.__makePartial) { <del> global.__makePartial(NativeUIManager); <del> } <del>} <del> <del>if (!global.nativeCallSyncHook) { <del> Object.keys(getConstants()).forEach(viewManagerName => { <del> if (!UIManagerProperties.includes(viewManagerName)) { <del> if (!viewManagerConfigs[viewManagerName]) { <del> viewManagerConfigs[viewManagerName] = getConstants()[viewManagerName]; <del> } <del> defineLazyObjectProperty(NativeUIManager, viewManagerName, { <del> get: () => { <del> console.warn( <del> `Accessing view manager configs directly off UIManager via UIManager['${viewManagerName}'] ` + <del> `is no longer supported. Use UIManager.getViewManagerConfig('${viewManagerName}') instead.`, <del> ); <del> <del> return UIManagerJS.getViewManagerConfig(viewManagerName); <del> }, <del> }); <del> } <del> }); <del>} <add>const UIManager: UIManagerJSInterface = <add> global.RN$Bridgeless === true <add> ? require('./DummyUIManager') // No UIManager in bridgeless mode <add> : require('./PaperUIManager'); <ide> <del>module.exports = UIManagerJS; <add>module.exports = UIManager;
3
Text
Text
update the complementary color section
06111e2eaf8bee5c96ad4d46d1a4e6a28af74684
<ide><path>guide/english/visual-design/color-theory/index.md <ide> successful a product is. <ide> <ide> **Complementary Colors:** <ide> Red-green, yellow-purple, blue-orange <del>These are colors formed by mixing colors that are oppsite from each other on the color wheel. <add>These are colors formed by mixing colors that are opposite from each other on the color wheel. <add>When chosing to work with complementary colors, the ratio between them is very important. While a 50 50 ratio could work for the red and green pair, it would produce unpleasing results in a yellow purple pair. <add> <add>The basic complementary ratios are: <add>``` <add>Red-Green : 50% 50% <add>Orange-Blue : 30% 70% <add>Yellow-Purple : 10% 90% <add>``` <ide> <ide> In web design, colors also carry with them connotations and implications that need to be understood or else you could cause confusion. The color red in a non-digital space, such as a fast-food restaurant, carries the implication of energy or excitement. However, on the web the color red also carries with it the implication that the user has committed an error. This example of how color means certain things in certain settings should be a critical reminder to understand how the person viewing your page will interpret the color selection you’ve made. <ide>
1
PHP
PHP
fix closure problem
07de62a58b7133165d5df6a2da5ef7902a3f28fd
<ide><path>src/Illuminate/View/Compilers/BladeCompiler.php <ide> protected function compileRegularEchos($value) <ide> <ide> $callback = function($matches) use ($me) <ide> { <del> return $matches[1] ? substr($matches[0], 1) : '<?php echo '.$this->compileEchoDefaults($matches[2]).'; ?>'; <add> return $matches[1] ? substr($matches[0], 1) : '<?php echo '.$me->compileEchoDefaults($matches[2]).'; ?>'; <ide> }; <ide> <ide> return preg_replace_callback($pattern, $callback, $value);
1
Python
Python
improve error messages in convolutional.py
a4aeb3755594d0c0796c23eb60d9536760c4ce24
<ide><path>keras/layers/convolutional.py <ide> def __init__(self, <ide> filters = int(filters) <ide> if filters is not None and filters < 0: <ide> raise ValueError(f'Received a negative value for `filters`.' <del> f'Was expecting a positive value, got {filters}.') <add> f'Was expecting a positive value. Received {filters}.') <ide> self.filters = filters <ide> self.groups = groups or 1 <ide> self.kernel_size = conv_utils.normalize_tuple( <ide> def _get_channel_axis(self): <ide> def _get_input_channel(self, input_shape): <ide> channel_axis = self._get_channel_axis() <ide> if input_shape.dims[channel_axis].value is None: <del> raise ValueError('The channel dimension of the inputs ' <del> 'should be defined. Found `None`.') <add> raise ValueError('The channel dimension of the inputs should be defined. ' <add> f'The input_shape received is {input_shape}, ' <add> f'where axis {channel_axis} (0-based) ' <add> 'is the channel dimension, which found to be `None`.') <ide> return int(input_shape[channel_axis]) <ide> <ide> def _get_padding_op(self): <ide> def __init__(self, <ide> self.output_padding, 1, 'output_padding') <ide> for stride, out_pad in zip(self.strides, self.output_padding): <ide> if out_pad >= stride: <del> raise ValueError('Stride ' + str(self.strides) + ' must be ' <del> 'greater than output padding ' + <del> str(self.output_padding)) <add> raise ValueError('Strides must be greater than output padding. ' <add> f'Received strides={self.strides}, ' <add> f'output_padding={self.output_padding}.') <ide> <ide> def build(self, input_shape): <ide> input_shape = tf.TensorShape(input_shape) <ide> if len(input_shape) != 3: <del> raise ValueError('Inputs should have rank 3. Received input shape: ' + <del> str(input_shape)) <add> raise ValueError('Inputs should have rank 3. ' <add> f'Received input_shape={input_shape}.') <ide> channel_axis = self._get_channel_axis() <ide> if input_shape.dims[channel_axis].value is None: <ide> raise ValueError('The channel dimension of the inputs ' <del> 'should be defined. Found `None`.') <add> 'to `Conv1DTranspose` should be defined. ' <add> f'The input_shape received is {input_shape}, ' <add> f'where axis {channel_axis} (0-based) ' <add> 'is the channel dimension, which found to be `None`.') <ide> input_dim = int(input_shape[channel_axis]) <ide> self.input_spec = InputSpec(ndim=3, axes={channel_axis: input_dim}) <ide> kernel_shape = self.kernel_size + (self.filters, input_dim) <ide> def __init__(self, <ide> self.output_padding, 2, 'output_padding') <ide> for stride, out_pad in zip(self.strides, self.output_padding): <ide> if out_pad >= stride: <del> raise ValueError('Stride ' + str(self.strides) + ' must be ' <del> 'greater than output padding ' + <del> str(self.output_padding)) <add> raise ValueError('Strides must be greater than output padding. ' <add> f'Received strides={self.strides}, ' <add> f'output_padding={self.output_padding}.') <ide> <ide> def build(self, input_shape): <ide> input_shape = tf.TensorShape(input_shape) <ide> if len(input_shape) != 4: <del> raise ValueError('Inputs should have rank 4. Received input ' <del> 'shape: ' + str(input_shape)) <add> raise ValueError('Inputs should have rank 4. ' <add> f'Received input_shape={input_shape}.') <ide> channel_axis = self._get_channel_axis() <ide> if input_shape.dims[channel_axis].value is None: <ide> raise ValueError('The channel dimension of the inputs ' <del> 'should be defined. Found `None`.') <add> 'to `Conv2DTranspose` should be defined. ' <add> f'The input_shape received is {input_shape}, ' <add> f'where axis {channel_axis} (0-based) ' <add> 'is the channel dimension, which found to be `None`.') <ide> input_dim = int(input_shape[channel_axis]) <ide> self.input_spec = InputSpec(ndim=4, axes={channel_axis: input_dim}) <ide> kernel_shape = self.kernel_size + (self.filters, input_dim) <ide> def __init__(self, <ide> self.output_padding, 3, 'output_padding') <ide> for stride, out_pad in zip(self.strides, self.output_padding): <ide> if out_pad >= stride: <del> raise ValueError('Stride ' + str(self.strides) + ' must be ' <del> 'greater than output padding ' + <del> str(self.output_padding)) <add> raise ValueError('Strides must be greater than output padding. ' <add> f'Received strides={self.strides}, ' <add> f'output_padding={self.output_padding}.') <ide> <ide> def build(self, input_shape): <ide> input_shape = tf.TensorShape(input_shape) <ide> if len(input_shape) != 5: <del> raise ValueError('Inputs should have rank 5, received input shape:', <del> str(input_shape)) <add> raise ValueError('Inputs should have rank 5. ' <add> f'Received input_shape={input_shape}.') <ide> channel_axis = self._get_channel_axis() <ide> if input_shape.dims[channel_axis].value is None: <ide> raise ValueError('The channel dimension of the inputs ' <del> 'should be defined, found None: ' + str(input_shape)) <add> 'to `Conv3DTranspose` should be defined. ' <add> f'The input_shape received is {input_shape}, ' <add> f'where axis {channel_axis} (0-based) ' <add> 'is the channel dimension, which found to be `None`.') <ide> input_dim = int(input_shape[channel_axis]) <ide> kernel_shape = self.kernel_size + (self.filters, input_dim) <ide> self.input_spec = InputSpec(ndim=5, axes={channel_axis: input_dim}) <ide> def build(self, input_shape): <ide> input_shape = tf.TensorShape(input_shape) <ide> channel_axis = self._get_channel_axis() <ide> if input_shape.dims[channel_axis].value is None: <del> raise ValueError('The channel dimension of the inputs ' <del> 'should be defined. Found `None`.') <add> raise ValueError('The channel dimension of the inputs should be defined. ' <add> f'The input_shape received is {input_shape}, ' <add> f'where axis {channel_axis} (0-based) ' <add> 'is the channel dimension, which found to be `None`.') <ide> input_dim = int(input_shape[channel_axis]) <ide> self.input_spec = InputSpec(ndim=self.rank + 2, <ide> axes={channel_axis: input_dim}) <ide> def __init__(self, <ide> <ide> def build(self, input_shape): <ide> if len(input_shape) != self.rank + 2: <del> raise ValueError('Inputs to `DepthwiseConv` should have rank ', <del> str(self.rank + 2), '. ', 'Received input shape:', <del> str(input_shape)) <add> raise ValueError('Inputs to `DepthwiseConv` should have ' <add> f'rank {self.rank + 2}. ' <add> f'Received input_shape={input_shape}.') <ide> input_shape = tf.TensorShape(input_shape) <ide> channel_axis = self._get_channel_axis() <ide> if input_shape.dims[channel_axis].value is None: <del> raise ValueError('The channel dimension of the inputs to ' <del> '`DepthwiseConv` ' <del> 'should be defined. Found `None`.') <add> raise ValueError('The channel dimension of the inputs to `DepthwiseConv` ' <add> 'should be defined. ' <add> f'The input_shape received is {input_shape}, ' <add> f'where axis {channel_axis} (0-based) ' <add> 'is the channel dimension, which found to be `None`.') <ide> input_dim = int(input_shape[channel_axis]) <ide> depthwise_kernel_shape = self.kernel_size + (input_dim, <ide> self.depth_multiplier) <ide> def __init__(self, <ide> self.size = conv_utils.normalize_tuple(size, 2, 'size') <ide> if interpolation not in {'nearest', 'bilinear'}: <ide> raise ValueError('`interpolation` argument should be one of `"nearest"` ' <del> 'or `"bilinear"`.') <add> f'or `"bilinear"`. Received: "{interpolation}".') <ide> self.interpolation = interpolation <ide> self.input_spec = InputSpec(ndim=4) <ide> <ide> def __init__(self, padding=(1, 1), data_format=None, **kwargs): <ide> elif hasattr(padding, '__len__'): <ide> if len(padding) != 2: <ide> raise ValueError('`padding` should have two elements. ' <del> 'Found: ' + str(padding)) <add> f'Received: {padding}.') <ide> height_padding = conv_utils.normalize_tuple(padding[0], 2, <ide> '1st entry of padding') <ide> width_padding = conv_utils.normalize_tuple(padding[1], 2, <ide> def __init__(self, padding=(1, 1), data_format=None, **kwargs): <ide> '(symmetric_height_pad, symmetric_width_pad), ' <ide> 'or a tuple of 2 tuples of 2 ints ' <ide> '((top_pad, bottom_pad), (left_pad, right_pad)). ' <del> 'Found: ' + str(padding)) <add> f'Received: {padding}.') <ide> self.input_spec = InputSpec(ndim=4) <ide> <ide> def compute_output_shape(self, input_shape): <ide> def __init__(self, padding=(1, 1, 1), data_format=None, **kwargs): <ide> elif hasattr(padding, '__len__'): <ide> if len(padding) != 3: <ide> raise ValueError('`padding` should have 3 elements. ' <del> 'Found: ' + str(padding)) <add> f'Received: {padding}.') <ide> dim1_padding = conv_utils.normalize_tuple(padding[0], 2, <ide> '1st entry of padding') <ide> dim2_padding = conv_utils.normalize_tuple(padding[1], 2, <ide> def __init__(self, padding=(1, 1, 1), data_format=None, **kwargs): <ide> '((left_dim1_pad, right_dim1_pad),' <ide> ' (left_dim2_pad, right_dim2_pad),' <ide> ' (left_dim3_pad, right_dim2_pad)). ' <del> 'Found: ' + str(padding)) <add> f'Received: {padding}.') <ide> self.input_spec = InputSpec(ndim=5) <ide> <ide> def compute_output_shape(self, input_shape): <ide> def __init__(self, cropping=((0, 0), (0, 0)), data_format=None, **kwargs): <ide> elif hasattr(cropping, '__len__'): <ide> if len(cropping) != 2: <ide> raise ValueError('`cropping` should have two elements. ' <del> 'Found: ' + str(cropping)) <add> f'Received: {cropping}.') <ide> height_cropping = conv_utils.normalize_tuple(cropping[0], 2, <ide> '1st entry of cropping') <ide> width_cropping = conv_utils.normalize_tuple(cropping[1], 2, <ide> def __init__(self, cropping=((0, 0), (0, 0)), data_format=None, **kwargs): <ide> '(symmetric_height_crop, symmetric_width_crop), ' <ide> 'or a tuple of 2 tuples of 2 ints ' <ide> '((top_crop, bottom_crop), (left_crop, right_crop)). ' <del> 'Found: ' + str(cropping)) <add> f'Received: {cropping}.') <ide> self.input_spec = InputSpec(ndim=4) <ide> <ide> def compute_output_shape(self, input_shape): <ide> def __init__(self, <ide> elif hasattr(cropping, '__len__'): <ide> if len(cropping) != 3: <ide> raise ValueError('`cropping` should have 3 elements. ' <del> 'Found: ' + str(cropping)) <add> f'Received: {cropping}.') <ide> dim1_cropping = conv_utils.normalize_tuple(cropping[0], 2, <ide> '1st entry of cropping') <ide> dim2_cropping = conv_utils.normalize_tuple(cropping[1], 2, <ide> def __init__(self, <ide> '((left_dim1_crop, right_dim1_crop),' <ide> ' (left_dim2_crop, right_dim2_crop),' <ide> ' (left_dim3_crop, right_dim2_crop)). ' <del> 'Found: ' + str(cropping)) <add> f'Received: {cropping}.') <ide> self.input_spec = InputSpec(ndim=5) <ide> <ide> def compute_output_shape(self, input_shape): <ide><path>keras/legacy_tf_layers/convolutional_test.py <ide> def testUnknownInputChannels(self): <ide> layer = conv_layers.Conv2D(32, [3, 3], activation=tf.nn.relu) <ide> with self.assertRaisesRegex( <ide> ValueError, 'The channel dimension of the inputs ' <del> 'should be defined. Found `None`.'): <add> 'should be defined. The input_shape received is'): <ide> _ = layer.apply(images) <ide> <ide> images = tf.compat.v1.placeholder(tf.float32, (5, None, 7, 9)) <ide> layer = conv_layers.Conv2D(32, [3, 3], data_format='channels_first') <ide> with self.assertRaisesRegex( <ide> ValueError, 'The channel dimension of the inputs ' <del> 'should be defined. Found `None`.'): <add> 'should be defined. The input_shape received is'): <ide> _ = layer.apply(images) <ide> <ide> def testConv2DPaddingSame(self): <ide> def testUnknownInputChannelsConv1D(self): <ide> layer = conv_layers.Conv1D(32, 3, activation=tf.nn.relu) <ide> with self.assertRaisesRegex( <ide> ValueError, 'The channel dimension of the inputs ' <del> 'should be defined. Found `None`.'): <add> 'should be defined. The input_shape received is'): <ide> _ = layer.apply(data) <ide> <ide> data = tf.compat.v1.placeholder(tf.float32, (5, None, 4)) <ide> layer = conv_layers.Conv1D(32, 3, data_format='channels_first') <ide> with self.assertRaisesRegex( <ide> ValueError, 'The channel dimension of the inputs ' <del> 'should be defined. Found `None`.'): <add> 'should be defined. The input_shape received is'): <ide> _ = layer.apply(data) <ide> <ide> def testCreateConv3D(self): <ide> def testUnknownInputChannelsConv3D(self): <ide> layer = conv_layers.Conv3D(32, [3, 3, 3], activation=tf.nn.relu) <ide> with self.assertRaisesRegex( <ide> ValueError, 'The channel dimension of the inputs ' <del> 'should be defined. Found `None`.'): <add> 'should be defined. The input_shape received is'): <ide> _ = layer.apply(volumes) <ide> <ide> def testConv2DKernelRegularizer(self):
2
Ruby
Ruby
provide a better location in 'odeprecated'
0a33cc591d258e07f2279bc0440d62e38983fd67
<ide><path>Library/Homebrew/utils.rb <ide> def odeprecated(method, replacement = nil, options = {}) <ide> "There is no replacement." <ide> end <ide> <del> # Show the first location that's not in compat. <del> backtrace = options[:caller] || caller <del> caller_message = backtrace[1] <add> # Try to show the most relevant location in message, i.e. (if applicable): <add> # - Location in a formula. <add> # - Location outside of 'compat/'. <add> # - Location of caller of deprecated method (if all else fails). <add> backtrace = options.fetch(:caller, caller) <add> caller_message = backtrace.detect do |line| <add> line.start_with?("#{HOMEBREW_LIBRARY}/Taps/") <add> end <add> caller_message ||= backtrace.detect do |line| <add> !line.start_with?("#{HOMEBREW_LIBRARY_PATH}/compat/") <add> end <add> caller_message ||= backtrace[1] <ide> <ide> message = <<-EOS.undent <ide> Calling #{method} is #{verb}! <ide> def odeprecated(method, replacement = nil, options = {}) <ide> EOS <ide> <ide> if ARGV.homebrew_developer? || options[:die] <del> raise FormulaMethodDeprecatedError.new message <add> raise FormulaMethodDeprecatedError, message <ide> else <ide> opoo "#{message}\n" <ide> end
1
PHP
PHP
clarify doc blocks
39fdafbde5f8a12c9b97c7afd481d26fa8ae50e2
<ide><path>src/Collection/CollectionInterface.php <ide> public function listNested($dir = 'desc', $nestingKey = 'children'); <ide> public function stopWhen($condition); <ide> <ide> /** <del> * Creates a new collection where the items that it will contain are the <add> * Creates a new collection where the items are the <ide> * concatenation of the lists of items generated by the transformer function <del> * after passing each of the items form the original collection. <add> * applied to each item in the original collection. <ide> * <ide> * The transformer function will receive the value and the key for each of the <ide> * items in the collection, in that order, and it must return an array or a <del> * Traversable object so that it can be concatenated to the final result. <add> * Traversable object that can be concatenated to the final result. <ide> * <ide> * If no transformer function is passed, an "identity" function will be used. <ide> * This is useful when each of the elements in the source collection are <ide><path>src/Collection/Iterator/UnfoldIterator.php <ide> use RecursiveIterator; <ide> <ide> /** <del> * An iterator that can be used to generate nested iterators out of each of <del> * applying an function to each of the elements in this iterator. <add> * An iterator that can be used to generate nested iterators out of a collection <add> * of items by applying an function to each of the elements in this iterator. <ide> * <ide> * @internal <ide> * @see Collection::unfold()
2
Java
Java
add marbles for single.concat operator
bb939111a026a12880a1e9b75c5579c366177fe0
<ide><path>src/main/java/io/reactivex/Single.java <ide> public static <T> Single<T> ambArray(final SingleSource<? extends T>... sources) <ide> /** <ide> * Concatenate the single values, in a non-overlapping fashion, of the SingleSources provided by <ide> * an Iterable sequence. <add> * <p> <add> * <img width="640" height="319" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.concat.i.png" alt=""> <ide> * <dl> <ide> * <dt><b>Backpressure:</b></dt> <ide> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer.</dd> <ide> public static <T> Flowable<T> concat(Iterable<? extends SingleSource<? extends T <ide> /** <ide> * Concatenate the single values, in a non-overlapping fashion, of the SingleSources provided by <ide> * an Observable sequence. <add> * <p> <add> * <img width="640" height="319" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.concat.o.png" alt=""> <ide> * <dl> <ide> * <dt><b>Scheduler:</b></dt> <ide> * <dd>{@code concat} does not operate by default on a particular {@link Scheduler}.</dd> <ide> public static <T> Observable<T> concat(ObservableSource<? extends SingleSource<? <ide> /** <ide> * Concatenate the single values, in a non-overlapping fashion, of the SingleSources provided by <ide> * a Publisher sequence. <add> * <p> <add> * <img width="640" height="308" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.concat.p.png" alt=""> <ide> * <dl> <ide> * <dt><b>Backpressure:</b></dt> <ide> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer <ide> public static <T> Flowable<T> concat(Publisher<? extends SingleSource<? extends <ide> /** <ide> * Concatenate the single values, in a non-overlapping fashion, of the SingleSources provided by <ide> * a Publisher sequence and prefetched by the specified amount. <add> * <p> <add> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.concat.pn.png" alt=""> <ide> * <dl> <ide> * <dt><b>Backpressure:</b></dt> <ide> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer <ide> public static <T> Flowable<T> concat(Publisher<? extends SingleSource<? extends <ide> /** <ide> * Returns a Flowable that emits the items emitted by two Singles, one after the other. <ide> * <p> <del> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.concat.png" alt=""> <add> * <img width="640" height="366" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.concat.png" alt=""> <ide> * <dl> <ide> * <dt><b>Backpressure:</b></dt> <ide> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer.</dd> <ide> public static <T> Flowable<T> concat( <ide> /** <ide> * Returns a Flowable that emits the items emitted by three Singles, one after the other. <ide> * <p> <del> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.concat.png" alt=""> <add> * <img width="640" height="366" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.concat.o3.png" alt=""> <ide> * <dl> <ide> * <dt><b>Backpressure:</b></dt> <ide> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer.</dd> <ide> public static <T> Flowable<T> concat( <ide> /** <ide> * Returns a Flowable that emits the items emitted by four Singles, one after the other. <ide> * <p> <del> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.concat.png" alt=""> <add> * <img width="640" height="362" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.concat.o4.png" alt=""> <ide> * <dl> <ide> * <dt><b>Backpressure:</b></dt> <ide> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer.</dd> <ide> public static <T> Flowable<T> concat( <ide> /** <ide> * Concatenate the single values, in a non-overlapping fashion, of the SingleSources provided in <ide> * an array. <add> * <p> <add> * <img width="640" height="319" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.concatArray.png" alt=""> <ide> * <dl> <ide> * <dt><b>Backpressure:</b></dt> <ide> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer.</dd>
1
Mixed
Python
extend example to ensure the text is preserved
bb9d2f15466ba32e221ec7138cfb30c1f0aabad6
<ide><path>spacy/tests/test_language.py <ide> def __init__(self, vocab): <ide> self.vocab = vocab <ide> <ide> def __call__(self, text): <del> words = text.split() <del> return Doc(self.vocab, words=words) <add> words = text.split(" ") <add> spaces = [True] * len(words) <add> # Avoid zero-length tokens <add> for i, word in enumerate(words): <add> if word == "": <add> words[i] = " " <add> spaces[i] = False <add> # Remove the final trailing space <add> if words[-1] == " ": <add> words = words[0:-1] <add> spaces = spaces[0:-1] <add> else: <add> spaces[-1] = False <add> <add> return Doc(self.vocab, words=words, spaces=spaces) <ide> <ide> nlp = spacy.blank("en") <ide> nlp.tokenizer = WhitespaceTokenizer(nlp.vocab) <del> doc = nlp("What's happened to me? he thought. It wasn't a dream. ") <del> assert doc <add> text = " What's happened to me? he thought. It wasn't a dream. " <add> doc = nlp(text) <add> assert doc.text == text <ide> <ide> <ide> def test_language_custom_tokenizer(): <ide><path>website/docs/usage/linguistic-features.md <ide> class WhitespaceTokenizer: <ide> self.vocab = vocab <ide> <ide> def __call__(self, text): <del> words = text.split() <del> return Doc(self.vocab, words=words) <add> words = text.split(" ") <add> spaces = [True] * len(words) <add> # Avoid zero-length tokens <add> for i, word in enumerate(words): <add> if word == "": <add> words[i] = " " <add> spaces[i] = False <add> # Remove the final trailing space <add> if words[-1] == " ": <add> words = words[0:-1] <add> spaces = spaces[0:-1] <add> else: <add> spaces[-1] = False <add> <add> return Doc(self.vocab, words=words, spaces=spaces) <ide> <ide> nlp = spacy.blank("en") <ide> nlp.tokenizer = WhitespaceTokenizer(nlp.vocab)
2
Java
Java
simplify aot contribution for scoped proxies
affccba8f1beccdb5910e4a0e909701d33255db5
<ide><path>spring-aop/src/main/java/org/springframework/aop/scope/ScopedProxyBeanRegistrationAotProcessor.java <ide> public CodeBlock generateInstanceSupplierCode(GenerationContext generationContex <ide> <ide> GeneratedMethod generatedMethod = beanRegistrationCode.getMethods() <ide> .add("getScopedProxyInstance", method -> { <del> Class<?> beanClass = this.targetBeanDefinition.getResolvableType() <del> .toClass(); <ide> method.addJavadoc( <ide> "Create the scoped proxy bean instance for '$L'.", <ide> this.registeredBean.getBeanName()); <ide> method.addModifiers(Modifier.PRIVATE, Modifier.STATIC); <del> method.returns(beanClass); <add> method.returns(ScopedProxyFactoryBean.class); <ide> method.addParameter(RegisteredBean.class, <ide> REGISTERED_BEAN_PARAMETER_NAME); <ide> method.addStatement("$T factory = new $T()", <ide> public CodeBlock generateInstanceSupplierCode(GenerationContext generationContex <ide> method.addStatement( <ide> "factory.setBeanFactory($L.getBeanFactory())", <ide> REGISTERED_BEAN_PARAMETER_NAME); <del> method.addStatement("return ($T) factory.getObject()", <del> beanClass); <add> method.addStatement("return factory"); <ide> }); <ide> return CodeBlock.of("$T.of($L)", InstanceSupplier.class, <ide> generatedMethod.toMethodReference().toCodeBlock());
1
Ruby
Ruby
use object id as the weak ref key
d6edefb5a7c1ad56c464ce5ca273a2db736e7b6e
<ide><path>lib/arel/session.rb <ide> def create(insert) <ide> end <ide> <ide> def read(select) <del> (@read ||= Hash.new do |hash, x| <del> hash[x] = x.call <del> end)[select] <add> @read ||= {} <add> key = select.object_id <add> return @read[key] if @read.key? key <add> @read[key] = select.call <ide> end <ide> <ide> def update(update)
1
Text
Text
add note on origin of manually moved agreement
e7b78370d99a59a80119ae1641b97ebbbb60088b
<ide><path>.github/contributors/shuvanon.md <add><!-- This agreement was mistakenly submitted as an update to the CONTRIBUTOR_AGREEMENT.md template. Commit: 8a2d22222dec5cf910df5a378cbcd9ea2ab53ec4. It was therefore moved over manually. --> <add> <ide> # spaCy contributor agreement <ide> <ide> This spaCy Contributor Agreement (**"SCA"**) is based on the
1
Ruby
Ruby
move all the "order by" together
3cbafe833b5c388403cd78c3bcb278850733d032
<ide><path>lib/arel/visitors/mssql.rb <ide> def visit_Arel_Nodes_SelectStatement o <ide> return super o <ide> end <ide> <del> select_order_by = "ORDER BY #{o.orders.map { |x| visit x }.join(', ')}" unless o.orders.empty? <del> <ide> is_select_count = false <ide> sql = o.cores.map { |x| <del> core_order_by = select_order_by || determine_order_by(x) <add> core_order_by = determine_order_by(o.orders, x) <ide> if select_count? x <ide> x.projections = [row_num_literal(core_order_by)] <ide> is_select_count = true <ide> def get_offset_limit_clause o <ide> end <ide> end <ide> <del> def determine_order_by x <del> if x.groups.any? <del> "ORDER BY #{x.groups.map { |g| visit g }.join ', ' }" <add> def determine_order_by orders, x <add> if orders.any? <add> "ORDER BY #{orders.map { |x| visit x }.join(', ')}" <ide> else <del> "ORDER BY #{find_left_table_pk(x.froms)}" <add> if x.groups.any? <add> "ORDER BY #{x.groups.map { |g| visit g }.join ', ' }" <add> else <add> "ORDER BY #{find_left_table_pk(x.froms)}" <add> end <ide> end <ide> end <ide>
1
Python
Python
use absl app
4c6181f1040f0e2b208d03ca48a7be49dfcff6e7
<ide><path>official/nlp/transformer/data_download.py <ide> import tarfile <ide> <ide> # pylint: disable=g-bad-import-order <del>from absl import app as absl_app <add>from absl import app <ide> from absl import flags <ide> from absl import logging <ide> import six <ide> def define_data_download_flags(): <ide> logging.set_verbosity(logging.INFO) <ide> define_data_download_flags() <ide> FLAGS = flags.FLAGS <del> tf.app.run(main) <add> app.run(main)
1
PHP
PHP
move middleware into more relevant packages
4de7bae59b3d7f622c023cfe75115062049cc855
<add><path>src/Error/Middleware/ErrorHandlerMiddleware.php <del><path>src/Http/Middleware/ErrorHandlerMiddleware.php <ide> * @since 3.3.0 <ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License <ide> */ <del>namespace Cake\Http\Middleware; <add>namespace Cake\Error\Middleware; <ide> <ide> use Cake\Core\App; <ide> use Cake\Http\ResponseTransformer; <add><path>src/Routing/Middleware/RoutingMiddleware.php <del><path>src/Http/Middleware/RoutingMiddleware.php <ide> * @since 3.3.0 <ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License <ide> */ <del>namespace Cake\Http\Middleware; <add>namespace Cake\Routing\Middleware; <ide> <ide> use Cake\Routing\Exception\RedirectException; <ide> use Cake\Routing\Router; <add><path>tests/TestCase/Error/Middleware/ErrorHandlerMiddlewareTest.php <del><path>tests/TestCase/Http/Middleware/ErrorHandlerMiddlewareTest.php <ide> * @since 3.3.0 <ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License <ide> */ <del>namespace Cake\Test\TestCase\Http\Middleware; <add>namespace Cake\Test\TestCase\Error\Middleware; <ide> <ide> use Cake\Core\Configure; <del>use Cake\Http\Middleware\ErrorHandlerMiddleware; <add>use Cake\Error\Middleware\ErrorHandlerMiddleware; <ide> use Cake\Http\ServerRequestFactory; <ide> use Cake\Network\Response as CakeResponse; <ide> use Cake\TestSuite\TestCase; <add><path>tests/TestCase/Routing/Middleware/RoutingMiddlewareTest.php <del><path>tests/TestCase/Http/Middleware/RoutingMiddlewareTest.php <ide> * @since 3.3.0 <ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License <ide> */ <del>namespace Cake\Test\TestCase\Http\Middleware; <add>namespace Cake\Test\TestCase\Routing\Middleware; <ide> <del>use Cake\Http\Middleware\RoutingMiddleware; <add>use Cake\Routing\Middleware\RoutingMiddleware; <ide> use Cake\Routing\Router; <ide> use Cake\TestSuite\TestCase; <ide> use Zend\Diactoros\Request;
4
Ruby
Ruby
update mysql for new exec_insert signature
3475051f7ff8d29eb779618c8f06e725b3889698
<ide><path>activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb <ide> def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) <ide> end <ide> alias :create :insert_sql <ide> <del> def exec_insert(sql, name, binds) <add> def exec_insert(sql, name, binds, pk = nil, sequence_name = nil) <ide> execute to_sql(sql, binds), name <ide> end <ide>
1
Python
Python
remove unused variable
f053fd80643910501bd5311d87f3f3a3d1892223
<ide><path>libcloud/container/drivers/kubernetes.py <ide> def _to_node(self, data): <ide> ID = data["metadata"]["uid"] <ide> name = data["metadata"]["name"] <ide> driver = self.connection.driver <del> namespace = "undefined" <ide> memory = data["status"].get("capacity", {}).get("memory", "0K") <ide> cpu = data["status"].get("capacity", {}).get("cpu", "1") <ide> if isinstance(cpu, str) and not cpu.isnumeric():
1
PHP
PHP
terminate the request after sending
46d1a27b772612a95147e56dd20b29175e8ab845
<ide><path>public/index.php <ide> | <ide> */ <ide> <del>$response = $app->make('Illuminate\Contracts\Http\Kernel')->handle( <del> Illuminate\Http\Request::capture() <add>$kernel = $app->make('Illuminate\Contracts\Http\Kernel'); <add> <add>$response = $kernel->handle( <add> $request = Illuminate\Http\Request::capture() <ide> ); <ide> <ide> $response->send(); <add> <add>$kernel->terminate($request, $response);
1
Go
Go
add unit test to daemon.searchregistryforimages…
636c276f67b3cd96a95dec2f6cfc419b7f219892
<ide><path>api/client/run.go <ide> func (cli *DockerCli) CmdRun(args ...string) error { <ide> } <ide> <ide> //start the container <del> if err := cli.client.ContainerStart(ctx, createResponse.ID); err != nil { <add> if err := cli.client.ContainerStart(ctx, createResponse.ID, ""); err != nil { <ide> // If we have holdHijackedConnection, we should notify <ide> // holdHijackedConnection we are going to exit and wait <ide> // to avoid the terminal are not restored. <ide><path>api/client/start.go <ide> func (cli *DockerCli) CmdStart(args ...string) error { <ide> }) <ide> <ide> // 3. Start the container. <del> if err := cli.client.ContainerStart(ctx, container); err != nil { <add> if err := cli.client.ContainerStart(ctx, container, ""); err != nil { <ide> cancelFun() <ide> <-cErr <ide> return err <ide> func (cli *DockerCli) CmdStart(args ...string) error { <ide> func (cli *DockerCli) startContainersWithoutAttachments(ctx context.Context, containers []string) error { <ide> var failedContainers []string <ide> for _, container := range containers { <del> if err := cli.client.ContainerStart(ctx, container); err != nil { <add> if err := cli.client.ContainerStart(ctx, container, ""); err != nil { <ide> fmt.Fprintf(cli.err, "%s\n", err) <ide> failedContainers = append(failedContainers, container) <ide> } else { <ide><path>daemon/daemon.go <ide> import ( <ide> "path/filepath" <ide> "regexp" <ide> "runtime" <del> "strconv" <ide> "strings" <ide> "sync" <ide> "syscall" <ide> import ( <ide> "github.com/docker/engine-api/types" <ide> containertypes "github.com/docker/engine-api/types/container" <ide> networktypes "github.com/docker/engine-api/types/network" <del> registrytypes "github.com/docker/engine-api/types/registry" <ide> "github.com/docker/engine-api/types/strslice" <ide> // register graph drivers <ide> _ "github.com/docker/docker/daemon/graphdriver/register" <ide> import ( <ide> volumedrivers "github.com/docker/docker/volume/drivers" <ide> "github.com/docker/docker/volume/local" <ide> "github.com/docker/docker/volume/store" <del> "github.com/docker/engine-api/types/filters" <ide> "github.com/docker/go-connections/nat" <ide> "github.com/docker/libnetwork" <ide> nwconfig "github.com/docker/libnetwork/config" <ide> type Daemon struct { <ide> configStore *Config <ide> statsCollector *statsCollector <ide> defaultLogConfig containertypes.LogConfig <del> RegistryService *registry.Service <add> RegistryService registry.Service <ide> EventsService *events.Events <ide> netController libnetwork.NetworkController <ide> volumes *store.VolumeStore <ide> func (daemon *Daemon) registerLink(parent, child *container.Container, alias str <ide> <ide> // NewDaemon sets up everything for the daemon to be able to service <ide> // requests from the webserver. <del>func NewDaemon(config *Config, registryService *registry.Service, containerdRemote libcontainerd.Remote) (daemon *Daemon, err error) { <add>func NewDaemon(config *Config, registryService registry.Service, containerdRemote libcontainerd.Remote) (daemon *Daemon, err error) { <ide> setDefaultMtu(config) <ide> <ide> // Ensure we have compatible and valid configuration options <ide> func configureVolumes(config *Config, rootUID, rootGID int) (*store.VolumeStore, <ide> <ide> // AuthenticateToRegistry checks the validity of credentials in authConfig <ide> func (daemon *Daemon) AuthenticateToRegistry(ctx context.Context, authConfig *types.AuthConfig) (string, string, error) { <del> return daemon.RegistryService.Auth(authConfig, dockerversion.DockerUserAgent(ctx)) <del>} <del> <del>var acceptedSearchFilterTags = map[string]bool{ <del> "is-automated": true, <del> "is-official": true, <del> "stars": true, <del>} <del> <del>// SearchRegistryForImages queries the registry for images matching <del>// term. authConfig is used to login. <del>func (daemon *Daemon) SearchRegistryForImages(ctx context.Context, filtersArgs string, term string, <del> authConfig *types.AuthConfig, <del> headers map[string][]string) (*registrytypes.SearchResults, error) { <del> <del> searchFilters, err := filters.FromParam(filtersArgs) <del> if err != nil { <del> return nil, err <del> } <del> if err := searchFilters.Validate(acceptedSearchFilterTags); err != nil { <del> return nil, err <del> } <del> <del> unfilteredResult, err := daemon.RegistryService.Search(term, authConfig, dockerversion.DockerUserAgent(ctx), headers) <del> if err != nil { <del> return nil, err <del> } <del> <del> var isAutomated, isOfficial bool <del> var hasStarFilter = 0 <del> if searchFilters.Include("is-automated") { <del> if searchFilters.ExactMatch("is-automated", "true") { <del> isAutomated = true <del> } else if !searchFilters.ExactMatch("is-automated", "false") { <del> return nil, fmt.Errorf("Invalid filter 'is-automated=%s'", searchFilters.Get("is-automated")) <del> } <del> } <del> if searchFilters.Include("is-official") { <del> if searchFilters.ExactMatch("is-official", "true") { <del> isOfficial = true <del> } else if !searchFilters.ExactMatch("is-official", "false") { <del> return nil, fmt.Errorf("Invalid filter 'is-official=%s'", searchFilters.Get("is-official")) <del> } <del> } <del> if searchFilters.Include("stars") { <del> hasStars := searchFilters.Get("stars") <del> for _, hasStar := range hasStars { <del> iHasStar, err := strconv.Atoi(hasStar) <del> if err != nil { <del> return nil, fmt.Errorf("Invalid filter 'stars=%s'", hasStar) <del> } <del> if iHasStar > hasStarFilter { <del> hasStarFilter = iHasStar <del> } <del> } <del> } <del> <del> filteredResults := []registrytypes.SearchResult{} <del> for _, result := range unfilteredResult.Results { <del> if searchFilters.Include("is-automated") { <del> if isAutomated != result.IsAutomated { <del> continue <del> } <del> } <del> if searchFilters.Include("is-official") { <del> if isOfficial != result.IsOfficial { <del> continue <del> } <del> } <del> if searchFilters.Include("stars") { <del> if result.StarCount < hasStarFilter { <del> continue <del> } <del> } <del> filteredResults = append(filteredResults, result) <del> } <del> <del> return &registrytypes.SearchResults{ <del> Query: unfilteredResult.Query, <del> NumResults: len(filteredResults), <del> Results: filteredResults, <del> }, nil <add> return daemon.RegistryService.Auth(ctx, authConfig, dockerversion.DockerUserAgent(ctx)) <ide> } <ide> <ide> // IsShuttingDown tells whether the daemon is shutting down or not <ide><path>daemon/search.go <add>package daemon <add> <add>import ( <add> "fmt" <add> "strconv" <add> <add> "golang.org/x/net/context" <add> <add> "github.com/docker/docker/dockerversion" <add> "github.com/docker/engine-api/types" <add> "github.com/docker/engine-api/types/filters" <add> registrytypes "github.com/docker/engine-api/types/registry" <add>) <add> <add>var acceptedSearchFilterTags = map[string]bool{ <add> "is-automated": true, <add> "is-official": true, <add> "stars": true, <add>} <add> <add>// SearchRegistryForImages queries the registry for images matching <add>// term. authConfig is used to login. <add>func (daemon *Daemon) SearchRegistryForImages(ctx context.Context, filtersArgs string, term string, <add> authConfig *types.AuthConfig, <add> headers map[string][]string) (*registrytypes.SearchResults, error) { <add> <add> searchFilters, err := filters.FromParam(filtersArgs) <add> if err != nil { <add> return nil, err <add> } <add> if err := searchFilters.Validate(acceptedSearchFilterTags); err != nil { <add> return nil, err <add> } <add> <add> unfilteredResult, err := daemon.RegistryService.Search(ctx, term, authConfig, dockerversion.DockerUserAgent(ctx), headers) <add> if err != nil { <add> return nil, err <add> } <add> <add> var isAutomated, isOfficial bool <add> var hasStarFilter = 0 <add> if searchFilters.Include("is-automated") { <add> if searchFilters.UniqueExactMatch("is-automated", "true") { <add> isAutomated = true <add> } else if !searchFilters.UniqueExactMatch("is-automated", "false") { <add> return nil, fmt.Errorf("Invalid filter 'is-automated=%s'", searchFilters.Get("is-automated")) <add> } <add> } <add> if searchFilters.Include("is-official") { <add> if searchFilters.UniqueExactMatch("is-official", "true") { <add> isOfficial = true <add> } else if !searchFilters.UniqueExactMatch("is-official", "false") { <add> return nil, fmt.Errorf("Invalid filter 'is-official=%s'", searchFilters.Get("is-official")) <add> } <add> } <add> if searchFilters.Include("stars") { <add> hasStars := searchFilters.Get("stars") <add> for _, hasStar := range hasStars { <add> iHasStar, err := strconv.Atoi(hasStar) <add> if err != nil { <add> return nil, fmt.Errorf("Invalid filter 'stars=%s'", hasStar) <add> } <add> if iHasStar > hasStarFilter { <add> hasStarFilter = iHasStar <add> } <add> } <add> } <add> <add> filteredResults := []registrytypes.SearchResult{} <add> for _, result := range unfilteredResult.Results { <add> if searchFilters.Include("is-automated") { <add> if isAutomated != result.IsAutomated { <add> continue <add> } <add> } <add> if searchFilters.Include("is-official") { <add> if isOfficial != result.IsOfficial { <add> continue <add> } <add> } <add> if searchFilters.Include("stars") { <add> if result.StarCount < hasStarFilter { <add> continue <add> } <add> } <add> filteredResults = append(filteredResults, result) <add> } <add> <add> return &registrytypes.SearchResults{ <add> Query: unfilteredResult.Query, <add> NumResults: len(filteredResults), <add> Results: filteredResults, <add> }, nil <add>} <ide><path>daemon/search_test.go <add>package daemon <add> <add>import ( <add> "fmt" <add> "strings" <add> "testing" <add> <add> "golang.org/x/net/context" <add> <add> "github.com/docker/docker/registry" <add> "github.com/docker/engine-api/types" <add> registrytypes "github.com/docker/engine-api/types/registry" <add>) <add> <add>type FakeService struct { <add> registry.DefaultService <add> <add> shouldReturnError bool <add> <add> term string <add> results []registrytypes.SearchResult <add>} <add> <add>func (s *FakeService) Search(ctx context.Context, term string, authConfig *types.AuthConfig, userAgent string, headers map[string][]string) (*registrytypes.SearchResults, error) { <add> if s.shouldReturnError { <add> return nil, fmt.Errorf("Search unknown error") <add> } <add> return &registrytypes.SearchResults{ <add> Query: s.term, <add> NumResults: len(s.results), <add> Results: s.results, <add> }, nil <add>} <add> <add>func TestSearchRegistryForImagesErrors(t *testing.T) { <add> errorCases := []struct { <add> filtersArgs string <add> shouldReturnError bool <add> expectedError string <add> }{ <add> { <add> expectedError: "Search unknown error", <add> shouldReturnError: true, <add> }, <add> { <add> filtersArgs: "invalid json", <add> expectedError: "invalid character 'i' looking for beginning of value", <add> }, <add> { <add> filtersArgs: `{"type":{"custom":true}}`, <add> expectedError: "Invalid filter 'type'", <add> }, <add> { <add> filtersArgs: `{"is-automated":{"invalid":true}}`, <add> expectedError: "Invalid filter 'is-automated=[invalid]'", <add> }, <add> { <add> filtersArgs: `{"is-automated":{"true":true,"false":true}}`, <add> expectedError: "Invalid filter 'is-automated", <add> }, <add> { <add> filtersArgs: `{"is-official":{"invalid":true}}`, <add> expectedError: "Invalid filter 'is-official=[invalid]'", <add> }, <add> { <add> filtersArgs: `{"is-official":{"true":true,"false":true}}`, <add> expectedError: "Invalid filter 'is-official", <add> }, <add> { <add> filtersArgs: `{"stars":{"invalid":true}}`, <add> expectedError: "Invalid filter 'stars=invalid'", <add> }, <add> { <add> filtersArgs: `{"stars":{"1":true,"invalid":true}}`, <add> expectedError: "Invalid filter 'stars=invalid'", <add> }, <add> } <add> for index, e := range errorCases { <add> daemon := &Daemon{ <add> RegistryService: &FakeService{ <add> shouldReturnError: e.shouldReturnError, <add> }, <add> } <add> _, err := daemon.SearchRegistryForImages(context.Background(), e.filtersArgs, "term", nil, map[string][]string{}) <add> if err == nil { <add> t.Errorf("%d: expected an error, got nothing", index) <add> } <add> if !strings.Contains(err.Error(), e.expectedError) { <add> t.Errorf("%d: expected error to contain %s, got %s", index, e.expectedError, err.Error()) <add> } <add> } <add>} <add> <add>func TestSearchRegistryForImages(t *testing.T) { <add> term := "term" <add> successCases := []struct { <add> filtersArgs string <add> registryResults []registrytypes.SearchResult <add> expectedResults []registrytypes.SearchResult <add> }{ <add> { <add> filtersArgs: "", <add> registryResults: []registrytypes.SearchResult{}, <add> expectedResults: []registrytypes.SearchResult{}, <add> }, <add> { <add> filtersArgs: "", <add> registryResults: []registrytypes.SearchResult{ <add> { <add> Name: "name", <add> Description: "description", <add> }, <add> }, <add> expectedResults: []registrytypes.SearchResult{ <add> { <add> Name: "name", <add> Description: "description", <add> }, <add> }, <add> }, <add> { <add> filtersArgs: `{"is-automated":{"true":true}}`, <add> registryResults: []registrytypes.SearchResult{ <add> { <add> Name: "name", <add> Description: "description", <add> }, <add> }, <add> expectedResults: []registrytypes.SearchResult{}, <add> }, <add> { <add> filtersArgs: `{"is-automated":{"true":true}}`, <add> registryResults: []registrytypes.SearchResult{ <add> { <add> Name: "name", <add> Description: "description", <add> IsAutomated: true, <add> }, <add> }, <add> expectedResults: []registrytypes.SearchResult{ <add> { <add> Name: "name", <add> Description: "description", <add> IsAutomated: true, <add> }, <add> }, <add> }, <add> { <add> filtersArgs: `{"is-automated":{"false":true}}`, <add> registryResults: []registrytypes.SearchResult{ <add> { <add> Name: "name", <add> Description: "description", <add> IsAutomated: true, <add> }, <add> }, <add> expectedResults: []registrytypes.SearchResult{}, <add> }, <add> { <add> filtersArgs: `{"is-automated":{"false":true}}`, <add> registryResults: []registrytypes.SearchResult{ <add> { <add> Name: "name", <add> Description: "description", <add> IsAutomated: false, <add> }, <add> }, <add> expectedResults: []registrytypes.SearchResult{ <add> { <add> Name: "name", <add> Description: "description", <add> IsAutomated: false, <add> }, <add> }, <add> }, <add> { <add> filtersArgs: `{"is-official":{"true":true}}`, <add> registryResults: []registrytypes.SearchResult{ <add> { <add> Name: "name", <add> Description: "description", <add> }, <add> }, <add> expectedResults: []registrytypes.SearchResult{}, <add> }, <add> { <add> filtersArgs: `{"is-official":{"true":true}}`, <add> registryResults: []registrytypes.SearchResult{ <add> { <add> Name: "name", <add> Description: "description", <add> IsOfficial: true, <add> }, <add> }, <add> expectedResults: []registrytypes.SearchResult{ <add> { <add> Name: "name", <add> Description: "description", <add> IsOfficial: true, <add> }, <add> }, <add> }, <add> { <add> filtersArgs: `{"is-official":{"false":true}}`, <add> registryResults: []registrytypes.SearchResult{ <add> { <add> Name: "name", <add> Description: "description", <add> IsOfficial: true, <add> }, <add> }, <add> expectedResults: []registrytypes.SearchResult{}, <add> }, <add> { <add> filtersArgs: `{"is-official":{"false":true}}`, <add> registryResults: []registrytypes.SearchResult{ <add> { <add> Name: "name", <add> Description: "description", <add> IsOfficial: false, <add> }, <add> }, <add> expectedResults: []registrytypes.SearchResult{ <add> { <add> Name: "name", <add> Description: "description", <add> IsOfficial: false, <add> }, <add> }, <add> }, <add> { <add> filtersArgs: `{"stars":{"0":true}}`, <add> registryResults: []registrytypes.SearchResult{ <add> { <add> Name: "name", <add> Description: "description", <add> StarCount: 0, <add> }, <add> }, <add> expectedResults: []registrytypes.SearchResult{ <add> { <add> Name: "name", <add> Description: "description", <add> StarCount: 0, <add> }, <add> }, <add> }, <add> { <add> filtersArgs: `{"stars":{"1":true}}`, <add> registryResults: []registrytypes.SearchResult{ <add> { <add> Name: "name", <add> Description: "description", <add> StarCount: 0, <add> }, <add> }, <add> expectedResults: []registrytypes.SearchResult{}, <add> }, <add> { <add> filtersArgs: `{"stars":{"1":true}}`, <add> registryResults: []registrytypes.SearchResult{ <add> { <add> Name: "name0", <add> Description: "description0", <add> StarCount: 0, <add> }, <add> { <add> Name: "name1", <add> Description: "description1", <add> StarCount: 1, <add> }, <add> }, <add> expectedResults: []registrytypes.SearchResult{ <add> { <add> Name: "name1", <add> Description: "description1", <add> StarCount: 1, <add> }, <add> }, <add> }, <add> { <add> filtersArgs: `{"stars":{"1":true}, "is-official":{"true":true}, "is-automated":{"true":true}}`, <add> registryResults: []registrytypes.SearchResult{ <add> { <add> Name: "name0", <add> Description: "description0", <add> StarCount: 0, <add> IsOfficial: true, <add> IsAutomated: true, <add> }, <add> { <add> Name: "name1", <add> Description: "description1", <add> StarCount: 1, <add> IsOfficial: false, <add> IsAutomated: true, <add> }, <add> { <add> Name: "name2", <add> Description: "description2", <add> StarCount: 1, <add> IsOfficial: true, <add> IsAutomated: false, <add> }, <add> { <add> Name: "name3", <add> Description: "description3", <add> StarCount: 2, <add> IsOfficial: true, <add> IsAutomated: true, <add> }, <add> }, <add> expectedResults: []registrytypes.SearchResult{ <add> { <add> Name: "name3", <add> Description: "description3", <add> StarCount: 2, <add> IsOfficial: true, <add> IsAutomated: true, <add> }, <add> }, <add> }, <add> } <add> for index, s := range successCases { <add> daemon := &Daemon{ <add> RegistryService: &FakeService{ <add> term: term, <add> results: s.registryResults, <add> }, <add> } <add> results, err := daemon.SearchRegistryForImages(context.Background(), s.filtersArgs, term, nil, map[string][]string{}) <add> if err != nil { <add> t.Errorf("%d: %v", index, err) <add> } <add> if results.Query != term { <add> t.Errorf("%d: expected Query to be %s, got %s", index, term, results.Query) <add> } <add> if results.NumResults != len(s.expectedResults) { <add> t.Errorf("%d: expected NumResults to be %d, got %d", index, len(s.expectedResults), results.NumResults) <add> } <add> for _, result := range results.Results { <add> found := false <add> for _, expectedResult := range s.expectedResults { <add> if expectedResult.Name == result.Name && <add> expectedResult.Description == result.Description && <add> expectedResult.IsAutomated == result.IsAutomated && <add> expectedResult.IsOfficial == result.IsOfficial && <add> expectedResult.StarCount == result.StarCount { <add> found = true <add> } <add> } <add> if !found { <add> t.Errorf("%d: expected results %v, got %v", index, s.expectedResults, results.Results) <add> } <add> } <add> } <add>} <ide><path>distribution/pull.go <ide> type ImagePullConfig struct { <ide> ProgressOutput progress.Output <ide> // RegistryService is the registry service to use for TLS configuration <ide> // and endpoint lookup. <del> RegistryService *registry.Service <add> RegistryService registry.Service <ide> // ImageEventLogger notifies events for a given image <ide> ImageEventLogger func(id, name, action string) <ide> // MetadataStore is the storage backend for distribution-specific <ide><path>distribution/push.go <ide> type ImagePushConfig struct { <ide> ProgressOutput progress.Output <ide> // RegistryService is the registry service to use for TLS configuration <ide> // and endpoint lookup. <del> RegistryService *registry.Service <add> RegistryService registry.Service <ide> // ImageEventLogger notifies events for a given image <ide> ImageEventLogger func(id, name, action string) <ide> // MetadataStore is the storage backend for distribution-specific <ide><path>registry/registry_test.go <ide> func TestMirrorEndpointLookup(t *testing.T) { <ide> } <ide> return false <ide> } <del> s := Service{config: makeServiceConfig([]string{"my.mirror"}, nil)} <add> s := DefaultService{config: makeServiceConfig([]string{"my.mirror"}, nil)} <ide> <ide> imageName, err := reference.WithName(IndexName + "/test/image") <ide> if err != nil { <ide><path>registry/service.go <ide> import ( <ide> "net/url" <ide> "strings" <ide> <add> "golang.org/x/net/context" <add> <ide> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/reference" <ide> "github.com/docker/engine-api/types" <ide> registrytypes "github.com/docker/engine-api/types/registry" <ide> ) <ide> <del>// Service is a registry service. It tracks configuration data such as a list <add>// Service is the interface defining what a registry service should implement. <add>type Service interface { <add> Auth(ctx context.Context, authConfig *types.AuthConfig, userAgent string) (status, token string, err error) <add> LookupPullEndpoints(hostname string) (endpoints []APIEndpoint, err error) <add> LookupPushEndpoints(hostname string) (endpoints []APIEndpoint, err error) <add> ResolveRepository(name reference.Named) (*RepositoryInfo, error) <add> ResolveIndex(name string) (*registrytypes.IndexInfo, error) <add> Search(ctx context.Context, term string, authConfig *types.AuthConfig, userAgent string, headers map[string][]string) (*registrytypes.SearchResults, error) <add> ServiceConfig() *registrytypes.ServiceConfig <add> TLSConfig(hostname string) (*tls.Config, error) <add>} <add> <add>// DefaultService is a registry service. It tracks configuration data such as a list <ide> // of mirrors. <del>type Service struct { <add>type DefaultService struct { <ide> config *serviceConfig <ide> } <ide> <del>// NewService returns a new instance of Service ready to be <add>// NewService returns a new instance of DefaultService ready to be <ide> // installed into an engine. <del>func NewService(options ServiceOptions) *Service { <del> return &Service{ <add>func NewService(options ServiceOptions) *DefaultService { <add> return &DefaultService{ <ide> config: newServiceConfig(options), <ide> } <ide> } <ide> <ide> // ServiceConfig returns the public registry service configuration. <del>func (s *Service) ServiceConfig() *registrytypes.ServiceConfig { <add>func (s *DefaultService) ServiceConfig() *registrytypes.ServiceConfig { <ide> return &s.config.ServiceConfig <ide> } <ide> <ide> // Auth contacts the public registry with the provided credentials, <ide> // and returns OK if authentication was successful. <ide> // It can be used to verify the validity of a client's credentials. <del>func (s *Service) Auth(authConfig *types.AuthConfig, userAgent string) (status, token string, err error) { <add>func (s *DefaultService) Auth(ctx context.Context, authConfig *types.AuthConfig, userAgent string) (status, token string, err error) { <add> // TODO Use ctx when searching for repositories <ide> serverAddress := authConfig.ServerAddress <ide> if serverAddress == "" { <ide> serverAddress = IndexServer <ide> func splitReposSearchTerm(reposName string) (string, string) { <ide> <ide> // Search queries the public registry for images matching the specified <ide> // search terms, and returns the results. <del>func (s *Service) Search(term string, authConfig *types.AuthConfig, userAgent string, headers map[string][]string) (*registrytypes.SearchResults, error) { <add>func (s *DefaultService) Search(ctx context.Context, term string, authConfig *types.AuthConfig, userAgent string, headers map[string][]string) (*registrytypes.SearchResults, error) { <add> // TODO Use ctx when searching for repositories <ide> if err := validateNoScheme(term); err != nil { <ide> return nil, err <ide> } <ide> func (s *Service) Search(term string, authConfig *types.AuthConfig, userAgent st <ide> <ide> // ResolveRepository splits a repository name into its components <ide> // and configuration of the associated registry. <del>func (s *Service) ResolveRepository(name reference.Named) (*RepositoryInfo, error) { <add>func (s *DefaultService) ResolveRepository(name reference.Named) (*RepositoryInfo, error) { <ide> return newRepositoryInfo(s.config, name) <ide> } <ide> <ide> // ResolveIndex takes indexName and returns index info <del>func (s *Service) ResolveIndex(name string) (*registrytypes.IndexInfo, error) { <add>func (s *DefaultService) ResolveIndex(name string) (*registrytypes.IndexInfo, error) { <ide> return newIndexInfo(s.config, name) <ide> } <ide> <ide> func (e APIEndpoint) ToV1Endpoint(userAgent string, metaHeaders http.Header) (*V <ide> } <ide> <ide> // TLSConfig constructs a client TLS configuration based on server defaults <del>func (s *Service) TLSConfig(hostname string) (*tls.Config, error) { <add>func (s *DefaultService) TLSConfig(hostname string) (*tls.Config, error) { <ide> return newTLSConfig(hostname, isSecureIndex(s.config, hostname)) <ide> } <ide> <del>func (s *Service) tlsConfigForMirror(mirrorURL *url.URL) (*tls.Config, error) { <add>func (s *DefaultService) tlsConfigForMirror(mirrorURL *url.URL) (*tls.Config, error) { <ide> return s.TLSConfig(mirrorURL.Host) <ide> } <ide> <ide> // LookupPullEndpoints creates a list of endpoints to try to pull from, in order of preference. <ide> // It gives preference to v2 endpoints over v1, mirrors over the actual <ide> // registry, and HTTPS over plain HTTP. <del>func (s *Service) LookupPullEndpoints(hostname string) (endpoints []APIEndpoint, err error) { <add>func (s *DefaultService) LookupPullEndpoints(hostname string) (endpoints []APIEndpoint, err error) { <ide> return s.lookupEndpoints(hostname) <ide> } <ide> <ide> // LookupPushEndpoints creates a list of endpoints to try to push to, in order of preference. <ide> // It gives preference to v2 endpoints over v1, and HTTPS over plain HTTP. <ide> // Mirrors are not included. <del>func (s *Service) LookupPushEndpoints(hostname string) (endpoints []APIEndpoint, err error) { <add>func (s *DefaultService) LookupPushEndpoints(hostname string) (endpoints []APIEndpoint, err error) { <ide> allEndpoints, err := s.lookupEndpoints(hostname) <ide> if err == nil { <ide> for _, endpoint := range allEndpoints { <ide> func (s *Service) LookupPushEndpoints(hostname string) (endpoints []APIEndpoint, <ide> return endpoints, err <ide> } <ide> <del>func (s *Service) lookupEndpoints(hostname string) (endpoints []APIEndpoint, err error) { <add>func (s *DefaultService) lookupEndpoints(hostname string) (endpoints []APIEndpoint, err error) { <ide> endpoints, err = s.lookupV2Endpoints(hostname) <ide> if err != nil { <ide> return nil, err <ide><path>registry/service_v1.go <ide> import ( <ide> "github.com/docker/go-connections/tlsconfig" <ide> ) <ide> <del>func (s *Service) lookupV1Endpoints(hostname string) (endpoints []APIEndpoint, err error) { <add>func (s *DefaultService) lookupV1Endpoints(hostname string) (endpoints []APIEndpoint, err error) { <ide> var cfg = tlsconfig.ServerDefault <ide> tlsConfig := &cfg <ide> if hostname == DefaultNamespace { <ide><path>registry/service_v2.go <ide> import ( <ide> "github.com/docker/go-connections/tlsconfig" <ide> ) <ide> <del>func (s *Service) lookupV2Endpoints(hostname string) (endpoints []APIEndpoint, err error) { <add>func (s *DefaultService) lookupV2Endpoints(hostname string) (endpoints []APIEndpoint, err error) { <ide> var cfg = tlsconfig.ServerDefault <ide> tlsConfig := &cfg <ide> if hostname == DefaultNamespace || hostname == DefaultV1Registry.Host {
11
Python
Python
fix scalar inf comparison in allclose
4de81d32d97a2efb1023ca0c19e36990f1ba64a4
<ide><path>numpy/core/numeric.py <ide> def identity(n, dtype=None): <ide> a = array([1]+n*[0],dtype=dtype) <ide> b = empty((n,n),dtype=dtype) <ide> <del> # Note that this assignment depends on the convention that since the a array <del> # is shorter than the flattened b array, then the a array will be repeated <del> # until it is the appropriate size. Given a's construction, this nicely sets <del> # the diagonal to all ones. <add> # Note that this assignment depends on the convention that since the a <add> # array is shorter than the flattened b array, then the a array will <add> # be repeated until it is the appropriate size. Given a's construction, <add> # this nicely sets the diagonal to all ones. <ide> b.flat = a <ide> return b <ide> <ide> def allclose(a, b, rtol=1.e-5, atol=1.e-8): <ide> yinf = isinf(y) <ide> if (not xinf.any() and not yinf.any()): <ide> return d1.all() <del> d2 = (xinf != yinf) <ide> d3 = (x[xinf] == y[yinf]) <ide> d4 = (~xinf & ~yinf) <del> if d3.size == 0: <del> return False <add> if d3.size < 2: <add> if d3.size==0: <add> return False <add> return d3 <ide> if d3.all(): <ide> return d1[d4].all() <ide> else:
1
Python
Python
squad v2 bert + xlnet
0669c1fcd15051ec6fe2d950079886faccf2fb33
<ide><path>transformers/__init__.py <ide> glue_output_modes, glue_convert_examples_to_features, <ide> glue_processors, glue_tasks_num_labels, <ide> squad_convert_examples_to_features, SquadFeatures, <del> SquadExample, read_squad_examples) <add> SquadExample) <ide> <ide> if is_sklearn_available(): <ide> from .data import glue_compute_metrics <ide><path>transformers/data/__init__.py <ide> from .processors import InputExample, InputFeatures, DataProcessor, SquadFeatures <ide> from .processors import glue_output_modes, glue_processors, glue_tasks_num_labels, glue_convert_examples_to_features <del>from .processors import squad_convert_examples_to_features, SquadExample, read_squad_examples <add>from .processors import squad_convert_examples_to_features, SquadExample <ide> <ide> from .metrics import is_sklearn_available <ide> if is_sklearn_available(): <ide><path>transformers/data/processors/__init__.py <ide> from .utils import InputExample, InputFeatures, DataProcessor <ide> from .glue import glue_output_modes, glue_processors, glue_tasks_num_labels, glue_convert_examples_to_features <del>from .squad import squad_convert_examples_to_features, SquadFeatures, SquadExample, read_squad_examples <add>from .squad import squad_convert_examples_to_features, SquadFeatures, SquadExample <ide> <ide><path>transformers/data/processors/squad.py <ide> def _check_is_max_context(doc_spans, cur_span_index, position): <ide> <ide> return cur_span_index == best_span_index <ide> <del> <ide> def _new_check_is_max_context(doc_spans, cur_span_index, position): <ide> """Check if this is the 'max context' doc span for the token.""" <ide> # if len(doc_spans) == 1: <ide> def squad_convert_examples_to_features(examples, tokenizer, max_seq_length, <ide> features = [] <ide> new_features = [] <ide> for (example_index, example) in enumerate(tqdm(examples)): <del> if is_training: <add> if is_training and not example.is_impossible: <ide> # Get start and end position <ide> answer_length = len(example.answer_text) <ide> start_position = example.start_position <ide> def squad_convert_examples_to_features(examples, tokenizer, max_seq_length, <ide> logger.warning("Could not find answer: '%s' vs. '%s'", actual_text, cleaned_answer_text) <ide> continue <ide> <add> <ide> tok_to_orig_index = [] <ide> orig_to_tok_index = [] <ide> all_doc_tokens = [] <ide> def squad_convert_examples_to_features(examples, tokenizer, max_seq_length, <ide> tok_to_orig_index.append(i) <ide> all_doc_tokens.append(sub_token) <ide> <add> <add> if is_training and not example.is_impossible: <add> tok_start_position = orig_to_tok_index[example.start_position] <add> if example.end_position < len(example.doc_tokens) - 1: <add> tok_end_position = orig_to_tok_index[example.end_position + 1] - 1 <add> else: <add> tok_end_position = len(all_doc_tokens) - 1 <add> <add> (tok_start_position, tok_end_position) = _improve_answer_span( <add> all_doc_tokens, tok_start_position, tok_end_position, tokenizer, example.answer_text <add> ) <add> <ide> spans = [] <ide> <ide> truncated_query = tokenizer.encode(example.question_text, add_special_tokens=False, max_length=max_query_length) <ide> def squad_convert_examples_to_features(examples, tokenizer, max_seq_length, <ide> # Set the CLS index to '0' <ide> p_mask[cls_index] = 0 <ide> <add> <add> span_is_impossible = example.is_impossible <add> start_position = 0 <add> end_position = 0 <add> if is_training and not span_is_impossible: <add> # For training, if our document chunk does not contain an annotation <add> # we throw it out, since there is nothing to predict. <add> doc_start = span["start"] <add> doc_end = span["start"] + span["length"] - 1 <add> out_of_span = False <add> <add> if not (tok_start_position >= doc_start and tok_end_position <= doc_end): <add> out_of_span = True <add> <add> if out_of_span: <add> start_position = cls_index <add> end_position = cls_index <add> span_is_impossible = True <add> else: <add> if sequence_a_is_doc: <add> doc_offset = 0 <add> else: <add> doc_offset = len(truncated_query) + sequence_added_tokens <add> <add> start_position = tok_start_position - doc_start + doc_offset <add> end_position = tok_end_position - doc_start + doc_offset <add> <add> <ide> new_features.append(NewSquadFeatures( <ide> span['input_ids'], <ide> span['attention_mask'], <ide> def squad_convert_examples_to_features(examples, tokenizer, max_seq_length, <ide> paragraph_len=span['paragraph_len'], <ide> token_is_max_context=span["token_is_max_context"], <ide> tokens=span["tokens"], <del> token_to_orig_map=span["token_to_orig_map"] <add> token_to_orig_map=span["token_to_orig_map"], <add> <add> start_position=start_position, <add> end_position=end_position <ide> )) <ide> <ide> unique_id += 1 <ide> <ide> return new_features <ide> <ide> <del>def read_squad_examples(input_file, is_training, version_2_with_negative): <del> """Read a SQuAD json file into a list of SquadExample.""" <del> with open(input_file, "r", encoding='utf-8') as reader: <del> input_data = json.load(reader)["data"] <del> <del> def is_whitespace(c): <del> if c == " " or c == "\t" or c == "\r" or c == "\n" or ord(c) == 0x202F: <del> return True <del> return False <del> <del> examples = [] <del> for entry in input_data: <del> for paragraph in entry["paragraphs"]: <del> paragraph_text = paragraph["context"] <del> doc_tokens = [] <del> char_to_word_offset = [] <del> prev_is_whitespace = True <del> for c in paragraph_text: <del> if is_whitespace(c): <del> prev_is_whitespace = True <del> else: <del> if prev_is_whitespace: <del> doc_tokens.append(c) <del> else: <del> doc_tokens[-1] += c <del> prev_is_whitespace = False <del> char_to_word_offset.append(len(doc_tokens) - 1) <del> <del> for qa in paragraph["qas"]: <del> qas_id = qa["id"] <del> question_text = qa["question"] <del> start_position = None <del> end_position = None <del> orig_answer_text = None <del> is_impossible = False <del> if is_training: <del> if version_2_with_negative: <del> is_impossible = qa["is_impossible"] <del> if (len(qa["answers"]) != 1) and (not is_impossible): <del> raise ValueError( <del> "For training, each question should have exactly 1 answer.") <del> if not is_impossible: <del> answer = qa["answers"][0] <del> orig_answer_text = answer["text"] <del> answer_offset = answer["answer_start"] <del> answer_length = len(orig_answer_text) <del> start_position = char_to_word_offset[answer_offset] <del> end_position = char_to_word_offset[answer_offset + answer_length - 1] <del> # Only add answers where the text can be exactly recovered from the <del> # document. If this CAN'T happen it's likely due to weird Unicode <del> # stuff so we will just skip the example. <del> # <del> # Note that this means for training mode, every example is NOT <del> # guaranteed to be preserved. <del> actual_text = " ".join(doc_tokens[start_position:(end_position + 1)]) <del> cleaned_answer_text = " ".join( <del> whitespace_tokenize(orig_answer_text)) <del> if actual_text.find(cleaned_answer_text) == -1: <del> logger.warning("Could not find answer: '%s' vs. '%s'", <del> actual_text, cleaned_answer_text) <del> continue <del> else: <del> start_position = -1 <del> end_position = -1 <del> orig_answer_text = "" <del> <del> example = SquadExample( <del> qas_id=qas_id, <del> question_text=question_text, <del> doc_tokens=doc_tokens, <del> orig_answer_text=orig_answer_text, <del> start_position=start_position, <del> end_position=end_position, <del> is_impossible=is_impossible) <del> examples.append(example) <del> return examples <del> <del> <del>class SquadV1Processor(DataProcessor): <add>class SquadProcessor(DataProcessor): <ide> """Processor for the SQuAD data set.""" <add> train_file = None <add> dev_file = None <ide> <ide> def get_example_from_tensor_dict(self, tensor_dict): <ide> """See base class.""" <ide> def get_example_from_tensor_dict(self, tensor_dict): <ide> <ide> def get_train_examples(self, data_dir, only_first=None): <ide> """See base class.""" <del> with open(os.path.join(data_dir, "train-v1.1.json"), "r", encoding='utf-8') as reader: <add> if self.train_file is None: <add> raise ValueError("SquadProcessor should be instantiated via SquadV1Processor or SquadV2Processor") <add> <add> with open(os.path.join(data_dir, self.train_file), "r", encoding='utf-8') as reader: <ide> input_data = json.load(reader)["data"] <ide> return self._create_examples(input_data, "train", only_first) <ide> <ide> def get_dev_examples(self, data_dir, only_first=None): <ide> """See base class.""" <del> with open(os.path.join(data_dir, "dev-v1.1.json"), "r", encoding='utf-8') as reader: <add> if self.dev_file is None: <add> raise ValueError("SquadProcessor should be instantiated via SquadV1Processor or SquadV2Processor") <add> <add> with open(os.path.join(data_dir, self.dev_file), "r", encoding='utf-8') as reader: <ide> input_data = json.load(reader)["data"] <ide> return self._create_examples(input_data, "dev", only_first) <ide> <ide> def _create_examples(self, input_data, set_type, only_first=None): <ide> question_text = qa["question"] <ide> start_position_character = None <ide> answer_text = None <del> if is_training: <add> <add> if "is_impossible" in qa: <add> is_impossible = qa["is_impossible"] <add> else: <add> is_impossible = False <add> <add> if not is_impossible and is_training: <ide> if (len(qa["answers"]) != 1): <ide> raise ValueError( <ide> "For training, each question should have exactly 1 answer.") <ide> def _create_examples(self, input_data, set_type, only_first=None): <ide> context_text=context_text, <ide> answer_text=answer_text, <ide> start_position_character=start_position_character, <del> title=title <add> title=title, <add> is_impossible=is_impossible <ide> ) <add> <ide> examples.append(example) <ide> <ide> if only_first is not None and len(examples) > only_first: <ide> return examples <ide> return examples <del> <ide> <add>class SquadV1Processor(SquadProcessor): <add> train_file = "train-v1.1.json" <add> dev_file = "dev-v1.1.json" <add> <add> <add>class SquadV2Processor(SquadProcessor): <add> train_file = "train-v2.0.json" <add> dev_file = "dev-v2.0.json" <add> <ide> <ide> class NewSquadExample(object): <ide> """ <ide> def __init__(self, <ide> context_text, <ide> answer_text, <ide> start_position_character, <del> title): <add> title, <add> is_impossible=False): <ide> self.qas_id = qas_id <ide> self.question_text = question_text <ide> self.context_text = context_text <ide> self.answer_text = answer_text <ide> self.title = title <del> self.is_impossible = False <add> self.is_impossible = is_impossible <add> <add> self.start_position, self.end_position = 0, 0 <ide> <ide> doc_tokens = [] <ide> char_to_word_offset = [] <ide> def __init__(self, <ide> self.char_to_word_offset = char_to_word_offset <ide> <ide> # Start end end positions only has a value during evaluation. <del> if start_position_character is not None: <add> if start_position_character is not None and not is_impossible: <ide> self.start_position = char_to_word_offset[start_position_character] <ide> self.end_position = char_to_word_offset[start_position_character + len(answer_text) - 1] <ide> <ide> def __init__(self, <ide> paragraph_len, <ide> token_is_max_context, <ide> tokens, <del> token_to_orig_map <add> token_to_orig_map, <add> <add> start_position, <add> end_position <ide> ): <ide> self.input_ids = input_ids <ide> self.attention_mask = attention_mask <ide> def __init__(self, <ide> self.tokens = tokens <ide> self.token_to_orig_map = token_to_orig_map <ide> <add> self.start_position = start_position <add> self.end_position = end_position <add> <ide> class SquadExample(object): <ide> """ <ide> A single training/test example for the Squad dataset.
4
Text
Text
fix id in example
5c8b5e3b1b6341d3b328dfcfb6536adb73d40890
<ide><path>docs/recipes/structuring-reducers/NormalizingStateShape.md <ide> An example of a normalized state structure for the blog example above might look <ide> comment : ".....", <ide> }, <ide> }, <del> allIds : ["comment1", "comment2", "comment3", "commment4", "comment5"] <add> allIds : ["comment1", "comment2", "comment3", "comment4", "comment5"] <ide> }, <ide> users : { <ide> byId : {
1
Javascript
Javascript
add attributedivisors to state
c6c305a39de6cebb5c0d5a5ca3a5481603556247
<ide><path>src/renderers/webgl/WebGLState.js <ide> THREE.WebGLState = function ( gl, extensions, paramThreeToGL ) { <ide> <ide> var newAttributes = new Uint8Array( 16 ); <ide> var enabledAttributes = new Uint8Array( 16 ); <add> var attributeDivisors = new Uint8Array( 16 ); <ide> <ide> var capabilities = {}; <ide>
1
Python
Python
add fp16 benchmarks to ncf
3b69c26fed693b45bfdce84bfc3e1b07a13bb1e2
<ide><path>official/recommendation/ncf_keras_benchmark.py <ide> def benchmark_1_gpu_ctl_mlperf_like(self): <ide> self._run_and_report_benchmark_mlperf_like() <ide> <ide> def benchmark_1_gpu_ctl_fp16_mlperf_like(self): <del> """1 GPU using CTL.""" <add> """1 GPU using CTL and FP16.""" <ide> self._setup() <ide> FLAGS.keras_use_ctl = True <ide> FLAGS.train_epochs = 7 <ide> FLAGS.dtype = 'fp16' <ide> FLAGS.loss_scale = 8192 <ide> self._run_and_report_benchmark_mlperf_like() <ide> <add> def benchmark_1_gpu_fp16_mlperf_like(self): <add> """1 GPU using FP16.""" <add> self._setup() <add> FLAGS.train_epochs = 7 <add> FLAGS.dtype = 'fp16' <add> FLAGS.loss_scale = 8192 <add> self._run_and_report_benchmark_mlperf_like() <add> <ide> def benchmark_1_gpu_ctl_run_eagerly_mlperf_like(self): <ide> """1 GPU using CTL with eager and distribution strategy.""" <ide> self._setup() <ide> def benchmark_xla_1_gpu_ctl_mlperf_like(self): <ide> FLAGS.train_epochs = 7 <ide> self._run_and_report_benchmark_mlperf_like() <ide> <add> def benchmark_xla_1_gpu_fp16_mlperf_like(self): <add> """1 GPU using with XLA and FP16.""" <add> self._setup() <add> FLAGS.enable_xla = True <add> FLAGS.train_epochs = 7 <add> FLAGS.dtype = 'fp16' <add> FLAGS.loss_scale = 8192 <add> self._run_and_report_benchmark_mlperf_like() <add> <ide> def benchmark_xla_1_gpu_ctl_fp16_mlperf_like(self): <del> """1 GPU using CTL with XLA.""" <add> """1 GPU using CTL with XLA and FP16.""" <ide> self._setup() <ide> FLAGS.keras_use_ctl = True <ide> FLAGS.enable_xla = True <ide> def benchmark_8_gpu_tf_data_ctl_mlperf_like(self): <ide> FLAGS.input_meta_data_path = os.path.join(NCF_TF_DATA_1M_BATCH_DIR_NAME, "meta_data.json") <ide> self._run_and_report_benchmark_mlperf_like() <ide> <add> def benchmark_8_gpu_tf_data_fp16_mlperf_like(self): <add> """8 GPU FP16""" <add> self._setup() <add> FLAGS.num_gpus = 8 <add> FLAGS.train_epochs = 17 <add> FLAGS.batch_size = 1048576 <add> FLAGS.eval_batch_size = 1048000 <add> FLAGS.learning_rate = 0.0045 <add> FLAGS.beta1 = 0.25 <add> FLAGS.beta2 = 0.5 <add> FLAGS.epsilon = 1e-8 <add> FLAGS.dtype = 'fp16' <add> FLAGS.loss_scale = 8192 <add> FLAGS.train_dataset_path = os.path.join(NCF_TF_DATA_1M_BATCH_DIR_NAME, "training_cycle_*/*") <add> FLAGS.eval_dataset_path = os.path.join(NCF_TF_DATA_1M_BATCH_DIR_NAME, "eval_data/*") <add> FLAGS.input_meta_data_path = os.path.join(NCF_TF_DATA_1M_BATCH_DIR_NAME, "meta_data.json") <add> self._run_and_report_benchmark_mlperf_like() <add> <ide> def benchmark_8_gpu_tf_data_ctl_fp16_mlperf_like(self): <del> """8 GPU using CTL.""" <add> """8 GPU FP16 using CTL""" <ide> self._setup() <ide> FLAGS.keras_use_ctl = True <ide> FLAGS.num_gpus = 8
1
PHP
PHP
make url() interoperable with psr7
2e97ed6c621e3de25e0f1bbc1ee4bcb8dd1a41eb
<ide><path>src/Http/Client/Request.php <ide> * <ide> * Used by Cake\Network\Http\Client to contain request information <ide> * for making requests. <del> * <ide> */ <ide> class Request extends Message implements RequestInterface <ide> { <ide> class Request extends Message implements RequestInterface <ide> */ <ide> protected $_body; <ide> <del> /** <del> * The URL to request. <del> * <del> * @var string <del> */ <del> protected $_url; <del> <ide> /** <ide> * Constructor <ide> * <ide> public function method($method = null) <ide> * <ide> * @param string|null $url The url for the request. Leave null for get <ide> * @return $this|string Either $this or the url value. <add> * @deprecated 3.3.0 Use getUri() and withUri() instead. <ide> */ <ide> public function url($url = null) <ide> { <ide> if ($url === null) { <del> return $this->_url; <add> return '' . $this->getUri(); <ide> } <del> $this->_url = $url; <add> $this->uri = $this->createUri($url); <ide> return $this; <ide> } <ide> <ide><path>tests/TestCase/Network/Http/RequestTest.php <ide> <ide> use Cake\Network\Http\Request; <ide> use Cake\TestSuite\TestCase; <add>use Zend\Diactoros\Uri; <ide> <ide> /** <ide> * HTTP request test. <ide> public function testUrl() <ide> $this->assertEquals('http://example.com', $request->url()); <ide> } <ide> <add> /** <add> * Test that url() modifies the PSR7 stream <add> * <add> * @return void <add> */ <add> public function testUrlInteroperability() <add> { <add> $request = new Request(); <add> $request->url('http://example.com'); <add> $this->assertSame('http://example.com', $request->url()); <add> $this->assertSame('http://example.com', $request->getUri()->__toString()); <add> <add> $uri = 'http://example.com/test'; <add> $request = new Request(); <add> $request = $request->withUri(new Uri($uri)); <add> $this->assertSame($uri, $request->url()); <add> $this->assertSame($uri, $request->getUri()->__toString()); <add> } <add> <ide> /** <ide> * test method method. <ide> * <ide> public function testBody() <ide> $this->assertEquals($data, $request->body()); <ide> } <ide> <add> /** <add> * Test that body() modifies the PSR7 stream <add> * <add> * @return void <add> */ <add> public function testBodyInteroperability() <add> { <add> $this->markTestIncomplete(); <add> } <add> <ide> /** <ide> * test header method. <ide> *
2
Ruby
Ruby
move stuff from compatibility.rb to deprecated.rb
48bb3b3904806abaea7c62961559c03e689dd12f
<ide><path>actionpack/lib/action_controller/base.rb <ide> def self.filter_parameter_logging(*args, &block) <ide> <ide> end <ide> end <add> <add>require "action_controller/deprecated/base" <ide><path>actionpack/lib/action_controller/deprecated/base.rb <add>module ActionController <add> class Base <add> class << self <add> def deprecated_config_accessor(option, message = nil) <add> deprecated_config_reader(option, message) <add> deprecated_config_writer(option, message) <add> end <add> <add> def deprecated_config_reader(option, message = nil) <add> message ||= "Reading #{option} directly from ActionController::Base is deprecated. " \ <add> "Please read it from config.#{option}" <add> <add> self.class_eval <<-RUBY, __FILE__, __LINE__ + 1 <add> def #{option} <add> ActiveSupport::Deprecation.warn #{message.inspect}, caller <add> config.#{option} <add> end <add> RUBY <add> end <add> <add> def deprecated_config_writer(option, message = nil) <add> message ||= "Setting #{option} directly on ActionController::Base is deprecated. " \ <add> "Please set it on config.action_controller.#{option}" <add> <add> self.class_eval <<-RUBY, __FILE__, __LINE__ + 1 <add> def #{option}=(val) <add> ActiveSupport::Deprecation.warn #{message.inspect}, caller <add> config.#{option} = val <add> end <add> RUBY <add> end <add> <add> def consider_all_requests_local <add> ActiveSupport::Deprecation.warn "ActionController::Base.consider_all_requests_local is deprecated, " << <add> "use Rails.application.config.consider_all_requests_local instead", caller <add> Rails.application.config.consider_all_requests_local <add> end <add> <add> def consider_all_requests_local=(value) <add> ActiveSupport::Deprecation.warn "ActionController::Base.consider_all_requests_local= is deprecated. " << <add> "Please configure it on your application with config.consider_all_requests_local=", caller <add> Rails.application.config.consider_all_requests_local = value <add> end <add> <add> def allow_concurrency <add> ActiveSupport::Deprecation.warn "ActionController::Base.allow_concurrency is deprecated, " << <add> "use Rails.application.config.allow_concurrency instead", caller <add> Rails.application.config.allow_concurrency <add> end <add> <add> def allow_concurrency=(value) <add> ActiveSupport::Deprecation.warn "ActionController::Base.allow_concurrency= is deprecated. " << <add> "Please configure it on your application with config.allow_concurrency=", caller <add> Rails.application.config.allow_concurrency = value <add> end <add> <add> def ip_spoofing_check=(value) <add> ActiveSupport::Deprecation.warn "ActionController::Base.ip_spoofing_check= is deprecated. " << <add> "Please configure it on your application with config.action_dispatch.ip_spoofing_check=", caller <add> Rails.application.config.action_disaptch.ip_spoofing_check = value <add> end <add> <add> def ip_spoofing_check <add> ActiveSupport::Deprecation.warn "ActionController::Base.ip_spoofing_check is deprecated. " << <add> "Configuring ip_spoofing_check on the application configures a middleware.", caller <add> Rails.application.config.action_disaptch.ip_spoofing_check <add> end <add> <add> def trusted_proxies=(value) <add> ActiveSupport::Deprecation.warn "ActionController::Base.trusted_proxies= is deprecated. " << <add> "Please configure it on your application with config.action_dispatch.trusted_proxies=", caller <add> Rails.application.config.action_dispatch.ip_spoofing_check = value <add> end <add> <add> def trusted_proxies <add> ActiveSupport::Deprecation.warn "ActionController::Base.trusted_proxies is deprecated. " << <add> "Configuring trusted_proxies on the application configures a middleware.", caller <add> Rails.application.config.action_dispatch.ip_spoofing_check = value <add> end <add> <add> def session=(value) <add> ActiveSupport::Deprecation.warn "ActionController::Base.session= is deprecated. " << <add> "Please configure it on your application with config.action_dispatch.session=", caller <add> Rails.application.config.action_dispatch.session = value.delete(:disabled) ? nil : value <add> end <add> <add> # Controls the resource action separator <add> def resource_action_separator <add> @resource_action_separator ||= "/" <add> end <add> <add> def resource_action_separator=(val) <add> ActiveSupport::Deprecation.warn "ActionController::Base.resource_action_separator is deprecated and only " \ <add> "works with the deprecated router DSL." <add> @resource_action_separator = val <add> end <add> <add> def use_accept_header <add> ActiveSupport::Deprecation.warn "ActionController::Base.use_accept_header doesn't do anything anymore. " \ <add> "The accept header is always taken into account." <add> end <add> <add> def use_accept_header=(val) <add> use_accept_header <add> end <add> end <add> <add> deprecated_config_writer :session_store <add> deprecated_config_writer :session_options <add> deprecated_config_accessor :relative_url_root, "relative_url_root is ineffective. Please stop using it" <add> deprecated_config_accessor :assets_dir <add> deprecated_config_accessor :javascripts_dir <add> deprecated_config_accessor :stylesheets_dir <add> <add> delegate :consider_all_requests_local, :consider_all_requests_local=, <add> :allow_concurrency, :allow_concurrency=, :to => :"self.class" <add> end <add>end <ide>\ No newline at end of file <ide><path>actionpack/lib/action_controller/metal/compatibility.rb <ide> class << self <ide> @before_filter_chain_aborted @_headers @_params <ide> @_response) <ide> <del> # Controls the resource action separator <del> def self.resource_action_separator <del> @resource_action_separator ||= "/" <del> end <del> <del> def self.resource_action_separator=(val) <del> ActiveSupport::Deprecation.warn "ActionController::Base.resource_action_separator is deprecated and only " \ <del> "works with the deprecated router DSL." <del> @resource_action_separator = val <del> end <del> <del> def self.use_accept_header <del> ActiveSupport::Deprecation.warn "ActionController::Base.use_accept_header doesn't do anything anymore. " \ <del> "The accept header is always taken into account." <add> def rescue_action(env) <add> raise env["action_dispatch.rescue.exception"] <ide> end <ide> <del> def self.use_accept_header=(val) <del> use_accept_header <add> # Defines the storage option for cached fragments <add> def cache_store=(store_option) <add> @@cache_store = ActiveSupport::Cache.lookup_store(store_option) <ide> end <ide> <ide> self.page_cache_directory = defined?(Rails.public_path) ? Rails.public_path : "" <del> <del> # Prepends all the URL-generating helpers from AssetHelper. This makes it possible to easily move javascripts, stylesheets, <del> # and images to a dedicated asset server away from the main web server. Example: <del> # ActionController::Base.asset_host = "http://assets.example.com" <del> cattr_accessor :asset_host <ide> end <ide> <del> def self.deprecated_config_accessor(option, message = nil) <del> deprecated_config_reader(option, message) <del> deprecated_config_writer(option, message) <del> end <del> <del> def self.deprecated_config_reader(option, message = nil) <del> message ||= "Reading #{option} directly from ActionController::Base is deprecated. " \ <del> "Please read it from config.#{option}" <del> <del> ClassMethods.class_eval <<-RUBY, __FILE__, __LINE__ + 1 <del> def #{option} <del> ActiveSupport::Deprecation.warn #{message.inspect}, caller <del> config.#{option} <del> end <del> RUBY <del> end <del> <del> def self.deprecated_config_writer(option, message = nil) <del> message ||= "Setting #{option} directly on ActionController::Base is deprecated. " \ <del> "Please set it on config.action_controller.#{option}" <del> <del> ClassMethods.class_eval <<-RUBY, __FILE__, __LINE__ + 1 <del> def #{option}=(val) <del> ActiveSupport::Deprecation.warn #{message.inspect}, caller <del> config.#{option} = val <del> end <del> RUBY <del> end <del> <del> deprecated_config_writer :session_store <del> deprecated_config_writer :session_options <del> deprecated_config_accessor :relative_url_root, "relative_url_root is ineffective. Please stop using it" <del> deprecated_config_accessor :assets_dir <del> deprecated_config_accessor :javascripts_dir <del> deprecated_config_accessor :stylesheets_dir <del> <ide> # For old tests <ide> def initialize_template_class(*) end <ide> def assign_shortcuts(*) end <ide> <del> # TODO: Remove this after we flip <ide> def template <ide> @template ||= view_context <ide> end <ide> def process_action(*) <ide> super <ide> end <ide> <del> module ClassMethods <del> def consider_all_requests_local <del> ActiveSupport::Deprecation.warn "ActionController::Base.consider_all_requests_local is deprecated, " << <del> "use Rails.application.config.consider_all_requests_local instead", caller <del> Rails.application.config.consider_all_requests_local <del> end <del> <del> def consider_all_requests_local=(value) <del> ActiveSupport::Deprecation.warn "ActionController::Base.consider_all_requests_local= is deprecated. " << <del> "Please configure it on your application with config.consider_all_requests_local=", caller <del> Rails.application.config.consider_all_requests_local = value <del> end <del> <del> def allow_concurrency <del> ActiveSupport::Deprecation.warn "ActionController::Base.allow_concurrency is deprecated, " << <del> "use Rails.application.config.allow_concurrency instead", caller <del> Rails.application.config.allow_concurrency <del> end <del> <del> def allow_concurrency=(value) <del> ActiveSupport::Deprecation.warn "ActionController::Base.allow_concurrency= is deprecated. " << <del> "Please configure it on your application with config.allow_concurrency=", caller <del> Rails.application.config.allow_concurrency = value <del> end <del> <del> def ip_spoofing_check=(value) <del> ActiveSupport::Deprecation.warn "ActionController::Base.ip_spoofing_check= is deprecated. " << <del> "Please configure it on your application with config.action_dispatch.ip_spoofing_check=", caller <del> Rails.application.config.action_disaptch.ip_spoofing_check = value <del> end <del> <del> def ip_spoofing_check <del> ActiveSupport::Deprecation.warn "ActionController::Base.ip_spoofing_check is deprecated. " << <del> "Configuring ip_spoofing_check on the application configures a middleware.", caller <del> Rails.application.config.action_disaptch.ip_spoofing_check <del> end <del> <del> def trusted_proxies=(value) <del> ActiveSupport::Deprecation.warn "ActionController::Base.trusted_proxies= is deprecated. " << <del> "Please configure it on your application with config.action_dispatch.trusted_proxies=", caller <del> Rails.application.config.action_dispatch.ip_spoofing_check = value <del> end <del> <del> def trusted_proxies <del> ActiveSupport::Deprecation.warn "ActionController::Base.trusted_proxies is deprecated. " << <del> "Configuring trusted_proxies on the application configures a middleware.", caller <del> Rails.application.config.action_dispatch.ip_spoofing_check = value <del> end <del> <del> def session=(value) <del> ActiveSupport::Deprecation.warn "ActionController::Base.session= is deprecated. " << <del> "Please configure it on your application with config.action_dispatch.session=", caller <del> Rails.application.config.action_dispatch.session = value.delete(:disabled) ? nil : value <del> end <del> <del> def rescue_action(env) <del> raise env["action_dispatch.rescue.exception"] <del> end <del> <del> # Defines the storage option for cached fragments <del> def cache_store=(store_option) <del> @@cache_store = ActiveSupport::Cache.lookup_store(store_option) <del> end <del> end <del> <del> delegate :consider_all_requests_local, :consider_all_requests_local=, <del> :allow_concurrency, :allow_concurrency=, :to => :"self.class" <del> <ide> def render_to_body(options) <ide> if options.is_a?(Hash) && options.key?(:template) <ide> options[:template].sub!(/^\//, '') <ide><path>actionpack/test/template/asset_tag_helper_test.rb <ide> def host_with_port() 'localhost' end <ide> <ide> def teardown <ide> ActionController::Base.perform_caching = false <del> ActionController::Base.asset_host = nil <ide> ENV.delete('RAILS_ASSET_ID') <ide> end <ide>
4
Java
Java
remove variance from the input source of retrywhen
19d83c148eea5cf789761020638d36b3fee015b3
<ide><path>src/main/java/io/reactivex/Completable.java <ide> public final Completable retry(Predicate<? super Throwable> predicate) { <ide> * @throws NullPointerException if handler is null <ide> */ <ide> @SchedulerSupport(SchedulerSupport.NONE) <del> public final Completable retryWhen(Function<? super Flowable<? extends Throwable>, ? extends Publisher<Object>> handler) { <add> public final Completable retryWhen(Function<? super Flowable<Throwable>, ? extends Publisher<Object>> handler) { <ide> return fromPublisher(toFlowable().retryWhen(handler)); <ide> } <ide> <ide><path>src/main/java/io/reactivex/Flowable.java <ide> public final Flowable<T> retryUntil(final BooleanSupplier stop) { <ide> @BackpressureSupport(BackpressureKind.FULL) <ide> @SchedulerSupport(SchedulerSupport.NONE) <ide> public final Flowable<T> retryWhen( <del> final Function<? super Flowable<? extends Throwable>, ? extends Publisher<?>> handler) { <add> final Function<? super Flowable<Throwable>, ? extends Publisher<?>> handler) { <ide> ObjectHelper.requireNonNull(handler, "handler is null"); <ide> <ide> return RxJavaPlugins.onAssembly(new FlowableRetryWhen<T>(this, handler)); <ide><path>src/main/java/io/reactivex/Maybe.java <ide> public final Maybe<T> retryUntil(final BooleanSupplier stop) { <ide> */ <ide> @SchedulerSupport(SchedulerSupport.NONE) <ide> public final Maybe<T> retryWhen( <del> final Function<? super Flowable<? extends Throwable>, ? extends Publisher<?>> handler) { <add> final Function<? super Flowable<Throwable>, ? extends Publisher<?>> handler) { <ide> return toFlowable().retryWhen(handler).singleElement(); <ide> } <ide> <ide><path>src/main/java/io/reactivex/Observable.java <ide> public final Observable<T> retryUntil(final BooleanSupplier stop) { <ide> */ <ide> @SchedulerSupport(SchedulerSupport.NONE) <ide> public final Observable<T> retryWhen( <del> final Function<? super Observable<? extends Throwable>, ? extends ObservableSource<?>> handler) { <add> final Function<? super Observable<Throwable>, ? extends ObservableSource<?>> handler) { <ide> ObjectHelper.requireNonNull(handler, "handler is null"); <ide> return RxJavaPlugins.onAssembly(new ObservableRedo<T>(this, ObservableInternalHelper.retryWhenHandler(handler))); <ide> } <ide><path>src/main/java/io/reactivex/Single.java <ide> public final Single<T> retry(Predicate<? super Throwable> predicate) { <ide> * @return the new Single instance <ide> */ <ide> @SchedulerSupport(SchedulerSupport.NONE) <del> public final Single<T> retryWhen(Function<? super Flowable<? extends Throwable>, ? extends Publisher<Object>> handler) { <add> public final Single<T> retryWhen(Function<? super Flowable<Throwable>, ? extends Publisher<Object>> handler) { <ide> return toSingle(toFlowable().retryWhen(handler)); <ide> } <ide> <ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableInternalHelper.java <ide> public boolean test(Notification<Object> t) throws Exception { <ide> <ide> static final class RetryWhenInner <ide> implements Function<Observable<Notification<Object>>, ObservableSource<?>> { <del> private final Function<? super Observable<? extends Throwable>, ? extends ObservableSource<?>> handler; <add> private final Function<? super Observable<Throwable>, ? extends ObservableSource<?>> handler; <ide> <ide> RetryWhenInner( <del> Function<? super Observable<? extends Throwable>, ? extends ObservableSource<?>> handler) { <add> Function<? super Observable<Throwable>, ? extends ObservableSource<?>> handler) { <ide> this.handler = handler; <ide> } <ide> <ide> public ObservableSource<?> apply(Observable<Notification<Object>> no) throws Exc <ide> } <ide> } <ide> <del> public static <T> Function<Observable<Notification<Object>>, ObservableSource<?>> retryWhenHandler(final Function<? super Observable<? extends Throwable>, ? extends ObservableSource<?>> handler) { <add> public static <T> Function<Observable<Notification<Object>>, ObservableSource<?>> retryWhenHandler(final Function<? super Observable<Throwable>, ? extends ObservableSource<?>> handler) { <ide> return new RetryWhenInner(handler); <ide> } <ide>
6
PHP
PHP
require files more than once
9740c18b9213d0da7cc0e8648b3a13053d5a7721
<ide><path>src/Core/BasePlugin.php <ide> public function routes($routes) <ide> { <ide> $path = $this->getConfigPath() . DS . 'routes.php'; <ide> if (file_exists($path)) { <del> require_once $path; <add> require $path; <ide> } <ide> } <ide> <ide> public function bootstrap() <ide> { <ide> $bootstrap = $this->getConfigPath() . DS . 'bootstrap.php'; <ide> if (file_exists($bootstrap)) { <del> require_once $bootstrap; <add> require $bootstrap; <ide> } <ide> } <ide>
1
Python
Python
remove dead code from shakespeare_main model
6d6ab9ca95eeaa54d595a165815c9811d26f1c66
<ide><path>official/staging/shakespeare/shakespeare_main.py <ide> def build_model(vocab_size, <ide> Returns: <ide> A Keras Model. <ide> """ <del> # In V1 there is a separate class for CuDNN. In V2 the LSTM class will use <del> # CuDNN automatically if applicable. <del> if use_cudnn and not keras_utils.is_v2_0(): <del> LSTM = tf.compat.v1.CuDNNLSTM <del> else: <del> # The LSTM call was rewritten to be more efficient in 2.0. However because <del> # we want to compare the performance of the two runtimes, we force both <del> # V1 and V2 to use the more efficient implementation. <del> LSTM = functools.partial(tf.keras.layers.LSTM, implementation=2) <add> assert keras_utils.is_v2_0() <add> LSTM = functools.partial(tf.keras.layers.LSTM, implementation=2) <ide> <ide> # By indirecting the activation through a lambda layer, the logic to dispatch <ide> # to CuDNN in V2 doesn't trigger and we force the LSTM to run in non-CuDNN
1
Ruby
Ruby
remove warnings on ruby trunk
d48222d22ef576c1b429ec2321c712bc221698d7
<ide><path>guides/bug_report_templates/action_controller_master.rb <del>unless File.exists?('Gemfile') <add>unless File.exist?('Gemfile') <ide> File.write('Gemfile', <<-GEMFILE) <ide> source 'https://rubygems.org' <ide> gem 'rails', github: 'rails/rails' <ide> def test_returns_success <ide> def app <ide> Rails.application <ide> end <del>end <ide>\ No newline at end of file <add>end <ide><path>guides/bug_report_templates/active_record_master.rb <del>unless File.exists?('Gemfile') <add>unless File.exist?('Gemfile') <ide> File.write('Gemfile', <<-GEMFILE) <ide> source 'https://rubygems.org' <ide> gem 'rails', github: 'rails/rails' <ide><path>guides/code/getting_started/config/boot.rb <ide> # Set up gems listed in the Gemfile. <ide> ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) <ide> <del>require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE']) <add>require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE']) <ide><path>guides/rails_guides.rb <ide> def bundler? <ide> # Note that rake sets the cwd to the one that contains the Rakefile <ide> # being executed. <del> File.exists?('Gemfile') <add> File.exist?('Gemfile') <ide> end <ide> <ide> begin <ide><path>guides/rails_guides/generator.rb <ide> def output_path_for(output_file) <ide> def generate?(source_file, output_file) <ide> fin = File.join(source_dir, source_file) <ide> fout = output_path_for(output_file) <del> all || !File.exists?(fout) || File.mtime(fout) < File.mtime(fin) <add> all || !File.exist?(fout) || File.mtime(fout) < File.mtime(fin) <ide> end <ide> <ide> def generate_guide(guide, output_file)
5
Text
Text
add drf-base64 to third-party serializers
d98a0772d0423b8f5f49b8198af72020fad2d570
<ide><path>docs/api-guide/serializers.md <ide> The [drf-dynamic-fields][drf-dynamic-fields] package provides a mixin to dynamic <ide> <ide> The [html-json-forms][html-json-forms] package provides an algorithm and serializer for processing `<form>` submissions per the (inactive) [HTML JSON Form specification][json-form-spec]. The serializer facilitates processing of arbitrarily nested JSON structures within HTML. For example, `<input name="items[0][id]" value="5">` will be interpreted as `{"items": [{"id": "5"}]}`. <ide> <add>## DRF-Base64 <add> <add>[DRF-Base64][drf-base64] provides a set of field and model serializers that handles the upload of base64-encoded files. <add> <ide> [cite]: https://groups.google.com/d/topic/django-users/sVFaOfQi4wY/discussion <ide> [relations]: relations.md <ide> [model-managers]: https://docs.djangoproject.com/en/stable/topics/db/managers/ <ide> The [html-json-forms][html-json-forms] package provides an algorithm and seriali <ide> [html-json-forms]: https://github.com/wq/html-json-forms <ide> [json-form-spec]: https://www.w3.org/TR/html-json-forms/ <ide> [drf-dynamic-fields]: https://github.com/dbrgn/drf-dynamic-fields <add>[drf-base64]: https://bitbucket.org/levit_scs/drf_base64
1
Javascript
Javascript
add options hash to replacewith docs
aa65e1c93c8bbbd6913c68d02045ac36b0a6dd1a
<ide><path>packages/ember-routing/lib/system/route.js <ide> let Route = EmberObject.extend(ActionHandler, Evented, { <ide> @param {String} name the name of the route or a URL <ide> @param {...Object} models the model(s) or identifier(s) to be used while <ide> transitioning to the route. <add> @param {Object} [options] optional hash with a queryParams property <add> containing a mapping of query parameters <ide> @return {Transition} the transition object associated with this <ide> attempted transition <ide> @since 1.0.0
1
PHP
PHP
fix coding standards
89100f947682ae0cdbc383a3dfbd152c5da884d5
<ide><path>lib/Cake/Test/Case/TestSuite/CakeTestFixtureTest.php <ide> public function insertCallback($table, $fields, $values) { <ide> $this->insertMulti['fields'] = $fields; <ide> $this->insertMulti['values'] = $values; <ide> $this->insertMulti['fields_values'] = array(); <del> foreach($values as $record) { <add> foreach ($values as $record) { <ide> $this->insertMulti['fields_values'][] = array_combine($fields, $record); <ide> } <ide> return true; <ide> public function testInsertStrings() { <ide> $this->assertEquals($expected, $this->insertMulti['values']); <ide> $expected = array( <ide> array( <del> 'name' => 'Mark Doe', <del> 'email' => 'mark.doe@email.com', <add> 'name' => 'Mark Doe', <add> 'email' => 'mark.doe@email.com', <ide> 'age' => null <ide> ), <ide> array( <del> 'name' => 'John Doe', <del> 'email' => 'john.doe@email.com', <add> 'name' => 'John Doe', <add> 'email' => 'john.doe@email.com', <ide> 'age' => 20 <ide> ), <ide> array( <del> 'name' => 'Jane Doe', <del> 'email' => 'jane.doe@email.com', <add> 'name' => 'Jane Doe', <add> 'email' => 'jane.doe@email.com', <ide> 'age' => 30 <ide> ), <ide> ); <ide><path>lib/Cake/Test/Case/TestSuite/CakeTestSuiteDispatcherTest.php <ide> <?php <add>/** <add> * CakeTestSuiteDispatcherTest file <add> * <add> * Test Case for CakeTestSuiteDispatcher class <add> * <add> * PHP version 5 <add> * <add> * CakePHP : 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 Project <add> * @package Cake.Test.Case.TestSuite <add> * @since CakePHP v 2.3.2 <add> * @license MIT License (http://www.opensource.org/licenses/mit-license.php) <add> */ <ide> <ide> class CakeTestSuiteDispatcherTest extends CakeTestCase { <ide> <del> public function setUp() { <del> $this->vendors = App::path('vendors'); <del> $this->includePath = ini_get('include_path'); <del> } <add> public function setUp() { <add> $this->vendors = App::path('vendors'); <add> $this->includePath = ini_get('include_path'); <add> } <ide> <del> public function tearDown() { <del> App::build(array('Vendor' => $this->vendors), App::RESET); <del> ini_set('include_path', $this->includePath); <del> } <add> public function tearDown() { <add> App::build(array('Vendor' => $this->vendors), App::RESET); <add> ini_set('include_path', $this->includePath); <add> } <ide> <del> protected function clearPaths() { <del> App::build(array('Vendor' => array('junk')), App::RESET); <del> ini_set('include_path', 'junk'); <del> } <add> protected function clearPaths() { <add> App::build(array('Vendor' => array('junk')), App::RESET); <add> ini_set('include_path', 'junk'); <add> } <ide> <del> public function testLoadTestFramework() { <del> $dispatcher = new CakeTestSuiteDispatcher(); <add> public function testLoadTestFramework() { <add> $dispatcher = new CakeTestSuiteDispatcher(); <ide> <del> $this->assertTrue($dispatcher->loadTestFramework()); <add> $this->assertTrue($dispatcher->loadTestFramework()); <ide> <del> $this->clearPaths(); <add> $this->clearPaths(); <ide> <del> $exception = null; <add> $exception = null; <ide> <del> try { <del> $dispatcher->loadTestFramework(); <del> } catch (Exception $ex) { <del> $exception = $ex; <del> } <add> try { <add> $dispatcher->loadTestFramework(); <add> } catch (Exception $ex) { <add> $exception = $ex; <add> } <ide> <del> $this->assertEquals(get_class($exception), "PHPUnit_Framework_Error_Warning"); <del> } <add> $this->assertEquals(get_class($exception), "PHPUnit_Framework_Error_Warning"); <add> } <ide> <del>} <add>} <ide>\ No newline at end of file <ide><path>lib/Cake/TestSuite/CakeTestSuiteDispatcher.php <ide> protected function _checkPHPUnit() { <ide> */ <ide> public function loadTestFramework() { <ide> foreach (App::path('vendors') as $vendor) { <del> $vendor = rtrim($vendor, DS); <add> $vendor = rtrim($vendor, DS); <ide> if (is_dir($vendor . DS . 'PHPUnit')) { <ide> ini_set('include_path', $vendor . PATH_SEPARATOR . ini_get('include_path')); <ide> break; <ide> } <ide> } <ide> <del> return (include('PHPUnit' . DS . 'Autoload.php')) !== false; <add> return (include ('PHPUnit' . DS . 'Autoload.php')) !== false; <ide> } <ide> <ide> /**
3
Ruby
Ruby
add free_port test helper
bfcba0f5f0a4c039939441c6f257b771f054c649
<ide><path>Library/Homebrew/dev-cmd/test.rb <ide> def test <ide> test_args.parse <ide> <ide> require "formula_assertions" <add> require "formula_free_port" <ide> <ide> args.resolved_formulae.each do |f| <ide> # Cannot test uninstalled formulae <ide><path>Library/Homebrew/formula_free_port.rb <add># frozen_string_literal: true <add> <add>module Homebrew <add> module FreePort <add> require "socket" <add> <add> def free_port <add> server = TCPServer.new 0 <add> _, port, = server.addr <add> server.close <add> <add> port <add> end <add> end <add>end <ide><path>Library/Homebrew/test.rb <ide> require "timeout" <ide> require "debrew" <ide> require "formula_assertions" <add>require "formula_free_port" <ide> require "fcntl" <ide> require "socket" <ide> require "cli/parser" <ide> <ide> formula = Homebrew.args.resolved_formulae.first <ide> formula.extend(Homebrew::Assertions) <add> formula.extend(Homebrew::FreePort) <ide> formula.extend(Debrew::Formula) if Homebrew.args.debug? <ide> <ide> # tests can also return false to indicate failure <ide><path>Library/Homebrew/test/formula_free_port_spec.rb <add># frozen_string_literal: true <add> <add>require "socket" <add>require "formula_free_port" <add> <add>module Homebrew <add> describe FreePort do <add> include described_class <add> <add> describe "#free_port" do <add> # IANA suggests user port from 1024 to 49151 <add> # and dynamic port for 49152 to 65535 <add> # http://www.iana.org/assignments/port-numbers <add> MIN_PORT = 1024 <add> MAX_PORT = 65535 <add> <add> it "returns a free TCP/IP port" do <add> port = free_port <add> <add> expect(port).to be_between(MIN_PORT, MAX_PORT) <add> expect { TCPServer.new(port).close }.not_to raise_error <add> end <add> end <add> end <add>end
4
PHP
PHP
add better tests for hasone
0fc7f57c7b6422b7e3ecd4fa2fbcaf5603607b88
<ide><path>tests/Fixture/ProfilesFixture.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.5.0 <add> * @license http://www.opensource.org/licenses/mit-license.php MIT License <add> */ <add>namespace Cake\Test\Fixture; <add> <add>use Cake\TestSuite\Fixture\TestFixture; <add> <add>/** <add> * ProfileFixture <add> */ <add>class ProfilesFixture extends TestFixture <add>{ <add> <add> /** <add> * fields property <add> * <add> * @var array <add> */ <add> public $fields = [ <add> 'id' => ['type' => 'integer'], <add> 'user_id' => ['type' => 'integer', 'null' => false], <add> 'first_name' => ['type' => 'string', 'null' => true], <add> 'last_name' => ['type' => 'string', 'null' => true], <add> 'is_active' => ['type' => 'boolean', 'null' => false, 'default' => true], <add> '_constraints' => [ <add> 'primary' => ['type' => 'primary', 'columns' => ['id']], <add> 'user_idx' => [ <add> 'type' => 'foreign', <add> 'columns' => ['user_id'], <add> 'references' => ['users', 'id'] <add> ] <add> ] <add> ]; <add> <add> /** <add> * records property <add> * <add> * @var array <add> */ <add> public $records = [ <add> ['user_id' => 1, 'first_name' => 'mariano', 'last_name' => 'iglesias', 'is_active' => false], <add> ['user_id' => 2, 'first_name' => 'nate', 'last_name' => 'abele', 'is_active' => false], <add> ['user_id' => 3, 'first_name' => 'larry', 'last_name' => 'masters', 'is_active' => true], <add> ['user_id' => 4, 'first_name' => 'garrett', 'last_name' => 'woodworth', 'is_active' => false], <add> ]; <add>} <ide><path>tests/TestCase/ORM/Association/HasOneTest.php <ide> */ <ide> class HasOneTest extends TestCase <ide> { <add> /** <add> * Fixtures to load <add> * <add> * @var array <add> */ <add> public $fixtures = ['core.users', 'core.profiles']; <add> <ide> /** <ide> * Set up <ide> * <ide> class HasOneTest extends TestCase <ide> public function setUp() <ide> { <ide> parent::setUp(); <del> $this->user = TableRegistry::get('Users', [ <del> 'schema' => [ <del> 'id' => ['type' => 'integer'], <del> 'username' => ['type' => 'string'], <del> '_constraints' => [ <del> 'primary' => ['type' => 'primary', 'columns' => ['id']] <del> ] <del> ] <del> ]); <del> $this->profile = TableRegistry::get('Profiles', [ <del> 'schema' => [ <del> 'id' => ['type' => 'integer'], <del> 'first_name' => ['type' => 'string'], <del> 'user_id' => ['type' => 'integer'], <del> '_constraints' => [ <del> 'primary' => ['type' => 'primary', 'columns' => ['id']] <del> ] <del> ] <del> ]); <del> $this->profilesTypeMap = new TypeMap([ <del> 'Profiles.id' => 'integer', <del> 'id' => 'integer', <del> 'Profiles.first_name' => 'string', <del> 'first_name' => 'string', <del> 'Profiles.user_id' => 'integer', <del> 'user_id' => 'integer', <del> 'Profiles__first_name' => 'string', <del> 'Profiles__user_id' => 'integer', <del> 'Profiles__id' => 'integer', <del> ]); <add> $this->user = TableRegistry::get('Users'); <add> $this->profile = TableRegistry::get('Profiles'); <ide> } <ide> <ide> /** <ide> public function testCanBeJoined() <ide> */ <ide> public function testAttachTo() <ide> { <del> $query = $this->getMockBuilder('\Cake\ORM\Query') <del> ->setMethods(['join', 'select']) <del> ->setConstructorArgs([null, null]) <del> ->getMock(); <ide> $config = [ <ide> 'foreignKey' => 'user_id', <ide> 'sourceTable' => $this->user, <ide> 'targetTable' => $this->profile, <add> 'property' => 'profile', <add> 'joinType' => 'INNER', <ide> 'conditions' => ['Profiles.is_active' => true] <ide> ]; <ide> $association = new HasOne('Profiles', $config); <del> $field = new IdentifierExpression('Profiles.user_id'); <del> $query->expects($this->once())->method('join')->with([ <del> 'Profiles' => [ <del> 'conditions' => new QueryExpression([ <del> 'Profiles.is_active' => true, <del> ['Users.id' => $field], <del> ], $this->profilesTypeMap), <del> 'type' => 'LEFT', <del> 'table' => 'profiles' <del> ] <del> ]); <del> $query->expects($this->once())->method('select')->with([ <del> 'Profiles__id' => 'Profiles.id', <del> 'Profiles__first_name' => 'Profiles.first_name', <del> 'Profiles__user_id' => 'Profiles.user_id' <del> ]); <add> $query = $this->user->find(); <ide> $association->attachTo($query); <ide> <del> $this->assertEquals( <del> 'string', <del> $query->typeMap()->type('Profiles__first_name'), <del> 'Associations should map types.' <del> ); <add> $results = $query->order('Users.id')->toArray(); <add> $this->assertCount(1, $results, 'Only one record because of conditions & join type'); <add> $this->assertSame('masters', $results[0]->Profiles['last_name']); <ide> } <ide> <ide> /** <ide> public function testAttachTo() <ide> */ <ide> public function testAttachToNoFields() <ide> { <del> $query = $this->getMockBuilder('\Cake\ORM\Query') <del> ->setMethods(['join', 'select']) <del> ->setConstructorArgs([null, null]) <del> ->getMock(); <ide> $config = [ <ide> 'sourceTable' => $this->user, <ide> 'targetTable' => $this->profile, <ide> 'conditions' => ['Profiles.is_active' => true] <ide> ]; <ide> $association = new HasOne('Profiles', $config); <del> $field = new IdentifierExpression('Profiles.user_id'); <del> $query->expects($this->once())->method('join')->with([ <del> 'Profiles' => [ <del> 'conditions' => new QueryExpression([ <del> 'Profiles.is_active' => true, <del> ['Users.id' => $field], <del> ], $this->profilesTypeMap), <del> 'type' => 'LEFT', <del> 'table' => 'profiles' <del> ] <del> ]); <del> $query->expects($this->never())->method('select'); <add> $query = $this->user->query(); <ide> $association->attachTo($query, ['includeFields' => false]); <add> $this->assertEmpty($query->clause('select')); <ide> } <ide> <ide> /** <ide> public function testAttachToNoFields() <ide> */ <ide> public function testAttachToMultiPrimaryKey() <ide> { <del> $query = $this->getMockBuilder('\Cake\ORM\Query') <del> ->setMethods(['join', 'select']) <del> ->setConstructorArgs([null, null]) <del> ->getMock(); <add> $selectTypeMap = new TypeMap([ <add> 'Profiles.id' => 'integer', <add> 'id' => 'integer', <add> 'Profiles.first_name' => 'string', <add> 'first_name' => 'string', <add> 'Profiles.user_id' => 'integer', <add> 'user_id' => 'integer', <add> 'Profiles__first_name' => 'string', <add> 'Profiles__user_id' => 'integer', <add> 'Profiles__id' => 'integer', <add> 'Profiles__last_name' => 'string', <add> 'Profiles.last_name' => 'string', <add> 'last_name' => 'string', <add> 'Profiles__is_active' => 'boolean', <add> 'Profiles.is_active' => 'boolean', <add> 'is_active' => 'boolean', <add> ]); <ide> $config = [ <ide> 'sourceTable' => $this->user, <ide> 'targetTable' => $this->profile, <ide> 'conditions' => ['Profiles.is_active' => true], <ide> 'foreignKey' => ['user_id', 'user_site_id'] <ide> ]; <add> <ide> $this->user->primaryKey(['id', 'site_id']); <ide> $association = new HasOne('Profiles', $config); <add> <add> $query = $this->getMockBuilder('\Cake\ORM\Query') <add> ->setMethods(['join', 'select']) <add> ->setConstructorArgs([null, null]) <add> ->getMock(); <ide> $field1 = new IdentifierExpression('Profiles.user_id'); <ide> $field2 = new IdentifierExpression('Profiles.user_site_id'); <ide> $query->expects($this->once())->method('join')->with([ <ide> 'Profiles' => [ <ide> 'conditions' => new QueryExpression([ <ide> 'Profiles.is_active' => true, <ide> ['Users.id' => $field1, 'Users.site_id' => $field2], <del> ], $this->profilesTypeMap), <add> ], $selectTypeMap), <ide> 'type' => 'LEFT', <ide> 'table' => 'profiles' <ide> ] <ide> public function testAttachToMultiPrimaryKey() <ide> * @expectedExceptionMessage Cannot match provided foreignKey for "Profiles", got "(user_id)" but expected foreign key for "(id, site_id)" <ide> * @return void <ide> */ <del> public function testAttachToMultiPrimaryKeyMistmatch() <add> public function testAttachToMultiPrimaryKeyMismatch() <ide> { <ide> $query = $this->getMockBuilder('\Cake\ORM\Query') <ide> ->setMethods(['join', 'select']) <ide> public function testPropertyOption() <ide> */ <ide> public function testPropertyNoPlugin() <ide> { <del> $mock = $this->getMockBuilder('Cake\ORM\Table') <del> ->disableOriginalConstructor() <del> ->getMock(); <ide> $config = [ <ide> 'sourceTable' => $this->user, <del> 'targetTable' => $mock, <add> 'targetTable' => $this->profile, <ide> ]; <ide> $association = new HasOne('Contacts.Profiles', $config); <ide> $this->assertEquals('profile', $association->property()); <ide> public function testPropertyNoPlugin() <ide> */ <ide> public function testAttachToBeforeFind() <ide> { <del> $query = $this->getMockBuilder('\Cake\ORM\Query') <del> ->setMethods(['join', 'select']) <del> ->setConstructorArgs([null, null]) <del> ->getMock(); <ide> $config = [ <ide> 'foreignKey' => 'user_id', <ide> 'sourceTable' => $this->user, <ide> 'targetTable' => $this->profile, <ide> ]; <del> $listener = $this->getMockBuilder('stdClass') <del> ->setMethods(['__invoke']) <del> ->getMock(); <del> $this->profile->eventManager()->attach($listener, 'Model.beforeFind'); <add> $query = $this->user->query(); <add> <add> $this->listenerCalled = false; <add> $this->profile->eventManager()->on('Model.beforeFind', function($event, $query, $options, $primary) { <add> $this->listenerCalled = true; <add> $this->assertInstanceOf('\Cake\Event\Event', $event); <add> $this->assertInstanceOf('\Cake\ORM\Query', $query); <add> $this->assertInstanceOf('\ArrayObject', $options); <add> $this->assertFalse($primary); <add> }); <ide> $association = new HasOne('Profiles', $config); <del> $listener->expects($this->once())->method('__invoke') <del> ->with( <del> $this->isInstanceOf('\Cake\Event\Event'), <del> $this->isInstanceOf('\Cake\ORM\Query'), <del> $this->isInstanceOf('\ArrayObject'), <del> false <del> ); <ide> $association->attachTo($query); <add> $this->assertTrue($this->listenerCalled, 'beforeFind event not fired.'); <ide> } <ide> <ide> /** <ide> public function testAttachToBeforeFindExtraOptions() <ide> return $q->applyOptions(['something' => 'more']); <ide> }]); <ide> } <add> <add> /** <add> * Test cascading deletes. <add> * <add> * @return void <add> */ <add> public function testCascadeDelete() <add> { <add> $config = [ <add> 'dependent' => true, <add> 'sourceTable' => $this->user, <add> 'targetTable' => $this->profile, <add> 'conditions' => ['Profiles.is_active' => true], <add> 'cascadeCallbacks' => false, <add> ]; <add> $association = new HasOne('Profiles', $config); <add> <add> $this->profile->eventManager()->on('Model.beforeDelete', function () { <add> $this->fail('Callbacks should not be triggered when callbacks do not cascade.'); <add> }); <add> <add> $entity = new Entity(['id' => 1]); <add> $association->cascadeDelete($entity); <add> <add> $query = $this->profile->query()->where(['user_id' => 1]); <add> $this->assertEquals(1, $query->count(), 'Left non-matching row behind'); <add> <add> $query = $this->profile->query()->where(['user_id' => 3]); <add> $this->assertEquals(1, $query->count(), 'other records left behind'); <add> <add> $user = new Entity(['id' => 3]); <add> $this->assertTrue($association->cascadeDelete($user)); <add> $query = $this->profile->query()->where(['user_id' => 3]); <add> $this->assertEquals(0, $query->count(), 'Matching record was deleted.'); <add> } <add> <add> /** <add> * Test cascading delete with has many. <add> * <add> * @return void <add> */ <add> public function testCascadeDeleteCallbacks() <add> { <add> $config = [ <add> 'dependent' => true, <add> 'sourceTable' => $this->user, <add> 'targetTable' => $this->profile, <add> 'conditions' => ['Profiles.is_active' => true], <add> 'cascadeCallbacks' => true, <add> ]; <add> $association = new HasOne('Profiles', $config); <add> <add> $user = new Entity(['id' => 1]); <add> $this->assertTrue($association->cascadeDelete($user)); <add> <add> $query = $this->profile->query()->where(['user_id' => 1]); <add> $this->assertEquals(1, $query->count(), 'Left non-matching row behind'); <add> <add> $query = $this->profile->query()->where(['user_id' => 3]); <add> $this->assertEquals(1, $query->count(), 'other records left behind'); <add> <add> $user = new Entity(['id' => 3]); <add> $this->assertTrue($association->cascadeDelete($user)); <add> $query = $this->profile->query()->where(['user_id' => 3]); <add> $this->assertEquals(0, $query->count(), 'Matching record was deleted.'); <add> } <ide> }
2
PHP
PHP
add conditional container templates
61c41758f949c173528f84fa8e3cfb7b17a71e7e
<ide><path>src/View/Helper/FormHelper.php <ide> public function input($fieldName, array $options = []) { <ide> $errorSuffix = empty($error) ? '' : 'Error'; <ide> unset($options['error']); <ide> } <del> $template = 'inputContainer' . $errorSuffix; <add> <add> $template = $options['type'] . 'Container' . $errorSuffix; <add> if (!$this->templates($template)) { <add> $template = 'inputContainer' . $errorSuffix; <add> } <ide> <ide> $label = $options['label']; <ide> if ($options['type'] !== 'radio') { <ide><path>tests/TestCase/View/Helper/FormHelperTest.php <ide> public function testNestInputInLabel() { <ide> $this->assertTags($result, $expected); <ide> } <ide> <add>/** <add> * Test that *Container templates are used by input. <add> * <add> * @return void <add> */ <add> public function testInputContainerTemplates() { <add> $this->Form->templates([ <add> 'checkboxContainer' => '<div class="check">{{content}}</div>', <add> 'radioContainer' => '<div class="rad">{{content}}</div>', <add> 'radioContainerError' => '<div class="rad err">{{content}}</div>', <add> ]); <add> <add> $this->article['errors'] = [ <add> 'Article' => ['published' => 'error message'] <add> ]; <add> $this->Form->create($this->article); <add> <add> $result = $this->Form->input('accept', [ <add> 'type' => 'checkbox' <add> ]); <add> $expected = [ <add> 'div' => ['class' => 'check'], <add> ['input' => ['type' => 'hidden', 'name' => 'accept', 'value' => 0]], <add> ['input' => ['id' => 'accept', 'type' => 'checkbox', 'name' => 'accept', 'value' => 1]], <add> 'label' => ['for' => 'accept'], <add> 'Accept', <add> '/label', <add> '/div' <add> ]; <add> $this->assertTags($result, $expected); <add> <add> $result = $this->Form->input('accept', [ <add> 'type' => 'radio', <add> 'options' => ['Y', 'N'] <add> ]); <add> $this->assertContains('<div class="rad">', $result); <add> <add> $result = $this->Form->input('Article.published', [ <add> 'type' => 'radio', <add> 'options' => ['Y', 'N'] <add> ]); <add> $this->assertContains('<div class="rad err">', $result); <add> } <add> <ide> /** <ide> * Test resetting templates. <ide> *
2
Ruby
Ruby
use version dups for resources (#534)
242508fca4d2b167cef3c355722f3471594d7b4b
<ide><path>Library/Homebrew/software_spec.rb <ide> def owner=(owner) <ide> @resource.owner = self <ide> resources.each_value do |r| <ide> r.owner = self <del> r.version ||= version <add> r.version ||= (version.head? ? Version.create("HEAD") : version.dup) <ide> end <ide> patches.each { |p| p.owner = self } <ide> end
1
Javascript
Javascript
remove legacypromise from src/core/obj.js
8616b2ccf3eea55e59bb5c7c0af292a55f77dd68
<ide><path>src/core/obj.js <ide> isStream, Lexer, Page, Parser, Promise, shadow, <ide> stringToPDFString, stringToUTF8String, warn, isString, <ide> Promise, MissingDataException, XRefParseException, Stream, <del> ChunkedStream, LegacyPromise */ <add> ChunkedStream, createPromiseCapability */ <ide> <ide> 'use strict'; <ide> <ide> var Dict = (function DictClosure() { <ide> // Same as get(), but returns a promise and uses fetchIfRefAsync(). <ide> getAsync: function Dict_getAsync(key1, key2, key3) { <ide> var value; <del> var promise; <ide> var xref = this.xref; <ide> if (typeof (value = this.map[key1]) !== undefined || key1 in this.map || <ide> typeof key2 === undefined) { <ide> if (xref) { <ide> return xref.fetchIfRefAsync(value); <ide> } <del> promise = new LegacyPromise(); <del> promise.resolve(value); <del> return promise; <add> return Promise.resolve(value); <ide> } <ide> if (typeof (value = this.map[key2]) !== undefined || key2 in this.map || <ide> typeof key3 === undefined) { <ide> if (xref) { <ide> return xref.fetchIfRefAsync(value); <ide> } <del> promise = new LegacyPromise(); <del> promise.resolve(value); <del> return promise; <add> return Promise.resolve(value); <ide> } <ide> value = this.map[key3] || null; <ide> if (xref) { <ide> return xref.fetchIfRefAsync(value); <ide> } <del> promise = new LegacyPromise(); <del> promise.resolve(value); <del> return promise; <add> return Promise.resolve(value); <ide> }, <ide> <ide> // no dereferencing <ide> var Catalog = (function CatalogClosure() { <ide> }, <ide> <ide> getPageDict: function Catalog_getPageDict(pageIndex) { <del> var promise = new LegacyPromise(); <add> var capability = createPromiseCapability(); <ide> var nodesToVisit = [this.catDict.getRaw('Pages')]; <ide> var currentPageIndex = 0; <ide> var xref = this.xref; <ide> var Catalog = (function CatalogClosure() { <ide> xref.fetchAsync(currentNode).then(function (obj) { <ide> if ((isDict(obj, 'Page') || (isDict(obj) && !obj.has('Kids')))) { <ide> if (pageIndex === currentPageIndex) { <del> promise.resolve([obj, currentNode]); <add> capability.resolve([obj, currentNode]); <ide> } else { <ide> currentPageIndex++; <ide> next(); <ide> var Catalog = (function CatalogClosure() { <ide> } <ide> nodesToVisit.push(obj); <ide> next(); <del> }.bind(this), promise.reject.bind(promise)); <add> }.bind(this), capability.reject.bind(capability)); <ide> return; <ide> } <ide> <ide> var Catalog = (function CatalogClosure() { <ide> } <ide> } <ide> } <del> promise.reject('Page index ' + pageIndex + ' not found.'); <add> capability.reject('Page index ' + pageIndex + ' not found.'); <ide> } <ide> next(); <del> return promise; <add> return capability.promise; <ide> }, <ide> <ide> getPageIndex: function Catalog_getPageIndex(ref) { <ide> var XRef = (function XRefClosure() { <ide> <ide> fetchIfRefAsync: function XRef_fetchIfRefAsync(obj) { <ide> if (!isRef(obj)) { <del> var promise = new LegacyPromise(); <del> promise.resolve(obj); <del> return promise; <add> return Promise.resolve(obj); <ide> } <ide> return this.fetchAsync(obj); <ide> }, <ide> <ide> fetchAsync: function XRef_fetchAsync(ref, suppressEncryption) { <del> var promise = new LegacyPromise(); <del> var tryFetch = function (promise) { <del> try { <del> promise.resolve(this.fetch(ref, suppressEncryption)); <del> } catch (e) { <del> if (e instanceof MissingDataException) { <del> this.stream.manager.requestRange(e.begin, e.end, tryFetch); <del> return; <del> } <del> promise.reject(e); <del> } <del> }.bind(this, promise); <del> tryFetch(); <del> return promise; <del> }, <add> return new Promise(function (resolve, reject) { <add> var tryFetch = function () { <add> try { <add> resolve(this.fetch(ref, suppressEncryption)); <add> } catch (e) { <add> if (e instanceof MissingDataException) { <add> this.stream.manager.requestRange(e.begin, e.end, tryFetch); <add> return; <add> } <add> reject(e); <add> } <add> }.bind(this); <add> tryFetch(); <add> }.bind(this)); <add> }, <ide> <ide> getCatalogObj: function XRef_getCatalogObj() { <ide> return this.root; <ide> var ObjectLoader = (function() { <ide> ObjectLoader.prototype = { <ide> load: function ObjectLoader_load() { <ide> var keys = this.keys; <del> this.promise = new LegacyPromise(); <add> this.capability = createPromiseCapability(); <ide> // Don't walk the graph if all the data is already loaded. <ide> if (!(this.xref.stream instanceof ChunkedStream) || <ide> this.xref.stream.getMissingChunks().length === 0) { <del> this.promise.resolve(); <del> return this.promise; <add> this.capability.resolve(); <add> return this.capability.promise; <ide> } <ide> <ide> this.refSet = new RefSet(); <ide> var ObjectLoader = (function() { <ide> } <ide> <ide> this.walk(nodesToVisit); <del> return this.promise; <add> return this.capability.promise; <ide> }, <ide> <ide> walk: function ObjectLoader_walk(nodesToVisit) { <ide> var ObjectLoader = (function() { <ide> } <ide> // Everything is loaded. <ide> this.refSet = null; <del> this.promise.resolve(); <add> this.capability.resolve(); <ide> } <ide> }; <ide>
1
Ruby
Ruby
fix core/all require of adjacent core features
3202671dc9360c4a89d80355824b239b52b2f611
<ide><path>activesupport/lib/active_support/core/all.rb <ide> require 'active_support/core' <del>Dir["#{File.dirname(__FILE__)}/core/*.rb"].sort.each do |path| <add>Dir["#{File.dirname(__FILE__)}/*.rb"].sort.each do |path| <ide> require "active_support/core/#{File.basename(path, '.rb')}" <ide> end
1
Python
Python
solve issue #206 / server port in client mode
a9a7a70d67c771e791f0a6512e2ae264871870a0
<ide><path>glances/glances.py <ide> def main(): <ide> stats.update({}) <ide> elif client_tag: <ide> # Init the client (displaying server stat in the CLI) <del> client = GlancesClient(server_ip, server_port, username, password) <add> client = GlancesClient(server_ip, int(server_port), username, password) <ide> <ide> # Test if client and server are in the same major version <ide> if not client.client_init():
1
Go
Go
use spf13/cobra for docker top
0f3866926763447c247bb24268923b5e50c006e1
<ide><path>api/client/commands.go <ide> func (cli *DockerCli) Command(name string) func(...string) error { <ide> "save": cli.CmdSave, <ide> "stats": cli.CmdStats, <ide> "tag": cli.CmdTag, <del> "top": cli.CmdTop, <ide> "update": cli.CmdUpdate, <ide> "version": cli.CmdVersion, <ide> "wait": cli.CmdWait, <ide><path>api/client/container/top.go <add>package container <add> <add>import ( <add> "fmt" <add> "strings" <add> "text/tabwriter" <add> <add> "golang.org/x/net/context" <add> <add> "github.com/docker/docker/api/client" <add> "github.com/docker/docker/cli" <add> "github.com/spf13/cobra" <add>) <add> <add>type topOptions struct { <add> container string <add> <add> args []string <add>} <add> <add>// NewTopCommand creats a new cobra.Command for `docker top` <add>func NewTopCommand(dockerCli *client.DockerCli) *cobra.Command { <add> var opts topOptions <add> <add> cmd := &cobra.Command{ <add> Use: "top CONTAINER [ps OPTIONS]", <add> Short: "Display the running processes of a container", <add> Args: cli.RequiresMinArgs(1), <add> RunE: func(cmd *cobra.Command, args []string) error { <add> opts.container = args[0] <add> opts.args = args[1:] <add> return runTop(dockerCli, &opts) <add> }, <add> } <add> cmd.SetFlagErrorFunc(flagErrorFunc) <add> <add> flags := cmd.Flags() <add> flags.SetInterspersed(false) <add> <add> return cmd <add>} <add> <add>func runTop(dockerCli *client.DockerCli, opts *topOptions) error { <add> ctx := context.Background() <add> <add> procList, err := dockerCli.Client().ContainerTop(ctx, opts.container, opts.args) <add> if err != nil { <add> return err <add> } <add> <add> w := tabwriter.NewWriter(dockerCli.Out(), 20, 1, 3, ' ', 0) <add> fmt.Fprintln(w, strings.Join(procList.Titles, "\t")) <add> <add> for _, proc := range procList.Processes { <add> fmt.Fprintln(w, strings.Join(proc, "\t")) <add> } <add> w.Flush() <add> return nil <add>} <ide><path>api/client/top.go <del>package client <del> <del>import ( <del> "fmt" <del> "strings" <del> "text/tabwriter" <del> <del> "golang.org/x/net/context" <del> <del> Cli "github.com/docker/docker/cli" <del> flag "github.com/docker/docker/pkg/mflag" <del>) <del> <del>// CmdTop displays the running processes of a container. <del>// <del>// Usage: docker top CONTAINER <del>func (cli *DockerCli) CmdTop(args ...string) error { <del> cmd := Cli.Subcmd("top", []string{"CONTAINER [ps OPTIONS]"}, Cli.DockerCommands["top"].Description, true) <del> cmd.Require(flag.Min, 1) <del> <del> cmd.ParseFlags(args, true) <del> <del> var arguments []string <del> if cmd.NArg() > 1 { <del> arguments = cmd.Args()[1:] <del> } <del> <del> procList, err := cli.client.ContainerTop(context.Background(), cmd.Arg(0), arguments) <del> if err != nil { <del> return err <del> } <del> <del> w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0) <del> fmt.Fprintln(w, strings.Join(procList.Titles, "\t")) <del> <del> for _, proc := range procList.Processes { <del> fmt.Fprintln(w, strings.Join(proc, "\t")) <del> } <del> w.Flush() <del> return nil <del>} <ide><path>cli/cobraadaptor/adaptor.go <ide> func NewCobraAdaptor(clientFlags *cliflags.ClientFlags) CobraAdaptor { <ide> container.NewRunCommand(dockerCli), <ide> container.NewStartCommand(dockerCli), <ide> container.NewStopCommand(dockerCli), <add> container.NewTopCommand(dockerCli), <ide> container.NewUnpauseCommand(dockerCli), <ide> image.NewRemoveCommand(dockerCli), <ide> image.NewSearchCommand(dockerCli), <ide><path>cli/usage.go <ide> var DockerCommandUsage = []Command{ <ide> {"save", "Save one or more images to a tar archive"}, <ide> {"stats", "Display a live stream of container(s) resource usage statistics"}, <ide> {"tag", "Tag an image into a repository"}, <del> {"top", "Display the running processes of a container"}, <ide> {"update", "Update configuration of one or more containers"}, <ide> {"version", "Show the Docker version information"}, <ide> {"wait", "Block until a container stops, then print its exit code"},
5
Text
Text
add 13 and 12 to previous versions
7f94fe004062ab2f5c84a927bfaf9c2ed2c06968
<ide><path>BUILDING.md <ide> Supported platforms and toolchains change with each major version of Node.js. <ide> This document is only valid for the current major version of Node.js. <ide> Consult previous versions of this document for older versions of Node.js: <ide> <add>* [Node.js 13](https://github.com/nodejs/node/blob/v13.x/BUILDING.md) <add>* [Node.js 12](https://github.com/nodejs/node/blob/v12.x/BUILDING.md) <ide> * [Node.js 10](https://github.com/nodejs/node/blob/v10.x/BUILDING.md) <ide> * [Node.js 8](https://github.com/nodejs/node/blob/v8.x/BUILDING.md) <del>* [Node.js 6](https://github.com/nodejs/node/blob/v6.x/BUILDING.md) <ide> <ide> ## Building Node.js on supported platforms <ide>
1
PHP
PHP
add truncationstrategy manager
6a7fa33b555d0ecb8a5a3e566ab85c318612f0cd
<ide><path>src/TestSuite/Fixture/TruncationStrategy.php <add><?php <add>declare(strict_types=1); <add> <add>/** <add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (https://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. (https://cakefoundation.org) <add> * @link https://cakephp.org CakePHP(tm) Project <add> * @since 4.3.0 <add> * @license https://opensource.org/licenses/mit-license.php MIT License <add> */ <add>namespace Cake\TestSuite\Fixture; <add> <add>use Cake\Database\Connection; <add>use Cake\Database\Schema\SqlGeneratorInterface; <add>use Cake\Datasource\ConnectionManager; <add> <add>/** <add> * Fixture state strategy that truncates tables before a test. <add> * <add> * This strategy is slower than the TransactionStrategy, but <add> * allows tests to reset state when applications require operations <add> * that cannot be executed in a transaction. An example <add> * of this is DDL operations in MySQL which auto-commit any open <add> * transactions. <add> * <add> * This mode also offers 'backwards compatible' behavior <add> * with the schema + data fixture system. <add> */ <add>class TruncationStrategy <add>{ <add> /** <add> * Constructor. <add> * <add> * @param bool $enableLogging Whether or not to enable query logging. <add> * @return void <add> */ <add> public function __construct(bool $enableLogging = false) <add> { <add> $this->aliasConnections($enableLogging); <add> } <add> <add> /** <add> * Alias non test connections to the test ones <add> * so that models reach the test database connections instead. <add> * <add> * @param bool $enableLogging Whether or not to enable query logging. <add> * @return void <add> */ <add> protected function aliasConnections(bool $enableLogging): void <add> { <add> $connections = ConnectionManager::configured(); <add> ConnectionManager::alias('test', 'default'); <add> $map = []; <add> foreach ($connections as $connection) { <add> if ($connection === 'test' || $connection === 'default') { <add> continue; <add> } <add> if (isset($map[$connection])) { <add> continue; <add> } <add> if (strpos($connection, 'test_') === 0) { <add> $map[$connection] = substr($connection, 5); <add> } else { <add> $map['test_' . $connection] = $connection; <add> } <add> } <add> foreach ($map as $testConnection => $normal) { <add> ConnectionManager::alias($testConnection, $normal); <add> $connection = ConnectionManager::get($normal); <add> if ($connection instanceof Connection && $enableLogging) { <add> $connection->enableQueryLogging(); <add> } <add> } <add> } <add> <add> /** <add> * Before each test start a transaction. <add> * <add> * @return void <add> */ <add> public function beforeTest(): void <add> { <add> $connections = ConnectionManager::configured(); <add> foreach ($connections as $connection) { <add> if (strpos($connection, 'test') !== 0) { <add> continue; <add> } <add> $db = ConnectionManager::get($connection); <add> if (!($db instanceof Connection)) { <add> continue; <add> } <add> <add> $db->disableConstraints(function (Connection $db): void { <add> $schema = $db->getSchemaCollection(); <add> foreach ($schema->listTables() as $table) { <add> $tableSchema = $schema->describe($table); <add> if (!($tableSchema instanceof SqlGeneratorInterface)) { <add> continue; <add> } <add> $sql = $tableSchema->truncateSql($db); <add> foreach ($sql as $stmt) { <add> $db->execute($stmt)->closeCursor(); <add> } <add> } <add> }); <add> } <add> } <add> <add> /** <add> * No op. <add> * <add> * Implemented to satisfy the interface. <add> * <add> * @return void <add> */ <add> public function afterTest(): void <add> { <add> // Do nothing <add> } <add>} <ide><path>tests/TestCase/TestSuite/Fixture/TruncationStrategyTest.php <add><?php <add>declare(strict_types=1); <add> <add>/** <add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (https://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. (https://cakefoundation.org) <add> * @link https://cakephp.org CakePHP(tm) Project <add> * @since 4.3.0 <add> * @license https://opensource.org/licenses/mit-license.php MIT License <add> */ <add>namespace Cake\Test\TestCase\TestSuite; <add> <add>use Cake\ORM\TableRegistry; <add>use Cake\TestSuite\Fixture\TruncationStrategy; <add>use Cake\TestSuite\TestCase; <add> <add>/** <add> * TruncationStrategy test <add> */ <add>class TruncationStrategyTest extends TestCase <add>{ <add> public $fixtures = ['core.Articles', 'core.ArticlesTags', 'core.Tags']; <add> <add> /** <add> * Test that beforeTest truncates tables from the previous test <add> * <add> * @return void <add> */ <add> public function testBeforeTestSimple() <add> { <add> $articles = TableRegistry::get('Articles'); <add> $articlesTags = TableRegistry::get('ArticlesTags'); <add> <add> $rowCount = $articles->find()->count(); <add> $this->assertGreaterThan(0, $rowCount); <add> $rowCount = $articlesTags->find()->count(); <add> $this->assertGreaterThan(0, $rowCount); <add> <add> $strategy = new TruncationStrategy(); <add> $strategy->beforeTest(); <add> <add> $rowCount = $articles->find()->count(); <add> $this->assertEquals(0, $rowCount); <add> $rowCount = $articlesTags->find()->count(); <add> $this->assertEquals(0, $rowCount); <add> } <add>}
2
Python
Python
set a constant to buffer_size
8bab6d630648f660c00585cbe68b9937f0a9a31c
<ide><path>keras/preprocessing/image_dataset.py <ide> def image_dataset_from_directory(directory, <ide> dataset = dataset.batch(batch_size) <ide> else: <ide> if shuffle: <del> dataset = dataset.shuffle(buffer_size=len(dataset), seed=seed) <add> dataset = dataset.shuffle(buffer_size=1024, seed=seed) <ide> <ide> # Users may need to reference `class_names`. <ide> dataset.class_names = class_names <ide><path>keras/preprocessing/text_dataset.py <ide> def text_dataset_from_directory(directory, <ide> dataset = dataset.batch(batch_size) <ide> else: <ide> if shuffle: <del> dataset = dataset.shuffle(buffer_size=len(dataset), seed=seed) <add> dataset = dataset.shuffle(buffer_size=1024, seed=seed) <ide> <ide> # Users may need to reference `class_names`. <ide> dataset.class_names = class_names <ide><path>keras/preprocessing/timeseries.py <ide> def timeseries_dataset_from_array( <ide> dataset = dataset.batch(batch_size) <ide> else: <ide> if shuffle: <del> dataset = dataset.shuffle(buffer_size=len(dataset), seed=seed) <add> dataset = dataset.shuffle(buffer_size=1024, seed=seed) <ide> return dataset <ide> <ide>
3
Text
Text
fix typo in events.md
757d7ba12b156ee2c5aaca1702bab2f95d28c750
<ide><path>doc/api/events.md <ide> added: v14.5.0 <ide> <ide> * Returns: {EventTarget} this <ide> <del>Node.js-speciic alias for `eventTarget.removeListener()`. <add>Node.js-specific alias for `eventTarget.removeListener()`. <ide> <ide> #### `nodeEventTarget.on(type, listener[, options])` <ide> <!-- YAML
1
Text
Text
add a step to the release process
c8f14c26b05d84ac6f5d1fd93e9572d589b837f2
<ide><path>scripts/release-manager/Readme.md <ide> git push <ide> **This step is only necessary for a stable release.** <ide> If you’re just cutting an alpha, you should skip it. <ide> <del>Copy your new release notes from `CHANGELOG.md` and [create a new Release](https://github.com/facebook/react/releases/new) on GitHub. Choose the tag version you just pushed in the dropdown so that it says “Existing tag”. Paste the release notes and push the button. <add>Copy your new release notes from `CHANGELOG.md` and [create a new Release](https://github.com/facebook/react/releases/new) on GitHub. Choose the tag version you just pushed in the dropdown so that it says “Existing tag”. Paste the release notes. <add> <add>Finally, attach these files to the release: <add> <add>* `build/react.js` <add>* `build/react.min.js` <add>* `build/react-dom.js` <add>* `build/react-dom.min.js` <ide> <ide> ### Force-Updating the Website <ide>
1
Text
Text
use proper casing for vmware in readme
9030f531659ddc9ca7bfffcb708cde579973e2ae
<ide><path>README.md <ide> security@docker.com and not by creating a github issue. <ide> <ide> A common method for distributing applications and sandboxing their <ide> execution is to use virtual machines, or VMs. Typical VM formats are <del>VMWare's vmdk, Oracle VirtualBox's vdi, and Amazon EC2's ami. In theory <add>VMware's vmdk, Oracle VirtualBox's vdi, and Amazon EC2's ami. In theory <ide> these formats should allow every developer to automatically package <ide> their application into a "machine" for easy distribution and deployment. <ide> In practice, that almost never happens, for a few reasons:
1
Javascript
Javascript
fix initial scenes rendering
81c62c5f41da2e34f0c0e19ca38843918c23c32b
<ide><path>Libraries/CustomComponents/NavigationExperimental/NavigationCardStackStyleInterpolator.js <ide> import type { <ide> * +------------+ <ide> */ <ide> <add>/** <add> * Render the initial style when the initial layout isn't measured yet. <add> */ <add>function forInitial(props: NavigationSceneRendererProps): Object { <add> const { <add> navigationState, <add> scene, <add> } = props; <add> <add> const focused = navigationState.index === scene.index; <add> const opacity = focused ? 1 : 0; <add> // If not focused, move the scene to the far away. <add> const translate = focused ? 0 : 1000000; <add> return { <add> opacity, <add> transform: [ <add> { translateX: translate }, <add> { translateY: translate }, <add> ], <add> }; <add>} <add> <ide> function forHorizontal(props: NavigationSceneRendererProps): Object { <ide> const { <ide> layout, <ide> position, <ide> scene, <ide> } = props; <ide> <add> if (!layout.isMeasured) { <add> return forInitial(props); <add> } <add> <ide> const index = scene.index; <ide> const inputRange = [index - 1, index, index + 1]; <ide> const width = layout.initWidth; <ide> function forVertical(props: NavigationSceneRendererProps): Object { <ide> scene, <ide> } = props; <ide> <add> if (!layout.isMeasured) { <add> return forInitial(props); <add> } <add> <ide> const index = scene.index; <ide> const inputRange = [index - 1, index, index + 1]; <ide> const height = layout.initHeight; <ide><path>Libraries/NavigationExperimental/NavigationAnimatedView.js <ide> type Props = { <ide> }; <ide> <ide> type State = { <add> layout: NavigationLayout, <ide> position: NavigationAnimatedValue, <ide> scenes: Array<NavigationScene>, <ide> }; <ide> function applyDefaultAnimation( <ide> class NavigationAnimatedView <ide> extends React.Component<any, Props, State> { <ide> <del> _layout: NavigationLayout; <ide> _onLayout: (event: any) => void; <ide> _onProgressChange: (data: {value: number}) => void; <ide> _positionListener: any; <ide> class NavigationAnimatedView <ide> constructor(props: Props, context: any) { <ide> super(props, context); <ide> <del> this._layout = { <del> initWidth: 0, <add> // The initial layout isn't measured. Measured layout will be only available <add> // when the component is mounted. <add> const layout = { <add> height: new Animated.Value(0), <ide> initHeight: 0, <add> initWidth: 0, <add> isMeasured: false, <ide> width: new Animated.Value(0), <del> height: new Animated.Value(0), <ide> }; <ide> <ide> this.state = { <add> layout, <ide> position: new Animated.Value(this.props.navigationState.index), <ide> scenes: NavigationScenesReducer([], this.props.navigationState), <ide> }; <ide> class NavigationAnimatedView <ide> } = this.state; <ide> <ide> return renderScene({ <del> layout: this._layout, <add> layout: this.state.layout, <ide> navigationState, <ide> onNavigate, <ide> position, <ide> class NavigationAnimatedView <ide> } = this.state; <ide> <ide> return renderOverlay({ <del> layout: this._layout, <add> layout: this.state.layout, <ide> navigationState, <ide> onNavigate, <ide> position, <ide> class NavigationAnimatedView <ide> const {height, width} = event.nativeEvent.layout; <ide> <ide> const layout = { <del> ...this._layout, <add> ...this.state.layout, <ide> initHeight: height, <ide> initWidth: width, <add> isMeasured: true, <ide> }; <ide> <del> this._layout = layout; <del> <ide> layout.height.setValue(height); <ide> layout.width.setValue(width); <add> <add> this.setState({ layout }); <ide> } <ide> } <ide> <ide><path>Libraries/NavigationExperimental/NavigationPropTypes.js <ide> const layout = PropTypes.shape({ <ide> height: animatedValue, <ide> initHeight: PropTypes.number.isRequired, <ide> initWidth: PropTypes.number.isRequired, <add> isMeasured: PropTypes.bool.isRequired, <ide> width: animatedValue, <ide> }); <ide> <ide><path>Libraries/NavigationExperimental/NavigationTypeDefinition.js <ide> export type NavigationLayout = { <ide> height: NavigationAnimatedValue, <ide> initHeight: number, <ide> initWidth: number, <add> isMeasured: boolean, <ide> width: NavigationAnimatedValue, <ide> }; <ide>
4
PHP
PHP
reword exception explanation
19b98082129931c73612e4b4b3e8b34f6635740d
<ide><path>src/Cache/SimpleCacheEngine.php <ide> public function clear() <ide> * @param iterable $keys A list of keys that can obtained in a single operation. <ide> * @param mixed $default Default value to return for keys that do not exist. <ide> * @return iterable A list of key => value pairs. Cache keys that do not exist or are stale will have $default as value. <del> * @throws \Psr\SimpleCache\InvalidArgumentException <del> * MUST be thrown if $keys is neither an array nor a Traversable, <add> * @throws \Psr\SimpleCache\InvalidArgumentException If $keys is neither an array nor a Traversable, <ide> * or if any of the $keys are not a legal value. <ide> */ <ide> public function getMultiple($keys, $default = null)
1
Python
Python
add test for deepmac builder
441f14a6aac221406aeb98c96df3ef3d0c3752f9
<ide><path>research/object_detection/builders/model_builder.py <ide> from object_detection.core import target_assigner <ide> from object_detection.meta_architectures import center_net_meta_arch <ide> from object_detection.meta_architectures import context_rcnn_meta_arch <add>from object_detection.meta_architectures import deepmac_meta_arch <ide> from object_detection.meta_architectures import faster_rcnn_meta_arch <ide> from object_detection.meta_architectures import rfcn_meta_arch <ide> from object_detection.meta_architectures import ssd_meta_arch <ide><path>research/object_detection/builders/model_builder_tf2_test.py <ide> from object_detection.builders import model_builder <ide> from object_detection.builders import model_builder_test <ide> from object_detection.core import losses <add>from object_detection.meta_architectures import deepmac_meta_arch <ide> from object_detection.models import center_net_hourglass_feature_extractor <ide> from object_detection.models.keras_models import hourglass_network <ide> from object_detection.protos import center_net_pb2 <ide> def test_create_center_net_model_mobilenet(self): <ide> # Verify that there are up_sampling2d layers. <ide> self.assertGreater(num_up_sampling2d_layers, 0) <ide> <add> def test_create_center_net_deepmac(self): <add> """Test building a CenterNet DeepMAC model.""" <add> <add> proto_txt = """ <add> center_net { <add> num_classes: 90 <add> feature_extractor { <add> type: "hourglass_52" <add> } <add> image_resizer { <add> keep_aspect_ratio_resizer { <add> min_dimension: 512 <add> max_dimension: 512 <add> pad_to_max_dimension: true <add> } <add> } <add> object_detection_task { <add> task_loss_weight: 1.0 <add> offset_loss_weight: 1.0 <add> scale_loss_weight: 0.1 <add> localization_loss { <add> l1_localization_loss { <add> } <add> } <add> } <add> object_center_params { <add> object_center_loss_weight: 1.0 <add> min_box_overlap_iou: 0.7 <add> max_box_predictions: 100 <add> classification_loss { <add> penalty_reduced_logistic_focal_loss { <add> alpha: 2.0 <add> beta: 4.0 <add> } <add> } <add> } <add> <add> deepmac_mask_estimation { <add> classification_loss { <add> weighted_sigmoid {} <add> } <add> } <add> } <add> """ <add> # Set up the configuration proto. <add> config = text_format.Parse(proto_txt, model_pb2.DetectionModel()) <add> <add> # Build the model from the configuration. <add> model = model_builder.build(config, is_training=True) <add> self.assertIsInstance(model, deepmac_meta_arch.DeepMACMetaArch) <add> <ide> <ide> if __name__ == '__main__': <ide> tf.test.main()
2
Python
Python
define __ne__ when __eq__
cd27aef18aaccabd7c063e6c0cba7426c70be435
<ide><path>celery/datastructures.py <ide> def as_dict(self): <ide> def __eq__(self, other): <ide> return self._heap == other._heap <ide> <add> def __ne__(self, other): <add> return not self.__eq__(other) <add> <ide> def __repr__(self): <ide> return 'LimitedSet({0})'.format(len(self)) <ide> <ide><path>celery/result.py <ide> def __eq__(self, other): <ide> return other == self.id <ide> return NotImplemented <ide> <add> def __ne__(self, other): <add> return not self.__eq__(other) <add> <ide> def __copy__(self): <ide> r = self.__reduce__() <ide> return r[0](*r[1]) <ide> def __eq__(self, other): <ide> return other.results == self.results <ide> return NotImplemented <ide> <add> def __ne__(self, other): <add> return not self.__eq__(other) <add> <ide> def __repr__(self): <ide> return '<{0}: [{1}]>'.format(type(self).__name__, <ide> ', '.join(r.id for r in self.results)) <ide> def __eq__(self, other): <ide> return other.id == self.id and other.results == self.results <ide> return NotImplemented <ide> <add> def __ne__(self, other): <add> return not self.__eq__(other) <add> <ide> def __repr__(self): <ide> return '<{0}: {1} [{2}]>'.format(type(self).__name__, self.id, <ide> ', '.join(r.id for r in self.results)) <ide><path>celery/schedules.py <ide> def __eq__(self, other): <ide> return self.run_every == other.run_every <ide> return self.run_every == other <ide> <add> def __ne__(self, other): <add> return not self.__eq__(other) <add> <ide> @property <ide> def seconds(self): <ide> return timedelta_seconds(self.run_every) <ide> def __eq__(self, other): <ide> other.minute == self.minute) <ide> return other is self <ide> <add> def __ne__(self, other): <add> return not self.__eq__(other) <add> <ide> <ide> def maybe_schedule(s, relative=False): <ide> if isinstance(s, int): <ide><path>celery/utils/timer2.py <ide> def __gt__(self, other): <ide> def __eq__(self, other): <ide> return hash(self) == hash(other) <ide> <add> def __ne__(self, other): <add> return not self.__eq__(other) <add> <ide> <ide> def to_timestamp(d, default_timezone=timezone.utc): <ide> if isinstance(d, datetime):
4
Java
Java
add nonnull annotation to fabric event classes
a58fcbff0bfd27a442884010aae48957a9990de1
<ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/events/EventBeatManager.java <ide> package com.facebook.react.fabric.events; <ide> <ide> import android.annotation.SuppressLint; <add>import androidx.annotation.NonNull; <ide> import com.facebook.jni.HybridData; <ide> import com.facebook.proguard.annotations.DoNotStrip; <ide> import com.facebook.react.bridge.ReactApplicationContext; <ide> public class EventBeatManager implements BatchEventDispatchedListener { <ide> <ide> private native void beat(); <ide> <del> public EventBeatManager(ReactApplicationContext reactApplicationContext) { <add> public EventBeatManager(@NonNull ReactApplicationContext reactApplicationContext) { <ide> mHybridData = initHybrid(); <ide> mReactApplicationContext = reactApplicationContext; <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/events/EventEmitterWrapper.java <ide> package com.facebook.react.fabric.events; <ide> <ide> import android.annotation.SuppressLint; <add>import androidx.annotation.NonNull; <ide> import androidx.annotation.Nullable; <ide> import com.facebook.jni.HybridData; <ide> import com.facebook.proguard.annotations.DoNotStrip; <ide> private EventEmitterWrapper() { <ide> mHybridData = initHybrid(); <ide> } <ide> <del> private native void invokeEvent(String eventName, NativeMap params); <add> private native void invokeEvent(@NonNull String eventName, @NonNull NativeMap params); <ide> <ide> /** <ide> * Invokes the execution of the C++ EventEmitter. <ide> * <ide> * @param eventName {@link String} name of the event to execute. <ide> * @param params {@link WritableMap} payload of the event <ide> */ <del> public void invoke(String eventName, @Nullable WritableMap params) { <add> public void invoke(@NonNull String eventName, @Nullable WritableMap params) { <ide> NativeMap payload = params == null ? new WritableNativeMap() : (NativeMap) params; <ide> invokeEvent(eventName, payload); <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/events/FabricEventEmitter.java <ide> import static com.facebook.react.uimanager.events.TouchesHelper.TOUCHES_KEY; <ide> <ide> import android.util.Pair; <add>import androidx.annotation.NonNull; <ide> import androidx.annotation.Nullable; <ide> import com.facebook.common.logging.FLog; <ide> import com.facebook.react.bridge.ReadableMap; <ide> <ide> public class FabricEventEmitter implements RCTEventEmitter { <ide> <del> private static final String TAG = FabricEventEmitter.class.getSimpleName(); <add> private static final String TAG = "FabricEventEmitter"; <ide> <del> private final FabricUIManager mUIManager; <add> @NonNull private final FabricUIManager mUIManager; <ide> <del> public FabricEventEmitter(FabricUIManager uiManager) { <add> public FabricEventEmitter(@NonNull FabricUIManager uiManager) { <ide> mUIManager = uiManager; <ide> } <ide> <ide> @Override <del> public void receiveEvent(int reactTag, String eventName, @Nullable WritableMap params) { <add> public void receiveEvent(int reactTag, @NonNull String eventName, @Nullable WritableMap params) { <ide> Systrace.beginSection( <ide> Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, <ide> "FabricEventEmitter.receiveEvent('" + eventName + "')"); <ide> public void receiveEvent(int reactTag, String eventName, @Nullable WritableMap p <ide> <ide> @Override <ide> public void receiveTouches( <del> String eventTopLevelType, WritableArray touches, WritableArray changedIndices) { <add> @NonNull String eventTopLevelType, <add> @NonNull WritableArray touches, <add> @NonNull WritableArray changedIndices) { <ide> Pair<WritableArray, WritableArray> result = <ide> TOP_TOUCH_END_KEY.equalsIgnoreCase(eventTopLevelType) <ide> || TOP_TOUCH_CANCEL_KEY.equalsIgnoreCase(eventTopLevelType) <ide> public void receiveTouches( <ide> } <ide> <ide> /** TODO T31905686 optimize this to avoid copying arrays */ <del> private WritableArray copyWritableArray(WritableArray array) { <add> private WritableArray copyWritableArray(@NonNull WritableArray array) { <ide> WritableNativeArray ret = new WritableNativeArray(); <ide> for (int i = 0; i < array.size(); i++) { <ide> ret.pushMap(getWritableMap(array.getMap(i))); <ide> private WritableArray copyWritableArray(WritableArray array) { <ide> * @param indices {WritableArray} Indices to remove from `touches`. <ide> * @return {Array<Touch>} Subsequence of removed touch objects. <ide> */ <del> private Pair<WritableArray, WritableArray> removeTouchesAtIndices( <del> WritableArray touches, WritableArray indices) { <add> private @NonNull Pair<WritableArray, WritableArray> removeTouchesAtIndices( <add> @NonNull WritableArray touches, @NonNull WritableArray indices) { <ide> WritableArray rippedOut = new WritableNativeArray(); <ide> // use an unsafe downcast to alias to nullable elements, <ide> // so we can delete and then compact. <ide> private Pair<WritableArray, WritableArray> removeTouchesAtIndices( <ide> * @param changedIndices {@link WritableArray} Indices by which to pull subsequence. <ide> * @return {Array<Touch>} Subsequence of touch objects. <ide> */ <del> private Pair<WritableArray, WritableArray> touchSubsequence( <del> WritableArray touches, WritableArray changedIndices) { <add> private @NonNull Pair<WritableArray, WritableArray> touchSubsequence( <add> @NonNull WritableArray touches, @NonNull WritableArray changedIndices) { <ide> WritableArray result = new WritableNativeArray(); <ide> for (int i = 0; i < changedIndices.size(); i++) { <ide> result.pushMap(getWritableMap(touches.getMap(changedIndices.getInt(i)))); <ide> private Pair<WritableArray, WritableArray> touchSubsequence( <ide> * <ide> * @param readableMap {@link ReadableMap} source map <ide> */ <del> private WritableMap getWritableMap(ReadableMap readableMap) { <add> private @NonNull WritableMap getWritableMap(@NonNull ReadableMap readableMap) { <ide> WritableNativeMap map = new WritableNativeMap(); <ide> map.merge(readableMap); <ide> return map; <ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/MountingManager.java <ide> import android.view.ViewGroup; <ide> import android.view.ViewParent; <ide> import androidx.annotation.AnyThread; <add>import androidx.annotation.NonNull; <ide> import androidx.annotation.Nullable; <ide> import androidx.annotation.UiThread; <ide> import com.facebook.infer.annotation.Assertions; <ide> public class MountingManager { <ide> public static final String TAG = MountingManager.class.getSimpleName(); <ide> <del> private final ConcurrentHashMap<Integer, ViewState> mTagToViewState; <del> private final JSResponderHandler mJSResponderHandler = new JSResponderHandler(); <del> private final ViewManagerRegistry mViewManagerRegistry; <del> private final RootViewManager mRootViewManager = new RootViewManager(); <add> @NonNull private final ConcurrentHashMap<Integer, ViewState> mTagToViewState; <add> @NonNull private final JSResponderHandler mJSResponderHandler = new JSResponderHandler(); <add> @NonNull private final ViewManagerRegistry mViewManagerRegistry; <add> @NonNull private final RootViewManager mRootViewManager = new RootViewManager(); <ide> <del> public MountingManager(ViewManagerRegistry viewManagerRegistry) { <add> public MountingManager(@NonNull ViewManagerRegistry viewManagerRegistry) { <ide> mTagToViewState = new ConcurrentHashMap<>(); <ide> mViewManagerRegistry = viewManagerRegistry; <ide> } <ide> <del> public void addRootView(int reactRootTag, View rootView) { <add> public void addRootView(int reactRootTag, @NonNull View rootView) { <ide> if (rootView.getId() != View.NO_ID) { <ide> throw new IllegalViewOperationException( <ide> "Trying to add a root view with an explicit id already set. React Native uses " <ide> public void addRootView(int reactRootTag, View rootView) { <ide> <ide> /** Releases all references to given native View. */ <ide> @UiThread <del> private void dropView(View view) { <add> private void dropView(@NonNull View view) { <ide> UiThreadUtil.assertOnUiThread(); <ide> <ide> int reactTag = view.getId(); <ide> public void addViewAt(int parentTag, int tag, int index) { <ide> getViewGroupManager(parentViewState).addView(parentView, view, index); <ide> } <ide> <del> private ViewState getViewState(int tag) { <add> private @NonNull ViewState getViewState(int tag) { <ide> ViewState viewState = mTagToViewState.get(tag); <ide> if (viewState == null) { <ide> throw new IllegalStateException("Unable to find viewState view for tag " + tag); <ide> public void receiveCommand(int reactTag, int commandId, @Nullable ReadableArray <ide> } <ide> <ide> if (viewState.mViewManager == null) { <del> throw new IllegalStateException("Unable to find viewState manager for tag " + reactTag); <add> throw new IllegalStateException("Unable to find viewManager for tag " + reactTag); <ide> } <ide> <ide> if (viewState.mView == null) { <ide> public void receiveCommand(int reactTag, int commandId, @Nullable ReadableArray <ide> viewState.mViewManager.receiveCommand(viewState.mView, commandId, commandArgs); <ide> } <ide> <del> public void receiveCommand(int reactTag, String commandId, @Nullable ReadableArray commandArgs) { <add> public void receiveCommand( <add> int reactTag, @NonNull String commandId, @Nullable ReadableArray commandArgs) { <ide> ViewState viewState = getNullableViewState(reactTag); <ide> <ide> if (viewState == null) { <ide> public void sendAccessibilityEvent(int reactTag, int eventType) { <ide> } <ide> <ide> @SuppressWarnings("unchecked") // prevents unchecked conversion warn of the <ViewGroup> type <del> private static ViewGroupManager<ViewGroup> getViewGroupManager(ViewState viewState) { <add> private static @NonNull ViewGroupManager<ViewGroup> getViewGroupManager( <add> @NonNull ViewState viewState) { <ide> if (viewState.mViewManager == null) { <ide> throw new IllegalStateException("Unable to find ViewManager for view: " + viewState); <ide> } <ide> public void removeViewAt(int parentTag, int index) { <ide> <ide> @UiThread <ide> public void createView( <del> ThemedReactContext themedReactContext, <del> String componentName, <add> @NonNull ThemedReactContext themedReactContext, <add> @NonNull String componentName, <ide> int reactTag, <ide> @Nullable ReadableMap props, <ide> @Nullable StateWrapper stateWrapper, <ide> public void createView( <ide> } <ide> <ide> @UiThread <del> public void updateProps(int reactTag, ReadableMap props) { <add> public void updateProps(int reactTag, @Nullable ReadableMap props) { <ide> if (props == null) { <ide> return; <ide> } <ide> public void deleteView(int reactTag) { <ide> } <ide> <ide> @UiThread <del> public void updateLocalData(int reactTag, ReadableMap newLocalData) { <add> public void updateLocalData(int reactTag, @NonNull ReadableMap newLocalData) { <ide> UiThreadUtil.assertOnUiThread(); <ide> ViewState viewState = getViewState(reactTag); <ide> if (viewState.mCurrentProps == null) { <ide> public void updateState(final int reactTag, @Nullable StateWrapper stateWrapper) <ide> <ide> @UiThread <ide> public void preallocateView( <del> ThemedReactContext reactContext, <add> @NonNull ThemedReactContext reactContext, <ide> String componentName, <ide> int reactTag, <ide> @Nullable ReadableMap props, <ide> public void preallocateView( <ide> } <ide> <ide> @UiThread <del> public void updateEventEmitter(int reactTag, EventEmitterWrapper eventEmitter) { <add> public void updateEventEmitter(int reactTag, @NonNull EventEmitterWrapper eventEmitter) { <ide> UiThreadUtil.assertOnUiThread(); <ide> ViewState viewState = getViewState(reactTag); <ide> viewState.mEventEmitter = eventEmitter; <ide> public void clearJSResponder() { <ide> <ide> @AnyThread <ide> public long measure( <del> Context context, <del> String componentName, <del> ReadableMap localData, <del> ReadableMap props, <del> ReadableMap state, <add> @NonNull Context context, <add> @NonNull String componentName, <add> @NonNull ReadableMap localData, <add> @NonNull ReadableMap props, <add> @NonNull ReadableMap state, <ide> float width, <del> YogaMeasureMode widthMode, <add> @NonNull YogaMeasureMode widthMode, <ide> float height, <del> YogaMeasureMode heightMode) { <add> @NonNull YogaMeasureMode heightMode) { <ide> <ide> return mViewManagerRegistry <ide> .get(componentName)
4
Ruby
Ruby
use require_dependency inside active storage
1e55ee5a283df448c6cf4c4d3bb9c98e49927520
<ide><path>activestorage/app/models/active_storage/blob.rb <ide> # update a blob's metadata on a subsequent pass, but you should not update the key or change the uploaded file. <ide> # If you need to create a derivative or otherwise change the blob, simply create a new blob and purge the old one. <ide> class ActiveStorage::Blob < ActiveRecord::Base <del> include ActiveStorage::Blob::Analyzable <del> include ActiveStorage::Blob::Identifiable <del> include ActiveStorage::Blob::Representable <add> require_dependency "active_storage/blob/analyzable" <add> require_dependency "active_storage/blob/identifiable" <add> require_dependency "active_storage/blob/representable" <add> <add> include Analyzable <add> include Identifiable <add> include Representable <ide> <ide> self.table_name = "active_storage_blobs" <ide> <ide><path>activestorage/app/models/active_storage/filename.rb <ide> # Encapsulates a string representing a filename to provide convenient access to parts of it and sanitization. <ide> # A Filename instance is returned by ActiveStorage::Blob#filename, and is comparable so it can be used for sorting. <ide> class ActiveStorage::Filename <add> require_dependency "active_storage/filename/parameters" <add> <ide> include Comparable <ide> <ide> class << self
2
Javascript
Javascript
change top bar colors for hot reloading label
e81c1e3c7a5300652c7d32f0e5ed1ee6324171a5
<ide><path>Libraries/Utilities/HMRLoadingView.ios.js <ide> class HMRLoadingView { <ide> if (NativeDevLoadingView != null) { <ide> NativeDevLoadingView.showMessage( <ide> message, <del> processColor('#000000'), <del> processColor('#aaaaaa'), <add> // Use same colors as iOS "Personal Hotspot" bar. <add> processColor('#ffffff'), <add> processColor('#2584e8'), <ide> ); <ide> } <ide> }
1
Javascript
Javascript
fix undefined error in parser event
95fafc0254f6636b7c7546ac63599c79a7182fd9
<ide><path>lib/_http_common.js <ide> function parserOnHeaders(headers, url) { <ide> function parserOnHeadersComplete(versionMajor, versionMinor, headers, method, <ide> url, statusCode, statusMessage, upgrade, <ide> shouldKeepAlive) { <del> var parser = this; <add> const parser = this; <add> const { socket } = parser; <ide> <ide> if (!headers) { <ide> headers = parser._headers; <ide> function parserOnHeadersComplete(versionMajor, versionMinor, headers, method, <ide> } <ide> <ide> // Parser is also used by http client <del> var ParserIncomingMessage = parser.socket && parser.socket.server ? <del> parser.socket.server[kIncomingMessage] : IncomingMessage; <add> const ParserIncomingMessage = (socket && socket.server && <add> socket.server[kIncomingMessage]) || <add> IncomingMessage; <ide> <del> parser.incoming = new ParserIncomingMessage(parser.socket); <add> parser.incoming = new ParserIncomingMessage(socket); <ide> parser.incoming.httpVersionMajor = versionMajor; <ide> parser.incoming.httpVersionMinor = versionMinor; <ide> parser.incoming.httpVersion = `${versionMajor}.${versionMinor}`;
1
PHP
PHP
accept string
e6995b8a07985c4eb116624c13ccb10eb12e3c58
<ide><path>src/Illuminate/Routing/PendingResourceRegistration.php <ide> public function except($methods) <ide> /** <ide> * Set the route names for controller actions. <ide> * <del> * @param array $names <add> * @param array|string $names <ide> * @return \Illuminate\Routing\PendingResourceRegistration <ide> */ <del> public function names(array $names) <add> public function names($names) <ide> { <ide> $this->options['names'] = $names; <ide> <ide><path>tests/Routing/RouteRegistrarTest.php <ide> public function testUserCanRegisterApiResource() <ide> <ide> public function testCanNameRoutesOnRegisteredResource() <ide> { <add> $this->router->resource('comments', 'Illuminate\Tests\Routing\RouteRegistrarControllerStub') <add> ->only('create', 'store')->names('reply'); <add> <ide> $this->router->resource('users', 'Illuminate\Tests\Routing\RouteRegistrarControllerStub') <ide> ->only('create', 'store')->names([ <ide> 'create' => 'user.build', <ide> public function testCanNameRoutesOnRegisteredResource() <ide> ->name('create', 'posts.make') <ide> ->name('destroy', 'posts.remove'); <ide> <add> $this->assertTrue($this->router->getRoutes()->hasNamedRoute('reply.create')); <add> $this->assertTrue($this->router->getRoutes()->hasNamedRoute('reply.store')); <ide> $this->assertTrue($this->router->getRoutes()->hasNamedRoute('user.build')); <ide> $this->assertTrue($this->router->getRoutes()->hasNamedRoute('user.save')); <ide> $this->assertTrue($this->router->getRoutes()->hasNamedRoute('posts.make'));
2
Python
Python
remove old comment
a8eecddf879848cadfa971fbc2d19de49ed5b446
<ide><path>libcloud/drivers/rackspace.py <ide> def reboot_node(self, node): <ide> return resp.status == 202 <ide> <ide> def _node_action(self, node, body): <del> ### consider this from old code: <del> # data = ('<%s xmlns="%s" %s/>' <del> # % (verb, NAMESPACE, <del> # ' '.join(['%s="%s"' % item for item in params.items()]))) <ide> if isinstance(body, list): <ide> attr = ' '.join(['%s="%s"' % (item[0], item[1]) for item in body[1:]]) <ide> body = '<%s xmlns="%s" %s/>' % (body[0], NAMESPACE, attr)
1
Python
Python
fix the undefined variable in squad example
7ac3311e487541b6b8a6a43a39c23ea343da3545
<ide><path>examples/run_squad.py <ide> def main(): <ide> train_examples = read_squad_examples( <ide> input_file=args.train_file, is_training=True, version_2_with_negative=args.version_2_with_negative) <ide> num_train_optimization_steps = int( <del> len(train_dataset) / args.train_batch_size / args.gradient_accumulation_steps) * args.num_train_epochs <add> len(train_examples) / args.train_batch_size / args.gradient_accumulation_steps) * args.num_train_epochs <ide> if args.local_rank != -1: <ide> num_train_optimization_steps = num_train_optimization_steps // torch.distributed.get_world_size() <ide>
1
Python
Python
add wip cloudflare driver
d3a3a4ab79926e715786113ab42d53310da7b712
<ide><path>libcloud/dns/drivers/cloudflare.py <add># Licensed to the Apache Software Foundation (ASF) under one or more <add># contributor license agreements. See the NOTICE file distributed with <add># this work for additional information regarding copyright ownership. <add># The ASF licenses this file to You under the Apache License, Version 2.0 <add># (the "License"); you may not use this file except in compliance with <add># the License. You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, software <add># distributed under the License is distributed on an "AS IS" BASIS, <add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add># See the License for the specific language governing permissions and <add># limitations under the License. <add> <add>__all__ = [ <add> 'CloudFlareDNSDriver' <add>] <add> <add>import copy <add> <add>from libcloud.common.base import JsonResponse, ConnectionUserAndKey <add>from libcloud.common.types import InvalidCredsError, LibcloudError <add>from libcloud.utils.py3 import httplib <add>from libcloud.dns.base import DNSDriver, Zone, Record <add>from libcloud.dns.types import Provider <add>from libcloud.dns.types import ZoneDoesNotExistError, RecordDoesNotExistError <add> <add>API_URL = 'https://www.cloudflare.com/api_json.html' <add>API_HOST = 'www.cloudflare.com' <add>API_PATH = '/api_json.html' <add> <add>ZONE_EXTRA_ATTRIBUTES = [ <add> 'display_name', <add> 'zone_status', <add> 'zone_type', <add> 'host_id', <add> 'host_pubname', <add> 'host_website', <add> 'fqdns', <add> 'vtxt', <add> 'step', <add> 'zone_status_class', <add> 'zone_status_desc', <add> 'orig_registrar', <add> 'orig_dnshost', <add> 'orig_ns_names' <add>] <add> <add>RECORD_EXTRA_ATTRIBUTES = [ <add> 'rec_tag', <add> 'display_name', <add> 'pro', <add> 'display_content', <add> 'ttl_ceil', <add> 'ssl_id', <add> 'ssl_status', <add> 'ssl_expires_on', <add> 'auto_ttl', <add> 'service_mode' <add>] <add> <add> <add>class CloudFlareDNSResponse(JsonResponse): <add> def success(self): <add> return self.status in [httplib.OK, httplib.CREATED, httplib.ACCEPTED] <add> <add> def parse_body(self): <add> body = super(CloudFlareDNSResponse, self).parse_body() <add> result = body.get('result', None) <add> error_code = body.get('err_code', None) <add> msg = body.get('msg', None) <add> <add> if error_code == 'E_UNAUTH': <add> raise InvalidCredsError(msg) <add> elif result == 'error' or error_code is not None: <add> msg = 'Request failed: %s' % (self.body) <add> raise LibcloudError(value=msg, driver=self.connection.driver) <add> <add> return body <add> <add> <add>class CloudFlareDNSConnection(ConnectionUserAndKey): <add> host = API_HOST <add> secure = True <add> responseCls = CloudFlareDNSResponse <add> <add> def request(self, action, params=None, data=None, headers=None, <add> method='GET'): <add> params = params or {} <add> data = data or {} <add> <add> base_params = { <add> 'email': self.user_id, <add> 'tkn': self.key, <add> 'a': action <add> } <add> params = copy.deepcopy(params) <add> params.update(base_params) <add> <add> return super(CloudFlareDNSConnection, self).request(action=API_PATH, <add> params=params, <add> data=None, <add> method=method, <add> headers=headers) <add> <add> <add>class CloudFlareDNSDriver(DNSDriver): <add> type = Provider.CLOUDFLARE <add> name = 'CloudFlare DNS' <add> website = 'https://www.cloudflare.com' <add> connectionCls = CloudFlareDNSConnection <add> <add> def iterate_zones(self): <add> # TODO: Support pagination <add> result = self.connection.request(action='zone_load_multi').object <add> zones = self._to_zones(data=result['response']['zones']['objs']) <add> <add> return zones <add> <add> def iterate_records(self, zone): <add> # TODO: Support pagination <add> params = {'z': zone.domain} <add> result = self.connection.request(action='rec_load_all', params=params).object <add> records = self._to_records(zone=zone, data=result['response']['recs']['objs']) <add> return records <add> <add> def ex_get_zone_stats(self, zone, interval=30): <add> params = {'z': zone.domain, 'interval': interval} <add> result = self.connection.request(action='stats', params=params).object <add> result = result['response']['result']['objs'] <add> return result <add> <add> def ex_zone_check(self, zones): <add> zone_domains = [zone.domain for zone in zones] <add> zone_domains = ','.join(zone_domains) <add> params = {'zones': zone_domains} <add> result = self.connection.request(action='zone_check', params=params).object <add> result = result['response']['zones'] <add> return result <add> <add> def ex_get_ip_threat_score(self, ip): <add> """ <add> Retrieve current threat score for a given IP. Note that scores are on <add> a logarithmic scale, where a higher score indicates a higher threat. <add> """ <add> params = {'ip': ip} <add> result = self.connection.request(action='ip_lkup', params=params).object <add> result = result['response'] <add> return result <add> <add> def ex_get_zone_settings(self, zone): <add> """ <add> Retrieve all current settings for a given zone. <add> """ <add> params = {'z': zone.domain} <add> result = self.connection.request(action='zone_settings', params=params).object <add> result = result['response']['result']['objs'][0] <add> return result <add> <add> def ex_set_zone_security_level(self, zone, level): <add> """ <add> Set the zone Basic Security Level to I'M UNDER ATTACK! / HIGH / MEDIUM / <add> LOW / ESSENTIALLY OFF. <add> <add> :param level: Security level. Valid values are: help, high, med, low, <add> eoff. <add> :type level: ``str`` <add> """ <add> params = {'z': zone.domain, 'v': level} <add> result = self.connection.request(action='sec_lvl', params=params).object <add> return result.get('result', None) == 'success' <add> <add> def ex_set_zone_cache_level(self, zone, level): <add> """ <add> Set the zone caching level. <add> <add> :param level: Caching level. Valid values are: agg (aggresive), basic. <add> :type level: ``str`` <add> """ <add> params = {'z': zone.domain, 'v': level} <add> result = self.connection.request(action='cache_lvl', params=params).object <add> return result.get('result', None) == 'success' <add> <add> def ex_enable_development_mode(self, zone): <add> """ <add> Enable development mode. When Development Mode is on the cache is <add> bypassed. Development mode remains on for 3 hours or until when it is <add> toggled back off. <add> """ <add> params = {'z': zone.domain, 'v': 1} <add> result = self.connection.request(action='devmode', params=params).object <add> return result.get('result', None) == 'success' <add> <add> def ex_disable_development_mode(self, zone): <add> """ <add> Disable development mode. <add> """ <add> params = {'z': zone.domain, 'v': 0} <add> result = self.connection.request(action='devmode', params=params).object <add> return result.get('result', None) == 'success' <add> <add> def ex_purge_cache_files(self, zone): <add> """ <add> Purge CloudFlare of any cached files. <add> """ <add> params = {'z': zone.domain, 'v': 1} <add> result = self.connection.request(action='fpurge_ts', params=params).object <add> return result.get('result', None) == 'success' <add> <add> def ex_purge_cache_file(self, zone, url): <add> """ <add> Purgle single file from CloudFlare's cache. <add> <add> :param url: URL to the file to purge from cache. <add> :type url: ``str`` <add> """ <add> params = {'z': zone.domain, 'url': url} <add> result = self.connection.request(action='zone_file_purge', params=params).object <add> return result.get('result', None) == 'success' <add> <add> def ex_whitelist_ip(self, zone, ip): <add> """ <add> Whitelist the provided IP. <add> """ <add> params = {'z': zone.domain, 'key': ip} <add> result = self.connection.request(action='wl', params=params).object <add> return result.get('result', None) == 'success' <add> <add> def ex_blacklist_ip(self, zone, ip): <add> """ <add> Blacklist the provided IP. <add> """ <add> params = {'z': zone.domain, 'key': ip} <add> result = self.connection.request(action='ban', params=params).object <add> return result.get('result', None) == 'success' <add> <add> def ex_unlist_ip(self, zone, ip): <add> """ <add> Remove provided ip from the whitelist and blacklist. <add> """ <add> params = {'z': zone.domain, 'key': ip} <add> result = self.connection.request(action='nul', params=params).object <add> return result.get('result', None) == 'success' <add> <add> def ex_enable_ipv6_support(self, zone): <add> """ <add> Enable IPv6 support for the provided zone. <add> """ <add> params = {'z': zone.domain, 'v': 3} <add> result = self.connection.request(action='ipv46', params=params).object <add> return result.get('result', None) == 'success' <add> <add> def ex_disable_ipv6_support(self, zone): <add> """ <add> Disable IPv6 support for the provided zone. <add> """ <add> params = {'z': zone.domain, 'v': 0} <add> result = self.connection.request(action='ipv46', params=params).object <add> return result.get('result', None) == 'success' <add> <add> <add> def _to_zones(self, data): <add> zones = [] <add> <add> for item in data: <add> zone = self._to_zone(item=item) <add> zones.append(zone) <add> <add> return zones <add> <add> def _to_zone(self, item): <add> type = 'master' if item.get('zone_type', '').lower() == 'p' else 'slave' <add> <add> extra = {} <add> extra['props'] = item.get('props', {}) <add> extra['confirm_code'] = item.get('confirm_code', {}) <add> extra['allow'] = item.get('allow', {}) <add> for attribute in ZONE_EXTRA_ATTRIBUTES: <add> value = item.get(attribute, None) <add> extra[attribute] = value <add> <add> zone = Zone(id=str(item['zone_id']), domain=item['zone_name'], type=type, <add> ttl=None, driver=self, extra=extra) <add> return zone <add> <add> def _to_records(self, zone, data): <add> records = [] <add> <add> for item in data: <add> record = self._to_record(zone=zone, item=item) <add> records.append(record) <add> <add> return records <add> <add> def _to_record(self, zone, item): <add> name = self._get_record_name(item=item) <add> type = item['type'] <add> data = item['content'] <add> <add> extra = {} <add> extra['ttl'] = item['ttl'] <add> extra['props'] = item.get('props', {}) <add> for attribute in RECORD_EXTRA_ATTRIBUTES: <add> value = item.get(attribute, None) <add> extra[attribute] = value <add> <add> record = Record(id=str(item['rec_id']), name=name, type=type, <add> data=data, zone=zone, driver=self, extra=extra) <add> return record <add> <add> def _get_record_name(self, item): <add> name = item['name'].replace('.' + item['zone_name'], '') or None <add> if name: <add> name = name.replace(item['zone_name'], '') or None <add> return name <ide><path>libcloud/dns/providers.py <ide> ('libcloud.dns.drivers.zonomi', 'ZonomiDNSDriver'), <ide> Provider.DURABLEDNS: <ide> ('libcloud.dns.drivers.durabledns', 'DurableDNSDriver'), <add> Provider.CLOUDFLARE: <add> ('libcloud.dns.drivers.cloudflare', 'CloudFlareDNSDriver'), <ide> # Deprecated <ide> Provider.RACKSPACE_US: <ide> ('libcloud.dns.drivers.rackspace', 'RackspaceUSDNSDriver'), <ide><path>libcloud/dns/types.py <ide> class Provider(object): <ide> LIQUIDWEB = 'liquidweb' <ide> ZONOMI = 'zonomi' <ide> DURABLEDNS = 'durabledns' <add> CLOUDFLARE = 'cloudflare' <ide> <ide> # Deprecated <ide> RACKSPACE_US = 'rackspace_us'
3
Text
Text
replace "comments.json" with this.props.url
7614af3c9a8ad950c6f0a73fad07c8161afcc180
<ide><path>docs/docs/tutorial.md <ide> var CommentBox = React.createClass({ <ide> }, <ide> componentWillMount: function() { <ide> $.ajax({ <del> url: 'comments.json', <add> url: this.props.url, <ide> dataType: 'json', <ide> success: function(data) { <ide> this.setState({data: data}); <ide> }.bind(this), <ide> error: function(xhr, status, err) { <del> console.error("comments.json", status, err.toString()); <add> console.error(this.props.url, status, err.toString()); <ide> }.bind(this) <ide> }); <ide> },
1
Python
Python
remove class variables
51d7fea2cdf6f066abf934b81a0629de9215a7be
<ide><path>libcloud/compute/base.py <ide> class VolumeSnapshot(object): <ide> """ <ide> A base VolumeSnapshot class to derive from. <ide> """ <del> id = None <del> driver = None <del> size = None <del> extra = None <del> created = None <del> <ide> def __init__(self, id, driver, size=None, extra=None, created=None): <ide> """ <ide> VolumeSnapshot constructor.
1
PHP
PHP
remove class from compilation
b28b995337c20aae42f0847bdca36e581f41eb5e
<ide><path>src/Illuminate/Foundation/Console/Optimize/config.php <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Support/ServiceProvider.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Support/AggregateServiceProvider.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Routing/RoutingServiceProvider.php', <del> $basePath.'/vendor/laravel/framework/src/Illuminate/Routing/ControllerServiceProvider.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Events/EventServiceProvider.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Validation/ValidationServiceProvider.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Foundation/Validation/ValidatesRequests.php',
1
Python
Python
fix typo in savetxt docstring (closes )
1aaf99a31835beacd49ced62a7d02120e6942522
<ide><path>numpy/lib/npyio.py <ide> def savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', <ide> a) a single specifier, `fmt='%.4e'`, resulting in numbers formatted <ide> like `' (%s+%sj)' % (fmt, fmt)` <ide> b) a full string specifying every real and imaginary part, e.g. <del> `' %.4e %+.4j %.4e %+.4j %.4e %+.4j'` for 3 columns <add> `' %.4e %+.4ej %.4e %+.4ej %.4e %+.4ej'` for 3 columns <ide> c) a list of specifiers, one per column - in this case, the real <ide> and imaginary part must have separate specifiers, <ide> e.g. `['%.3e + %.3ej', '(%.15e%+.15ej)']` for 2 columns
1
Java
Java
consolidate sendto vs sendtouser detection
46e41a9d94bf586e5a80f262d2eee31b9612e93f
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/annotation/support/SendToMethodReturnValueHandler.java <ide> public void handleReturnValue(Object returnValue, MethodParameter returnType, Me <ide> MessageHeaders headers = message.getHeaders(); <ide> String sessionId = SimpMessageHeaderAccessor.getSessionId(headers); <ide> PlaceholderResolver varResolver = initVarResolver(headers); <del> SendToUser sendToUser = getSendToUser(returnType); <add> Object annotation = findAnnotation(returnType); <ide> <del> if (sendToUser != null) { <add> if (annotation != null && annotation instanceof SendToUser) { <add> SendToUser sendToUser = (SendToUser) annotation; <ide> boolean broadcast = sendToUser.broadcast(); <ide> String user = getUserName(message, headers); <ide> if (user == null) { <ide> public void handleReturnValue(Object returnValue, MethodParameter returnType, Me <ide> } <ide> } <ide> else { <del> SendTo sendTo = getSendTo(returnType); <add> SendTo sendTo = (SendTo) annotation; <ide> String[] destinations = getTargetDestinations(sendTo, message, this.defaultDestinationPrefix); <ide> for (String destination : destinations) { <ide> destination = this.placeholderHelper.replacePlaceholders(destination, varResolver); <ide> public void handleReturnValue(Object returnValue, MethodParameter returnType, Me <ide> } <ide> } <ide> <add> private Object findAnnotation(MethodParameter returnType) { <add> Annotation[] annot = new Annotation[4]; <add> annot[0] = AnnotatedElementUtils.findMergedAnnotation(returnType.getMethod(), SendToUser.class); <add> annot[1] = AnnotatedElementUtils.findMergedAnnotation(returnType.getMethod(), SendTo.class); <add> annot[2] = AnnotatedElementUtils.findMergedAnnotation(returnType.getDeclaringClass(), SendToUser.class); <add> annot[3] = AnnotatedElementUtils.findMergedAnnotation(returnType.getDeclaringClass(), SendTo.class); <add> <add> if (annot[0] != null && !ObjectUtils.isEmpty(((SendToUser) annot[0]).value())) { <add> return annot[0]; <add> } <add> if (annot[1] != null && !ObjectUtils.isEmpty(((SendTo) annot[1]).value())) { <add> return annot[1]; <add> } <add> if (annot[2] != null && !ObjectUtils.isEmpty(((SendToUser) annot[2]).value())) { <add> return annot[2]; <add> } <add> if (annot[3] != null && !ObjectUtils.isEmpty(((SendTo) annot[3]).value())) { <add> return annot[3]; <add> } <add> <add> for (int i=0; i < 4; i++) { <add> if (annot[i] != null) { <add> return annot[i]; <add> } <add> } <add> <add> return null; <add> } <add> <ide> private SendToUser getSendToUser(MethodParameter returnType) { <ide> SendToUser annot = AnnotatedElementUtils.findMergedAnnotation(returnType.getMethod(), SendToUser.class); <ide> if (annot != null && !ObjectUtils.isEmpty(annot.value())) { <ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/annotation/support/SendToMethodReturnValueHandlerTests.java <ide> public void sendToUserClassDefaultOverride() throws Exception { <ide> assertResponse(this.userDefaultOverrideAnnotation, sessionId, 1, "/user/sess1/dest4"); <ide> } <ide> <add> @Test // SPR-14238 <add> public void sendToUserWithSendToDefaultOverride() throws Exception { <add> given(this.messageChannel.send(any(Message.class))).willReturn(true); <add> <add> Class<?> clazz = SendToUserWithSendToOverrideTestBean.class; <add> Method method = clazz.getDeclaredMethod("handleAndSendToDefaultDestination"); <add> MethodParameter parameter = new SynthesizingMethodParameter(method, -1); <add> <add> String sessionId = "sess1"; <add> Message<?> inputMessage = createMessage(sessionId, "sub1", null, null, null); <add> this.handler.handleReturnValue(PAYLOAD, parameter, inputMessage); <add> <add> verify(this.messageChannel, times(1)).send(this.messageCaptor.capture()); <add> assertResponse(parameter, sessionId, 0, "/user/sess1/dest-default"); <add> } <add> <add> @Test // SPR-14238 <add> public void sendToUserWithSendToOverride() throws Exception { <add> given(this.messageChannel.send(any(Message.class))).willReturn(true); <add> <add> Class<?> clazz = SendToUserWithSendToOverrideTestBean.class; <add> Method method = clazz.getDeclaredMethod("handleAndSendToOverride"); <add> MethodParameter parameter = new SynthesizingMethodParameter(method, -1); <add> <add> String sessionId = "sess1"; <add> Message<?> inputMessage = createMessage(sessionId, "sub1", null, null, null); <add> this.handler.handleReturnValue(PAYLOAD, parameter, inputMessage); <add> <add> verify(this.messageChannel, times(2)).send(this.messageCaptor.capture()); <add> assertResponse(parameter, sessionId, 0, "/dest3"); <add> assertResponse(parameter, sessionId, 1, "/dest4"); <add> } <add> <ide> <ide> private void assertResponse(MethodParameter methodParameter, String sessionId, <ide> int index, String destination) { <ide> public String getDestinationUserName() { <ide> <ide> @SendTo <ide> @Retention(RetentionPolicy.RUNTIME) <del> public @interface MySendTo { <add> @interface MySendTo { <ide> <ide> @AliasFor(annotation = SendTo.class, attribute = "value") <ide> String[] dest(); <ide> } <ide> <ide> @SendToUser <ide> @Retention(RetentionPolicy.RUNTIME) <del> public @interface MySendToUser { <add> @interface MySendToUser { <ide> <ide> @AliasFor(annotation = SendToUser.class, attribute = "destinations") <ide> String[] dest(); <ide> } <ide> <ide> <ide> @SuppressWarnings("unused") <del> public String handleNoAnnotations() { <add> String handleNoAnnotations() { <ide> return PAYLOAD; <ide> } <ide> <ide> @SendTo @SuppressWarnings("unused") <del> public String handleAndSendToDefaultDestination() { <add> String handleAndSendToDefaultDestination() { <ide> return PAYLOAD; <ide> } <ide> <ide> @SendTo({"/dest1", "/dest2"}) @SuppressWarnings("unused") <del> public String handleAndSendTo() { <add> String handleAndSendTo() { <ide> return PAYLOAD; <ide> } <ide> <ide> @SendTo("/topic/chat.message.filtered.{roomName}") @SuppressWarnings("unused") <del> public String handleAndSendToWithPlaceholders() { <add> String handleAndSendToWithPlaceholders() { <ide> return PAYLOAD; <ide> } <ide> <ide> @SendToUser @SuppressWarnings("unused") <del> public String handleAndSendToUserDefaultDestination() { <add> String handleAndSendToUserDefaultDestination() { <ide> return PAYLOAD; <ide> } <ide> <ide> @SendToUser(broadcast = false) @SuppressWarnings("unused") <del> public String handleAndSendToUserDefaultDestinationSingleSession() { <add> String handleAndSendToUserDefaultDestinationSingleSession() { <ide> return PAYLOAD; <ide> } <ide> <ide> @SendToUser({"/dest1", "/dest2"}) @SuppressWarnings("unused") <del> public String handleAndSendToUser() { <add> String handleAndSendToUser() { <ide> return PAYLOAD; <ide> } <ide> <ide> @SendToUser(destinations = { "/dest1", "/dest2" }, broadcast = false) @SuppressWarnings("unused") <del> public String handleAndSendToUserSingleSession() { <add> String handleAndSendToUserSingleSession() { <ide> return PAYLOAD; <ide> } <ide> <ide> @JsonView(MyJacksonView1.class) @SuppressWarnings("unused") <del> public JacksonViewBean handleAndSendToJsonView() { <add> JacksonViewBean handleAndSendToJsonView() { <ide> JacksonViewBean payload = new JacksonViewBean(); <ide> payload.setWithView1("with"); <ide> payload.setWithView2("with"); <ide> public JacksonViewBean handleAndSendToJsonView() { <ide> @MySendTo(dest = "/dest-default") @SuppressWarnings("unused") <ide> private static class SendToTestBean { <ide> <del> public String handleNoAnnotation() { <add> String handleNoAnnotation() { <ide> return PAYLOAD; <ide> } <ide> <ide> @SendTo <del> public String handleAndSendToDefaultDestination() { <add> String handleAndSendToDefaultDestination() { <ide> return PAYLOAD; <ide> } <ide> <ide> @MySendTo(dest = {"/dest3", "/dest4"}) <del> public String handleAndSendToOverride() { <add> String handleAndSendToOverride() { <ide> return PAYLOAD; <ide> } <ide> } <ide> <ide> @MySendToUser(dest = "/dest-default") @SuppressWarnings("unused") <ide> private static class SendToUserTestBean { <ide> <del> public String handleNoAnnotation() { <add> String handleNoAnnotation() { <ide> return PAYLOAD; <ide> } <ide> <ide> @SendToUser <del> public String handleAndSendToDefaultDestination() { <add> String handleAndSendToDefaultDestination() { <ide> return PAYLOAD; <ide> } <ide> <ide> @MySendToUser(dest = {"/dest3", "/dest4"}) <del> public String handleAndSendToOverride() { <add> String handleAndSendToOverride() { <add> return PAYLOAD; <add> } <add> } <add> <add> @MySendToUser(dest = "/dest-default") @SuppressWarnings("unused") <add> private static class SendToUserWithSendToOverrideTestBean { <add> <add> @SendTo <add> String handleAndSendToDefaultDestination() { <add> return PAYLOAD; <add> } <add> <add> @MySendTo(dest = {"/dest3", "/dest4"}) <add> String handleAndSendToOverride() { <ide> return PAYLOAD; <ide> } <ide> } <ide> public String getWithView1() { <ide> return withView1; <ide> } <ide> <del> public void setWithView1(String withView1) { <add> void setWithView1(String withView1) { <ide> this.withView1 = withView1; <ide> } <ide> <del> public String getWithView2() { <add> String getWithView2() { <ide> return withView2; <ide> } <ide> <del> public void setWithView2(String withView2) { <add> void setWithView2(String withView2) { <ide> this.withView2 = withView2; <ide> } <ide> <del> public String getWithoutView() { <add> String getWithoutView() { <ide> return withoutView; <ide> } <ide> <del> public void setWithoutView(String withoutView) { <add> void setWithoutView(String withoutView) { <ide> this.withoutView = withoutView; <ide> } <ide> }
2
Text
Text
add 0.69.2 changelog
31887277931cf2a3c84f6965df72e3bd85c16f8f
<ide><path>CHANGELOG.md <ide> # Changelog <ide> <add>## v0.69.2 <add> <add>### Changed <add> <add>- Set react-shallow-renderer v16.15.0 for react v18 compat ([a39a7c453d](https://github.com/facebook/react-native/commit/a39a7c453d87086935ff07d549ba8220cbcf30bd) by [@mikehardy](https://github.com/mikehardy)) <add>- Upgrade RN CLI to v8.0.3 ([28cbd21d21](https://github.com/facebook/react-native/commit/28cbd21d21f2ffb3f38b2449a4983f013947ce0a) by [@thymikee](https://github.com/thymikee)) <add> <add>#### iOS specific <add> <add>- Hermes pod: change logic to use the hermes tag to set the pod source correctly ([46a9edc854](https://github.com/facebook/react-native/commit/46a9edc8544ae070149a97ea3d919b88dd6e2942) by [@kelset](https://github.com/kelset)) <add>- Fix the race condition when calling readAsDataURL after new Blob(blobs) ([bd12e41188](https://github.com/facebook/react-native/commit/bd12e41188c8d85c0acbd713f10f0bd34ea0edca) by [@wood1986](https://github.com/wood1986)) <add>- Make sure that Flipper pods are not installed when creating a release build ([23accbf58d](https://github.com/facebook/react-native/commit/23accbf58d2fa03ad020e07f00012a32609c7218) by [@cipolleschi](https://github.com/cipolleschi)) <add> <ide> ## v0.69.1 <ide> <ide> ### Changed
1
Javascript
Javascript
fix the encoding problem for truetype
30460ce4b2bcc28090f9bb4d47f63841a6392a00
<ide><path>pdf.js <ide> var CanvasExtraState = (function() { <ide> const Encodings = { <ide> get ExpertEncoding() { <ide> return shadow(this, "ExpertEncoding", [ <add> null, null, null, null, null, null, null, null, null, null, null, <add> null, null, null, null, null, null, null, null, null, null, null, <add> null, null, null, null, null, null, null, null, null, null, <ide> "space","exclamsmall","Hungarumlautsmall",,"dollaroldstyle","dollarsuperior", <ide> "ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior", <ide> "twodotenleader","onedotenleader","comma","hyphen","period","fraction", <ide> const Encodings = { <ide> }, <ide> get MacExpertEncoding() { <ide> return shadow(this, "MacExpertEncoding", [ <add> null, null, null, null, null, null, null, null, null, null, null, <add> null, null, null, null, null, null, null, null, null, null, null, <add> null, null, null, null, null, null, null, null, null, null, <ide> "space","exclamsmall","Hungarumlautsmall","centoldstyle","dollaroldstyle", <ide> "dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior", <ide> "parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period", <ide> const Encodings = { <ide> }, <ide> get MacRomanEncoding() { <ide> return shadow(this, "MacRomanEncoding", [ <add> null, null, null, null, null, null, null, null, null, null, null, <add> null, null, null, null, null, null, null, null, null, null, null, <add> null, null, null, null, null, null, null, null, null, null, <ide> "space","exclam","quotedbl","numbersign","dollar","percent","ampersand", <ide> "quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen", <ide> "period","slash","zero","one","two","three","four","five","six","seven","eight", <ide> const Encodings = { <ide> }, <ide> get StandardEncoding() { <ide> return shadow(this, "StandardEncoding", [ <add> null, null, null, null, null, null, null, null, null, null, null, <add> null, null, null, null, null, null, null, null, null, null, null, <add> null, null, null, null, null, null, null, null, null, null, <ide> "space","exclam","quotedbl","numbersign","dollar","percent","ampersand", <ide> "quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period", <ide> "slash","zero","one","two","three","four","five","six","seven","eight","nine", <ide> const Encodings = { <ide> }, <ide> get WinAnsiEncoding() { <ide> return shadow(this, "WinAnsiEncoding", [ <add> null, null, null, null, null, null, null, null, null, null, null, <add> null, null, null, null, null, null, null, null, null, null, null, <add> null, null, null, null, null, null, null, null, null, null, <ide> "space","exclam","quotedbl","numbersign","dollar","percent","ampersand", <ide> "quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen", <ide> "period","slash","zero","one","two","three","four","five","six","seven","eight", <ide> const Encodings = { <ide> }, <ide> get zapfDingbatsEncoding() { <ide> return shadow(this, "zapfDingbatsEncoding", [ <add> null, null, null, null, null, null, null, null, null, null, null, <add> null, null, null, null, null, null, null, null, null, null, null, <add> null, null, null, null, null, null, null, null, null, null, <ide> "space","a1","a2","a202","a3","a4","a5","a119","a118","a117","a11","a12","a13", <ide> "a14","a15","a16","a105","a17","a18","a19","a20","a21","a22","a23","a24","a25", <ide> "a26","a27","a28","a6","a7","a8","a9","a10","a29","a30","a31","a32","a33","a34", <ide> var CanvasGraphics = (function() { <ide> var widths = xref.fetchIfRef(fontDict.get("Widths")); <ide> assertWellFormed(IsArray(widths) && IsInt(firstChar), <ide> "invalid font Widths or FirstChar"); <add> <ide> for (var j = 0; j < widths.length; j++) { <ide> if (widths[j]) <ide> charset.push(encoding[j + firstChar]);
1
PHP
PHP
set interest cohort
c42988a551ffdae0e70aa15959969732265789c0
<ide><path>src/Illuminate/Routing/Router.php <ide> public static function toResponse($request, $response) <ide> $response->setNotModified(); <ide> } <ide> <add> if (! $response->headers->has('Permissions-Policy')) { <add> $response->headers->set('Permissions-Policy', 'interest-cohort=()'); <add> } <add> <ide> return $response->prepare($request); <ide> } <ide>
1
PHP
PHP
fix failing sqlserverschema tests
aca68e244194c07ee60b85f4b4b36e3fe3535486
<ide><path>tests/TestCase/Database/Schema/SqlserverSchemaTest.php <ide> public function setUp() { <ide> */ <ide> protected function _needsConnection() { <ide> $config = ConnectionManager::config('test'); <del> $this->skipIf(strpos($config['className'], 'Sqlserver') === false, 'Not using Sqlserver for test config'); <add> $this->skipIf(strpos($config['driver'], 'Sqlserver') === false, 'Not using Sqlserver for test config'); <ide> } <ide> <ide> /** <ide> public function testDescribeTable() { <ide> 'type' => 'biginteger', <ide> 'null' => false, <ide> 'default' => null, <del> 'length' => 20, <add> 'length' => 19, <ide> 'precision' => null, <ide> 'unsigned' => null, <ide> 'autoIncrement' => null, <ide> public function testDescribeTable() { <ide> 'comment' => null, <ide> ], <ide> 'created' => [ <del> 'type' => 'datetime', <add> 'type' => 'timestamp', <ide> 'null' => true, <ide> 'default' => null, <ide> 'length' => null,
1
Python
Python
add .meta to language object
618ce3b4255f7b3435f44b2a422ec7647431c26d
<ide><path>spacy/language.py <ide> def __init__(self, **overrides): <ide> if path is True: <ide> path = util.match_best_version(self.lang, '', util.get_data_path()) <ide> <add> self.meta = overrides.get('meta', {}) <ide> self.path = path <ide> <ide> self.vocab = self.Defaults.create_vocab(self) \
1
Javascript
Javascript
remove var redeclarations in test-crypto-*
2c97bd47e40aedf932f7f4392f446da63d679d1a
<ide><path>test/parallel/test-crypto-binary-default.js <ide> assert.throws(function() { <ide> }, 'not enough data'); <ide> <ide> // Test HMAC <del>var h1 = crypto.createHmac('sha1', 'Node') <del> .update('some data') <del> .update('to hmac') <del> .digest('hex'); <del>assert.equal(h1, '19fd6e1ba73d9ed2224dd5094a71babe85d9a892', 'test HMAC'); <add>const hmacHash = crypto.createHmac('sha1', 'Node') <add> .update('some data') <add> .update('to hmac') <add> .digest('hex'); <add>assert.equal(hmacHash, '19fd6e1ba73d9ed2224dd5094a71babe85d9a892', 'test HMAC'); <ide> <ide> // Test HMAC-SHA-* (rfc 4231 Test Cases) <ide> var rfc4231 = [ <ide> var rfc4231 = [ <ide> } <ide> ]; <ide> <del>for (var i = 0, l = rfc4231.length; i < l; i++) { <add>for (let i = 0, l = rfc4231.length; i < l; i++) { <ide> for (var hash in rfc4231[i]['hmac']) { <ide> var result = crypto.createHmac(hash, rfc4231[i]['key']) <ide> .update(rfc4231[i]['data']) <ide> var rfc2202_sha1 = [ <ide> } <ide> ]; <ide> <del>for (var i = 0, l = rfc2202_md5.length; i < l; i++) { <add>for (let i = 0, l = rfc2202_md5.length; i < l; i++) { <ide> if (!common.hasFipsCrypto) { <ide> assert.equal(rfc2202_md5[i]['hmac'], <ide> crypto.createHmac('md5', rfc2202_md5[i]['key']) <ide> for (var i = 0, l = rfc2202_md5.length; i < l; i++) { <ide> 'Test HMAC-MD5 : Test case ' + (i + 1) + ' rfc 2202'); <ide> } <ide> } <del>for (var i = 0, l = rfc2202_sha1.length; i < l; i++) { <add>for (let i = 0, l = rfc2202_sha1.length; i < l; i++) { <ide> assert.equal(rfc2202_sha1[i]['hmac'], <ide> crypto.createHmac('sha1', rfc2202_sha1[i]['key']) <ide> .update(rfc2202_sha1[i]['data']) <ide> assert.throws(function() { <ide> var s1 = crypto.createSign('RSA-SHA1') <ide> .update('Test123') <ide> .sign(keyPem, 'base64'); <del>var verified = crypto.createVerify('RSA-SHA1') <del> .update('Test') <del> .update('123') <del> .verify(certPem, s1, 'base64'); <del>assert.strictEqual(verified, true, 'sign and verify (base 64)'); <add>var s1Verified = crypto.createVerify('RSA-SHA1') <add> .update('Test') <add> .update('123') <add> .verify(certPem, s1, 'base64'); <add>assert.strictEqual(s1Verified, true, 'sign and verify (base 64)'); <ide> <ide> var s2 = crypto.createSign('RSA-SHA256') <ide> .update('Test123') <ide> .sign(keyPem); // binary <del>var verified = crypto.createVerify('RSA-SHA256') <del> .update('Test') <del> .update('123') <del> .verify(certPem, s2); // binary <del>assert.strictEqual(verified, true, 'sign and verify (binary)'); <add>var s2Verified = crypto.createVerify('RSA-SHA256') <add> .update('Test') <add> .update('123') <add> .verify(certPem, s2); // binary <add>assert.strictEqual(s2Verified, true, 'sign and verify (binary)'); <ide> <ide> var s3 = crypto.createSign('RSA-SHA1') <ide> .update('Test123') <ide> .sign(keyPem, 'buffer'); <del>var verified = crypto.createVerify('RSA-SHA1') <del> .update('Test') <del> .update('123') <del> .verify(certPem, s3); <del>assert.strictEqual(verified, true, 'sign and verify (buffer)'); <add>var s3Verified = crypto.createVerify('RSA-SHA1') <add> .update('Test') <add> .update('123') <add> .verify(certPem, s3); <add>assert.strictEqual(s3Verified, true, 'sign and verify (buffer)'); <ide> <ide> <ide> function testCipher1(key) { <ide><path>test/parallel/test-crypto-hmac.js <ide> var wikipedia = [ <ide> }, <ide> ]; <ide> <del>for (var i = 0, l = wikipedia.length; i < l; i++) { <del> for (var hash in wikipedia[i]['hmac']) { <add>for (let i = 0, l = wikipedia.length; i < l; i++) { <add> for (const hash in wikipedia[i]['hmac']) { <ide> // FIPS does not support MD5. <ide> if (common.hasFipsCrypto && hash == 'md5') <ide> continue; <del> var result = crypto.createHmac(hash, wikipedia[i]['key']) <del> .update(wikipedia[i]['data']) <del> .digest('hex'); <add> const result = crypto.createHmac(hash, wikipedia[i]['key']) <add> .update(wikipedia[i]['data']) <add> .digest('hex'); <ide> assert.equal(wikipedia[i]['hmac'][hash], <ide> result, <ide> 'Test HMAC-' + hash + ': Test case ' + (i + 1) + ' wikipedia'); <ide> var rfc4231 = [ <ide> } <ide> ]; <ide> <del>for (var i = 0, l = rfc4231.length; i < l; i++) { <del> for (var hash in rfc4231[i]['hmac']) { <del> var str = crypto.createHmac(hash, rfc4231[i].key); <add>for (let i = 0, l = rfc4231.length; i < l; i++) { <add> for (const hash in rfc4231[i]['hmac']) { <add> const str = crypto.createHmac(hash, rfc4231[i].key); <ide> str.end(rfc4231[i].data); <del> var strRes = str.read().toString('hex'); <del> var result = crypto.createHmac(hash, rfc4231[i]['key']) <del> .update(rfc4231[i]['data']) <del> .digest('hex'); <add> let strRes = str.read().toString('hex'); <add> let result = crypto.createHmac(hash, rfc4231[i]['key']) <add> .update(rfc4231[i]['data']) <add> .digest('hex'); <ide> if (rfc4231[i]['truncate']) { <ide> result = result.substr(0, 32); // first 128 bits == 32 hex chars <ide> strRes = strRes.substr(0, 32); <ide> var rfc2202_sha1 = [ <ide> ]; <ide> <ide> if (!common.hasFipsCrypto) { <del> for (var i = 0, l = rfc2202_md5.length; i < l; i++) { <add> for (let i = 0, l = rfc2202_md5.length; i < l; i++) { <ide> assert.equal(rfc2202_md5[i]['hmac'], <ide> crypto.createHmac('md5', rfc2202_md5[i]['key']) <ide> .update(rfc2202_md5[i]['data']) <ide> .digest('hex'), <ide> 'Test HMAC-MD5 : Test case ' + (i + 1) + ' rfc 2202'); <ide> } <ide> } <del>for (var i = 0, l = rfc2202_sha1.length; i < l; i++) { <add>for (let i = 0, l = rfc2202_sha1.length; i < l; i++) { <ide> assert.equal(rfc2202_sha1[i]['hmac'], <ide> crypto.createHmac('sha1', rfc2202_sha1[i]['key']) <ide> .update(rfc2202_sha1[i]['data']) <ide><path>test/parallel/test-crypto-rsa-dsa.js <ide> assert.throws(function() { <ide> // <ide> // Test DSA signing and verification with encrypted key <ide> // <del>(function() { <del> var input = 'I AM THE WALRUS'; <add>const input = 'I AM THE WALRUS'; <ide> <del> var sign = crypto.createSign('DSS1'); <add>{ <add> const sign = crypto.createSign('DSS1'); <ide> sign.update(input); <ide> assert.throws(function() { <ide> sign.sign({ key: dsaKeyPemEncrypted, passphrase: 'wrong' }, 'hex'); <ide> }); <add>} <ide> <add>{ <ide> // DSA signatures vary across runs so there is no static string to verify <ide> // against <del> var sign = crypto.createSign('DSS1'); <add> const sign = crypto.createSign('DSS1'); <ide> sign.update(input); <ide> <del> var signature; <add> let signature; <ide> assert.doesNotThrow(function() { <del> var signOptions = { key: dsaKeyPemEncrypted, passphrase: 'password' }; <add> const signOptions = { key: dsaKeyPemEncrypted, passphrase: 'password' }; <ide> signature = sign.sign(signOptions, 'hex'); <ide> }); <ide> <del> var verify = crypto.createVerify('DSS1'); <add> const verify = crypto.createVerify('DSS1'); <ide> verify.update(input); <ide> <ide> assert.strictEqual(verify.verify(dsaPubPem, signature, 'hex'), true); <del>})(); <add>} <ide><path>test/parallel/test-crypto-sign-verify.js <ide> var certPem = fs.readFileSync(common.fixturesDir + '/test_cert.pem', 'ascii'); <ide> var keyPem = fs.readFileSync(common.fixturesDir + '/test_key.pem', 'ascii'); <ide> <ide> // Test signing and verifying <del>var s1 = crypto.createSign('RSA-SHA1') <del> .update('Test123') <del> .sign(keyPem, 'base64'); <del>var s1stream = crypto.createSign('RSA-SHA1'); <del>s1stream.end('Test123'); <del>s1stream = s1stream.sign(keyPem, 'base64'); <del>assert.equal(s1, s1stream, 'Stream produces same output'); <add>{ <add> const s1 = crypto.createSign('RSA-SHA1') <add> .update('Test123') <add> .sign(keyPem, 'base64'); <add> let s1stream = crypto.createSign('RSA-SHA1'); <add> s1stream.end('Test123'); <add> s1stream = s1stream.sign(keyPem, 'base64'); <add> assert.equal(s1, s1stream, 'Stream produces same output'); <ide> <del>var verified = crypto.createVerify('RSA-SHA1') <del> .update('Test') <del> .update('123') <del> .verify(certPem, s1, 'base64'); <del>assert.strictEqual(verified, true, 'sign and verify (base 64)'); <add> const verified = crypto.createVerify('RSA-SHA1') <add> .update('Test') <add> .update('123') <add> .verify(certPem, s1, 'base64'); <add> assert.strictEqual(verified, true, 'sign and verify (base 64)'); <add>} <ide> <del>var s2 = crypto.createSign('RSA-SHA256') <del> .update('Test123') <del> .sign(keyPem, 'binary'); <del>var s2stream = crypto.createSign('RSA-SHA256'); <del>s2stream.end('Test123'); <del>s2stream = s2stream.sign(keyPem, 'binary'); <del>assert.equal(s2, s2stream, 'Stream produces same output'); <add>{ <add> const s2 = crypto.createSign('RSA-SHA256') <add> .update('Test123') <add> .sign(keyPem, 'binary'); <add> let s2stream = crypto.createSign('RSA-SHA256'); <add> s2stream.end('Test123'); <add> s2stream = s2stream.sign(keyPem, 'binary'); <add> assert.equal(s2, s2stream, 'Stream produces same output'); <ide> <del>var verified = crypto.createVerify('RSA-SHA256') <del> .update('Test') <del> .update('123') <del> .verify(certPem, s2, 'binary'); <del>assert.strictEqual(verified, true, 'sign and verify (binary)'); <add> let verified = crypto.createVerify('RSA-SHA256') <add> .update('Test') <add> .update('123') <add> .verify(certPem, s2, 'binary'); <add> assert.strictEqual(verified, true, 'sign and verify (binary)'); <ide> <del>var verStream = crypto.createVerify('RSA-SHA256'); <del>verStream.write('Tes'); <del>verStream.write('t12'); <del>verStream.end('3'); <del>verified = verStream.verify(certPem, s2, 'binary'); <del>assert.strictEqual(verified, true, 'sign and verify (stream)'); <add> const verStream = crypto.createVerify('RSA-SHA256'); <add> verStream.write('Tes'); <add> verStream.write('t12'); <add> verStream.end('3'); <add> verified = verStream.verify(certPem, s2, 'binary'); <add> assert.strictEqual(verified, true, 'sign and verify (stream)'); <add>} <ide> <del>var s3 = crypto.createSign('RSA-SHA1') <del> .update('Test123') <del> .sign(keyPem, 'buffer'); <del>var verified = crypto.createVerify('RSA-SHA1') <del> .update('Test') <del> .update('123') <del> .verify(certPem, s3); <del>assert.strictEqual(verified, true, 'sign and verify (buffer)'); <add>{ <add> const s3 = crypto.createSign('RSA-SHA1') <add> .update('Test123') <add> .sign(keyPem, 'buffer'); <add> let verified = crypto.createVerify('RSA-SHA1') <add> .update('Test') <add> .update('123') <add> .verify(certPem, s3); <add> assert.strictEqual(verified, true, 'sign and verify (buffer)'); <ide> <del>var verStream = crypto.createVerify('RSA-SHA1'); <del>verStream.write('Tes'); <del>verStream.write('t12'); <del>verStream.end('3'); <del>verified = verStream.verify(certPem, s3); <del>assert.strictEqual(verified, true, 'sign and verify (stream)'); <add> const verStream = crypto.createVerify('RSA-SHA1'); <add> verStream.write('Tes'); <add> verStream.write('t12'); <add> verStream.end('3'); <add> verified = verStream.verify(certPem, s3); <add> assert.strictEqual(verified, true, 'sign and verify (stream)'); <add>} <ide><path>test/parallel/test-crypto.js <ide> assert.equal(-1, crypto.getCiphers().indexOf('AES-128-CBC')); <ide> assertSorted(crypto.getCiphers()); <ide> <ide> // Assume that we have at least AES256-SHA. <del>var tls = require('tls'); <ide> assert.notEqual(0, tls.getCiphers().length); <ide> assert.notEqual(-1, tls.getCiphers().indexOf('aes256-sha')); <ide> assert.equal(-1, tls.getCiphers().indexOf('AES256-SHA'));
5
Python
Python
use -v (capital v) for version
4b40e3fe0e3238a7fad9566c36941d10cb319dd8
<ide><path>glances/core/glances_main.py <ide> def init_args(self): <ide> """Init all the command line arguments.""" <ide> version = "Glances v" + __version__ + " with psutil v" + __psutil_version__ <ide> parser = argparse.ArgumentParser(prog=__appname__, conflict_handler='resolve') <del> parser.add_argument('-v', '--version', action='version', version=version) <add> parser.add_argument('-V', '--version', action='version', version=version) <ide> parser.add_argument('-b', '--byte', action='store_true', default=False, <ide> dest='byte', help=_('display network rate in byte per second')) <ide> parser.add_argument('-B', '--bind', default='0.0.0.0', dest='bind_address',
1
Python
Python
clarify deletechars in docs
4ebd08df74769ad0628a05e1d0654244008ab10b
<ide><path>numpy/lib/npyio.py <ide> def genfromtxt(fname, dtype=float, comments='#', delimiter=None, <ide> column, individually. <ide> comments : str, optional <ide> The character used to indicate the start of a comment. <del> By default, the character '#' starts a comment. <add> By default, the character '#' starts a comment. If some other <add> character is used, override `deletechars` to preserve <add> special characters in the header names. <ide> All the characters occurring on a line after a comment are discarded <ide> delimiter : str, int, or sequence, optional <ide> The string used to separate values. By default, any consecutive <ide> def genfromtxt(fname, dtype=float, comments='#', delimiter=None, <ide> for example, `file` would become `file_`. <ide> deletechars : str, optional <ide> A string combining invalid characters that must be deleted from the <del> names. <add> names. In case `comments` is something other than '#', this must be <add> an empty string in order to preserve special characters in the names. <ide> defaultfmt : str, optional <ide> A format used to define default field names, such as "f%i" or "f_%02i". <ide> autostrip : bool, optional
1
Java
Java
fix experimental, signatures of throttlelast
5b3510bc925947230f6c1a7e66d30694e0f304b3
<ide><path>src/main/java/io/reactivex/rxjava3/core/Flowable.java <ide> public final Flowable<T> sample(long period, @NonNull TimeUnit unit, @NonNull Sc <ide> * <dd>You specify which {@code Scheduler} this operator will use.</dd> <ide> * </dl> <ide> * <del> * <p>History: 2.0.5 - experimental <ide> * @param period <ide> * the sampling rate <ide> * @param unit <ide> public final Flowable<T> sample(long period, @NonNull TimeUnit unit, @NonNull Sc <ide> * @see <a href="http://reactivex.io/documentation/operators/sample.html">ReactiveX operators documentation: Sample</a> <ide> * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Backpressure">RxJava wiki: Backpressure</a> <ide> * @see #throttleLast(long, TimeUnit, Scheduler) <del> * @since 2.1 <add> * @since 3.1.6 - Experimental <ide> */ <ide> @CheckReturnValue <ide> @NonNull <ide> @BackpressureSupport(BackpressureKind.ERROR) <ide> @SchedulerSupport(SchedulerSupport.CUSTOM) <del> public final Flowable<T> sample(long period, @NonNull TimeUnit unit, @NonNull Scheduler scheduler, boolean emitLast, @NonNull Consumer<T> onDropped) { <add> @Experimental <add> public final Flowable<T> sample(long period, @NonNull TimeUnit unit, @NonNull Scheduler scheduler, boolean emitLast, @NonNull Consumer<? super T> onDropped) { <ide> Objects.requireNonNull(unit, "unit is null"); <ide> Objects.requireNonNull(scheduler, "scheduler is null"); <ide> Objects.requireNonNull(onDropped, "onDropped is null"); <ide> public final Flowable<T> throttleFirst(long skipDuration, @NonNull TimeUnit unit <ide> * @throws NullPointerException if {@code unit} or {@code scheduler} or {@code onDropped} is {@code null} <ide> * @see <a href="http://reactivex.io/documentation/operators/sample.html">ReactiveX operators documentation: Sample</a> <ide> * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Backpressure">RxJava wiki: Backpressure</a> <add> * @since 3.1.6 - Experimental <ide> */ <ide> @CheckReturnValue <ide> @NonNull <ide> @BackpressureSupport(BackpressureKind.ERROR) <ide> @SchedulerSupport(SchedulerSupport.CUSTOM) <add> @Experimental <ide> public final Flowable<T> throttleFirst(long skipDuration, @NonNull TimeUnit unit, @NonNull Scheduler scheduler, @NonNull Consumer<? super T> onDropped) { <ide> Objects.requireNonNull(unit, "unit is null"); <ide> Objects.requireNonNull(scheduler, "scheduler is null"); <ide> public final Flowable<T> throttleLast(long intervalDuration, @NonNull TimeUnit u <ide> * @see <a href="http://reactivex.io/documentation/operators/sample.html">ReactiveX operators documentation: Sample</a> <ide> * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Backpressure">RxJava wiki: Backpressure</a> <ide> * @see #sample(long, TimeUnit, Scheduler) <add> * @since 3.1.6 - Experimental <ide> */ <ide> @CheckReturnValue <ide> @BackpressureSupport(BackpressureKind.ERROR) <ide> @SchedulerSupport(SchedulerSupport.CUSTOM) <ide> @NonNull <del> public final Flowable<T> throttleLast(long intervalDuration, @NonNull TimeUnit unit, @NonNull Scheduler scheduler, @NonNull Consumer<T> onDropped) { <add> @Experimental <add> public final Flowable<T> throttleLast(long intervalDuration, @NonNull TimeUnit unit, @NonNull Scheduler scheduler, @NonNull Consumer<? super T> onDropped) { <ide> return sample(intervalDuration, unit, scheduler, false, onDropped); <ide> } <ide> <ide><path>src/main/java/io/reactivex/rxjava3/core/Observable.java <ide> public final Observable<T> sample(long period, @NonNull TimeUnit unit, @NonNull <ide> <ide> /** <ide> * Returns an {@code Observable} that emits the most recently emitted item (if any) emitted by the current {@code Observable} <del> * within periodic time intervals, where the intervals are defined on a particular {@link Scheduler}. <add> * within periodic time intervals, where the intervals are defined on a particular {@link Scheduler} <add> * and optionally emit the very last upstream item when the upstream completes. <ide> * <p> <del> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/sample.s.v3.png" alt=""> <add> * <img width="640" height="277" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/sample.s.emitlast.png" alt=""> <ide> * <dl> <ide> * <dt><b>Scheduler:</b></dt> <ide> * <dd>You specify which {@code Scheduler} this operator will use.</dd> <ide> * </dl> <ide> * <add> * <p>History: 2.0.5 - experimental <ide> * @param period <ide> * the sampling rate <ide> * @param unit <ide> * the {@link TimeUnit} in which {@code period} is defined <ide> * @param scheduler <ide> * the {@code Scheduler} to use when sampling <del> * @param onDropped <del> * called with the current entry when it has been replaced by a new one <add> * @param emitLast <add> * if {@code true} and the upstream completes while there is still an unsampled item available, <add> * that item is emitted to downstream before completion <add> * if {@code false}, an unsampled last item is ignored. <ide> * @return the new {@code Observable} instance <del> * @throws NullPointerException if {@code unit} or {@code scheduler} is {@code null} or {@code onDropped} is {@code null} <add> * @throws NullPointerException if {@code unit} or {@code scheduler} is {@code null} <ide> * @see <a href="http://reactivex.io/documentation/operators/sample.html">ReactiveX operators documentation: Sample</a> <ide> * @see #throttleLast(long, TimeUnit, Scheduler) <add> * @since 2.1 <ide> */ <ide> @CheckReturnValue <ide> @SchedulerSupport(SchedulerSupport.CUSTOM) <ide> @NonNull <del> public final Observable<T> sample(long period, @NonNull TimeUnit unit, @NonNull Scheduler scheduler, @NonNull Consumer<T> onDropped) { <add> public final Observable<T> sample(long period, @NonNull TimeUnit unit, @NonNull Scheduler scheduler, boolean emitLast) { <ide> Objects.requireNonNull(unit, "unit is null"); <ide> Objects.requireNonNull(scheduler, "scheduler is null"); <del> Objects.requireNonNull(onDropped, "onDropped is null"); <del> return RxJavaPlugins.onAssembly(new ObservableSampleTimed<>(this, period, unit, scheduler, false, onDropped)); <add> return RxJavaPlugins.onAssembly(new ObservableSampleTimed<>(this, period, unit, scheduler, emitLast, null)); <ide> } <ide> <ide> /** <ide> * Returns an {@code Observable} that emits the most recently emitted item (if any) emitted by the current {@code Observable} <del> * within periodic time intervals, where the intervals are defined on a particular {@link Scheduler} <del> * and optionally emit the very last upstream item when the upstream completes. <add> * within periodic time intervals, where the intervals are defined on a particular {@link Scheduler}. <ide> * <p> <del> * <img width="640" height="277" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/sample.s.emitlast.png" alt=""> <add> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/sample.s.v3.png" alt=""> <ide> * <dl> <ide> * <dt><b>Scheduler:</b></dt> <ide> * <dd>You specify which {@code Scheduler} this operator will use.</dd> <ide> * </dl> <ide> * <del> * <p>History: 2.0.5 - experimental <ide> * @param period <ide> * the sampling rate <ide> * @param unit <ide> public final Observable<T> sample(long period, @NonNull TimeUnit unit, @NonNull <ide> * if {@code true} and the upstream completes while there is still an unsampled item available, <ide> * that item is emitted to downstream before completion <ide> * if {@code false}, an unsampled last item is ignored. <add> * @param onDropped <add> * called with the current entry when it has been replaced by a new one <ide> * @return the new {@code Observable} instance <del> * @throws NullPointerException if {@code unit} or {@code scheduler} is {@code null} <add> * @throws NullPointerException if {@code unit} or {@code scheduler} is {@code null} or {@code onDropped} is {@code null} <ide> * @see <a href="http://reactivex.io/documentation/operators/sample.html">ReactiveX operators documentation: Sample</a> <ide> * @see #throttleLast(long, TimeUnit, Scheduler) <del> * @since 2.1 <add> * @since 3.1.6 - Experimental <ide> */ <ide> @CheckReturnValue <ide> @SchedulerSupport(SchedulerSupport.CUSTOM) <ide> @NonNull <del> public final Observable<T> sample(long period, @NonNull TimeUnit unit, @NonNull Scheduler scheduler, boolean emitLast) { <add> @Experimental <add> public final Observable<T> sample(long period, @NonNull TimeUnit unit, @NonNull Scheduler scheduler, boolean emitLast, @NonNull Consumer<? super T> onDropped) { <ide> Objects.requireNonNull(unit, "unit is null"); <ide> Objects.requireNonNull(scheduler, "scheduler is null"); <del> return RxJavaPlugins.onAssembly(new ObservableSampleTimed<>(this, period, unit, scheduler, emitLast, null)); <add> Objects.requireNonNull(onDropped, "onDropped is null"); <add> return RxJavaPlugins.onAssembly(new ObservableSampleTimed<>(this, period, unit, scheduler, emitLast, onDropped)); <ide> } <ide> <ide> /** <ide> public final Observable<T> throttleFirst(long skipDuration, @NonNull TimeUnit un <ide> * @return the new {@code Observable} instance <ide> * @throws NullPointerException if {@code unit} or {@code scheduler} or {@code onDropped} is {@code null} <ide> * @see <a href="http://reactivex.io/documentation/operators/sample.html">ReactiveX operators documentation: Sample</a> <add> * @since 3.1.6 - Experimental <ide> */ <ide> @CheckReturnValue <ide> @SchedulerSupport(SchedulerSupport.CUSTOM) <ide> @NonNull <add> @Experimental <ide> public final Observable<T> throttleFirst(long skipDuration, @NonNull TimeUnit unit, @NonNull Scheduler scheduler, @NonNull Consumer<? super T> onDropped) { <ide> Objects.requireNonNull(unit, "unit is null"); <ide> Objects.requireNonNull(scheduler, "scheduler is null"); <ide> public final Observable<T> throttleLast(long intervalDuration, @NonNull TimeUnit <ide> * @throws NullPointerException if {@code unit} or {@code scheduler} is {@code null} or {@code onDropped} is {@code null} <ide> * @see <a href="http://reactivex.io/documentation/operators/sample.html">ReactiveX operators documentation: Sample</a> <ide> * @see #sample(long, TimeUnit, Scheduler) <add> * @since 3.1.6 - Experimental <ide> */ <ide> @CheckReturnValue <ide> @SchedulerSupport(SchedulerSupport.CUSTOM) <ide> @NonNull <del> public final Observable<T> throttleLast(long intervalDuration, @NonNull TimeUnit unit, @NonNull Scheduler scheduler, @NonNull Consumer<T> onDropped) { <del> return sample(intervalDuration, unit, scheduler, onDropped); <add> @Experimental <add> public final Observable<T> throttleLast(long intervalDuration, @NonNull TimeUnit unit, @NonNull Scheduler scheduler, @NonNull Consumer<? super T> onDropped) { <add> return sample(intervalDuration, unit, scheduler, false, onDropped); <ide> } <ide> <ide> /** <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableSampleTimed.java <ide> final TimeUnit unit; <ide> final Scheduler scheduler; <ide> final boolean emitLast; <del> final Consumer<T> onDropped; <add> final Consumer<? super T> onDropped; <ide> <del> public FlowableSampleTimed(Flowable<T> source, long period, TimeUnit unit, Scheduler scheduler, boolean emitLast, Consumer<T> onDropped) { <add> public FlowableSampleTimed(Flowable<T> source, long period, TimeUnit unit, Scheduler scheduler, boolean emitLast, Consumer<? super T> onDropped) { <ide> super(source); <ide> this.period = period; <ide> this.unit = unit; <ide> protected void subscribeActual(Subscriber<? super T> s) { <ide> final long period; <ide> final TimeUnit unit; <ide> final Scheduler scheduler; <del> final Consumer<T> onDropped; <add> final Consumer<? super T> onDropped; <ide> <ide> final AtomicLong requested = new AtomicLong(); <ide> <ide> final SequentialDisposable timer = new SequentialDisposable(); <ide> <ide> Subscription upstream; <ide> <del> SampleTimedSubscriber(Subscriber<? super T> actual, long period, TimeUnit unit, Scheduler scheduler, Consumer<T> onDropped) { <add> SampleTimedSubscriber(Subscriber<? super T> actual, long period, TimeUnit unit, Scheduler scheduler, Consumer<? super T> onDropped) { <ide> this.downstream = actual; <ide> this.period = period; <ide> this.unit = unit; <ide> void emit() { <ide> <ide> private static final long serialVersionUID = -7139995637533111443L; <ide> <del> SampleTimedNoLast(Subscriber<? super T> actual, long period, TimeUnit unit, Scheduler scheduler, Consumer<T> onDropped) { <add> SampleTimedNoLast(Subscriber<? super T> actual, long period, TimeUnit unit, Scheduler scheduler, Consumer<? super T> onDropped) { <ide> super(actual, period, unit, scheduler, onDropped); <ide> } <ide> <ide> public void run() { <ide> <ide> final AtomicInteger wip; <ide> <del> SampleTimedEmitLast(Subscriber<? super T> actual, long period, TimeUnit unit, Scheduler scheduler, Consumer<T> onDropped) { <add> SampleTimedEmitLast(Subscriber<? super T> actual, long period, TimeUnit unit, Scheduler scheduler, Consumer<? super T> onDropped) { <ide> super(actual, period, unit, scheduler, onDropped); <ide> this.wip = new AtomicInteger(1); <ide> } <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableSampleTimed.java <ide> import io.reactivex.rxjava3.functions.Consumer; <ide> import io.reactivex.rxjava3.internal.disposables.DisposableHelper; <ide> import io.reactivex.rxjava3.observers.SerializedObserver; <del>import io.reactivex.rxjava3.plugins.RxJavaPlugins; <ide> <ide> public final class ObservableSampleTimed<T> extends AbstractObservableWithUpstream<T, T> { <ide> final long period; <ide> final TimeUnit unit; <ide> final Scheduler scheduler; <del> final Consumer<T> onDropped; <add> final Consumer<? super T> onDropped; <ide> final boolean emitLast; <ide> <ide> public ObservableSampleTimed(ObservableSource<T> source, <ide> long period, <ide> TimeUnit unit, <ide> Scheduler scheduler, <ide> boolean emitLast, <del> Consumer<T> onDropped) { <add> Consumer<? super T> onDropped) { <ide> super(source); <ide> this.period = period; <ide> this.unit = unit; <ide> public void subscribeActual(Observer<? super T> t) { <ide> final long period; <ide> final TimeUnit unit; <ide> final Scheduler scheduler; <del> final Consumer<T> onDropped; <add> final Consumer<? super T> onDropped; <ide> <ide> final AtomicReference<Disposable> timer = new AtomicReference<>(); <ide> <ide> Disposable upstream; <ide> <del> SampleTimedObserver(Observer<? super T> actual, long period, TimeUnit unit, Scheduler scheduler, Consumer<T> onDropped) { <add> SampleTimedObserver(Observer<? super T> actual, long period, TimeUnit unit, Scheduler scheduler, Consumer<? super T> onDropped) { <ide> this.downstream = actual; <ide> this.period = period; <ide> this.unit = unit; <ide> void emit() { <ide> <ide> private static final long serialVersionUID = -7139995637533111443L; <ide> <del> SampleTimedNoLast(Observer<? super T> actual, long period, TimeUnit unit, Scheduler scheduler, Consumer<T> onDropped) { <add> SampleTimedNoLast(Observer<? super T> actual, long period, TimeUnit unit, Scheduler scheduler, Consumer<? super T> onDropped) { <ide> super(actual, period, unit, scheduler, onDropped); <ide> } <ide> <ide> public void run() { <ide> <ide> final AtomicInteger wip; <ide> <del> SampleTimedEmitLast(Observer<? super T> actual, long period, TimeUnit unit, Scheduler scheduler, Consumer<T> onDropped) { <add> SampleTimedEmitLast(Observer<? super T> actual, long period, TimeUnit unit, Scheduler scheduler, Consumer<? super T> onDropped) { <ide> super(actual, period, unit, scheduler, onDropped); <ide> this.wip = new AtomicInteger(1); <ide> } <ide><path>src/test/java/io/reactivex/rxjava3/validators/ParamValidationCheckerTest.java <ide> public void checkParallelFlowable() { <ide> addOverride(new ParamOverride(Observable.class, 0, ParamMode.ANY, "sample", Long.TYPE, TimeUnit.class)); <ide> addOverride(new ParamOverride(Observable.class, 0, ParamMode.ANY, "sample", Long.TYPE, TimeUnit.class, Boolean.TYPE)); <ide> addOverride(new ParamOverride(Observable.class, 0, ParamMode.ANY, "sample", Long.TYPE, TimeUnit.class, Scheduler.class)); <del> addOverride(new ParamOverride(Observable.class, 0, ParamMode.ANY, "sample", Long.TYPE, TimeUnit.class, Scheduler.class, Consumer.class)); <ide> addOverride(new ParamOverride(Observable.class, 0, ParamMode.ANY, "sample", Long.TYPE, TimeUnit.class, Scheduler.class, Boolean.TYPE)); <add> addOverride(new ParamOverride(Observable.class, 0, ParamMode.ANY, "sample", Long.TYPE, TimeUnit.class, Scheduler.class, Boolean.TYPE, Consumer.class)); <ide> <ide> // negative time is considered as zero time <ide> addOverride(new ParamOverride(Observable.class, 0, ParamMode.ANY, "takeLast", Long.TYPE, TimeUnit.class));
5
PHP
PHP
fix fallback locale
b59741374d692934cfe86ca095296447bea96033
<ide><path>src/Illuminate/Translation/Translator.php <ide> use Illuminate\Support\NamespacedItemResolver; <ide> use Symfony\Component\Translation\Loader\ArrayLoader; <ide> use Symfony\Component\Translation\TranslatorInterface; <add>use Symfony\Component\Translation\Translator as SymfonyTranslator; <ide> <ide> class Translator extends NamespacedItemResolver implements TranslatorInterface { <ide> <ide> class Translator extends NamespacedItemResolver implements TranslatorInterface { <ide> */ <ide> protected $trans; <ide> <add> /** <add> * The fallback locale for the translator. <add> * <add> * @var string <add> */ <add> protected $fallback; <add> <ide> /** <ide> * The array of loaded translation groups. <ide> * <ide> public function __construct(LoaderInterface $loader, $default, $fallback) <ide> { <ide> $this->loader = $loader; <ide> <add> $this->fallback = $fallback; <add> <ide> $this->trans = $this->createSymfonyTranslator($default, $fallback); <ide> } <ide> <ide> public function load($group, $namespace, $locale) <ide> { <ide> $domain = $namespace.'::'.$group; <ide> <del> $locale = $locale ?: $this->getLocale(); <del> <del> // The domain is used to store the messages in the Symfony translator object <del> // and functions as a sort of logical separator of message types so we'll <del> // use the namespace and group as the "domain", which should be unique. <del> if ($this->loaded($group, $namespace, $locale)) <add> foreach ($this->getLocales($locale) as $locale) <ide> { <del> return $domain; <add> // The domain is used to store the messages in the Symfony translator object <add> // and functions as a sort of logical separator of message types so we'll <add> // use the namespace and group as the "domain", which should be unique. <add> if ($this->loaded($group, $namespace, $locale)) <add> { <add> return $domain; <add> } <add> <add> $lines = $this->loader->load($locale, $group, $namespace); <add> <add> // We're finally ready to load the array of messages from the loader and add <add> // them to the Symfony translator. We will also convert this array to dot <add> // format so that deeply nested items will be accessed by a translator. <add> $this->addResource(array_dot($lines), $locale, $domain); <add> <add> $this->setLoaded($group, $namespace, $locale); <ide> } <ide> <del> $lines = $this->loader->load($locale, $group, $namespace); <del> <del> // We're finally ready to load the array of messages from the loader and add <del> // them to the Symfony translator. We will also convert this array to dot <del> // format so that deeply nested items will be accessed by a translator. <del> $this->addResource(array_dot($lines), $locale, $domain); <add> return $domain; <add> } <ide> <del> $this->setLoaded($group, $namespace, $locale); <add> /** <add> * Get the locales to be loaded. <add> * <add> * @param string $locale <add> * @return array <add> */ <add> protected function getLocales($locale) <add> { <add> $locale = $locale ?: $this->getLocale(); <ide> <del> return $domain; <add> return array_unique(array($locale, $this->fallback)); <ide> } <ide> <ide> /** <ide> public function load($group, $namespace, $locale) <ide> protected function addResource(array $lines, $locale, $domain) <ide> { <ide> $this->trans->addResource('array', $lines, $locale, $domain); <del> <del> $this->trans->refreshCatalogue($locale); <ide> } <ide> <ide> /** <ide><path>tests/Translation/TranslationTranslatorTest.php <ide> public function testLoadMethodProperlyCallsLoaderToRetrieveItems() <ide> { <ide> $t = new Translator($loader = $this->getLoader(), 'en', 'sp'); <ide> $loader->shouldReceive('load')->once()->with('en', 'foo', 'bar')->andReturn(array('messages' => array('foo' => 'bar'))); <add> $loader->shouldReceive('load')->once()->with('sp', 'foo', 'bar')->andReturn(array()); <ide> $t->setSymfonyTranslator($base = m::mock('Illuminate\Translation\SymfonyTranslator')); <ide> $base->shouldReceive('addResource')->once()->with('array', array('messages.foo' => 'bar'), 'en', 'bar::foo'); <del> $base->shouldReceive('refreshCatalogue')->once()->with('en'); <add> $base->shouldReceive('addResource')->once()->with('array', array(), 'sp', 'bar::foo'); <ide> $base->shouldReceive('getLocale')->andReturn('en'); <ide> $domain = $t->load('foo', 'bar', null); <ide> <ide> public function testLoadMethodProperlyCallsLoaderToRetrieveItems() <ide> public function testKeyIsReturnedThroughTransMethodsWhenItemsDontExist() <ide> { <ide> $t = new Translator($loader = $this->getLoader(), 'en', 'sp'); <del> $loader->shouldReceive('load')->once()->andReturn(array()); <add> $loader->shouldReceive('load')->twice()->andReturn(array()); <ide> $t->setSymfonyTranslator($base = m::mock('Illuminate\Translation\SymfonyTranslator')); <ide> $base->shouldReceive('getLocale')->andReturn('en'); <del> $base->shouldReceive('addResource'); <del> $base->shouldReceive('refreshCatalogue')->once()->with('en'); <add> $base->shouldReceive('addResource')->once()->with('array', array(), 'en', '::foo'); <add> $base->shouldReceive('addResource')->once()->with('array', array(), 'sp', '::foo'); <ide> $base->shouldReceive('trans')->once()->with('bar', array(), '::foo', null)->andReturn('bar'); <ide> <ide> $this->assertEquals('foo.bar', $t->trans('foo.bar'));
2
Javascript
Javascript
add documentation to addmodalpanel api
128f702784773b995ce5317d9ea0cd2265a2dade
<ide><path>spec/panel-container-element-spec.js <ide> describe('PanelContainerElement', () => { <ide> <ide> it("focuses the first tabbable item if available", () => { <ide> const panel = createPanel() <del> <ide> const panelEl = panel.getElement() <ide> const inputEl = document.createElement('input') <del> panelEl.appendChild(inputEl) <ide> <add> panelEl.appendChild(inputEl) <ide> expect(document.activeElement).not.toBe(inputEl) <add> <ide> panel.show() <ide> expect(document.activeElement).toBe(inputEl) <ide> }) <ide><path>src/panel-container-element.js <ide> class PanelContainerElement extends HTMLElement { <ide> if (this.model.isModal()) { <ide> this.hideAllPanelsExcept(panel) <ide> this.subscriptions.add(panel.onDidChangeVisible(visible => { <del> if (visible) this.hideAllPanelsExcept(panel) <add> if (visible) { this.hideAllPanelsExcept(panel) } <ide> })) <ide> <ide> if (panel.autoFocus) { <ide><path>src/workspace.js <ide> module.exports = class Workspace extends Model { <ide> // (default: true) <ide> // * `priority` (optional) {Number} Determines stacking order. Lower priority items are <ide> // forced closer to the edges of the window. (default: 100) <add> // * `autoFocus` (optional) {Boolean} true if you want modal focus managed for you by Atom. <add> // Atom will automatically focus your modal panel's first tabbable element when the modal <add> // opens and will restore the previously selected element when the modal closes. Atom will <add> // also automatically restrict user tab focus within your modal while it is open. <add> // (default: false) <ide> // <ide> // Returns a {Panel} <ide> addModalPanel (options = {}) {
3
PHP
PHP
remove undeeded method
0b7c22f898ac445eaeb9a3f4c2bae7edfd5459bb
<ide><path>src/Illuminate/Validation/Validator.php <ide> protected function initializeAttributeOnData($attribute) <ide> return $data; <ide> } <ide> <del> /** <del> * Fill a missing field in an array with null. <del> * <del> * This to make sure the "required" rule is effective if the array does not have the key <del> * <del> * @param array $originalData <del> * @param string $field <del> * @param array $levelData <del> * @param array $segments <del> * @param string $lastSegment <del> * @param array $keysArray <del> * @return void <del> */ <del> protected function fillMissingArrayKeys(&$originalData, $field, $levelData, $segments, $lastSegment, $keysArray = []) <del> { <del> foreach ($levelData as $key => $levelValues) { <del> if ($key !== $lastSegment) { <del> if (! is_array($levelValues) || (! is_numeric($key) && ! in_array($key, $segments))) { <del> continue; <del> } <del> <del> // If the last key is numeric then a previous root was checked and we are moving <del> // into a following root thus we need to reset our index. <del> if (is_numeric(last($keysArray))) { <del> array_pop($keysArray); <del> } <del> <del> $keysArray[] = $key; <del> $this->fillMissingArrayKeys($originalData, $field, $levelValues, $segments, $lastSegment, $keysArray); <del> } else { <del> foreach ($levelValues as $i => $rootValue) { <del> if (! isset($rootValue[$field])) { <del> $keysArray = array_merge($keysArray, [$lastSegment, $i, $field]); <del> $originalData[implode('.', $keysArray)] = null; <del> } <del> } <del> } <del> } <del> } <del> <ide> /** <ide> * Merge additional rules into a given attribute. <ide> *
1
Ruby
Ruby
use explicit order to stop test failing randomly
6f4b2469fb19bb01fa0f53192eb49f8f2d95db1b
<ide><path>activerecord/test/cases/associations/eager_test.rb <ide> def test_eager_loading_with_conditions_on_joined_table_preloads <ide> assert_equal authors(:david), assert_no_queries { posts[0].author} <ide> <ide> posts = assert_queries(2) do <del> Post.find(:all, :include => :author, :joins => {:taggings => :tag}, :conditions => "tags.name = 'General'") <add> Post.find(:all, :include => :author, :joins => {:taggings => :tag}, :conditions => "tags.name = 'General'", :order => 'posts.id') <ide> end <ide> assert_equal posts(:welcome, :thinking), posts <ide> <ide> posts = assert_queries(2) do <del> Post.find(:all, :include => :author, :joins => {:taggings => {:tag => :taggings}}, :conditions => "taggings_tags.super_tag_id=2") <add> Post.find(:all, :include => :author, :joins => {:taggings => {:tag => :taggings}}, :conditions => "taggings_tags.super_tag_id=2", :order => 'posts.id') <ide> end <ide> assert_equal posts(:welcome, :thinking), posts <ide>
1
Python
Python
fix loss computation in trainer
3ffd18a6177eb3a2214627f7baba07d273daee0e
<ide><path>src/transformers/trainer.py <ide> def train( <ide> <ide> if args.logging_nan_inf_filter and (torch.isnan(tr_loss_step) or torch.isinf(tr_loss_step)): <ide> # if loss is nan or inf simply add the average of previous logged losses <del> tr_loss += tr_loss / 1 + (self.state.global_step - self._globalstep_last_logged) <add> tr_loss += tr_loss / (1 + self.state.global_step - self._globalstep_last_logged) <ide> else: <ide> tr_loss += tr_loss_step <ide>
1
Python
Python
create a copy for tokenizer object
df5e4232f59e6fea08911eddd0adc965d1b59c15
<ide><path>src/transformers/tokenization_utils_fast.py <ide> Tokenization classes for fast tokenizers (provided by HuggingFace's tokenizers library). For slow (python) tokenizers <ide> see tokenization_utils.py <ide> """ <add>import copy <ide> import json <ide> import os <ide> from collections import defaultdict <ide> def __init__(self, *args, **kwargs): <ide> ) <ide> <ide> if tokenizer_object is not None: <del> fast_tokenizer = tokenizer_object <add> fast_tokenizer = copy.deepcopy(tokenizer_object) <ide> elif fast_tokenizer_file is not None and not from_slow: <ide> # We have a serialization from tokenizers which let us directly build the backend <ide> fast_tokenizer = TokenizerFast.from_file(fast_tokenizer_file)
1
Python
Python
add type hints for prophetnet (pytorch)
7ba1d4e51fbf86aa843fc15009c38c9b776919c6
<ide><path>src/transformers/models/prophetnet/configuration_prophetnet.py <ide> # limitations under the License. <ide> """ ProphetNet model configuration""" <ide> <add>from typing import Callable, Optional, Union <ide> <ide> from ...configuration_utils import PretrainedConfig <ide> from ...utils import logging <ide> class ProphetNetConfig(PretrainedConfig): <ide> <ide> def __init__( <ide> self, <del> activation_dropout=0.1, <del> activation_function="gelu", <del> vocab_size=30522, <del> hidden_size=1024, <del> encoder_ffn_dim=4096, <del> num_encoder_layers=12, <del> num_encoder_attention_heads=16, <del> decoder_ffn_dim=4096, <del> num_decoder_layers=12, <del> num_decoder_attention_heads=16, <del> attention_dropout=0.1, <del> dropout=0.1, <del> max_position_embeddings=512, <del> init_std=0.02, <del> is_encoder_decoder=True, <del> add_cross_attention=True, <del> decoder_start_token_id=0, <del> ngram=2, <del> num_buckets=32, <del> relative_max_distance=128, <del> disable_ngram_loss=False, <del> eps=0.0, <del> use_cache=True, <del> pad_token_id=0, <del> bos_token_id=1, <del> eos_token_id=2, <add> activation_dropout: Optional[float] = 0.1, <add> activation_function: Optional[Union[str, Callable]] = "gelu", <add> vocab_size: Optional[int] = 30522, <add> hidden_size: Optional[int] = 1024, <add> encoder_ffn_dim: Optional[int] = 4096, <add> num_encoder_layers: Optional[int] = 12, <add> num_encoder_attention_heads: Optional[int] = 16, <add> decoder_ffn_dim: Optional[int] = 4096, <add> num_decoder_layers: Optional[int] = 12, <add> num_decoder_attention_heads: Optional[int] = 16, <add> attention_dropout: Optional[float] = 0.1, <add> dropout: Optional[float] = 0.1, <add> max_position_embeddings: Optional[int] = 512, <add> init_std: Optional[float] = 0.02, <add> is_encoder_decoder: Optional[bool] = True, <add> add_cross_attention: Optional[bool] = True, <add> decoder_start_token_id: Optional[int] = 0, <add> ngram: Optional[int] = 2, <add> num_buckets: Optional[int] = 32, <add> relative_max_distance: Optional[int] = 128, <add> disable_ngram_loss: Optional[bool] = False, <add> eps: Optional[float] = 0.0, <add> use_cache: Optional[bool] = True, <add> pad_token_id: Optional[int] = 0, <add> bos_token_id: Optional[int] = 1, <add> eos_token_id: Optional[int] = 2, <ide> **kwargs <ide> ): <ide> self.vocab_size = vocab_size <ide><path>src/transformers/models/prophetnet/modeling_prophetnet.py <ide> class ProphetNetSeq2SeqModelOutput(ModelOutput): <ide> <ide> If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1, <ide> hidden_size)` is output. <del> last_hidden_state_ngram (`torch.FloatTensor` of shape `(batch_size,ngram * decoder_sequence_length, config.vocab_size)`): <add> last_hidden_state_ngram (`torch.FloatTensor` of shape `(batch_size,ngram * decoder_sequence_length, config.vocab_size)`, *optional*): <ide> Sequence of predict stream hidden-states at the output of the last layer of the decoder of the model. <ide> past_key_values (`List[torch.FloatTensor]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): <ide> List of `torch.FloatTensor` of length `config.n_layers`, with each tensor of shape `(2, batch_size, <ide> class ProphetNetPositionalEmbeddings(nn.Embedding): <ide> the forward function. <ide> """ <ide> <del> def __init__(self, config: ProphetNetConfig): <add> def __init__(self, config: ProphetNetConfig) -> None: <ide> self.max_length = config.max_position_embeddings <ide> super().__init__(config.max_position_embeddings, config.hidden_size, config.pad_token_id) <ide> <ide> class ProphetNetDecoder(ProphetNetPreTrainedModel): <ide> embeddings instead of randomly initialized word embeddings. <ide> """ <ide> <del> def __init__(self, config: ProphetNetConfig, word_embeddings: nn.Embedding = None): <add> def __init__(self, config: ProphetNetConfig, word_embeddings: Optional[nn.Embedding] = None): <ide> super().__init__(config) <ide> <ide> self.ngram = config.ngram <ide> def prepare_predict_attention_mask(self, hidden_states, attention_mask): <ide> PROPHETNET_START_DOCSTRING, <ide> ) <ide> class ProphetNetModel(ProphetNetPreTrainedModel): <del> def __init__(self, config): <add> def __init__(self, config: ProphetNetConfig): <ide> super().__init__(config) <ide> self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id) <ide> <ide> def get_decoder(self): <ide> PROPHETNET_START_DOCSTRING, <ide> ) <ide> class ProphetNetForCausalLM(ProphetNetPreTrainedModel): <del> def __init__(self, config): <add> def __init__(self, config: ProphetNetConfig): <ide> # set config for CLM <ide> config = copy.deepcopy(config) <ide> config.is_decoder = True <ide> class ProphetNetDecoderWrapper(ProphetNetPreTrainedModel): <ide> classes. <ide> """ <ide> <del> def __init__(self, config): <add> def __init__(self, config: ProphetNetConfig): <ide> super().__init__(config) <ide> self.decoder = ProphetNetDecoder(config) <ide> <ide><path>src/transformers/models/prophetnet/tokenization_prophetnet.py <ide> <ide> import collections <ide> import os <del>from typing import List, Optional, Tuple <add>from typing import Iterable, List, Optional, Tuple <ide> <ide> from ...tokenization_utils import PreTrainedTokenizer <ide> from ...utils import logging <ide> class ProphetNetTokenizer(PreTrainedTokenizer): <ide> <ide> def __init__( <ide> self, <del> vocab_file, <del> do_lower_case=True, <del> do_basic_tokenize=True, <del> never_split=None, <del> unk_token="[UNK]", <del> sep_token="[SEP]", <del> x_sep_token="[X_SEP]", <del> pad_token="[PAD]", <del> mask_token="[MASK]", <del> tokenize_chinese_chars=True, <del> strip_accents=None, <add> vocab_file: str, <add> do_lower_case: Optional[bool] = True, <add> do_basic_tokenize: Optional[bool] = True, <add> never_split: Optional[Iterable] = None, <add> unk_token: Optional[str] = "[UNK]", <add> sep_token: Optional[str] = "[SEP]", <add> x_sep_token: Optional[str] = "[X_SEP]", <add> pad_token: Optional[str] = "[PAD]", <add> mask_token: Optional[str] = "[MASK]", <add> tokenize_chinese_chars: Optional[bool] = True, <add> strip_accents: Optional[bool] = None, <ide> **kwargs <ide> ): <ide> super().__init__( <ide> def _tokenize(self, text): <ide> split_tokens = self.wordpiece_tokenizer.tokenize(text) <ide> return split_tokens <ide> <del> def _convert_token_to_id(self, token): <add> def _convert_token_to_id(self, token: str): <ide> """Converts a token (str) in an id using the vocab.""" <ide> return self.vocab.get(token, self.vocab.get(self.unk_token)) <ide> <del> def _convert_id_to_token(self, index): <add> def _convert_id_to_token(self, index: int): <ide> """Converts an index (integer) in a token (str) using the vocab.""" <ide> return self.ids_to_tokens.get(index, self.unk_token) <ide> <del> def convert_tokens_to_string(self, tokens): <add> def convert_tokens_to_string(self, tokens: str): <ide> """Converts a sequence of tokens (string) in a single string.""" <ide> out_string = " ".join(tokens).replace(" ##", "").strip() <ide> return out_string <ide> <ide> def get_special_tokens_mask( <del> self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False <add> self, <add> token_ids_0: List[int], <add> token_ids_1: Optional[List[int]] = None, <add> already_has_special_tokens: Optional[bool] = False, <ide> ) -> List[int]: <ide> """ <ide> Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
3
Python
Python
add some preliminary tests for shelloutsshclient
62152da83923197296eb367e95e459481f9caf10
<ide><path>libcloud/compute/ssh.py <ide> def _get_base_ssh_command(self): <ide> return cmd <ide> <ide> def _run_remote_shell_command(self, cmd): <add> """ <add> Run a command on a remote server. <add> <add> @param cmd: Command to run. <add> @type cmd: C{list} of C{str} <add> <add> @return: Command stdout, stderr and status code. <add> @rtype: C{tuple} <add> """ <ide> base_cmd = self._get_base_ssh_command() <ide> full_cmd = base_cmd + [' '.join(cmd)] <ide> <ide><path>libcloud/test/compute/test_ssh_client.py <ide> import unittest <ide> <ide> from libcloud.compute.ssh import ParamikoSSHClient <add>from libcloud.compute.ssh import ShellOutSSHClient <ide> from libcloud.compute.ssh import have_paramiko <ide> <ide> from mock import patch, Mock <ide> def test_delete_script(self): <ide> <ide> mock.close() <ide> <add> <ide> if not ParamikoSSHClient: <ide> class ParamikoSSHClientTests(unittest.TestCase): <ide> pass <ide> <ide> <add>class ShellOutSSHClientTests(unittest.TestCase): <add> def test_password_auth_not_supported(self): <add> try: <add> ShellOutSSHClient(hostname='localhost', username='foo', <add> password='bar') <add> except ValueError: <add> e = sys.exc_info()[1] <add> msg = str(e) <add> self.assertTrue('ShellOutSSHClient only supports key auth' in msg) <add> else: <add> self.fail('Exception was not thrown') <add> <add> def test_ssh_executable_not_available(self): <add> class MockChild(object): <add> returncode = 127 <add> <add> def communicate(*args, **kwargs): <add> pass <add> <add> def mock_popen(*args, **kwargs): <add> return MockChild() <add> <add> with patch('subprocess.Popen', mock_popen): <add> try: <add> ShellOutSSHClient(hostname='localhost', username='foo') <add> except ValueError: <add> e = sys.exc_info()[1] <add> msg = str(e) <add> self.assertTrue('ssh client is not available' in msg) <add> else: <add> self.fail('Exception was not thrown') <add> <add> def test_connect_success(self): <add> client = ShellOutSSHClient(hostname='localhost', username='root') <add> self.assertTrue(client.connect()) <add> <add> def test_close_success(self): <add> client = ShellOutSSHClient(hostname='localhost', username='root') <add> self.assertEqual(client.close(), None) <add> <add> def test_get_base_ssh_command(self): <add> client1 = ShellOutSSHClient(hostname='localhost', username='root') <add> client2 = ShellOutSSHClient(hostname='localhost', username='root', <add> key='/home/my.key') <add> client3 = ShellOutSSHClient(hostname='localhost', username='root', <add> key='/home/my.key', timeout=5) <add> <add> cmd1 = client1._get_base_ssh_command() <add> cmd2 = client2._get_base_ssh_command() <add> cmd3 = client3._get_base_ssh_command() <add> <add> self.assertEquals(cmd1, ['ssh', 'root@localhost']) <add> self.assertEquals(cmd2, ['ssh', '-i', '/home/my.key', <add> 'root@localhost']) <add> self.assertEquals(cmd3, ['ssh', '-i', '/home/my.key', <add> '-oConnectTimeout=5', 'root@localhost']) <add> <add> <ide> if __name__ == '__main__': <ide> sys.exit(unittest.main())
2
Java
Java
fix warnings in localsessionfactorybean
e3f544904c3cce5b6e9947c6429708a4b3bc4ef8
<ide><path>spring-orm/src/main/java/org/springframework/orm/hibernate3/LocalSessionFactoryBean.java <ide> import java.util.Enumeration; <ide> import java.util.Map; <ide> import java.util.Properties; <add> <ide> import javax.sql.DataSource; <ide> import javax.transaction.TransactionManager; <ide> <ide> import org.hibernate.HibernateException; <ide> import org.hibernate.Interceptor; <ide> import org.hibernate.Session; <ide> import org.hibernate.SessionFactory; <del>import org.hibernate.cache.CacheProvider; <ide> import org.hibernate.cfg.Configuration; <ide> import org.hibernate.cfg.Environment; <ide> import org.hibernate.cfg.NamingStrategy; <ide> import org.hibernate.event.EventListeners; <ide> import org.hibernate.tool.hbm2ddl.DatabaseMetadata; <ide> import org.hibernate.transaction.JTATransactionFactory; <del> <ide> import org.springframework.beans.BeanUtils; <ide> import org.springframework.beans.factory.BeanClassLoaderAware; <ide> import org.springframework.core.io.ClassPathResource; <ide> public class LocalSessionFactoryBean extends AbstractSessionFactoryBean implemen <ide> private static final ThreadLocal<Object> configTimeRegionFactoryHolder = <ide> new ThreadLocal<Object>(); <ide> <del> private static final ThreadLocal<CacheProvider> configTimeCacheProviderHolder = <del> new ThreadLocal<CacheProvider>(); <add> @SuppressWarnings("deprecation") <add> private static final ThreadLocal<org.hibernate.cache.CacheProvider> configTimeCacheProviderHolder = <add> new ThreadLocal<org.hibernate.cache.CacheProvider>(); <ide> <ide> private static final ThreadLocal<LobHandler> configTimeLobHandlerHolder = <ide> new ThreadLocal<LobHandler>(); <ide> static Object getConfigTimeRegionFactory() { <ide> * during configuration. <ide> * @see #setCacheProvider <ide> */ <del> public static CacheProvider getConfigTimeCacheProvider() { <add> @SuppressWarnings("deprecation") <add> public static org.hibernate.cache.CacheProvider getConfigTimeCacheProvider() { <ide> return configTimeCacheProviderHolder.get(); <ide> } <ide> <ide> public static LobHandler getConfigTimeLobHandler() { <ide> <ide> private Object cacheRegionFactory; <ide> <del> private CacheProvider cacheProvider; <add> @SuppressWarnings("deprecation") <add> private org.hibernate.cache.CacheProvider cacheProvider; <ide> <ide> private LobHandler lobHandler; <ide> <ide> public void setCacheRegionFactory(Object cacheRegionFactory) { <ide> * @see #setCacheRegionFactory <ide> */ <ide> @Deprecated <del> public void setCacheProvider(CacheProvider cacheProvider) { <add> public void setCacheProvider(org.hibernate.cache.CacheProvider cacheProvider) { <ide> this.cacheProvider = cacheProvider; <ide> } <ide> <ide> protected SessionFactory buildSessionFactory() throws Exception { <ide> } <ide> <ide> if (dataSource != null) { <del> Class providerClass = LocalDataSourceConnectionProvider.class; <add> Class<?> providerClass = LocalDataSourceConnectionProvider.class; <ide> if (isUseTransactionAwareDataSource() || dataSource instanceof TransactionAwareDataSourceProxy) { <ide> providerClass = TransactionAwareDataSourceConnectionProvider.class; <ide> } <ide> else if (this.cacheProvider != null) { <ide> <ide> if (this.entityCacheStrategies != null) { <ide> // Register cache strategies for mapped entities. <del> for (Enumeration classNames = this.entityCacheStrategies.propertyNames(); classNames.hasMoreElements();) { <add> for (Enumeration<?> classNames = this.entityCacheStrategies.propertyNames(); classNames.hasMoreElements();) { <ide> String className = (String) classNames.nextElement(); <ide> String[] strategyAndRegion = <ide> StringUtils.commaDelimitedListToStringArray(this.entityCacheStrategies.getProperty(className)); <ide> else if (strategyAndRegion.length > 0) { <ide> <ide> if (this.collectionCacheStrategies != null) { <ide> // Register cache strategies for mapped collections. <del> for (Enumeration collRoles = this.collectionCacheStrategies.propertyNames(); collRoles.hasMoreElements();) { <add> for (Enumeration<?> collRoles = this.collectionCacheStrategies.propertyNames(); collRoles.hasMoreElements();) { <ide> String collRole = (String) collRoles.nextElement(); <ide> String[] strategyAndRegion = <ide> StringUtils.commaDelimitedListToStringArray(this.collectionCacheStrategies.getProperty(collRole)); <ide> public void updateDatabaseSchema() throws DataAccessException { <ide> hibernateTemplate.execute( <ide> new HibernateCallback<Object>() { <ide> public Object doInHibernate(Session session) throws HibernateException, SQLException { <add> @SuppressWarnings("deprecation") <ide> Connection con = session.connection(); <ide> DatabaseMetadata metadata = new DatabaseMetadata(con, dialect); <ide> String[] sql = getConfiguration().generateSchemaUpdateScript(dialect, metadata); <ide> public void validateDatabaseSchema() throws DataAccessException { <ide> hibernateTemplate.execute( <ide> new HibernateCallback<Object>() { <ide> public Object doInHibernate(Session session) throws HibernateException, SQLException { <add> @SuppressWarnings("deprecation") <ide> Connection con = session.connection(); <ide> DatabaseMetadata metadata = new DatabaseMetadata(con, dialect, false); <ide> getConfiguration().validateSchema(dialect, metadata); <ide> public void dropDatabaseSchema() throws DataAccessException { <ide> hibernateTemplate.execute( <ide> new HibernateCallback<Object>() { <ide> public Object doInHibernate(Session session) throws HibernateException, SQLException { <add> @SuppressWarnings("deprecation") <ide> Connection con = session.connection(); <ide> String[] sql = getConfiguration().generateDropSchemaScript(dialect); <ide> executeSchemaScript(con, sql); <ide> public void createDatabaseSchema() throws DataAccessException { <ide> hibernateTemplate.execute( <ide> new HibernateCallback<Object>() { <ide> public Object doInHibernate(Session session) throws HibernateException, SQLException { <add> @SuppressWarnings("deprecation") <ide> Connection con = session.connection(); <ide> String[] sql = getConfiguration().generateSchemaCreationScript(dialect); <ide> executeSchemaScript(con, sql);
1
Python
Python
ignore all `*` characters in the reveal tests
b84946d15e5b63f44cd4bbbc04e5230a18720afc
<ide><path>numpy/typing/tests/test_typing.py <ide> def test_reveal(path): <ide> ]) <ide> <ide> with open(path) as fin: <del> lines = fin.readlines() <add> lines = fin.read().replace('*', '').split("\n") <ide> <del> for error_line in stdout.split("\n"): <add> stdout_list = stdout.replace('*', '').split("\n") <add> for error_line in stdout_list: <ide> error_line = error_line.strip() <ide> if not error_line: <ide> continue
1
Python
Python
remove test for
5e7d98f72a035b1dc5e600b9f77660fa1548074e
<ide><path>spacy/tests/regression/test_issue1491.py <del># coding: utf8 <del>from __future__ import unicode_literals <del> <del>import pytest <del>import regex as re <del> <del>from ...lang.en import English <del>from ...tokenizer import Tokenizer <del> <del> <del>@pytest.mark.xfail <del>def test_issue1491(): <del> """Test possible off-by-one error in tokenizer prefix/suffix/infix rules.""" <del> prefix_re = re.compile(r'''[\[\("']''') <del> suffix_re = re.compile(r'''[\]\)"']''') <del> infix_re = re.compile(r'''[-~]''') <del> <del> def my_tokenizer(nlp): <del> return Tokenizer(nlp.vocab, {}, <del> prefix_search=prefix_re.search, <del> suffix_search=suffix_re.search, <del> infix_finditer=infix_re.finditer) <del> <del> nlp = English() <del> nlp.tokenizer = my_tokenizer(nlp) <del> doc = nlp("single quote 'goodbye end.") <del> tokens = [token.text for token in doc] <del> assert tokens == ['single', 'quote', "'", 'goodbye', 'end', '.']
1
PHP
PHP
fix failing tests caused by path changes
87d3a2ef197c5f4e4b321b44d5e329b2018644d7
<ide><path>lib/Cake/Test/Case/Error/ExceptionRendererTest.php <ide> public static function testProvider() { <ide> 500 <ide> ), <ide> array( <del> new MissingHelperFileException(array('file' => 'my_custom.php', 'class' => 'MyCustomHelper')), <add> new MissingHelperFileException(array('file' => 'MyCustomHelper.php', 'class' => 'MyCustomHelper')), <ide> array( <ide> '/<h2>Missing Helper File<\/h2>/', <ide> '/Create the class below in file:/', <del> '/(\/|\\\)my_custom.php/' <add> '/(\/|\\\)MyCustomHelper.php/' <ide> ), <ide> 500 <ide> ), <ide> array( <del> new MissingHelperClassException(array('file' => 'my_custom.php', 'class' => 'MyCustomHelper')), <add> new MissingHelperClassException(array('file' => 'MyCustomHelper.php', 'class' => 'MyCustomHelper')), <ide> array( <ide> '/<h2>Missing Helper Class<\/h2>/', <ide> '/The helper class <em>MyCustomHelper<\/em> can not be found or does not exist./', <del> '/(\/|\\\)my_custom.php/', <add> '/(\/|\\\)MyCustomHelper.php/', <ide> ), <ide> 500 <ide> ), <ide> array( <del> new MissingBehaviorFileException(array('file' => 'my_custom.php', 'class' => 'MyCustomBehavior')), <add> new MissingBehaviorFileException(array('file' => 'MyCustomBehavior.php', 'class' => 'MyCustomBehavior')), <ide> array( <ide> '/<h2>Missing Behavior File<\/h2>/', <ide> '/Create the class below in file:/', <del> '/(\/|\\\)my_custom.php/', <add> '/(\/|\\\)MyCustomBehavior.php/', <ide> ), <ide> 500 <ide> ), <ide> array( <del> new MissingBehaviorClassException(array('file' => 'my_custom.php', 'class' => 'MyCustomBehavior')), <add> new MissingBehaviorClassException(array('file' => 'MyCustomBehavior.php', 'class' => 'MyCustomBehavior')), <ide> array( <ide> '/The behavior class <em>MyCustomBehavior<\/em> can not be found or does not exist./', <del> '/(\/|\\\)my_custom.php/' <add> '/(\/|\\\)MyCustomBehavior.php/' <ide> ), <ide> 500 <ide> ), <ide> array( <del> new MissingComponentFileException(array('file' => 'sidebox.php', 'class' => 'SideboxComponent')), <add> new MissingComponentFileException(array('file' => 'SideboxComponent.php', 'class' => 'SideboxComponent')), <ide> array( <ide> '/<h2>Missing Component File<\/h2>/', <ide> '/Create the class <em>SideboxComponent<\/em> in file:/', <del> '/(\/|\\\)sidebox.php/' <add> '/(\/|\\\)SideboxComponent.php/' <ide> ), <ide> 500 <ide> ), <ide> array( <del> new MissingComponentClassException(array('file' => 'sidebox.php', 'class' => 'SideboxComponent')), <add> new MissingComponentClassException(array('file' => 'SideboxComponent.php', 'class' => 'SideboxComponent')), <ide> array( <ide> '/<h2>Missing Component Class<\/h2>/', <ide> '/Create the class <em>SideboxComponent<\/em> in file:/', <del> '/(\/|\\\)sidebox.php/' <add> '/(\/|\\\)SideboxComponent.php/' <ide> ), <ide> 500 <ide> ),
1
Javascript
Javascript
reduce calls to getter
4c1ad1ee7dca825a667f1de95b4cf828fb06f046
<ide><path>lib/Compilation.js <ide> BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si <ide> // Here webpack is using heuristic that assumes <ide> // mostly esm dependencies would be used <ide> // so we don't allocate extra string for them <add> const category = dep.category; <ide> const cacheKey = <del> dep.category === esmDependencyCategory <add> category === esmDependencyCategory <ide> ? resourceIdent <del> : `${dep.category}${resourceIdent}`; <add> : `${category}${resourceIdent}`; <ide> const constructor = dep.constructor; <ide> let innerMap; <ide> let factory;
1
Javascript
Javascript
use same whitelist mechanism as $compile does
333523483f3ce6dd3177b697a5e5a7177ca364c8
<ide><path>angularFiles.js <ide> angularFiles = { <ide> 'src/ng/parse.js', <ide> 'src/ng/q.js', <ide> 'src/ng/rootScope.js', <add> 'src/ng/sanitizeUri.js', <ide> 'src/ng/sce.js', <ide> 'src/ng/sniffer.js', <ide> 'src/ng/timeout.js', <ide><path>src/AngularPublic.js <ide> $ParseProvider, <ide> $RootScopeProvider, <ide> $QProvider, <add> $$SanitizeUriProvider, <ide> $SceProvider, <ide> $SceDelegateProvider, <ide> $SnifferProvider, <ide> function publishExternalAPI(angular){ <ide> <ide> angularModule('ng', ['ngLocale'], ['$provide', <ide> function ngModule($provide) { <add> // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it. <add> $provide.provider({ <add> $$sanitizeUri: $$SanitizeUriProvider <add> }); <ide> $provide.provider('$compile', $CompileProvider). <ide> directive({ <ide> a: htmlAnchorDirective, <ide><path>src/ng/compile.js <ide> var $compileMinErr = minErr('$compile'); <ide> * <ide> * @description <ide> */ <del>$CompileProvider.$inject = ['$provide']; <del>function $CompileProvider($provide) { <add>$CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider']; <add>function $CompileProvider($provide, $$sanitizeUriProvider) { <ide> var hasDirectives = {}, <ide> Suffix = 'Directive', <ide> COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/, <del> CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/, <del> aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/, <del> imgSrcSanitizationWhitelist = /^\s*(https?|ftp|file):|data:image\//; <add> CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/; <ide> <ide> // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes <ide> // The assumption is that future DOM event attribute names will begin with <ide> function $CompileProvider($provide) { <ide> */ <ide> this.aHrefSanitizationWhitelist = function(regexp) { <ide> if (isDefined(regexp)) { <del> aHrefSanitizationWhitelist = regexp; <add> $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp); <ide> return this; <add> } else { <add> return $$sanitizeUriProvider.aHrefSanitizationWhitelist(); <ide> } <del> return aHrefSanitizationWhitelist; <ide> }; <ide> <ide> <ide> function $CompileProvider($provide) { <ide> */ <ide> this.imgSrcSanitizationWhitelist = function(regexp) { <ide> if (isDefined(regexp)) { <del> imgSrcSanitizationWhitelist = regexp; <add> $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp); <ide> return this; <add> } else { <add> return $$sanitizeUriProvider.imgSrcSanitizationWhitelist(); <ide> } <del> return imgSrcSanitizationWhitelist; <ide> }; <ide> <del> <ide> this.$get = [ <ide> '$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse', <del> '$controller', '$rootScope', '$document', '$sce', '$animate', <add> '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri', <ide> function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse, <del> $controller, $rootScope, $document, $sce, $animate) { <add> $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) { <ide> <ide> var Attributes = function(element, attr) { <ide> this.$$element = element; <ide> function $CompileProvider($provide) { <ide> // sanitize a[href] and img[src] values <ide> if ((nodeName === 'A' && key === 'href') || <ide> (nodeName === 'IMG' && key === 'src')) { <del> // NOTE: urlResolve() doesn't support IE < 8 so we don't sanitize for that case. <del> if (!msie || msie >= 8 ) { <del> normalizedVal = urlResolve(value).href; <del> if (normalizedVal !== '') { <del> if ((key === 'href' && !normalizedVal.match(aHrefSanitizationWhitelist)) || <del> (key === 'src' && !normalizedVal.match(imgSrcSanitizationWhitelist))) { <del> this[key] = value = 'unsafe:' + normalizedVal; <del> } <del> } <del> } <add> this[key] = value = $$sanitizeUri(value, key === 'src'); <ide> } <ide> <ide> if (writeAttr !== false) { <ide><path>src/ng/sanitizeUri.js <add>'use strict'; <add> <add>/** <add> * @description <add> * Private service to sanitize uris for links and images. Used by $compile and $sanitize. <add> */ <add>function $$SanitizeUriProvider() { <add> var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/, <add> imgSrcSanitizationWhitelist = /^\s*(https?|ftp|file):|data:image\//; <add> <add> /** <add> * @description <add> * Retrieves or overrides the default regular expression that is used for whitelisting of safe <add> * urls during a[href] sanitization. <add> * <add> * The sanitization is a security measure aimed at prevent XSS attacks via html links. <add> * <add> * Any url about to be assigned to a[href] via data-binding is first normalized and turned into <add> * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist` <add> * regular expression. If a match is found, the original url is written into the dom. Otherwise, <add> * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. <add> * <add> * @param {RegExp=} regexp New regexp to whitelist urls with. <add> * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for <add> * chaining otherwise. <add> */ <add> this.aHrefSanitizationWhitelist = function(regexp) { <add> if (isDefined(regexp)) { <add> aHrefSanitizationWhitelist = regexp; <add> return this; <add> } <add> return aHrefSanitizationWhitelist; <add> }; <add> <add> <add> /** <add> * @description <add> * Retrieves or overrides the default regular expression that is used for whitelisting of safe <add> * urls during img[src] sanitization. <add> * <add> * The sanitization is a security measure aimed at prevent XSS attacks via html links. <add> * <add> * Any url about to be assigned to img[src] via data-binding is first normalized and turned into <add> * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist` <add> * regular expression. If a match is found, the original url is written into the dom. Otherwise, <add> * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. <add> * <add> * @param {RegExp=} regexp New regexp to whitelist urls with. <add> * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for <add> * chaining otherwise. <add> */ <add> this.imgSrcSanitizationWhitelist = function(regexp) { <add> if (isDefined(regexp)) { <add> imgSrcSanitizationWhitelist = regexp; <add> return this; <add> } <add> return imgSrcSanitizationWhitelist; <add> }; <add> <add> this.$get = function() { <add> return function sanitizeUri(uri, isImage) { <add> var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist; <add> var normalizedVal; <add> // NOTE: urlResolve() doesn't support IE < 8 so we don't sanitize for that case. <add> if (!msie || msie >= 8 ) { <add> normalizedVal = urlResolve(uri).href; <add> if (normalizedVal !== '' && !normalizedVal.match(regex)) { <add> return 'unsafe:'+normalizedVal; <add> } <add> } <add> return uri; <add> }; <add> }; <add>} <ide><path>src/ngSanitize/filter/linky.js <ide> 'use strict'; <ide> <del>/* global htmlSanitizeWriter: false */ <add>/* global sanitizeText: false */ <ide> <ide> /** <ide> * @ngdoc filter <ide> </doc:scenario> <ide> </doc:example> <ide> */ <del>angular.module('ngSanitize').filter('linky', function() { <add>angular.module('ngSanitize').filter('linky', ['$sanitize', function($sanitize) { <ide> var LINKY_URL_REGEXP = <ide> /((ftp|https?):\/\/|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>]/, <ide> MAILTO_REGEXP = /^mailto:/; <ide> angular.module('ngSanitize').filter('linky', function() { <ide> var match; <ide> var raw = text; <ide> var html = []; <del> // TODO(vojta): use $sanitize instead <del> var writer = htmlSanitizeWriter(html); <ide> var url; <ide> var i; <del> var properties = {}; <del> if (angular.isDefined(target)) { <del> properties.target = target; <del> } <ide> while ((match = raw.match(LINKY_URL_REGEXP))) { <ide> // We can not end in these as they are sometimes found at the end of the sentence <ide> url = match[0]; <ide> // if we did not match ftp/http/mailto then assume mailto <ide> if (match[2] == match[3]) url = 'mailto:' + url; <ide> i = match.index; <del> writer.chars(raw.substr(0, i)); <del> properties.href = url; <del> writer.start('a', properties); <del> writer.chars(match[0].replace(MAILTO_REGEXP, '')); <del> writer.end('a'); <add> addText(raw.substr(0, i)); <add> addLink(url, match[0].replace(MAILTO_REGEXP, '')); <ide> raw = raw.substring(i + match[0].length); <ide> } <del> writer.chars(raw); <del> return html.join(''); <add> addText(raw); <add> return $sanitize(html.join('')); <add> <add> function addText(text) { <add> if (!text) { <add> return; <add> } <add> html.push(sanitizeText(text)); <add> } <add> <add> function addLink(url, text) { <add> html.push('<a '); <add> if (angular.isDefined(target)) { <add> html.push('target="'); <add> html.push(target); <add> html.push('" '); <add> } <add> html.push('href="'); <add> html.push(url); <add> html.push('">'); <add> addText(text); <add> html.push('</a>'); <add> } <ide> }; <del>}); <add>}]); <ide><path>src/ngSanitize/sanitize.js <ide> var $sanitizeMinErr = angular.$$minErr('$sanitize'); <ide> * it into the returned string, however, since our parser is more strict than a typical browser <ide> * parser, it's possible that some obscure input, which would be recognized as valid HTML by a <ide> * browser, won't make it through the sanitizer. <add> * The whitelist is configured using the functions `aHrefSanitizationWhitelist` and <add> * `imgSrcSanitizationWhitelist` of {@link ng.$compileProvider `$compileProvider`}. <ide> * <ide> * @param {string} html Html input. <ide> * @returns {string} Sanitized html. <ide> var $sanitizeMinErr = angular.$$minErr('$sanitize'); <ide> </doc:scenario> <ide> </doc:example> <ide> */ <del>var $sanitize = function(html) { <add>function $SanitizeProvider() { <add> this.$get = ['$$sanitizeUri', function($$sanitizeUri) { <add> return function(html) { <add> var buf = []; <add> htmlParser(html, htmlSanitizeWriter(buf, function(uri, isImage) { <add> return !/^unsafe/.test($$sanitizeUri(uri, isImage)); <add> })); <add> return buf.join(''); <add> }; <add> }]; <add>} <add> <add>function sanitizeText(chars) { <ide> var buf = []; <del> htmlParser(html, htmlSanitizeWriter(buf)); <del> return buf.join(''); <del>}; <add> var writer = htmlSanitizeWriter(buf, angular.noop); <add> writer.chars(chars); <add> return buf.join(''); <add>} <ide> <ide> <ide> // Regular Expressions for parsing tags and attributes <ide> var START_TAG_REGEXP = <ide> COMMENT_REGEXP = /<!--(.*?)-->/g, <ide> DOCTYPE_REGEXP = /<!DOCTYPE([^>]*?)>/i, <ide> CDATA_REGEXP = /<!\[CDATA\[(.*?)]]>/g, <del> URI_REGEXP = /^((ftp|https?):\/\/|mailto:|tel:|#)/i, <ide> // Match everything outside of normal chars and " (quote character) <ide> NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g; <ide> <ide> function htmlParser( html, handler ) { <ide> */ <ide> var hiddenPre=document.createElement("pre"); <ide> function decodeEntities(value) { <del> hiddenPre.innerHTML=value.replace(/</g,"&lt;"); <del> return hiddenPre.innerText || hiddenPre.textContent || ''; <add> if (!value) { <add> return ''; <add> } <add> // Note: IE8 does not preserve spaces at the start/end of innerHTML <add> var spaceRe = /^(\s*)([\s\S]*?)(\s*)$/; <add> var parts = spaceRe.exec(value); <add> parts[0] = ''; <add> if (parts[2]) { <add> hiddenPre.innerHTML=parts[2].replace(/</g,"&lt;"); <add> parts[2] = hiddenPre.innerText || hiddenPre.textContent; <add> } <add> return parts.join(''); <ide> } <ide> <ide> /** <ide> function encodeEntities(value) { <ide> * comment: function(text) {} <ide> * } <ide> */ <del>function htmlSanitizeWriter(buf){ <add>function htmlSanitizeWriter(buf, uriValidator){ <ide> var ignore = false; <ide> var out = angular.bind(buf, buf.push); <ide> return { <ide> function htmlSanitizeWriter(buf){ <ide> out(tag); <ide> angular.forEach(attrs, function(value, key){ <ide> var lkey=angular.lowercase(key); <del> if (validAttrs[lkey]===true && (uriAttrs[lkey]!==true || value.match(URI_REGEXP))) { <add> var isImage = (tag === 'img' && lkey === 'src') || (lkey === 'background'); <add> if (validAttrs[lkey] === true && <add> (uriAttrs[lkey] !== true || uriValidator(value, isImage))) { <ide> out(' '); <ide> out(key); <ide> out('="'); <ide> function htmlSanitizeWriter(buf){ <ide> <ide> <ide> // define ngSanitize module and register $sanitize service <del>angular.module('ngSanitize', []).value('$sanitize', $sanitize); <add>angular.module('ngSanitize', []).provider('$sanitize', $SanitizeProvider); <ide><path>test/ng/compileSpec.js <ide> describe('$compile', function() { <ide> <ide> <ide> describe('img[src] sanitization', function() { <add> <ide> it('should NOT require trusted values for img src', inject(function($rootScope, $compile, $sce) { <ide> element = $compile('<img src="{{testUrl}}"></img>')($rootScope); <ide> $rootScope.testUrl = 'http://example.com/image.png'; <ide> describe('$compile', function() { <ide> expect(element.attr('src')).toEqual('http://example.com/image2.png'); <ide> })); <ide> <del> it('should sanitize javascript: urls', inject(function($compile, $rootScope) { <del> element = $compile('<img src="{{testUrl}}"></a>')($rootScope); <del> $rootScope.testUrl = "javascript:doEvilStuff()"; <del> $rootScope.$apply(); <del> expect(element.attr('src')).toBe('unsafe:javascript:doEvilStuff()'); <del> })); <del> <del> it('should sanitize non-image data: urls', inject(function($compile, $rootScope) { <del> element = $compile('<img src="{{testUrl}}"></a>')($rootScope); <del> $rootScope.testUrl = "data:application/javascript;charset=US-ASCII,alert('evil!');"; <del> $rootScope.$apply(); <del> expect(element.attr('src')).toBe("unsafe:data:application/javascript;charset=US-ASCII,alert('evil!');"); <del> $rootScope.testUrl = "data:,foo"; <del> $rootScope.$apply(); <del> expect(element.attr('src')).toBe("unsafe:data:,foo"); <del> })); <del> <del> <del> it('should not sanitize data: URIs for images', inject(function($compile, $rootScope) { <del> element = $compile('<img src="{{dataUri}}"></img>')($rootScope); <del> <del> // image data uri <del> // ref: http://probablyprogramming.com/2009/03/15/the-tiniest-gif-ever <del> $rootScope.dataUri = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; <del> $rootScope.$apply(); <del> expect(element.attr('src')).toBe('data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=='); <del> })); <del> <del> <del> // Fails on IE <= 10 with "TypeError: Access is denied" when trying to set img[src] <del> if (!msie || msie > 10) { <del> it('should sanitize mailto: urls', inject(function($compile, $rootScope) { <del> element = $compile('<img src="{{testUrl}}"></a>')($rootScope); <del> $rootScope.testUrl = "mailto:foo@bar.com"; <del> $rootScope.$apply(); <del> expect(element.attr('src')).toBe('unsafe:mailto:foo@bar.com'); <del> })); <del> } <del> <del> it('should sanitize obfuscated javascript: urls', inject(function($compile, $rootScope) { <del> element = $compile('<img src="{{testUrl}}"></img>')($rootScope); <del> <del> // case-sensitive <del> $rootScope.testUrl = "JaVaScRiPt:doEvilStuff()"; <del> $rootScope.$apply(); <del> expect(element[0].src).toBe('unsafe:javascript:doEvilStuff()'); <del> <del> // tab in protocol <del> $rootScope.testUrl = "java\u0009script:doEvilStuff()"; <del> $rootScope.$apply(); <del> expect(element[0].src).toMatch(/(http:\/\/|unsafe:javascript:doEvilStuff\(\))/); <del> <del> // space before <del> $rootScope.testUrl = " javascript:doEvilStuff()"; <del> $rootScope.$apply(); <del> expect(element[0].src).toBe('unsafe:javascript:doEvilStuff()'); <del> <del> // ws chars before <del> $rootScope.testUrl = " \u000e javascript:doEvilStuff()"; <del> $rootScope.$apply(); <del> expect(element[0].src).toMatch(/(http:\/\/|unsafe:javascript:doEvilStuff\(\))/); <del> <del> // post-fixed with proper url <del> $rootScope.testUrl = "javascript:doEvilStuff(); http://make.me/look/good"; <del> $rootScope.$apply(); <del> expect(element[0].src).toBeOneOf( <del> 'unsafe:javascript:doEvilStuff(); http://make.me/look/good', <del> 'unsafe:javascript:doEvilStuff();%20http://make.me/look/good' <del> ); <del> })); <del> <del> it('should sanitize ng-src bindings as well', inject(function($compile, $rootScope) { <del> element = $compile('<img ng-src="{{testUrl}}"></img>')($rootScope); <del> $rootScope.testUrl = "javascript:doEvilStuff()"; <del> $rootScope.$apply(); <del> <del> expect(element[0].src).toBe('unsafe:javascript:doEvilStuff()'); <del> })); <del> <del> <del> it('should not sanitize valid urls', inject(function($compile, $rootScope) { <del> element = $compile('<img src="{{testUrl}}"></img>')($rootScope); <del> <del> $rootScope.testUrl = "foo/bar"; <del> $rootScope.$apply(); <del> expect(element.attr('src')).toBe('foo/bar'); <del> <del> $rootScope.testUrl = "/foo/bar"; <del> $rootScope.$apply(); <del> expect(element.attr('src')).toBe('/foo/bar'); <del> <del> $rootScope.testUrl = "../foo/bar"; <del> $rootScope.$apply(); <del> expect(element.attr('src')).toBe('../foo/bar'); <del> <del> $rootScope.testUrl = "#foo"; <del> $rootScope.$apply(); <del> expect(element.attr('src')).toBe('#foo'); <del> <del> $rootScope.testUrl = "http://foo.com/bar"; <del> $rootScope.$apply(); <del> expect(element.attr('src')).toBe('http://foo.com/bar'); <del> <del> $rootScope.testUrl = " http://foo.com/bar"; <del> $rootScope.$apply(); <del> expect(element.attr('src')).toBe(' http://foo.com/bar'); <del> <del> $rootScope.testUrl = "https://foo.com/bar"; <del> $rootScope.$apply(); <del> expect(element.attr('src')).toBe('https://foo.com/bar'); <del> <del> $rootScope.testUrl = "ftp://foo.com/bar"; <del> $rootScope.$apply(); <del> expect(element.attr('src')).toBe('ftp://foo.com/bar'); <del> <del> $rootScope.testUrl = "file:///foo/bar.html"; <del> $rootScope.$apply(); <del> expect(element.attr('src')).toBe('file:///foo/bar.html'); <del> })); <del> <del> <ide> it('should not sanitize attributes other than src', inject(function($compile, $rootScope) { <ide> element = $compile('<img title="{{testUrl}}"></img>')($rootScope); <ide> $rootScope.testUrl = "javascript:doEvilStuff()"; <ide> describe('$compile', function() { <ide> expect(element.attr('title')).toBe('javascript:doEvilStuff()'); <ide> })); <ide> <add> it('should use $$sanitizeUriProvider for reconfiguration of the src whitelist', function() { <add> module(function($compileProvider, $$sanitizeUriProvider) { <add> var newRe = /javascript:/, <add> returnVal; <add> expect($compileProvider.imgSrcSanitizationWhitelist()).toBe($$sanitizeUriProvider.imgSrcSanitizationWhitelist()); <ide> <del> it('should allow reconfiguration of the src whitelist', function() { <del> module(function($compileProvider) { <del> expect($compileProvider.imgSrcSanitizationWhitelist() instanceof RegExp).toBe(true); <del> var returnVal = $compileProvider.imgSrcSanitizationWhitelist(/javascript:/); <add> returnVal = $compileProvider.imgSrcSanitizationWhitelist(newRe); <ide> expect(returnVal).toBe($compileProvider); <add> expect($$sanitizeUriProvider.imgSrcSanitizationWhitelist()).toBe(newRe); <add> expect($compileProvider.imgSrcSanitizationWhitelist()).toBe(newRe); <ide> }); <add> inject(function() { <add> // needed to the module definition above is run... <add> }); <add> }); <ide> <add> it('should use $$sanitizeUri', function() { <add> var $$sanitizeUri = jasmine.createSpy('$$sanitizeUri'); <add> module(function($provide) { <add> $provide.value('$$sanitizeUri', $$sanitizeUri); <add> }); <ide> inject(function($compile, $rootScope) { <ide> element = $compile('<img src="{{testUrl}}"></img>')($rootScope); <add> $rootScope.testUrl = "someUrl"; <ide> <del> // Fails on IE <= 11 with "TypeError: Object doesn't support this property or method" when <del> // trying to set img[src] <del> if (!msie || msie > 11) { <del> $rootScope.testUrl = "javascript:doEvilStuff()"; <del> $rootScope.$apply(); <del> expect(element.attr('src')).toBe('javascript:doEvilStuff()'); <del> } <del> <del> $rootScope.testUrl = "http://recon/figured"; <add> $$sanitizeUri.andReturn('someSanitizedUrl'); <ide> $rootScope.$apply(); <del> expect(element.attr('src')).toBe('unsafe:http://recon/figured'); <add> expect(element.attr('src')).toBe('someSanitizedUrl'); <add> expect($$sanitizeUri).toHaveBeenCalledWith($rootScope.testUrl, true); <ide> }); <ide> }); <del> <ide> }); <ide> <ide> <ide> describe('a[href] sanitization', function() { <ide> <del> it('should sanitize javascript: urls', inject(function($compile, $rootScope) { <del> element = $compile('<a href="{{testUrl}}"></a>')($rootScope); <del> $rootScope.testUrl = "javascript:doEvilStuff()"; <del> $rootScope.$apply(); <del> <del> expect(element.attr('href')).toBe('unsafe:javascript:doEvilStuff()'); <del> })); <del> <del> <del> it('should sanitize data: urls', inject(function($compile, $rootScope) { <del> element = $compile('<a href="{{testUrl}}"></a>')($rootScope); <del> $rootScope.testUrl = "data:evilPayload"; <del> $rootScope.$apply(); <del> <del> expect(element.attr('href')).toBe('unsafe:data:evilPayload'); <del> })); <del> <del> <del> it('should sanitize obfuscated javascript: urls', inject(function($compile, $rootScope) { <del> element = $compile('<a href="{{testUrl}}"></a>')($rootScope); <del> <del> // case-sensitive <del> $rootScope.testUrl = "JaVaScRiPt:doEvilStuff()"; <del> $rootScope.$apply(); <del> expect(element[0].href).toBe('unsafe:javascript:doEvilStuff()'); <del> <del> // tab in protocol <del> $rootScope.testUrl = "java\u0009script:doEvilStuff()"; <del> $rootScope.$apply(); <del> expect(element[0].href).toMatch(/(http:\/\/|unsafe:javascript:doEvilStuff\(\))/); <del> <del> // space before <del> $rootScope.testUrl = " javascript:doEvilStuff()"; <del> $rootScope.$apply(); <del> expect(element[0].href).toBe('unsafe:javascript:doEvilStuff()'); <del> <del> // ws chars before <del> $rootScope.testUrl = " \u000e javascript:doEvilStuff()"; <del> $rootScope.$apply(); <del> expect(element[0].href).toMatch(/(http:\/\/|unsafe:javascript:doEvilStuff\(\))/); <del> <del> // post-fixed with proper url <del> $rootScope.testUrl = "javascript:doEvilStuff(); http://make.me/look/good"; <del> $rootScope.$apply(); <del> expect(element[0].href).toBeOneOf( <del> 'unsafe:javascript:doEvilStuff(); http://make.me/look/good', <del> 'unsafe:javascript:doEvilStuff();%20http://make.me/look/good' <del> ); <del> })); <del> <del> <del> it('should sanitize ngHref bindings as well', inject(function($compile, $rootScope) { <del> element = $compile('<a ng-href="{{testUrl}}"></a>')($rootScope); <del> $rootScope.testUrl = "javascript:doEvilStuff()"; <del> $rootScope.$apply(); <del> <del> expect(element[0].href).toBe('unsafe:javascript:doEvilStuff()'); <del> })); <del> <del> <del> it('should not sanitize valid urls', inject(function($compile, $rootScope) { <del> element = $compile('<a href="{{testUrl}}"></a>')($rootScope); <del> <del> $rootScope.testUrl = "foo/bar"; <del> $rootScope.$apply(); <del> expect(element.attr('href')).toBe('foo/bar'); <del> <del> $rootScope.testUrl = "/foo/bar"; <del> $rootScope.$apply(); <del> expect(element.attr('href')).toBe('/foo/bar'); <del> <del> $rootScope.testUrl = "../foo/bar"; <del> $rootScope.$apply(); <del> expect(element.attr('href')).toBe('../foo/bar'); <del> <del> $rootScope.testUrl = "#foo"; <del> $rootScope.$apply(); <del> expect(element.attr('href')).toBe('#foo'); <del> <del> $rootScope.testUrl = "http://foo/bar"; <del> $rootScope.$apply(); <del> expect(element.attr('href')).toBe('http://foo/bar'); <del> <del> $rootScope.testUrl = " http://foo/bar"; <del> $rootScope.$apply(); <del> expect(element.attr('href')).toBe(' http://foo/bar'); <del> <del> $rootScope.testUrl = "https://foo/bar"; <del> $rootScope.$apply(); <del> expect(element.attr('href')).toBe('https://foo/bar'); <del> <del> $rootScope.testUrl = "ftp://foo/bar"; <del> $rootScope.$apply(); <del> expect(element.attr('href')).toBe('ftp://foo/bar'); <del> <del> $rootScope.testUrl = "mailto:foo@bar.com"; <del> $rootScope.$apply(); <del> expect(element.attr('href')).toBe('mailto:foo@bar.com'); <del> <del> $rootScope.testUrl = "file:///foo/bar.html"; <del> $rootScope.$apply(); <del> expect(element.attr('href')).toBe('file:///foo/bar.html'); <del> })); <del> <del> <ide> it('should not sanitize href on elements other than anchor', inject(function($compile, $rootScope) { <ide> element = $compile('<div href="{{testUrl}}"></div>')($rootScope); <ide> $rootScope.testUrl = "javascript:doEvilStuff()"; <ide> describe('$compile', function() { <ide> expect(element.attr('href')).toBe('javascript:doEvilStuff()'); <ide> })); <ide> <del> <ide> it('should not sanitize attributes other than href', inject(function($compile, $rootScope) { <ide> element = $compile('<a title="{{testUrl}}"></a>')($rootScope); <ide> $rootScope.testUrl = "javascript:doEvilStuff()"; <ide> describe('$compile', function() { <ide> expect(element.attr('title')).toBe('javascript:doEvilStuff()'); <ide> })); <ide> <add> it('should use $$sanitizeUriProvider for reconfiguration of the href whitelist', function() { <add> module(function($compileProvider, $$sanitizeUriProvider) { <add> var newRe = /javascript:/, <add> returnVal; <add> expect($compileProvider.aHrefSanitizationWhitelist()).toBe($$sanitizeUriProvider.aHrefSanitizationWhitelist()); <ide> <del> it('should allow reconfiguration of the href whitelist', function() { <del> module(function($compileProvider) { <del> expect($compileProvider.aHrefSanitizationWhitelist() instanceof RegExp).toBe(true); <del> var returnVal = $compileProvider.aHrefSanitizationWhitelist(/javascript:/); <add> returnVal = $compileProvider.aHrefSanitizationWhitelist(newRe); <ide> expect(returnVal).toBe($compileProvider); <add> expect($$sanitizeUriProvider.aHrefSanitizationWhitelist()).toBe(newRe); <add> expect($compileProvider.aHrefSanitizationWhitelist()).toBe(newRe); <add> }); <add> inject(function() { <add> // needed to the module definition above is run... <ide> }); <add> }); <ide> <add> it('should use $$sanitizeUri', function() { <add> var $$sanitizeUri = jasmine.createSpy('$$sanitizeUri'); <add> module(function($provide) { <add> $provide.value('$$sanitizeUri', $$sanitizeUri); <add> }); <ide> inject(function($compile, $rootScope) { <ide> element = $compile('<a href="{{testUrl}}"></a>')($rootScope); <add> $rootScope.testUrl = "someUrl"; <ide> <del> $rootScope.testUrl = "javascript:doEvilStuff()"; <del> $rootScope.$apply(); <del> expect(element.attr('href')).toBe('javascript:doEvilStuff()'); <del> <del> $rootScope.testUrl = "http://recon/figured"; <add> $$sanitizeUri.andReturn('someSanitizedUrl'); <ide> $rootScope.$apply(); <del> expect(element.attr('href')).toBe('unsafe:http://recon/figured'); <add> expect(element.attr('href')).toBe('someSanitizedUrl'); <add> expect($$sanitizeUri).toHaveBeenCalledWith($rootScope.testUrl, false); <ide> }); <ide> }); <add> <ide> }); <ide> <ide> describe('interpolation on HTML DOM event handler attributes onclick, onXYZ, formaction', function() { <ide><path>test/ng/sanitizeUriSpec.js <add>'use strict'; <add> <add>describe('sanitizeUri', function() { <add> var sanitizeHref, sanitizeImg, sanitizeUriProvider, testUrl; <add> beforeEach(function() { <add> module(function(_$$sanitizeUriProvider_) { <add> sanitizeUriProvider = _$$sanitizeUriProvider_; <add> }); <add> inject(function($$sanitizeUri) { <add> sanitizeHref = function(uri) { <add> return $$sanitizeUri(uri, false); <add> }; <add> sanitizeImg = function(uri) { <add> return $$sanitizeUri(uri, true); <add> } <add> }); <add> }); <add> <add> function isEvilInCurrentBrowser(uri) { <add> var a = document.createElement('a'); <add> a.setAttribute('href', uri); <add> return a.href.substring(0, 4) !== 'http'; <add> } <add> <add> describe('img[src] sanitization', function() { <add> <add> it('should sanitize javascript: urls', function() { <add> testUrl = "javascript:doEvilStuff()"; <add> expect(sanitizeImg(testUrl)).toBe('unsafe:javascript:doEvilStuff()'); <add> }); <add> <add> it('should sanitize non-image data: urls', function() { <add> testUrl = "data:application/javascript;charset=US-ASCII,alert('evil!');"; <add> expect(sanitizeImg(testUrl)).toBe("unsafe:data:application/javascript;charset=US-ASCII,alert('evil!');"); <add> <add> testUrl = "data:,foo"; <add> expect(sanitizeImg(testUrl)).toBe("unsafe:data:,foo"); <add> }); <add> <add> it('should not sanitize data: URIs for images', function() { <add> // image data uri <add> // ref: http://probablyprogramming.com/2009/03/15/the-tiniest-gif-ever <add> testUrl = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; <add> expect(sanitizeImg(testUrl)).toBe('data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=='); <add> }); <add> <add> it('should sanitize mailto: urls', function() { <add> testUrl = "mailto:foo@bar.com"; <add> expect(sanitizeImg(testUrl)).toBe('unsafe:mailto:foo@bar.com'); <add> }); <add> <add> it('should sanitize obfuscated javascript: urls', function() { <add> // case-sensitive <add> testUrl = "JaVaScRiPt:doEvilStuff()"; <add> expect(sanitizeImg(testUrl)).toBe('unsafe:javascript:doEvilStuff()'); <add> <add> // tab in protocol <add> testUrl = "java\u0009script:doEvilStuff()"; <add> if (isEvilInCurrentBrowser(testUrl)) { <add> expect(sanitizeImg(testUrl)).toEqual('unsafe:javascript:doEvilStuff()'); <add> } <add> <add> // space before <add> testUrl = " javascript:doEvilStuff()"; <add> expect(sanitizeImg(testUrl)).toBe('unsafe:javascript:doEvilStuff()'); <add> <add> // ws chars before <add> testUrl = " \u000e javascript:doEvilStuff()"; <add> if (isEvilInCurrentBrowser(testUrl)) { <add> expect(sanitizeImg(testUrl)).toEqual('unsafe:javascript:doEvilStuff()'); <add> } <add> <add> // post-fixed with proper url <add> testUrl = "javascript:doEvilStuff(); http://make.me/look/good"; <add> expect(sanitizeImg(testUrl)).toBeOneOf( <add> 'unsafe:javascript:doEvilStuff(); http://make.me/look/good', <add> 'unsafe:javascript:doEvilStuff();%20http://make.me/look/good' <add> ); <add> }); <add> <add> it('should sanitize ng-src bindings as well', function() { <add> testUrl = "javascript:doEvilStuff()"; <add> expect(sanitizeImg(testUrl)).toBe('unsafe:javascript:doEvilStuff()'); <add> }); <add> <add> <add> it('should not sanitize valid urls', function() { <add> testUrl = "foo/bar"; <add> expect(sanitizeImg(testUrl)).toBe('foo/bar'); <add> <add> testUrl = "/foo/bar"; <add> expect(sanitizeImg(testUrl)).toBe('/foo/bar'); <add> <add> testUrl = "../foo/bar"; <add> expect(sanitizeImg(testUrl)).toBe('../foo/bar'); <add> <add> testUrl = "#foo"; <add> expect(sanitizeImg(testUrl)).toBe('#foo'); <add> <add> testUrl = "http://foo.com/bar"; <add> expect(sanitizeImg(testUrl)).toBe('http://foo.com/bar'); <add> <add> testUrl = " http://foo.com/bar"; <add> expect(sanitizeImg(testUrl)).toBe(' http://foo.com/bar'); <add> <add> testUrl = "https://foo.com/bar"; <add> expect(sanitizeImg(testUrl)).toBe('https://foo.com/bar'); <add> <add> testUrl = "ftp://foo.com/bar"; <add> expect(sanitizeImg(testUrl)).toBe('ftp://foo.com/bar'); <add> <add> testUrl = "file:///foo/bar.html"; <add> expect(sanitizeImg(testUrl)).toBe('file:///foo/bar.html'); <add> }); <add> <add> <add> it('should allow reconfiguration of the src whitelist', function() { <add> var returnVal; <add> expect(sanitizeUriProvider.imgSrcSanitizationWhitelist() instanceof RegExp).toBe(true); <add> returnVal = sanitizeUriProvider.imgSrcSanitizationWhitelist(/javascript:/); <add> expect(returnVal).toBe(sanitizeUriProvider); <add> <add> testUrl = "javascript:doEvilStuff()"; <add> expect(sanitizeImg(testUrl)).toBe('javascript:doEvilStuff()'); <add> <add> testUrl = "http://recon/figured"; <add> expect(sanitizeImg(testUrl)).toBe('unsafe:http://recon/figured'); <add> }); <add> <add> }); <add> <add> <add> describe('a[href] sanitization', function() { <add> <add> it('should sanitize javascript: urls', inject(function() { <add> testUrl = "javascript:doEvilStuff()"; <add> expect(sanitizeHref(testUrl)).toBe('unsafe:javascript:doEvilStuff()'); <add> })); <add> <add> <add> it('should sanitize data: urls', inject(function() { <add> testUrl = "data:evilPayload"; <add> expect(sanitizeHref(testUrl)).toBe('unsafe:data:evilPayload'); <add> })); <add> <add> <add> it('should sanitize obfuscated javascript: urls', inject(function() { <add> // case-sensitive <add> testUrl = "JaVaScRiPt:doEvilStuff()"; <add> expect(sanitizeHref(testUrl)).toBe('unsafe:javascript:doEvilStuff()'); <add> <add> // tab in protocol <add> testUrl = "java\u0009script:doEvilStuff()"; <add> if (isEvilInCurrentBrowser(testUrl)) { <add> expect(sanitizeHref(testUrl)).toEqual('unsafe:javascript:doEvilStuff()'); <add> } <add> <add> // space before <add> testUrl = " javascript:doEvilStuff()"; <add> expect(sanitizeHref(testUrl)).toBe('unsafe:javascript:doEvilStuff()'); <add> <add> // ws chars before <add> testUrl = " \u000e javascript:doEvilStuff()"; <add> if (isEvilInCurrentBrowser(testUrl)) { <add> expect(sanitizeHref(testUrl)).toEqual('unsafe:javascript:doEvilStuff()'); <add> } <add> <add> // post-fixed with proper url <add> testUrl = "javascript:doEvilStuff(); http://make.me/look/good"; <add> expect(sanitizeHref(testUrl)).toBeOneOf( <add> 'unsafe:javascript:doEvilStuff(); http://make.me/look/good', <add> 'unsafe:javascript:doEvilStuff();%20http://make.me/look/good' <add> ); <add> })); <add> <add> <add> it('should sanitize ngHref bindings as well', inject(function() { <add> testUrl = "javascript:doEvilStuff()"; <add> expect(sanitizeHref(testUrl)).toBe('unsafe:javascript:doEvilStuff()'); <add> })); <add> <add> <add> it('should not sanitize valid urls', inject(function() { <add> testUrl = "foo/bar"; <add> expect(sanitizeHref(testUrl)).toBe('foo/bar'); <add> <add> testUrl = "/foo/bar"; <add> expect(sanitizeHref(testUrl)).toBe('/foo/bar'); <add> <add> testUrl = "../foo/bar"; <add> expect(sanitizeHref(testUrl)).toBe('../foo/bar'); <add> <add> testUrl = "#foo"; <add> expect(sanitizeHref(testUrl)).toBe('#foo'); <add> <add> testUrl = "http://foo/bar"; <add> expect(sanitizeHref(testUrl)).toBe('http://foo/bar'); <add> <add> testUrl = " http://foo/bar"; <add> expect(sanitizeHref(testUrl)).toBe(' http://foo/bar'); <add> <add> testUrl = "https://foo/bar"; <add> expect(sanitizeHref(testUrl)).toBe('https://foo/bar'); <add> <add> testUrl = "ftp://foo/bar"; <add> expect(sanitizeHref(testUrl)).toBe('ftp://foo/bar'); <add> <add> testUrl = "mailto:foo@bar.com"; <add> expect(sanitizeHref(testUrl)).toBe('mailto:foo@bar.com'); <add> <add> testUrl = "file:///foo/bar.html"; <add> expect(sanitizeHref(testUrl)).toBe('file:///foo/bar.html'); <add> })); <add> <add> it('should allow reconfiguration of the href whitelist', function() { <add> var returnVal; <add> expect(sanitizeUriProvider.aHrefSanitizationWhitelist() instanceof RegExp).toBe(true); <add> returnVal = sanitizeUriProvider.aHrefSanitizationWhitelist(/javascript:/); <add> expect(returnVal).toBe(sanitizeUriProvider); <add> <add> testUrl = "javascript:doEvilStuff()"; <add> expect(sanitizeHref(testUrl)).toBe('javascript:doEvilStuff()'); <add> <add> testUrl = "http://recon/figured"; <add> expect(sanitizeHref(testUrl)).toBe('unsafe:http://recon/figured'); <add> }); <add> <add> }); <add> <add>}); <ide>\ No newline at end of file <ide><path>test/ngSanitize/sanitizeSpec.js <ide> describe('HTML', function() { <ide> var expectHTML; <ide> <ide> beforeEach(module('ngSanitize')); <del> <del> beforeEach(inject(function($sanitize) { <add> beforeEach(function() { <ide> expectHTML = function(html){ <del> return expect($sanitize(html)); <add> var sanitize; <add> inject(function($sanitize) { <add> sanitize = $sanitize; <add> }); <add> return expect(sanitize(html)); <ide> }; <del> })); <add> }); <ide> <ide> describe('htmlParser', function() { <ide> if (angular.isUndefined(window.htmlParser)) return; <ide> describe('HTML', function() { <ide> toEqual(''); <ide> }); <ide> <add> it('should keep spaces as prefix/postfix', function() { <add> expectHTML(' a ').toEqual(' a '); <add> }); <add> <add> it('should allow multiline strings', function() { <add> expectHTML('\na\n').toEqual('&#10;a\&#10;'); <add> }); <add> <ide> describe('htmlSanitizerWriter', function() { <ide> if (angular.isUndefined(window.htmlSanitizeWriter)) return; <ide> <del> var writer, html; <add> var writer, html, uriValidator; <ide> beforeEach(function() { <ide> html = ''; <del> writer = htmlSanitizeWriter({push:function(text){html+=text;}}); <add> uriValidator = jasmine.createSpy('uriValidator'); <add> writer = htmlSanitizeWriter({push:function(text){html+=text;}}, uriValidator); <ide> }); <ide> <ide> it('should write basic HTML', function() { <ide> describe('HTML', function() { <ide> }); <ide> }); <ide> <del> describe('isUri', function() { <add> describe('uri validation', function() { <add> it('should call the uri validator', function() { <add> writer.start('a', {href:'someUrl'}, false); <add> expect(uriValidator).toHaveBeenCalledWith('someUrl', false); <add> uriValidator.reset(); <add> writer.start('img', {src:'someImgUrl'}, false); <add> expect(uriValidator).toHaveBeenCalledWith('someImgUrl', true); <add> uriValidator.reset(); <add> writer.start('someTag', {src:'someNonUrl'}, false); <add> expect(uriValidator).not.toHaveBeenCalled(); <add> }); <ide> <del> function isUri(value) { <del> return value.match(URI_REGEXP); <del> } <add> it('should drop non valid uri attributes', function() { <add> uriValidator.andReturn(false); <add> writer.start('a', {href:'someUrl'}, false); <add> expect(html).toEqual('<a>'); <ide> <del> it('should be URI', function() { <del> expect(isUri('http://abc')).toBeTruthy(); <del> expect(isUri('HTTP://abc')).toBeTruthy(); <del> expect(isUri('https://abc')).toBeTruthy(); <del> expect(isUri('HTTPS://abc')).toBeTruthy(); <del> expect(isUri('ftp://abc')).toBeTruthy(); <del> expect(isUri('FTP://abc')).toBeTruthy(); <del> expect(isUri('mailto:me@example.com')).toBeTruthy(); <del> expect(isUri('MAILTO:me@example.com')).toBeTruthy(); <del> expect(isUri('tel:123-123-1234')).toBeTruthy(); <del> expect(isUri('TEL:123-123-1234')).toBeTruthy(); <del> expect(isUri('#anchor')).toBeTruthy(); <add> html = ''; <add> uriValidator.andReturn(true); <add> writer.start('a', {href:'someUrl'}, false); <add> expect(html).toEqual('<a href="someUrl">'); <ide> }); <add> }); <add> }); <ide> <del> it('should not be URI', function() { <del> expect(isUri('')).toBeFalsy(); <del> expect(isUri('javascript:alert')).toBeFalsy(); <add> describe('uri checking', function() { <add> beforeEach(function() { <add> this.addMatchers({ <add> toBeValidUrl: function() { <add> var sanitize; <add> inject(function($sanitize) { <add> sanitize = $sanitize; <add> }); <add> var input = '<a href="'+this.actual+'"></a>'; <add> return sanitize(input) === input; <add> }, <add> toBeValidImageSrc: function() { <add> var sanitize; <add> inject(function($sanitize) { <add> sanitize = $sanitize; <add> }); <add> var input = '<img src="'+this.actual+'"/>'; <add> return sanitize(input) === input; <add> } <ide> }); <ide> }); <ide> <del> describe('javascript URL attribute', function() { <del> beforeEach(function() { <del> this.addMatchers({ <del> toBeValidUrl: function() { <del> return URI_REGEXP.exec(this.actual); <del> } <del> }); <add> it('should use $$sanitizeUri for links', function() { <add> var $$sanitizeUri = jasmine.createSpy('$$sanitizeUri'); <add> module(function($provide) { <add> $provide.value('$$sanitizeUri', $$sanitizeUri); <ide> }); <add> inject(function() { <add> $$sanitizeUri.andReturn('someUri'); <ide> <add> expectHTML('<a href="someUri"></a>').toEqual('<a href="someUri"></a>'); <add> expect($$sanitizeUri).toHaveBeenCalledWith('someUri', false); <add> <add> $$sanitizeUri.andReturn('unsafe:someUri'); <add> expectHTML('<a href="someUri"></a>').toEqual('<a></a>'); <add> }); <add> }); <add> <add> it('should use $$sanitizeUri for links', function() { <add> var $$sanitizeUri = jasmine.createSpy('$$sanitizeUri'); <add> module(function($provide) { <add> $provide.value('$$sanitizeUri', $$sanitizeUri); <add> }); <add> inject(function() { <add> $$sanitizeUri.andReturn('someUri'); <add> <add> expectHTML('<img src="someUri"/>').toEqual('<img src="someUri"/>'); <add> expect($$sanitizeUri).toHaveBeenCalledWith('someUri', true); <add> <add> $$sanitizeUri.andReturn('unsafe:someUri'); <add> expectHTML('<img src="someUri"/>').toEqual('<img/>'); <add> }); <add> }); <add> <add> it('should be URI', function() { <add> expect('').toBeValidUrl(); <add> expect('http://abc').toBeValidUrl(); <add> expect('HTTP://abc').toBeValidUrl(); <add> expect('https://abc').toBeValidUrl(); <add> expect('HTTPS://abc').toBeValidUrl(); <add> expect('ftp://abc').toBeValidUrl(); <add> expect('FTP://abc').toBeValidUrl(); <add> expect('mailto:me@example.com').toBeValidUrl(); <add> expect('MAILTO:me@example.com').toBeValidUrl(); <add> expect('tel:123-123-1234').toBeValidUrl(); <add> expect('TEL:123-123-1234').toBeValidUrl(); <add> expect('#anchor').toBeValidUrl(); <add> expect('/page1.md').toBeValidUrl(); <add> }); <add> <add> it('should not be URI', function() { <add> expect('javascript:alert').not.toBeValidUrl(); <add> }); <add> <add> describe('javascript URLs', function() { <ide> it('should ignore javascript:', function() { <ide> expect('JavaScript:abc').not.toBeValidUrl(); <ide> expect(' \n Java\n Script:abc').not.toBeValidUrl(); <ide> describe('HTML', function() { <ide> }); <ide> <ide> it('should ignore hex encoded whitespace javascript:', function() { <del> expect('jav&#x09;ascript:alert("A");').not.toBeValidUrl(); <del> expect('jav&#x0A;ascript:alert("B");').not.toBeValidUrl(); <del> expect('jav&#x0A ascript:alert("C");').not.toBeValidUrl(); <del> expect('jav\u0000ascript:alert("D");').not.toBeValidUrl(); <del> expect('java\u0000\u0000script:alert("D");').not.toBeValidUrl(); <del> expect(' &#14; java\u0000\u0000script:alert("D");').not.toBeValidUrl(); <add> expect('jav&#x09;ascript:alert();').not.toBeValidUrl(); <add> expect('jav&#x0A;ascript:alert();').not.toBeValidUrl(); <add> expect('jav&#x0A ascript:alert();').not.toBeValidUrl(); <add> expect('jav\u0000ascript:alert();').not.toBeValidUrl(); <add> expect('java\u0000\u0000script:alert();').not.toBeValidUrl(); <add> expect(' &#14; java\u0000\u0000script:alert();').not.toBeValidUrl(); <ide> }); <ide> }); <add> }); <ide> <del> <add> describe('sanitizeText', function() { <add> it('should escape text', function() { <add> expect(sanitizeText('a<div>&</div>c')).toEqual('a&lt;div&gt;&amp;&lt;/div&gt;c'); <add> }); <ide> }); <ide> });
9
Python
Python
add __init__ method to variable class
2bb40ef996a9da5e4eb7f63cceeef9b03b51494e
<ide><path>airflow/models/variable.py <ide> class Variable(Base, LoggingMixin): <ide> _val = Column('val', Text) <ide> is_encrypted = Column(Boolean, unique=False, default=False) <ide> <add> def __init__(self, key=None, val=None): <add> super().__init__() <add> self.key = key <add> self.val = val <add> <ide> def __repr__(self): <ide> # Hiding the value <ide> return '{} : {}'.format(self.key, self._val) <ide> def set( <ide> stored_value = str(value) <ide> <ide> Variable.delete(key, session=session) <del> session.add(Variable(key=key, val=stored_value)) # type: ignore # pylint: disable=E1123 <add> session.add(Variable(key=key, val=stored_value)) <ide> session.flush() <ide> <ide> @classmethod
1
Javascript
Javascript
fix regex to match windows line endings
cc04f14e2be5c790c4036251793b4ceab2093a03
<ide><path>lib/broccoli-ember-inline-template-precompiler.js <ide> function EmberInlineTemplatePrecompiler (inputTree, options) { <ide> this.inlineTemplateRegExp = /precompileTemplate\(['"](.*)['"]\)/; <ide> // Used for replacing the original variable declaration to satisfy JSHint. <ide> // For example, removes `var precompileTemplate = Ember.Handlebars.compile;`. <del> this.precompileTemplateVarRegex = /var precompileTemplate =.*\n/g; <add> this.precompileTemplateVarRegex = /var precompileTemplate =.*\r?\n/g; <ide> } <ide> <ide> EmberInlineTemplatePrecompiler.prototype.extensions = ['js'];
1
Ruby
Ruby
fix deprecation warnings in verification tests
25ea18aa150c7eb26fd09ab6ab26eb455fac7ff0
<ide><path>actionpack/test/controller/verification_test.rb <ide> class TestController < ActionController::Base <ide> :redirect_to => { :action => "unguarded" } <ide> <ide> verify :only => :guarded_with_flash, :params => "one", <del> :add_flash => { "notice" => "prereqs failed" }, <add> :add_flash => { :notice => "prereqs failed" }, <ide> :redirect_to => { :action => "unguarded" } <ide> <ide> verify :only => :guarded_in_session, :session => "one", <ide> def guarded_two <ide> end <ide> <ide> def guarded_in_session <del> render :text => "#{@session["one"]}" <add> render :text => "#{session["one"]}" <ide> end <ide> <ide> def multi_one <del> render :text => "#{@session["one"]}:#{@session["two"]}" <add> render :text => "#{session["one"]}:#{session["two"]}" <ide> end <ide> <ide> def multi_two <del> render :text => "#{@session["two"]}:#{@session["one"]}" <add> render :text => "#{session["two"]}:#{session["one"]}" <ide> end <ide> <ide> def guarded_by_method <ide> def test_guarded_one_without_prereqs <ide> def test_guarded_with_flash_with_prereqs <ide> get :guarded_with_flash, :one => "here" <ide> assert_equal "here", @response.body <del> assert_flash_empty <add> assert flash.empty? <ide> end <ide> <ide> def test_guarded_with_flash_without_prereqs <ide> get :guarded_with_flash <ide> assert_redirected_to :action => "unguarded" <del> assert_flash_equal "prereqs failed", "notice" <add> assert_equal "prereqs failed", flash[:notice] <ide> end <ide> <ide> def test_guarded_two_with_prereqs
1