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
|
---|---|---|---|---|---|
Javascript | Javascript | fix wrong context argument to `apply` | e0af1aabec3d3ee24f57aaaf9407860463f20213 | <ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.new.js
<ide> export function queueRecoverableErrors(errors: Array<mixed>) {
<ide> workInProgressRootRecoverableErrors = errors;
<ide> } else {
<ide> workInProgressRootConcurrentErrors = workInProgressRootConcurrentErrors.push.apply(
<del> null,
<add> workInProgressRootConcurrentErrors,
<ide> errors,
<ide> );
<ide> }
<ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.old.js
<ide> export function queueRecoverableErrors(errors: Array<mixed>) {
<ide> workInProgressRootRecoverableErrors = errors;
<ide> } else {
<ide> workInProgressRootConcurrentErrors = workInProgressRootConcurrentErrors.push.apply(
<del> null,
<add> workInProgressRootConcurrentErrors,
<ide> errors,
<ide> );
<ide> } | 2 |
Javascript | Javascript | remove console.logs (#402) | 43b0e6f51420325abf2aed1157a197392364b25d | <ide><path>client/next-prefetcher.js
<ide> /* global self */
<ide>
<ide> const CACHE_NAME = 'next-prefetcher-v1'
<add>const log = () => {}
<ide>
<ide> self.addEventListener('install', () => {
<del> console.log('Installing Next Prefetcher')
<add> log('Installing Next Prefetcher')
<ide> })
<ide>
<ide> self.addEventListener('activate', (e) => {
<del> console.log('Activated Next Prefetcher')
<add> log('Activated Next Prefetcher')
<ide> e.waitUntil(Promise.all([
<ide> resetCache(),
<ide> notifyClients()
<ide> self.addEventListener('fetch', (e) => {
<ide> self.addEventListener('message', (e) => {
<ide> switch (e.data.action) {
<ide> case 'ADD_URL': {
<del> console.log('CACHING ', e.data.url)
<add> log('CACHING ', e.data.url)
<ide> sendReply(e, cacheUrl(e.data.url))
<ide> break
<ide> }
<ide> case 'RESET': {
<del> console.log('RESET')
<add> log('RESET')
<ide> sendReply(e, resetCache())
<ide> break
<ide> }
<ide> function getResponse (req) {
<ide> .then((cache) => cache.match(req))
<ide> .then((res) => {
<ide> if (res) {
<del> console.log('CACHE HIT: ' + req.url)
<add> log('CACHE HIT: ' + req.url)
<ide> return res
<ide> } else {
<del> console.log('CACHE MISS: ' + req.url)
<add> log('CACHE MISS: ' + req.url)
<ide> return self.fetch(req)
<ide> }
<ide> })
<ide><path>lib/prefetch.js
<ide> class Messenger {
<ide> this.serviceWorkerState = 'REGISTERED'
<ide> this.serviceWorkerReadyCallbacks.forEach(cb => cb())
<ide> this.serviceWorkerReadyCallbacks = []
<del> console.log('Next Prefetcher registered')
<ide> })
<ide> }
<ide> } | 2 |
PHP | PHP | add throws tag for public method | 3bd551afada4561f96b54775e15b68c781dabd62 | <ide><path>src/View/Helper/FormHelper.php
<ide> protected function validateValueSources(array $sources): void
<ide> * @see FormHelper::$supportedValueSources for valid values.
<ide> * @param string|string[] $sources A string or a list of strings identifying a source.
<ide> * @return $this
<add> * @throws \InvalidArgumentException If sources list contains invalid value.
<ide> */
<ide> public function setValueSources($sources)
<ide> { | 1 |
PHP | PHP | add simple caching to fixture loading | 2da2f840f727c80e97b5ad35b46f4eacd3b8d925 | <ide><path>src/TestSuite/Fixture/FixtureHelper.php
<ide> class FixtureHelper
<ide> */
<ide> public function loadFixtures(array $fixtureNames): array
<ide> {
<add> static $cachedFixtures = [];
<add>
<ide> $fixtures = [];
<ide> foreach ($fixtureNames as $fixtureName) {
<ide> if (strpos($fixtureName, '.')) {
<ide> public function loadFixtures(array $fixtureNames): array
<ide> throw new UnexpectedValueException("Could not find fixture `$fixtureName`.");
<ide> }
<ide>
<del> $fixtures[$className] = new $className();
<add> if (!isset($cachedFixtures[$className])) {
<add> $cachedFixtures[$className] = new $className();
<add> }
<add>
<add> $fixtures[$className] = $cachedFixtures[$className];
<ide> }
<ide>
<ide> return $fixtures; | 1 |
Ruby | Ruby | fix typo in routing documentation | 858efc9cbdec47888a4056cf82238605d825b542 | <ide><path>actionpack/lib/action_dispatch/routing/mapper.rb
<ide> def put(*args, &block)
<ide> map_method(:put, args, &block)
<ide> end
<ide>
<del> # Define a route that only recognizes HTTP PUT.
<add> # Define a route that only recognizes HTTP DELETE.
<ide> # For supported arguments, see <tt>Base#match</tt>.
<ide> #
<ide> # Example: | 1 |
Text | Text | add hint and solution | 7bc3f6378f64daf227105ccd2f564d989eeca94e | <ide><path>guide/english/certifications/front-end-libraries/react-and-redux/use-provider-to-connect-redux-to-react/index.md
<ide> title: Use Provider to Connect Redux to React
<ide> ---
<ide> ## Use Provider to Connect Redux to React
<ide>
<del>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/front-end-libraries/react-and-redux/use-provider-to-connect-redux-to-react/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<add>### Hint 1
<ide>
<del><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<add>You do not need to wrap the `Provider` in any `<div>` tags.
<ide>
<del><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<add>### Solution
<add>
<add>```jsx
<add>// Redux Code:
<add>const ADD = 'ADD';
<add>
<add>const addMessage = (message) => {
<add> return {
<add> type: ADD,
<add> message
<add> }
<add>};
<add>
<add>const messageReducer = (state = [], action) => {
<add> switch (action.type) {
<add> case ADD:
<add> return [
<add> ...state,
<add> action.message
<add> ];
<add> default:
<add> return state;
<add> }
<add>};
<add>
<add>
<add>
<add>const store = Redux.createStore(messageReducer);
<add>
<add>// React Code:
<add>
<add>class DisplayMessages extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> this.state = {
<add> input: '',
<add> messages: []
<add> }
<add> this.handleChange = this.handleChange.bind(this);
<add> this.submitMessage = this.submitMessage.bind(this);
<add> }
<add> handleChange(event) {
<add> this.setState({
<add> input: event.target.value
<add> });
<add> }
<add> submitMessage() {
<add> const currentMessage = this.state.input;
<add> this.setState({
<add> input: '',
<add> messages: this.state.messages.concat(currentMessage)
<add> });
<add> }
<add> render() {
<add> return (
<add> <div>
<add> <h2>Type in a new Message:</h2>
<add> <input
<add> value={this.state.input}
<add> onChange={this.handleChange}/><br/>
<add> <button onClick={this.submitMessage}>Submit</button>
<add> <ul>
<add> {this.state.messages.map( (message, idx) => {
<add> return (
<add> <li key={idx}>{message}</li>
<add> )
<add> })
<add> }
<add> </ul>
<add> </div>
<add> );
<add> }
<add>};
<add>
<add>const Provider = ReactRedux.Provider;
<add>
<add>class AppWrapper extends React.Component {
<add> // Below is the code required to pass the test
<add> render() {
<add> return (
<add> <Provider store={store}>
<add> <DisplayMessages />
<add> </Provider>
<add> );
<add> }
<add> // Above is the code required to pass the test
<add>};
<add>``` | 1 |
Javascript | Javascript | hoist reflection from verification | 69b4611049e3211b7a64ffcf49dcb87128163218 | <ide><path>Libraries/Utilities/__tests__/verifyComponentAttributeEquivalence-test.js
<ide>
<ide> 'use strict';
<ide>
<del>const getNativeComponentAttributes = require('../../ReactNative/getNativeComponentAttributes');
<add>jest.dontMock('../verifyComponentAttributeEquivalence');
<add>
<ide> const verifyComponentAttributeEquivalence = require('../verifyComponentAttributeEquivalence')
<ide> .default;
<ide>
<del>jest.dontMock('../verifyComponentAttributeEquivalence');
<del>jest.mock('../../ReactNative/getNativeComponentAttributes', () => () => ({
<add>const TestComponentNativeViewConfig = {
<add> uiViewClassName: 'TestComponent',
<ide> NativeProps: {
<ide> value: 'BOOL',
<ide> },
<ide> jest.mock('../../ReactNative/getNativeComponentAttributes', () => () => ({
<ide> },
<ide> transform: 'CATransform3D',
<ide> },
<del>}));
<del>
<del>beforeEach(() => {
<del> global.__DEV__ = true;
<del> console.error = jest.fn();
<del> jest.resetModules();
<del>});
<add>};
<ide>
<ide> describe('verifyComponentAttributeEquivalence', () => {
<del> test('should not verify in prod', () => {
<del> global.__DEV__ = false;
<del> verifyComponentAttributeEquivalence('TestComponent', {});
<add> beforeEach(() => {
<add> global.__DEV__ = true;
<add> console.error = jest.fn();
<add> jest.resetModules();
<ide> });
<ide>
<del> test('should not error with native config that is a subset of the given config', () => {
<del> const configWithAdditionalProperties = getNativeComponentAttributes(
<del> 'TestComponent',
<del> );
<add> it('should not verify in prod', () => {
<add> global.__DEV__ = false;
<add> verifyComponentAttributeEquivalence(TestComponentNativeViewConfig, {});
<add> });
<ide>
<del> configWithAdditionalProperties.bubblingEventTypes.topFocus = {
<del> phasedRegistrationNames: {
<del> bubbled: 'onFocus',
<del> captured: 'onFocusCapture',
<add> it('should not error with native config that is a subset of the given config', () => {
<add> const configWithAdditionalProperties = {
<add> ...TestComponentNativeViewConfig,
<add> bubblingEventTypes: {
<add> ...TestComponentNativeViewConfig.bubblingEventTypes,
<add> topFocus: {
<add> phasedRegistrationNames: {
<add> bubbled: 'onFocus',
<add> captured: 'onFocusCapture',
<add> },
<add> },
<add> },
<add> directEventTypes: {
<add> ...TestComponentNativeViewConfig.directEventTypes,
<add> topSlidingComplete: {
<add> registrationName: 'onSlidingComplete',
<add> },
<add> },
<add> validAttributes: {
<add> ...TestComponentNativeViewConfig.validAttributes,
<add> active: true,
<ide> },
<ide> };
<del>
<del> configWithAdditionalProperties.directEventTypes.topSlidingComplete = {
<del> registrationName: 'onSlidingComplete',
<del> };
<del>
<del> configWithAdditionalProperties.validAttributes.active = true;
<del>
<del> verifyComponentAttributeEquivalence(
<del> 'TestComponent',
<del> configWithAdditionalProperties,
<del> );
<ide> verifyComponentAttributeEquivalence(
<del> 'TestComponent',
<add> TestComponentNativeViewConfig,
<ide> configWithAdditionalProperties,
<ide> );
<ide>
<ide> expect(console.error).not.toBeCalled();
<ide> });
<ide>
<del> test('should error if given config is missing native config properties', () => {
<del> verifyComponentAttributeEquivalence('TestComponent', {});
<add> it('should error if given config is missing native config properties', () => {
<add> verifyComponentAttributeEquivalence(TestComponentNativeViewConfig, {});
<ide>
<ide> expect(console.error).toBeCalledTimes(3);
<ide> expect(console.error).toBeCalledWith(
<del> 'TestComponent generated view config for directEventTypes does not match native, missing: topAccessibilityAction',
<add> "'TestComponent' has a view config that does not match native. 'validAttributes' is missing: borderColor, style",
<ide> );
<ide> expect(console.error).toBeCalledWith(
<del> 'TestComponent generated view config for bubblingEventTypes does not match native, missing: topChange',
<add> "'TestComponent' has a view config that does not match native. 'bubblingEventTypes' is missing: topChange",
<ide> );
<ide> expect(console.error).toBeCalledWith(
<del> 'TestComponent generated view config for validAttributes does not match native, missing: borderColor style',
<add> "'TestComponent' has a view config that does not match native. 'directEventTypes' is missing: topAccessibilityAction",
<ide> );
<ide> });
<ide> });
<ide><path>Libraries/Utilities/registerGeneratedViewConfig.js
<ide>
<ide> 'use strict';
<ide>
<del>const ReactNativeViewConfigRegistry = require('../Renderer/shims/ReactNativeViewConfigRegistry');
<del>const ReactNativeViewViewConfig = require('../Components/View/ReactNativeViewViewConfig');
<add>import ReactNativeViewConfigRegistry from '../Renderer/shims/ReactNativeViewConfigRegistry';
<add>import ReactNativeViewViewConfig from '../Components/View/ReactNativeViewViewConfig';
<add>import getNativeComponentAttributes from '../ReactNative/getNativeComponentAttributes';
<ide> import verifyComponentAttributeEquivalence from './verifyComponentAttributeEquivalence';
<ide>
<ide> export type GeneratedViewConfig = {
<ide> function registerGeneratedViewConfig(
<ide> componentName: string,
<ide> viewConfig: GeneratedViewConfig,
<ide> ) {
<del> const mergedViewConfig = {
<add> const staticViewConfig = {
<ide> uiViewClassName: componentName,
<ide> Commands: {},
<ide> /* $FlowFixMe(>=0.122.0 site=react_native_fb) This comment suppresses an
<ide> function registerGeneratedViewConfig(
<ide>
<ide> ReactNativeViewConfigRegistry.register(componentName, () => {
<ide> if (!global.RN$Bridgeless) {
<del> verifyComponentAttributeEquivalence(componentName, mergedViewConfig);
<add> const nativeViewConfig = getNativeComponentAttributes(componentName);
<add>
<add> verifyComponentAttributeEquivalence(nativeViewConfig, staticViewConfig);
<ide> }
<ide>
<del> return mergedViewConfig;
<add> return staticViewConfig;
<ide> });
<ide> }
<ide>
<ide><path>Libraries/Utilities/verifyComponentAttributeEquivalence.js
<ide>
<ide> 'use strict';
<ide>
<del>const getNativeComponentAttributes = require('../ReactNative/getNativeComponentAttributes');
<del>
<ide> import ReactNativeViewViewConfig from '../Components/View/ReactNativeViewViewConfig';
<ide> import type {ReactNativeBaseComponentViewConfig} from '../Renderer/shims/ReactNativeTypes';
<ide>
<ide> const IGNORED_KEYS = ['transform', 'hitSlop'];
<ide> * years from now...
<ide> */
<ide> export default function verifyComponentAttributeEquivalence(
<del> componentName: string,
<del> config: ReactNativeBaseComponentViewConfig<>,
<add> nativeViewConfig: ReactNativeBaseComponentViewConfig<>,
<add> staticViewConfig: ReactNativeBaseComponentViewConfig<>,
<ide> ) {
<del> const nativeAttributes = getNativeComponentAttributes(componentName);
<del>
<del> ['validAttributes', 'bubblingEventTypes', 'directEventTypes'].forEach(
<del> prop => {
<del> const diffKeys = Object.keys(
<del> lefthandObjectDiff(nativeAttributes[prop], config[prop]),
<add> for (const prop of [
<add> 'validAttributes',
<add> 'bubblingEventTypes',
<add> 'directEventTypes',
<add> ]) {
<add> const diff = Object.keys(
<add> lefthandObjectDiff(nativeViewConfig[prop], staticViewConfig[prop]),
<add> );
<add>
<add> if (diff.length > 0) {
<add> const name =
<add> staticViewConfig.uiViewClassName ?? nativeViewConfig.uiViewClassName;
<add> console.error(
<add> `'${name}' has a view config that does not match native. ` +
<add> `'${prop}' is missing: ${diff.join(', ')}`,
<ide> );
<del>
<del> if (diffKeys.length) {
<del> console.error(
<del> `${componentName} generated view config for ${prop} does not match native, missing: ${diffKeys.join(
<del> ' ',
<del> )}`,
<del> );
<del> }
<del> },
<del> );
<add> }
<add> }
<ide> }
<ide>
<ide> export function lefthandObjectDiff(leftObj: Object, rightObj: Object): Object { | 3 |
Text | Text | add gdams to collaborators | 91e897ac9281de1a36139b6514609753f1154ab2 | <ide><path>README.md
<ide> For more information about the governance of the Node.js project, see
<ide> **Jeremiah Senkpiel** <[email protected]>
<ide> * [gabrielschulhof](https://github.com/gabrielschulhof) -
<ide> **Gabriel Schulhof** <[email protected]>
<add>* [gdams](https://github.com/gdams) -
<add>**George Adams** <[email protected]> (he/him)
<ide> * [geek](https://github.com/geek) -
<ide> **Wyatt Preul** <[email protected]>
<ide> * [gibfahn](https://github.com/gibfahn) - | 1 |
Javascript | Javascript | fix crypto-stream after openssl update | a76811c811f8e1602181f1c4368370c192adff0c | <ide><path>test/parallel/test-crypto-stream.js
<ide> var key = new Buffer('48fb56eb10ffeb13fc0ef551bbca3b1b', 'hex'),
<ide>
<ide> cipher.pipe(decipher)
<ide> .on('error', common.mustCall(function end(err) {
<del> assert(/Unsupported/.test(err));
<add> assert(/bad decrypt/.test(err));
<ide> }));
<ide>
<ide> cipher.end('Papaya!'); // Should not cause an unhandled exception. | 1 |
PHP | PHP | remove logexception and cacheexception | 669ab207227b2e2dfa3fbf983f8eaaca6736ad31 | <ide><path>lib/Cake/Cache/Cache.php
<ide> public static function config($name = null, $settings = array()) {
<ide> *
<ide> * @param string $name Name of the config array that needs an engine instance built
<ide> * @return boolean
<del> * @throws CacheException
<add> * @throws Cake\Error\Exception
<ide> */
<ide> protected static function _buildEngine($name) {
<ide> $config = Configure::read('Cache.' . $name);
<ide> protected static function _buildEngine($name) {
<ide> return false;
<ide> }
<ide> if (!is_subclass_of($cacheClass, 'Cake\Cache\CacheEngine')) {
<del> throw new Error\CacheException(__d('cake_dev', 'Cache engines must use Cake\Cache\CacheEngine as a base class.'));
<add> throw new Error\Exception(__d('cake_dev', 'Cache engines must use Cake\Cache\CacheEngine as a base class.'));
<ide> }
<ide> $engine = new $cacheClass();
<ide> if ($engine->init($config)) {
<ide><path>lib/Cake/Error/CacheException.php
<del><?php
<del>/**
<del> * CacheException class
<del> *
<del> * PHP 5
<del> *
<del> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<del> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> *
<del> * Licensed under The MIT License
<del> * Redistributions of files must retain the above copyright notice.
<del> *
<del> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://book.cakephp.org/2.0/en/development/testing.html
<del> * @package Cake.Error
<del> * @since CakePHP(tm) v 3.0
<del> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<del> */
<del>namespace Cake\Error;
<del>
<del>/**
<del> * Exception class for Cache. This exception will be thrown from Cache when it
<del> * encounters an error.
<del> *
<del> * @package Cake.Error
<del> */
<del>class CacheException extends Exception {
<del>}
<ide><path>lib/Cake/Error/LogException.php
<del><?php
<del>/**
<del> * LogException class
<del> *
<del> * PHP 5
<del> *
<del> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<del> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> *
<del> * Licensed under The MIT License
<del> * Redistributions of files must retain the above copyright notice.
<del> *
<del> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://book.cakephp.org/2.0/en/development/testing.html
<del> * @package Cake.Error
<del> * @since CakePHP(tm) v 3.0
<del> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<del> */
<del>namespace Cake\Error;
<del>
<del>/**
<del> * Exception class for Log. This exception will be thrown from Log when it
<del> * encounters an error.
<del> *
<del> * @package Cake.Error
<del> */
<del>class LogException extends Exception {
<del>}
<ide><path>lib/Cake/Log/Log.php
<ide> public static function reset() {
<ide> * logger later.
<ide> * @param array $config Array of configuration information for the logger
<ide> * @return boolean success of configuration.
<del> * @throws Cake\Error\LogException
<add> * @throws Cake\Error\Exception
<ide> */
<ide> public static function config($key, $config) {
<ide> trigger_error(
<ide> public static function drop($streamName) {
<ide> *
<ide> * @param string $streamName to check
<ide> * @return bool
<del> * @throws Cake\Error\LogException
<add> * @throws Cake\Error\Exception
<ide> */
<ide> public static function enabled($streamName) {
<ide> static::_init();
<ide> if (!isset(static::$_Collection->{$streamName})) {
<del> throw new Error\LogException(__d('cake_dev', 'Stream %s not found', $streamName));
<add> throw new Error\Exception(__d('cake_dev', 'Stream %s not found', $streamName));
<ide> }
<ide> return static::$_Collection->enabled($streamName);
<ide> }
<ide> public static function enabled($streamName) {
<ide> *
<ide> * @param string $streamName to enable
<ide> * @return void
<del> * @throws Cake\Error\LogException
<add> * @throws Cake\Error\Exception
<ide> */
<ide> public static function enable($streamName) {
<ide> static::_init();
<ide> if (!isset(static::$_Collection->{$streamName})) {
<del> throw new Error\LogException(__d('cake_dev', 'Stream %s not found', $streamName));
<add> throw new Error\Exception(__d('cake_dev', 'Stream %s not found', $streamName));
<ide> }
<ide> static::$_Collection->enable($streamName);
<ide> }
<ide> public static function enable($streamName) {
<ide> *
<ide> * @param string $streamName to disable
<ide> * @return void
<del> * @throws Cake\Error\LogException
<add> * @throws Cake\Error\Exception
<ide> */
<ide> public static function disable($streamName) {
<ide> static::_init();
<ide> if (!isset(static::$_Collection->{$streamName})) {
<del> throw new Error\LogException(__d('cake_dev', 'Stream %s not found', $streamName));
<add> throw new Error\Exception(__d('cake_dev', 'Stream %s not found', $streamName));
<ide> }
<ide> static::$_Collection->disable($streamName);
<ide> }
<ide><path>lib/Cake/Log/LogEngineCollection.php
<ide> class LogEngineCollection extends ObjectCollection {
<ide> * @param LogInterface|array $options Setting for the Log Engine, or the log engine
<ide> * If a log engine is used, the adapter will be enabled.
<ide> * @return BaseLog BaseLog engine instance
<del> * @throws Cake\Error\LogException when logger class does not implement a write method
<add> * @throws Cake\Error\Exception when logger class does not implement a write method
<ide> */
<ide> public function load($name, $options = array()) {
<ide> $logger = false;
<ide> public function load($name, $options = array()) {
<ide> $logger = $this->_getLogger($options);
<ide> }
<ide> if (!$logger instanceof LogInterface) {
<del> throw new Error\LogException(sprintf(
<add> throw new Error\Exception(sprintf(
<ide> __d('cake_dev', 'logger class %s is not an instance of Cake\Log\LogInterface.'), $name
<ide> ));
<ide> }
<ide> protected static function _getLogger($options) {
<ide> unset($options['engine']);
<ide> $class = App::classname($name, 'Log/Engine');
<ide> if (!$class) {
<del> throw new Error\LogException(__d('cake_dev', 'Could not load class %s', $name));
<add> throw new Error\Exception(__d('cake_dev', 'Could not load class %s', $name));
<ide> }
<ide> $logger = new $class($options);
<ide> return $logger;
<ide><path>lib/Cake/Test/TestCase/Cache/CacheTest.php
<ide> public function testDecrementNonExistingConfig() {
<ide> /**
<ide> * test that trying to configure classes that don't extend CacheEngine fail.
<ide> *
<del> * @expectedException Cake\Error\CacheException
<add> * @expectedException Cake\Error\Exception
<ide> * @return void
<ide> */
<ide> public function testAttemptingToConfigureANonCacheEngineClass() {
<ide><path>lib/Cake/Test/TestCase/Log/LogTest.php
<ide> public function testImportingLoggers() {
<ide> /**
<ide> * test all the errors from failed logger imports
<ide> *
<del> * @expectedException Cake\Error\LogException
<add> * @expectedException Cake\Error\Exception
<ide> * @return void
<ide> */
<ide> public function testImportingLoggerFailure() {
<ide> public function testValidKeyName() {
<ide> /**
<ide> * test that loggers have to implement the correct interface.
<ide> *
<del> * @expectedException Cake\Error\LogException
<add> * @expectedException Cake\Error\Exception
<ide> * @return void
<ide> */
<ide> public function testNotImplementingInterface() {
<ide> public function testDrop() {
<ide> * Test that engine() throws an exception when adding an
<ide> * adapter with the wrong type.
<ide> *
<del> * @expectedException Cake\Error\LogException
<add> * @expectedException Cake\Error\Exception
<ide> * @return void
<ide> */
<ide> public function testEngineInjectErrorOnWrongType() {
<ide> public function testSelectiveLoggingByLevel() {
<ide> /**
<ide> * test enable
<ide> *
<del> * @expectedException Cake\Error\LogException
<add> * @expectedException Cake\Error\Exception
<ide> */
<ide> public function testStreamEnable() {
<ide> Configure::write('Log.spam', array(
<ide> public function testStreamEnable() {
<ide> /**
<ide> * test disable
<ide> *
<del> * @expectedException Cake\Error\LogException
<add> * @expectedException Cake\Error\Exception
<ide> */
<ide> public function testStreamDisable() {
<ide> Configure::write('Log.spam', array(
<ide> public function testStreamDisable() {
<ide> /**
<ide> * test enabled() invalid stream
<ide> *
<del> * @expectedException Cake\Error\LogException
<add> * @expectedException Cake\Error\Exception
<ide> */
<ide> public function testStreamEnabledInvalid() {
<ide> Log::enabled('bogus_stream');
<ide> public function testStreamEnabledInvalid() {
<ide> /**
<ide> * test disable invalid stream
<ide> *
<del> * @expectedException Cake\Error\LogException
<add> * @expectedException Cake\Error\Exception
<ide> */
<ide> public function testStreamDisableInvalid() {
<ide> Log::disable('bogus_stream'); | 7 |
Javascript | Javascript | accept eprotonosupport ipv6 error | 62512bb29cd000dd5ce848258c10f3211f153bd5 | <ide><path>test/parallel/test-dgram-error-message-address.js
<ide> var family_ipv6 = 'IPv6';
<ide> socket_ipv6.on('listening', assert.fail);
<ide>
<ide> socket_ipv6.on('error', common.mustCall(function(e) {
<del> // EAFNOSUPPORT means IPv6 is disabled on this system.
<del> var code = (e.code === 'EADDRNOTAVAIL' ? e.code : 'EAFNOSUPPORT');
<del> assert.equal(e.message, 'bind ' + code + ' 111::1:' + common.PORT);
<add> // EAFNOSUPPORT or EPROTONOSUPPORT means IPv6 is disabled on this system.
<add> var allowed = ['EADDRNOTAVAIL', 'EAFNOSUPPORT', 'EPROTONOSUPPORT'];
<add> assert.notEqual(allowed.indexOf(e.code), -1);
<add> assert.equal(e.message, 'bind ' + e.code + ' 111::1:' + common.PORT);
<ide> assert.equal(e.address, '111::1');
<ide> assert.equal(e.port, common.PORT);
<del> assert.equal(e.code, code);
<ide> socket_ipv6.close();
<ide> }));
<ide> | 1 |
Ruby | Ruby | move methods to a more logical place | 129e25032beec324f3441608c14b86f0e75227aa | <ide><path>Library/Homebrew/formula.rb
<ide> def downloader
<ide> active_spec.downloader
<ide> end
<ide>
<add> def cached_download
<add> downloader.cached_location
<add> end
<add>
<add> def clear_cache
<add> downloader.clear_cache
<add> end
<add>
<ide> # if the dir is there, but it's empty we consider it not installed
<ide> def installed?
<ide> (dir = installed_prefix).directory? && dir.children.length > 0
<ide> def opt_prefix
<ide> Pathname.new("#{HOMEBREW_PREFIX}/opt/#{name}")
<ide> end
<ide>
<del> def cached_download
<del> downloader.cached_location
<del> end
<del>
<del> def clear_cache
<del> downloader.clear_cache
<del> end
<del>
<ide> # Can be overridden to selectively disable bottles from formulae.
<ide> # Defaults to true so overridden version does not have to check if bottles
<ide> # are supported. | 1 |
Text | Text | replace xcode to xcode | 2953a1a02ee9aef15fa143e90eb727b03da2d010 | <ide><path>docs/GettingStarted.md
<ide> npm install -g react-native-cli
<ide>
<ide> <block class="mac ios" />
<ide>
<del>#### XCode
<add>#### Xcode
<ide>
<ide> [Xcode](https://developer.apple.com/xcode/downloads/) 7.0 or higher. Open the App Store or go to https://developer.apple.com/xcode/downloads/. This will also install `git` as well.
<ide>
<ide> Enable [Gradle Daemon](https://docs.gradle.org/2.9/userguide/gradle_daemon.html)
<ide>
<ide> #### Git
<ide>
<del>Git version control. If you have installed [XCode](https://developer.apple.com/xcode/), Git is
<add>Git version control. If you have installed [Xcode](https://developer.apple.com/xcode/), Git is
<ide> already installed, otherwise run the following:
<ide>
<ide> ``` | 1 |
Javascript | Javascript | fix incorrect markup in tests | 06d154f91c67250864c590ce20c5ad5cf03a3191 | <ide><path>test/ng/compileSpec.js
<ide> describe('$compile', function() {
<ide> // All interpolations are disallowed.
<ide> $rootScope.onClickJs = '';
<ide> expect(function() {
<del> $compile('<button onclick="{{onClickJs}}"></script>');
<add> $compile('<button onclick="{{onClickJs}}"></button>');
<ide> }).toThrowMinErr(
<ide> '$compile', 'nodomevents', 'Interpolations for HTML DOM event attributes are disallowed');
<ide> expect(function() {
<del> $compile('<button ONCLICK="{{onClickJs}}"></script>');
<add> $compile('<button ONCLICK="{{onClickJs}}"></button>');
<ide> }).toThrowMinErr(
<ide> '$compile', 'nodomevents', 'Interpolations for HTML DOM event attributes are disallowed');
<ide> expect(function() {
<del> $compile('<button ng-attr-onclick="{{onClickJs}}"></script>');
<add> $compile('<button ng-attr-onclick="{{onClickJs}}"></button>');
<ide> }).toThrowMinErr(
<ide> '$compile', 'nodomevents', 'Interpolations for HTML DOM event attributes are disallowed');
<ide> expect(function() {
<del> $compile('<button ng-attr-ONCLICK="{{onClickJs}}"></script>');
<add> $compile('<button ng-attr-ONCLICK="{{onClickJs}}"></button>');
<ide> }).toThrowMinErr(
<ide> '$compile', 'nodomevents', 'Interpolations for HTML DOM event attributes are disallowed');
<ide> }));
<ide>
<ide> it('should pass through arbitrary values on onXYZ event attributes that contain a hyphen', inject(function($compile, $rootScope) {
<del> element = $compile('<button on-click="{{onClickJs}}"></script>')($rootScope);
<add> element = $compile('<button on-click="{{onClickJs}}"></button>')($rootScope);
<ide> $rootScope.onClickJs = 'javascript:doSomething()';
<ide> $rootScope.$apply();
<ide> expect(element.attr('on-click')).toEqual('javascript:doSomething()');
<ide> }));
<ide>
<ide> it('should pass through arbitrary values on "on" and "data-on" attributes', inject(function($compile, $rootScope) {
<del> element = $compile('<button data-on="{{dataOnVar}}"></script>')($rootScope);
<add> element = $compile('<button data-on="{{dataOnVar}}"></button>')($rootScope);
<ide> $rootScope.dataOnVar = 'data-on text';
<ide> $rootScope.$apply();
<ide> expect(element.attr('data-on')).toEqual('data-on text');
<ide>
<del> element = $compile('<button on="{{onVar}}"></script>')($rootScope);
<add> element = $compile('<button on="{{onVar}}"></button>')($rootScope);
<ide> $rootScope.onVar = 'on text';
<ide> $rootScope.$apply();
<ide> expect(element.attr('on')).toEqual('on text');
<ide><path>test/ng/ngPropSpec.js
<ide> describe('ngProp*', function() {
<ide> it('should disallow property binding to onclick', inject(function($compile, $rootScope) {
<ide> // All event prop bindings are disallowed.
<ide> expect(function() {
<del> $compile('<button ng-prop-onclick="onClickJs"></script>');
<add> $compile('<button ng-prop-onclick="onClickJs"></button>');
<ide> }).toThrowMinErr(
<ide> '$compile', 'nodomevents', 'Property bindings for HTML DOM event properties are disallowed');
<ide> expect(function() {
<del> $compile('<button ng-prop-ONCLICK="onClickJs"></script>');
<add> $compile('<button ng-prop-ONCLICK="onClickJs"></button>');
<ide> }).toThrowMinErr(
<ide> '$compile', 'nodomevents', 'Property bindings for HTML DOM event properties are disallowed');
<ide> })); | 2 |
Python | Python | improve pep8 (s1721) | f069d8107118f407fa2cffa6fc096dc3d086f339 | <ide><path>glances/core/glances_client_browser.py
<ide> def serve_forever(self):
<ide> # Do not retreive stats for statics server
<ide> # Why ? Because for each offline servers, the timeout will be reached
<ide> # So ? The curse interface freezes
<del> if (v['type'] == 'STATIC' and v['status'] in ['UNKNOWN', 'SNMP', 'OFFLINE']):
<add> if v['type'] == 'STATIC' and v['status'] in ['UNKNOWN', 'SNMP', 'OFFLINE']:
<ide> continue
<ide>
<ide> # Select the connection mode (with or without password)
<ide><path>glances/core/glances_logs.py
<ide> def clean(self, critical=False):
<ide> """
<ide> # Create a new clean list
<ide> clean_logs_list = []
<del> while (self.len() > 0):
<add> while self.len() > 0:
<ide> item = self.logs_list.pop()
<ide> if item[1] < 0 or (not critical and item[2].startswith("CRITICAL")):
<ide> clean_logs_list.insert(0, item)
<ide><path>glances/core/glances_processes.py
<ide> def is_kernel_thread(proc):
<ide> """ Return True if proc is a kernel thread, False instead. """
<ide> try:
<ide> return os.getpgid(proc.pid) == 0
<del> except OSError: # Python >= 3.3 raises ProcessLookupError, which inherits OSError
<add> # Python >= 3.3 raises ProcessLookupError, which inherits OSError
<add> except OSError:
<ide> # return False is process is dead
<ide> return False
<ide>
<ide> def __str__(self):
<ide> if current_node.is_root:
<ide> lines.append(indent_str)
<ide> else:
<del> lines.append("%s[%s]" % (indent_str, current_node.process.name()))
<add> lines.append("%s[%s]" %
<add> (indent_str, current_node.process.name()))
<ide> indent_str = " " * (len(lines[-1]) - 1)
<ide> children_nodes_to_print = collections.deque()
<ide> for child in current_node.children:
<ide> if child is current_node.children[-1]:
<ide> tree_char = "└─"
<ide> else:
<ide> tree_char = "├─"
<del> children_nodes_to_print.appendleft((indent_str + tree_char, child))
<add> children_nodes_to_print.appendleft(
<add> (indent_str + tree_char, child))
<ide> if children_nodes_to_print:
<ide> nodes_to_print.append(children_nodes_to_print)
<ide> return "\n".join(lines)
<ide>
<ide> def set_sorting(self, key, reverse):
<ide> """ Set sorting key or func for user with __iter__ (affects the whole tree from this node). """
<del> if (self.sort_key != key) or (self.reverse_sorting != reverse):
<add> if self.sort_key != key or self.reverse_sorting != reverse:
<ide> nodes_to_flag_unsorted = collections.deque([self])
<ide> while nodes_to_flag_unsorted:
<ide> current_node = nodes_to_flag_unsorted.pop()
<ide> def __iter__(self):
<ide> if not self.children_sorted:
<ide> # optimization to avoid sorting twice (once when limiting the maximum processes to grab stats for,
<ide> # and once before displaying)
<del> self.children.sort(key=self.__class__.get_weight, reverse=self.reverse_sorting)
<add> self.children.sort(
<add> key=self.__class__.get_weight, reverse=self.reverse_sorting)
<ide> self.children_sorted = True
<ide> for child in self.children:
<ide> for n in iter(child):
<ide> def iter_children(self, exclude_incomplete_stats=True):
<ide> if not self.children_sorted:
<ide> # optimization to avoid sorting twice (once when limiting the maximum processes to grab stats for,
<ide> # and once before displaying)
<del> self.children.sort(key=self.__class__.get_weight, reverse=self.reverse_sorting)
<add> self.children.sort(
<add> key=self.__class__.get_weight, reverse=self.reverse_sorting)
<ide> self.children_sorted = True
<ide> for child in self.children:
<del> if (not exclude_incomplete_stats) or ("time_since_update" in child.stats):
<add> if not exclude_incomplete_stats or "time_since_update" in child.stats:
<ide> yield child
<ide>
<ide> def find_process(self, process):
<ide> """ Search in tree for the ProcessTreeNode owning process, return it or None if not found. """
<ide> nodes_to_search = collections.deque([self])
<ide> while nodes_to_search:
<ide> current_node = nodes_to_search.pop()
<del> if (not current_node.is_root) and (current_node.process.pid == process.pid):
<add> if not current_node.is_root and current_node.process.pid == process.pid:
<ide> return current_node
<ide> nodes_to_search.extend(current_node.children)
<ide>
<ide> def build_tree(process_dict, sort_key, hide_kernel_threads):
<ide> # parent is not in tree, add this node later
<ide> nodes_to_add_last.append(new_node)
<ide>
<del> # next pass(es): add nodes to their parents if it could not be done in previous pass
<add> # next pass(es): add nodes to their parents if it could not be done in
<add> # previous pass
<ide> while nodes_to_add_last:
<del> node_to_add = nodes_to_add_last.popleft() # pop from left and append to right to avoid infinite loop
<add> # pop from left and append to right to avoid infinite loop
<add> node_to_add = nodes_to_add_last.popleft()
<ide> try:
<ide> parent_process = node_to_add.process.parent()
<ide> except psutil.NoSuchProcess:
<del> # parent is dead, consider no parent, add this node at the top level
<add> # parent is dead, consider no parent, add this node at the top
<add> # level
<ide> tree_root.children.append(node_to_add)
<ide> else:
<ide> if parent_process is None:
<ide> def set_process_filter(self, value):
<ide> if value is not None:
<ide> try:
<ide> self.process_filter_re = re.compile(value)
<del> logger.debug("Process filter regex compilation OK: {0}".format(self.get_process_filter()))
<add> logger.debug(
<add> "Process filter regex compilation OK: {0}".format(self.get_process_filter()))
<ide> except Exception:
<del> logger.error("Cannot compile process filter regex: {0}".format(value))
<add> logger.error(
<add> "Cannot compile process filter regex: {0}".format(value))
<ide> self.process_filter_re = None
<ide> else:
<ide> self.process_filter_re = None
<ide> def update(self):
<ide> processdict = {}
<ide> for proc in psutil.process_iter():
<ide> # Ignore kernel threads if needed
<del> if (self.no_kernel_threads and (not is_windows)
<del> and is_kernel_thread(proc)):
<add> if self.no_kernel_threads and not is_windows and is_kernel_thread(proc):
<ide> continue
<ide>
<ide> # If self.get_max_processes() is None: Only retreive mandatory stats
<ide> def update(self):
<ide> # ignore the 'idle' process on Windows and *BSD
<ide> # ignore the 'kernel_task' process on OS X
<ide> # waiting for upstream patch from psutil
<del> if (is_bsd and processdict[proc]['name'] == 'idle' or
<del> is_windows and processdict[proc]['name'] == 'System Idle Process' or
<del> is_mac and processdict[proc]['name'] == 'kernel_task'):
<del> continue
<add> if is_bsd and processdict[proc]['name'] == 'idle' or is_windows and processdict[proc]['name'] == 'System Idle Process' or is_mac and processdict[proc]['name'] == 'kernel_task':
<add> continue
<ide> # Update processcount (global statistics)
<ide> try:
<ide> self.processcount[str(proc.status())] += 1
<ide> def update(self):
<ide>
<ide> for i, node in enumerate(self.process_tree):
<ide> # Only retreive stats for visible processes (get_max_processes)
<del> if (self.get_max_processes() is not None) and (i >= self.get_max_processes()):
<add> if self.get_max_processes() is not None and i >= self.get_max_processes():
<ide> break
<ide>
<ide> # add standard stats
<ide> def update(self):
<ide> processiter = sorted(
<ide> processdict.items(), key=lambda x: x[1][self.getsortkey()], reverse=True)
<ide> except (KeyError, TypeError) as e:
<del> logger.error("Cannot sort process list by %s (%s)" % (self.getsortkey(), e))
<add> logger.error(
<add> "Cannot sort process list by %s (%s)" % (self.getsortkey(), e))
<ide> logger.error("%s" % str(processdict.items()[0]))
<ide> # Fallback to all process (issue #423)
<ide> processloop = processdict.items()
<ide><path>glances/core/glances_webserver.py
<ide> def __init__(self, config=None, args=None):
<ide> # Init stats
<ide> self.stats = GlancesStats(config)
<ide>
<del> if (not is_windows) and args.no_kernel_threads:
<add> if not is_windows and args.no_kernel_threads:
<ide> # Ignore kernel threads in process list
<ide> glances_processes.disable_kernel_threads()
<ide>
<ide><path>glances/plugins/glances_processlist.py
<ide> def get_process_tree_curses_data(self, node, args, first_level=True, max_node_co
<ide> """ Get curses data to display for a process tree. """
<ide> ret = []
<ide> node_count = 0
<del> if (not node.is_root) and ((max_node_count is None) or (max_node_count > 0)):
<add> if not node.is_root and ((max_node_count is None) or (max_node_count > 0)):
<ide> node_data = self.get_process_curses_data(node.stats, False, args)
<ide> node_count += 1
<ide> ret.extend(node_data)
<ide> for child in node.iter_children():
<ide> # stop if we have enough nodes to display
<del> if (max_node_count is not None) and (node_count >= max_node_count):
<add> if max_node_count is not None and node_count >= max_node_count:
<ide> break
<ide>
<ide> if max_node_count is None:
<ide> def add_tree_decoration(self, child_data, is_last_child, first_level):
<ide> # find process command indices in messages
<ide> pos = []
<ide> for i, m in enumerate(child_data):
<del> if (m["msg"] == "\n") and (m is not child_data[-1]):
<add> if m["msg"] == "\n" and m is not child_data[-1]:
<ide> # new line pos + 12
<ide> # TODO find a way to get rid of hardcoded 12 value
<ide> pos.append(i + 12) | 5 |
Ruby | Ruby | remove broken --verbose functionality | 4a89cfb1dc75a1fae98809868b26d98eda1f8c6f | <ide><path>Library/Homebrew/cmd/man.rb
<ide> def man
<ide> puts "Writing HTML fragments to #{DOC_PATH}"
<ide> puts "Writing manpages to #{TARGET_PATH}"
<ide>
<del> target_file = nil
<ide> Dir["#{SOURCE_PATH}/*.md"].each do |source_file|
<ide> target_html = DOC_PATH/"#{File.basename(source_file, ".md")}.html"
<ide> safe_system "ronn --fragment --pipe --organization='Homebrew' --manual='brew' #{source_file} > #{target_html}"
<ide> target_man = TARGET_PATH/File.basename(source_file, ".md")
<ide> safe_system "ronn --roff --pipe --organization='Homebrew' --manual='brew' #{source_file} > #{target_man}"
<ide> end
<del>
<del> system "man", target_file if ARGV.flag? "--verbose"
<ide> end
<ide> end
<ide> end | 1 |
PHP | PHP | remove redundant fixture from strategy names | dca117a59f53b49844c759c689ebcd3f9eefb71b | <add><path>src/TestSuite/Fixture/TransactionStrategy.php
<del><path>src/TestSuite/Fixture/TransactionFixtureStrategy.php
<ide> *
<ide> * Any test that calls Connection::rollback(true) will break this strategy.
<ide> */
<del>class TransactionFixtureStrategy implements FixtureStrategyInterface
<add>class TransactionStrategy implements FixtureStrategyInterface
<ide> {
<ide> /**
<ide> * @var \Cake\TestSuite\Fixture\FixtureHelper
<ide> public function setupTest(array $fixtureNames): void
<ide> throw new RuntimeException(
<ide> "Could not enable save points for the `{$connection->configName()}` connection. " .
<ide> 'Your database needs to support savepoints in order to use ' .
<del> 'TransactionFixtureStrategy.'
<add> 'TransactionStrategy.'
<ide> );
<ide> }
<ide>
<add><path>src/TestSuite/Fixture/TruncateStrategy.php
<del><path>src/TestSuite/Fixture/TruncateFixtureStrategy.php
<ide> /**
<ide> * Fixture strategy that truncates all fixture ables at the end of test.
<ide> */
<del>class TruncateFixtureStrategy implements FixtureStrategyInterface
<add>class TruncateStrategy implements FixtureStrategyInterface
<ide> {
<ide> /**
<ide> * @var \Cake\TestSuite\Fixture\FixtureHelper
<ide><path>src/TestSuite/TestCase.php
<ide> use Cake\TestSuite\Constraint\EventFired;
<ide> use Cake\TestSuite\Constraint\EventFiredWith;
<ide> use Cake\TestSuite\Fixture\FixtureStrategyInterface;
<del>use Cake\TestSuite\Fixture\TruncateFixtureStrategy;
<add>use Cake\TestSuite\Fixture\TruncateStrategy;
<ide> use Cake\Utility\Inflector;
<ide> use LogicException;
<ide> use PHPUnit\Framework\Constraint\DirectoryExists;
<ide> protected function teardownFixtures(): void
<ide> */
<ide> protected function getFixtureStrategy(): FixtureStrategyInterface
<ide> {
<del> return new TruncateFixtureStrategy();
<add> return new TruncateStrategy();
<ide> }
<ide>
<ide> /**
<add><path>tests/TestCase/TestSuite/Fixture/TransactionStrategyTest.php
<del><path>tests/TestCase/TestSuite/Fixture/TruncateFixtureStrategyTest.php
<ide> namespace Cake\Test\TestCase\TestSuite;
<ide>
<ide> use Cake\Datasource\ConnectionManager;
<del>use Cake\TestSuite\Fixture\TruncateFixtureStrategy;
<add>use Cake\TestSuite\Fixture\TransactionStrategy;
<ide> use Cake\TestSuite\TestCase;
<ide>
<del>class TruncateFixtureStrategyTest extends TestCase
<add>class TransactionStrategyTest extends TestCase
<ide> {
<ide> protected $fixtures = ['core.Articles'];
<ide>
<ide> public function testStrategy(): void
<ide> $this->assertEmpty($rows->fetchAll());
<ide> $rows->closeCursor();
<ide>
<del> $strategy = new TruncateFixtureStrategy();
<add> $strategy = new TransactionStrategy();
<ide> $strategy->setupTest(['core.Articles']);
<ide> $rows = $connection->newQuery()->select('*')->from('articles')->execute();
<ide> $this->assertNotEmpty($rows->fetchAll());
<add><path>tests/TestCase/TestSuite/Fixture/TruncateStrategyTest.php
<del><path>tests/TestCase/TestSuite/Fixture/TransactionFixtureStrategyTest.php
<ide> namespace Cake\Test\TestCase\TestSuite;
<ide>
<ide> use Cake\Datasource\ConnectionManager;
<del>use Cake\TestSuite\Fixture\TransactionFixtureStrategy;
<add>use Cake\TestSuite\Fixture\TruncateStrategy;
<ide> use Cake\TestSuite\TestCase;
<ide>
<del>class TransactionFixtureStrategyTest extends TestCase
<add>class TruncateStrategyTest extends TestCase
<ide> {
<ide> protected $fixtures = ['core.Articles'];
<ide>
<ide> public function testStrategy(): void
<ide> $this->assertEmpty($rows->fetchAll());
<ide> $rows->closeCursor();
<ide>
<del> $strategy = new TransactionFixtureStrategy();
<add> $strategy = new TruncateStrategy();
<ide> $strategy->setupTest(['core.Articles']);
<ide> $rows = $connection->newQuery()->select('*')->from('articles')->execute();
<ide> $this->assertNotEmpty($rows->fetchAll()); | 5 |
Python | Python | remove jython check | f0e9fea0234569724f6081b683851bf40ff3a07f | <ide><path>celery/apps/worker.py
<ide> def restart_worker_sig_handler(*args):
<ide>
<ide>
<ide> def install_cry_handler(sig='SIGUSR1'):
<del> # Jython/PyPy does not have sys._current_frames
<del> if is_jython or is_pypy: # pragma: no cover
<add> # PyPy does not have sys._current_frames
<add> if is_pypy: # pragma: no cover
<ide> return
<ide>
<ide> def cry_handler(*args): | 1 |
Go | Go | fix change detection when applying tar layers | 10cd902f900392a2f10a6f8763bba70607ea0d41 | <ide><path>archive/changes.go
<ide> import (
<ide> "path/filepath"
<ide> "strings"
<ide> "syscall"
<add> "time"
<ide> )
<ide>
<ide> type ChangeType int
<ide> func (change *Change) String() string {
<ide> return fmt.Sprintf("%s %s", kind, change.Path)
<ide> }
<ide>
<add>// Gnu tar and the go tar writer don't have sub-second mtime
<add>// precision, which is problematic when we apply changes via tar
<add>// files, we handle this by comparing for exact times, *or* same
<add>// second count and either a or b having exactly 0 nanoseconds
<add>func sameFsTime(a, b time.Time) bool {
<add> return a == b ||
<add> (a.Unix() == b.Unix() &&
<add> (a.Nanosecond() == 0 || b.Nanosecond() == 0))
<add>}
<add>
<add>func sameFsTimeSpec(a, b syscall.Timespec) bool {
<add> return a.Sec == b.Sec &&
<add> (a.Nsec == b.Nsec || a.Nsec == 0 || b.Nsec == 0)
<add>}
<add>
<ide> func Changes(layers []string, rw string) ([]Change, error) {
<ide> var changes []Change
<ide> err := filepath.Walk(rw, func(path string, f os.FileInfo, err error) error {
<ide> func Changes(layers []string, rw string) ([]Change, error) {
<ide> // However, if it's a directory, maybe it wasn't actually modified.
<ide> // If you modify /foo/bar/baz, then /foo will be part of the changed files only because it's the parent of bar
<ide> if stat.IsDir() && f.IsDir() {
<del> if f.Size() == stat.Size() && f.Mode() == stat.Mode() && f.ModTime() == stat.ModTime() {
<add> if f.Size() == stat.Size() && f.Mode() == stat.Mode() && sameFsTime(f.ModTime(), stat.ModTime()) {
<ide> // Both directories are the same, don't record the change
<ide> return nil
<ide> }
<ide> func (info *FileInfo) addChanges(oldInfo *FileInfo, changes *[]Change) {
<ide> oldStat.Rdev != newStat.Rdev ||
<ide> // Don't look at size for dirs, its not a good measure of change
<ide> (oldStat.Size != newStat.Size && oldStat.Mode&syscall.S_IFDIR != syscall.S_IFDIR) ||
<del> getLastModification(oldStat) != getLastModification(newStat) {
<add> !sameFsTimeSpec(getLastModification(oldStat), getLastModification(newStat)) {
<ide> change := Change{
<ide> Path: newChild.path(),
<ide> Kind: ChangeModify, | 1 |
Text | Text | add poojadurgad as a triager | 18ff3c8db37d780826ae7ee0bc85a0d5a665f28b | <ide><path>README.md
<ide> For information about the governance of the Node.js project, see
<ide> Collaborators follow the [Collaborator Guide](./doc/guides/collaborator-guide.md) in
<ide> maintaining the Node.js project.
<ide>
<add>### Triagers
<add>
<add>* [PoojaDurgad](https://github.com/PoojaDurgad) -
<add>**Pooja Durgad** <[email protected]>
<add>
<ide> ### Release Keys
<ide>
<ide> Primary GPG keys for Node.js Releasers (some Releasers sign with subkeys): | 1 |
Javascript | Javascript | use babel polyfill for async | 2e598f692d10fd72a14dbbb50103539950e68ebc | <ide><path>client/src/client/workers/test-evaluator.js
<ide> /* global chai, importScripts */
<del>importScripts('https://cdnjs.cloudflare.com/ajax/libs/chai/4.2.0/chai.min.js');
<add>importScripts(
<add> 'https://cdnjs.cloudflare.com/ajax/libs/chai/4.2.0/chai.min.js',
<add> 'https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/7.0.0/polyfill.min.js'
<add>);
<ide>
<ide> const oldLog = self.console.log.bind(self.console);
<ide> self.console.log = function proxyConsole(...args) {
<ide><path>client/src/templates/Challenges/rechallenge/builders.js
<ide> export const cssToHtml = cond([
<ide> // ) => Observable[{ build: String, sources: Dictionary }]
<ide> export function concatHtml(required, template, files) {
<ide> const createBody = template ? _template(template) : defaultTemplate;
<del> const sourceMap = Promise.all(files).then(
<del> files => files.reduce((sources, file) => {
<add> const sourceMap = Promise.all(files).then(files =>
<add> files.reduce((sources, file) => {
<ide> sources[file.name] = file.source || file.contents;
<ide> return sources;
<ide> }, {})
<ide> A required file can not have both a src and a link: src = ${src}, link = ${link}
<ide> .map(source => createBody({ source }))
<ide> );
<ide>
<add> /* eslint-disable max-len */
<add> const babelPolyfillCDN =
<add> 'https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/7.0.0/polyfill.min.js';
<add> const babelPolyfill = `<script src="${babelPolyfillCDN}" type="text/javascript"></script>`;
<add> /* eslint-enable max-len */
<ide> const frameRunner =
<ide> '<script src="/js/frame-runner.js" type="text/javascript"></script>';
<ide>
<ide> return from(
<del> Promise.all([head, body, frameRunner, sourceMap]).then(
<del> ([head, body, frameRunner, sourceMap]) => ({
<del> build: head + body + frameRunner,
<add> Promise.all([head, body, babelPolyfill, frameRunner, sourceMap]).then(
<add> ([head, body, babelPolyfill, frameRunner, sourceMap]) => ({
<add> build: head + body + babelPolyfill + frameRunner,
<ide> sources: sourceMap
<ide> })
<ide> )
<ide><path>client/src/templates/Challenges/utils/build.js
<ide> import { isPromise } from './polyvinyl';
<ide>
<ide> const jQueryCDN =
<ide> 'https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js';
<del>const jQuery = `<script src='${jQueryCDN}' typ='text/javascript'></script>`;
<add>const jQuery = `<script src='${jQueryCDN}' type='text/javascript'></script>`;
<ide> const frameRunner =
<ide> "<script src='/js/frame-runner.js' type='text/javascript'></script>";
<ide> | 3 |
Ruby | Ruby | add cask methods." | a6033529cfdcfc6458aaa83a0bc9c4c141c60f96 | <ide><path>Library/Homebrew/tap.rb
<ide> def initialize(user, repo)
<ide> def clear_cache
<ide> @remote = nil
<ide> @formula_dir = nil
<del> @cask_dir = nil
<ide> @formula_files = nil
<ide> @alias_dir = nil
<ide> @alias_files = nil
<ide> def formula_dir
<ide> @formula_dir ||= [path/"Formula", path/"HomebrewFormula", path].detect(&:directory?)
<ide> end
<ide>
<del> # path to the directory of all casks for caskroom/cask {Tap}.
<del> def cask_dir
<del> @cask_dir ||= [path/"Casks", path].detect(&:directory?)
<del> end
<del>
<ide> # an array of all {Formula} files of this {Tap}.
<ide> def formula_files
<ide> @formula_files ||= if formula_dir
<ide> def formula_files
<ide> def formula_file?(file)
<ide> file = Pathname.new(file) unless file.is_a? Pathname
<ide> file = file.expand_path(path)
<del> file.extname == ".rb" && (file.parent == formula_dir || file.parent == cask_dir)
<add> file.extname == ".rb" && file.parent == formula_dir
<ide> end
<ide>
<ide> # an array of all {Formula} names of this {Tap}.
<ide> def formula_dir
<ide> end
<ide> end
<ide>
<del> # @private
<del> def cask_dir
<del> @cask_dir ||= begin
<del> self.class.ensure_installed!
<del> super
<del> end
<del> end
<del>
<ide> # @private
<ide> def alias_dir
<ide> @alias_dir ||= begin | 1 |
PHP | PHP | break guard into two interfaces | 7b586da6619b043fa79b6711c08a1c17cdca5a76 | <ide><path>src/Illuminate/Contracts/Auth/Guard.php
<ide>
<ide> namespace Illuminate\Contracts\Auth;
<ide>
<del>interface Guard
<add>interface Guard extends StatelessGuard
<ide> {
<del> /**
<del> * Determine if the current user is authenticated.
<del> *
<del> * @return bool
<del> */
<del> public function check();
<del>
<del> /**
<del> * Determine if the current user is a guest.
<del> *
<del> * @return bool
<del> */
<del> public function guest();
<del>
<del> /**
<del> * Get the currently authenticated user.
<del> *
<del> * @return \Illuminate\Contracts\Auth\Authenticatable|null
<del> */
<del> public function user();
<del>
<del> /**
<del> * Get the ID for the currently authenticated user.
<del> *
<del> * @return int|null
<del> */
<del> public function id();
<del>
<del> /**
<del> * Log a user into the application without sessions or cookies.
<del> *
<del> * @param array $credentials
<del> * @return bool
<del> */
<del> public function once(array $credentials = []);
<del>
<ide> /**
<ide> * Attempt to authenticate a user using the given credentials.
<ide> *
<ide> public function attempt(array $credentials = [], $remember = false, $login = tru
<ide> */
<ide> public function basic($field = 'email');
<ide>
<del> /**
<del> * Perform a stateless HTTP Basic login attempt.
<del> *
<del> * @param string $field
<del> * @return \Symfony\Component\HttpFoundation\Response|null
<del> */
<del> public function onceBasic($field = 'email');
<del>
<del> /**
<del> * Validate a user's credentials.
<del> *
<del> * @param array $credentials
<del> * @return bool
<del> */
<del> public function validate(array $credentials = []);
<del>
<ide> /**
<ide> * Log a user into the application.
<ide> *
<ide> public function validate(array $credentials = []);
<ide> */
<ide> public function login(Authenticatable $user, $remember = false);
<ide>
<del> /**
<del> * Log the given user ID into the application without sessions or cookies.
<del> *
<del> * @param mixed $id
<del> * @return bool
<del> */
<del> public function onceUsingId($id);
<del>
<ide> /**
<ide> * Log the given user ID into the application.
<ide> *
<ide><path>src/Illuminate/Contracts/Auth/StatelessGuard.php
<add><?php
<add>
<add>namespace Illuminate\Contracts\Auth;
<add>
<add>interface StatelessGuard
<add>{
<add> /**
<add> * Determine if the current user is authenticated.
<add> *
<add> * @return bool
<add> */
<add> public function check();
<add>
<add> /**
<add> * Determine if the current user is a guest.
<add> *
<add> * @return bool
<add> */
<add> public function guest();
<add>
<add> /**
<add> * Get the currently authenticated user.
<add> *
<add> * @return \Illuminate\Contracts\Auth\Authenticatable|null
<add> */
<add> public function user();
<add>
<add> /**
<add> * Get the ID for the currently authenticated user.
<add> *
<add> * @return int|null
<add> */
<add> public function id();
<add>
<add> /**
<add> * Log a user into the application without sessions or cookies.
<add> *
<add> * @param array $credentials
<add> * @return bool
<add> */
<add> public function once(array $credentials = []);
<add>
<add> /**
<add> * Perform a stateless HTTP Basic login attempt.
<add> *
<add> * @param string $field
<add> * @return \Symfony\Component\HttpFoundation\Response|null
<add> */
<add> public function onceBasic($field = 'email');
<add>
<add> /**
<add> * Validate a user's credentials.
<add> *
<add> * @param array $credentials
<add> * @return bool
<add> */
<add> public function validate(array $credentials = []);
<add>
<add> /**
<add> * Log the given user ID into the application without sessions or cookies.
<add> *
<add> * @param mixed $id
<add> * @return bool
<add> */
<add> public function onceUsingId($id);
<add>} | 2 |
Javascript | Javascript | replace "integer" type with "number" | f1df1d43d449b9aecb6c0585520cb10602ca9dd8 | <ide><path>packages/ember-runtime/lib/mixins/array.js
<ide> export default Mixin.create(Enumerable, {
<ide> ```
<ide>
<ide> @method slice
<del> @param {Integer} beginIndex (Optional) index to begin slicing from.
<del> @param {Integer} endIndex (Optional) index to end the slice at (but not included).
<add> @param {Number} beginIndex (Optional) index to begin slicing from.
<add> @param {Number} endIndex (Optional) index to end the slice at (but not included).
<ide> @return {Array} New array with specified slice
<ide> */
<ide> slice(beginIndex, endIndex) {
<ide><path>packages/ember-runtime/lib/mixins/comparable.js
<ide> export default Mixin.create({
<ide> @method compare
<ide> @param a {Object} the first object to compare
<ide> @param b {Object} the second object to compare
<del> @return {Integer} the result of the comparison
<add> @return {Number} the result of the comparison
<ide> */
<ide> compare: null
<ide> }); | 2 |
Text | Text | update license year | ffe48048dee66aaec5ee078f2e75dd19d99d1ee5 | <ide><path>license.md
<ide> The MIT License (MIT)
<ide>
<del>Copyright (c) 2016 Zeit, Inc.
<add>Copyright (c) 2016-present Zeit, Inc.
<ide>
<ide> Permission is hereby granted, free of charge, to any person obtaining a copy
<ide> of this software and associated documentation files (the "Software"), to deal | 1 |
Text | Text | update license year | d7b3458b150a160f93c1f5c89f8a224ed872cb6f | <ide><path>LICENSE.md
<ide> BSD 3-Clause License
<ide>
<del>Copyright (c) 2016, Free Code Camp.
<add>Copyright (c) 2017, Free Code Camp.
<ide> All rights reserved.
<ide>
<ide> Redistribution and use in source and binary forms, with or without
<ide><path>README.md
<ide> We welcome pull requests from Free Code Camp campers (our students) and seasoned
<ide> License
<ide> -------
<ide>
<del>Copyright (c) 2016 Free Code Camp.
<add>Copyright (c) 2017 Free Code Camp.
<ide>
<ide> The content of this repository bound by the following LICENSE(S)
<ide> - The computer software is licensed under the [BSD-3-Clause](./LICENSE.md). | 2 |
Text | Text | update japanese translation to 75fafe1 | 852753c13adfda7b9764827773b9e1789c5404a9 | <ide><path>docs/docs/10.9-perf.ja-JP.md
<ide> Reactは普通、従来の枠を超えてとても速いです。しかし、ア
<ide> ### `Perf.start()` と `Perf.stop()`
<ide> 測定の開始/終了です。その間のReactの操作は以下のような分析のために記録されます。あまり時間を使わない操作は無視されます。
<ide>
<add>停止した後、あなたは、測定結果を得るために `Perf.getLastMeasurements()` (後述)が必要になります。
<add>
<ide> ### `Perf.printInclusive(measurements)`
<ide> かかった全ての時間を出力します。引数が渡されなかった場合は、デフォルトで最後の測定から全ての測定が行われます。これは以下のように、コンソールに綺麗にフォーマットされたテーブルを出力します。
<ide> | 1 |
Text | Text | add model architectures intro | 96a9c65f97059d33fa19f9fe0ff0d89abb739259 | <ide><path>website/docs/usage/training.md
<ide> that reference this variable.
<ide> ### Model architectures {#model-architectures}
<ide>
<ide> <!-- TODO: refer to architectures API: /api/architectures -->
<add>A **model architecture** is a function that wires up a Thinc `Model` instance,
<add>which you can then use in a component or as a layer of a larger network. You
<add>can use Thinc as a thin wrapper around frameworks such as PyTorch, Tensorflow
<add>or MXNet, or you can implement your logic in Thinc directly.
<add>
<add>spaCy's built-in components will never construct their `Model` instances
<add>themselves, so you won't have to subclass the component to change its model
<add>architecture. You can just update the config so that it refers
<add>to a different registered function. Once the component has been created, its
<add>model instance has already been assigned, so you cannot change its model
<add>architecture. The architecture is like a recipe for the network, and you can't
<add>change the recipe once the dish has already been prepared. You have to make
<add>a new one.
<ide>
<ide> ### Metrics, training output and weighted scores {#metrics}
<ide> | 1 |
Python | Python | increase toc depth | 08b4638139c94ae5a1d9ad0342aaf022153e23c3 | <ide><path>docs/conf.py
<ide> on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
<ide>
<ide> if on_rtd:
<del> cmd = 'sphinx-apidoc -d 2 -o apidocs/ ../libcloud/'
<add> cmd = 'sphinx-apidoc -d 3 -o apidocs/ ../libcloud/'
<ide> subprocess.call(cmd, shell=True)
<ide>
<ide> # If extensions (or modules to document with autodoc) are in another directory, | 1 |
Python | Python | add signum function | 1bbb0092f3fc311fac9e56e12c1fa223dbe16465 | <ide><path>maths/signum.py
<add>"""
<add>Signum function -- https://en.wikipedia.org/wiki/Sign_function
<add>"""
<add>
<add>
<add>def signum(num: float) -> int:
<add> """
<add> Applies signum function on the number
<add>
<add> >>> signum(-10)
<add> -1
<add> >>> signum(10)
<add> 1
<add> >>> signum(0)
<add> 0
<add> """
<add> if num < 0:
<add> return -1
<add> return 1 if num else 0
<add>
<add>
<add>def test_signum() -> None:
<add> """
<add> Tests the signum function
<add> """
<add> assert signum(5) == 1
<add> assert signum(-5) == -1
<add> assert signum(0) == 0
<add>
<add>
<add>if __name__ == "__main__":
<add> print(signum(12))
<add> print(signum(-12))
<add> print(signum(0)) | 1 |
Javascript | Javascript | add comments to clarify why a sort is needed here | ef593368155bc3bc9e361b65242455c230295acb | <ide><path>lib/Compilation.js
<ide> class Compilation extends Tapable {
<ide> hash.update(child.hash);
<ide> });
<ide> let chunk;
<add> // clone needed as sort below is inplace mutation
<ide> const chunks = this.chunks.slice();
<add> /**
<add> * sort here will bring all "falsy" values to the beginning
<add> * this is needed as the "hasRuntime()" chunks are dependent on the
<add> * hashes of the non-runtime chunks.
<add> */
<ide> chunks.sort((a, b) => {
<ide> const aEntry = a.hasRuntime();
<ide> const bEntry = b.hasRuntime(); | 1 |
Python | Python | fix xla and amp | 86caeb76367834369a7e9e04fbc12a78b7ce1c8b | <ide><path>src/transformers/models/t5/modeling_tf_t5.py
<ide> def __init__(self, config, has_relative_attention_bias=False, **kwargs):
<ide> self.o = tf.keras.layers.Dense(self.d_model, use_bias=False, name="o")
<ide> self.dropout = tf.keras.layers.Dropout(config.dropout_rate)
<ide>
<del> if self.has_relative_attention_bias:
<del> self.relative_attention_bias = tf.keras.layers.Embedding(
<del> self.relative_attention_num_buckets,
<del> self.n_heads,
<del> name="relative_attention_bias",
<del> )
<ide> self.pruned_heads = set()
<ide>
<add> def build(self, input_shape):
<add> if self.has_relative_attention_bias:
<add> with tf.name_scope("relative_attention_bias"):
<add> self.relative_attention_bias = self.add_weight(
<add> name="embeddings",
<add> shape=[self.relative_attention_num_buckets, self.n_heads],
<add> )
<add>
<add> return super().build(input_shape)
<add>
<ide> def prune_heads(self, heads):
<ide> raise NotImplementedError
<ide>
<ide> def _relative_position_bucket(relative_position, bidirectional=True, num_buckets
<ide> # n = -relative_position
<ide> if bidirectional:
<ide> num_buckets //= 2
<del> relative_buckets += tf.dtypes.cast(tf.math.greater(relative_position, 0), tf.int32) * num_buckets
<add> relative_buckets += (
<add> tf.cast(tf.math.greater(relative_position, 0), dtype=relative_position.dtype) * num_buckets
<add> )
<ide> relative_position = tf.math.abs(relative_position)
<ide> else:
<ide> relative_position = -tf.math.minimum(relative_position, 0)
<ide> # now n is in the range [0, inf)
<ide> max_exact = num_buckets // 2
<ide> is_small = tf.math.less(relative_position, max_exact)
<del> relative_position_if_large = max_exact + tf.dtypes.cast(
<del> tf.math.log(tf.dtypes.cast(relative_position, tf.float32) / max_exact)
<add> relative_position_if_large = max_exact + tf.cast(
<add> tf.math.log(relative_position / max_exact)
<ide> / math.log(max_distance / max_exact)
<ide> * (num_buckets - max_exact),
<del> tf.int32,
<add> dtype=relative_position.dtype,
<ide> )
<ide> relative_position_if_large = tf.math.minimum(relative_position_if_large, num_buckets - 1)
<ide> relative_buckets += tf.where(is_small, relative_position, relative_position_if_large)
<ide> def compute_bias(self, query_length, key_length):
<ide> bidirectional=(not self.is_decoder),
<ide> num_buckets=self.relative_attention_num_buckets,
<ide> )
<del> values = self.relative_attention_bias(relative_position_bucket) # shape (query_length, key_length, num_heads)
<add> values = tf.gather(
<add> self.relative_attention_bias, relative_position_bucket
<add> ) # shape (query_length, key_length, num_heads)
<ide> values = tf.expand_dims(
<ide> tf.transpose(values, [2, 0, 1]), axis=0
<ide> ) # shape (1, num_heads, query_length, key_length)
<ide> def project(hidden_states, proj_layer, key_value_states, past_key_value):
<ide>
<ide> if position_bias is None:
<ide> if not self.has_relative_attention_bias:
<del> position_bias = tf.zeros((1, self.n_heads, real_seq_length, key_length), dtype=tf.float32)
<add> position_bias = tf.zeros((1, self.n_heads, real_seq_length, key_length))
<ide> else:
<ide> position_bias = self.compute_bias(real_seq_length, key_length)
<ide>
<ide> def project(hidden_states, proj_layer, key_value_states, past_key_value):
<ide> position_bias = position_bias[:, :, -seq_length:, :]
<ide>
<ide> if mask is not None:
<add> position_bias = tf.cast(position_bias, dtype=mask.dtype)
<ide> position_bias = position_bias + mask # (batch_size, n_heads, query_length, key_length)
<ide>
<ide> scores += position_bias
<ide> def call(
<ide>
<ide> # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
<ide> # ourselves in which case we just need to make it broadcastable to all heads.
<del> inputs["attention_mask"] = tf.cast(inputs["attention_mask"], dtype=tf.float32)
<add> inputs["attention_mask"] = tf.cast(inputs["attention_mask"], dtype=inputs["inputs_embeds"].dtype)
<ide> num_dims_attention_mask = len(shape_list(inputs["attention_mask"]))
<ide> if num_dims_attention_mask == 3:
<ide> extended_attention_mask = inputs["attention_mask"][:, None, :, :]
<ide> def call(
<ide> tf.tile(seq_ids[None, None, :], (batch_size, mask_seq_length, 1)),
<ide> seq_ids[None, :, None],
<ide> )
<del> causal_mask = tf.cast(causal_mask, dtype=tf.float32)
<add> causal_mask = tf.cast(causal_mask, dtype=inputs["attention_mask"].dtype)
<ide> extended_attention_mask = causal_mask[:, None, :, :] * inputs["attention_mask"][:, None, None, :]
<ide> if inputs["past_key_values"][0] is not None:
<ide> extended_attention_mask = extended_attention_mask[:, :, -seq_length:, :]
<ide> def call(
<ide> # If a 2D ou 3D attention mask is provided for the cross-attention
<ide> # we need to make broadcastable to [batch_size, num_heads, mask_seq_length, mask_seq_length]
<ide> # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
<del> inputs["encoder_attention_mask"] = tf.cast(inputs["encoder_attention_mask"], dtype=tf.float32)
<add> inputs["encoder_attention_mask"] = tf.cast(
<add> inputs["encoder_attention_mask"], dtype=extended_attention_mask.dtype
<add> )
<ide> num_dims_encoder_attention_mask = len(shape_list(inputs["encoder_attention_mask"]))
<ide> if num_dims_encoder_attention_mask == 3:
<ide> encoder_extended_attention_mask = inputs["encoder_attention_mask"][:, None, :, :]
<ide> def _shift_right(self, input_ids):
<ide> decoder_start_token_id is not None
<ide> ), "self.model.config.decoder_start_token_id has to be defined. In TF T5 it is usually set to the pad_token_id. See T5 docs for more information"
<ide>
<del> shifted_input_ids = tf.cast(input_ids, tf.int32)
<del> shifted_input_ids = tf.roll(shifted_input_ids, 1, axis=-1)
<add> shifted_input_ids = tf.roll(input_ids, 1, axis=-1)
<ide> start_tokens = tf.fill((shape_list(shifted_input_ids)[0], 1), decoder_start_token_id)
<ide> shifted_input_ids = tf.concat([start_tokens, shifted_input_ids[:, 1:]], -1)
<ide>
<ide> def _shift_right(self, input_ids):
<ide> )
<ide>
<ide> # "Verify that `labels` has only positive values and -100"
<del> assert_gte0 = tf.debugging.assert_greater_equal(shifted_input_ids, tf.cast(0, tf.int32))
<add> assert_gte0 = tf.debugging.assert_greater_equal(shifted_input_ids, tf.constant(0))
<ide>
<ide> # Make sure the assertion op is called by wrapping the result in an identity no-op
<ide> with tf.control_dependencies([assert_gte0]):
<ide><path>tests/test_modeling_tf_t5.py
<ide> def test_saved_model_creation(self):
<ide> # This test is too long (>30sec) and makes fail the CI
<ide> pass
<ide>
<del> def test_mixed_precision(self):
<del> # TODO JP: Make T5 float16 compliant
<del> pass
<del>
<del> def test_xla_mode(self):
<del> # TODO JP: Make T5 XLA compliant
<del> pass
<del>
<ide> @slow
<ide> def test_model_from_pretrained(self):
<ide> model = TFT5Model.from_pretrained("t5-small")
<ide> def test_model(self):
<ide> def test_train_pipeline_custom_model(self):
<ide> pass
<ide>
<del> def test_mixed_precision(self):
<del> # TODO JP: Make T5 float16 compliant
<del> pass
<del>
<del> def test_xla_mode(self):
<del> # TODO JP: Make T5 XLA compliant
<del> pass
<del>
<ide>
<ide> @require_tf
<ide> @require_sentencepiece | 2 |
Ruby | Ruby | fix failing flash test | 8736dd324117af90e0bf120cfd2074b06ccb45eb | <ide><path>actionpack/lib/action_controller/base.rb
<ide> def process_cleanup
<ide> end
<ide>
<ide> Base.class_eval do
<del> [ Flash, Filters, Layout, Benchmarking, Rescue, MimeResponds, Helpers,
<add> [ Filters, Layout, Benchmarking, Rescue, Flash, MimeResponds, Helpers,
<ide> Cookies, Caching, Verification, Streaming, SessionManagement,
<ide> HttpAuthentication::Basic::ControllerMethods, RecordIdentifier,
<ide> RequestForgeryProtection, Translation | 1 |
Text | Text | fix typo in docs | 2e8ccfd883ea2c4e304a03b3585e1fa7f9fe3d0a | <ide><path>docs/api-guide/viewsets.md
<ide> A more complete example of extra actions:
<ide>
<ide> @action(detail=False)
<ide> def recent_users(self, request):
<del> recent_users = User.objects.all().order('-last_login')
<add> recent_users = User.objects.all().order_by('-last_login')
<ide>
<ide> page = self.paginate_queryset(recent_users)
<ide> if page is not None: | 1 |
Text | Text | make javascript javascript and github github | e139ab85969c92916639f6fa026740e3cc8dc0ff | <ide><path>docs/00-Getting-Started.md
<ide> First we need to include the Chart.js library on the page. The library occupies
<ide> <script src="Chart.js"></script>
<ide> ```
<ide>
<del>Alternatively, if you're using an AMD loader for javascript modules, that is also supported in the Chart.js core. Please note: the library will still occupy a global variable of `Chart`, even if it detects `define` and `define.amd`. If this is a problem, you can call `noConflict` to restore the global Chart variable to it's previous owner.
<add>Alternatively, if you're using an AMD loader for JavaScript modules, that is also supported in the Chart.js core. Please note: the library will still occupy a global variable of `Chart`, even if it detects `define` and `define.amd`. If this is a problem, you can call `noConflict` to restore the global Chart variable to it's previous owner.
<ide>
<ide> ```javascript
<ide> // Using requirejs
<ide><path>docs/06-Advanced.md
<ide> new Chart(ctx).LineAlt(data);
<ide>
<ide> ### Creating custom builds
<ide>
<del>Chart.js uses <a href="http://gulpjs.com/" target="_blank">gulp</a> to build the library into a single javascript file. We can use this same build script with custom parameters in order to build a custom version.
<add>Chart.js uses <a href="http://gulpjs.com/" target="_blank">gulp</a> to build the library into a single JavaScript file. We can use this same build script with custom parameters in order to build a custom version.
<ide>
<ide> Firstly, we need to ensure development dependencies are installed. With node and npm installed, after cloning the Chart.js repo to a local directory, and navigating to that directory in the command line, we can run the following:
<ide>
<ide> npm install
<ide> npm install -g gulp
<ide> ```
<ide>
<del>This will install the local development dependencies for Chart.js, along with a CLI for the javascript task runner <a href="http://gulpjs.com/" target="_blank">gulp</a>.
<add>This will install the local development dependencies for Chart.js, along with a CLI for the JavaScript task runner <a href="http://gulpjs.com/" target="_blank">gulp</a>.
<ide>
<ide> Now, we can run the `gulp build` task, and pass in a comma seperated list of types as an argument to build a custom version of Chart.js with only specified chart types.
<ide>
<ide><path>docs/07-Notes.md
<ide> Some important points to note in my experience using ExplorerCanvas as a fallbac
<ide>
<ide> ### Bugs & issues
<ide>
<del>Please report these on the Github page - at <a href="https://github.com/nnnick/Chart.js" target="_blank">github.com/nnnick/Chart.js</a>. If you could include a link to a simple <a href="http://jsbin.com/" target="_blank">jsbin</a> or similar to demonstrate the issue, that'd be really helpful.
<add>Please report these on the GitHub page - at <a href="https://github.com/nnnick/Chart.js" target="_blank">github.com/nnnick/Chart.js</a>. If you could include a link to a simple <a href="http://jsbin.com/" target="_blank">jsbin</a> or similar to demonstrate the issue, that'd be really helpful.
<ide>
<ide>
<ide> ### Contributing | 3 |
Java | Java | provide simple way to create clientresponse | 04c2a2990dda185cca75ded2b218dff3054dafa8 | <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/client/ClientResponse.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> package org.springframework.web.reactive.function.client;
<ide>
<add>import java.util.Collections;
<ide> import java.util.List;
<ide> import java.util.Optional;
<ide> import java.util.OptionalLong;
<add>import java.util.function.Consumer;
<ide>
<ide> import reactor.core.publisher.Flux;
<ide> import reactor.core.publisher.Mono;
<ide>
<ide> import org.springframework.core.ParameterizedTypeReference;
<add>import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.HttpStatus;
<ide> import org.springframework.http.MediaType;
<ide> import org.springframework.http.ResponseCookie;
<ide> import org.springframework.http.ResponseEntity;
<ide> import org.springframework.http.client.reactive.ClientHttpResponse;
<add>import org.springframework.http.codec.HttpMessageReader;
<add>import org.springframework.http.codec.HttpMessageWriter;
<add>import org.springframework.util.Assert;
<ide> import org.springframework.util.MultiValueMap;
<ide> import org.springframework.web.reactive.function.BodyExtractor;
<ide>
<ide> public interface ClientResponse {
<ide> */
<ide> MultiValueMap<String, ResponseCookie> cookies();
<ide>
<add> /**
<add> * Return the strategies used to convert the body of this response.
<add> */
<add> ExchangeStrategies strategies();
<add>
<ide> /**
<ide> * Extract the body with the given {@code BodyExtractor}.
<ide> * @param extractor the {@code BodyExtractor} that reads from the response
<ide> public interface ClientResponse {
<ide> <T> Mono<ResponseEntity<List<T>>> toEntityList(ParameterizedTypeReference<T> typeReference);
<ide>
<ide>
<add> // Static builder methods
<add>
<add> /**
<add> * Create a builder with the status, headers, and cookies of the given response.
<add> * @param other the response to copy the status, headers, and cookies from
<add> * @return the created builder
<add> */
<add> static Builder from(ClientResponse other) {
<add> Assert.notNull(other, "'other' must not be null");
<add> return new DefaultClientResponseBuilder(other);
<add> }
<add>
<add> /**
<add> * Create a response builder with the given status code and using default strategies for reading
<add> * the body.
<add> * @param statusCode the status code
<add> * @return the created builder
<add> */
<add> static Builder create(HttpStatus statusCode) {
<add> return create(statusCode, ExchangeStrategies.withDefaults());
<add> }
<add>
<add> /**
<add> * Create a response builder with the given status code and strategies for reading the body.
<add> * @param statusCode the status code
<add> * @param strategies the strategies
<add> * @return the created builder
<add> */
<add> static Builder create(HttpStatus statusCode, ExchangeStrategies strategies) {
<add> Assert.notNull(statusCode, "'statusCode' must not be null");
<add> Assert.notNull(strategies, "'strategies' must not be null");
<add> return new DefaultClientResponseBuilder(strategies)
<add> .statusCode(statusCode);
<add> }
<add>
<add> /**
<add> * Create a response builder with the given status code and message body readers.
<add> * @param statusCode the status code
<add> * @param messageReaders the message readers
<add> * @return the created builder
<add> */
<add> static Builder create(HttpStatus statusCode, List<HttpMessageReader<?>> messageReaders) {
<add> Assert.notNull(statusCode, "'statusCode' must not be null");
<add> Assert.notNull(messageReaders, "'messageReaders' must not be null");
<add>
<add> return create(statusCode, new ExchangeStrategies() {
<add> @Override
<add> public List<HttpMessageReader<?>> messageReaders() {
<add> return messageReaders;
<add> }
<add>
<add> @Override
<add> public List<HttpMessageWriter<?>> messageWriters() {
<add> // not used in the response
<add> return Collections.emptyList();
<add> }
<add> });
<add>
<add> }
<add>
<ide> /**
<ide> * Represents the headers of the HTTP response.
<ide> * @see ClientResponse#headers()
<ide> interface Headers {
<ide> HttpHeaders asHttpHeaders();
<ide> }
<ide>
<add> /**
<add> * Defines a builder for a response.
<add> */
<add> interface Builder {
<add>
<add> /**
<add> * Set the status code of the response.
<add> * @param statusCode the new status code.
<add> * @return this builder
<add> */
<add> Builder statusCode(HttpStatus statusCode);
<add>
<add> /**
<add> * Add the given header value(s) under the given name.
<add> * @param headerName the header name
<add> * @param headerValues the header value(s)
<add> * @return this builder
<add> * @see HttpHeaders#add(String, String)
<add> */
<add> Builder header(String headerName, String... headerValues);
<add>
<add> /**
<add> * Manipulate this response's headers with the given consumer. The
<add> * headers provided to the consumer are "live", so that the consumer can be used to
<add> * {@linkplain HttpHeaders#set(String, String) overwrite} existing header values,
<add> * {@linkplain HttpHeaders#remove(Object) remove} values, or use any of the other
<add> * {@link HttpHeaders} methods.
<add> * @param headersConsumer a function that consumes the {@code HttpHeaders}
<add> * @return this builder
<add> */
<add> Builder headers(Consumer<HttpHeaders> headersConsumer);
<add>
<add> /**
<add> * Add a cookie with the given name and value(s).
<add> * @param name the cookie name
<add> * @param values the cookie value(s)
<add> * @return this builder
<add> */
<add> Builder cookie(String name, String... values);
<add>
<add> /**
<add> * Manipulate this response's cookies with the given consumer. The
<add> * map provided to the consumer is "live", so that the consumer can be used to
<add> * {@linkplain MultiValueMap#set(Object, Object) overwrite} existing header values,
<add> * {@linkplain MultiValueMap#remove(Object) remove} values, or use any of the other
<add> * {@link MultiValueMap} methods.
<add> * @param cookiesConsumer a function that consumes the cookies map
<add> * @return this builder
<add> */
<add> Builder cookies(Consumer<MultiValueMap<String, ResponseCookie>> cookiesConsumer);
<add>
<add> /**
<add> * Sets the body of the response. Calling this methods will
<add> * {@linkplain org.springframework.core.io.buffer.DataBufferUtils#release(DataBuffer) release}
<add> * the existing body of the builder.
<add> * @param body the new body.
<add> * @return this builder
<add> */
<add> Builder body(Flux<DataBuffer> body);
<add>
<add> /**
<add> * Sets the body of the response to the UTF-8 encoded bytes of the given string.
<add> * Calling this methods will
<add> * {@linkplain org.springframework.core.io.buffer.DataBufferUtils#release(DataBuffer) release}
<add> * the existing body of the builder.
<add> * @param body the new body.
<add> * @return this builder
<add> */
<add> Builder body(String body);
<add>
<add> /**
<add> * Builds the response.
<add> * @return the response
<add> */
<add> ClientResponse build();
<add> }
<ide> }
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/client/DefaultClientResponse.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public DefaultClientResponse(ClientHttpResponse response, ExchangeStrategies str
<ide> this.headers = new DefaultHeaders();
<ide> }
<ide>
<add> @Override
<add> public ExchangeStrategies strategies() {
<add> return this.strategies;
<add> }
<ide>
<ide> @Override
<ide> public HttpStatus statusCode() {
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/client/DefaultClientResponseBuilder.java
<add>/*
<add> * Copyright 2002-2018 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * 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>
<add>package org.springframework.web.reactive.function.client;
<add>
<add>import java.nio.charset.StandardCharsets;
<add>import java.util.function.Consumer;
<add>
<add>import reactor.core.publisher.Flux;
<add>
<add>import org.springframework.core.io.buffer.DataBuffer;
<add>import org.springframework.core.io.buffer.DataBufferFactory;
<add>import org.springframework.core.io.buffer.DataBufferUtils;
<add>import org.springframework.core.io.buffer.DefaultDataBufferFactory;
<add>import org.springframework.http.HttpHeaders;
<add>import org.springframework.http.HttpStatus;
<add>import org.springframework.http.ResponseCookie;
<add>import org.springframework.http.client.reactive.ClientHttpResponse;
<add>import org.springframework.lang.Nullable;
<add>import org.springframework.util.Assert;
<add>import org.springframework.util.CollectionUtils;
<add>import org.springframework.util.LinkedMultiValueMap;
<add>import org.springframework.util.MultiValueMap;
<add>
<add>/**
<add> * Default implementation of {@link ClientResponse.Builder}.
<add> *
<add> * @author Arjen Poutsma
<add> * @since 5.0.5
<add> */
<add>class DefaultClientResponseBuilder implements ClientResponse.Builder {
<add>
<add> private final HttpHeaders headers = new HttpHeaders();
<add>
<add> private final MultiValueMap<String, ResponseCookie> cookies = new LinkedMultiValueMap<>();
<add>
<add> private HttpStatus statusCode = HttpStatus.OK;
<add>
<add> private Flux<DataBuffer> body = Flux.empty();
<add>
<add> private ExchangeStrategies strategies;
<add>
<add>
<add> public DefaultClientResponseBuilder(ExchangeStrategies strategies) {
<add> Assert.notNull(strategies, "'strategies' must not be null");
<add> this.strategies = strategies;
<add> }
<add>
<add> public DefaultClientResponseBuilder(ClientResponse other) {
<add> this(other.strategies());
<add> statusCode(other.statusCode());
<add> headers(headers -> headers.addAll(other.headers().asHttpHeaders()));
<add> cookies(cookies -> cookies.addAll(other.cookies()));
<add> }
<add>
<add> @Override
<add> public DefaultClientResponseBuilder statusCode(HttpStatus statusCode) {
<add> Assert.notNull(statusCode, "'statusCode' must not be null");
<add> this.statusCode = statusCode;
<add> return this;
<add> }
<add>
<add> @Override
<add> public ClientResponse.Builder header(String headerName, String... headerValues) {
<add> for (String headerValue : headerValues) {
<add> this.headers.add(headerName, headerValue);
<add> }
<add> return this;
<add> }
<add>
<add> @Override
<add> public ClientResponse.Builder headers(Consumer<HttpHeaders> headersConsumer) {
<add> Assert.notNull(headersConsumer, "'headersConsumer' must not be null");
<add> headersConsumer.accept(this.headers);
<add> return this;
<add> }
<add>
<add> @Override
<add> public DefaultClientResponseBuilder cookie(String name, String... values) {
<add> for (String value : values) {
<add> this.cookies.add(name, ResponseCookie.from(name, value).build());
<add> }
<add> return this;
<add> }
<add>
<add> @Override
<add> public ClientResponse.Builder cookies(
<add> Consumer<MultiValueMap<String, ResponseCookie>> cookiesConsumer) {
<add> Assert.notNull(cookiesConsumer, "'cookiesConsumer' must not be null");
<add> cookiesConsumer.accept(this.cookies);
<add> return this;
<add> }
<add>
<add> @Override
<add> public ClientResponse.Builder body(Flux<DataBuffer> body) {
<add> Assert.notNull(body, "'body' must not be null");
<add> releaseBody();
<add> this.body = body;
<add> return this;
<add> }
<add>
<add> @Override
<add> public ClientResponse.Builder body(String body) {
<add> Assert.notNull(body, "'body' must not be null");
<add> releaseBody();
<add> DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
<add> this.body = Flux.just(body).
<add> map(s -> {
<add> byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
<add> return dataBufferFactory.wrap(bytes);
<add> });
<add> return this;
<add> }
<add>
<add> private void releaseBody() {
<add> this.body.subscribe(DataBufferUtils.releaseConsumer());
<add> }
<add>
<add> @Override
<add> public ClientResponse build() {
<add> ClientHttpResponse clientHttpResponse = new BuiltClientHttpResponse(this.statusCode,
<add> this.headers, this.cookies, this.body);
<add> return new DefaultClientResponse(clientHttpResponse, this.strategies);
<add> }
<add>
<add> private static class BuiltClientHttpResponse implements ClientHttpResponse {
<add>
<add> private final HttpStatus statusCode;
<add>
<add> private final HttpHeaders headers;
<add>
<add> private final MultiValueMap<String, ResponseCookie> cookies;
<add>
<add> private final Flux<DataBuffer> body;
<add>
<add> public BuiltClientHttpResponse(HttpStatus statusCode, HttpHeaders headers,
<add> MultiValueMap<String, ResponseCookie> cookies,
<add> Flux<DataBuffer> body) {
<add>
<add> this.statusCode = statusCode;
<add> this.headers = HttpHeaders.readOnlyHttpHeaders(headers);
<add> this.cookies = unmodifiableCopy(cookies);
<add> this.body = body;
<add> }
<add>
<add> private static @Nullable <K, V> MultiValueMap<K, V> unmodifiableCopy(@Nullable MultiValueMap<K, V> original) {
<add> if (original != null) {
<add> return CollectionUtils.unmodifiableMultiValueMap(new LinkedMultiValueMap<>(original));
<add> }
<add> else {
<add> return null;
<add> }
<add> }
<add>
<add> @Override
<add> public HttpStatus getStatusCode() {
<add> return this.statusCode;
<add> }
<add>
<add> @Override
<add> public HttpHeaders getHeaders() {
<add> return this.headers;
<add> }
<add>
<add> @Override
<add> public MultiValueMap<String, ResponseCookie> getCookies() {
<add> return this.cookies;
<add> }
<add>
<add> @Override
<add> public Flux<DataBuffer> getBody() {
<add> return this.body;
<add> }
<add> }
<add>
<add>}
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/client/support/ClientResponseWrapper.java
<add>/*
<add> * Copyright 2002-2018 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * 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>
<add>package org.springframework.web.reactive.function.client.support;
<add>
<add>import java.util.List;
<add>import java.util.Optional;
<add>import java.util.OptionalLong;
<add>
<add>import reactor.core.publisher.Flux;
<add>import reactor.core.publisher.Mono;
<add>
<add>import org.springframework.core.ParameterizedTypeReference;
<add>import org.springframework.http.HttpHeaders;
<add>import org.springframework.http.HttpStatus;
<add>import org.springframework.http.MediaType;
<add>import org.springframework.http.ResponseCookie;
<add>import org.springframework.http.ResponseEntity;
<add>import org.springframework.http.client.reactive.ClientHttpResponse;
<add>import org.springframework.util.Assert;
<add>import org.springframework.util.MultiValueMap;
<add>import org.springframework.web.reactive.function.BodyExtractor;
<add>import org.springframework.web.reactive.function.client.ClientResponse;
<add>import org.springframework.web.reactive.function.client.ExchangeStrategies;
<add>
<add>/**
<add> * Implementation of the {@link ClientResponse} interface that can be subclassed
<add> * to adapt the request in a
<add> * {@link org.springframework.web.reactive.function.client.ExchangeFilterFunction exchange filter function}.
<add> * All methods default to calling through to the wrapped request.
<add> *
<add> * @author Arjen Poutsma
<add> * @since 5.0.5
<add> */
<add>public class ClientResponseWrapper implements ClientResponse {
<add>
<add> private final ClientResponse delegate;
<add>
<add>
<add> /**
<add> * Create a new {@code ClientResponseWrapper} that wraps the given response.
<add> * @param delegate the response to wrap
<add> */
<add> public ClientResponseWrapper(ClientResponse delegate) {
<add> Assert.notNull(delegate, "'delegate' must not be null");
<add> this.delegate = delegate;
<add> }
<add>
<add>
<add> /**
<add> * Return the wrapped request.
<add> */
<add> public ClientResponse response() {
<add> return this.delegate;
<add> }
<add>
<add> @Override
<add> public ExchangeStrategies strategies() {
<add> return this.delegate.strategies();
<add> }
<add>
<add> @Override
<add> public HttpStatus statusCode() {
<add> return this.delegate.statusCode();
<add> }
<add>
<add> @Override
<add> public Headers headers() {
<add> return this.delegate.headers();
<add> }
<add>
<add> @Override
<add> public MultiValueMap<String, ResponseCookie> cookies() {
<add> return this.delegate.cookies();
<add> }
<add>
<add> @Override
<add> public <T> T body(BodyExtractor<T, ? super ClientHttpResponse> extractor) {
<add> return this.delegate.body(extractor);
<add> }
<add>
<add> @Override
<add> public <T> Mono<T> bodyToMono(Class<? extends T> elementClass) {
<add> return this.delegate.bodyToMono(elementClass);
<add> }
<add>
<add> @Override
<add> public <T> Mono<T> bodyToMono(ParameterizedTypeReference<T> typeReference) {
<add> return this.delegate.bodyToMono(typeReference);
<add> }
<add>
<add> @Override
<add> public <T> Flux<T> bodyToFlux(Class<? extends T> elementClass) {
<add> return this.delegate.bodyToFlux(elementClass);
<add> }
<add>
<add> @Override
<add> public <T> Flux<T> bodyToFlux(ParameterizedTypeReference<T> typeReference) {
<add> return this.delegate.bodyToFlux(typeReference);
<add> }
<add>
<add> @Override
<add> public <T> Mono<ResponseEntity<T>> toEntity(Class<T> bodyType) {
<add> return this.delegate.toEntity(bodyType);
<add> }
<add>
<add> @Override
<add> public <T> Mono<ResponseEntity<T>> toEntity(ParameterizedTypeReference<T> typeReference) {
<add> return this.delegate.toEntity(typeReference);
<add> }
<add>
<add> @Override
<add> public <T> Mono<ResponseEntity<List<T>>> toEntityList(Class<T> elementType) {
<add> return this.delegate.toEntityList(elementType);
<add> }
<add>
<add> @Override
<add> public <T> Mono<ResponseEntity<List<T>>> toEntityList(ParameterizedTypeReference<T> typeReference) {
<add> return this.delegate.toEntityList(typeReference);
<add> }
<add>
<add> /**
<add> * Implementation of the {@code Headers} interface that can be subclassed
<add> * to adapt the headers in a
<add> * {@link org.springframework.web.reactive.function.client.ExchangeFilterFunction exchange filter function}.
<add> * All methods default to calling through to the wrapped request.
<add> */
<add> public static class HeadersWrapper implements ClientResponse.Headers {
<add>
<add> private final Headers headers;
<add>
<add>
<add> /**
<add> * Create a new {@code HeadersWrapper} that wraps the given request.
<add> * @param headers the headers to wrap
<add> */
<add> public HeadersWrapper(Headers headers) {
<add> this.headers = headers;
<add> }
<add>
<add>
<add> @Override
<add> public OptionalLong contentLength() {
<add> return this.headers.contentLength();
<add> }
<add>
<add> @Override
<add> public Optional<MediaType> contentType() {
<add> return this.headers.contentType();
<add> }
<add>
<add> @Override
<add> public List<String> header(String headerName) {
<add> return this.headers.header(headerName);
<add> }
<add>
<add> @Override
<add> public HttpHeaders asHttpHeaders() {
<add> return this.headers.asHttpHeaders();
<add> }
<add> }
<add>
<add>}
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/client/support/package-info.java
<add>/*
<add> * Copyright 2002-2018 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * 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>
<add>/**
<add> * Classes supporting the {@code org.springframework.web.reactive.function.client} package.
<add> * Contains a {@code ClientResponse} wrapper to adapt a request.
<add> */
<add>@NonNullApi
<add>@NonNullFields
<add>package org.springframework.web.reactive.function.client.support;
<add>
<add>import org.springframework.lang.NonNullApi;
<add>import org.springframework.lang.NonNullFields;
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/support/ServerRequestWrapper.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.MultiValueMap;
<ide> import org.springframework.web.reactive.function.BodyExtractor;
<del>import org.springframework.web.reactive.function.server.HandlerFunction;
<ide> import org.springframework.web.reactive.function.server.ServerRequest;
<ide> import org.springframework.web.server.WebSession;
<ide> import org.springframework.web.util.UriBuilder;
<ide>
<ide> /**
<ide> * Implementation of the {@link ServerRequest} interface that can be subclassed
<del> * to adapt the request to a {@link HandlerFunction handler function}.
<add> * to adapt the request in a
<add> * {@link org.springframework.web.reactive.function.server.HandlerFilterFunction handler filter function}.
<ide> * All methods default to calling through to the wrapped request.
<ide> *
<ide> * @author Arjen Poutsma
<ide> public class ServerRequestWrapper implements ServerRequest {
<ide>
<ide>
<ide> /**
<del> * Create a new {@code RequestWrapper} that wraps the given request.
<add> * Create a new {@code ServerRequestWrapper} that wraps the given request.
<ide> * @param delegate the request to wrap
<ide> */
<ide> public ServerRequestWrapper(ServerRequest delegate) {
<ide> public Mono<? extends Principal> principal() {
<ide>
<ide> /**
<ide> * Implementation of the {@code Headers} interface that can be subclassed
<del> * to adapt the headers to a {@link HandlerFunction handler function}.
<add> * to adapt the headers in a
<add> * {@link org.springframework.web.reactive.function.server.HandlerFilterFunction handler filter function}.
<ide> * All methods default to calling through to the wrapped headers.
<ide> */
<ide> public static class HeadersWrapper implements ServerRequest.Headers {
<ide>
<ide> private final Headers headers;
<ide>
<add>
<ide> /**
<ide> * Create a new {@code HeadersWrapper} that wraps the given request.
<ide> * @param headers the headers to wrap
<ide> public HeadersWrapper(Headers headers) {
<ide> this.headers = headers;
<ide> }
<ide>
<add>
<ide> @Override
<ide> public List<MediaType> accept() {
<ide> return this.headers.accept();
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/support/package-info.java
<ide> /**
<del> * Classes supporting the {@code org.springframework.web.reactive.function} package.
<add> * Classes supporting the {@code org.springframework.web.reactive.function.server} package.
<ide> * Contains a {@code HandlerAdapter} that supports {@code HandlerFunction}s,
<ide> * a {@code HandlerResultHandler} that supports {@code ServerResponse}s, and
<ide> * a {@code ServerRequest} wrapper to adapt a request.
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultClientResponseBuilderTests.java
<add>/*
<add> * Copyright 2002-2018 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * 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>
<add>package org.springframework.web.reactive.function.client;
<add>
<add>import java.nio.charset.StandardCharsets;
<add>
<add>import org.junit.Before;
<add>import org.junit.Test;
<add>import reactor.core.publisher.Flux;
<add>import reactor.test.StepVerifier;
<add>
<add>import org.springframework.core.io.buffer.DataBuffer;
<add>import org.springframework.core.io.buffer.DataBufferFactory;
<add>import org.springframework.core.io.buffer.DefaultDataBufferFactory;
<add>import org.springframework.http.HttpHeaders;
<add>import org.springframework.http.HttpStatus;
<add>import org.springframework.http.ResponseCookie;
<add>
<add>import static org.junit.Assert.*;
<add>
<add>/**
<add> * @author Arjen Poutsma
<add> */
<add>public class DefaultClientResponseBuilderTests {
<add>
<add> private DataBufferFactory dataBufferFactory;
<add>
<add> @Before
<add> public void createBufferFactory() {
<add> this.dataBufferFactory = new DefaultDataBufferFactory();
<add> }
<add>
<add> @Test
<add> public void normal() {
<add> Flux<DataBuffer> body = Flux.just("baz")
<add> .map(s -> s.getBytes(StandardCharsets.UTF_8))
<add> .map(dataBufferFactory::wrap);
<add>
<add> ClientResponse response = ClientResponse.create(HttpStatus.BAD_GATEWAY, ExchangeStrategies.withDefaults())
<add> .header("foo", "bar")
<add> .cookie("baz", "qux")
<add> .body(body)
<add> .build();
<add>
<add> assertEquals(HttpStatus.BAD_GATEWAY, response.statusCode());
<add> HttpHeaders responseHeaders = response.headers().asHttpHeaders();
<add> assertEquals("bar", responseHeaders.getFirst("foo"));
<add> assertNotNull("qux", response.cookies().getFirst("baz"));
<add> assertEquals("qux", response.cookies().getFirst("baz").getValue());
<add>
<add> StepVerifier.create(response.bodyToFlux(String.class))
<add> .expectNext("baz")
<add> .verifyComplete();
<add> }
<add>
<add> @Test
<add> public void from() throws Exception {
<add> Flux<DataBuffer> otherBody = Flux.just("foo", "bar")
<add> .map(s -> s.getBytes(StandardCharsets.UTF_8))
<add> .map(dataBufferFactory::wrap);
<add>
<add> ClientResponse other = ClientResponse.create(HttpStatus.BAD_REQUEST, ExchangeStrategies.withDefaults())
<add> .header("foo", "bar")
<add> .cookie("baz", "qux")
<add> .body(otherBody)
<add> .build();
<add>
<add> Flux<DataBuffer> body = Flux.just("baz")
<add> .map(s -> s.getBytes(StandardCharsets.UTF_8))
<add> .map(dataBufferFactory::wrap);
<add>
<add> ClientResponse result = ClientResponse.from(other)
<add> .headers(httpHeaders -> httpHeaders.set("foo", "baar"))
<add> .cookies(cookies -> cookies.set("baz", ResponseCookie.from("baz", "quux").build()))
<add> .body(body)
<add> .build();
<add>
<add> assertEquals(HttpStatus.BAD_REQUEST, result.statusCode());
<add> assertEquals(1, result.headers().asHttpHeaders().size());
<add> assertEquals("baar", result.headers().asHttpHeaders().getFirst("foo"));
<add> assertEquals(1, result.cookies().size());
<add> assertEquals("quux", result.cookies().getFirst("baz").getValue());
<add>
<add> StepVerifier.create(result.bodyToFlux(String.class))
<add> .expectNext("baz")
<add> .verifyComplete();
<add> }
<add>
<add>
<add>}
<ide>\ No newline at end of file
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/function/client/support/ClientResponseWrapperTests.java
<add>/*
<add> * Copyright 2002-2018 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * 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>
<add>package org.springframework.web.reactive.function.client.support;
<add>
<add>import java.util.List;
<add>
<add>import org.junit.Before;
<add>import org.junit.Test;
<add>import reactor.core.publisher.Flux;
<add>import reactor.core.publisher.Mono;
<add>
<add>import org.springframework.core.ParameterizedTypeReference;
<add>import org.springframework.http.HttpStatus;
<add>import org.springframework.http.ReactiveHttpInputMessage;
<add>import org.springframework.http.ResponseCookie;
<add>import org.springframework.http.ResponseEntity;
<add>import org.springframework.util.MultiValueMap;
<add>import org.springframework.web.reactive.function.BodyExtractor;
<add>import org.springframework.web.reactive.function.BodyExtractors;
<add>import org.springframework.web.reactive.function.client.ClientResponse;
<add>
<add>import static java.util.Collections.singletonList;
<add>import static org.junit.Assert.*;
<add>import static org.mockito.Mockito.*;
<add>
<add>/**
<add> * @author Arjen Poutsma
<add> */
<add>public class ClientResponseWrapperTests {
<add>
<add> private ClientResponse mockResponse;
<add>
<add> private ClientResponseWrapper wrapper;
<add>
<add> @Before
<add> public void createWrapper() {
<add> this.mockResponse = mock(ClientResponse.class);
<add> this.wrapper = new ClientResponseWrapper(mockResponse);
<add> }
<add>
<add> @Test
<add> public void response() throws Exception {
<add> assertSame(mockResponse, wrapper.response());
<add> }
<add>
<add> @Test
<add> public void statusCode() throws Exception {
<add> HttpStatus status = HttpStatus.BAD_REQUEST;
<add> when(mockResponse.statusCode()).thenReturn(status);
<add>
<add> assertSame(status, wrapper.statusCode());
<add> }
<add>
<add> @Test
<add> public void headers() throws Exception {
<add> ClientResponse.Headers headers = mock(ClientResponse.Headers.class);
<add> when(mockResponse.headers()).thenReturn(headers);
<add>
<add> assertSame(headers, wrapper.headers());
<add> }
<add>
<add> @Test
<add> public void cookies() throws Exception {
<add> MultiValueMap<String, ResponseCookie> cookies = mock(MultiValueMap.class);
<add> when(mockResponse.cookies()).thenReturn(cookies);
<add>
<add> assertSame(cookies, wrapper.cookies());
<add> }
<add>
<add> @Test
<add> public void bodyExtractor() throws Exception {
<add> Mono<String> result = Mono.just("foo");
<add> BodyExtractor<Mono<String>, ReactiveHttpInputMessage> extractor = BodyExtractors.toMono(String.class);
<add> when(mockResponse.body(extractor)).thenReturn(result);
<add>
<add> assertSame(result, wrapper.body(extractor));
<add> }
<add>
<add> @Test
<add> public void bodyToMonoClass() throws Exception {
<add> Mono<String> result = Mono.just("foo");
<add> when(mockResponse.bodyToMono(String.class)).thenReturn(result);
<add>
<add> assertSame(result, wrapper.bodyToMono(String.class));
<add> }
<add>
<add> @Test
<add> public void bodyToMonoParameterizedTypeReference() throws Exception {
<add> Mono<String> result = Mono.just("foo");
<add> ParameterizedTypeReference<String> reference = new ParameterizedTypeReference<String>() {};
<add> when(mockResponse.bodyToMono(reference)).thenReturn(result);
<add>
<add> assertSame(result, wrapper.bodyToMono(reference));
<add> }
<add>
<add> @Test
<add> public void bodyToFluxClass() throws Exception {
<add> Flux<String> result = Flux.just("foo");
<add> when(mockResponse.bodyToFlux(String.class)).thenReturn(result);
<add>
<add> assertSame(result, wrapper.bodyToFlux(String.class));
<add> }
<add>
<add> @Test
<add> public void bodyToFluxParameterizedTypeReference() throws Exception {
<add> Flux<String> result = Flux.just("foo");
<add> ParameterizedTypeReference<String> reference = new ParameterizedTypeReference<String>() {};
<add> when(mockResponse.bodyToFlux(reference)).thenReturn(result);
<add>
<add> assertSame(result, wrapper.bodyToFlux(reference));
<add> }
<add>
<add> @Test
<add> public void toEntityClass() throws Exception {
<add> Mono<ResponseEntity<String>> result = Mono.just(new ResponseEntity<>("foo", HttpStatus.OK));
<add> when(mockResponse.toEntity(String.class)).thenReturn(result);
<add>
<add> assertSame(result, wrapper.toEntity(String.class));
<add> }
<add>
<add> @Test
<add> public void toEntityParameterizedTypeReference() throws Exception {
<add> Mono<ResponseEntity<String>> result = Mono.just(new ResponseEntity<>("foo", HttpStatus.OK));
<add> ParameterizedTypeReference<String> reference = new ParameterizedTypeReference<String>() {};
<add> when(mockResponse.toEntity(reference)).thenReturn(result);
<add>
<add> assertSame(result, wrapper.toEntity(reference));
<add> }
<add>
<add> @Test
<add> public void toEntityListClass() throws Exception {
<add> Mono<ResponseEntity<List<String>>> result = Mono.just(new ResponseEntity<>(singletonList("foo"), HttpStatus.OK));
<add> when(mockResponse.toEntityList(String.class)).thenReturn(result);
<add>
<add> assertSame(result, wrapper.toEntityList(String.class));
<add> }
<add>
<add> @Test
<add> public void toEntityListParameterizedTypeReference() throws Exception {
<add> Mono<ResponseEntity<List<String>>> result = Mono.just(new ResponseEntity<>(singletonList("foo"), HttpStatus.OK));
<add> ParameterizedTypeReference<String> reference = new ParameterizedTypeReference<String>() {};
<add> when(mockResponse.toEntityList(reference)).thenReturn(result);
<add>
<add> assertSame(result, wrapper.toEntityList(reference));
<add> }
<add>
<add>
<add>
<add>}
<ide>\ No newline at end of file
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/function/server/support/ServerRequestWrapperTests.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> import org.junit.Before;
<ide> import org.junit.Test;
<add>import reactor.core.publisher.Flux;
<add>import reactor.core.publisher.Mono;
<ide>
<add>import org.springframework.core.ParameterizedTypeReference;
<add>import org.springframework.http.HttpCookie;
<ide> import org.springframework.http.HttpMethod;
<add>import org.springframework.http.ReactiveHttpInputMessage;
<ide> import org.springframework.util.LinkedMultiValueMap;
<ide> import org.springframework.util.MultiValueMap;
<add>import org.springframework.web.reactive.function.BodyExtractor;
<add>import org.springframework.web.reactive.function.BodyExtractors;
<ide> import org.springframework.web.reactive.function.server.ServerRequest;
<ide>
<ide> import static org.junit.Assert.*;
<ide> public void pathVariables() throws Exception {
<ide> assertSame(pathVariables, wrapper.pathVariables());
<ide> }
<ide>
<add> @Test
<add> public void cookies() throws Exception {
<add> MultiValueMap<String, HttpCookie> cookies = mock(MultiValueMap.class);
<add> when(mockRequest.cookies()).thenReturn(cookies);
<add>
<add> assertSame(cookies, wrapper.cookies());
<add> }
<add>
<add> @Test
<add> public void bodyExtractor() throws Exception {
<add> Mono<String> result = Mono.just("foo");
<add> BodyExtractor<Mono<String>, ReactiveHttpInputMessage> extractor = BodyExtractors.toMono(String.class);
<add> when(mockRequest.body(extractor)).thenReturn(result);
<add>
<add> assertSame(result, wrapper.body(extractor));
<add> }
<add>
<add> @Test
<add> public void bodyToMonoClass() throws Exception {
<add> Mono<String> result = Mono.just("foo");
<add> when(mockRequest.bodyToMono(String.class)).thenReturn(result);
<add>
<add> assertSame(result, wrapper.bodyToMono(String.class));
<add> }
<add>
<add> @Test
<add> public void bodyToMonoParameterizedTypeReference() throws Exception {
<add> Mono<String> result = Mono.just("foo");
<add> ParameterizedTypeReference<String> reference = new ParameterizedTypeReference<String>() {};
<add> when(mockRequest.bodyToMono(reference)).thenReturn(result);
<add>
<add> assertSame(result, wrapper.bodyToMono(reference));
<add> }
<add>
<add> @Test
<add> public void bodyToFluxClass() throws Exception {
<add> Flux<String> result = Flux.just("foo");
<add> when(mockRequest.bodyToFlux(String.class)).thenReturn(result);
<add>
<add> assertSame(result, wrapper.bodyToFlux(String.class));
<add> }
<add>
<add> @Test
<add> public void bodyToFluxParameterizedTypeReference() throws Exception {
<add> Flux<String> result = Flux.just("foo");
<add> ParameterizedTypeReference<String> reference = new ParameterizedTypeReference<String>() {};
<add> when(mockRequest.bodyToFlux(reference)).thenReturn(result);
<add>
<add> assertSame(result, wrapper.bodyToFlux(reference));
<add> }
<add>
<ide> }
<ide>\ No newline at end of file | 10 |
PHP | PHP | move utility/debugger to error/debugger | bf51a2b2b2793f84202cf1830a2aa550f955db75 | <add><path>src/Error/Debugger.php
<del><path>src/Utility/Debugger.php
<ide> * @since 1.2.0
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<del>namespace Cake\Utility;
<add>namespace Cake\Error;
<ide>
<ide> use Cake\Core\Configure;
<ide> use Cake\Error\Exception;
<ide> use Cake\Log\Log;
<add>use Cake\Utility\Hash;
<add>use Cake\Utility\String;
<ide>
<ide> /**
<ide> * Provide custom logging and error handling.
<ide><path>src/basics.php
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<ide> use Cake\Cache\Cache;
<add>use Cake\Collection\Collection;
<ide> use Cake\Core\Configure;
<add>use Cake\Error\Debugger;
<ide> use Cake\I18n\I18n;
<del>use Cake\Utility\Debugger;
<del>use Cake\Collection\Collection;
<ide>
<ide> /**
<ide> * Basic defines for timing functions.
<add><path>tests/TestCase/Error/DebuggerTest.php
<del><path>tests/TestCase/Utility/DebuggerTest.php
<ide> * @since 1.2.0
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<del>namespace Cake\Test\TestCase\Utility;
<add>namespace Cake\Test\TestCase\Error;
<ide>
<ide> use Cake\Controller\Controller;
<ide> use Cake\Core\Configure;
<add>use Cake\Error\Debugger;
<ide> use Cake\Log\Log;
<ide> use Cake\TestSuite\TestCase;
<del>use Cake\Utility\Debugger;
<ide> use Cake\View\View;
<ide>
<ide> /**
<ide> public function testExportVarRecursion() {
<ide> */
<ide> public function testTraceExclude() {
<ide> $result = Debugger::trace();
<del> $this->assertRegExp('/^Cake\\\Test\\\TestCase\\\Utility\\\DebuggerTest::testTraceExclude/', $result);
<add> $this->assertRegExp('/^Cake\\\Test\\\TestCase\\\Error\\\DebuggerTest::testTraceExclude/', $result);
<ide>
<ide> $result = Debugger::trace(array(
<del> 'exclude' => array('Cake\Test\TestCase\Utility\DebuggerTest::testTraceExclude')
<add> 'exclude' => array('Cake\Test\TestCase\Error\DebuggerTest::testTraceExclude')
<ide> ));
<del> $this->assertNotRegExp('/^Cake\\\Test\\\TestCase\\\Utility\\\DebuggerTest::testTraceExclude/', $result);
<add> $this->assertNotRegExp('/^Cake\\\Test\\\TestCase\\\Error\\\DebuggerTest::testTraceExclude/', $result);
<ide> }
<ide>
<ide> /**
<ide> public function testDebugInfo() {
<ide> $object = new DebuggableThing();
<ide> $result = Debugger::exportVar($object, 2);
<ide> $expected = <<<eos
<del>object(Cake\Test\TestCase\Utility\DebuggableThing) {
<add>object(Cake\Test\TestCase\Error\DebuggableThing) {
<ide>
<ide> 'foo' => 'bar',
<del> 'inner' => object(Cake\Test\TestCase\Utility\DebuggableThing) {}
<add> 'inner' => object(Cake\Test\TestCase\Error\DebuggableThing) {}
<ide>
<ide> }
<ide> eos; | 3 |
Javascript | Javascript | add font mime type | 77e6d833f6818cbf3eecbe8e7cf640453af36ee1 | <ide><path>lib/nodeserver/server.js
<ide> StaticServlet.MimeMap = {
<ide> 'jpeg': 'image/jpeg',
<ide> 'gif': 'image/gif',
<ide> 'png': 'image/png',
<del> 'manifest': 'text/cache-manifest'
<add> 'manifest': 'text/cache-manifest',
<add> // it should be application/font-woff
<add> // but only this silences chrome warnings
<add> 'woff': 'font/opentype'
<ide> };
<ide>
<ide> StaticServlet.prototype.handleRequest = function(req, res) { | 1 |
Ruby | Ruby | use thread variable in taggedlogging | 6e76f8f5c05cb2f00d7a2f4d58e6dd35a23655f6 | <ide><path>activesupport/lib/active_support/tagged_logging.rb
<ide> module ActiveSupport
<ide> class TaggedLogging
<ide> def initialize(logger)
<ide> @logger = logger
<del> @tags = Hash.new { |h,k| h[k] = [] }
<ide> end
<ide>
<ide> def tagged(*new_tags)
<ide> def #{severity}(progname = nil, &block) # def warn(progname = nil,
<ide> end
<ide>
<ide> def flush
<del> @tags.delete(Thread.current)
<add> current_tags.clear
<ide> @logger.flush if @logger.respond_to?(:flush)
<ide> end
<ide>
<ide> def tags_text
<ide> end
<ide>
<ide> def current_tags
<del> @tags[Thread.current]
<add> Thread.current[:activesupport_tagged_logging_tags] ||= []
<ide> end
<ide> end
<ide> end | 1 |
Javascript | Javascript | convert select/option to not use wrappers | abfd151b90c54510d0a7a5b4404c443688510c35 | <ide><path>src/renderers/dom/client/wrappers/ReactDOMOption.js
<ide>
<ide> 'use strict';
<ide>
<del>var ReactBrowserComponentMixin = require('ReactBrowserComponentMixin');
<ide> var ReactChildren = require('ReactChildren');
<del>var ReactClass = require('ReactClass');
<ide> var ReactDOMSelect = require('ReactDOMSelect');
<del>var ReactElement = require('ReactElement');
<del>var ReactPropTypes = require('ReactPropTypes');
<ide>
<ide> var assign = require('Object.assign');
<ide> var warning = require('warning');
<ide>
<del>var option = ReactElement.createFactory('option');
<del>
<ide> var valueContextKey = ReactDOMSelect.valueContextKey;
<ide>
<ide> /**
<ide> * Implements an <option> native component that warns when `selected` is set.
<ide> */
<del>var ReactDOMOption = ReactClass.createClass({
<del> displayName: 'ReactDOMOption',
<del> tagName: 'OPTION',
<del>
<del> mixins: [ReactBrowserComponentMixin],
<del>
<del> getInitialState: function() {
<del> return {selected: null};
<del> },
<del>
<del> contextTypes: (function() {
<del> var obj = {};
<del> obj[valueContextKey] = ReactPropTypes.any;
<del> return obj;
<del> })(),
<del>
<del> componentWillMount: function() {
<add>var ReactDOMOption = {
<add> mountWrapper: function(inst, props, context) {
<ide> // TODO (yungsters): Remove support for `selected` in <option>.
<ide> if (__DEV__) {
<ide> warning(
<del> this.props.selected == null,
<add> props.selected == null,
<ide> 'Use the `defaultValue` or `value` props on <select> instead of ' +
<ide> 'setting `selected` on <option>.'
<ide> );
<ide> }
<ide>
<del> // Look up whether this option is 'selected' via parent-based context
<del> var context = this.context;
<add> // Look up whether this option is 'selected' via context
<ide> var selectValue = context[valueContextKey];
<ide>
<ide> // If context key is null (e.g., no specified value or after initial mount)
<del> // or missing (e.g., for <datalist>) skip props
<add> // or missing (e.g., for <datalist>), we don't change props.selected
<add> var selected = null;
<ide> if (selectValue != null) {
<del> var selected = false;
<add> selected = false;
<ide> if (Array.isArray(selectValue)) {
<ide> // multiple
<ide> for (var i = 0; i < selectValue.length; i++) {
<del> if ('' + selectValue[i] === '' + this.props.value) {
<add> if ('' + selectValue[i] === '' + props.value) {
<ide> selected = true;
<ide> break;
<ide> }
<ide> }
<ide> } else {
<del> selected = ('' + selectValue === '' + this.props.value);
<add> selected = ('' + selectValue === '' + props.value);
<ide> }
<del> this.setState({selected: selected});
<ide> }
<add>
<add> inst._wrapperState = {selected: selected};
<ide> },
<ide>
<del> render: function() {
<del> var props = this.props;
<add> getNativeProps: function(inst, props, context) {
<add> var nativeProps = assign({selected: undefined, children: undefined}, props);
<ide>
<ide> // Read state only from initial mount because <select> updates value
<ide> // manually; we need the initial state only for server rendering
<del> if (this.state.selected != null) {
<del> props = assign({}, props, {selected: this.state.selected});
<add> if (inst._wrapperState.selected != null) {
<add> nativeProps.selected = inst._wrapperState.selected;
<ide> }
<ide>
<ide> var content = '';
<ide>
<ide> // Flatten children and warn if they aren't strings or numbers;
<ide> // invalid types are ignored.
<del> ReactChildren.forEach(this.props.children, function(child) {
<add> ReactChildren.forEach(props.children, function(child) {
<ide> if (child == null) {
<ide> return;
<ide> }
<ide> var ReactDOMOption = ReactClass.createClass({
<ide> }
<ide> });
<ide>
<del> return option(props, content);
<add> nativeProps.children = content;
<add> return nativeProps;
<ide> },
<ide>
<del>});
<add>};
<ide>
<ide> module.exports = ReactDOMOption;
<ide><path>src/renderers/dom/client/wrappers/ReactDOMSelect.js
<ide>
<ide> 'use strict';
<ide>
<del>var AutoFocusUtils = require('AutoFocusUtils');
<ide> var LinkedValueUtils = require('LinkedValueUtils');
<del>var ReactBrowserComponentMixin = require('ReactBrowserComponentMixin');
<del>var ReactClass = require('ReactClass');
<del>var ReactElement = require('ReactElement');
<del>var ReactInstanceMap = require('ReactInstanceMap');
<add>var ReactMount = require('ReactMount');
<ide> var ReactUpdates = require('ReactUpdates');
<del>var ReactPropTypes = require('ReactPropTypes');
<ide>
<ide> var assign = require('Object.assign');
<del>var findDOMNode = require('findDOMNode');
<del>
<del>var select = ReactElement.createFactory('select');
<add>var warning = require('warning');
<ide>
<ide> var valueContextKey =
<ide> '__ReactDOMSelect_value$' + Math.random().toString(36).slice(2);
<ide>
<ide> function updateOptionsIfPendingUpdateAndMounted() {
<del> if (this._pendingUpdate) {
<del> this._pendingUpdate = false;
<del> var value = LinkedValueUtils.getValue(this.props);
<del> if (value != null && this.isMounted()) {
<del> updateOptions(this, value);
<add> if (this._wrapperState.pendingUpdate && this._rootNodeID) {
<add> this._wrapperState.pendingUpdate = false;
<add>
<add> var props = this._currentElement.props;
<add> var value = LinkedValueUtils.getValue(props);
<add>
<add> if (value != null) {
<add> updateOptions(this, props, value);
<ide> }
<ide> }
<ide> }
<ide>
<add>function getDeclarationErrorAddendum(owner) {
<add> if (owner) {
<add> var name = owner.getName();
<add> if (name) {
<add> return ' Check the render method of `' + name + '`.';
<add> }
<add> }
<add> return '';
<add>}
<add>
<add>var valuePropNames = ['value', 'defaultValue'];
<add>
<ide> /**
<ide> * Validation function for `value` and `defaultValue`.
<ide> * @private
<ide> */
<del>function selectValueType(props, propName, componentName) {
<del> if (props[propName] == null) {
<del> return null;
<del> }
<del> if (props.multiple) {
<del> if (!Array.isArray(props[propName])) {
<del> return new Error(
<del> `The \`${propName}\` prop supplied to <select> must be an array if ` +
<del> `\`multiple\` is true.`
<del> );
<add>function checkSelectPropTypes(inst, props) {
<add> var owner = inst._currentElement._owner;
<add> LinkedValueUtils.checkPropTypes(
<add> 'select',
<add> props,
<add> owner
<add> );
<add>
<add> for (var i = 0; i < valuePropNames.length; i++) {
<add> var propName = valuePropNames[i];
<add> if (props[propName] == null) {
<add> continue;
<ide> }
<del> } else {
<del> if (Array.isArray(props[propName])) {
<del> return new Error(
<del> `The \`${propName}\` prop supplied to <select> must be a scalar ` +
<del> `value if \`multiple\` is false.`
<add> if (props.multiple) {
<add> warning(
<add> Array.isArray(props[propName]),
<add> 'The `%s` prop supplied to <select> must be an array if ' +
<add> '`multiple` is true.%s',
<add> propName,
<add> getDeclarationErrorAddendum(owner)
<add> );
<add> } else {
<add> warning(
<add> !Array.isArray(props[propName]),
<add> 'The `%s` prop supplied to <select> must be a scalar ' +
<add> 'value if `multiple` is false.%s',
<add> propName,
<add> getDeclarationErrorAddendum(owner)
<ide> );
<ide> }
<ide> }
<ide> }
<ide>
<ide> /**
<del> * @param {ReactComponent} component Instance of ReactDOMSelect
<add> * @param {ReactDOMComponent} inst
<add> * @param {boolean} multiple
<ide> * @param {*} propValue A stringable (with `multiple`, a list of stringables).
<ide> * @private
<ide> */
<del>function updateOptions(component, propValue) {
<add>function updateOptions(inst, multiple, propValue) {
<ide> var selectedValue, i;
<del> var options = findDOMNode(component).options;
<add> var options = ReactMount.getNode(inst._rootNodeID).options;
<ide>
<del> if (component.props.multiple) {
<add> if (multiple) {
<ide> selectedValue = {};
<ide> for (i = 0; i < propValue.length; i++) {
<ide> selectedValue['' + propValue[i]] = true;
<ide> function updateOptions(component, propValue) {
<ide> * If `defaultValue` is provided, any options with the supplied values will be
<ide> * selected.
<ide> */
<del>var ReactDOMSelect = ReactClass.createClass({
<del> displayName: 'ReactDOMSelect',
<del> tagName: 'SELECT',
<del>
<del> mixins: [AutoFocusUtils.Mixin, ReactBrowserComponentMixin],
<del>
<del> statics: {
<del> valueContextKey: valueContextKey,
<add>var ReactDOMSelect = {
<add> valueContextKey: valueContextKey,
<add>
<add> getNativeProps: function(inst, props, context) {
<add> return assign({}, props, {
<add> onChange: inst._wrapperState.onChange,
<add> value: undefined,
<add> });
<ide> },
<ide>
<del> propTypes: {
<del> defaultValue: selectValueType,
<del> value: selectValueType,
<del> },
<del>
<del> componentWillMount: function() {
<del> LinkedValueUtils.checkPropTypes(
<del> 'select',
<del> this.props,
<del> ReactInstanceMap.get(this)._currentElement._owner
<del> );
<add> mountWrapper: function(inst, props) {
<add> if (__DEV__) {
<add> checkSelectPropTypes(inst, props);
<add> }
<ide>
<del> this._pendingUpdate = false;
<add> var value = LinkedValueUtils.getValue(props);
<add> inst._wrapperState = {
<add> pendingUpdate: false,
<add> initialValue: value != null ? value : props.defaultValue,
<add> onChange: _handleChange.bind(inst),
<add> wasMultiple: Boolean(props.multiple),
<add> };
<ide> },
<ide>
<del> getInitialState: function() {
<add> processChildContext: function(inst, props, context) {
<ide> // Pass down initial value so initial generated markup has correct
<ide> // `selected` attributes
<del> var value = LinkedValueUtils.getValue(this.props);
<del> if (value != null) {
<del> return {initialValue: value};
<del> } else {
<del> return {initialValue: this.props.defaultValue};
<del> }
<del> },
<del>
<del> childContextTypes: (function() {
<del> var obj = {};
<del> obj[valueContextKey] = ReactPropTypes.any;
<del> return obj;
<del> })(),
<del>
<del> getChildContext: function() {
<del> var obj = {};
<del> obj[valueContextKey] = this.state.initialValue;
<del> return obj;
<add> var childContext = assign({}, context);
<add> childContext[valueContextKey] = inst._wrapperState.initialValue;
<add> return childContext;
<ide> },
<ide>
<del> render: function() {
<del> // Clone `this.props` so we don't mutate the input.
<del> var props = assign({}, this.props);
<add> postUpdateWrapper: function(inst) {
<add> var props = inst._currentElement.props;
<ide>
<del> props.onChange = this._handleChange;
<del> props.value = null;
<del>
<del> return select(props, this.props.children);
<del> },
<del>
<del> componentWillReceiveProps: function(nextProps) {
<ide> // After the initial mount, we control selected-ness manually so don't pass
<ide> // the context value down
<del> this.setState({initialValue: null});
<del> },
<add> inst._wrapperState.initialValue = undefined;
<ide>
<del> componentDidUpdate: function(prevProps) {
<del> var value = LinkedValueUtils.getValue(this.props);
<add> var wasMultiple = inst._wrapperState.wasMultiple;
<add> inst._wrapperState.wasMultiple = Boolean(props.multiple);
<add>
<add> var value = LinkedValueUtils.getValue(props);
<ide> if (value != null) {
<del> this._pendingUpdate = false;
<del> updateOptions(this, value);
<del> } else if (!prevProps.multiple !== !this.props.multiple) {
<add> inst._wrapperState.pendingUpdate = false;
<add> updateOptions(inst, Boolean(props.multiple), value);
<add> } else if (wasMultiple !== Boolean(props.multiple)) {
<ide> // For simplicity, reapply `defaultValue` if `multiple` is toggled.
<del> if (this.props.defaultValue != null) {
<del> updateOptions(this, this.props.defaultValue);
<add> if (props.defaultValue != null) {
<add> updateOptions(inst, Boolean(props.multiple), props.defaultValue);
<ide> } else {
<ide> // Revert the select back to its default unselected state.
<del> updateOptions(this, this.props.multiple ? [] : '');
<add> updateOptions(inst, Boolean(props.multiple), props.multiple ? [] : '');
<ide> }
<ide> }
<ide> },
<add>};
<ide>
<del> _handleChange: function(event) {
<del> var returnValue = LinkedValueUtils.executeOnChange(this.props, event);
<del>
<del> this._pendingUpdate = true;
<del> ReactUpdates.asap(updateOptionsIfPendingUpdateAndMounted, this);
<del> return returnValue;
<del> },
<add>function _handleChange(event) {
<add> var props = this._currentElement.props;
<add> var returnValue = LinkedValueUtils.executeOnChange(props, event);
<ide>
<del>});
<add> this._wrapperState.pendingUpdate = true;
<add> ReactUpdates.asap(updateOptionsIfPendingUpdateAndMounted, this);
<add> return returnValue;
<add>}
<ide>
<ide> module.exports = ReactDOMSelect;
<ide><path>src/renderers/dom/client/wrappers/__tests__/ReactDOMSelect-test.js
<ide> describe('ReactDOMSelect', function() {
<ide> <option value="gorilla">A gorilla!</option>
<ide> </select>;
<ide> var markup = React.renderToString(stub);
<del> expect(markup).toContain('<option value="giraffe" selected=');
<del> expect(markup).not.toContain('<option value="monkey" selected=');
<del> expect(markup).not.toContain('<option value="gorilla" selected=');
<add> expect(markup).toContain('<option selected="" value="giraffe"');
<add> expect(markup).not.toContain('<option selected="" value="monkey"');
<add> expect(markup).not.toContain('<option selected="" value="gorilla"');
<ide> });
<ide>
<ide> it('should support server-side rendering with defaultValue', function() {
<ide> describe('ReactDOMSelect', function() {
<ide> <option value="gorilla">A gorilla!</option>
<ide> </select>;
<ide> var markup = React.renderToString(stub);
<del> expect(markup).toContain('<option value="giraffe" selected=');
<del> expect(markup).not.toContain('<option value="monkey" selected=');
<del> expect(markup).not.toContain('<option value="gorilla" selected=');
<add> expect(markup).toContain('<option selected="" value="giraffe"');
<add> expect(markup).not.toContain('<option selected="" value="monkey"');
<add> expect(markup).not.toContain('<option selected="" value="gorilla"');
<ide> });
<ide>
<ide> it('should support server-side rendering with multiple', function() {
<ide> describe('ReactDOMSelect', function() {
<ide> <option value="gorilla">A gorilla!</option>
<ide> </select>;
<ide> var markup = React.renderToString(stub);
<del> expect(markup).toContain('<option value="giraffe" selected=');
<del> expect(markup).toContain('<option value="gorilla" selected=');
<del> expect(markup).not.toContain('<option value="monkey" selected=');
<add> expect(markup).toContain('<option selected="" value="giraffe"');
<add> expect(markup).toContain('<option selected="" value="gorilla"');
<add> expect(markup).not.toContain('<option selected="" value="monkey"');
<ide> });
<ide>
<ide> it('should not control defaultValue if readding options', function() {
<ide><path>src/renderers/dom/shared/ReactDOMComponent.js
<ide> var ReactComponentBrowserEnvironment =
<ide> require('ReactComponentBrowserEnvironment');
<ide> var ReactDOMButton = require('ReactDOMButton');
<ide> var ReactDOMInput = require('ReactDOMInput');
<add>var ReactDOMOption = require('ReactDOMOption');
<add>var ReactDOMSelect = require('ReactDOMSelect');
<ide> var ReactDOMTextarea = require('ReactDOMTextarea');
<ide> var ReactMount = require('ReactMount');
<ide> var ReactMultiChild = require('ReactMultiChild');
<ide> function trapBubbledEventsLocal() {
<ide> }
<ide> }
<ide>
<add>function postUpdateSelectWrapper() {
<add> ReactDOMSelect.postUpdateWrapper(this);
<add>}
<add>
<ide> // For HTML, certain tags should omit their close tag. We keep a whitelist for
<ide> // those special cased tags.
<ide>
<ide> ReactDOMComponent.Mixin = {
<ide> props = ReactDOMButton.getNativeProps(this, props, context);
<ide> break;
<ide> case 'input':
<del> ReactDOMInput.mountWrapper(this, props);
<add> ReactDOMInput.mountWrapper(this, props, context);
<ide> props = ReactDOMInput.getNativeProps(this, props, context);
<ide> break;
<add> case 'option':
<add> ReactDOMOption.mountWrapper(this, props, context);
<add> props = ReactDOMOption.getNativeProps(this, props, context);
<add> break;
<add> case 'select':
<add> ReactDOMSelect.mountWrapper(this, props, context);
<add> props = ReactDOMSelect.getNativeProps(this, props, context);
<add> context = ReactDOMSelect.processChildContext(this, props, context);
<add> break;
<ide> case 'textarea':
<del> ReactDOMTextarea.mountWrapper(this, props);
<add> ReactDOMTextarea.mountWrapper(this, props, context);
<ide> props = ReactDOMTextarea.getNativeProps(this, props, context);
<ide> break;
<ide> }
<ide> ReactDOMComponent.Mixin = {
<ide> switch (this._tag) {
<ide> case 'button':
<ide> case 'input':
<add> case 'select':
<ide> case 'textarea':
<ide> if (props.autoFocus) {
<ide> transaction.getReactMountReady().enqueue(
<ide> ReactDOMComponent.Mixin = {
<ide> lastProps = ReactDOMInput.getNativeProps(this, lastProps);
<ide> nextProps = ReactDOMInput.getNativeProps(this, nextProps);
<ide> break;
<add> case 'option':
<add> lastProps = ReactDOMOption.getNativeProps(this, lastProps);
<add> nextProps = ReactDOMOption.getNativeProps(this, nextProps);
<add> break;
<add> case 'select':
<add> lastProps = ReactDOMSelect.getNativeProps(this, lastProps);
<add> nextProps = ReactDOMSelect.getNativeProps(this, nextProps);
<add> break;
<ide> case 'textarea':
<ide> ReactDOMTextarea.updateWrapper(this);
<ide> lastProps = ReactDOMTextarea.getNativeProps(this, lastProps);
<ide> ReactDOMComponent.Mixin = {
<ide> transaction,
<ide> processChildContext(context, this)
<ide> );
<add>
<add> if (this._tag === 'select') {
<add> // <select> value update needs to occur after <option> children
<add> // reconciliation
<add> transaction.getReactMountReady().enqueue(postUpdateSelectWrapper, this);
<add> }
<ide> },
<ide>
<ide> /**
<ide><path>src/renderers/dom/shared/ReactDefaultInjection.js
<ide> var ReactComponentBrowserEnvironment =
<ide> var ReactDefaultBatchingStrategy = require('ReactDefaultBatchingStrategy');
<ide> var ReactDOMComponent = require('ReactDOMComponent');
<ide> var ReactDOMIDOperations = require('ReactDOMIDOperations');
<del>var ReactDOMOption = require('ReactDOMOption');
<del>var ReactDOMSelect = require('ReactDOMSelect');
<ide> var ReactDOMTextComponent = require('ReactDOMTextComponent');
<ide> var ReactElement = require('ReactElement');
<ide> var ReactEventListener = require('ReactEventListener');
<ide> function inject() {
<ide>
<ide> ReactInjection.Class.injectMixin(ReactBrowserComponentMixin);
<ide>
<del> ReactInjection.NativeComponent.injectComponentClasses({
<del> 'option': ReactDOMOption,
<del> 'select': ReactDOMSelect,
<del> });
<del>
<ide> ReactInjection.DOMProperty.injectDOMPropertyConfig(HTMLDOMPropertyConfig);
<ide> ReactInjection.DOMProperty.injectDOMPropertyConfig(SVGDOMPropertyConfig);
<ide> | 5 |
PHP | PHP | allow customizing templates for prev() and next() | 058daad01c2eb82e323c498e9e8a8db8dcf65063 | <ide><path>src/View/Helper/PaginatorHelper.php
<ide> protected function _toggledLink($text, $enabled, $options, $templates)
<ide> }
<ide> $text = $options['escape'] ? h($text) : $text;
<ide>
<add> $templater = $this->templater();
<add> $newTemplates = !empty($options['templates']) ? $options['templates'] : false;
<add> if ($newTemplates) {
<add> $templater->push();
<add> $templateMethod = is_string($options['templates']) ? 'load' : 'add';
<add> $templater->{$templateMethod}($options['templates']);
<add> }
<add>
<ide> if (!$enabled) {
<del> return $this->templater()->format($template, [
<add> $out = $templater->format($template, [
<ide> 'text' => $text,
<ide> ]);
<add>
<add> if ($newTemplates) {
<add> $templater->pop();
<add> }
<add>
<add> return $out;
<ide> }
<ide> $paging = $this->params($options['model']);
<ide>
<ide> protected function _toggledLink($text, $enabled, $options, $templates)
<ide> ['page' => $paging['page'] + $options['step']]
<ide> );
<ide> $url = $this->generateUrl($url, $options['model']);
<del> return $this->templater()->format($template, [
<add>
<add> $out = $templater->format($template, [
<ide> 'url' => $url,
<ide> 'text' => $text,
<ide> ]);
<add>
<add> if ($newTemplates) {
<add> $templater->pop();
<add> }
<add>
<add> return $out;
<ide> }
<ide>
<ide> /**
<ide> protected function _toggledLink($text, $enabled, $options, $templates)
<ide> * - `escape` Whether you want the contents html entity encoded, defaults to true
<ide> * - `model` The model to use, defaults to PaginatorHelper::defaultModel()
<ide> * - `url` An array of additional URL options to use for link generation.
<add> * - `templates` An array of templates, or template file name containing the
<add> * templates you'd like to use when generating the link for previous page.
<add> * The helper's original templates will be restored once prev() is done.
<ide> *
<ide> * @param string $title Title for the link. Defaults to '<< Previous'.
<ide> * @param array $options Options for pagination link. See above for list of keys.
<ide> public function prev($title = '<< Previous', array $options = [])
<ide> * - `escape` Whether you want the contents html entity encoded, defaults to true
<ide> * - `model` The model to use, defaults to PaginatorHelper::defaultModel()
<ide> * - `url` An array of additional URL options to use for link generation.
<add> * - `templates` An array of templates, or template file name containing the
<add> * templates you'd like to use when generating the link for next page.
<add> * The helper's original templates will be restored once next() is done.
<ide> *
<ide> * @param string $title Title for the link. Defaults to 'Next >>'.
<ide> * @param array $options Options for pagination link. See above for list of keys.
<ide><path>tests/TestCase/View/Helper/PaginatorHelperTest.php
<ide> public function testPrev()
<ide> '/li'
<ide> ];
<ide> $this->assertHtml($expected, $result);
<add>
<add> $result = $this->Paginator->prev('Prev', [
<add> 'templates' => [
<add> 'prevActive' => '<a rel="prev" href="{{url}}">{{text}}</a>'
<add> ]
<add> ]);
<add> $expected = [
<add> 'a' => ['href' => '/index', 'rel' => 'prev'],
<add> 'Prev',
<add> '/a',
<add> ];
<add> $this->assertHtml($expected, $result);
<ide> }
<ide>
<ide> /**
<ide> public function testNext()
<ide> ];
<ide> $this->assertHtml($expected, $result);
<ide>
<add> $result = $this->Paginator->next('Next', [
<add> 'templates' => [
<add> 'nextActive' => '<a rel="next" href="{{url}}">{{text}}</a>'
<add> ]
<add> ]);
<add> $expected = [
<add> 'a' => ['href' => '/index?page=2', 'rel' => 'next'],
<add> 'Next',
<add> '/a',
<add> ];
<add> $this->assertHtml($expected, $result);
<add>
<ide> $result = $this->Paginator->next('Next >>', ['escape' => false]);
<ide> $expected = [
<ide> 'li' => ['class' => 'next'], | 2 |
Javascript | Javascript | move fbobjc bundle command to cli | 7ad418a396994324764f19907b86f4d3c5b39e41 | <ide><path>packager/react-packager/index.js
<ide> */
<ide> 'use strict';
<ide>
<del>require('babel-core/register')({
<del> only: /react-packager\/src/
<del>});
<add>require('babel-core/register')();
<ide>
<ide> useGracefulFs();
<ide>
<ide><path>private-cli/index.js
<ide> */
<ide> 'use strict';
<ide>
<del>require('babel-core/register')({
<del> only: [
<del> /react-native-github\/private-cli\/src/
<del> ],
<del>});
<add>// trigger babel-core/register
<add>require('../packager/react-packager');
<ide>
<ide> var cli = require('./src/cli');
<ide> var fs = require('fs');
<ide><path>private-cli/src/bundle/__mocks__/sign.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>'use strict';
<add>
<add>function sign(source) {
<add> return source;
<add>}
<add>
<add>module.exports = sign;
<ide><path>private-cli/src/bundle/__tests__/getAssetDestPathAndroid-test.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>'use strict';
<add>
<add>jest.dontMock('../getAssetDestPathAndroid');
<add>
<add>const getAssetDestPathAndroid = require('../getAssetDestPathAndroid');
<add>
<add>describe('getAssetDestPathAndroid', () => {
<add> it('should use the right destination folder', () => {
<add> const asset = {
<add> name: 'icon',
<add> type: 'png',
<add> httpServerLocation: '/assets/test',
<add> };
<add>
<add> const expectDestPathForScaleToStartWith = (scale, path) => {
<add> if (!getAssetDestPathAndroid(asset, scale).startsWith(path)) {
<add> throw new Error(`asset for scale ${scale} should start with path '${path}'`);
<add> }
<add> };
<add>
<add> expectDestPathForScaleToStartWith(1, 'drawable-mdpi');
<add> expectDestPathForScaleToStartWith(1.5, 'drawable-hdpi');
<add> expectDestPathForScaleToStartWith(2, 'drawable-xhdpi');
<add> expectDestPathForScaleToStartWith(3, 'drawable-xxhdpi');
<add> expectDestPathForScaleToStartWith(4, 'drawable-xxxhdpi');
<add> });
<add>
<add> it('should lowercase path', () => {
<add> const asset = {
<add> name: 'Icon',
<add> type: 'png',
<add> httpServerLocation: '/assets/App/Test',
<add> };
<add>
<add> expect(getAssetDestPathAndroid(asset, 1)).toBe(
<add> 'drawable-mdpi/app_test_icon.png'
<add> );
<add> });
<add>
<add> it('should remove `assets/` prefix', () => {
<add> const asset = {
<add> name: 'icon',
<add> type: 'png',
<add> httpServerLocation: '/assets/RKJSModules/Apps/AndroidSample/Assets',
<add> };
<add>
<add> expect(
<add> getAssetDestPathAndroid(asset, 1).startsWith('assets_')
<add> ).toBeFalsy();
<add> });
<add>});
<ide><path>private-cli/src/bundle/__tests__/getAssetDestPathIOS-test.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>'use strict';
<add>
<add>jest.dontMock('../getAssetDestPathIOS');
<add>
<add>const getAssetDestPathIOS = require('../getAssetDestPathIOS');
<add>
<add>describe('getAssetDestPathIOS', () => {
<add> it('should build correct path', () => {
<add> const asset = {
<add> name: 'icon',
<add> type: 'png',
<add> httpServerLocation: '/assets/test',
<add> };
<add>
<add> expect(getAssetDestPathIOS(asset, 1)).toBe('assets/test/icon.png');
<add> });
<add>
<add> it('should consider scale', () => {
<add> const asset = {
<add> name: 'icon',
<add> type: 'png',
<add> httpServerLocation: '/assets/test',
<add> };
<add>
<add> expect(getAssetDestPathIOS(asset, 2)).toBe('assets/test/[email protected]');
<add> expect(getAssetDestPathIOS(asset, 3)).toBe('assets/test/[email protected]');
<add> });
<add>});
<ide><path>private-cli/src/bundle/__tests__/saveBundleAndMap-test.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>'use strict';
<add>
<add>jest
<add> .dontMock('../saveBundleAndMap')
<add> .dontMock('os-tmpdir')
<add> .dontMock('temp');
<add>
<add>jest.mock('fs');
<add>
<add>const saveBundleAndMap = require('../saveBundleAndMap');
<add>const fs = require('fs');
<add>const temp = require('temp');
<add>
<add>const code = 'const foo = "bar";';
<add>const map = JSON.stringify({
<add> version: 3,
<add> file: 'foo.js.map',
<add> sources: ['foo.js'],
<add> sourceRoot: '/',
<add> names: ['bar'],
<add> mappings: 'AAA0B,kBAAhBA,QAAOC,SACjBD,OAAOC,OAAO'
<add>});
<add>
<add>describe('saveBundleAndMap', () => {
<add> beforeEach(() => {
<add> fs.writeFileSync = jest.genMockFn();
<add> });
<add>
<add> it('should save bundle', () => {
<add> const codeWithMap = {code: code};
<add> const bundleOutput = temp.path({suffix: '.bundle'});
<add>
<add> saveBundleAndMap(
<add> codeWithMap,
<add> 'ios',
<add> bundleOutput
<add> );
<add>
<add> expect(fs.writeFileSync.mock.calls[0]).toEqual([bundleOutput, code]);
<add> });
<add>
<add> it('should save sourcemaps if required so', () => {
<add> const codeWithMap = {code: code, map: map};
<add> const bundleOutput = temp.path({suffix: '.bundle'});
<add> const sourceMapOutput = temp.path({suffix: '.map'});
<add> saveBundleAndMap(
<add> codeWithMap,
<add> 'ios',
<add> bundleOutput,
<add> sourceMapOutput
<add> );
<add>
<add> expect(fs.writeFileSync.mock.calls[1]).toEqual([sourceMapOutput, map]);
<add> });
<add>});
<ide><path>private-cli/src/bundle/bundle.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>'use strict';
<add>
<add>const log = require('../util/log').out('bundle');
<add>const parseCommandLine = require('../../../packager/parseCommandLine');
<add>const processBundle = require('./processBundle');
<add>const Promise = require('promise');
<add>const ReactPackager = require('../../../packager/react-packager');
<add>const saveBundleAndMap = require('./saveBundleAndMap');
<add>
<add>/**
<add> * Builds the bundle starting to look for dependencies at the given entry path.
<add> */
<add>function bundle(argv, config) {
<add> return new Promise((resolve, reject) => {
<add> _bundle(argv, config, resolve, reject);
<add> });
<add>}
<add>
<add>function _bundle(argv, config, resolve, reject) {
<add> const args = parseCommandLine([
<add> {
<add> command: 'entry-file',
<add> description: 'Path to the root JS file, either absolute or relative to JS root',
<add> type: 'string',
<add> required: true,
<add> }, {
<add> command: 'platform',
<add> description: 'Either "ios" or "android"',
<add> type: 'string',
<add> required: true,
<add> }, {
<add> command: 'dev',
<add> description: 'If false, warnings are disabled and the bundle is minified',
<add> default: true,
<add> }, {
<add> command: 'bundle-output',
<add> description: 'File name where to store the resulting bundle, ex. /tmp/groups.bundle',
<add> type: 'string',
<add> required: true,
<add> }, {
<add> command: 'sourcemap-output',
<add> description: 'File name where to store the sourcemap file for resulting bundle, ex. /tmp/groups.map',
<add> type: 'string',
<add> }, {
<add> command: 'assets-dest',
<add> description: 'Directory name where to store assets referenced in the bundle',
<add> type: 'string',
<add> }
<add> ], argv);
<add>
<add> // This is used by a bazillion of npm modules we don't control so we don't
<add> // have other choice than defining it as an env variable here.
<add> process.env.NODE_ENV = args.dev ? 'development' : 'production';
<add>
<add> const options = {
<add> projectRoots: config.getProjectRoots(),
<add> assetRoots: config.getAssetRoots(),
<add> blacklistRE: config.getBlacklistRE(),
<add> transformModulePath: config.getTransformModulePath(),
<add> };
<add>
<add> const requestOpts = {
<add> entryFile: args['entry-file'],
<add> dev: args.dev,
<add> minify: !args.dev,
<add> platform: args.platform,
<add> };
<add>
<add> resolve(ReactPackager.createClientFor(options).then(client => {
<add> log('Created ReactPackager');
<add> return client.buildBundle(requestOpts)
<add> .then(outputBundle => {
<add> log('Closing client');
<add> client.close();
<add> return outputBundle;
<add> })
<add> .then(outputBundle => processBundle(outputBundle, !args.dev))
<add> .then(outputBundle => saveBundleAndMap(
<add> outputBundle,
<add> args.platform,
<add> args['bundle-output'],
<add> args['sourcemap-output'],
<add> args['assets-dest']
<add> ));
<add> }));
<add>}
<add>
<add>module.exports = bundle;
<ide><path>private-cli/src/bundle/getAssetDestPathAndroid.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>'use strict';
<add>
<add>const path = require('path');
<add>
<add>function getAndroidAssetSuffix(scale) {
<add> switch (scale) {
<add> case 0.75: return 'ldpi';
<add> case 1: return 'mdpi';
<add> case 1.5: return 'hdpi';
<add> case 2: return 'xhdpi';
<add> case 3: return 'xxhdpi';
<add> case 4: return 'xxxhdpi';
<add> }
<add>}
<add>
<add>function getAssetDestPathAndroid(asset, scale) {
<add> var suffix = getAndroidAssetSuffix(scale);
<add> if (!suffix) {
<add> throw new Error(
<add> 'Don\'t know which android drawable suffix to use for asset: ' +
<add> JSON.stringify(asset)
<add> );
<add> }
<add> const androidFolder = 'drawable-' + suffix;
<add> // TODO: reuse this logic from https://fburl.com/151101135
<add> const fileName = (asset.httpServerLocation.substr(1) + '/' + asset.name)
<add> .toLowerCase()
<add> .replace(/\//g, '_') // Encode folder structure in file name
<add> .replace(/([^a-z0-9_])/g, '') // Remove illegal chars
<add> .replace(/^assets_/, ''); // Remove "assets_" prefix
<add>
<add> return path.join(androidFolder, fileName + '.' + asset.type);
<add>}
<add>
<add>module.exports = getAssetDestPathAndroid;
<ide><path>private-cli/src/bundle/getAssetDestPathIOS.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>'use strict';
<add>
<add>const path = require('path');
<add>
<add>function getAssetDestPathIOS(asset, scale) {
<add> const suffix = scale === 1 ? '' : '@' + scale + 'x';
<add> const fileName = asset.name + suffix + '.' + asset.type;
<add> return path.join(asset.httpServerLocation.substr(1), fileName);
<add>}
<add>
<add>module.exports = getAssetDestPathIOS;
<ide><path>private-cli/src/bundle/processBundle.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>'use strict';
<add>
<add>const log = require('../util/log').out('bundle');
<add>
<add>function processBundle(input, shouldMinify) {
<add> log('start');
<add> let bundle;
<add> if (shouldMinify) {
<add> bundle = input.getMinifiedSourceAndMap();
<add> } else {
<add> bundle = {
<add> code: input.getSource(),
<add> map: JSON.stringify(input.getSourceMap()),
<add> };
<add> }
<add> bundle.assets = input.getAssets();
<add> log('finish');
<add> return bundle;
<add>}
<add>
<add>module.exports = processBundle;
<ide><path>private-cli/src/bundle/saveBundleAndMap.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>'use strict';
<add>
<add>const execFile = require('child_process').execFile;
<add>const fs = require('fs');
<add>const getAssetDestPathAndroid = require('./getAssetDestPathAndroid');
<add>const getAssetDestPathIOS = require('./getAssetDestPathIOS');
<add>const log = require('../util/log').out('bundle');
<add>const path = require('path');
<add>const sign = require('./sign');
<add>
<add>function saveBundleAndMap(
<add> codeWithMap,
<add> platform,
<add> bundleOutput,
<add> sourcemapOutput,
<add> assetsDest
<add>) {
<add> log('Writing bundle output to:', bundleOutput);
<add> fs.writeFileSync(bundleOutput, sign(codeWithMap.code));
<add> log('Done writing bundle output');
<add>
<add> if (sourcemapOutput) {
<add> log('Writing sourcemap output to:', sourcemapOutput);
<add> fs.writeFileSync(sourcemapOutput, codeWithMap.map);
<add> log('Done writing sourcemap output');
<add> }
<add>
<add> if (!assetsDest) {
<add> console.warn('Assets destination folder is not set, skipping...');
<add> return Promise.resolve();
<add> }
<add>
<add> const getAssetDestPath = platform === 'android'
<add> ? getAssetDestPathAndroid
<add> : getAssetDestPathIOS;
<add>
<add> const filesToCopy = Object.create(null); // Map src -> dest
<add> codeWithMap.assets
<add> .filter(asset => !asset.deprecated)
<add> .forEach(asset =>
<add> asset.scales.forEach((scale, idx) => {
<add> const src = asset.files[idx];
<add> const dest = path.join(assetsDest, getAssetDestPath(asset, scale));
<add> filesToCopy[src] = dest;
<add> })
<add> );
<add>
<add> return copyAll(filesToCopy);
<add>}
<add>
<add>function copyAll(filesToCopy) {
<add> const queue = Object.keys(filesToCopy);
<add> if (queue.length === 0) {
<add> return Promise.resolve();
<add> }
<add>
<add> log('Copying ' + queue.length + ' asset files');
<add> return new Promise((resolve, reject) => {
<add> const copyNext = (error) => {
<add> if (error) {
<add> return reject(error);
<add> }
<add> if (queue.length === 0) {
<add> log('Done copying assets');
<add> resolve();
<add> } else {
<add> const src = queue.shift();
<add> const dest = filesToCopy[src];
<add> copy(src, dest, copyNext);
<add> }
<add> };
<add> copyNext();
<add> });
<add>}
<add>
<add>function copy(src, dest, callback) {
<add> const destDir = path.dirname(dest);
<add> execFile('mkdir', ['-p', destDir], err => {
<add> if (err) {
<add> return callback(err);
<add> }
<add> fs.createReadStream(src)
<add> .pipe(fs.createWriteStream(dest))
<add> .on('finish', callback);
<add> });
<add>}
<add>
<add>module.exports = saveBundleAndMap;
<ide><path>private-cli/src/bundle/sign.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>'use strict';
<add>
<add>const signedsource = require('./signedsource');
<add>const util = require('util');
<add>
<add>function sign(source) {
<add> var ssToken = util.format('<<%sSource::*O*zOeWoEQle#+L!plEphiEmie@IsG>>', 'Signed');
<add> var signedPackageText =
<add> source + util.format('\n__SSTOKENSTRING = "@%s %s";\n', 'generated', ssToken);
<add> return signedsource.sign(signedPackageText).signed_data;
<add>}
<add>
<add>module.exports = sign;
<ide><path>private-cli/src/bundle/signedsource.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>'use strict';
<add>
<add>var TOKEN = '<<SignedSource::*O*zOeWoEQle#+L!plEphiEmie@IsG>>',
<add> OLDTOKEN = '<<SignedSource::*O*zOeWoEQle#+L!plEphiEmie@I>>',
<add> TOKENS = [TOKEN, OLDTOKEN],
<add> PATTERN = new RegExp('@'+'generated (?:SignedSource<<([a-f0-9]{32})>>)');
<add>
<add>exports.SIGN_OK = {message:'ok'};
<add>exports.SIGN_UNSIGNED = new Error('unsigned');
<add>exports.SIGN_INVALID = new Error('invalid');
<add>
<add>// Thrown by sign(). Primarily for unit tests.
<add>exports.TokenNotFoundError = new Error(
<add> 'Code signing placeholder not found (expected to find \''+TOKEN+'\')');
<add>
<add>var md5_hash_hex;
<add>
<add>// MD5 hash function for Node.js. To port this to other platforms, provide an
<add>// alternate code path for defining the md5_hash_hex function.
<add>var crypto = require('crypto');
<add>md5_hash_hex = function md5_hash_hex(data, input_encoding) {
<add> var md5sum = crypto.createHash('md5');
<add> md5sum.update(data, input_encoding);
<add> return md5sum.digest('hex');
<add>};
<add>
<add>// Returns the signing token to be embedded, generally in a header comment,
<add>// in the file you wish to be signed.
<add>//
<add>// @return str to be embedded in to-be-signed file
<add>function signing_token() {
<add> return '@'+'generated '+TOKEN;
<add>}
<add>exports.signing_token = signing_token;
<add>
<add>// Determine whether a file is signed. This does NOT verify the signature.
<add>//
<add>// @param str File contents as a string.
<add>// @return bool True if the file has a signature.
<add>function is_signed(file_data) {
<add> return !!PATTERN.exec(file_data);
<add>}
<add>exports.is_signed = is_signed;
<add>
<add>// Sign a source file which you have previously embedded a signing token
<add>// into. Signing modifies only the signing token, so the semantics of the
<add>// file will not change if you've put it in a comment.
<add>//
<add>// @param str File contents as a string (with embedded token).
<add>// @return str Signed data.
<add>function sign(file_data) {
<add> var first_time = file_data.indexOf(TOKEN) !== -1;
<add> if (!first_time) {
<add> if (is_signed(file_data))
<add> file_data = file_data.replace(PATTERN, signing_token());
<add> else
<add> throw exports.TokenNotFoundError;
<add> }
<add> var signature = md5_hash_hex(file_data, 'utf8');
<add> var signed_data = file_data.replace(TOKEN, 'SignedSource<<'+signature+'>>');
<add> return { first_time: first_time, signed_data: signed_data };
<add>}
<add>exports.sign = sign;
<add>
<add>// Verify a file's signature.
<add>//
<add>// @param str File contents as a string.
<add>// @return Returns SIGN_OK if the data contains a valid signature,
<add>// SIGN_UNSIGNED if it contains no signature, or SIGN_INVALID if
<add>// it contains an invalid signature.
<add>function verify_signature(file_data) {
<add> var match = PATTERN.exec(file_data);
<add> if (!match)
<add> return exports.SIGN_UNSIGNED;
<add> // Replace the signature with the TOKEN, then hash and see if it matches
<add> // the value in the file. For backwards compatibility, also try with
<add> // OLDTOKEN if that doesn't match.
<add> var k, token, with_token, actual_md5, expected_md5 = match[1];
<add> for (k in TOKENS) {
<add> token = TOKENS[k];
<add> with_token = file_data.replace(PATTERN, '@'+'generated '+token);
<add> actual_md5 = md5_hash_hex(with_token, 'utf8');
<add> if (expected_md5 === actual_md5)
<add> return exports.SIGN_OK;
<add> }
<add> return exports.SIGN_INVALID;
<add>}
<add>exports.verify_signature = verify_signature;
<ide><path>private-cli/src/cli.js
<ide> */
<ide> 'use strict';
<ide>
<add>const bundle = require('./bundle/bundle');
<ide> const Config = require('./util/Config');
<ide> const dependencies = require('./dependencies/dependencies');
<ide> const Promise = require('promise');
<ide>
<ide> const documentedCommands = {
<add> bundle: bundle,
<ide> dependencies: dependencies,
<ide> };
<ide>
<ide><path>private-cli/src/dependencies/dependencies.js
<ide> const ReactPackager = require('../../../packager/react-packager');
<ide> /**
<ide> * Returns the dependencies an entry path has.
<ide> */
<del>function dependencies(argv, conf) {
<add>function dependencies(argv, config) {
<ide> return new Promise((resolve, reject) => {
<del> _dependencies(argv, conf, resolve, reject);
<add> _dependencies(argv, config, resolve, reject);
<ide> });
<ide> }
<ide>
<del>function _dependencies(argv, conf, resolve, reject) {
<add>function _dependencies(argv, config, resolve, reject) {
<ide> const args = parseCommandLine([
<ide> {
<ide> command: 'entry-file',
<ide> function _dependencies(argv, conf, resolve, reject) {
<ide> reject(`File ${rootModuleAbsolutePath} does not exist`);
<ide> }
<ide>
<del> const config = {
<del> projectRoots: conf.getProjectRoots(),
<del> assetRoots: conf.getAssetRoots(),
<del> blacklistRE: conf.getBlacklistRE(),
<del> transformModulePath: conf.getTransformModulePath(),
<add> const packageOpts = {
<add> projectRoots: config.getProjectRoots(),
<add> assetRoots: config.getAssetRoots(),
<add> blacklistRE: config.getBlacklistRE(),
<add> transformModulePath: config.getTransformModulePath(),
<ide> };
<ide>
<del> const relativePath = config.projectRoots.map(root =>
<add> const relativePath = packageOpts.projectRoots.map(root =>
<ide> path.relative(
<ide> root,
<ide> rootModuleAbsolutePath
<ide> function _dependencies(argv, conf, resolve, reject) {
<ide>
<ide> log('Running ReactPackager');
<ide> log('Waiting for the packager.');
<del> resolve(ReactPackager.createClientFor(config).then(client => {
<add> resolve(ReactPackager.createClientFor(packageOpts).then(client => {
<ide> log('Packager client was created');
<ide> return client.getOrderedDependencyPaths(options)
<ide> .then(deps => {
<ide> function _dependencies(argv, conf, resolve, reject) {
<ide> // Long term, we need either
<ide> // (a) JS code to not depend on anything outside this directory, or
<ide> // (b) Come up with a way to declare this dependency in Buck.
<del> const isInsideProjectRoots = config.projectRoots.filter(root =>
<del> modulePath.startsWith(root)
<add> const isInsideProjectRoots = packageOpts.projectRoots.filter(
<add> root => modulePath.startsWith(root)
<ide> ).length > 0;
<ide>
<ide> if (isInsideProjectRoots) { | 15 |
Python | Python | add support for managed identity in wasb hook | caf0a8499f6099c943b0dd5054a9480b2e046bf1 | <ide><path>airflow/providers/microsoft/azure/hooks/wasb.py
<ide> from typing import Any, Dict, List, Optional
<ide>
<ide> from azure.core.exceptions import ResourceExistsError, ResourceNotFoundError
<del>from azure.identity import ClientSecretCredential
<add>from azure.identity import ClientSecretCredential, ManagedIdentityCredential
<ide> from azure.storage.blob import BlobClient, BlobServiceClient, ContainerClient, StorageStreamDownloader
<ide>
<ide> from airflow.exceptions import AirflowException
<ide> class WasbHook(BaseHook):
<ide> passed to the `BlockBlockService()` constructor. For example, authenticate
<ide> using a SAS token by adding {"sas_token": "YOUR_TOKEN"}.
<ide>
<add> If no authentication configuration is provided, managed identity will be used (applicable
<add> when using Azure compute infrastructure).
<add>
<ide> :param wasb_conn_id: Reference to the :ref:`wasb connection <howto/connection:wasb>`.
<ide> :type wasb_conn_id: str
<ide> :param public_read: Whether an anonymous public read access should be used. default is False
<ide> def get_conn(self) -> BlobServiceClient: # pylint: disable=too-many-return-stat
<ide> return BlobServiceClient(account_url=extra.get('sas_token'))
<ide> if sas_token and not sas_token.startswith('https'):
<ide> return BlobServiceClient(account_url=f"https://{conn.login}.blob.core.windows.net/" + sas_token)
<del> else:
<del> # Fall back to old auth
<del> return BlobServiceClient(
<del> account_url=f"https://{conn.login}.blob.core.windows.net/", credential=conn.password, **extra
<del> )
<add>
<add> # Fall back to old auth (password) or use managed identity if not provided.
<add> credential = conn.password
<add> if not credential:
<add> credential = ManagedIdentityCredential()
<add> self.log.info("Using managed identity as credential")
<add> return BlobServiceClient(
<add> account_url=f"https://{conn.login}.blob.core.windows.net/",
<add> credential=credential,
<add> **extra,
<add> )
<ide>
<ide> def _get_container_client(self, container_name: str) -> ContainerClient:
<ide> """
<ide><path>tests/providers/microsoft/azure/hooks/test_wasb.py
<ide> from unittest import mock
<ide>
<ide> import pytest
<add>from azure.identity import ManagedIdentityCredential
<ide> from azure.storage.blob import BlobServiceClient
<ide>
<ide> from airflow.exceptions import AirflowException
<ide> def setUp(self):
<ide> self.ad_conn_id = 'azure_AD_test'
<ide> self.sas_conn_id = 'sas_token_id'
<ide> self.public_read_conn_id = 'pub_read_id'
<add> self.managed_identity_conn_id = 'managed_identity'
<ide>
<ide> db.merge_conn(
<ide> Connection(
<ide> def setUp(self):
<ide> ),
<ide> )
<ide> )
<add> db.merge_conn(
<add> Connection(
<add> conn_id=self.managed_identity_conn_id,
<add> conn_type=self.connection_type,
<add> )
<add> )
<ide> db.merge_conn(
<ide> Connection(
<ide> conn_id=self.sas_conn_id,
<ide> def test_shared_key_connection(self):
<ide> hook = WasbHook(wasb_conn_id=self.shared_key_conn_id)
<ide> assert isinstance(hook.get_conn(), BlobServiceClient)
<ide>
<add> def test_managed_identity(self):
<add> hook = WasbHook(wasb_conn_id=self.managed_identity_conn_id)
<add> self.assertIsInstance(hook.get_conn(), BlobServiceClient)
<add> self.assertIsInstance(hook.get_conn().credential, ManagedIdentityCredential)
<add>
<ide> def test_sas_token_connection(self):
<ide> hook = WasbHook(wasb_conn_id=self.sas_conn_id)
<ide> assert isinstance(hook.get_conn(), BlobServiceClient) | 2 |
Text | Text | simplify http2stream encoding text | 9191b42c83d52e361ca8933f672802aa0f92e5d7 | <ide><path>doc/api/http2.md
<ide> All `Http2Stream` instances are [`Duplex`][] streams. The `Writable` side of the
<ide> `Duplex` is used to send data to the connected peer, while the `Readable` side
<ide> is used to receive data sent by the connected peer.
<ide>
<del>The default text character encoding for all `Http2Stream`s is UTF-8. As a best
<del>practice, it is recommended that when using an `Http2Stream` to send text,
<del>the `'content-type'` header should be set and should identify the character
<del>encoding used.
<add>The default text character encoding for an `Http2Stream` is UTF-8. When using an
<add>`Http2Stream` to send text, use the `'content-type'` header to set the character
<add>encoding.
<ide>
<ide> ```js
<ide> stream.respond({ | 1 |
Javascript | Javascript | remove broken concatenation for now | 181a2f032ac57d7efda67c2b2fd0dccd14790588 | <ide><path>lib/css/CssExportsGenerator.js
<ide> class CssExportsGenerator extends Generator {
<ide> super();
<ide> }
<ide>
<del> /**
<del> * @param {NormalModule} module module for which the bailout reason should be determined
<del> * @param {ConcatenationBailoutReasonContext} context context
<del> * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated
<del> */
<del> getConcatenationBailoutReason(module, context) {
<del> return undefined;
<del> }
<add> // TODO add getConcatenationBailoutReason to allow concatenation
<add> // but how to make it have a module id
<ide>
<ide> /**
<ide> * @param {NormalModule} module module for which the code should be generated | 1 |
Javascript | Javascript | introduce knowledge of freebsd jails | c15e81afdd5413f94df23eb82b6fc65875cb07fb | <ide><path>test/common.js
<ide> exports.tmpDir = path.join(exports.testDir, exports.tmpDirName);
<ide>
<ide> var opensslCli = null;
<ide>
<add>Object.defineProperty(exports, 'inFreeBSDJail', {
<add> get: function() {
<add> if (process.platform === 'freebsd' &&
<add> child_process.execSync('sysctl -n security.jail.jailed').toString() ===
<add> '1\n') {
<add> return true;
<add> } else {
<add> return false;
<add> }
<add> }
<add>});
<add>
<add>Object.defineProperty(exports, 'localhost_ipv4', {
<add> get: function() {
<add> if (exports.inFreeBSDJail) {
<add> // Jailed network interfaces are a bit special - since we need to jump
<add> // through loops, as well as this being an exception case, assume the
<add> // user will provide this instead.
<add> if (process.env.LOCALHOST)
<add> return process.env.LOCALHOST;
<add>
<add> console.error('Looks like we\'re in a FreeBSD Jail. ' +
<add> 'Please provide your default interface address ' +
<add> 'as LOCALHOST or expect some tests to fail.');
<add> }
<add> return '127.0.0.1';
<add> }
<add>});
<add>
<ide> // opensslCli defined lazily to reduce overhead of spawnSync
<ide> Object.defineProperty(exports, 'opensslCli', {get: function() {
<ide> if (opensslCli !== null) return opensslCli;
<ide><path>test/parallel/test-dgram-address.js
<ide> var assert = require('assert');
<ide> var dgram = require('dgram');
<ide>
<ide> // IPv4 Test
<del>var localhost_ipv4 = '127.0.0.1';
<add>var localhost_ipv4 = common.localhost_ipv4;
<ide> var socket_ipv4 = dgram.createSocket('udp4');
<ide> var family_ipv4 = 'IPv4';
<ide>
<ide><path>test/parallel/test-dgram-bind-default-address.js
<ide> var common = require('../common');
<ide> var assert = require('assert');
<ide> var dgram = require('dgram');
<ide>
<add>// skip test in FreeBSD jails since 0.0.0.0 will resolve to default interface
<add>if (common.inFreeBSDJail) {
<add> console.log('1..0 # Skipped: In a FreeBSD jail');
<add> process.exit();
<add>}
<add>
<ide> dgram.createSocket('udp4').bind(common.PORT + 0, common.mustCall(function() {
<ide> assert.equal(this.address().port, common.PORT + 0);
<ide> assert.equal(this.address().address, '0.0.0.0');
<ide><path>test/parallel/test-dgram-udp4.js
<ide> server = dgram.createSocket('udp4');
<ide> server.on('message', function(msg, rinfo) {
<ide> console.log('server got: ' + msg +
<ide> ' from ' + rinfo.address + ':' + rinfo.port);
<del> assert.strictEqual(rinfo.address, '127.0.0.1');
<add> assert.strictEqual(rinfo.address, common.localhost_ipv4);
<ide> assert.strictEqual(msg.toString(), message_to_send.toString());
<ide> server.send(msg, 0, msg.length, rinfo.port, rinfo.address);
<ide> });
<ide> server.on('listening', function() {
<ide> client.on('message', function(msg, rinfo) {
<ide> console.log('client got: ' + msg +
<ide> ' from ' + rinfo.address + ':' + address.port);
<del> assert.strictEqual(rinfo.address, '127.0.0.1');
<add> assert.strictEqual(rinfo.address, common.localhost_ipv4);
<ide> assert.strictEqual(rinfo.port, server_port);
<ide> assert.strictEqual(msg.toString(), message_to_send.toString());
<ide> client.close();
<ide><path>test/parallel/test-net-local-address-port.js
<ide> var conns = 0, conns_closed = 0;
<ide>
<ide> var server = net.createServer(function(socket) {
<ide> conns++;
<del> assert.equal('127.0.0.1', socket.localAddress);
<add> assert.equal(common.localhost_ipv4, socket.localAddress);
<ide> assert.equal(socket.localPort, common.PORT);
<ide> socket.on('end', function() {
<ide> server.close();
<ide> });
<ide> socket.resume();
<ide> });
<ide>
<del>server.listen(common.PORT, '127.0.0.1', function() {
<del> var client = net.createConnection(common.PORT, '127.0.0.1');
<add>server.listen(common.PORT, common.localhost_ipv4, function() {
<add> var client = net.createConnection(common.PORT, common.localhost_ipv4);
<ide> client.on('connect', function() {
<ide> client.end();
<ide> });
<ide><path>test/parallel/test-net-remote-address-port.js
<ide> var net = require('net');
<ide>
<ide> var conns = 0, conns_closed = 0;
<ide>
<del>var remoteAddrCandidates = [ '127.0.0.1'];
<add>var remoteAddrCandidates = [ common.localhost_ipv4 ];
<ide> if (common.hasIPv6) remoteAddrCandidates.push('::ffff:127.0.0.1');
<ide>
<ide> var remoteFamilyCandidates = ['IPv4'];
<ide><path>test/sequential/test-net-server-address.js
<ide> var assert = require('assert');
<ide> var net = require('net');
<ide>
<ide> // Test on IPv4 Server
<del>var localhost_ipv4 = '127.0.0.1';
<add>var localhost_ipv4 = common.localhost_ipv4;
<ide> var family_ipv4 = 'IPv4';
<ide> var server_ipv4 = net.createServer();
<ide> | 7 |
Java | Java | ensure xmleventdecoder compiles on jdk 9 and 11 | ab1b8dee58532f704bd7cc41365a63226f6e5fd3 | <ide><path>spring-web/src/main/java/org/springframework/http/codec/xml/XmlEventDecoder.java
<ide>
<ide> import java.io.InputStream;
<ide> import java.util.ArrayList;
<add>import java.util.Iterator;
<ide> import java.util.List;
<ide> import java.util.Map;
<ide> import java.util.function.Function;
<ide> * by other decoders which are registered by default.
<ide> *
<ide> * @author Arjen Poutsma
<add> * @author Sam Brannen
<ide> * @since 5.0
<ide> */
<ide> public class XmlEventDecoder extends AbstractDecoder<XMLEvent> {
<ide> public XmlEventDecoder() {
<ide>
<ide>
<ide> @Override
<del> @SuppressWarnings({"rawtypes", "unchecked"}) // on JDK 9 where XMLEventReader is Iterator<Object>
<add> @SuppressWarnings({"rawtypes", "unchecked", "cast"}) // on JDK 9 where XMLEventReader is Iterator<Object> instead of simply Iterator
<ide> public Flux<XMLEvent> decode(Publisher<DataBuffer> inputStream, ResolvableType elementType,
<ide> @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
<ide>
<ide> public Flux<XMLEvent> decode(Publisher<DataBuffer> inputStream, ResolvableType e
<ide> InputStream is = dataBuffer.asInputStream();
<ide> return () -> {
<ide> try {
<del> return inputFactory.createXMLEventReader(is);
<add> // Explicit cast to (Iterator) is necessary on JDK 9+ since XMLEventReader
<add> // now extends Iterator<Object> instead of simply Iterator
<add> return (Iterator) inputFactory.createXMLEventReader(is);
<ide> }
<ide> catch (XMLStreamException ex) {
<ide> throw Exceptions.propagate(ex); | 1 |
Javascript | Javascript | add test case | e2edfa72239a8c200abddb0ab0d19039f95648b3 | <ide><path>test/cases/side-effects/dynamic-reexports/index.js
<ide> import {
<ide> value2 as value2Checked
<ide> } from "./checked-export";
<ide> import Default2 from "./dynamic-reexport-default";
<add>import {
<add> value as valueMultipleSources,
<add> value2 as value2MultipleSources
<add>} from "./multiple-sources";
<ide>
<ide> it("should dedupe static reexport target", () => {
<ide> expect(valueStatic).toBe(42);
<ide> it("should handle default export correctly", () => {
<ide> expect(Default1).toBe(undefined);
<ide> expect(Default2).toBe("static");
<ide> });
<add>
<add>it("should handle multiple dynamic sources correctly", () => {
<add> expect(valueMultipleSources).toBe(42);
<add> expect(value2MultipleSources).toBe(42);
<add>});
<ide><path>test/cases/side-effects/dynamic-reexports/multiple-sources/a.js
<add>Object(exports).value = 42;
<ide><path>test/cases/side-effects/dynamic-reexports/multiple-sources/b.js
<add>Object(exports).value2 = 42;
<ide><path>test/cases/side-effects/dynamic-reexports/multiple-sources/index.js
<add>export * from "./module";
<add>export * from "./b";
<ide><path>test/cases/side-effects/dynamic-reexports/multiple-sources/module.js
<add>export * from "./a"; | 5 |
Javascript | Javascript | add newline to warning | 6846ef9fb8238dd1170f462926b3057bdc05eba5 | <ide><path>src/renderers/shared/fiber/ReactChildFiber.js
<ide> function throwOnInvalidObjectType(returnFiber : Fiber, newChild : Object) {
<ide> if (owner && typeof owner.tag === 'number') {
<ide> const name = getComponentName((owner : any));
<ide> if (name) {
<del> addendum += ' Check the render method of `' + name + '`.';
<add> addendum += '\n\nCheck the render method of `' + name + '`.';
<ide> }
<ide> }
<ide> } | 1 |
Ruby | Ruby | extend `search` tests | 3a361c139e9dad4874c17cb254a8657140354195 | <ide><path>Library/Homebrew/test/cmd/search_remote_tap_spec.rb
<ide> require "cmd/search"
<ide>
<ide> describe Homebrew do
<del> specify "#search_taps" do
<del> # Otherwise the tested method returns [], regardless of our stub
<del> ENV.delete("HOMEBREW_NO_GITHUB_API")
<add> describe "#search_taps" do
<add> before do
<add> ENV.delete("HOMEBREW_NO_GITHUB_API")
<add> end
<ide>
<del> json_response = {
<del> "items" => [
<del> {
<del> "path" => "Formula/some-formula.rb",
<del> "repository" => {
<del> "full_name" => "Homebrew/homebrew-foo",
<add> it "does not raise if `HOMEBREW_NO_GITHUB_API` is set" do
<add> ENV["HOMEBREW_NO_GITHUB_API"] = "1"
<add> expect(described_class.search_taps("some-formula")).to match([[], []])
<add> end
<add>
<add> it "does not raise if the network fails" do
<add> allow(GitHub).to receive(:open_api).and_raise(GitHub::Error)
<add>
<add> expect(described_class.search_taps("some-formula"))
<add> .to match([[], []])
<add> end
<add>
<add> it "returns Formulae and Casks separately" do
<add> json_response = {
<add> "items" => [
<add> {
<add> "path" => "Formula/some-formula.rb",
<add> "repository" => {
<add> "full_name" => "Homebrew/homebrew-foo",
<add> },
<add> },
<add> {
<add> "path" => "Casks/some-cask.rb",
<add> "repository" => {
<add> "full_name" => "Homebrew/homebrew-bar",
<add> },
<ide> },
<del> },
<del> ],
<del> }
<add> ],
<add> }
<ide>
<del> allow(GitHub).to receive(:open_api).and_yield(json_response)
<add> allow(GitHub).to receive(:open_api).and_yield(json_response)
<ide>
<del> expect(described_class.search_taps("some-formula"))
<del> .to match([["homebrew/foo/some-formula"], []])
<add> expect(described_class.search_taps("some-formula"))
<add> .to match([["homebrew/foo/some-formula"], ["homebrew/bar/some-cask"]])
<add> end
<ide> end
<ide> end
<ide><path>Library/Homebrew/test/cmd/search_spec.rb
<add>require "cmd/search"
<add>
<ide> describe "brew search", :integration_test do
<ide> before do
<ide> setup_test_formula "testball"
<ide> .and be_a_success
<ide> end
<ide> end
<add>
<add> describe "::query_regexp" do
<add> it "correctly parses a regex query" do
<add> expect(Homebrew.query_regexp("/^query$/")).to eq(/^query$/)
<add> end
<add>
<add> it "correctly converts a query string to a regex" do
<add> expect(Homebrew.query_regexp("query")).to eq(/.*query.*/i)
<add> end
<add>
<add> it "raises an error if the query is an invalid regex" do
<add> expect { Homebrew.query_regexp("/+/") }.to raise_error(/not a valid regex/)
<add> end
<add> end
<ide> end | 2 |
Ruby | Ruby | add simply bounce handling | 8eb239bd1a1350b151d57a639e589c68aed1f47a | <ide><path>lib/action_mailroom/mailbox.rb
<ide> class ActionMailroom::Mailbox
<ide> include Callbacks, Routing
<ide>
<ide> attr_reader :inbound_email
<del> delegate :mail, to: :inbound_email
<add> delegate :mail, :bounced!, to: :inbound_email
<ide>
<ide> def self.receive(inbound_email)
<ide> new(inbound_email).perform_processing
<ide> def process
<ide> def track_status_of_inbound_email
<ide> inbound_email.processing!
<ide> yield
<del> inbound_email.delivered!
<add> inbound_email.delivered! unless inbound_email.bounced?
<ide> rescue => exception
<ide> inbound_email.failed!
<ide> raise
<ide><path>test/unit/mailbox/state_test.rb
<ide> def process
<ide> end
<ide> end
<ide>
<add>class BouncingMailbox < ActionMailroom::Mailbox
<add> def process
<add> $processed = :bounced
<add> bounced!
<add> end
<add>end
<add>
<add>
<ide> class ActionMailroom::Mailbox::StateTest < ActiveSupport::TestCase
<ide> setup do
<ide> $processed = false
<ide> class ActionMailroom::Mailbox::StateTest < ActiveSupport::TestCase
<ide> assert @inbound_email.failed?
<ide> assert_equal :failure, $processed
<ide> end
<add>
<add> test "bounced inbound emails are not delivered" do
<add> BouncingMailbox.receive @inbound_email
<add> assert @inbound_email.bounced?
<add> assert_equal :bounced, $processed
<add> end
<ide> end | 2 |
Python | Python | add statistic calculation for provider's testing. | f08c2d58d135ddcb3ab617c2719ab8e8f9472cec | <ide><path>dev/stats/calculate_statistics_provider_testing_issues.py
<add>#!/usr/bin/env python3
<add># Licensed to the Apache Software Foundation (ASF) under one
<add># or more contributor license agreements. See the NOTICE file
<add># distributed with this work for additional information
<add># regarding copyright ownership. The ASF licenses this file
<add># to you under the Apache License, Version 2.0 (the
<add># "License"); you may not use this file except in compliance
<add># with 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,
<add># software distributed under the License is distributed on an
<add># "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
<add># KIND, either express or implied. See the License for the
<add># specific language governing permissions and limitations
<add># under the License.
<add>
<add>import logging
<add>import os
<add>import re
<add>import textwrap
<add>from pathlib import Path
<add>from typing import List, Set, Tuple
<add>
<add>import click
<add>from attr import dataclass
<add>from github import Github
<add>from github.Issue import Issue
<add>from rich.console import Console
<add>from tabulate import tabulate
<add>
<add>PROVIDER_TESTING_LABEL = "testing status"
<add>
<add>logger = logging.getLogger(__name__)
<add>
<add>console = Console(width=400, color_system="standard")
<add>
<add>MY_DIR_PATH = Path(os.path.dirname(__file__))
<add>SOURCE_DIR_PATH = MY_DIR_PATH / os.pardir / os.pardir
<add>
<add>
<add>@click.group(context_settings={'help_option_names': ['-h', '--help'], 'max_content_width': 500})
<add>def cli():
<add> ...
<add>
<add>
<add>option_table = click.option(
<add> "--table",
<add> is_flag=True,
<add> help="Print output as markdown table1",
<add>)
<add>
<add>option_github_token = click.option(
<add> "--github-token",
<add> type=str,
<add> required=True,
<add> help=textwrap.dedent(
<add> """
<add> Github token used to authenticate.
<add> You can set omit it if you have GITHUB_TOKEN env variable set
<add> Can be generated with:
<add> https://github.com/settings/tokens/new?description=Read%20Write%20isssues&scopes=repo"""
<add> ),
<add> envvar='GITHUB_TOKEN',
<add>)
<add>
<add>
<add>@dataclass
<add>class Stats:
<add> issue_number: int
<add> title: str
<add> num_providers: int
<add> num_issues: int
<add> tested_issues: int
<add> url: str
<add> users_involved: Set[str]
<add> users_commented: Set[str]
<add>
<add> def percent_tested(self) -> int:
<add> return int(100.0 * self.tested_issues / self.num_issues)
<add>
<add> def num_involved_users_who_commented(self) -> int:
<add> return len(self.users_involved.intersection(self.users_commented))
<add>
<add> def num_commenting_not_involved(self) -> int:
<add> return len(self.users_commented - self.users_involved)
<add>
<add> def percent_commented_among_involved(self) -> int:
<add> return int(100.0 * self.num_involved_users_who_commented() / len(self.users_involved))
<add>
<add> def __str__(self):
<add> return (
<add> f"#{self.issue_number}: {self.title}: Num providers: {self.num_providers}, "
<add> f"Issues: {self.num_issues}, Tested {self.tested_issues}, "
<add> f"Percent Tested: {self.percent_tested()}%, "
<add> f"Involved users: {len(self.users_involved)}, Commenting users: {len(self.users_commented)}, "
<add> f"Involved who commented: {self.num_involved_users_who_commented()}, "
<add> f"Extra people: {self.num_commenting_not_involved()}, "
<add> f"Percent commented: {self.percent_commented_among_involved()}%, "
<add> f"URL: {self.url}"
<add> )
<add>
<add>
<add>def get_users_from_content(content: str) -> Set[str]:
<add> users_match = re.findall(r"@\S*", content, re.MULTILINE)
<add> users: Set[str] = set()
<add> for user_match in users_match:
<add> users.add(user_match)
<add> return users
<add>
<add>
<add>def get_users_who_commented(issue: Issue) -> Set[str]:
<add> users: Set[str] = set()
<add> for comment in issue.get_comments():
<add> users.add("@" + comment.user.login)
<add> return users
<add>
<add>
<add>def get_stats(issue: Issue) -> Stats:
<add> content = issue.body
<add> return Stats(
<add> issue_number=issue.number,
<add> title=issue.title,
<add> num_providers=content.count("Provider "),
<add> num_issues=content.count("- [") - 1,
<add> tested_issues=content.count("[x]") + content.count("[X]") - 1,
<add> url=issue.html_url,
<add> users_involved=get_users_from_content(content),
<add> users_commented=get_users_who_commented(issue),
<add> )
<add>
<add>
<add>def stats_to_rows(stats_list: List[Stats]) -> List[Tuple]:
<add> total = Stats(
<add> issue_number=0,
<add> title="",
<add> num_providers=0,
<add> num_issues=0,
<add> tested_issues=0,
<add> url="",
<add> users_commented=set(),
<add> users_involved=set(),
<add> )
<add> rows: List[Tuple] = []
<add> for stat in stats_list:
<add> total.num_providers += stat.num_providers
<add> total.num_issues += stat.num_issues
<add> total.tested_issues += stat.tested_issues
<add> total.users_involved.update(stat.users_involved)
<add> total.users_commented.update(stat.users_commented)
<add> rows.append(
<add> (
<add> f"[{stat.issue_number}]({stat.url})",
<add> stat.num_providers,
<add> stat.num_issues,
<add> stat.tested_issues,
<add> stat.percent_tested(),
<add> len(stat.users_involved),
<add> len(stat.users_commented),
<add> stat.num_involved_users_who_commented(),
<add> stat.num_commenting_not_involved(),
<add> stat.percent_commented_among_involved(),
<add> )
<add> )
<add> rows.append(
<add> (
<add> "Total",
<add> total.num_providers,
<add> total.num_issues,
<add> total.tested_issues,
<add> total.percent_tested(),
<add> len(total.users_involved),
<add> len(total.users_commented),
<add> total.num_involved_users_who_commented(),
<add> total.num_commenting_not_involved(),
<add> total.percent_commented_among_involved(),
<add> )
<add> )
<add> return rows
<add>
<add>
<add>@option_github_token
<add>@option_table
<add>@cli.command()
<add>def provide_stats(github_token: str, table: bool):
<add> g = Github(github_token)
<add> repo = g.get_repo("apache/airflow")
<add> issues = repo.get_issues(labels=[PROVIDER_TESTING_LABEL], state="closed", sort="created", direction="asc")
<add> stats_list: List[Stats] = []
<add> for issue in issues:
<add> stat = get_stats(issue)
<add> if not table:
<add> print(stat)
<add> else:
<add> stats_list.append(stat)
<add> if table:
<add> rows = stats_to_rows(stats_list)
<add> print(
<add> tabulate(
<add> rows,
<add> headers=(
<add> "Issue",
<add> "Num Providers",
<add> "Num Issues",
<add> "Tested Issues",
<add> "Tested (%)",
<add> "Involved",
<add> "Commenting",
<add> "Involved who commented",
<add> "Extra people",
<add> "User response (%)",
<add> ),
<add> tablefmt="github",
<add> )
<add> )
<add>
<add>
<add>if __name__ == "__main__":
<add> cli() | 1 |
Ruby | Ruby | allow unscoping of left_outer_joins | f3d69c005291591220875efc48f82ea3909c6625 | <ide><path>activerecord/lib/active_record/relation/query_methods.rb
<ide> def reorder!(*args) # :nodoc:
<ide>
<ide> VALID_UNSCOPING_VALUES = Set.new([:where, :select, :group, :order, :lock,
<ide> :limit, :offset, :joins, :includes, :from,
<del> :readonly, :having])
<add> :readonly, :having, :left_outer_joins])
<ide>
<ide> # Removes an unwanted relation that is already defined on a chain of relations.
<ide> # This is useful when passing around chains of relations and would like to | 1 |
Text | Text | add two tests to challenge | ec8d2489290f6ca9e66bfeaaf3013e1305f8a708 | <ide><path>curriculum/challenges/english/10-coding-interview-prep/rosetta-code/abundant-deficient-and-perfect-number-classifications.md
<ide> dashedName: abundant-deficient-and-perfect-number-classifications
<ide>
<ide> # --description--
<ide>
<del>These define three classifications of positive integers based on their [proper divisors](<https://rosettacode.org/wiki/Proper divisors> "Proper divisors").
<add>These define three classifications of positive integers based on their proper divisors.
<ide>
<ide> Let $P(n)$ be the sum of the proper divisors of `n` where proper divisors are all positive integers `n` other than `n` itself.
<ide>
<ide> If `P(n) > n` then `n` is classed as `abundant`
<ide>
<ide> # --instructions--
<ide>
<del>Implement a function that calculates how many of the integers from `1` to `20,000` (inclusive) are in each of the three classes. Output the result as an array in the following format `[deficient, perfect, abundant]`.
<add>Implement a function that calculates how many of the integers from `1` to `num` (inclusive) are in each of the three classes. Output the result as an array in the following format `[deficient, perfect, abundant]`.
<ide>
<ide> # --hints--
<ide>
<ide> Implement a function that calculates how many of the integers from `1` to `20,00
<ide> assert(typeof getDPA === 'function');
<ide> ```
<ide>
<del>`getDPA` should return an array.
<add>`getDPA(5000)` should return an array.
<ide>
<ide> ```js
<del>assert(Array.isArray(getDPA(100)));
<add>assert(Array.isArray(getDPA(5000)));
<ide> ```
<ide>
<del>`getDPA` return value should have a length of 3.
<add>`getDPA(5000)` return array should have a length of `3`.
<ide>
<ide> ```js
<del>assert(getDPA(100).length === 3);
<add>assert(getDPA(5000).length === 3);
<ide> ```
<ide>
<del>`getDPA(20000)` should equal [15043, 4, 4953]
<add>`getDPA(5000)` should return `[3758, 3, 1239]`.
<ide>
<ide> ```js
<del>assert.deepEqual(getDPA(20000), solution);
<add>assert.deepEqual(getDPA(5000), [3758, 3, 1239]);
<ide> ```
<ide>
<del># --seed--
<add>`getDPA(10000)` should return `[7508, 4, 2488]`.
<add>
<add>```js
<add>assert.deepEqual(getDPA(10000), [7508, 4, 2488]);
<add>```
<ide>
<del>## --after-user-code--
<add>`getDPA(20000)` should return `[15043, 4, 4953]`.
<ide>
<ide> ```js
<del>const solution = [15043, 4, 4953];
<add>assert.deepEqual(getDPA(20000), [15043, 4, 4953]);
<ide> ```
<ide>
<add># --seed--
<add>
<ide> ## --seed-contents--
<ide>
<ide> ```js | 1 |
Ruby | Ruby | remove 10.9 warning | ada07d07bf997341444949030478a967e7bf42db | <ide><path>Library/Homebrew/cmd/doctor.rb
<ide> def check_for_osx_gcc_installer
<ide> end
<ide> end
<ide>
<del>def check_for_unsupported_osx
<del> if MacOS.version > 10.8 then <<-EOS.undent
<del> You are using Mac OS X #{MacOS.version}.
<del> We do not yet provide support for this (unreleased) version.
<del> EOS
<del> end
<del>end
<del>
<ide> def check_for_stray_developer_directory
<ide> # if the uninstaller script isn't there, it's a good guess neither are
<ide> # any troublesome leftover Xcode files | 1 |
Text | Text | add missing middleware methods to guide | 1c54862c82f8977fa90f8d8da748df87c724c7a1 | <ide><path>guides/source/rails_on_rack.md
<ide> You can swap an existing middleware in the middleware stack using `config.middle
<ide> config.middleware.swap ActionDispatch::ShowExceptions, Lifo::ShowExceptions
<ide> ```
<ide>
<add>#### Moving a Middleware
<add>
<add>You can move an existing middleware in the middleware stack using `config.middleware.move_before` and `config.middleware.move_after`.
<add>
<add>```ruby
<add># config/application.rb
<add>
<add># Move ActionDispatch::ShowExceptions to before Lifo::ShowExceptions
<add>config.middleware.move_before Lifo::ShowExceptions, ActionDispatch::ShowExceptions
<add>```
<add>
<add>```ruby
<add># config/application.rb
<add>
<add># Move ActionDispatch::ShowExceptions to after Lifo::ShowExceptions
<add>config.middleware.move_after Lifo::ShowExceptions, ActionDispatch::ShowExceptions
<add>```
<add>
<ide> #### Deleting a Middleware
<ide>
<ide> Add the following lines to your application configuration: | 1 |
Text | Text | fix incorrect changelog entry for 16.3.3 | 41f6d8cc7acb13d31b05783b958fa993d67cae68 | <ide><path>CHANGELOG.md
<ide>
<ide> * The [new host config shape](https://github.com/facebook/react/blob/c601f7a64640290af85c9f0e33c78480656b46bc/packages/react-noop-renderer/src/createReactNoop.js#L82-L285) is flat and doesn't use nested objects. ([@gaearon](https://github.com/gaearon) in [#12792](https://github.com/facebook/react/pull/12792))
<ide>
<add>## 16.3.3 (August 1, 2018)
<add>
<add>### React DOM Server
<add>
<add>* Fix a [potential XSS vulnerability when the attacker controls an attribute name](https://reactjs.org/blog/2018/08/01/react-v-16-4-2.html) (`CVE-2018-6341`). This fix is available in the latest `[email protected]`, as well as in previous affected minor versions: `[email protected]`, `[email protected]`, `[email protected]`, and `[email protected]`. ([@gaearon](https://github.com/gaearon) in [#13302](https://github.com/facebook/react/pull/13302))
<add>
<ide> ## 16.3.2 (April 16, 2018)
<ide>
<ide> ### React
<ide>
<ide> * Add a UMD build. ([@bvaughn](https://github.com/bvaughn) in [#12594](https://github.com/facebook/react/pull/12594))
<ide>
<del>## 16.3.2 (August 1, 2018)
<del>
<del>### React DOM Server
<del>
<del>* Fix a [potential XSS vulnerability when the attacker controls an attribute name](https://reactjs.org/blog/2018/08/01/react-v-16-4-2.html) (`CVE-2018-6341`). This fix is available in the latest `[email protected]`, as well as in previous affected minor versions: `[email protected]`, `[email protected]`, `[email protected]`, and `[email protected]`. ([@gaearon](https://github.com/gaearon) in [#13302](https://github.com/facebook/react/pull/13302))
<del>
<ide> ## 16.3.1 (April 3, 2018)
<ide>
<ide> ### React | 1 |
Ruby | Ruby | drop a temporary table before end of a test case | 445696c0ca1b5fea1066677e0a9cb13ad0fe30e1 | <ide><path>railties/test/json_params_parsing_test.rb
<ide> require "active_record"
<ide>
<ide> class JsonParamsParsingTest < ActionDispatch::IntegrationTest
<del> test "prevent null query" do
<add> def test_prevent_null_query
<ide> # Make sure we have data to find
<ide> klass = Class.new(ActiveRecord::Base) do
<ide> def self.name; 'Foo'; end
<ide> def self.name; 'Foo'; end
<ide> [[[nil]], [[[nil]]]].each do |data|
<ide> assert_nil app.call(make_env({ 't' => data }))
<ide> end
<add> ensure
<add> klass.connection.drop_table("foos")
<ide> end
<ide>
<ide> private | 1 |
Java | Java | convert view to @reactprop | bf598647d2ff7aad1d29c7c5d28d816c01941c1c | <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/BaseViewManager.java
<add>// Copyright 2004-present Facebook. All Rights Reserved.
<add>
<add>package com.facebook.react.uimanager;
<add>
<add>import android.graphics.Color;
<add>import android.os.Build;
<add>import android.view.View;
<add>
<add>import com.facebook.react.bridge.ReadableMap;
<add>
<add>/**
<add> * Base class that should be suitable for the majority of subclasses of {@link ViewManager}.
<add> * It provides support for base view properties such as backgroundColor, opacity, etc.
<add> */
<add>public abstract class BaseViewManager<T extends View, C extends ReactShadowNode>
<add> extends ViewManager<T, C> {
<add>
<add> private static final String PROP_BACKGROUND_COLOR = ViewProps.BACKGROUND_COLOR;
<add> private static final String PROP_DECOMPOSED_MATRIX = "decomposedMatrix";
<add> private static final String PROP_DECOMPOSED_MATRIX_ROTATE = "rotate";
<add> private static final String PROP_DECOMPOSED_MATRIX_SCALE_X = "scaleX";
<add> private static final String PROP_DECOMPOSED_MATRIX_SCALE_Y = "scaleY";
<add> private static final String PROP_DECOMPOSED_MATRIX_TRANSLATE_X = "translateX";
<add> private static final String PROP_DECOMPOSED_MATRIX_TRANSLATE_Y = "translateY";
<add> private static final String PROP_OPACITY = "opacity";
<add> private static final String PROP_RENDER_TO_HARDWARE_TEXTURE = "renderToHardwareTextureAndroid";
<add> private static final String PROP_ACCESSIBILITY_LABEL = "accessibilityLabel";
<add> private static final String PROP_ACCESSIBILITY_COMPONENT_TYPE = "accessibilityComponentType";
<add> private static final String PROP_ACCESSIBILITY_LIVE_REGION = "accessibilityLiveRegion";
<add> private static final String PROP_IMPORTANT_FOR_ACCESSIBILITY = "importantForAccessibility";
<add>
<add> // DEPRECATED
<add> private static final String PROP_ROTATION = "rotation";
<add> private static final String PROP_SCALE_X = "scaleX";
<add> private static final String PROP_SCALE_Y = "scaleY";
<add> private static final String PROP_TRANSLATE_X = "translateX";
<add> private static final String PROP_TRANSLATE_Y = "translateY";
<add>
<add> /**
<add> * Used to locate views in end-to-end (UI) tests.
<add> */
<add> public static final String PROP_TEST_ID = "testID";
<add>
<add>
<add> @ReactProp(name = PROP_BACKGROUND_COLOR, defaultInt = Color.TRANSPARENT, customType = "Color")
<add> public void setBackgroundColor(T view, int backgroundColor) {
<add> view.setBackgroundColor(backgroundColor);
<add> }
<add>
<add> @ReactProp(name = PROP_DECOMPOSED_MATRIX)
<add> public void setDecomposedMatrix(T view, ReadableMap decomposedMatrix) {
<add> if (decomposedMatrix == null) {
<add> resetTransformMatrix(view);
<add> } else {
<add> setTransformMatrix(view, decomposedMatrix);
<add> }
<add> }
<add>
<add> @ReactProp(name = PROP_OPACITY, defaultFloat = 1.f)
<add> public void setOpacity(T view, float opacity) {
<add> view.setAlpha(opacity);
<add> }
<add>
<add> @ReactProp(name = PROP_RENDER_TO_HARDWARE_TEXTURE)
<add> public void setRenderToHardwareTexture(T view, boolean useHWTexture) {
<add> view.setLayerType(useHWTexture ? View.LAYER_TYPE_HARDWARE : View.LAYER_TYPE_NONE, null);
<add> }
<add>
<add> @ReactProp(name = PROP_TEST_ID)
<add> public void setTestId(T view, String testId) {
<add> view.setTag(testId);
<add> }
<add>
<add> @ReactProp(name = PROP_ACCESSIBILITY_LABEL)
<add> public void setAccessibilityLabel(T view, String accessibilityLabel) {
<add> view.setContentDescription(accessibilityLabel);
<add> }
<add>
<add> @ReactProp(name = PROP_ACCESSIBILITY_COMPONENT_TYPE)
<add> public void setAccessibilityComponentType(T view, String accessibilityComponentType) {
<add> AccessibilityHelper.updateAccessibilityComponentType(view, accessibilityComponentType);
<add> }
<add>
<add> @ReactProp(name = PROP_IMPORTANT_FOR_ACCESSIBILITY)
<add> public void setImportantForAccessibility(T view, String importantForAccessibility) {
<add> if (importantForAccessibility == null || importantForAccessibility.equals("auto")) {
<add> view.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_AUTO);
<add> } else if (importantForAccessibility.equals("yes")) {
<add> view.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
<add> } else if (importantForAccessibility.equals("no")) {
<add> view.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
<add> } else if (importantForAccessibility.equals("no-hide-descendants")) {
<add> view.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
<add> }
<add> }
<add>
<add> @Deprecated
<add> @ReactProp(name = PROP_ROTATION)
<add> public void setRotation(T view, float rotation) {
<add> view.setRotation(rotation);
<add> }
<add>
<add> @Deprecated
<add> @ReactProp(name = PROP_SCALE_X, defaultFloat = 1f)
<add> public void setScaleX(T view, float scaleX) {
<add> view.setScaleX(scaleX);
<add> }
<add>
<add> @Deprecated
<add> @ReactProp(name = PROP_SCALE_Y, defaultFloat = 1f)
<add> public void setScaleY(T view, float scaleY) {
<add> view.setScaleY(scaleY);
<add> }
<add>
<add> @Deprecated
<add> @ReactProp(name = PROP_TRANSLATE_X, defaultFloat = 1f)
<add> public void setTranslateX(T view, float translateX) {
<add> view.setTranslationX(translateX);
<add> }
<add>
<add> @Deprecated
<add> @ReactProp(name = PROP_TRANSLATE_Y, defaultFloat = 1f)
<add> public void setTranslateY(T view, float translateY) {
<add> view.setTranslationY(translateY);
<add> }
<add>
<add> @ReactProp(name = PROP_ACCESSIBILITY_LIVE_REGION)
<add> public void setAccessibilityLiveRegion(T view, String liveRegion) {
<add> if (Build.VERSION.SDK_INT >= 19) {
<add> if (liveRegion == null || liveRegion.equals("none")) {
<add> view.setAccessibilityLiveRegion(View.ACCESSIBILITY_LIVE_REGION_NONE);
<add> } else if (liveRegion.equals("polite")) {
<add> view.setAccessibilityLiveRegion(View.ACCESSIBILITY_LIVE_REGION_POLITE);
<add> } else if (liveRegion.equals("assertive")) {
<add> view.setAccessibilityLiveRegion(View.ACCESSIBILITY_LIVE_REGION_ASSERTIVE);
<add> }
<add> }
<add> }
<add>
<add> private static void setTransformMatrix(View view, ReadableMap matrix) {
<add> view.setTranslationX(PixelUtil.toPixelFromDIP(
<add> (float) matrix.getDouble(PROP_DECOMPOSED_MATRIX_TRANSLATE_X)));
<add> view.setTranslationY(PixelUtil.toPixelFromDIP(
<add> (float) matrix.getDouble(PROP_DECOMPOSED_MATRIX_TRANSLATE_Y)));
<add> view.setRotation(
<add> (float) matrix.getDouble(PROP_DECOMPOSED_MATRIX_ROTATE));
<add> view.setScaleX(
<add> (float) matrix.getDouble(PROP_DECOMPOSED_MATRIX_SCALE_X));
<add> view.setScaleY(
<add> (float) matrix.getDouble(PROP_DECOMPOSED_MATRIX_SCALE_Y));
<add> }
<add>
<add> private static void resetTransformMatrix(View view) {
<add> view.setTranslationX(PixelUtil.toPixelFromDIP(0));
<add> view.setTranslationY(PixelUtil.toPixelFromDIP(0));
<add> view.setRotation(0);
<add> view.setScaleX(1);
<add> view.setScaleY(1);
<add> }
<add>}
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/BaseViewPropertyApplicator.java
<ide>
<ide> /**
<ide> * Takes common view properties from JS and applies them to a given {@link View}.
<add> *
<add> * TODO(krzysztof): Blow away this class once refactoring is complete
<ide> */
<ide> public class BaseViewPropertyApplicator {
<ide>
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/SimpleViewManager.java
<ide> import android.view.View;
<ide>
<ide> /**
<del> * A partial implementation of {@link ViewManager} that applies common properties such as background
<del> * color, opacity and CSS layout. Implementations should make sure to call
<del> * {@code super.updateView()} in order for these properties to be applied.
<add> * Common base class for most of the {@link ViewManager}s. It provides support for most common
<add> * properties through extending {@link BaseViewManager}. It also reduces boilerplate by specifying
<add> * the type of shadow node to be {@link ReactShadowNode} and providing default, empty implementation
<add> * for some of the methods of {@link ViewManager} interface.
<ide> *
<ide> * @param <T> the view handled by this manager
<ide> */
<del>public abstract class SimpleViewManager<T extends View> extends ViewManager<T, ReactShadowNode> {
<add>public abstract class SimpleViewManager<T extends View> extends
<add> BaseViewManager<T, ReactShadowNode> {
<ide>
<ide> @Override
<ide> public ReactShadowNode createCSSNodeInstance() {
<ide> return new ReactShadowNode();
<ide> }
<ide>
<del> @Override
<del> public void updateView(T root, CatalystStylesDiffMap props) {
<del> BaseViewPropertyApplicator.applyCommonViewProperties(root, props);
<del> }
<del>
<ide> @Override
<ide> public void updateExtraData(T root, Object extraData) {
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIProp.java
<ide> * @UIProp(UIProp.Type.BOOLEAN) public static final String PROP_FOO = "foo";
<ide> * @UIProp(UIProp.Type.STRING) public static final String PROP_BAR = "bar";
<ide> * }
<add> *
<add> * TODO(krzysztof): Kill this class once @ReactProp refactoring is done
<ide> */
<ide> @Target(ElementType.FIELD)
<ide> @Retention(RUNTIME)
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewGroupManager.java
<ide> * Class providing children management API for view managers of classes extending ViewGroup.
<ide> */
<ide> public abstract class ViewGroupManager <T extends ViewGroup>
<del> extends ViewManager<T, ReactShadowNode> {
<add> extends BaseViewManager<T, ReactShadowNode> {
<ide>
<ide> @Override
<ide> public ReactShadowNode createCSSNodeInstance() {
<ide> return new ReactShadowNode();
<ide> }
<ide>
<del> @Override
<del> public void updateView(T root, CatalystStylesDiffMap props) {
<del> BaseViewPropertyApplicator.applyCommonViewProperties(root, props);
<del> }
<del>
<ide> @Override
<ide> public void updateExtraData(T root, Object extraData) {
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewManager.java
<ide> import com.facebook.react.bridge.ReadableMap;
<ide> import com.facebook.react.common.MapBuilder;
<ide> import com.facebook.react.common.annotations.VisibleForTesting;
<del>import com.facebook.react.uimanager.BaseViewPropertyApplicator;
<ide> import com.facebook.react.uimanager.CatalystStylesDiffMap;
<ide> import com.facebook.react.uimanager.PixelUtil;
<ide> import com.facebook.react.uimanager.PointerEvents;
<add>import com.facebook.react.uimanager.ReactProp;
<add>import com.facebook.react.uimanager.ReactPropGroup;
<ide> import com.facebook.react.uimanager.ThemedReactContext;
<del>import com.facebook.react.uimanager.UIProp;
<ide> import com.facebook.react.uimanager.ViewGroupManager;
<ide> import com.facebook.react.uimanager.ViewProps;
<ide>
<ide> public class ReactViewManager extends ViewGroupManager<ReactViewGroup> {
<ide> private static final int[] SPACING_TYPES = {
<ide> Spacing.ALL, Spacing.LEFT, Spacing.RIGHT, Spacing.TOP, Spacing.BOTTOM,
<ide> };
<del> private static final String[] PROPS_BORDER_COLOR = {
<del> "borderColor", "borderLeftColor", "borderRightColor", "borderTopColor", "borderBottomColor"
<del> };
<ide> private static final int CMD_HOTSPOT_UPDATE = 1;
<ide> private static final int CMD_SET_PRESSED = 2;
<ide> private static final int[] sLocationBuf = new int[2];
<ide>
<del> @UIProp(UIProp.Type.STRING) public static final String PROP_ACCESSIBLE = "accessible";
<del> @UIProp(UIProp.Type.NUMBER) public static final String PROP_BORDER_RADIUS = "borderRadius";
<del> @UIProp(UIProp.Type.STRING) public static final String PROP_BORDER_STYLE = "borderStyle";
<del> @UIProp(UIProp.Type.STRING) public static final String PROP_POINTER_EVENTS = "pointerEvents";
<del> @UIProp(UIProp.Type.MAP) public static final String PROP_NATIVE_BG = "nativeBackgroundAndroid";
<add> @ReactProp(name = "accessible")
<add> public void setAccessible(ReactViewGroup view, boolean accessible) {
<add> view.setFocusable(accessible);
<add> }
<ide>
<del> @Override
<del> public String getName() {
<del> return REACT_CLASS;
<add> @ReactProp(name = "borderRadius")
<add> public void setBorderRadius(ReactViewGroup view, float borderRadius) {
<add> view.setBorderRadius(PixelUtil.toPixelFromDIP(borderRadius));
<ide> }
<ide>
<del> @Override
<del> public ReactViewGroup createViewInstance(ThemedReactContext context) {
<del> return new ReactViewGroup(context);
<add> @ReactProp(name = "borderStyle")
<add> public void setBorderStyle(ReactViewGroup view, @Nullable String borderStyle) {
<add> view.setBorderStyle(borderStyle);
<ide> }
<ide>
<del> @Override
<del> public Map<String, String> getNativeProps() {
<del> Map<String, String> nativeProps = super.getNativeProps();
<del> Map<String, UIProp.Type> baseProps = BaseViewPropertyApplicator.getCommonProps();
<del> for (Map.Entry<String, UIProp.Type> entry : baseProps.entrySet()) {
<del> nativeProps.put(entry.getKey(), entry.getValue().toString());
<add> @ReactProp(name = "pointerEvents")
<add> public void setPointerEvents(ReactViewGroup view, @Nullable String pointerEventsStr) {
<add> if (pointerEventsStr != null) {
<add> PointerEvents pointerEvents =
<add> PointerEvents.valueOf(pointerEventsStr.toUpperCase(Locale.US).replace("-", "_"));
<add> view.setPointerEvents(pointerEvents);
<ide> }
<del> for (int i = 0; i < SPACING_TYPES.length; i++) {
<del> nativeProps.put(ViewProps.BORDER_WIDTHS[i], UIProp.Type.NUMBER.toString());
<del> nativeProps.put(PROPS_BORDER_COLOR[i], UIProp.Type.STRING.toString());
<del> }
<del> return nativeProps;
<ide> }
<ide>
<del> @Override
<del> public void updateView(ReactViewGroup view, CatalystStylesDiffMap props) {
<del> super.updateView(view, props);
<del> ReactClippingViewGroupHelper.applyRemoveClippedSubviewsProperty(view, props);
<del>
<del> // Border widths
<del> for (int i = 0; i < SPACING_TYPES.length; i++) {
<del> String key = ViewProps.BORDER_WIDTHS[i];
<del> if (props.hasKey(key)) {
<del> float width = props.getFloat(key, CSSConstants.UNDEFINED);
<del> if (!CSSConstants.isUndefined(width)) {
<del> width = PixelUtil.toPixelFromDIP(width);
<del> }
<del> view.setBorderWidth(SPACING_TYPES[i], width);
<del> }
<del> }
<add> @ReactProp(name = "nativeBackgroundAndroid")
<add> public void setNativeBackground(ReactViewGroup view, @Nullable ReadableMap bg) {
<add> view.setTranslucentBackgroundDrawable(bg == null ?
<add> null : ReactDrawableHelper.createDrawableFromJSDescription(view.getContext(), bg));
<add> }
<ide>
<del> // Border colors
<del> for (int i = 0; i < SPACING_TYPES.length; i++) {
<del> String key = PROPS_BORDER_COLOR[i];
<del> if (props.hasKey(key)) {
<del> float color = CSSConstants.UNDEFINED;
<del> if (!props.isNull(PROPS_BORDER_COLOR[i])) {
<del> // Check CatalystStylesDiffMap#getColorInt() to see why this is needed
<del> int colorInt = props.getInt(PROPS_BORDER_COLOR[i], Color.TRANSPARENT);
<del> color = colorInt;
<del> }
<del> view.setBorderColor(SPACING_TYPES[i], color);
<del> }
<add> @ReactProp(name = ViewProps.BORDER_WIDTH, defaultFloat = CSSConstants.UNDEFINED)
<add> public void setBorderWidth(ReactViewGroup view, float width) {
<add> if (!CSSConstants.isUndefined(width)) {
<add> width = PixelUtil.toPixelFromDIP(width);
<ide> }
<add> view.setBorderWidth(Spacing.ALL, width);
<add> }
<ide>
<del> // Border radius
<del> if (props.hasKey(PROP_BORDER_RADIUS)) {
<del> view.setBorderRadius(PixelUtil.toPixelFromDIP(props.getFloat(PROP_BORDER_RADIUS, 0.0f)));
<del> }
<add> @ReactProp(name = ReactClippingViewGroupHelper.PROP_REMOVE_CLIPPED_SUBVIEWS)
<add> public void setRemoveClippedSubviews(ReactViewGroup view, boolean removeClippedSubviews) {
<add> view.setRemoveClippedSubviews(removeClippedSubviews);
<add> }
<ide>
<del> if (props.hasKey(PROP_BORDER_STYLE)) {
<del> view.setBorderStyle(props.getString(PROP_BORDER_STYLE));
<del> }
<add> @ReactProp(name = ViewProps.NEEDS_OFFSCREEN_ALPHA_COMPOSITING)
<add> public void setNeedsOffscreenAlphaCompositing(
<add> ReactViewGroup view,
<add> boolean needsOffscreenAlphaCompositing) {
<add> view.setNeedsOffscreenAlphaCompositing(needsOffscreenAlphaCompositing);
<add> }
<ide>
<del> if (props.hasKey(PROP_POINTER_EVENTS)) {
<del> String pointerEventsStr = props.getString(PROP_POINTER_EVENTS);
<del> if (pointerEventsStr != null) {
<del> PointerEvents pointerEvents =
<del> PointerEvents.valueOf(pointerEventsStr.toUpperCase(Locale.US).replace("-", "_"));
<del> view.setPointerEvents(pointerEvents);
<del> }
<add> @ReactPropGroup(names = {
<add> ViewProps.BORDER_WIDTH,
<add> ViewProps.BORDER_LEFT_WIDTH,
<add> ViewProps.BORDER_RIGHT_WIDTH,
<add> ViewProps.BORDER_TOP_WIDTH,
<add> ViewProps.BORDER_BOTTOM_WIDTH,
<add> }, defaultFloat = CSSConstants.UNDEFINED)
<add> public void setBorderWidth(ReactViewGroup view, int index, float width) {
<add> if (!CSSConstants.isUndefined(width)) {
<add> width = PixelUtil.toPixelFromDIP(width);
<ide> }
<add> view.setBorderWidth(SPACING_TYPES[index], width);
<add> }
<ide>
<del> // Native background
<del> if (props.hasKey(PROP_NATIVE_BG)) {
<del> ReadableMap map = props.getMap(PROP_NATIVE_BG);
<del> view.setTranslucentBackgroundDrawable(map == null ?
<del> null : ReactDrawableHelper.createDrawableFromJSDescription(view.getContext(), map));
<del> }
<add> @ReactPropGroup(names = {
<add> "borderColor", "borderLeftColor", "borderRightColor", "borderTopColor", "borderBottomColor"
<add> }, customType = "Color")
<add> public void setBorderColor(ReactViewGroup view, int index, Integer color) {
<add> view.setBorderColor(
<add> SPACING_TYPES[index],
<add> color == null ? CSSConstants.UNDEFINED : (float) color);
<add> }
<ide>
<del> if (props.hasKey(PROP_ACCESSIBLE)) {
<del> view.setFocusable(props.getBoolean(PROP_ACCESSIBLE, false));
<del> }
<add> @Override
<add> public String getName() {
<add> return REACT_CLASS;
<add> }
<ide>
<del> if (props.hasKey(ViewProps.NEEDS_OFFSCREEN_ALPHA_COMPOSITING)) {
<del> view.setNeedsOffscreenAlphaCompositing(
<del> props.getBoolean(ViewProps.NEEDS_OFFSCREEN_ALPHA_COMPOSITING, false));
<del> }
<add> @Override
<add> public ReactViewGroup createViewInstance(ThemedReactContext context) {
<add> return new ReactViewGroup(context);
<ide> }
<ide>
<ide> @Override | 6 |
Mixed | Javascript | add `getplayer` method to video.js. | a15e616a453006d2e8038efc98eef71bee268085 | <ide><path>docs/guides/setup.md
<ide> However, using an `id` attribute isn't always practical; so, the `videojs` funct
<ide> videojs(document.querySelector('.video-js'));
<ide> ```
<ide>
<add>### Getting References to Players
<add>
<add>Once players are created, Video.js keeps track of them internally. There are a few ways to get references to pre-existing players.
<add>
<add>#### Using `videojs`
<add>
<add>Calling `videojs()` with the ID of element of an already-existing player will return that player and will not create another one.
<add>
<add>If there is no player matching the argument, it will attempt to create one.
<add>
<add>#### Using `videojs.getPlayer()`
<add>
<add>Sometimes, you want to get a reference to a player without the potential side effects of calling `videojs()`. This can be acheived by calling `videojs.getPlayer()` with either a string matching the element's ID or the element itself.
<add>
<add>#### Using `videojs.getPlayers()` or `videojs.players`
<add>
<add>The `videojs.players` property exposes all known players. The method, `videojs.getPlayers()` simply returns the same object.
<add>
<add>Players are stored on this object with keys matching their IDs.
<add>
<add>> **Note:** A player created from an element without an ID will be assigned an automatically-generated ID.
<add>
<ide> ## Options
<ide>
<ide> > **Note:** This guide only covers how to pass options during player setup. For a complete reference on _all_ available options, see the [options guide](/docs/guides/options.md).
<ide><path>src/js/video.js
<ide> if (typeof HTMLVideoElement === 'undefined' && Dom.isReal()) {
<ide> document.createElement('video-js');
<ide> }
<ide>
<add>/**
<add> * Normalize an `id` value by trimming off a leading `#`
<add> *
<add> * @param {string} id
<add> * A string, maybe with a leading `#`.
<add> *
<add> * @returns {string}
<add> * The string, without any leading `#`.
<add> */
<add>const normalizeId = (id) => id.indexOf('#') === 0 ? id.slice(1) : id;
<add>
<ide> /**
<ide> * Doubles as the main function for users to create a player instance and also
<ide> * the main library object.
<ide> if (typeof HTMLVideoElement === 'undefined' && Dom.isReal()) {
<ide> * A player instance
<ide> */
<ide> function videojs(id, options, ready) {
<del> let tag;
<add> let player = videojs.getPlayer(id);
<ide>
<del> // Allow for element or ID to be passed in
<del> // String ID
<del> if (typeof id === 'string') {
<del> const players = videojs.getPlayers();
<del>
<del> // Adjust for jQuery ID syntax
<del> if (id.indexOf('#') === 0) {
<del> id = id.slice(1);
<add> if (player) {
<add> if (options) {
<add> log.warn(`Player "${id}" is already initialised. Options will not be applied.`);
<ide> }
<del>
<del> // If a player instance has already been created for this ID return it.
<del> if (players[id]) {
<del>
<del> // If options or ready function are passed, warn
<del> if (options) {
<del> log.warn(`Player "${id}" is already initialised. Options will not be applied.`);
<del> }
<del>
<del> if (ready) {
<del> players[id].ready(ready);
<del> }
<del>
<del> return players[id];
<add> if (ready) {
<add> player.ready(ready);
<ide> }
<del>
<del> // Otherwise get element for ID
<del> tag = Dom.$('#' + id);
<del>
<del> // ID is a media element
<del> } else {
<del> tag = id;
<add> return player;
<ide> }
<ide>
<del> // Check for a useable element
<del> // re: nodeName, could be a box div also
<del> if (!tag || !tag.nodeName) {
<del> throw new TypeError('The element or ID supplied is not valid. (videojs)');
<del> }
<add> const el = (typeof id === 'string') ? Dom.$('#' + normalizeId(id)) : id;
<ide>
<del> // Element may have a player attr referring to an already created player instance.
<del> // If so return that otherwise set up a new player below
<del> if (tag.player || Player.players[tag.playerId]) {
<del> return tag.player || Player.players[tag.playerId];
<add> if (!Dom.isEl(el)) {
<add> throw new TypeError('The element or ID supplied is not valid. (videojs)');
<ide> }
<ide>
<del> // Check if element is included in the DOM
<del> if (Dom.isEl(tag) && !document.body.contains(tag)) {
<add> if (!document.body.contains(el)) {
<ide> log.warn('The element supplied is not included in the DOM');
<ide> }
<ide>
<ide> options = options || {};
<ide>
<del> videojs.hooks('beforesetup').forEach(function(hookFunction) {
<del> const opts = hookFunction(tag, mergeOptions(options));
<add> videojs.hooks('beforesetup').forEach((hookFunction) => {
<add> const opts = hookFunction(el, mergeOptions(options));
<ide>
<ide> if (!isObject(opts) || Array.isArray(opts)) {
<ide> log.error('please return an object in beforesetup hooks');
<ide> function videojs(id, options, ready) {
<ide> options = mergeOptions(options, opts);
<ide> });
<ide>
<add> // We get the current "Player" component here in case an integration has
<add> // replaced it with a custom player.
<ide> const PlayerComponent = Component.getComponent('Player');
<del> // If not, set up a new player
<del> const player = new PlayerComponent(tag, options, ready);
<add>
<add> player = new PlayerComponent(el, options, ready);
<ide>
<ide> videojs.hooks('setup').forEach((hookFunction) => hookFunction(player));
<ide>
<ide> videojs.options = Player.prototype.options_;
<ide> */
<ide> videojs.getPlayers = () => Player.players;
<ide>
<add>/**
<add> * Get a single player based on an ID or DOM element.
<add> *
<add> * This is useful if you want to check if an element or ID has an associated
<add> * Video.js player, but not create one if it doesn't.
<add> *
<add> * @param {string|Element} id
<add> * An HTML element - `<video>`, `<audio>`, or `<video-js>` -
<add> * or a string matching the `id` of such an element.
<add> *
<add> * @returns {Player|undefined}
<add> * A player instance or `undefined` if there is no player instance
<add> * matching the argument.
<add> */
<add>videojs.getPlayer = (id) => {
<add> const players = Player.players;
<add>
<add> if (typeof id === 'string') {
<add> return players[normalizeId(id)];
<add> }
<add>
<add> if (Dom.isEl(id)) {
<add> const {player, playerId} = id;
<add>
<add> // Element may have a `player` property referring to an already created
<add> // player instance. If so, return that.
<add> if (player || players[playerId]) {
<add> return player || players[playerId];
<add> }
<add> }
<add>};
<add>
<ide> /**
<ide> * Expose players object.
<ide> *
<ide><path>test/unit/video.test.js
<ide> QUnit.test('should create a new tag for movingMediaElementInDOM', function(asser
<ide> Html5.nativeSourceHandler.canPlayType = oldCPT;
<ide> });
<ide>
<add>QUnit.test('getPlayer', function(assert) {
<add> const fixture = document.getElementById('qunit-fixture');
<add>
<add> fixture.innerHTML += '<video-js id="test_vid_id"></video-js>';
<add>
<add> assert.notOk(videojs.getPlayer('test_vid_id'), 'no player was created yet');
<add>
<add> const tag = document.querySelector('#test_vid_id');
<add> const player = videojs(tag);
<add>
<add> assert.strictEqual(videojs.getPlayer('#test_vid_id'), player, 'the player was returned when using a jQuery-style ID selector');
<add> assert.strictEqual(videojs.getPlayer('test_vid_id'), player, 'the player was returned when using a raw ID value');
<add> assert.strictEqual(videojs.getPlayer(tag), player, 'the player was returned when using the original tag/element');
<add>
<add> player.dispose();
<add>});
<add>
<ide> /* **************************************************** *
<ide> * div embed tests copied from video emebed tests above *
<ide> * **************************************************** */ | 3 |
Text | Text | update readme with setup instructions | c83cd98cae72e82dd4f13087a72143433e6b56ba | <ide><path>App/README.md
<ide> you can install this project & the required dependencies using:
<ide> php composer.phar create-project cakephp/cakephp-app --dev
<ide>
<ide> This will download this repository, install the CakePHP framework and testing libraries.
<add>
<add>## Configuration
<add>
<add>Once you've installed the dependencies copy the `Config/app.php.default` to `Config/app.php`.
<add>You should edit this file and setup the 'Datasources' array to point at your database.
<add>
<add>After creating `Config/app.php` you should go to the `/` route and ensure all the boxes are green. | 1 |
Javascript | Javascript | use utf8stream for net streams with utf8 encoding | ed5f1162fae2303a324017a98b247728dbe4718e | <ide><path>lib/net.js
<ide> var sys = require("sys");
<ide> var fs = require("fs");
<add>var Utf8Decoder = require("utf8decoder").Utf8Decoder;
<ide> var events = require("events");
<ide> var dns = require('dns');
<ide>
<ide> function initStream (self) {
<ide>
<ide> // Optimization: emit the original buffer with end points
<ide> if (self.ondata) self.ondata(pool, start, end);
<add> } else if (this._decoder) {
<add> this._decoder.write(pool.slice(start, end));
<ide> } else {
<ide> var string = pool.toString(self._encoding, start, end);
<ide> self.emit('data', string);
<ide> Stream.prototype._writeQueueLast = function () {
<ide>
<ide>
<ide> Stream.prototype.setEncoding = function (enc) {
<add> var self = this;
<ide> // TODO check values, error out on bad, and deprecation message?
<ide> this._encoding = enc.toLowerCase();
<add> if (this._encoding == 'utf-8' || this._encoding == 'utf8') {
<add> this._decoder = new Utf8Decoder();
<add> this._decoder.onString = function(str) {
<add> self.emit('data', str);
<add> };
<add> } else if (this._decoder) {
<add> delete this._decoder;
<add> }
<ide> };
<ide>
<ide> | 1 |
Go | Go | remove duplication of dns in config merging | 48cb2f03177732823b4091fd3ddd44b2bef2c58e | <ide><path>runconfig/config_test.go
<ide> func TestMerge(t *testing.T) {
<ide> volumesUser := make(map[string]struct{})
<ide> volumesUser["/test3"] = struct{}{}
<ide> configUser := &Config{
<del> Dns: []string{"3.3.3.3"},
<add> Dns: []string{"2.2.2.2", "3.3.3.3"},
<ide> PortSpecs: []string{"3333:2222", "3333:3333"},
<ide> Env: []string{"VAR2=3", "VAR3=3"},
<ide> Volumes: volumesUser,
<ide><path>runconfig/merge.go
<ide> func Merge(userConf, imageConf *Config) error {
<ide> if userConf.Dns == nil || len(userConf.Dns) == 0 {
<ide> userConf.Dns = imageConf.Dns
<ide> } else {
<del> //duplicates aren't an issue here
<del> userConf.Dns = append(userConf.Dns, imageConf.Dns...)
<add> dnsSet := make(map[string]struct{}, len(userConf.Dns))
<add> for _, dns := range userConf.Dns {
<add> dnsSet[dns] = struct{}{}
<add> }
<add> for _, dns := range imageConf.Dns {
<add> if _, exists := dnsSet[dns]; !exists {
<add> userConf.Dns = append(userConf.Dns, dns)
<add> }
<add> }
<ide> }
<ide> if userConf.Entrypoint == nil || len(userConf.Entrypoint) == 0 {
<ide> userConf.Entrypoint = imageConf.Entrypoint | 2 |
Javascript | Javascript | rewrite tests for colgroup, caption | b3e546c4eb0e14c5fefefa1e0c14026ba63f0017 | <ide><path>test/unit/manipulation.js
<ide> var testAppendForObject = function( valueObj, isFragment ) {
<ide>
<ide> var testAppend = function( valueObj ) {
<ide>
<del> expect( 63 );
<add> expect( 66 );
<ide>
<ide> testAppendForObject( valueObj, false );
<ide> testAppendForObject( valueObj, true );
<ide>
<ide> var defaultText, result, message, iframe, iframeDoc, j, d,
<del> $input, $radioChecked, $radioUnchecked, $radioParent, $map;
<add> $input, $radioChecked, $radioUnchecked, $radioParent, $map, $table;
<ide>
<ide> defaultText = "Try them out:";
<ide> result = jQuery("#first").append( valueObj("<b>buga</b>") );
<ide> var testAppend = function( valueObj ) {
<ide> equal( jQuery("#select1 optgroup").attr("label"), "optgroup", "Label attribute in newly inserted optgroup is correct" );
<ide> equal( jQuery("#select1 option:last").text(), "optgroup", "Appending optgroup" );
<ide>
<del> jQuery("#table").append( valueObj("<colgroup></colgroup>") );
<del> equal( jQuery("#table colgroup").length, 1, "Append colgroup" );
<add> $table = jQuery("#table");
<add>
<add> jQuery.each( "thead tbody tfoot colgroup caption".split(" "), function( i, name ) {
<add> $table.append( valueObj( "<" + name + "/>" ) );
<add> equal( $table.find( name ).length, 1, "Append " + name );
<add> });
<ide>
<ide> jQuery("#table colgroup").append( valueObj("<col/>") );
<ide> equal( jQuery("#table colgroup col").length, 1, "Append col" );
<ide>
<del> jQuery("#table").append( valueObj("<caption></caption>") );
<del> equal( jQuery("#table caption").length, 1, "Append caption" );
<del>
<ide> jQuery("#form")
<ide> .append( valueObj("<select id='appendSelect1'></select>") )
<ide> .append( valueObj("<select id='appendSelect2'><option>Test</option></select>") ); | 1 |
PHP | PHP | use short array syntax | 0f4e8ebffcc8c2f890f2d36b842ba12287366053 | <ide><path>src/Utility/Hash.php
<ide> public static function sort(array $data, $path, $dir = 'asc', $type = 'regular')
<ide>
<ide> // $type can be overloaded for case insensitive sort
<ide> if (is_array($type)) {
<del> $type += array('ignoreCase' => false, 'type' => 'regular');
<add> $type += ['ignoreCase' => false, 'type' => 'regular'];
<ide> $ignoreCase = $type['ignoreCase'];
<ide> $type = $type['type'];
<ide> } | 1 |
Ruby | Ruby | move formulacreator to formula_creator.rb | e05f72bc5232a7fd880da28050e59e45123ef0d7 | <ide><path>Library/Homebrew/dev-cmd/create.rb
<ide> #: the specified tap.
<ide>
<ide> require "formula"
<add>require "formula_creator"
<ide> require "missing_formula"
<ide> require "cli_parser"
<del>require "digest"
<del>require "erb"
<ide>
<ide> module Homebrew
<ide> module_function
<ide> def create
<ide> switch :debug
<ide> flag "--set-name="
<ide> flag "--set-version="
<del> flag "--tag="
<add> flag "--tap="
<ide> end
<ide> raise UsageError if ARGV.named.empty?
<ide>
<ide> def __gets
<ide> gots = $stdin.gets.chomp
<ide> gots.empty? ? nil : gots
<ide> end
<del>
<del> class FormulaCreator
<del> attr_reader :url, :sha256, :desc, :homepage
<del> attr_accessor :name, :version, :tap, :path, :mode
<del>
<del> def url=(url)
<del> @url = url
<del> path = Pathname.new(url)
<del> if @name.nil?
<del> case url
<del> when %r{github\.com/(\S+)/(\S+)\.git}
<del> @user = Regexp.last_match(1)
<del> @name = Regexp.last_match(2)
<del> @head = true
<del> @github = true
<del> when %r{github\.com/(\S+)/(\S+)/(archive|releases)/}
<del> @user = Regexp.last_match(1)
<del> @name = Regexp.last_match(2)
<del> @github = true
<del> else
<del> @name = path.basename.to_s[/(.*?)[-_.]?#{Regexp.escape(path.version.to_s)}/, 1]
<del> end
<del> end
<del> update_path
<del> if @version
<del> @version = Version.create(@version)
<del> else
<del> @version = Version.detect(url, {})
<del> end
<del> end
<del>
<del> def update_path
<del> return if @name.nil? || @tap.nil?
<del> @path = Formulary.path "#{@tap}/#{@name}"
<del> end
<del>
<del> def fetch?
<del> !Homebrew.args.no_fetch?
<del> end
<del>
<del> def head?
<del> @head || Homebrew.args.head?
<del> end
<del>
<del> def generate!
<del> raise "#{path} already exists" if path.exist?
<del>
<del> if version.nil? || version.null?
<del> opoo "Version cannot be determined from URL."
<del> puts "You'll need to add an explicit 'version' to the formula."
<del> elsif fetch?
<del> unless head?
<del> r = Resource.new
<del> r.url(url)
<del> r.version(version)
<del> r.owner = self
<del> @sha256 = r.fetch.sha256 if r.download_strategy == CurlDownloadStrategy
<del> end
<del>
<del> if @user && @name
<del> begin
<del> metadata = GitHub.repository(@user, @name)
<del> @desc = metadata["description"]
<del> @homepage = metadata["homepage"]
<del> rescue GitHub::HTTPNotFoundError
<del> # If there was no repository found assume the network connection is at
<del> # fault rather than the input URL.
<del> nil
<del> end
<del> end
<del> end
<del>
<del> path.write ERB.new(template, nil, ">").result(binding)
<del> end
<del>
<del> def template
<del> <<~EOS
<del> # Documentation: https://docs.brew.sh/Formula-Cookbook
<del> # http://www.rubydoc.info/github/Homebrew/brew/master/Formula
<del> # PLEASE REMOVE ALL GENERATED COMMENTS BEFORE SUBMITTING YOUR PULL REQUEST!
<del> class #{Formulary.class_s(name)} < Formula
<del> desc "#{desc}"
<del> homepage "#{homepage}"
<del> <% if head? %>
<del> head "#{url}"
<del> <% else %>
<del> url "#{url}"
<del> <% unless version.nil? or version.detected_from_url? %>
<del> version "#{version}"
<del> <% end %>
<del> sha256 "#{sha256}"
<del> <% end %>
<del> <% if mode == :cmake %>
<del> depends_on "cmake" => :build
<del> <% elsif mode == :meson %>
<del> depends_on "meson-internal" => :build
<del> depends_on "ninja" => :build
<del> depends_on "python" => :build
<del> <% elsif mode.nil? %>
<del> # depends_on "cmake" => :build
<del> <% end %>
<del>
<del> def install
<del> # ENV.deparallelize # if your formula fails when building in parallel
<del> <% if mode == :cmake %>
<del> system "cmake", ".", *std_cmake_args
<del> <% elsif mode == :autotools %>
<del> # Remove unrecognized options if warned by configure
<del> system "./configure", "--disable-debug",
<del> "--disable-dependency-tracking",
<del> "--disable-silent-rules",
<del> "--prefix=\#{prefix}"
<del> <% elsif mode == :meson %>
<del> ENV.refurbish_args
<del>
<del> mkdir "build" do
<del> system "meson", "--prefix=\#{prefix}", ".."
<del> system "ninja"
<del> system "ninja", "install"
<del> end
<del> <% else %>
<del> # Remove unrecognized options if warned by configure
<del> system "./configure", "--disable-debug",
<del> "--disable-dependency-tracking",
<del> "--disable-silent-rules",
<del> "--prefix=\#{prefix}"
<del> # system "cmake", ".", *std_cmake_args
<del> <% end %>
<del> <% if mode != :meson %>
<del> system "make", "install" # if this fails, try separate make/make install steps
<del> <% end %>
<del> end
<del>
<del> test do
<del> # `test do` will create, run in and delete a temporary directory.
<del> #
<del> # This test will fail and we won't accept that! For Homebrew/homebrew-core
<del> # this will need to be a test that verifies the functionality of the
<del> # software. Run the test with `brew test #{name}`. Options passed
<del> # to `brew install` such as `--HEAD` also need to be provided to `brew test`.
<del> #
<del> # The installed folder is not in the path, so use the entire path to any
<del> # executables being tested: `system "\#{bin}/program", "do", "something"`.
<del> system "false"
<del> end
<del> end
<del> EOS
<del> end
<del> end
<ide> end
<ide><path>Library/Homebrew/formula_creator.rb
<add>require "digest"
<add>require "erb"
<add>
<add>module Homebrew
<add> class FormulaCreator
<add> attr_reader :url, :sha256, :desc, :homepage
<add> attr_accessor :name, :version, :tap, :path, :mode
<add>
<add> def url=(url)
<add> @url = url
<add> path = Pathname.new(url)
<add> if @name.nil?
<add> case url
<add> when %r{github\.com/(\S+)/(\S+)\.git}
<add> @user = Regexp.last_match(1)
<add> @name = Regexp.last_match(2)
<add> @head = true
<add> @github = true
<add> when %r{github\.com/(\S+)/(\S+)/(archive|releases)/}
<add> @user = Regexp.last_match(1)
<add> @name = Regexp.last_match(2)
<add> @github = true
<add> else
<add> @name = path.basename.to_s[/(.*?)[-_.]?#{Regexp.escape(path.version.to_s)}/, 1]
<add> end
<add> end
<add> update_path
<add> if @version
<add> @version = Version.create(@version)
<add> else
<add> @version = Version.detect(url, {})
<add> end
<add> end
<add>
<add> def update_path
<add> return if @name.nil? || @tap.nil?
<add> @path = Formulary.path "#{@tap}/#{@name}"
<add> end
<add>
<add> def fetch?
<add> !Homebrew.args.no_fetch?
<add> end
<add>
<add> def head?
<add> @head || Homebrew.args.HEAD?
<add> end
<add>
<add> def generate!
<add> raise "#{path} already exists" if path.exist?
<add>
<add> if version.nil? || version.null?
<add> opoo "Version cannot be determined from URL."
<add> puts "You'll need to add an explicit 'version' to the formula."
<add> elsif fetch?
<add> unless head?
<add> r = Resource.new
<add> r.url(url)
<add> r.version(version)
<add> r.owner = self
<add> @sha256 = r.fetch.sha256 if r.download_strategy == CurlDownloadStrategy
<add> end
<add>
<add> if @user && @name
<add> begin
<add> metadata = GitHub.repository(@user, @name)
<add> @desc = metadata["description"]
<add> @homepage = metadata["homepage"]
<add> rescue GitHub::HTTPNotFoundError
<add> # If there was no repository found assume the network connection is at
<add> # fault rather than the input URL.
<add> nil
<add> end
<add> end
<add> end
<add>
<add> path.write ERB.new(template, nil, ">").result(binding)
<add> end
<add>
<add> def template
<add> <<~EOS
<add> # Documentation: https://docs.brew.sh/Formula-Cookbook
<add> # http://www.rubydoc.info/github/Homebrew/brew/master/Formula
<add> # PLEASE REMOVE ALL GENERATED COMMENTS BEFORE SUBMITTING YOUR PULL REQUEST!
<add> class #{Formulary.class_s(name)} < Formula
<add> desc "#{desc}"
<add> homepage "#{homepage}"
<add> <% if head? %>
<add> head "#{url}"
<add> <% else %>
<add> url "#{url}"
<add> <% unless version.nil? or version.detected_from_url? %>
<add> version "#{version}"
<add> <% end %>
<add> sha256 "#{sha256}"
<add> <% end %>
<add> <% if mode == :cmake %>
<add> depends_on "cmake" => :build
<add> <% elsif mode == :meson %>
<add> depends_on "meson-internal" => :build
<add> depends_on "ninja" => :build
<add> depends_on "python" => :build
<add> <% elsif mode.nil? %>
<add> # depends_on "cmake" => :build
<add> <% end %>
<add>
<add> def install
<add> # ENV.deparallelize # if your formula fails when building in parallel
<add> <% if mode == :cmake %>
<add> system "cmake", ".", *std_cmake_args
<add> <% elsif mode == :autotools %>
<add> # Remove unrecognized options if warned by configure
<add> system "./configure", "--disable-debug",
<add> "--disable-dependency-tracking",
<add> "--disable-silent-rules",
<add> "--prefix=\#{prefix}"
<add> <% elsif mode == :meson %>
<add> ENV.refurbish_args
<add>
<add> mkdir "build" do
<add> system "meson", "--prefix=\#{prefix}", ".."
<add> system "ninja"
<add> system "ninja", "install"
<add> end
<add> <% else %>
<add> # Remove unrecognized options if warned by configure
<add> system "./configure", "--disable-debug",
<add> "--disable-dependency-tracking",
<add> "--disable-silent-rules",
<add> "--prefix=\#{prefix}"
<add> # system "cmake", ".", *std_cmake_args
<add> <% end %>
<add> <% if mode != :meson %>
<add> system "make", "install" # if this fails, try separate make/make install steps
<add> <% end %>
<add> end
<add>
<add> test do
<add> # `test do` will create, run in and delete a temporary directory.
<add> #
<add> # This test will fail and we won't accept that! For Homebrew/homebrew-core
<add> # this will need to be a test that verifies the functionality of the
<add> # software. Run the test with `brew test #{name}`. Options passed
<add> # to `brew install` such as `--HEAD` also need to be provided to `brew test`.
<add> #
<add> # The installed folder is not in the path, so use the entire path to any
<add> # executables being tested: `system "\#{bin}/program", "do", "something"`.
<add> system "false"
<add> end
<add> end
<add> EOS
<add> end
<add> end
<add>end | 2 |
Javascript | Javascript | fix a typo | 0040efc8d85923d64bee1fdf7e9029d65d01b751 | <ide><path>packages/react-reconciler/src/ReactFiberPendingPriority.js
<ide> function findNextExpirationTimeToWorkOn(completedExpirationTime, root) {
<ide> let nextExpirationTimeToWorkOn =
<ide> earliestPendingTime !== NoWork ? earliestPendingTime : latestPingedTime;
<ide>
<del> // If there is no pending or pinted work, check if there's suspended work
<add> // If there is no pending or pinged work, check if there's suspended work
<ide> // that's lower priority than what we just completed.
<ide> if (
<ide> nextExpirationTimeToWorkOn === NoWork && | 1 |
Javascript | Javascript | use a different way to add the event listener | 22c858c2eca56d9be135ea187226c0d1e16f5309 | <ide><path>extensions/firefox/components/PdfStreamConverter.js
<ide> function log(aMsg) {
<ide> Services.console.logStringMessage(msg);
<ide> dump(msg + '\n');
<ide> }
<del>function getWindow(top, id) {
<del> return top.QueryInterface(Ci.nsIInterfaceRequestor)
<del> .getInterface(Ci.nsIDOMWindowUtils)
<del> .getOuterWindowWithId(id);
<del>}
<del>function windowID(win) {
<del> return win.QueryInterface(Ci.nsIInterfaceRequestor)
<del> .getInterface(Ci.nsIDOMWindowUtils)
<del> .outerWindowID;
<del>}
<del>function topWindow(win) {
<del> return win.QueryInterface(Ci.nsIInterfaceRequestor)
<del> .getInterface(Ci.nsIWebNavigation)
<del> .QueryInterface(Ci.nsIDocShellTreeItem)
<del> .rootTreeItem
<del> .QueryInterface(Ci.nsIInterfaceRequestor)
<del> .getInterface(Ci.nsIDOMWindow);
<add>
<add>function getDOMWindow(aChannel) {
<add> var requestor = aChannel.notificationCallbacks;
<add> var win = requestor.getInterface(Components.interfaces.nsIDOMWindow);
<add> return win;
<ide> }
<ide>
<ide> // All the priviledged actions.
<ide> ChromeActions.prototype = {
<ide> }
<ide> };
<ide>
<add>function getDOMWindow(aChannel) {
<add> var requestor = aChannel.notificationCallbacks;
<add> var win = requestor.getInterface(Components.interfaces.nsIDOMWindow);
<add> return win;
<add>}
<add>
<ide> // Event listener to trigger chrome privedged code.
<ide> function RequestListener(actions) {
<ide> this.actions = actions;
<ide> PdfStreamConverter.prototype = {
<ide> var channel = ioService.newChannel(
<ide> 'resource://pdf.js/web/viewer.html', null, null);
<ide>
<del> // Keep the URL the same so the browser sees it as the same.
<del> channel.originalURI = aRequest.URI;
<del> channel.asyncOpen(this.listener, aContext);
<del>
<del> // Setup a global listener waiting for the next DOM to be created and verfiy
<del> // that its the one we want by its URL. When the correct DOM is found create
<del> // an event listener on that window for the pdf.js events that require
<del> // chrome priviledges. Code snippet from John Galt.
<del> let window = aRequest.loadGroup.groupObserver
<del> .QueryInterface(Ci.nsIWebProgress)
<del> .DOMWindow;
<del> let top = topWindow(window);
<del> let id = windowID(window);
<del> window = null;
<del>
<del> top.addEventListener('DOMWindowCreated', function onDOMWinCreated(event) {
<del> let doc = event.originalTarget;
<del> let win = doc.defaultView;
<del>
<del> if (id == windowID(win)) {
<del> top.removeEventListener('DOMWindowCreated', onDOMWinCreated, true);
<del> if (!doc.documentURIObject.equals(aRequest.URI))
<del> return;
<del>
<add> var listener = this.listener;
<add> // Proxy all the requst observer calls, when it gets to onStopRequst
<add> // we can get the dom window.
<add> var proxy = {
<add> onStartRequest: function() {
<add> listener.onStartRequest.apply(listener, arguments);
<add> },
<add> onDataAvailable: function() {
<add> listener.onDataAvailable.apply(listener, arguments);
<add> },
<add> onStopRequest: function() {
<add> var domWindow = getDOMWindow(channel);
<ide> let requestListener = new RequestListener(new ChromeActions);
<del> win.addEventListener(PDFJS_EVENT_ID, function(event) {
<add> domWindow.addEventListener(PDFJS_EVENT_ID, function(event) {
<ide> requestListener.receive(event);
<ide> }, false, true);
<del> } else if (!getWindow(top, id)) {
<del> top.removeEventListener('DOMWindowCreated', onDOMWinCreated, true);
<add> listener.onStopRequest.apply(listener, arguments);
<ide> }
<del> }, true);
<add> };
<add>
<add> // Keep the URL the same so the browser sees it as the same.
<add> channel.originalURI = aRequest.URI;
<add> channel.asyncOpen(proxy, aContext);
<ide> },
<ide>
<ide> // nsIRequestObserver::onStopRequest | 1 |
PHP | PHP | add aggregate method to eloquent passthru | 097ca1ac101622b3b0769a8970a0509aa898165e | <ide><path>src/Illuminate/Database/Eloquent/Builder.php
<ide> class Builder
<ide> * @var string[]
<ide> */
<ide> protected $passthru = [
<add> 'aggregate',
<ide> 'average',
<ide> 'avg',
<ide> 'count', | 1 |
PHP | PHP | refactor the database connector | a1956f016c5e075074d66cdd2c84bac5792c7e36 | <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)) $dsn .= ';port='.$config->port;
<add> if (isset($config->port))
<add> {
<add> $dsn .= ';port='.$config->port;
<add> }
<ide>
<ide> $connection = new \PDO($dsn, $config->username, $config->password, $this->options);
<ide> | 1 |
Mixed | Python | add shortest path by bfs | 308505f18f71b793a2a2547717d3586ace6d99af | <ide><path>DIRECTORY.md
<ide> * [Bfs](https://github.com/TheAlgorithms/Python/blob/master/graphs/bfs.py)
<ide> * [Bfs Shortest Path](https://github.com/TheAlgorithms/Python/blob/master/graphs/bfs_shortest_path.py)
<ide> * [Breadth First Search](https://github.com/TheAlgorithms/Python/blob/master/graphs/breadth_first_search.py)
<add> * [Breadth First Search Shortest Path](https://github.com/TheAlgorithms/Python/blob/master/graphs/breadth_first_search_shortest_path.py)
<ide> * [Check Bipartite Graph Bfs](https://github.com/TheAlgorithms/Python/blob/master/graphs/check_bipartite_graph_bfs.py)
<ide> * [Check Bipartite Graph Dfs](https://github.com/TheAlgorithms/Python/blob/master/graphs/check_bipartite_graph_dfs.py)
<ide> * [Depth First Search](https://github.com/TheAlgorithms/Python/blob/master/graphs/depth_first_search.py)
<ide><path>graphs/breadth_first_search_shortest_path.py
<add>"""Breath First Search (BFS) can be used when finding the shortest path
<add>from a given source node to a target node in an unweighted graph.
<add>"""
<add>graph = {
<add> "A": ["B", "C", "E"],
<add> "B": ["A", "D", "E"],
<add> "C": ["A", "F", "G"],
<add> "D": ["B"],
<add> "E": ["A", "B", "D"],
<add> "F": ["C"],
<add> "G": ["C"],
<add>}
<add>
<add>from typing import Dict
<add>
<add>
<add>class Graph:
<add> def __init__(self, graph: Dict[str, str], source_vertex: str) -> None:
<add> """Graph is implemented as dictionary of adjancency lists. Also,
<add> Source vertex have to be defined upon initialization.
<add> """
<add> self.graph = graph
<add> # mapping node to its parent in resulting breadth first tree
<add> self.parent = {}
<add> self.source_vertex = source_vertex
<add>
<add> def breath_first_search(self) -> None:
<add> """This function is a helper for running breath first search on this graph.
<add> >>> g = Graph(graph, "G")
<add> >>> g.breath_first_search()
<add> >>> g.parent
<add> {'G': None, 'C': 'G', 'A': 'C', 'F': 'C', 'B': 'A', 'E': 'A', 'D': 'B'}
<add> """
<add> visited = {self.source_vertex}
<add> self.parent[self.source_vertex] = None
<add> queue = [self.source_vertex] # first in first out queue
<add>
<add> while queue:
<add> vertex = queue.pop(0)
<add> for adjancent_vertex in self.graph[vertex]:
<add> if adjancent_vertex not in visited:
<add> visited.add(adjancent_vertex)
<add> self.parent[adjancent_vertex] = vertex
<add> queue.append(adjancent_vertex)
<add>
<add> def shortest_path(self, target_vertex: str) -> str:
<add> """This shortest path function returns a string, describing the result:
<add> 1.) No path is found. The string is a human readable message to indicate this.
<add> 2.) The shortest path is found. The string is in the form `v1(->v2->v3->...->vn)`,
<add> where v1 is the source vertex and vn is the target vertex, if it exists separately.
<add>
<add> >>> g = Graph(graph, "G")
<add> >>> g.breath_first_search()
<add>
<add> Case 1 - No path is found.
<add> >>> g.shortest_path("Foo")
<add> 'No path from vertex:G to vertex:Foo'
<add>
<add> Case 2 - The path is found.
<add> >>> g.shortest_path("D")
<add> 'G->C->A->B->D'
<add> >>> g.shortest_path("G")
<add> 'G'
<add> """
<add> if target_vertex == self.source_vertex:
<add> return f"{self.source_vertex}"
<add> elif not self.parent.get(target_vertex):
<add> return f"No path from vertex:{self.source_vertex} to vertex:{target_vertex}"
<add> else:
<add> return self.shortest_path(self.parent[target_vertex]) + f"->{target_vertex}"
<add>
<add>
<add>if __name__ == "__main__":
<add> import doctest
<add>
<add> doctest.testmod()
<add> g = Graph(graph, "G")
<add> g.breath_first_search()
<add> print(g.shortest_path("D"))
<add> print(g.shortest_path("G"))
<add> print(g.shortest_path("Foo")) | 2 |
PHP | PHP | change a doc block | 9a2ebbbc2ccf6b2f91db2cea0271d58c38642fd4 | <ide><path>src/Illuminate/Support/ServiceProvider.php
<ide> abstract class ServiceProvider {
<ide> /**
<ide> * The application instance.
<ide> *
<del> * @var \Illuminate\Foundation\Application
<add> * @var \Illuminate\Contracts\Foundation\Application
<ide> */
<ide> protected $app;
<ide>
<ide> abstract class ServiceProvider {
<ide> /**
<ide> * Create a new service provider instance.
<ide> *
<del> * @param \Illuminate\Foundation\Application $app
<add> * @param \Illuminate\Contracts\Foundation\Application $app
<ide> * @return void
<ide> */
<ide> public function __construct($app) | 1 |
PHP | PHP | add test for the model push method | a8cf7f4b82762b4738f605e04da637227c7de5a8 | <ide><path>tests/Integration/Database/EloquentPushTest.php
<add><?php
<add>
<add>namespace Illuminate\Tests\Integration\Database;
<add>
<add>use Illuminate\Support\Facades\Schema;
<add>use Illuminate\Database\Eloquent\Model;
<add>use Illuminate\Database\Schema\Blueprint;
<add>
<add>/**
<add> * @group integration
<add> */
<add>class EloquentPushTest extends DatabaseTestCase
<add>{
<add> public function setUp()
<add> {
<add> parent::setUp();
<add>
<add> Schema::create('users', function (Blueprint $table) {
<add> $table->increments('id');
<add> $table->string('name');
<add> });
<add>
<add> Schema::create('posts', function (Blueprint $table) {
<add> $table->increments('id');
<add> $table->string('title');
<add> $table->unsignedInteger('user_id');
<add> });
<add>
<add> Schema::create('comments', function (Blueprint $table) {
<add> $table->increments('id');
<add> $table->string('comment');
<add> $table->unsignedInteger('post_id');
<add> });
<add> }
<add>
<add> public function testPushMethodSavesTheRelationshipsRecursively()
<add> {
<add> $user = new UserX();
<add> $user->name = 'Test';
<add> $user->save();
<add> $user->posts()->create(['title' => 'Test title']);
<add>
<add> $post = PostX::firstOrFail();
<add> $post->comments()->create(['comment' => 'Test comment']);
<add>
<add> $user = $user->fresh();
<add> $user->name = 'Test 1';
<add> $user->posts[0]->title = 'Test title 1';
<add> $user->posts[0]->comments[0]->comment = 'Test comment 1';
<add> $user->push();
<add>
<add> $this->assertSame(1, UserX::count());
<add> $this->assertSame('Test 1', UserX::firstOrFail()->name);
<add> $this->assertSame(1, PostX::count());
<add> $this->assertSame('Test title 1', PostX::firstOrFail()->title);
<add> $this->assertSame(1, CommentX::count());
<add> $this->assertSame('Test comment 1', CommentX::firstOrFail()->comment);
<add> }
<add>}
<add>
<add>class UserX extends Model
<add>{
<add> public $timestamps = false;
<add> protected $guarded = [];
<add> protected $table = 'users';
<add>
<add> public function posts()
<add> {
<add> return $this->hasMany(PostX::class, 'user_id');
<add> }
<add>}
<add>
<add>class PostX extends Model
<add>{
<add> public $timestamps = false;
<add> protected $guarded = [];
<add> protected $table = 'posts';
<add>
<add> public function comments()
<add> {
<add> return $this->hasMany(CommentX::class, 'post_id');
<add> }
<add>}
<add>
<add>class CommentX extends Model
<add>{
<add> public $timestamps = false;
<add> protected $guarded = [];
<add> protected $table = 'comments';
<add>} | 1 |
Ruby | Ruby | fix scope typo in add_lock! closes . [zubek] | c302cdfcc4e70d1adbc5fb4c89d361e446349800 | <ide><path>activerecord/lib/active_record/base.rb
<ide> def add_limit!(sql, options, scope = :auto)
<ide> # The optional scope argument is for the current :find scope.
<ide> # The :lock option has precedence over a scoped :lock.
<ide> def add_lock!(sql, options, scope = :auto)
<del> scope = scope(:find) if :auto == :scope
<add> scope = scope(:find) if :auto == scope
<ide> options = options.reverse_merge(:lock => scope[:lock]) if scope
<ide> connection.add_lock!(sql, options)
<ide> end | 1 |
Ruby | Ruby | require json arrays/objects for audit exceptions | b4d4f6d50422107ef79c5b976bed891915d5ef2e | <ide><path>Library/Homebrew/dev-cmd/audit.rb
<ide> def audit_json_files
<ide>
<ide> def audit_tap_audit_exceptions
<ide> @tap_audit_exceptions.each do |list_name, formula_names|
<add> unless [Hash, Array].include? formula_names.class
<add> problem <<~EOS
<add> audit_exceptions/#{list_name}.json should contain a JSON array
<add> of formula names or a JSON object mapping formula names to values
<add> EOS
<add> next
<add> end
<add>
<ide> formula_names = formula_names.keys if formula_names.is_a? Hash
<ide>
<ide> invalid_formulae = [] | 1 |
Java | Java | add cache(int capacity) to observable | d44f059848e3f46462a9f981ce163af9dc2f159d | <ide><path>rxjava-core/src/main/java/rx/Observable.java
<ide> public final Observable<T> cache() {
<ide> return create(new OnSubscribeCache<T>(this));
<ide> }
<ide>
<add> /**
<add> * {@code cache} with initial capacity.
<add> *
<add> * @param capacity
<add> * initial cache size
<add> * @return an Observable that, when first subscribed to, caches all of its items and notifications for the
<add> * benefit of subsequent subscribers
<add> * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#cache">RxJava Wiki: cache()</a>
<add> */
<add> public final Observable<T> cache(int capacity) {
<add> return create(new OnSubscribeCache<T>(this, capacity));
<add> }
<add>
<ide> /**
<ide> * Returns an Observable that emits the items emitted by the source Observable, converted to the specified
<ide> * type.
<ide><path>rxjava-core/src/main/java/rx/internal/operators/OnSubscribeCache.java
<ide> public OnSubscribeCache(Observable<? extends T> source) {
<ide> this(source, ReplaySubject.<T> create());
<ide> }
<ide>
<add> public OnSubscribeCache(Observable<? extends T> source, int capacity) {
<add> this(source, ReplaySubject.<T> create(capacity));
<add> }
<add>
<ide> /* accessible to tests */OnSubscribeCache(Observable<? extends T> source, Subject<? super T, ? extends T> cache) {
<ide> this.source = source;
<ide> this.cache = cache;
<ide><path>rxjava-core/src/test/java/rx/ObservableTests.java
<ide> public void call(String v) {
<ide> assertEquals(1, counter.get());
<ide> }
<ide>
<add> @Test
<add> public void testCacheWithCapacity() throws InterruptedException {
<add> final AtomicInteger counter = new AtomicInteger();
<add> Observable<String> o = Observable.create(new OnSubscribe<String>() {
<add>
<add> @Override
<add> public void call(final Subscriber<? super String> observer) {
<add> new Thread(new Runnable() {
<add>
<add> @Override
<add> public void run() {
<add> counter.incrementAndGet();
<add> observer.onNext("one");
<add> observer.onCompleted();
<add> }
<add> }).start();
<add> }
<add> }).cache(1);
<add>
<add> // we then expect the following 2 subscriptions to get that same value
<add> final CountDownLatch latch = new CountDownLatch(2);
<add>
<add> // subscribe once
<add> o.subscribe(new Action1<String>() {
<add>
<add> @Override
<add> public void call(String v) {
<add> assertEquals("one", v);
<add> latch.countDown();
<add> }
<add> });
<add>
<add> // subscribe again
<add> o.subscribe(new Action1<String>() {
<add>
<add> @Override
<add> public void call(String v) {
<add> assertEquals("one", v);
<add> latch.countDown();
<add> }
<add> });
<add>
<add> if (!latch.await(1000, TimeUnit.MILLISECONDS)) {
<add> fail("subscriptions did not receive values");
<add> }
<add> assertEquals(1, counter.get());
<add> }
<add>
<ide> /**
<ide> * https://github.com/Netflix/RxJava/issues/198
<ide> * | 3 |
Text | Text | fix confusing language about microtask queue | f2172012f30e7de48cea54b4dbbbbaa1195d9a02 | <ide><path>doc/api/globals.md
<ide> The `queueMicrotask()` method queues a microtask to invoke `callback`. If
<ide> be emitted.
<ide>
<ide> In general, `queueMicrotask` is the idiomatic choice over `process.nextTick()`.
<del>`process.nextTick()` will always run before microtasks, and so unexpected
<del>execution order may be observed.
<add>`process.nextTick()` will always run before the microtask queue, and so
<add>unexpected execution order may be observed.
<ide>
<ide> ```js
<ide> // Here, `queueMicrotask()` is used to ensure the 'load' event is always | 1 |
Text | Text | change id links for scales objects | e1a1d9cd6dc16b3291f45b57dd0c13a69694f41f | <ide><path>docs/02-Scales.md
<ide> afterCalculateTickRotation | Function | undefined | Callback that runs after tic
<ide> beforeFit | Function | undefined | Callback that runs before the scale fits to the canvas. Passed a single argument, the scale instance.
<ide> afterFit | Function | undefined | Callback that runs after the scale fits to the canvas. Passed a single argument, the scale instance.
<ide> afterUpdate | Function | undefined | Callback that runs at the end of the update process. Passed a single argument, the scale instance.
<del>**gridLines** | Object | - | See [grid line configuration](#scales-grid-line-configuration) section.
<del>**scaleLabel** | Object | | See [scale title configuration](#scales-scale-title-configuration) section.
<del>**ticks** | Object | | See [ticks configuration](#scales-ticks-configuration) section.
<add>**gridLines** | Object | - | See [grid line configuration](#grid-line-configuration) section.
<add>**scaleLabel** | Object | | See [scale title configuration](#scale-title-configuration) section.
<add>**ticks** | Object | | See [ticks configuration](#ticks-configuration) section.
<ide>
<ide> #### Grid Line Configuration
<ide>
<ide> parser | String or Function | - | If defined as a string, it is interpreted as a
<ide> round | String | - | If defined, dates will be rounded to the start of this unit. See [Time Units](#scales-time-units) below for the allowed units.
<ide> tooltipFormat | String | '' | The moment js format string to use for the tooltip.
<ide> unit | String | - | If defined, will force the unit to be a certain type. See [Time Units](#scales-time-units) section below for details.
<del>unitStepSize | Number | 1 | The number of units between grid lines.
<add>unitStepSize | Number | 1 | The number of units between grid lines.
<ide>
<ide> #### Date Formats
<ide>
<ide> When providing data for the time scale, Chart.js supports all of the formats tha
<ide>
<ide> The following display formats are used to configure how different time units are formed into strings for the axis tick marks. See [moment.js](http://momentjs.com/docs/#/displaying/format/) for the allowable format strings.
<ide>
<del>Name | Default
<del>--- | ---
<add>Name | Default
<add>--- | ---
<ide> millisecond | 'SSS [ms]'
<ide> second | 'h:mm:ss a'
<ide> minute | 'h:mm:ss a'
<ide> The following options are used to configure angled lines that radiate from the c
<ide>
<ide> Name | Type | Default | Description
<ide> --- | --- | --- | ---
<del>display | Boolean | true | If true, angle lines are shown.
<add>display | Boolean | true | If true, angle lines are shown.
<ide> color | Color | 'rgba(0, 0, 0, 0.1)' | Color of angled lines
<ide> lineWidth | Number | 1 | Width of angled lines
<ide> | 1 |
Ruby | Ruby | fix typo in am i18n validation test name [skip ci] | 3f92a8247cf0cf0ae78d55aee5e9a6510060e939 | <ide><path>activemodel/test/cases/validations/i18n_validation_test.rb
<ide> def test_errors_full_messages_uses_format
<ide> # validates_length_of :within too short w/ mocha
<ide>
<ide> COMMON_CASES.each do |name, validation_options, generate_message_options|
<del> test "validates_length_of for :withing on generated message when too short #{name}" do
<add> test "validates_length_of for :within on generated message when too short #{name}" do
<ide> Person.validates_length_of :title, validation_options.merge(within: 3..5)
<ide> @mock_generator.expect(:call, nil, [:title, :too_short, generate_message_options.merge(count: 3)])
<ide> @person.errors.stub(:generate_message, @mock_generator) do | 1 |
Javascript | Javascript | move a comment to its original location | 40a9e64e1f23e478036c5f302a60e5503ccf3a30 | <ide><path>packages/react-dom/src/server/ReactPartialRenderer.js
<ide> class ReactDOMServerRenderer {
<ide> const flatChildren = flattenTopLevelChildren(children);
<ide>
<ide> const topFrame: Frame = {
<add> type: null,
<ide> // Assume all trees start in the HTML namespace (not totally true, but
<ide> // this is what we did historically)
<del> type: null,
<ide> domNamespace: Namespaces.html,
<ide> children: flatChildren,
<ide> childIndex: 0, | 1 |
Javascript | Javascript | remove trailing spaces | f8ef75eb9124ce924be5fb521c783efd5c996e33 | <ide><path>src/ajax.js
<ide> jQuery.each( "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".sp
<ide> var jsc = now();
<ide>
<ide> jQuery.extend({
<del>
<add>
<ide> get: function( url, data, callback, type ) {
<ide> // shift arguments if data argument was ommited
<ide> if ( jQuery.isFunction( data ) ) {
<ide> jQuery.extend({
<ide>
<ide> if ( xml && data.documentElement.tagName == "parsererror" )
<ide> throw "parsererror";
<del>
<add>
<ide> // Allow a pre-filtering function to sanitize the response
<ide> // s != null is checked to keep backwards compatibility
<ide> if( s && s.dataFilter )
<ide> jQuery.extend({
<ide> if ( type == "json" )
<ide> data = window["eval"]("(" + data + ")");
<ide> }
<del>
<add>
<ide> return data;
<ide> },
<ide>
<ide><path>src/attributes.js
<ide> jQuery.fn.extend({
<ide> if ( elem ) {
<ide> if( jQuery.nodeName( elem, 'option' ) )
<ide> return (elem.attributes.value || {}).specified ? elem.value : elem.text;
<del>
<add>
<ide> // We need to handle select boxes special
<ide> if ( jQuery.nodeName( elem, "select" ) ) {
<ide> var index = elem.selectedIndex,
<ide> jQuery.fn.extend({
<ide> }
<ide> }
<ide>
<del> return values;
<add> return values;
<ide> }
<ide>
<ide> // Everything else, we just grab the value
<ide><path>src/core.js
<del>var
<add>var
<ide> // Will speed up references to window, and allows munging its name.
<ide> window = this,
<ide> // Will speed up references to undefined, and allows munging its name.
<ide> jQuery.extend = jQuery.fn.extend = function() {
<ide>
<ide> // Recurse if we're merging object values
<ide> if ( deep && copy && typeof copy === "object" && !copy.nodeType )
<del> target[ name ] = jQuery.extend( deep,
<add> target[ name ] = jQuery.extend( deep,
<ide> // Never move original objects, clone them
<ide> src || ( copy.length != null ? [ ] : { } )
<ide> , copy );
<ide><path>src/data.js
<ide> jQuery.extend({
<ide> },
<ide> queue: function( elem, type, data ) {
<ide> if ( elem ){
<del>
<add>
<ide> type = (type || "fx") + "queue";
<del>
<add>
<ide> var q = jQuery.data( elem, type );
<del>
<add>
<ide> if ( !q || jQuery.isArray(data) )
<ide> q = jQuery.data( elem, type, jQuery.makeArray(data) );
<ide> else if( data )
<ide> q.push( data );
<del>
<add>
<ide> }
<ide> return q;
<ide> },
<ide>
<ide> dequeue: function( elem, type ){
<ide> var queue = jQuery.queue( elem, type ),
<ide> fn = queue.shift();
<del>
<add>
<ide> if( !type || type === "fx" )
<ide> fn = queue[0];
<del>
<add>
<ide> if( fn !== undefined )
<ide> fn.call(elem);
<ide> }
<ide> jQuery.fn.extend({
<ide>
<ide> return this.each(function(){
<ide> var queue = jQuery.queue( this, type, data );
<del>
<add>
<ide> if( type == "fx" && queue.length == 1 )
<ide> queue[0].call(this);
<ide> });
<ide><path>src/dimensions.js
<ide> jQuery.each([ "Height", "Width" ], function(i, name){
<ide> jQuery.css( this[0], type, false, margin ? "margin" : "border" ) :
<ide> null;
<ide> };
<del>
<add>
<ide> jQuery.fn[ type ] = function( size ) {
<ide> // Get window width or height
<ide> return this[0] == window ?
<ide><path>src/event.js
<ide> jQuery.event = {
<ide>
<ide> // Get the current list of functions bound to this event
<ide> var handlers = events[type];
<del>
<add>
<ide> if ( jQuery.event.specialAll[type] )
<ide> jQuery.event.specialAll[type].setup.call(elem, data, namespaces);
<ide>
<ide> jQuery.event = {
<ide> // Handle the removal of namespaced events
<ide> if ( namespace.test(events[type][handle].type) )
<ide> delete events[type][handle];
<del>
<add>
<ide> if ( jQuery.event.specialAll[type] )
<ide> jQuery.event.specialAll[type].teardown.call(elem, namespaces);
<ide>
<ide> jQuery.event = {
<ide> // don't do events on text and comment nodes
<ide> if ( !elem || elem.nodeType == 3 || elem.nodeType == 8 )
<ide> return undefined;
<del>
<add>
<ide> // Clean up in case it is reused
<ide> event.result = undefined;
<ide> event.target = elem;
<del>
<add>
<ide> // Clone the incoming data, if any
<ide> data = jQuery.makeArray(data);
<ide> data.unshift( event );
<ide> jQuery.event = {
<ide>
<ide> event = arguments[0] = jQuery.event.fix( event || window.event );
<ide> event.currentTarget = this;
<del>
<add>
<ide> // Namespaced event handlers
<ide> var namespaces = event.type.split(".");
<ide> event.type = namespaces.shift();
<ide>
<ide> // Cache this now, all = true means, any handler
<ide> all = !namespaces.length && !event.exclusive;
<del>
<add>
<ide> var namespace = new RegExp("(^|\\.)" + namespaces.slice().sort().join(".*\\.") + "(\\.|$)");
<ide>
<ide> handlers = ( jQuery.data(this, "events") || {} )[event.type];
<ide> jQuery.event = {
<ide> teardown: function() {}
<ide> }
<ide> },
<del>
<add>
<ide> specialAll: {
<ide> live: {
<ide> setup: function( selector, namespaces ){
<ide> jQuery.event = {
<ide> teardown: function( namespaces ){
<ide> if ( namespaces.length ) {
<ide> var remove = 0, name = new RegExp("(^|\\.)" + namespaces[0] + "(\\.|$)");
<del>
<add>
<ide> jQuery.each( (jQuery.data(this, "events").live || {}), function(){
<ide> if ( name.test(this.type) )
<ide> remove++;
<ide> });
<del>
<add>
<ide> if ( remove < 1 )
<ide> jQuery.event.remove( this, namespaces[0], liveHandler );
<ide> }
<ide> jQuery.Event = function( src ){
<ide> // Allow instantiation without the 'new' keyword
<ide> if( !this.preventDefault )
<ide> return new jQuery.Event(src);
<del>
<add>
<ide> // Event object
<ide> if( src && src.type ){
<ide> this.originalEvent = src;
<ide> jQuery.Event = function( src ){
<ide> // timeStamp is buggy for some events on Firefox(#3843)
<ide> // So we won't rely on the native value
<ide> this.timeStamp = now();
<del>
<add>
<ide> // Mark it as fixed
<ide> this[expando] = true;
<ide> };
<ide> var withinElement = function(event) {
<ide> while ( parent && parent != this )
<ide> try { parent = parent.parentNode; }
<ide> catch(e) { parent = this; }
<del>
<add>
<ide> if( parent != this ){
<ide> // set the correct event type
<ide> event.type = event.data;
<ide> // handle event if we actually just moused on to a non sub-element
<ide> jQuery.event.handle.apply( this, arguments );
<ide> }
<ide> };
<del>
<del>jQuery.each({
<del> mouseover: 'mouseenter',
<add>
<add>jQuery.each({
<add> mouseover: 'mouseenter',
<ide> mouseout: 'mouseleave'
<ide> }, function( orig, fix ){
<ide> jQuery.event.special[ fix ] = {
<ide> jQuery.each({
<ide> teardown: function(){
<ide> jQuery.event.remove( this, orig, withinElement );
<ide> }
<del> };
<add> };
<ide> });
<ide>
<ide> jQuery.fn.extend({
<ide> jQuery.fn.extend({
<ide> event.stopPropagation();
<ide> jQuery.event.trigger( event, data, this[0] );
<ide> return event.result;
<del> }
<add> }
<ide> },
<ide>
<ide> toggle: function( fn ) {
<ide> jQuery.fn.extend({
<ide>
<ide> return this;
<ide> },
<del>
<add>
<ide> live: function( type, fn ){
<ide> var proxy = jQuery.event.proxy( fn );
<ide> proxy.guid += this.selector + type;
<ide> jQuery.fn.extend({
<ide>
<ide> return this;
<ide> },
<del>
<add>
<ide> die: function( type, fn ){
<ide> jQuery( this.context ).unbind( liveConvert(type, this.selector), fn ? { guid: fn.guid + this.selector + type } : null );
<ide> return this;
<ide> function liveHandler( event ){
<ide> elems.sort(function(a,b) {
<ide> return jQuery.data(a.elem, "closest") - jQuery.data(b.elem, "closest");
<ide> });
<del>
<add>
<ide> jQuery.each(elems, function(){
<ide> event.currentTarget = this.elem;
<ide> if ( this.fn.call(this.elem, event, this.fn.data) === false )
<ide> jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
<ide> // More info:
<ide> // - http://isaacschlueter.com/2006/10/msie-memory-leaks/
<ide> // - https://bugzilla.mozilla.org/show_bug.cgi?id=252542
<del>jQuery( window ).bind( 'unload', function(){
<add>jQuery( window ).bind( 'unload', function(){
<ide> for ( var id in jQuery.cache )
<ide> // Skip the window
<ide> if ( id != 1 && jQuery.cache[ id ].handle )
<ide> jQuery.event.remove( jQuery.cache[ id ].handle.elem );
<del>});
<add>});
<ide><path>src/fx.js
<ide> jQuery.fn.extend({
<ide> } else {
<ide> for ( var i = 0, l = this.length; i < l; i++ ){
<ide> var old = jQuery.data(this[i], "olddisplay");
<del>
<add>
<ide> this[i].style.display = old || "";
<del>
<add>
<ide> if ( jQuery.css(this[i], "display") === "none" ) {
<ide> var tagName = this[i].tagName, display;
<del>
<add>
<ide> if ( elemdisplay[ tagName ] ) {
<ide> display = elemdisplay[ tagName ];
<ide> } else {
<ide> var elem = jQuery("<" + tagName + " />").appendTo("body");
<del>
<add>
<ide> display = elem.css("display");
<ide> if ( display === "none" )
<ide> display = "block";
<del>
<add>
<ide> elem.remove();
<del>
<add>
<ide> elemdisplay[ tagName ] = display;
<ide> }
<del>
<add>
<ide> jQuery.data(this[i], "olddisplay", display);
<ide> }
<ide> }
<ide> jQuery.fn.extend({
<ide> for ( var i = 0, l = this.length; i < l; i++ ){
<ide> this[i].style.display = jQuery.data(this[i], "olddisplay") || "";
<ide> }
<del>
<add>
<ide> return this;
<ide> }
<ide> },
<ide> jQuery.fn.extend({
<ide> var optall = jQuery.speed(speed, easing, callback);
<ide>
<ide> return this[ optall.queue === false ? "each" : "queue" ](function(){
<del>
<add>
<ide> var opt = jQuery.extend({}, optall), p,
<ide> hidden = this.nodeType == 1 && jQuery(this).is(":hidden"),
<ide> self = this;
<del>
<add>
<ide> for ( p in prop ) {
<ide> if ( prop[p] == "hide" && hidden || prop[p] == "show" && !hidden )
<ide> return opt.complete.call(this);
<ide> jQuery.fx.prototype = {
<ide> if ( this.options.hide || this.options.show )
<ide> for ( var p in this.options.curAnim )
<ide> jQuery.style(this.elem, p, this.options.orig[p]);
<del>
<add>
<ide> // Execute the complete function
<ide> this.options.complete.call( this.elem );
<ide> }
<ide><path>src/manipulation.js
<ide> jQuery.fn.extend({
<ide> for ( var i = 0, l = this.length; i < l; i++ )
<ide> callback.call( root(this[i], first), this.length > 1 || i > 0 ?
<ide> fragment.cloneNode(true) : fragment );
<del>
<add>
<ide> if ( scripts )
<ide> jQuery.each( scripts, evalScript );
<ide> }
<ide>
<ide> return this;
<del>
<add>
<ide> function root( elem, cur ) {
<ide> return table && jQuery.nodeName(elem, "table") && jQuery.nodeName(cur, "tr") ?
<ide> (elem.getElementsByTagName("tbody")[0] ||
<ide> jQuery.extend({
<ide> // IE completely kills leading whitespace when innerHTML is used
<ide> if ( !jQuery.support.leadingWhitespace && /^\s/.test( elem ) )
<ide> div.insertBefore( context.createTextNode( elem.match(/^\s*/)[0] ), div.firstChild );
<del>
<add>
<ide> elem = jQuery.makeArray( div.childNodes );
<ide> }
<ide>
<ide> jQuery.extend({
<ide> fragment.appendChild( ret[i] );
<ide> }
<ide> }
<del>
<add>
<ide> return scripts;
<ide> }
<ide>
<ide><path>src/offset.js
<ide> if ( "getBoundingClientRect" in document.documentElement )
<ide> left = box.left + (self.pageXOffset || jQuery.boxModel && docElem.scrollLeft || body.scrollLeft) - clientLeft;
<ide> return { top: top, left: left };
<ide> };
<del>else
<add>else
<ide> jQuery.fn.offset = function() {
<ide> var elem = this[0];
<ide> if ( !elem ) return null;
<ide> jQuery.fn.extend({
<ide> parentOffset = /^body|html$/i.test(offsetParent[0].tagName) ? { top: 0, left: 0 } : offsetParent.offset();
<ide>
<ide> // Subtract element margins
<del> // note: when an element has margin: auto the offsetLeft and marginLeft
<add> // note: when an element has margin: auto the offsetLeft and marginLeft
<ide> // are the same in Safari causing offset.left to incorrectly be 0
<ide> offset.top -= parseFloat( jQuery.curCSS(elem, 'marginTop', true), 10 ) || 0;
<ide> offset.left -= parseFloat( jQuery.curCSS(elem, 'marginLeft', true), 10 ) || 0;
<ide> jQuery.fn.extend({
<ide> // Create scrollLeft and scrollTop methods
<ide> jQuery.each( ['Left', 'Top'], function(i, name) {
<ide> var method = 'scroll' + name;
<del>
<add>
<ide> jQuery.fn[ method ] = function(val) {
<ide> if ( !this[0] ) return null;
<ide>
<ide><path>src/selector.js
<ide> var Sizzle = function(selector, context, results, seed) {
<ide> if ( context.nodeType !== 1 && context.nodeType !== 9 ) {
<ide> return [];
<ide> }
<del>
<add>
<ide> if ( !selector || typeof selector !== "string" ) {
<ide> return results;
<ide> }
<ide>
<ide> var parts = [], m, set, checkSet, check, mode, extra, prune = true, contextXML = isXML(context);
<del>
<add>
<ide> // Reset the position of the chunker regexp (start from head)
<ide> chunker.lastIndex = 0;
<del>
<add>
<ide> while ( (m = chunker.exec(selector)) !== null ) {
<ide> parts.push( m[1] );
<del>
<add>
<ide> if ( m[2] ) {
<ide> extra = RegExp.rightContext;
<ide> break;
<ide> Sizzle.find = function(expr, context, isXML){
<ide>
<ide> for ( var i = 0, l = Expr.order.length; i < l; i++ ) {
<ide> var type = Expr.order[i], match;
<del>
<add>
<ide> if ( (match = Expr.match[ type ].exec( expr )) ) {
<ide> var left = RegExp.leftContext;
<ide>
<ide> var Expr = Sizzle.selectors = {
<ide> },
<ide> ATTR: function(match, curLoop, inplace, result, not, isXML){
<ide> var name = match[1].replace(/\\/g, "");
<del>
<add>
<ide> if ( !isXML && Expr.attrMap[name] ) {
<ide> match[1] = Expr.attrMap[name];
<ide> }
<ide> var Expr = Sizzle.selectors = {
<ide> } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
<ide> return true;
<ide> }
<del>
<add>
<ide> return match;
<ide> },
<ide> POS: function(match){
<ide> var Expr = Sizzle.selectors = {
<ide> if ( first == 1 && last == 0 ) {
<ide> return true;
<ide> }
<del>
<add>
<ide> var doneName = match[0],
<ide> parent = elem.parentNode;
<del>
<add>
<ide> if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) {
<ide> var count = 0;
<ide> for ( node = parent.firstChild; node; node = node.nextSibling ) {
<ide> if ( node.nodeType === 1 ) {
<ide> node.nodeIndex = ++count;
<ide> }
<del> }
<add> }
<ide> parent.sizcache = doneName;
<ide> }
<del>
<add>
<ide> var diff = elem.nodeIndex - last;
<ide> if ( first == 0 ) {
<ide> return diff == 0;
<ide> var makeArray = function(array, results) {
<ide> results.push.apply( results, array );
<ide> return results;
<ide> }
<del>
<add>
<ide> return array;
<ide> };
<ide>
<ide> if ( document.querySelectorAll ) (function(){
<ide> if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
<ide> return;
<ide> }
<del>
<add>
<ide> Sizzle = function(query, context, extra, seed){
<ide> context = context || document;
<ide>
<ide> if ( document.querySelectorAll ) (function(){
<ide> return makeArray( context.querySelectorAll(query), extra );
<ide> } catch(e){}
<ide> }
<del>
<add>
<ide> return oldSizzle(query, context, extra, seed);
<ide> };
<ide>
<ide><path>src/support.js
<ide> jQuery.support = {
<ide> // IE strips leading whitespace when .innerHTML is used
<ide> leadingWhitespace: div.firstChild.nodeType == 3,
<del>
<add>
<ide> // Make sure that tbody elements aren't automatically inserted
<ide> // IE will insert them into empty tables
<ide> tbody: !div.getElementsByTagName("tbody").length,
<del>
<add>
<ide> // Make sure that link elements get serialized correctly by innerHTML
<ide> // This requires a wrapper element in IE
<ide> htmlSerialize: !!div.getElementsByTagName("link").length,
<del>
<add>
<ide> // Get the style information from getAttribute
<ide> // (IE uses .cssText insted)
<ide> style: /red/.test( a.getAttribute("style") ),
<del>
<add>
<ide> // Make sure that URLs aren't manipulated
<ide> // (IE normalizes it by default)
<ide> hrefNormalized: a.getAttribute("href") === "/a",
<del>
<add>
<ide> // Make sure that element opacity exists
<ide> // (IE uses filter instead)
<ide> opacity: a.style.opacity === "0.5",
<del>
<add>
<ide> // Verify style float existence
<ide> // (IE uses styleFloat instead of cssFloat)
<ide> cssFloat: !!a.style.cssFloat,
<ide> noCloneEvent: true,
<ide> boxModel: null
<ide> };
<del>
<add>
<ide> script.type = "text/javascript";
<ide> try {
<ide> script.appendChild( document.createTextNode( "window." + id + "=1;" ) );
<ide> } catch(e){}
<ide>
<ide> root.insertBefore( script, root.firstChild );
<del>
<add>
<ide> // Make sure that the execution of code works by injecting a script
<ide> // tag with appendChild/createTextNode
<ide> // (IE doesn't support this, fails, and uses .text instead) | 11 |
Javascript | Javascript | fix saucelabs config | 94f1e21ba398a3d379aedfdb65b49e48e27e210f | <ide><path>karma.conf.js
<ide> module.exports = function(config) {
<ide> sauceLabs: {
<ide> recordScreenshots: false,
<ide> connectOptions: {
<del> port: 5757,
<add> // port: 5757,
<ide> logfile: 'sauce_connect.log'
<ide> },
<ide> public: 'public' | 1 |
Python | Python | remove unused import | 40af53f96c407ce0c3a5679270f8467994f46e1d | <ide><path>t/unit/backends/test_mongodb.py
<del>import perform as perform
<del>
<ide> import datetime
<ide> from pickle import dumps, loads
<ide> from unittest.mock import ANY, MagicMock, Mock, patch, sentinel | 1 |
PHP | PHP | remove deprecated methods from connection | d9206d432bda438dbe4e4a5c8d6d0cdcdd08879b | <ide><path>src/Database/Connection.php
<ide> public function getDriver()
<ide> return $this->_driver;
<ide> }
<ide>
<del> /**
<del> * Sets the driver instance. If a string is passed it will be treated
<del> * as a class name and will be instantiated.
<del> *
<del> * If no params are passed it will return the current driver instance.
<del> *
<del> * @deprecated 3.4.0 Use setDriver()/getDriver() instead.
<del> * @param \Cake\Database\Driver|string|null $driver The driver instance to use.
<del> * @param array $config Either config for a new driver or null.
<del> * @throws \Cake\Database\Exception\MissingDriverException When a driver class is missing.
<del> * @throws \Cake\Database\Exception\MissingExtensionException When a driver's PHP extension is missing.
<del> * @return \Cake\Database\Driver
<del> */
<del> public function driver($driver = null, $config = [])
<del> {
<del> deprecationWarning('Connection::driver() is deprecated. Use Connection::setDriver()/getDriver() instead.');
<del> if ($driver !== null) {
<del> $this->setDriver($driver, $config);
<del> }
<del>
<del> return $this->getDriver();
<del> }
<del>
<ide> /**
<ide> * Connects to the configured database.
<ide> *
<ide> public function getSchemaCollection()
<ide> return $this->_schemaCollection = new SchemaCollection($this);
<ide> }
<ide>
<del> /**
<del> * Gets or sets a Schema\Collection object for this connection.
<del> *
<del> * @deprecated 3.4.0 Use setSchemaCollection()/getSchemaCollection()
<del> * @param \Cake\Database\Schema\Collection|null $collection The schema collection object
<del> * @return \Cake\Database\Schema\Collection
<del> */
<del> public function schemaCollection(SchemaCollection $collection = null)
<del> {
<del> deprecationWarning(
<del> 'Connection::schemaCollection() is deprecated. ' .
<del> 'Use Connection::setSchemaCollection()/getSchemaCollection() instead.'
<del> );
<del> if ($collection !== null) {
<del> $this->setSchemaCollection($collection);
<del> }
<del>
<del> return $this->getSchemaCollection();
<del> }
<del>
<ide> /**
<ide> * Executes an INSERT query on the specified table.
<ide> *
<ide> public function isSavePointsEnabled()
<ide> return $this->_useSavePoints;
<ide> }
<ide>
<del> /**
<del> * Returns whether this connection is using savepoints for nested transactions
<del> * If a boolean is passed as argument it will enable/disable the usage of savepoints
<del> * only if driver the allows it.
<del> *
<del> * If you are trying to enable this feature, make sure you check the return value of this
<del> * function to verify it was enabled successfully.
<del> *
<del> * ### Example:
<del> *
<del> * `$connection->useSavePoints(true)` Returns true if drivers supports save points, false otherwise
<del> * `$connection->useSavePoints(false)` Disables usage of savepoints and returns false
<del> * `$connection->useSavePoints()` Returns current status
<del> *
<del> * @deprecated 3.4.0 Use enableSavePoints()/isSavePointsEnabled() instead.
<del> * @param bool|null $enable Whether or not save points should be used.
<del> * @return bool true if enabled, false otherwise
<del> */
<del> public function useSavePoints($enable = null)
<del> {
<del> deprecationWarning(
<del> 'Connection::useSavePoints() is deprecated. ' .
<del> 'Use Connection::enableSavePoints()/isSavePointsEnabled() instead.'
<del> );
<del> if ($enable !== null) {
<del> $this->enableSavePoints($enable);
<del> }
<del>
<del> return $this->isSavePointsEnabled();
<del> }
<del>
<ide> /**
<ide> * Creates a new save point for nested transactions.
<ide> *
<ide> public function logQueries($enable = null)
<ide> $this->_logQueries = $enable;
<ide> }
<ide>
<del> /**
<del> * {@inheritDoc}
<del> *
<del> * @deprecated 3.5.0 Use getLogger() and setLogger() instead.
<del> */
<del> public function logger($instance = null)
<del> {
<del> deprecationWarning(
<del> 'Connection::logger() is deprecated. ' .
<del> 'Use Connection::setLogger()/getLogger() instead.'
<del> );
<del> if ($instance === null) {
<del> return $this->getLogger();
<del> }
<del>
<del> $this->setLogger($instance);
<del> }
<del>
<ide> /**
<ide> * Sets a logger
<ide> *
<ide><path>src/Database/SchemaCache.php
<ide> public function clear($name = null)
<ide> */
<ide> public function getSchema(Connection $connection)
<ide> {
<del> if (!method_exists($connection, 'schemaCollection')) {
<del> throw new RuntimeException('The given connection object is not compatible with schema caching, as it does not implement a "schemaCollection()" method.');
<del> }
<del>
<ide> $config = $connection->config();
<ide> if (empty($config['cacheMetadata'])) {
<ide> $connection->cacheMetadata(true);
<ide><path>src/Datasource/ConnectionInterface.php
<ide> public function disableConstraints(callable $operation);
<ide> * @return bool
<ide> */
<ide> public function logQueries($enable = null);
<del>
<del> /**
<del> * Sets the logger object instance. When called with no arguments
<del> * it returns the currently setup logger instance.
<del> *
<del> * @param object|null $instance logger object instance
<del> * @return object logger instance
<del> * @deprecated 3.5.0 Will be replaced by getLogger()/setLogger()
<del> */
<del> public function logger($instance = null);
<ide> }
<ide><path>tests/TestCase/Database/ConnectionTest.php
<ide> public function testGetLoggerDefault()
<ide> $this->assertSame($logger, $this->connection->getLogger());
<ide> }
<ide>
<del> /**
<del> * Tests that a custom logger object can be set
<del> *
<del> * @group deprecated
<del> * @return void
<del> */
<del> public function testSetLogger()
<del> {
<del> $this->deprecated(function () {
<del> $logger = new QueryLogger;
<del> $this->connection->logger($logger);
<del> $this->assertSame($logger, $this->connection->logger());
<del> });
<del> }
<del>
<ide> /**
<ide> * Tests setting and getting the logger object
<ide> *
<ide> public function testSetSchemaCollection()
<ide> $this->assertSame($schema, $connection->getSchemaCollection());
<ide> }
<ide>
<del> /**
<del> * Tests it is possible to set a schema collection object
<del> *
<del> * @group deprecated
<del> * @return void
<del> */
<del> public function testSchemaCollection()
<del> {
<del> $this->deprecated(function () {
<del> $driver = $this->getMockFormDriver();
<del> $connection = $this->getMockBuilder(Connection::class)
<del> ->setMethods(['connect'])
<del> ->setConstructorArgs([['driver' => $driver]])
<del> ->getMock();
<del>
<del> $schema = $connection->schemaCollection();
<del> $this->assertInstanceOf('Cake\Database\Schema\Collection', $schema);
<del>
<del> $schema = $this->getMockBuilder('Cake\Database\Schema\Collection')
<del> ->setConstructorArgs([$connection])
<del> ->getMock();
<del> $connection->schemaCollection($schema);
<del> $this->assertSame($schema, $connection->schemaCollection());
<del> });
<del> }
<del>
<ide> /**
<ide> * Tests that allowed nesting of commit/rollback operations doesn't
<ide> * throw any exceptions. | 4 |
Javascript | Javascript | refactor the import of internalutil | 1a12b82396c6c0747f8f5c96a28d019f774e0257 | <ide><path>lib/internal/fs/streams.js
<ide> const {
<ide> ERR_OUT_OF_RANGE,
<ide> ERR_STREAM_DESTROYED
<ide> } = require('internal/errors').codes;
<del>const internalUtil = require('internal/util');
<add>const { deprecate } = require('internal/util');
<ide> const { validateNumber } = require('internal/validators');
<ide> const fs = require('fs');
<ide> const { Buffer } = require('buffer');
<ide> function ReadStream(path, options) {
<ide> ObjectSetPrototypeOf(ReadStream.prototype, Readable.prototype);
<ide> ObjectSetPrototypeOf(ReadStream, Readable);
<ide>
<del>const openReadFs = internalUtil.deprecate(function() {
<add>const openReadFs = deprecate(function() {
<ide> _openReadFs(this);
<ide> }, 'ReadStream.prototype.open() is deprecated', 'DEP0135');
<ide> ReadStream.prototype.open = openReadFs;
<ide> WriteStream.prototype._final = function(callback) {
<ide> callback();
<ide> };
<ide>
<del>const openWriteFs = internalUtil.deprecate(function() {
<add>const openWriteFs = deprecate(function() {
<ide> _openWriteFs(this);
<ide> }, 'WriteStream.prototype.open() is deprecated', 'DEP0135');
<ide> WriteStream.prototype.open = openWriteFs; | 1 |
Go | Go | add newdaemon without testingt | 04d9e157b2b09401ae3e9e00e143606218910580 | <ide><path>testutil/daemon/daemon.go
<ide> type logT interface {
<ide> Logf(string, ...interface{})
<ide> }
<ide>
<add>// nopLog is a no-op implementation of logT that is used in daemons created by
<add>// NewDaemon (where no testingT is available).
<add>type nopLog struct{}
<add>
<add>func (nopLog) Logf(string, ...interface{}) {}
<add>
<ide> const defaultDockerdBinary = "dockerd"
<ide> const containerdSocket = "/var/run/docker/containerd/containerd.sock"
<ide>
<ide> type Daemon struct {
<ide> CachedInfo types.Info
<ide> }
<ide>
<del>// New returns a Daemon instance to be used for testing.
<del>// This will create a directory such as d123456789 in the folder specified by $DOCKER_INTEGRATION_DAEMON_DEST or $DEST.
<add>// NewDaemon returns a Daemon instance to be used for testing.
<ide> // The daemon will not automatically start.
<del>func New(t testingT, ops ...Option) *Daemon {
<del> if ht, ok := t.(testutil.HelperT); ok {
<del> ht.Helper()
<del> }
<del> dest := os.Getenv("DOCKER_INTEGRATION_DAEMON_DEST")
<del> if dest == "" {
<del> dest = os.Getenv("DEST")
<del> }
<del> switch v := t.(type) {
<del> case namer:
<del> dest = filepath.Join(dest, v.Name())
<del> case testNamer:
<del> dest = filepath.Join(dest, v.TestName())
<del> }
<del> t.Logf("Creating a new daemon at: %s", dest)
<del> assert.Check(t, dest != "", "Please set the DOCKER_INTEGRATION_DAEMON_DEST or the DEST environment variable")
<del>
<add>// The daemon will modify and create files under workingDir.
<add>func NewDaemon(workingDir string, ops ...Option) (*Daemon, error) {
<ide> storageDriver := os.Getenv("DOCKER_GRAPHDRIVER")
<ide>
<del> assert.NilError(t, os.MkdirAll(SockRoot, 0700), "could not create daemon socket root")
<add> if err := os.MkdirAll(SockRoot, 0700); err != nil {
<add> return nil, fmt.Errorf("could not create daemon socket root: %v", err)
<add> }
<ide>
<ide> id := fmt.Sprintf("d%s", stringid.TruncateID(stringid.GenerateRandomID()))
<del> dir := filepath.Join(dest, id)
<add> dir := filepath.Join(workingDir, id)
<ide> daemonFolder, err := filepath.Abs(dir)
<del> assert.NilError(t, err, "Could not make %q an absolute path", dir)
<add> if err != nil {
<add> return nil, err
<add> }
<ide> daemonRoot := filepath.Join(daemonFolder, "root")
<del>
<del> assert.NilError(t, os.MkdirAll(daemonRoot, 0755), "Could not create daemon root %q", dir)
<add> if err := os.MkdirAll(daemonRoot, 0755); err != nil {
<add> return nil, fmt.Errorf("could not create daemon root: %v", err)
<add> }
<ide>
<ide> userlandProxy := true
<ide> if env := os.Getenv("DOCKER_USERLANDPROXY"); env != "" {
<ide> func New(t testingT, ops ...Option) *Daemon {
<ide> dockerdBinary: defaultDockerdBinary,
<ide> swarmListenAddr: defaultSwarmListenAddr,
<ide> SwarmPort: DefaultSwarmPort,
<del> log: t,
<add> log: nopLog{},
<ide> }
<ide>
<ide> for _, op := range ops {
<ide> op(d)
<ide> }
<ide>
<add> return d, nil
<add>}
<add>
<add>// New returns a Daemon instance to be used for testing.
<add>// This will create a directory such as d123456789 in the folder specified by
<add>// $DOCKER_INTEGRATION_DAEMON_DEST or $DEST.
<add>// The daemon will not automatically start.
<add>func New(t testingT, ops ...Option) *Daemon {
<add> if ht, ok := t.(testutil.HelperT); ok {
<add> ht.Helper()
<add> }
<add> dest := os.Getenv("DOCKER_INTEGRATION_DAEMON_DEST")
<add> if dest == "" {
<add> dest = os.Getenv("DEST")
<add> }
<add>
<add> switch v := t.(type) {
<add> case namer:
<add> dest = filepath.Join(dest, v.Name())
<add> case testNamer:
<add> dest = filepath.Join(dest, v.TestName())
<add> }
<add> assert.Check(t, dest != "", "Please set the DOCKER_INTEGRATION_DAEMON_DEST or the DEST environment variable")
<add>
<add> t.Logf("Creating a new daemon at: %q", dest)
<add> d, err := NewDaemon(dest, ops...)
<add> assert.NilError(t, err, "could not create daemon")
<add>
<ide> return d
<ide> }
<ide>
<ide> func (d *Daemon) NewClientT(t assert.TestingT, extraOpts ...client.Opt) *client.
<ide> ht.Helper()
<ide> }
<ide>
<add> c, err := d.NewClient(extraOpts...)
<add> assert.NilError(t, err, "cannot create daemon client")
<add> return c
<add>}
<add>
<add>// NewClient creates new client based on daemon's socket path
<add>func (d *Daemon) NewClient(extraOpts ...client.Opt) (*client.Client, error) {
<ide> clientOpts := []client.Opt{
<ide> client.FromEnv,
<ide> client.WithHost(d.Sock()),
<ide> }
<ide> clientOpts = append(clientOpts, extraOpts...)
<ide>
<del> c, err := client.NewClientWithOpts(clientOpts...)
<del> assert.NilError(t, err, "cannot create daemon client")
<del> return c
<add> return client.NewClientWithOpts(clientOpts...)
<ide> }
<ide>
<ide> // Cleanup cleans the daemon files : exec root (network namespaces, ...), swarmkit files
<ide><path>testutil/daemon/ops.go
<ide> package daemon
<ide>
<del>import "github.com/docker/docker/testutil/environment"
<add>import (
<add> "testing"
<add>
<add> "github.com/docker/docker/testutil/environment"
<add>)
<ide>
<ide> // Option is used to configure a daemon.
<ide> type Option func(*Daemon)
<ide> func WithDefaultCgroupNamespaceMode(mode string) Option {
<ide> }
<ide> }
<ide>
<add>// WithTestLogger causes the daemon to log certain actions to the provided test.
<add>func WithTestLogger(t testing.TB) func(*Daemon) {
<add> return func(d *Daemon) {
<add> d.log = t
<add> }
<add>}
<add>
<ide> // WithExperimental sets the daemon in experimental mode
<ide> func WithExperimental(d *Daemon) {
<ide> d.experimental = true | 2 |
Go | Go | remove use of global volume driver store | 977109d808ae94eb3931ae920338b1aa669f627e | <ide><path>daemon/daemon.go
<ide> func setDefaultMtu(conf *config.Config) {
<ide> }
<ide>
<ide> func (daemon *Daemon) configureVolumes(rootIDs idtools.IDPair) (*store.VolumeStore, error) {
<del> volumesDriver, err := local.New(daemon.configStore.Root, rootIDs)
<add> volumeDriver, err := local.New(daemon.configStore.Root, rootIDs)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<del>
<del> volumedrivers.RegisterPluginGetter(daemon.PluginStore)
<del>
<del> if !volumedrivers.Register(volumesDriver, volumesDriver.Name()) {
<add> drivers := volumedrivers.NewStore(daemon.PluginStore)
<add> if !drivers.Register(volumeDriver, volumeDriver.Name()) {
<ide> return nil, errors.New("local volume driver could not be registered")
<ide> }
<del> return store.New(daemon.configStore.Root)
<add> return store.New(daemon.configStore.Root, drivers)
<ide> }
<ide>
<ide> // IsShuttingDown tells whether the daemon is shutting down or not
<ide><path>daemon/daemon_test.go
<ide> import (
<ide> _ "github.com/docker/docker/pkg/discovery/memory"
<ide> "github.com/docker/docker/pkg/idtools"
<ide> "github.com/docker/docker/pkg/truncindex"
<del> "github.com/docker/docker/volume"
<ide> volumedrivers "github.com/docker/docker/volume/drivers"
<ide> "github.com/docker/docker/volume/local"
<ide> "github.com/docker/docker/volume/store"
<ide> func initDaemonWithVolumeStore(tmp string) (*Daemon, error) {
<ide> repository: tmp,
<ide> root: tmp,
<ide> }
<del> daemon.volumes, err = store.New(tmp)
<add> drivers := volumedrivers.NewStore(nil)
<add> daemon.volumes, err = store.New(tmp, drivers)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide> func initDaemonWithVolumeStore(tmp string) (*Daemon, error) {
<ide> if err != nil {
<ide> return nil, err
<ide> }
<del> volumedrivers.Register(volumesDriver, volumesDriver.Name())
<add> drivers.Register(volumesDriver, volumesDriver.Name())
<ide>
<ide> return daemon, nil
<ide> }
<ide> func TestContainerInitDNS(t *testing.T) {
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<del> defer volumedrivers.Unregister(volume.DefaultDriverName)
<ide>
<ide> c, err := daemon.load(containerID)
<ide> if err != nil {
<ide><path>daemon/info.go
<ide> import (
<ide> "github.com/docker/docker/pkg/sysinfo"
<ide> "github.com/docker/docker/pkg/system"
<ide> "github.com/docker/docker/registry"
<del> "github.com/docker/docker/volume/drivers"
<ide> "github.com/docker/go-connections/sockets"
<ide> "github.com/sirupsen/logrus"
<ide> )
<ide> func (daemon *Daemon) SystemVersion() types.Version {
<ide> func (daemon *Daemon) showPluginsInfo() types.PluginsInfo {
<ide> var pluginsInfo types.PluginsInfo
<ide>
<del> pluginsInfo.Volume = volumedrivers.GetDriverList()
<add> pluginsInfo.Volume = daemon.volumes.GetDriverList()
<ide> pluginsInfo.Network = daemon.GetNetworkDriverList()
<ide> // The authorization plugins are returned in the order they are
<ide> // used as they constitute a request/response modification chain.
<ide><path>volume/drivers/extpoint.go
<ide> import (
<ide> "sort"
<ide> "sync"
<ide>
<add> "github.com/docker/docker/errdefs"
<ide> "github.com/docker/docker/pkg/locker"
<ide> getter "github.com/docker/docker/pkg/plugingetter"
<ide> "github.com/docker/docker/volume"
<ide> "github.com/pkg/errors"
<ide> "github.com/sirupsen/logrus"
<ide> )
<ide>
<del>// currently created by hand. generation tool would generate this like:
<del>// $ extpoint-gen Driver > volume/extpoint.go
<del>
<del>var drivers = &driverExtpoint{
<del> extensions: make(map[string]volume.Driver),
<del> driverLock: &locker.Locker{},
<del>}
<del>
<ide> const extName = "VolumeDriver"
<ide>
<ide> // NewVolumeDriver returns a driver has the given name mapped on the given client.
<ide> type volumeDriver interface {
<ide> Capabilities() (capabilities volume.Capability, err error)
<ide> }
<ide>
<del>type driverExtpoint struct {
<del> extensions map[string]volume.Driver
<del> sync.Mutex
<add>// Store is an in-memory store for volume drivers
<add>type Store struct {
<add> extensions map[string]volume.Driver
<add> mu sync.Mutex
<ide> driverLock *locker.Locker
<del> plugingetter getter.PluginGetter
<add> pluginGetter getter.PluginGetter
<ide> }
<ide>
<del>// RegisterPluginGetter sets the plugingetter
<del>func RegisterPluginGetter(plugingetter getter.PluginGetter) {
<del> drivers.plugingetter = plugingetter
<del>}
<del>
<del>// Register associates the given driver to the given name, checking if
<del>// the name is already associated
<del>func Register(extension volume.Driver, name string) bool {
<del> if name == "" {
<del> return false
<del> }
<del>
<del> drivers.Lock()
<del> defer drivers.Unlock()
<del>
<del> _, exists := drivers.extensions[name]
<del> if exists {
<del> return false
<add>// NewStore creates a new volume driver store
<add>func NewStore(pg getter.PluginGetter) *Store {
<add> return &Store{
<add> extensions: make(map[string]volume.Driver),
<add> driverLock: locker.New(),
<add> pluginGetter: pg,
<ide> }
<del>
<del> if err := validateDriver(extension); err != nil {
<del> return false
<del> }
<del>
<del> drivers.extensions[name] = extension
<del>
<del> return true
<del>}
<del>
<del>// Unregister dissociates the name from its driver, if the association exists.
<del>func Unregister(name string) bool {
<del> drivers.Lock()
<del> defer drivers.Unlock()
<del>
<del> _, exists := drivers.extensions[name]
<del> if !exists {
<del> return false
<del> }
<del> delete(drivers.extensions, name)
<del> return true
<ide> }
<ide>
<ide> type driverNotFoundError string
<ide> func (driverNotFoundError) NotFound() {}
<ide> // lookup returns the driver associated with the given name. If a
<ide> // driver with the given name has not been registered it checks if
<ide> // there is a VolumeDriver plugin available with the given name.
<del>func lookup(name string, mode int) (volume.Driver, error) {
<del> drivers.driverLock.Lock(name)
<del> defer drivers.driverLock.Unlock(name)
<add>func (s *Store) lookup(name string, mode int) (volume.Driver, error) {
<add> if name == "" {
<add> return nil, errdefs.InvalidParameter(errors.New("driver name cannot be empty"))
<add> }
<add> s.driverLock.Lock(name)
<add> defer s.driverLock.Unlock(name)
<ide>
<del> drivers.Lock()
<del> ext, ok := drivers.extensions[name]
<del> drivers.Unlock()
<add> s.mu.Lock()
<add> ext, ok := s.extensions[name]
<add> s.mu.Unlock()
<ide> if ok {
<ide> return ext, nil
<ide> }
<del> if drivers.plugingetter != nil {
<del> p, err := drivers.plugingetter.Get(name, extName, mode)
<add> if s.pluginGetter != nil {
<add> p, err := s.pluginGetter.Get(name, extName, mode)
<ide> if err != nil {
<ide> return nil, errors.Wrap(err, "error looking up volume plugin "+name)
<ide> }
<ide> func lookup(name string, mode int) (volume.Driver, error) {
<ide> if err := validateDriver(d); err != nil {
<ide> if mode > 0 {
<ide> // Undo any reference count changes from the initial `Get`
<del> if _, err := drivers.plugingetter.Get(name, extName, mode*-1); err != nil {
<add> if _, err := s.pluginGetter.Get(name, extName, mode*-1); err != nil {
<ide> logrus.WithError(err).WithField("action", "validate-driver").WithField("plugin", name).Error("error releasing reference to plugin")
<ide> }
<ide> }
<ide> return nil, err
<ide> }
<ide>
<ide> if p.IsV1() {
<del> drivers.Lock()
<del> drivers.extensions[name] = d
<del> drivers.Unlock()
<add> s.mu.Lock()
<add> s.extensions[name] = d
<add> s.mu.Unlock()
<ide> }
<ide> return d, nil
<ide> }
<ide> func validateDriver(vd volume.Driver) error {
<ide> return nil
<ide> }
<ide>
<del>// GetDriver returns a volume driver by its name.
<del>// If the driver is empty, it looks for the local driver.
<del>func GetDriver(name string) (volume.Driver, error) {
<add>// Register associates the given driver to the given name, checking if
<add>// the name is already associated
<add>func (s *Store) Register(d volume.Driver, name string) bool {
<ide> if name == "" {
<del> name = volume.DefaultDriverName
<add> return false
<add> }
<add>
<add> s.mu.Lock()
<add> defer s.mu.Unlock()
<add>
<add> if _, exists := s.extensions[name]; exists {
<add> return false
<add> }
<add>
<add> if err := validateDriver(d); err != nil {
<add> return false
<ide> }
<del> return lookup(name, getter.Lookup)
<add>
<add> s.extensions[name] = d
<add> return true
<add>}
<add>
<add>// GetDriver returns a volume driver by its name.
<add>// If the driver is empty, it looks for the local driver.
<add>func (s *Store) GetDriver(name string) (volume.Driver, error) {
<add> return s.lookup(name, getter.Lookup)
<ide> }
<ide>
<ide> // CreateDriver returns a volume driver by its name and increments RefCount.
<ide> // If the driver is empty, it looks for the local driver.
<del>func CreateDriver(name string) (volume.Driver, error) {
<del> if name == "" {
<del> name = volume.DefaultDriverName
<del> }
<del> return lookup(name, getter.Acquire)
<add>func (s *Store) CreateDriver(name string) (volume.Driver, error) {
<add> return s.lookup(name, getter.Acquire)
<ide> }
<ide>
<ide> // ReleaseDriver returns a volume driver by its name and decrements RefCount..
<ide> // If the driver is empty, it looks for the local driver.
<del>func ReleaseDriver(name string) (volume.Driver, error) {
<del> if name == "" {
<del> name = volume.DefaultDriverName
<del> }
<del> return lookup(name, getter.Release)
<add>func (s *Store) ReleaseDriver(name string) (volume.Driver, error) {
<add> return s.lookup(name, getter.Release)
<ide> }
<ide>
<ide> // GetDriverList returns list of volume drivers registered.
<ide> // If no driver is registered, empty string list will be returned.
<del>func GetDriverList() []string {
<add>func (s *Store) GetDriverList() []string {
<ide> var driverList []string
<del> drivers.Lock()
<del> for driverName := range drivers.extensions {
<add> s.mu.Lock()
<add> for driverName := range s.extensions {
<ide> driverList = append(driverList, driverName)
<ide> }
<del> drivers.Unlock()
<add> s.mu.Unlock()
<ide> sort.Strings(driverList)
<ide> return driverList
<ide> }
<ide>
<ide> // GetAllDrivers lists all the registered drivers
<del>func GetAllDrivers() ([]volume.Driver, error) {
<add>func (s *Store) GetAllDrivers() ([]volume.Driver, error) {
<ide> var plugins []getter.CompatPlugin
<del> if drivers.plugingetter != nil {
<add> if s.pluginGetter != nil {
<ide> var err error
<del> plugins, err = drivers.plugingetter.GetAllByCap(extName)
<add> plugins, err = s.pluginGetter.GetAllByCap(extName)
<ide> if err != nil {
<ide> return nil, fmt.Errorf("error listing plugins: %v", err)
<ide> }
<ide> }
<ide> var ds []volume.Driver
<ide>
<del> drivers.Lock()
<del> defer drivers.Unlock()
<add> s.mu.Lock()
<add> defer s.mu.Unlock()
<ide>
<del> for _, d := range drivers.extensions {
<add> for _, d := range s.extensions {
<ide> ds = append(ds, d)
<ide> }
<ide>
<ide> for _, p := range plugins {
<ide> name := p.Name()
<ide>
<del> if _, ok := drivers.extensions[name]; ok {
<add> if _, ok := s.extensions[name]; ok {
<ide> continue
<ide> }
<ide>
<ide> ext := NewVolumeDriver(name, p.ScopedPath, p.Client())
<ide> if p.IsV1() {
<del> drivers.extensions[name] = ext
<add> s.extensions[name] = ext
<ide> }
<ide> ds = append(ds, ext)
<ide> }
<ide><path>volume/drivers/extpoint_test.go
<ide> import (
<ide> )
<ide>
<ide> func TestGetDriver(t *testing.T) {
<del> _, err := GetDriver("missing")
<add> s := NewStore(nil)
<add> _, err := s.GetDriver("missing")
<ide> if err == nil {
<ide> t.Fatal("Expected error, was nil")
<ide> }
<del> Register(volumetestutils.NewFakeDriver("fake"), "fake")
<add> s.Register(volumetestutils.NewFakeDriver("fake"), "fake")
<ide>
<del> d, err := GetDriver("fake")
<add> d, err := s.GetDriver("fake")
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide><path>volume/store/restore.go
<ide> import (
<ide>
<ide> "github.com/boltdb/bolt"
<ide> "github.com/docker/docker/volume"
<del> "github.com/docker/docker/volume/drivers"
<ide> "github.com/sirupsen/logrus"
<ide> )
<ide>
<ide> func (s *VolumeStore) restore() {
<ide> var v volume.Volume
<ide> var err error
<ide> if meta.Driver != "" {
<del> v, err = lookupVolume(meta.Driver, meta.Name)
<add> v, err = lookupVolume(s.drivers, meta.Driver, meta.Name)
<ide> if err != nil && err != errNoSuchVolume {
<ide> logrus.WithError(err).WithField("driver", meta.Driver).WithField("volume", meta.Name).Warn("Error restoring volume")
<ide> return
<ide> func (s *VolumeStore) restore() {
<ide> }
<ide>
<ide> // increment driver refcount
<del> volumedrivers.CreateDriver(meta.Driver)
<add> s.drivers.CreateDriver(meta.Driver)
<ide>
<ide> // cache the volume
<ide> s.globalLock.Lock()
<ide><path>volume/store/restore_test.go
<ide> func TestRestore(t *testing.T) {
<ide> assert.NilError(t, err)
<ide> defer os.RemoveAll(dir)
<ide>
<add> drivers := volumedrivers.NewStore(nil)
<ide> driverName := "test-restore"
<del> volumedrivers.Register(volumetestutils.NewFakeDriver(driverName), driverName)
<del> defer volumedrivers.Unregister("test-restore")
<add> drivers.Register(volumetestutils.NewFakeDriver(driverName), driverName)
<ide>
<del> s, err := New(dir)
<add> s, err := New(dir, drivers)
<ide> assert.NilError(t, err)
<ide> defer s.Shutdown()
<ide>
<ide> func TestRestore(t *testing.T) {
<ide>
<ide> s.Shutdown()
<ide>
<del> s, err = New(dir)
<add> s, err = New(dir, drivers)
<ide> assert.NilError(t, err)
<ide>
<ide> v, err := s.Get("test1")
<ide><path>volume/store/store.go
<ide> func (v volumeWrapper) CachedPath() string {
<ide>
<ide> // New initializes a VolumeStore to keep
<ide> // reference counting of volumes in the system.
<del>func New(rootPath string) (*VolumeStore, error) {
<add>func New(rootPath string, drivers *drivers.Store) (*VolumeStore, error) {
<ide> vs := &VolumeStore{
<ide> locks: &locker.Locker{},
<ide> names: make(map[string]volume.Volume),
<ide> refs: make(map[string]map[string]struct{}),
<ide> labels: make(map[string]map[string]string),
<ide> options: make(map[string]map[string]string),
<add> drivers: drivers,
<ide> }
<ide>
<ide> if rootPath != "" {
<ide> func (s *VolumeStore) Purge(name string) {
<ide> v, exists := s.names[name]
<ide> if exists {
<ide> driverName := v.DriverName()
<del> if _, err := volumedrivers.ReleaseDriver(driverName); err != nil {
<add> if _, err := s.drivers.ReleaseDriver(driverName); err != nil {
<ide> logrus.WithError(err).WithField("driver", driverName).Error("Error releasing reference to volume driver")
<ide> }
<ide> }
<ide> func (s *VolumeStore) Purge(name string) {
<ide> type VolumeStore struct {
<ide> // locks ensures that only one action is being performed on a particular volume at a time without locking the entire store
<ide> // since actions on volumes can be quite slow, this ensures the store is free to handle requests for other volumes.
<del> locks *locker.Locker
<add> locks *locker.Locker
<add> drivers *drivers.Store
<ide> // globalLock is used to protect access to mutable structures used by the store object
<ide> globalLock sync.RWMutex
<ide> // names stores the volume name -> volume relationship.
<ide> func (s *VolumeStore) list() ([]volume.Volume, []string, error) {
<ide> warnings []string
<ide> )
<ide>
<del> drivers, err := volumedrivers.GetAllDrivers()
<add> drivers, err := s.drivers.GetAllDrivers()
<ide> if err != nil {
<ide> return nil, nil, err
<ide> }
<ide> func (s *VolumeStore) checkConflict(name, driverName string) (volume.Volume, err
<ide> if driverName != "" {
<ide> // Retrieve canonical driver name to avoid inconsistencies (for example
<ide> // "plugin" vs. "plugin:latest")
<del> vd, err := volumedrivers.GetDriver(driverName)
<add> vd, err := s.drivers.GetDriver(driverName)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide> func (s *VolumeStore) checkConflict(name, driverName string) (volume.Volume, err
<ide>
<ide> // let's check if the found volume ref
<ide> // is stale by checking with the driver if it still exists
<del> exists, err := volumeExists(v)
<add> exists, err := volumeExists(s.drivers, v)
<ide> if err != nil {
<ide> return nil, errors.Wrapf(errNameConflict, "found reference to volume '%s' in driver '%s', but got an error while checking the driver: %v", name, vDriverName, err)
<ide> }
<ide> func (s *VolumeStore) checkConflict(name, driverName string) (volume.Volume, err
<ide>
<ide> // volumeExists returns if the volume is still present in the driver.
<ide> // An error is returned if there was an issue communicating with the driver.
<del>func volumeExists(v volume.Volume) (bool, error) {
<del> exists, err := lookupVolume(v.DriverName(), v.Name())
<add>func volumeExists(store *drivers.Store, v volume.Volume) (bool, error) {
<add> exists, err := lookupVolume(store, v.DriverName(), v.Name())
<ide> if err != nil {
<ide> return false, err
<ide> }
<ide> func (s *VolumeStore) create(name, driverName string, opts, labels map[string]st
<ide> }
<ide> }
<ide>
<del> vd, err := volumedrivers.CreateDriver(driverName)
<add> if driverName == "" {
<add> driverName = volume.DefaultDriverName
<add> }
<add> vd, err := s.drivers.CreateDriver(driverName)
<ide> if err != nil {
<ide> return nil, &OpErr{Op: "create", Name: name, Err: err}
<ide> }
<ide> func (s *VolumeStore) create(name, driverName string, opts, labels map[string]st
<ide> if v, _ = vd.Get(name); v == nil {
<ide> v, err = vd.Create(name, opts)
<ide> if err != nil {
<del> if _, err := volumedrivers.ReleaseDriver(driverName); err != nil {
<add> if _, err := s.drivers.ReleaseDriver(driverName); err != nil {
<ide> logrus.WithError(err).WithField("driver", driverName).Error("Error releasing reference to volume driver")
<ide> }
<ide> return nil, err
<ide> func (s *VolumeStore) GetWithRef(name, driverName, ref string) (volume.Volume, e
<ide> s.locks.Lock(name)
<ide> defer s.locks.Unlock(name)
<ide>
<del> vd, err := volumedrivers.GetDriver(driverName)
<add> if driverName == "" {
<add> driverName = volume.DefaultDriverName
<add> }
<add> vd, err := s.drivers.GetDriver(driverName)
<ide> if err != nil {
<ide> return nil, &OpErr{Err: err, Name: name, Op: "get"}
<ide> }
<ide> func (s *VolumeStore) getVolume(name string) (volume.Volume, error) {
<ide> }
<ide>
<ide> if meta.Driver != "" {
<del> vol, err := lookupVolume(meta.Driver, name)
<add> vol, err := lookupVolume(s.drivers, meta.Driver, name)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide> func (s *VolumeStore) getVolume(name string) (volume.Volume, error) {
<ide> }
<ide>
<ide> var scope string
<del> vd, err := volumedrivers.GetDriver(meta.Driver)
<add> vd, err := s.drivers.GetDriver(meta.Driver)
<ide> if err == nil {
<ide> scope = vd.Scope()
<ide> }
<ide> return volumeWrapper{vol, meta.Labels, scope, meta.Options}, nil
<ide> }
<ide>
<ide> logrus.Debugf("Probing all drivers for volume with name: %s", name)
<del> drivers, err := volumedrivers.GetAllDrivers()
<add> drivers, err := s.drivers.GetAllDrivers()
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide> func (s *VolumeStore) getVolume(name string) (volume.Volume, error) {
<ide> // If the driver returns an error that is not communication related the
<ide> // error is logged but not returned.
<ide> // If the volume is not found it will return `nil, nil``
<del>func lookupVolume(driverName, volumeName string) (volume.Volume, error) {
<del> vd, err := volumedrivers.GetDriver(driverName)
<add>func lookupVolume(store *drivers.Store, driverName, volumeName string) (volume.Volume, error) {
<add> if driverName == "" {
<add> driverName = volume.DefaultDriverName
<add> }
<add> vd, err := store.GetDriver(driverName)
<ide> if err != nil {
<ide> return nil, errors.Wrapf(err, "error while checking if volume %q exists in driver %q", volumeName, driverName)
<ide> }
<ide> func (s *VolumeStore) Remove(v volume.Volume) error {
<ide> return &OpErr{Err: errVolumeInUse, Name: v.Name(), Op: "remove", Refs: s.getRefs(name)}
<ide> }
<ide>
<del> vd, err := volumedrivers.GetDriver(v.DriverName())
<add> vd, err := s.drivers.GetDriver(v.DriverName())
<ide> if err != nil {
<ide> return &OpErr{Err: err, Name: v.DriverName(), Op: "remove"}
<ide> }
<ide> func (s *VolumeStore) Refs(v volume.Volume) []string {
<ide>
<ide> // FilterByDriver returns the available volumes filtered by driver name
<ide> func (s *VolumeStore) FilterByDriver(name string) ([]volume.Volume, error) {
<del> vd, err := volumedrivers.GetDriver(name)
<add> vd, err := s.drivers.GetDriver(name)
<ide> if err != nil {
<ide> return nil, &OpErr{Err: err, Name: name, Op: "list"}
<ide> }
<ide> func unwrapVolume(v volume.Volume) volume.Volume {
<ide> func (s *VolumeStore) Shutdown() error {
<ide> return s.db.Close()
<ide> }
<add>
<add>// GetDriverList gets the list of volume drivers from the configured volume driver
<add>// store.
<add>// TODO(@cpuguy83): This should be factored out into a separate service.
<add>func (s *VolumeStore) GetDriverList() []string {
<add> return s.drivers.GetDriverList()
<add>}
<ide><path>volume/store/store_test.go
<ide> import (
<ide> "testing"
<ide>
<ide> "github.com/docker/docker/volume"
<del> "github.com/docker/docker/volume/drivers"
<add> volumedrivers "github.com/docker/docker/volume/drivers"
<ide> volumetestutils "github.com/docker/docker/volume/testutils"
<ide> "github.com/google/go-cmp/cmp"
<ide> "github.com/gotestyourself/gotestyourself/assert"
<ide> is "github.com/gotestyourself/gotestyourself/assert/cmp"
<ide> )
<ide>
<ide> func TestCreate(t *testing.T) {
<del> volumedrivers.Register(volumetestutils.NewFakeDriver("fake"), "fake")
<del> defer volumedrivers.Unregister("fake")
<del> dir, err := ioutil.TempDir("", "test-create")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> defer os.RemoveAll(dir)
<add> t.Parallel()
<add>
<add> s, cleanup := setupTest(t)
<add> defer cleanup()
<add> s.drivers.Register(volumetestutils.NewFakeDriver("fake"), "fake")
<ide>
<del> s, err := New(dir)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<ide> v, err := s.Create("fake1", "fake", nil, nil)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> func TestCreate(t *testing.T) {
<ide> }
<ide>
<ide> func TestRemove(t *testing.T) {
<del> volumedrivers.Register(volumetestutils.NewFakeDriver("fake"), "fake")
<del> volumedrivers.Register(volumetestutils.NewFakeDriver("noop"), "noop")
<del> defer volumedrivers.Unregister("fake")
<del> defer volumedrivers.Unregister("noop")
<del> dir, err := ioutil.TempDir("", "test-remove")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> defer os.RemoveAll(dir)
<del> s, err := New(dir)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> t.Parallel()
<add>
<add> s, cleanup := setupTest(t)
<add> defer cleanup()
<add>
<add> s.drivers.Register(volumetestutils.NewFakeDriver("fake"), "fake")
<add> s.drivers.Register(volumetestutils.NewFakeDriver("noop"), "noop")
<ide>
<ide> // doing string compare here since this error comes directly from the driver
<ide> expected := "no such volume"
<ide> func TestRemove(t *testing.T) {
<ide> }
<ide>
<ide> func TestList(t *testing.T) {
<del> volumedrivers.Register(volumetestutils.NewFakeDriver("fake"), "fake")
<del> volumedrivers.Register(volumetestutils.NewFakeDriver("fake2"), "fake2")
<del> defer volumedrivers.Unregister("fake")
<del> defer volumedrivers.Unregister("fake2")
<add> t.Parallel()
<add>
<ide> dir, err := ioutil.TempDir("", "test-list")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> assert.NilError(t, err)
<ide> defer os.RemoveAll(dir)
<ide>
<del> s, err := New(dir)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> drivers := volumedrivers.NewStore(nil)
<add> drivers.Register(volumetestutils.NewFakeDriver("fake"), "fake")
<add> drivers.Register(volumetestutils.NewFakeDriver("fake2"), "fake2")
<add>
<add> s, err := New(dir, drivers)
<add> assert.NilError(t, err)
<add>
<ide> if _, err := s.Create("test", "fake", nil, nil); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> func TestList(t *testing.T) {
<ide> }
<ide>
<ide> // and again with a new store
<del> s, err = New(dir)
<add> s, err = New(dir, drivers)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> func TestList(t *testing.T) {
<ide> }
<ide>
<ide> func TestFilterByDriver(t *testing.T) {
<del> volumedrivers.Register(volumetestutils.NewFakeDriver("fake"), "fake")
<del> volumedrivers.Register(volumetestutils.NewFakeDriver("noop"), "noop")
<del> defer volumedrivers.Unregister("fake")
<del> defer volumedrivers.Unregister("noop")
<del> dir, err := ioutil.TempDir("", "test-filter-driver")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> s, err := New(dir)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> t.Parallel()
<add> s, cleanup := setupTest(t)
<add> defer cleanup()
<add>
<add> s.drivers.Register(volumetestutils.NewFakeDriver("fake"), "fake")
<add> s.drivers.Register(volumetestutils.NewFakeDriver("noop"), "noop")
<ide>
<ide> if _, err := s.Create("fake1", "fake", nil, nil); err != nil {
<ide> t.Fatal(err)
<ide> func TestFilterByDriver(t *testing.T) {
<ide> }
<ide>
<ide> func TestFilterByUsed(t *testing.T) {
<del> volumedrivers.Register(volumetestutils.NewFakeDriver("fake"), "fake")
<del> volumedrivers.Register(volumetestutils.NewFakeDriver("noop"), "noop")
<del> dir, err := ioutil.TempDir("", "test-filter-used")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> t.Parallel()
<add> s, cleanup := setupTest(t)
<add> defer cleanup()
<ide>
<del> s, err := New(dir)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> s.drivers.Register(volumetestutils.NewFakeDriver("fake"), "fake")
<add> s.drivers.Register(volumetestutils.NewFakeDriver("noop"), "noop")
<ide>
<ide> if _, err := s.CreateWithRef("fake1", "fake", "volReference", nil, nil); err != nil {
<ide> t.Fatal(err)
<ide> func TestFilterByUsed(t *testing.T) {
<ide> }
<ide>
<ide> func TestDerefMultipleOfSameRef(t *testing.T) {
<del> volumedrivers.Register(volumetestutils.NewFakeDriver("fake"), "fake")
<del> dir, err := ioutil.TempDir("", "test-same-deref")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> defer os.RemoveAll(dir)
<del> s, err := New(dir)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> t.Parallel()
<add> s, cleanup := setupTest(t)
<add> defer cleanup()
<add> s.drivers.Register(volumetestutils.NewFakeDriver("fake"), "fake")
<ide>
<ide> v, err := s.CreateWithRef("fake1", "fake", "volReference", nil, nil)
<ide> if err != nil {
<ide> func TestDerefMultipleOfSameRef(t *testing.T) {
<ide> }
<ide>
<ide> func TestCreateKeepOptsLabelsWhenExistsRemotely(t *testing.T) {
<add> t.Parallel()
<add> s, cleanup := setupTest(t)
<add> defer cleanup()
<add>
<ide> vd := volumetestutils.NewFakeDriver("fake")
<del> volumedrivers.Register(vd, "fake")
<del> dir, err := ioutil.TempDir("", "test-same-deref")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> defer os.RemoveAll(dir)
<del> s, err := New(dir)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> s.drivers.Register(vd, "fake")
<ide>
<ide> // Create a volume in the driver directly
<ide> if _, err := vd.Create("foo", nil); err != nil {
<ide> func TestCreateKeepOptsLabelsWhenExistsRemotely(t *testing.T) {
<ide> }
<ide>
<ide> func TestDefererencePluginOnCreateError(t *testing.T) {
<add> t.Parallel()
<add>
<ide> var (
<ide> l net.Listener
<ide> err error
<ide> func TestDefererencePluginOnCreateError(t *testing.T) {
<ide> }
<ide> defer l.Close()
<ide>
<add> s, cleanup := setupTest(t)
<add> defer cleanup()
<add>
<ide> d := volumetestutils.NewFakeDriver("TestDefererencePluginOnCreateError")
<ide> p, err := volumetestutils.MakeFakePlugin(d, l)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<ide> pg := volumetestutils.NewFakePluginGetter(p)
<del> volumedrivers.RegisterPluginGetter(pg)
<del> defer volumedrivers.RegisterPluginGetter(nil)
<del>
<del> dir, err := ioutil.TempDir("", "test-plugin-deref-err")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> defer os.RemoveAll(dir)
<del>
<del> s, err := New(dir)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<add> s.drivers = volumedrivers.NewStore(pg)
<ide>
<ide> // create a good volume so we have a plugin reference
<ide> _, err = s.Create("fake1", d.Name(), nil, nil)
<ide> func TestRefDerefRemove(t *testing.T) {
<ide> t.Parallel()
<ide>
<ide> driverName := "test-ref-deref-remove"
<del> s, cleanup := setupTest(t, driverName)
<del> defer cleanup(t)
<add> s, cleanup := setupTest(t)
<add> defer cleanup()
<add> s.drivers.Register(volumetestutils.NewFakeDriver(driverName), driverName)
<ide>
<ide> v, err := s.CreateWithRef("test", driverName, "test-ref", nil, nil)
<ide> assert.NilError(t, err)
<ide> func TestGet(t *testing.T) {
<ide> t.Parallel()
<ide>
<ide> driverName := "test-get"
<del> s, cleanup := setupTest(t, driverName)
<del> defer cleanup(t)
<add> s, cleanup := setupTest(t)
<add> defer cleanup()
<add> s.drivers.Register(volumetestutils.NewFakeDriver(driverName), driverName)
<ide>
<ide> _, err := s.Get("not-exist")
<ide> assert.Assert(t, is.ErrorContains(err, ""))
<ide> func TestGetWithRef(t *testing.T) {
<ide> t.Parallel()
<ide>
<ide> driverName := "test-get-with-ref"
<del> s, cleanup := setupTest(t, driverName)
<del> defer cleanup(t)
<add> s, cleanup := setupTest(t)
<add> defer cleanup()
<add> s.drivers.Register(volumetestutils.NewFakeDriver(driverName), driverName)
<ide>
<ide> _, err := s.GetWithRef("not-exist", driverName, "test-ref")
<ide> assert.Assert(t, is.ErrorContains(err, ""))
<ide> func TestGetWithRef(t *testing.T) {
<ide>
<ide> var cmpVolume = cmp.AllowUnexported(volumetestutils.FakeVolume{}, volumeWrapper{})
<ide>
<del>func setupTest(t *testing.T, name string) (*VolumeStore, func(*testing.T)) {
<del> t.Helper()
<del> s, cleanup := newTestStore(t)
<del>
<del> volumedrivers.Register(volumetestutils.NewFakeDriver(name), name)
<del> return s, func(t *testing.T) {
<del> cleanup(t)
<del> volumedrivers.Unregister(name)
<del> }
<del>}
<del>
<del>func newTestStore(t *testing.T) (*VolumeStore, func(*testing.T)) {
<add>func setupTest(t *testing.T) (*VolumeStore, func()) {
<ide> t.Helper()
<ide>
<del> dir, err := ioutil.TempDir("", "store-root")
<add> dirName := strings.Replace(t.Name(), string(os.PathSeparator), "_", -1)
<add> dir, err := ioutil.TempDir("", dirName)
<ide> assert.NilError(t, err)
<ide>
<del> cleanup := func(t *testing.T) {
<add> cleanup := func() {
<ide> err := os.RemoveAll(dir)
<ide> assert.Check(t, err)
<ide> }
<ide>
<del> s, err := New(dir)
<add> s, err := New(dir, volumedrivers.NewStore(nil))
<ide> assert.Check(t, err)
<del> return s, func(t *testing.T) {
<add> return s, func() {
<ide> s.Shutdown()
<del> cleanup(t)
<add> cleanup()
<ide> }
<ide> } | 9 |
Python | Python | tighten test_gen_pyf_stdout check | 02533c5da4b5e4328d49dcafb8d0a5592ae337c7 | <ide><path>numpy/f2py/tests/test_f2py2e.py
<ide> def test_gen_pyf_stdout(capfd, hello_world_f90, monkeypatch):
<ide> f2pycli()
<ide> out, _ = capfd.readouterr()
<ide> assert "Saving signatures to file" in out
<add> assert "function hi() ! in " in out
<ide>
<ide>
<ide> def test_gen_pyf_no_overwrite(capfd, hello_world_f90, monkeypatch): | 1 |
Text | Text | add changes metadata to tls newsession event | 9cbfabac25e9ee4c1b792efc45195ad5dc717e22 | <ide><path>doc/api/tls.md
<ide> server.on('keylog', (line, tlsSocket) => {
<ide> ### Event: `'newSession'`
<ide> <!-- YAML
<ide> added: v0.9.2
<add>changes:
<add> - version: v0.11.12
<add> pr-url: https://github.com/nodejs/node-v0.x-archive/pull/7118
<add> description: The `callback` argument is now supported.
<ide> -->
<ide>
<ide> The `'newSession'` event is emitted upon creation of a new TLS session. This may | 1 |
PHP | PHP | fix tests under http namespace | 6f70593c1de7ffa711b6aa3d32dfda674fa587bf | <ide><path>tests/TestCase/Http/ControllerFactoryTest.php
<ide> public function testApplicationController()
<ide> ]);
<ide> $result = $this->factory->create($request, $this->response);
<ide> $this->assertInstanceOf('TestApp\Controller\CakesController', $result);
<del> $this->assertSame($request, $result->request);
<del> $this->assertSame($this->response, $result->response);
<add> $this->assertSame($request, $result->getRequest());
<add> $this->assertSame($this->response, $result->getResponse());
<ide> }
<ide>
<ide> /**
<ide> public function testPrefixedAppController()
<ide> 'TestApp\Controller\Admin\PostsController',
<ide> $result
<ide> );
<del> $this->assertSame($request, $result->request);
<del> $this->assertSame($this->response, $result->response);
<add> $this->assertSame($request, $result->getRequest());
<add> $this->assertSame($this->response, $result->getResponse());
<ide> }
<ide>
<ide> /**
<ide> public function testNestedPrefixedAppController()
<ide> 'TestApp\Controller\Admin\Sub\PostsController',
<ide> $result
<ide> );
<del> $this->assertSame($request, $result->request);
<del> $this->assertSame($this->response, $result->response);
<add> $this->assertSame($request, $result->getRequest());
<add> $this->assertSame($this->response, $result->getResponse());
<ide> }
<ide>
<ide> /**
<ide> public function testPluginController()
<ide> 'TestPlugin\Controller\TestPluginController',
<ide> $result
<ide> );
<del> $this->assertSame($request, $result->request);
<del> $this->assertSame($this->response, $result->response);
<add> $this->assertSame($request, $result->getRequest());
<add> $this->assertSame($this->response, $result->getResponse());
<ide> }
<ide>
<ide> /**
<ide> public function testVendorPluginController()
<ide> 'Company\TestPluginThree\Controller\OvensController',
<ide> $result
<ide> );
<del> $this->assertSame($request, $result->request);
<del> $this->assertSame($this->response, $result->response);
<add> $this->assertSame($request, $result->getRequest());
<add> $this->assertSame($this->response, $result->getResponse());
<ide> }
<ide>
<ide> /**
<ide> public function testPrefixedPluginController()
<ide> 'TestPlugin\Controller\Admin\CommentsController',
<ide> $result
<ide> );
<del> $this->assertSame($request, $result->request);
<del> $this->assertSame($this->response, $result->response);
<add> $this->assertSame($request, $result->getRequest());
<add> $this->assertSame($this->response, $result->getResponse());
<ide> }
<ide>
<ide> /** | 1 |
Text | Text | remove backported changelog entry [ci skip] | d7b72761043f8d76dd95a7198c2dbba89da13b0b | <ide><path>activestorage/CHANGELOG.md
<del>* Allow full use of the AWS S3 SDK options for authentication. If an
<del> explicit AWS key pair and/or region is not provided in `storage.yml`,
<del> attempt to use environment variables, shared credentials, or IAM
<del> (instance or task) role credentials. Order of precedence is determined
<del> by the [AWS SDK](https://docs.aws.amazon.com/sdk-for-ruby/v3/developer-guide/setup-config.html).
<del>
<del> *Brian Knight*
<del>
<ide> * Rails 6 requires Ruby 2.4.1 or newer.
<ide>
<ide> *Jeremy Daer* | 1 |
Javascript | Javascript | try new way | cc845c3bae12df701eddcff94cb8b6f462c4a142 | <ide><path>src/text-editor.js
<ide> class TextEditor {
<ide> //
<ide> // Returns a {Cursor}.
<ide> addCursorAtBufferPosition (bufferPosition, options) {
<del> this.selectionsMarkerLayer.markBufferPosition(bufferPosition, {invalidate: 'never'})
<add> this.selectionsMarkerLayer.markBufferPosition(bufferPosition, {invalidate: 'never', exclusive: true})
<ide> if (!options || options.autoscroll !== false) this.getLastSelection().cursor.autoscroll()
<ide> return this.getLastSelection().cursor
<ide> }
<ide> class TextEditor {
<ide> //
<ide> // Returns a {Cursor}.
<ide> addCursorAtScreenPosition (screenPosition, options) {
<del> this.selectionsMarkerLayer.markScreenPosition(screenPosition, {invalidate: 'never'})
<add> this.selectionsMarkerLayer.markScreenPosition(screenPosition, {invalidate: 'never', exclusive: true})
<ide> if (!options || options.autoscroll !== false) this.getLastSelection().cursor.autoscroll()
<ide> return this.getLastSelection().cursor
<ide> }
<ide> class TextEditor {
<ide> this.buffer.insert([end, this.buffer.lineLengthForRow(end)], ' ' + commentEndString)
<ide>
<ide> // Prevent the cursor from selecting / passing the delimiters
<add> // See https://github.com/atom/atom/pull/17519
<ide> if (options.correctSelection && options.selection) {
<ide> let endLineLength = this.buffer.lineLengthForRow(end)
<del> let startDelta, endDelta
<ide> let oldRange = options.selection.getBufferRange()
<ide> if (oldRange.isEmpty()) {
<del> if (oldRange.start.column === indentLength) {
<del> startDelta = [0, commentStartString.length + 1]
<del> } else if (oldRange.start.column === endLineLength) {
<del> startDelta = [0, -commentEndString.length - 1]
<del> } else {
<del> startDelta = [0, 0]
<add> if (oldRange.start.column === endLineLength) {
<add> let endCol = endLineLength - commentEndString.length - 1
<add> options.selection.setBufferRange([[end, endCol], [end, endCol]], {autoscroll: false})
<add> return
<ide> }
<del> options.selection.setBufferRange(oldRange.translate(startDelta), { autoscroll: false })
<ide> } else {
<del> startDelta = oldRange.start.column === indentLength ? [0, commentStartString.length + 1] : [0, 0]
<del> endDelta = oldRange.end.column === endLineLength ? [0, -commentEndString.length - 1] : [0, 0]
<del> options.selection.setBufferRange(oldRange.translate(startDelta, endDelta), { autoscroll: false })
<add> let startDelta = oldRange.start.column === indentLength ? [0, commentStartString.length + 1] : [0, 0]
<add> let endDelta = oldRange.end.column === endLineLength ? [0, -commentEndString.length - 1] : [0, 0]
<add> options.selection.setBufferRange(oldRange.translate(startDelta, endDelta), {autoscroll: false})
<ide> }
<ide> }
<ide> }) | 1 |
Text | Text | correct grunt command in readme.md | 9d6beac3958da79671344fd11b9a3fe9b85f88e1 | <ide><path>README.md
<ide> npm install -g grunt-cli
<ide> ```
<ide> Make sure you have `grunt` installed by testing:
<ide> ```
<del>grunt -v
<add>grunt -V
<ide> ```
<ide>
<ide> Now by running the `grunt` command, in the jquery directory, you can build a full version of jQuery, just like with a `npm run build` command: | 1 |
Go | Go | remove getminimalipnet() as it's unused | 513310f776cf887b475106ed4d853c01045d5ee4 | <ide><path>libnetwork/types/types.go
<ide> func GetMinimalIP(ip net.IP) net.IP {
<ide> return ip
<ide> }
<ide>
<del>// GetMinimalIPNet returns a copy of the passed IP Network with congruent ip and mask notation
<del>func GetMinimalIPNet(nw *net.IPNet) *net.IPNet {
<del> if nw == nil {
<del> return nil
<del> }
<del> if len(nw.IP) == 16 && nw.IP.To4() != nil {
<del> m := nw.Mask
<del> if len(m) == 16 {
<del> m = m[12:16]
<del> }
<del> return &net.IPNet{IP: nw.IP.To4(), Mask: m}
<del> }
<del> return nw
<del>}
<del>
<ide> // IsIPNetValid returns true if the ipnet is a valid network/mask
<ide> // combination. Otherwise returns false.
<ide> func IsIPNetValid(nw *net.IPNet) bool { | 1 |
Java | Java | return static defaultapplicationstartup step | 5204d736f3a93ae274dd535c7dd17cc2e6532c7b | <ide><path>spring-core/src/main/java/org/springframework/core/metrics/DefaultApplicationStartup.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> */
<ide> class DefaultApplicationStartup implements ApplicationStartup {
<ide>
<add> private static final DefaultStartupStep DEFAULT_STARTUP_STEP = new DefaultStartupStep();
<add>
<ide> @Override
<ide> public DefaultStartupStep start(String name) {
<del> return new DefaultStartupStep();
<add> return DEFAULT_STARTUP_STEP;
<ide> }
<ide>
<ide>
<ide> static class DefaultStartupStep implements StartupStep {
<ide>
<del> boolean recorded = false;
<del>
<ide> private final DefaultTags TAGS = new DefaultTags();
<ide>
<ide> @Override
<ide> public Tags getTags() {
<ide>
<ide> @Override
<ide> public StartupStep tag(String key, String value) {
<del> if (this.recorded) {
<del> throw new IllegalArgumentException();
<del> }
<ide> return this;
<ide> }
<ide>
<ide> @Override
<ide> public StartupStep tag(String key, Supplier<String> value) {
<del> if (this.recorded) {
<del> throw new IllegalArgumentException();
<del> }
<ide> return this;
<ide> }
<ide>
<ide> @Override
<ide> public void end() {
<del> this.recorded = true;
<add>
<ide> }
<ide>
<ide> | 1 |
Javascript | Javascript | fix indentation to make jscs happy | a594fa523f8dfa11f1be14130cf5761d4d6464dc | <ide><path>test/ng/directive/ngClassSpec.js
<ide> describe('ngClass', function() {
<ide> );
<ide>
<ide> it('should allow ngClass with overlapping classes', inject(function($rootScope, $compile, $animate) {
<del> element = $compile('<div ng-class="{\'same yes\': test, \'same no\': !test}"></div>')($rootScope);
<del> $rootScope.$digest();
<add> element = $compile('<div ng-class="{\'same yes\': test, \'same no\': !test}"></div>')($rootScope);
<add> $rootScope.$digest();
<ide>
<del> expect(element).toHaveClass('same');
<del> expect(element).not.toHaveClass('yes');
<del> expect(element).toHaveClass('no');
<add> expect(element).toHaveClass('same');
<add> expect(element).not.toHaveClass('yes');
<add> expect(element).toHaveClass('no');
<ide>
<del> $rootScope.$apply(function() {
<del> $rootScope.test = true;
<del> });
<add> $rootScope.$apply(function() {
<add> $rootScope.test = true;
<add> });
<ide>
<del> expect(element).toHaveClass('same');
<del> expect(element).toHaveClass('yes');
<del> expect(element).not.toHaveClass('no');
<add> expect(element).toHaveClass('same');
<add> expect(element).toHaveClass('yes');
<add> expect(element).not.toHaveClass('no');
<ide> }));
<ide>
<ide> it('should allow both ngClass and ngClassOdd/Even with multiple classes', inject(function($rootScope, $compile) { | 1 |
PHP | PHP | remove support for integers with leading 0s | 6615ea8448e6323b5a453cd3023600f4c4fc4322 | <ide><path>src/Controller/ControllerFactory.php
<ide> protected function coerceStringToType(string $argument, ReflectionNamedType $typ
<ide> case 'float':
<ide> return is_numeric($argument) ? (float)$argument : null;
<ide> case 'int':
<del> return ctype_digit($argument) || filter_var($argument, FILTER_VALIDATE_INT) ? (int)$argument : null;
<add> return filter_var($argument, FILTER_VALIDATE_INT) ? (int)$argument : null;
<ide> case 'bool':
<ide> return $argument === '0' ? false : ($argument === '1' ? true : null);
<ide> case 'array':
<ide><path>tests/TestCase/Controller/ControllerFactoryTest.php
<ide> public function testInvokePassedParametersCoercion(): void
<ide> 'plugin' => null,
<ide> 'controller' => 'Dependencies',
<ide> 'action' => 'requiredTyped',
<del> 'pass' => ['1.0', '02', '0', '8,9'],
<add> 'pass' => ['1.0', '2', '0', '8,9'],
<ide> ],
<ide> ]);
<ide> $controller = $this->factory->create($request);
<ide> public function testInvokePassedParametersCoercion(): void
<ide> 'plugin' => null,
<ide> 'controller' => 'Dependencies',
<ide> 'action' => 'requiredTyped',
<del> 'pass' => ['1.0', '02', '0', ''],
<add> 'pass' => ['1.0', '2', '0', ''],
<ide> ],
<ide> ]);
<ide> $controller = $this->factory->create($request); | 2 |
Javascript | Javascript | fix race condition in profiling plugin | 387dce100f024c4b43833d960235648dae8edebb | <ide><path>lib/debug/ProfilingPlugin.js
<ide> const createTrace = (fs, outputPath) => {
<ide> profiler,
<ide> end: callback => {
<ide> // Wait until the write stream finishes.
<del> fsStream.on("finish", () => {
<add> fsStream.on("close", () => {
<ide> callback();
<ide> });
<ide> // Tear down the readable trace stream. | 1 |
Javascript | Javascript | fix owner tree for legacy backend | 4bfabbc32b545da69d6a7c80dca21ac9248494b2 | <ide><path>src/backend/legacy/renderer.js
<ide> export function attach(
<ide> id: getID(owner),
<ide> type: getElementType(owner),
<ide> });
<del> owner = owner.owner;
<add> if (owner._currentElement) {
<add> owner = owner._currentElement._owner;
<add> }
<ide> }
<ide> }
<ide> } | 1 |
PHP | PHP | return null instead of false on cache miss | f16842088dd1b10a7f0be0fe933ebb636befa184 | <ide><path>src/Utility/Inflector.php
<ide> class Inflector {
<ide> * @param string $type Inflection type
<ide> * @param string $key Original value
<ide> * @param string $value Inflected value
<del> * @return string Inflected value, from cache
<add> * @return string|null Inflected value on cache hit or null on cache miss.
<ide> */
<ide> protected static function _cache($type, $key, $value = false) {
<ide> $key = '_' . $key;
<ide> protected static function _cache($type, $key, $value = false) {
<ide> return $value;
<ide> }
<ide> if (!isset(static::$_cache[$type][$key])) {
<del> return false;
<add> return null;
<ide> }
<ide> return static::$_cache[$type][$key];
<ide> }
<ide> public static function underscore($camelCasedWord) {
<ide> */
<ide> public static function hyphenate($word) {
<ide> $result = static::_cache(__FUNCTION__, $word);
<del> if ($result !== false) {
<add> if ($result !== null) {
<ide> return $result;
<ide> }
<ide> | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.