content_type stringclasses 8
values | main_lang stringclasses 7
values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
PHP | PHP | restore original value of pretending | a2930ed0ee792783950125467907ba496031bb95 | <ide><path>src/Illuminate/Database/Connection.php
<ide> public function transactionLevel()
<ide> */
<ide> public function pretend(Closure $callback)
<ide> {
<add> $loggingQueries = $this->loggingQueries;
<add>
<ide> $this->enableQueryLog();
<del>
<add>
<ide> $this->pretending = true;
<ide>
<del> $this->queryLog = array();
<add> $this->queryLog = [];
<ide>
<ide> // Basically to make the database connection "pretend", we will just return
<ide> // the default values for all the query methods, then we will return an
<ide> public function pretend(Closure $callback)
<ide>
<ide> $this->pretending = false;
<ide>
<add> $this->loggingQueries = $loggingQueries;
<add>
<ide> return $this->queryLog;
<ide> }
<ide> | 1 |
Text | Text | add dilbert to master reame | 497f73c9644b50a70402d3b546eeca71acbbb23a | <ide><path>README.md
<ide> The library currently contains PyTorch implementations, pre-trained model weight
<ide> 5. **[XLNet](https://github.com/zihangdai/xlnet/)** (from Google/CMU) released with the paper [XLNet: Generalized Autoregressive Pretraining for Language Understanding](https://arxiv.org/abs/1906.08237) by Zhilin Yang*, Zihang Dai*, Yiming Yang, Jaime Carbonell, Ruslan Salakhutdinov, Quoc V. Le.
<ide> 6. **[XLM](https://github.com/facebookresearch/XLM/)** (from Facebook) released together with the paper [Cross-lingual Language Model Pretraining](https://arxiv.org/abs/1901.07291) by Guillaume Lample and Alexis Conneau.
<ide> 7. **[RoBERTa](https://github.com/pytorch/fairseq/tree/master/examples/roberta)** (from Facebook), a [Robustly Optimized BERT Pretraining Approach](https://arxiv.org/abs/1907.11692) by Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du et al.
<add>8. **[DilBERT](https://github.com/huggingface/pytorch-transformers/tree/master/examples/distillation)** (from HuggingFace), a smaller, faster, and lighter version of BERT leveraging knowledge distillation by Victor Sanh, Thomas Wolf and Lysandre Debut
<ide>
<ide> These implementations have been tested on several datasets (see the example scripts) and should match the performances of the original implementations (e.g. ~93 F1 on SQuAD for BERT Whole-Word-Masking, ~88 F1 on RocStories for OpenAI GPT, ~18.3 perplexity on WikiText 103 for Transformer-XL, ~0.916 Peason R coefficient on STS-B for XLNet). You can find more details on the performances in the Examples section of the [documentation](https://huggingface.co/pytorch-transformers/examples.html).
<ide> | 1 |
Text | Text | fix incorrect tensorflow url | fd6da687c34eb718fb914ec8ee2383256cc4cf06 | <ide><path>lfads/README.md
<ide> This code implements the model from the paper "[LFADS - Latent Factor Analysis v
<ide>
<ide> The code is written in Python 2.7.6. You will also need:
<ide>
<del>* **TensorFlow** version 1.2.1 ([install](http://tflearn.org/installation/)) -
<add>* **TensorFlow** version 1.2.1 ([install](https://www.tensorflow.org/install/)) -
<ide> * **NumPy, SciPy, Matplotlib** ([install SciPy stack](https://www.scipy.org/install.html), contains all of them)
<ide> * **h5py** ([install](https://pypi.python.org/pypi/h5py))
<ide> | 1 |
Javascript | Javascript | avoid new's in editor controls with spherical | 9d42f10fc75b0bad07fd01556ea45067349181c8 | <ide><path>examples/js/controls/EditorControls.js
<ide> THREE.EditorControls = function ( object, domElement ) {
<ide> var normalMatrix = new THREE.Matrix3();
<ide> var pointer = new THREE.Vector2();
<ide> var pointerOld = new THREE.Vector2();
<add> var spherical = new THREE.Spherical();
<ide>
<ide> // events
<ide>
<ide> THREE.EditorControls = function ( object, domElement ) {
<ide>
<ide> vector.copy( object.position ).sub( center );
<ide>
<del> var spherical = new THREE.Spherical().fromVector3( vector );
<add> spherical.fromVector3( vector );
<ide>
<ide> spherical.theta += delta.x;
<ide> spherical.phi += delta.y;
<ide>
<ide> spherical.makeSafe();
<ide>
<del> vector = spherical.toVector3();
<del>
<add> vector = spherical.toVector3( vector );
<add>
<ide> object.position.copy( center ).add( vector );
<ide>
<ide> object.lookAt( center ); | 1 |
Text | Text | update tracks.md with caption key info. closes | 6921b552ef625f3e5c37ecdc58cd57311f413e24 | <ide><path>docs/guides/tracks.md
<ide> Creating the Text File
<ide> ----------------------
<ide> Timed text requires a text file in [WebVTT](http://dev.w3.org/html5/webvtt/) format. This format defines a list of "cues" that have a start time, and end time, and text to display. [Microsoft has a builder](http://ie.microsoft.com/testdrive/Graphics/CaptionMaker/) that can help you get started on the file.
<ide>
<del>When creating captions, there's also additional [caption formatting techniques](http://www.theneitherworld.com/mcpoodle/SCC_TOOLS/DOCS/SCC_FORMAT.HTML#style) that would be good to use, like brackets around sound effects. [ sound effect ]
<add>When creating captions, there's also additional [caption formatting techniques] (http://www.theneitherworld.com/mcpoodle/SCC_TOOLS/DOCS/SCC_FORMAT.HTML#style) that would be good to use, like brackets around sound effects: [ sound effect ]. If you'd like a more in depth style guide for captioning, you can reference the [Captioning Key](http://www.dcmp.org/captioningkey/), but keep in mind not all features are supported by WebVTT or (more likely) the Video.js WebVTT implementation.
<ide>
<ide> Adding to Video.js
<ide> ------------------ | 1 |
Mixed | Javascript | fix native rotation android | e405e84fc35923888442df748757787698040010 | <ide><path>Libraries/Animated/src/NativeAnimatedHelper.js
<ide> function shouldUseNativeDriver(config: AnimationConfig | EventConfig): boolean {
<ide> return config.useNativeDriver || false;
<ide> }
<ide>
<add>function transformDataType(value: any): number {
<add> // Change the string type to number type so we can reuse the same logic in
<add> // iOS and Android platform
<add> if (typeof value !== 'string') {
<add> return value;
<add> }
<add> if (/deg$/.test(value)) {
<add> const degrees = parseFloat(value) || 0;
<add> const radians = (degrees * Math.PI) / 180.0;
<add> return radians;
<add> } else {
<add> // Assume radians
<add> return parseFloat(value) || 0;
<add> }
<add>}
<add>
<ide> module.exports = {
<ide> API,
<ide> addWhitelistedStyleProp,
<ide> module.exports = {
<ide> generateNewAnimationId,
<ide> assertNativeAnimatedModule,
<ide> shouldUseNativeDriver,
<add> transformDataType,
<ide> get nativeEventEmitter() {
<ide> if (!nativeEventEmitter) {
<ide> nativeEventEmitter = new NativeEventEmitter(NativeAnimatedModule);
<ide><path>Libraries/Animated/src/nodes/AnimatedInterpolation.js
<ide> class AnimatedInterpolation extends AnimatedWithChildren {
<ide> }
<ide>
<ide> __transformDataType(range: Array<any>) {
<del> // Change the string array type to number array
<del> // So we can reuse the same logic in iOS and Android platform
<del> return range.map(function(value) {
<del> if (typeof value !== 'string') {
<del> return value;
<del> }
<del> if (/deg$/.test(value)) {
<del> const degrees = parseFloat(value) || 0;
<del> const radians = (degrees * Math.PI) / 180.0;
<del> return radians;
<del> } else {
<del> // Assume radians
<del> return parseFloat(value) || 0;
<del> }
<del> });
<add> return range.map(NativeAnimatedHelper.transformDataType);
<ide> }
<ide>
<ide> __getNativeConfig(): any {
<ide><path>Libraries/Animated/src/nodes/AnimatedTransform.js
<ide> class AnimatedTransform extends AnimatedWithChildren {
<ide> transConfigs.push({
<ide> type: 'static',
<ide> property: key,
<del> value,
<add> value: NativeAnimatedHelper.transformDataType(value),
<ide> });
<ide> }
<ide> }
<ide><path>ReactAndroid/src/androidTest/java/com/facebook/react/tests/AnimatedTransformTest.java
<add>/**
<add> * Copyright (c) 2013-present, Facebook, Inc.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> */
<add>
<add>package com.facebook.react.tests;
<add>
<add>import android.view.View;
<add>
<add>
<add>import com.facebook.react.testing.ReactInstanceSpecForTest;
<add>import com.facebook.react.testing.StringRecordingModule;
<add>import com.facebook.react.bridge.JavaScriptModule;
<add>import com.facebook.react.testing.ReactAppInstrumentationTestCase;
<add>import com.facebook.react.testing.ReactTestHelper;
<add>
<add>/**
<add> * Integration test for {@code removeClippedSubviews} property that verify correct scrollview
<add> * behavior
<add> */
<add>public class AnimatedTransformTest extends ReactAppInstrumentationTestCase {
<add>
<add> private StringRecordingModule mStringRecordingModule;
<add>
<add> @Override
<add> protected String getReactApplicationKeyUnderTest() {
<add> return "AnimatedTransformTestApp";
<add> }
<add>
<add> @Override
<add> protected ReactInstanceSpecForTest createReactInstanceSpecForTest() {
<add> mStringRecordingModule = new StringRecordingModule();
<add> return super.createReactInstanceSpecForTest()
<add> .addNativeModule(mStringRecordingModule);
<add> }
<add>
<add> public void testAnimatedRotation() {
<add> waitForBridgeAndUIIdle();
<add>
<add> View button = ReactTestHelper.getViewWithReactTestId(
<add> getActivity().getRootView(),
<add> "TouchableOpacity");
<add>
<add> // Tap the button which triggers the animated transform containing the
<add> // rotation strings.
<add> createGestureGenerator().startGesture(button).endGesture();
<add> waitForBridgeAndUIIdle();
<add>
<add> // The previous cast error will prevent it from getting here
<add> assertEquals(2, mStringRecordingModule.getCalls().size());
<add> }
<add>
<add>}
<ide><path>ReactAndroid/src/androidTest/js/AnimatedTransformTestModule.js
<add>/**
<add> * Copyright (c) 2013-present, Facebook, Inc.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @providesModule AnimatedTransformTestModule
<add> */
<add>
<add>'use strict';
<add>
<add>var BatchedBridge = require('BatchedBridge');
<add>var React = require('React');
<add>var StyleSheet = require('StyleSheet');
<add>var View = require('View');
<add>var TouchableOpacity = require('TouchableOpacity');
<add>var Text = require('Text');
<add>var RecordingModule = require('NativeModules').Recording;
<add>
<add>const styles = StyleSheet.create({
<add> base: {
<add> width: 200,
<add> height: 200,
<add> backgroundColor: 'red',
<add> transform: [{rotate: '0deg'}],
<add> },
<add> transformed: {
<add> transform: [{rotate: '45deg'}],
<add> },
<add>});
<add>
<add>/**
<add> * This app presents a TouchableOpacity which was the simplest way to
<add> * demonstrate this issue. Tapping the TouchableOpacity causes an animated
<add> * transform to be created for the rotation property. Since the property isn't
<add> * animated itself, it comes through as a static property, but static properties
<add> * can't currently handle strings which causes a string->double cast exception.
<add> */
<add>class AnimatedTransformTestApp extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> this.toggle = this.toggle.bind(this);
<add> }
<add>
<add> state = {
<add> flag: false,
<add> };
<add>
<add> toggle() {
<add> this.setState({
<add> flag: !this.state.flag,
<add> });
<add> }
<add>
<add> render() {
<add> // Using this to verify if its fixed.
<add> RecordingModule.record('render');
<add>
<add> return (
<add> <View style={StyleSheet.absoluteFill}>
<add> <TouchableOpacity
<add> onPress={this.toggle}
<add> testID="TouchableOpacity"
<add> style={[styles.base, this.state.flag ? styles.transformed : null]}>
<add> <Text>TouchableOpacity</Text>
<add> </TouchableOpacity>
<add> </View>
<add> );
<add> }
<add>}
<add>
<add>var AnimatedTransformTestModule = {
<add> AnimatedTransformTestApp: AnimatedTransformTestApp,
<add>};
<add>
<add>BatchedBridge.registerCallableModule(
<add> 'AnimatedTransformTestModule',
<add> AnimatedTransformTestModule
<add>);
<add>
<add>module.exports = AnimatedTransformTestModule;
<ide><path>ReactAndroid/src/androidTest/js/TestBundle.js
<ide> require('TimePickerDialogTestModule');
<ide> const AppRegistry = require('AppRegistry');
<ide>
<ide> const apps = [
<add> {
<add> appKey: 'AnimatedTransformTestApp',
<add> component: () =>
<add> require('AnimatedTransformTestModule').AnimatedTransformTestApp,
<add> },
<ide> {
<ide> appKey: 'CatalystRootViewTestApp',
<ide> component: () => | 6 |
Text | Text | add section for official source code | 417ab301cf15e22def0a12cca59f318925e2d636 | <ide><path>README.md
<ide> Use Airflow to author workflows as directed acyclic graphs (DAGs) of tasks. The
<ide> - [Requirements](#requirements)
<ide> - [Getting started](#getting-started)
<ide> - [Installing from PyPI](#installing-from-pypi)
<del>- [Official Docker images](#official-docker-images)
<add>- [Official source code](#official-source-code)
<ide> - [Beyond the Horizon](#beyond-the-horizon)
<ide> - [Principles](#principles)
<ide> - [User Interface](#user-interface)
<ide> pip install apache-airflow[postgres,google]==1.10.12 \
<ide> --constraint "https://raw.githubusercontent.com/apache/airflow/constraints-1.10.12/constraints-3.7.txt"
<ide> ```
<ide>
<del>## Official Docker images
<del>In order to use Airflow in Docker Compose or Kubernetes, you might need to use or build production images of Apache Airflow. The production image is a multi-segment image. The first segment "airflow-build-image" contains all the build essentials and related dependencies that allow to install airflow locally. By default the image is build from a released version of Airflow from Github, but by providing some extra arguments you can also build it from local sources.
<del> This is particularly useful in CI environment where we are using the image to run Kubernetes tests(Helm Chart integration). We will also use released images in the Helm Chart(backward compatibility). You can see DockerHub images at https://hub.docker.com/repository/docker/apache/airflow. In DockerHub there is just a convenience binary and that image can (and often should) be built from the officially released sources. More Details [TODO](#).
<add>## Official source code
<ide>
<del>The community provides two types of support for the production images:
<del>- We provide pre-build released version of production image in PyPI build from released sources of Apache Airflow - shortly after release. Those images are available in the DockerHub. You can pull those images via `docker pull apache/airflow:<VERSION>-pythonX.Y` - version is the version number (for example 1.10.11). Additionally `docker pull apache/airflow` will pull latest stable version of the image with default python version (currently 3.6). Now change to root user(here we use root user) temporarily and install your own dependencies, for example mx. Change back to airflow user and then you can install some pip packages you want. You can add your dags by copying them and then build your own airflow image. You can use this airflow image with your own modifications.
<add>Looking at the legal side of the software creation process, Apache Airflow is an Apache Software Foundation (ASF) project. This means that Apache Airflow project releases are source code releases and follow the [ASF Release Policy](http://www.apache.org/legal/release-policy.html). There is only one official release repository for Apache Airflow, like all ASF projects: [The Distribution Site of ASF](https://downloads.apache.org). Official releases are cryptographically signed by the release manager and officially voted on by the PMC members during the [Release Approval Process](http://www.apache.org/legal/release-policy.html#release-approval).
<ide>
<del>- In `master` branch of Airflow and in `v1-10-stable` branch we provide Dockerfiles and accompanying
<del> files that allow to build your own customized version of the Airflow Production image. To build your own image or to customize it; first clone the image and then checkout the right version which are conservative, masters and if you are adventurous then you can run `docker build`.You can add various arguments to customize it.More instructions on how to build your own image with additional dependencies (if needed) are provided in the [IMAGES.rst](IMAGES.rst#production-images) if you want to build it using `docker build` command or in [BREEZE.rst](BREEZE.rst#building-production-images) to use Breeze tool which easier interface, auto-complete, and accompanying screencast video. Breeze is a development and text environment that is developed for airflow but it also supports building production image very easily so we specify the production image flag additional extras or python version or python dev. so most of the parameters you can specify here is in command line parameters which have auto completion option. Note, that while it is possible to use master branch to build images for released Airflow versions, it might at times get broken so you should rather rely on building your own images from the v1-10-stable branch.
<add>Following the ASF rules, the source packages released must be sufficient for a user to build and test the release provided they have access to the appropriate platform and tools.
<ide>
<del>Airflow Summit 2020's "Production Docker Image" talk where context, architecture and customization/extension methods are [explained](https://youtu.be/wDr3Y7q2XoI).
<add>Other ways of retrieving source code are "convenience" methods. For example, tagging in GitHub is a convenient way to mark the git project sources that were used to generate the official source packages. We also have binary "convenience" packages how Airflow is distributed: PyPI releases which are a convenient way of installing Apache Airflow using standard python tools or Docker Images published in the [Apache Airflow DockerHub](https://hub.docker.com/repository/docker/apache/airflow). Those are not official releases but they are built using officially released sources.
<add>
<add>> Note: Airflow Summit 2020's "Production Docker Image" talk where context, architecture and customization/extension methods are [explained](https://youtu.be/wDr3Y7q2XoI).
<ide>
<ide> ## Beyond the Horizon
<ide> | 1 |
Text | Text | introduce navigators in the tutorial | 7d3fbbdb68e5015311bce60236e0ae06d62f17a2 | <ide><path>docs/JavaScriptEnvironment.md
<ide> title: JavaScript Environment
<ide> layout: docs
<ide> category: Guides
<ide> permalink: docs/javascript-environment.html
<del>next: navigator-comparison
<add>next: navigation
<ide> ---
<ide>
<ide> ## JavaScript Runtime
<add><path>docs/Navigation.md
<del><path>docs/NavigatorComparison.md
<ide> ---
<del>id: navigator-comparison
<add>id: navigation
<ide> title: Navigation
<ide> layout: docs
<ide> category: Guides
<del>permalink: docs/navigator-comparison.html
<add>permalink: docs/navigation.html
<ide> next: performance
<ide> ---
<ide>
<del>Mobile apps rarely consist of just one scene (another word for screen). As soon as you add a second scene to your app, you will have to take into consideration how the user will navigate from one scene to the other.
<del>
<del>You can use navigators to transition between multiple scenes. These transitions can be typical side-to-side animations down a master/detail stack, or vertical modal popups.
<add>This guide covers the various navigation components available in React Native. If you are just getting started with navigation, you will probably want to use `Navigator`. If you are only targeting iOS and would like to stick to the native look and feel, check out `NavigatorIOS`. If you are looking for greater control over your navigation stack, you can't go wrong with `NavigationExperimental`.
<ide>
<ide> ## Navigator
<ide>
<del>React Native has several built-in navigation components, but for your first app you will probably want to use `Navigator`. It provides a JavaScript implementation of a navigation stack, so it works on both iOS and Android and is easy to customize.
<add>`Navigator` provides a JavaScript implementation of a navigation stack, so it works on both iOS and Android and is easy to customize. This is the same component you used to build your first navigation stack in the [navigators tutorial](docs/navigators.html).
<ide>
<ide> 
<ide>
<del>Something you will encounter a lot when dealing with navigation is the concept of routes. A route is an object that contains information about a scene. It is used to provide all the context that the navigator's `renderScene` function needs to render a scene. A basic `Navigator` implementation may look like this:
<del>
<del>```js
<del><Navigator
<del> initialRoute={{ title: 'My Initial Scene', index: 0 }}
<del> renderScene={(route, navigator) => {
<del> <MyScene title={route.title} />
<del> }}
<del>/>
<del>```
<del>
<del>The above example will display a single scene, but in order to push a new scene onto screen you will need to learn about `push` and `pop`. These two methods are provided by the `navigator` object that is passed to your `renderScene` function. They can be used, as you may have realized, to push and pop routes into your navigation stack.
<del>
<del>A more complete example that demonstrates the pushing and popping of routes could therefore look something like this:
<add>`Navigator` can easily be adapted to render different components based on the current route in its `renderScene` function. It will transition new scenes onto the screen by sliding in from the right by default, but you can control this behavior by using the `configureScene` function. You can also configure a navigation bar through the `navigationBar` prop.
<ide>
<del>```js
<del>import React, { Component, PropTypes } from 'react';
<del>import { Navigator, Text, TouchableHighlight, View } from 'react-native';
<del>
<del>export default class SimpleNavigationApp extends Component {
<del> render() {
<del> return (
<del> <Navigator
<del> initialRoute={{ title: 'My Initial Scene', index: 0 }}
<del> renderScene={(route, navigator) =>
<del> <MyScene
<del> title={route.title}
<del>
<del> // Function to call when a new scene should be displayed
<del> onForward={ () => {
<del> const nextIndex = route.index + 1;
<del> navigator.push({
<del> title: 'Scene ' + nextIndex,
<del> index: nextIndex,
<del> });
<del> }}
<del>
<del> // Function to call to go back to the previous scene
<del> onBack={() => {
<del> if (route.index > 0) {
<del> navigator.pop();
<del> }
<del> }}
<del> />
<del> }
<del> />
<del> )
<del> }
<del>}
<del>
<del>class MyScene extends Component {
<del> static propTypes = {
<del> title: PropTypes.string.isRequired,
<del> onForward: PropTypes.func.isRequired,
<del> onBack: PropTypes.func.isRequired,
<del> }
<del> render() {
<del> return (
<del> <View>
<del> <Text>Current Scene: { this.props.title }</Text>
<del> <TouchableHighlight onPress={this.props.onForward}>
<del> <Text>Tap me to load the next scene</Text>
<del> </TouchableHighlight>
<del> <TouchableHighlight onPress={this.props.onBack}>
<del> <Text>Tap me to go back</Text>
<del> </TouchableHighlight>
<del> </View>
<del> )
<del> }
<del>}
<del>```
<del>
<del>In this example, the `MyScene` component is passed the title of the current route via the `title` prop. It displays two tappable components that call the `onForward` and `onBack` functions passed through its props, which in turn will call `navigator.push()` and `navigator.pop()` as needed.
<del>
<del>While this is a very basic example, it can easily be adapted to render an entirely different component based on the route that is passed to the `renderScene` function. Navigator will push new scenes from the right by default, and you can control this behavior by using the `configureScene` function. You can also configure a navigation bar through the `navigationBar` prop.
<del>
<del>Check out the [Navigator API reference](docs/navigator.html) for more code samples.
<add>Check out the [Navigator API reference](docs/navigator.html) for specific examples that cover each of these scenarios.
<ide>
<ide> ## NavigatorIOS
<ide>
<ide> If you are targeting iOS only, you may also want to consider using [NavigatorIOS](docs/navigatorios.html). It looks and feels just like [`UINavigationController`](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UINavigationController_Class/), because it is actually built on top of it.
<ide>
<ide> 
<ide>
<del>```js
<add>```javascript
<ide> <NavigatorIOS
<ide> initialRoute={{
<ide> component: MyScene,
<ide> If you are targeting iOS only, you may also want to consider using [NavigatorIOS
<ide> />
<ide> ```
<ide>
<del>Just like Navigator, NavigatorIOS uses routes to represent scenes, with some important differences. The actual component that will be rendered can be specified using the `component` key in the route, and any props that should be passed to this component can be specified in `passProps`. A "navigator" object is automatically passed as a prop to the component, allowing you to call `push` and `pop` as needed.
<add>Just like `Navigator`, `NavigatorIOS` uses routes to represent scenes, with some important differences. The actual component that will be rendered can be specified using the `component` key in the route, and any props that should be passed to this component can be specified in `passProps`. A "navigator" object is automatically passed as a prop to the component, allowing you to call `push` and `pop` as needed.
<ide>
<del>As NavigatorIOS leverages native UIKit navigation, it will automatically render a navigation bar with a back button and title.
<add>As `NavigatorIOS` leverages native UIKit navigation, it will automatically render a navigation bar with a back button and title.
<ide>
<del>Check out the [NavigatorIOS reference docs](docs/navigatorios.html) to learn more about this component.
<del>
<del>```js
<add>```javascript
<ide> import React, { Component, PropTypes } from 'react';
<ide> import { NavigatorIOS, Text, TouchableHighlight, View } from 'react-native';
<ide>
<ide> class MyScene extends Component {
<ide> }
<ide> ```
<ide>
<add>Check out the [`NavigatorIOS` reference docs](docs/navigatorios.html) to learn more about this component.
<add>
<ide> > You may also want to check out [react-native-navigation](https://github.com/wix/react-native-navigation), a component that aims to provide native navigation on both iOS and Android.
<ide>
<ide> ## NavigationExperimental
<ide>
<del>Navigator and NavigatorIOS are both stateful components. If your app has multiple of these, it can become tricky to coordinate navigation transitions between them. NavigationExperimental provides a different approach to navigation, allowing any view to act as a navigation view and using reducers to manipulate state at a top-level object. It is bleeding edge as the name implies, but you might want to check it out if you are craving greater control over your app's navigation.
<add>`Navigator` and `NavigatorIOS` are both stateful components. If your app has multiple of these, it can become tricky to coordinate navigation transitions between them. NavigationExperimental provides a different approach to navigation, allowing any view to act as a navigation view and using reducers to manipulate state at a top-level object. It is bleeding edge as the name implies, but you might want to check it out if you are craving greater control over your app's navigation.
<ide>
<del>```js
<add>```javascript
<ide> <NavigationCardStack
<ide> onNavigateBack={onPopRouteFunc}
<ide> navigationState={myNavigationState}
<ide> renderScene={renderSceneFun}
<ide> />
<ide> ```
<ide>
<del>You can import NavigationExperimental like any other component in React Native. Once you have that, you can deconstruct any additional components from NavigationExperimental that you may find useful. Since I am feeling like building navigation stacks today, I'll go ahead and pick out NavigationCardStack and NavigationStateUtils.
<add>You can import `NavigationExperimental` like any other component in React Native. Once you have that, you can deconstruct any additional components from `NavigationExperimental` that you may find useful. Since I am feeling like building navigation stacks today, I'll go ahead and pick out `NavigationCardStack` and `NavigationStateUtils`.
<ide>
<del>```js
<add>```javascript
<ide> import React, { Component } from 'react';
<ide> import { NavigationExperimental } from 'react-native';
<ide>
<ide> const {
<ide> } = NavigationExperimental;
<ide> ```
<ide>
<del>As I said earlier, NavigationExperimental takes a different approach than Navigator and NavigatorIOS. Using it to build a navigation stack requires a few more steps than the stateful components, but the payoff is worth it.
<add>As I said earlier, `NavigationExperimental` takes a different approach than `Navigator` and `NavigatorIOS`. Using it to build a navigation stack requires a few more steps than the stateful components, but the payoff is worth it.
<ide>
<ide> ### Step 1. Define Initial State and Top Level Component
<ide>
<ide> Create a new component for your application. This will be the top-level object, so we will define the initial state here. The navigation state will be defined in the `navigationState` key, where we define our initial route:
<ide>
<del>```js
<add>```javascript
<ide> class BleedingEdgeApplication extends Component {
<ide> constructor(props, context) {
<ide> super(props, context);
<ide> NavigationExperimental comes built-in with a some useful reducers, and they are
<ide>
<ide> We can use them to write our `_onNavigationChange` function which, given a "push" or "pop" action, will reduce the state accordingly.
<ide>
<del>```js
<add>```javascript
<ide> _onNavigationChange(type) {
<ide> // Extract the navigationState from the current state:
<ide> let {navigationState} = this.state;
<ide> _onNavigationChange(type) {
<ide>
<ide> Cool. I'm getting the hang of this. This is the heart of NavigationExperimental. We are only handling two actions here, but a more complex application could also take into account a "back" action (e.g. Android back button), as well as handle the transition between several tabs in a tabbed application.
<ide>
<del>I am still missing the initial scene that will be rendered (as well as the actual navigator that will wrap it, but lets not get ahead of ourselves).
<add>I am still missing the initial scene that will be rendered (as well as the actual navigator that will wrap it, but let's not get ahead of ourselves).
<ide>
<ide> ### Step 3. Define Scenes
<ide>
<ide> First I want to define a Row component out of convenience. It displays some text and can call some function when pressed.
<ide>
<del>```js
<add>```javascript
<ide> class TappableRow extends Component {
<ide> render() {
<ide> return (
<ide> class TappableRow extends Component {
<ide>
<ide> Now I will define my actual scene. It uses a scroll view to display a vertical list of items. The first row displays the current route's key, and two more rows will call our theoretical navigator's push and pop functions.
<ide>
<del>```js
<add>```javascript
<ide> class MyVeryComplexScene extends Component {
<ide> render() {
<ide> return (
<ide> class MyVeryComplexScene extends Component {
<ide>
<ide> Now that I have defined the state and a function to manage it, I think I can go ahead and create a proper navigator component now. While I'm at it, I'll render my scene after configuring it with the current route's props.
<ide>
<del>```js
<add>```javascript
<ide> class MyVerySimpleNavigator extends Component {
<ide>
<ide> // This sets up the methods (e.g. Pop, Push) for navigation.
<ide> class MyVerySimpleNavigator extends Component {
<ide> }
<ide> ```
<ide>
<del>That's it -- so close to the finish line I can smell it. Lets plug our new navigator into our top-level component:
<add>That's it -- so close to the finish line I can smell it. Let's plug our new navigator into our top-level component:
<ide>
<del>```js
<add>```javascript
<ide> class BleedingEdgeApplication extends Component {
<ide>
<ide> // constructor and other methods omitted for clarity
<ide> We're done! Bask in the glory of NavigationExperimental.
<ide>
<ide> (Oh yes, sorry about that -- here's our missing imports and styles.)
<ide>
<del>```js
<add>```javascript
<ide> import { NavigationExperimental, PixelRatio, ScrollView, StyleSheet, Text, TouchableHighlight } from 'react-native';
<ide>
<ide> const styles = StyleSheet.create({
<ide><path>docs/Navigators.md
<add>---
<add>id: navigators
<add>title: Using Navigators
<add>layout: docs
<add>category: The Basics
<add>permalink: docs/using-navigators.html
<add>next: more-resources
<add>---
<add>
<add>Mobile apps rarely consist of just one screen. As soon as you add a second screen to your app, you will have to take into consideration how the user will navigate from one screen to the other.
<add>
<add>You can use navigators to transition between multiple screens. These transitions can be typical side-to-side animations down a master/detail stack, or vertical modal popups.
<add>
<add>## Navigator
<add>
<add>React Native has several built-in navigation components, but for your first app you will probably want to use `Navigator`. It provides a JavaScript implementation of a navigation stack, so it works on both iOS and Android and is easy to customize.
<add>
<add>
<add>
<add>### Working with Scenes
<add>
<add>At this point you should feel comfortable rendering all sorts of components in your app, be it a simple `View` with `Text` inside, or a `ScrollView` with a list of `Image`s. Together, these components make up a scene (another word for screen) in your app.
<add>
<add>A scene is nothing other than a React component that is typically rendered full screen. This is in contrast to a `Text`, an `Image`, or even a custom `SpinningBeachball` component that is meant to be rendered as part of a screen. You may have already used one without realizing it - the ["HelloWorldApp"](docs/tutorial.html), the ["FlexDirectionBasics"](docs/flexbox.html), and the ["ListViewBasics"](docs/using-a-listview.html) components covered earlier in the tutorial are all examples of scenes.
<add>
<add>For simplicity's sake, let's define a simple scene that displays a bit of text. We will come back to this scene later as we add navigation to our app. Create a new file called "MyScene.js" with the following contents:
<add>
<add>```javascript
<add>import React, { Component } from 'react';
<add>import { View, Text } from 'react-native';
<add>
<add>export default class MyScene extends Component {
<add> getDefaultProps() {
<add> return {
<add> title: 'MyScene'
<add> };
<add> }
<add>
<add> render() {
<add> return (
<add> <View>
<add> <Text>Hi! My name is {this.props.title}.</Text>
<add> </View>
<add> )
<add> }
<add>}
<add>```
<add>
<add>Notice the `export default` in front of the component declaration. This will _export_ the component, and in turn allow other components to _import_ it later on, like so:
<add>
<add>```javascript
<add>import React, { Component } from 'react';
<add>import { View, Text } from 'react-native';
<add>
<add>import MyScene from './MyScene';
<add>
<add>class YoDawgApp extends Component {
<add> render() {
<add> return (
<add> <MyScene />
<add> )
<add> }
<add>}
<add>
<add>AppRegistry.registerComponent('YoDawgApp', () => YoDawgApp);
<add>```
<add>
<add>We now have a simple app that renders your scene and nothing else. In this case, `MyScene` is a simple example of a [reusable React component](https://facebook.github.io/react/docs/reusable-components.html).
<add>
<add>### Using Navigator
<add>
<add>Enough about scenes, let's start navigating. We will start by rendering a `Navigator`, and then let the `Navigator` render the scene for you by passing in your own render function to its `renderScene` prop.
<add>
<add>```javascript
<add>render() {
<add> return (
<add> <Navigator
<add> initialRoute={{ title: 'My Initial Scene', index: 0 }}
<add> renderScene={(route, navigator) => {
<add> <MyScene title={route.title} />
<add> }}
<add> />
<add> );
<add>}
<add>```
<add>
<add>Something you will encounter a lot when dealing with navigation is the concept of routes. A route is an object that contains information about a scene. It is used to provide all the context that the navigator's `renderScene` function needs to render a scene. It can have any number of keys to help distinguish your scene, and I happened to pick a single `title` key for the above example.
<add>
<add>#### Pushing scenes onto the stack
<add>
<add>In order to transition to a new scene, you will need to learn about `push` and `pop`. These two methods are provided by the `navigator` object that is passed to your `renderScene` function above. They can be used, as you may have realized, to push and pop routes into your navigation stack.
<add>
<add>```javascript
<add>navigator.push({
<add> title: 'Next Scene',
<add> index: 1,
<add>});
<add>
<add>navigator.pop();
<add>```
<add>
<add>A more complete example that demonstrates the pushing and popping of routes could therefore look something like this:
<add>
<add>```javascript
<add>import React, { Component, PropTypes } from 'react';
<add>import { Navigator, Text, TouchableHighlight, View } from 'react-native';
<add>
<add>export default class SimpleNavigationApp extends Component {
<add> render() {
<add> return (
<add> <Navigator
<add> initialRoute={{ title: 'My Initial Scene', index: 0 }}
<add> renderScene={(route, navigator) =>
<add> <MyScene
<add> title={route.title}
<add>
<add> // Function to call when a new scene should be displayed
<add> onForward={ () => {
<add> const nextIndex = route.index + 1;
<add> navigator.push({
<add> title: 'Scene ' + nextIndex,
<add> index: nextIndex,
<add> });
<add> }}
<add>
<add> // Function to call to go back to the previous scene
<add> onBack={() => {
<add> if (route.index > 0) {
<add> navigator.pop();
<add> }
<add> }}
<add> />
<add> }
<add> />
<add> )
<add> }
<add>}
<add>
<add>class MyScene extends Component {
<add> static propTypes = {
<add> title: PropTypes.string.isRequired,
<add> onForward: PropTypes.func.isRequired,
<add> onBack: PropTypes.func.isRequired,
<add> }
<add> render() {
<add> return (
<add> <View>
<add> <Text>Current Scene: { this.props.title }</Text>
<add> <TouchableHighlight onPress={this.props.onForward}>
<add> <Text>Tap me to load the next scene</Text>
<add> </TouchableHighlight>
<add> <TouchableHighlight onPress={this.props.onBack}>
<add> <Text>Tap me to go back</Text>
<add> </TouchableHighlight>
<add> </View>
<add> )
<add> }
<add>}
<add>```
<add>
<add>In this example, the `MyScene` component is passed the title of the current route via the `title` prop. It displays two tappable components that call the `onForward` and `onBack` functions passed through its props, which in turn will call `navigator.push()` and `navigator.pop()` as needed.
<add>
<add>Check out the [Navigator API reference](docs/navigator.html) for more `Navigator` code samples, or read through the [Navigation guide](docs/navigation.html) for other examples of what you can do with navigators.
<add>
<add>## High Five!
<add>
<add>If you've gotten here by reading linearly through the tutorial, then you are a pretty impressive human being. Congratulations. Next, you might want to check out [all the cool stuff the community does with React Native](/react-native/docs/more-resources.html).
<ide><path>docs/Networking.md
<ide> title: Networking
<ide> layout: docs
<ide> category: The Basics
<ide> permalink: docs/network.html
<del>next: more-resources
<add>next: navigators
<ide> ---
<ide>
<ide> Many mobile apps need to load resources from a remote URL. You may want to make a POST request to a REST API, or you may simply need to fetch a chunk of static content from another server.
<ide> request.send();
<ide>
<ide> ## WebSocket Support
<ide>
<del>React Native supports [WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket), a protocol which provides full-duplex communication channels over a single TCP connection.
<add>React Native also supports [WebSockets](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket), a protocol which provides full-duplex communication channels over a single TCP connection.
<ide>
<ide> ```js
<ide> var ws = new WebSocket('ws://host.com/path');
<ide>
<ide> ws.onopen = () => {
<ide> // connection opened
<del> ws.send('something');
<add>
<add> ws.send('something'); // send a message
<ide> };
<ide>
<ide> ws.onmessage = (e) => {
<ide> ws.onclose = (e) => {
<ide> };
<ide> ```
<ide>
<del>If you've gotten here by reading linearly through the tutorial, then you are a pretty impressive human being. Congratulations. Next, you might want to check out [all the cool stuff the community does with React Native](/react-native/docs/more-resource.html).
<add>Your app can now display all sorts of data and you may soon need to organize this content into several screens. To manage the transition between these screens, you will need to learn about [navigators](/react-native/docs/using-navigators.html). | 4 |
Go | Go | fix the incorrect description for newinstream | 90bddb4243d29e11b2add2f25849fcfce7ee17ec | <ide><path>cli/command/in.go
<ide> func (i *InStream) CheckTty(attachStdin, ttyMode bool) error {
<ide> return nil
<ide> }
<ide>
<del>// NewInStream returns a new OutStream object from a Writer
<add>// NewInStream returns a new InStream object from a ReadCloser
<ide> func NewInStream(in io.ReadCloser) *InStream {
<ide> fd, isTerminal := term.GetFdInfo(in)
<ide> return &InStream{in: in, fd: fd, isTerminal: isTerminal} | 1 |
Ruby | Ruby | use the inflector rules made for the purpose | 3e00e1a297b70a6ae6e8ac3971ab2d49b6e01666 | <ide><path>activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb
<ide> class HasAndBelongsToManyAssociation < AssociationCollection #:nodoc:
<ide> def initialize(owner, association_name, association_class_name, association_class_primary_key_name, options)
<ide> super
<ide>
<del> @association_foreign_key = options[:association_foreign_key] || Inflector.underscore(Inflector.demodulize(association_class_name)) + "_id"
<add> @association_foreign_key = options[:association_foreign_key] || association_class_name.foreign_key
<ide> @association_table_name = options[:table_name] || @association_class.table_name
<ide> @join_table = options[:join_table]
<ide> @order = options[:order] | 1 |
Text | Text | fix a tiny typo | 50c3ffd00969f8b1f2a00849973f2587984a26bf | <ide><path>docs/sources/userguide/dockervolumes.md
<ide> it.
<ide>
<ide> Let's create a new named container with a volume to share.
<ide> While this container doesn't run an application, it reuses the `training/postgres`
<del>image so that all containers are using layers in common, saveing disk space.
<add>image so that all containers are using layers in common, saving disk space.
<ide>
<ide> $ sudo docker create -v /dbdata --name dbdata training/postgres
<ide> | 1 |
PHP | PHP | remove redundant event parameter | cab1a39ae3388cd226880db05a312500dd1fe417 | <ide><path>lib/Cake/Controller/Controller.php
<ide> public function setEventManager($eventManager) {
<ide> * @return void
<ide> */
<ide> public function startupProcess() {
<del> $this->getEventManager()->dispatch(new Event('Controller.initialize', $this, [$this]));
<del> $this->getEventManager()->dispatch(new Event('Controller.startup', $this, [$this]));
<add> $this->getEventManager()->dispatch(new Event('Controller.initialize', $this));
<add> $this->getEventManager()->dispatch(new Event('Controller.startup', $this));
<ide> }
<ide>
<ide> /**
<ide> public function startupProcess() {
<ide> * @return void
<ide> */
<ide> public function shutdownProcess() {
<del> $this->getEventManager()->dispatch(new Event('Controller.shutdown', $this, [$this]));
<add> $this->getEventManager()->dispatch(new Event('Controller.shutdown', $this));
<ide> }
<ide>
<ide> /**
<ide> public function redirect($url, $status = null, $exit = true) {
<ide> if (is_array($status)) {
<ide> extract($status, EXTR_OVERWRITE);
<ide> }
<del> $event = new Event('Controller.beforeRedirect', $this, array($this, $url, $status, $exit));
<add> $event = new Event('Controller.beforeRedirect', $this, array($url, $status, $exit));
<ide> $this->getEventManager()->dispatch($event);
<ide>
<ide> if ($event->isStopped()) {
<ide> public function validateErrors() {
<ide> * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::render
<ide> */
<ide> public function render($view = null, $layout = null) {
<del> $event = new Event('Controller.beforeRender', $this, [$this]);
<add> $event = new Event('Controller.beforeRender', $this);
<ide> $this->getEventManager()->dispatch($event);
<ide> if ($event->isStopped()) {
<ide> $this->autoRender = false; | 1 |
Text | Text | update pr template | d33bb9c33ac84a1d1aa1aa8805b667efca2e51d6 | <ide><path>.github/PULL_REQUEST_TEMPLATE.md
<ide> should start with an issue. Mention the issue number here.
<ide>
<ide>
<ide> ### Checklist ###
<add><!--
<ide> Mark an `[x]` for completed items, if you're not sure leave them unchecked and we can assist.
<add>-->
<ide>
<del>* [ ] All authors have signed the CLA at https://contribute.jquery.com/CLA/
<add>* [ ] All authors have signed the CLA at https://cla.js.foundation/jquery/jquery
<ide> * [ ] New tests have been added to show the fix or feature works
<ide> * [ ] Grunt build and unit tests pass locally with these changes
<ide> * [ ] If needed, a docs issue/PR was created at https://github.com/jquery/api.jquery.com
<ide>
<add><!--
<ide> Thanks! Bots and humans will be around shortly to check it out.
<add>--> | 1 |
Java | Java | improve javadoc of retrywhen() operators | 20a72ca2973ebe1ef160baa9d0ebda369c95d438 | <ide><path>src/main/java/io/reactivex/Completable.java
<ide> public final Completable retry(Predicate<? super Throwable> predicate) {
<ide> * Returns a Completable which given a Publisher and when this Completable emits an error, delivers
<ide> * that error through a Flowable and the Publisher should signal a value indicating a retry in response
<ide> * or a terminal event indicating a termination.
<add> * <p>
<add> * Note that the inner {@code Publisher} returned by the handler function should signal
<add> * either {@code onNext}, {@code onError} or {@code onComplete} in response to the received
<add> * {@code Throwable} to indicate the operator should retry or terminate. If the upstream to
<add> * the operator is asynchronous, signalling onNext followed by onComplete immediately may
<add> * result in the sequence to be completed immediately. Similarly, if this inner
<add> * {@code Publisher} signals {@code onError} or {@code onComplete} while the upstream is
<add> * active, the sequence is terminated with the same signal immediately.
<add> * <p>
<add> * The following example demonstrates how to retry an asynchronous source with a delay:
<add> * <pre><code>
<add> * Completable.timer(1, TimeUnit.SECONDS)
<add> * .doOnSubscribe(s -> System.out.println("subscribing"))
<add> * .doOnComplete(() -> { throw new RuntimeException(); })
<add> * .retryWhen(errors -> {
<add> * AtomicInteger counter = new AtomicInteger();
<add> * return errors
<add> * .takeWhile(e -> counter.getAndIncrement() != 3)
<add> * .flatMap(e -> {
<add> * System.out.println("delay retry by " + counter.get() + " second(s)");
<add> * return Flowable.timer(counter.get(), TimeUnit.SECONDS);
<add> * });
<add> * })
<add> * .blockingAwait();
<add> * </code></pre>
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code retryWhen} does not operate by default on a particular {@link Scheduler}.</dd>
<ide><path>src/main/java/io/reactivex/Flowable.java
<ide> public final Flowable<T> retryUntil(final BooleanSupplier stop) {
<ide> * resubscribe to the source Publisher.
<ide> * <p>
<ide> * <img width="640" height="430" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/retryWhen.f.png" alt="">
<del> *
<add> * <p>
<ide> * Example:
<ide> *
<ide> * This retries 3 times, each time incrementing the number of seconds it waits.
<ide> *
<ide> * <pre><code>
<del> * Publisher.create((Subscriber<? super String> s) -> {
<add> * Flowable.create((FlowableEmitter<? super String> s) -> {
<ide> * System.out.println("subscribing");
<ide> * s.onError(new RuntimeException("always fails"));
<del> * }).retryWhen(attempts -> {
<add> * }, BackpressureStrategy.BUFFER).retryWhen(attempts -> {
<ide> * return attempts.zipWith(Flowable.range(1, 3), (n, i) -> i).flatMap(i -> {
<ide> * System.out.println("delay retry by " + i + " second(s)");
<del> * return Publisher.timer(i, TimeUnit.SECONDS);
<add> * return Flowable.timer(i, TimeUnit.SECONDS);
<ide> * });
<ide> * }).blockingForEach(System.out::println);
<ide> * </code></pre>
<ide> public final Flowable<T> retryUntil(final BooleanSupplier stop) {
<ide> * delay retry by 3 second(s)
<ide> * subscribing
<ide> * } </pre>
<add> * <p>
<add> * Note that the inner {@code Publisher} returned by the handler function should signal
<add> * either {@code onNext}, {@code onError} or {@code onComplete} in response to the received
<add> * {@code Throwable} to indicate the operator should retry or terminate. If the upstream to
<add> * the operator is asynchronous, signalling onNext followed by onComplete immediately may
<add> * result in the sequence to be completed immediately. Similarly, if this inner
<add> * {@code Publisher} signals {@code onError} or {@code onComplete} while the upstream is
<add> * active, the sequence is terminated with the same signal immediately.
<add> * <p>
<add> * The following example demonstrates how to retry an asynchronous source with a delay:
<add> * <pre><code>
<add> * Flowable.timer(1, TimeUnit.SECONDS)
<add> * .doOnSubscribe(s -> System.out.println("subscribing"))
<add> * .map(v -> { throw new RuntimeException(); })
<add> * .retryWhen(errors -> {
<add> * AtomicInteger counter = new AtomicInteger();
<add> * return errors
<add> * .takeWhile(e -> counter.getAndIncrement() != 3)
<add> * .flatMap(e -> {
<add> * System.out.println("delay retry by " + counter.get() + " second(s)");
<add> * return Flowable.timer(counter.get(), TimeUnit.SECONDS);
<add> * });
<add> * })
<add> * .blockingSubscribe(System.out::println, System.out::println);
<add> * </code></pre>
<ide> * <dl>
<ide> * <dt><b>Backpressure:</b></dt>
<del> * <dd>The operator honors downstream backpressure and expects the source {@code Publisher} to honor backpressure as well.
<add> * <dd>The operator honors downstream backpressure and expects both the source
<add> * and inner {@code Publisher}s to honor backpressure as well.
<ide> * If this expectation is violated, the operator <em>may</em> throw an {@code IllegalStateException}.</dd>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code retryWhen} does not operate by default on a particular {@link Scheduler}.</dd>
<ide><path>src/main/java/io/reactivex/Maybe.java
<ide> public final Maybe<T> retryUntil(final BooleanSupplier stop) {
<ide> * resubscribe to the source Publisher.
<ide> * <p>
<ide> * <img width="640" height="430" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/retryWhen.f.png" alt="">
<del> *
<add> * <p>
<ide> * Example:
<ide> *
<ide> * This retries 3 times, each time incrementing the number of seconds it waits.
<ide> *
<ide> * <pre><code>
<del> * Flowable.create((FlowableEmitter<? super String> s) -> {
<add> * Maybe.create((MaybeEmitter<? super String> s) -> {
<ide> * System.out.println("subscribing");
<ide> * s.onError(new RuntimeException("always fails"));
<ide> * }, BackpressureStrategy.BUFFER).retryWhen(attempts -> {
<ide> * return attempts.zipWith(Publisher.range(1, 3), (n, i) -> i).flatMap(i -> {
<ide> * System.out.println("delay retry by " + i + " second(s)");
<del> * return Publisher.timer(i, TimeUnit.SECONDS);
<add> * return Flowable.timer(i, TimeUnit.SECONDS);
<ide> * });
<ide> * }).blockingForEach(System.out::println);
<ide> * </code></pre>
<ide> public final Maybe<T> retryUntil(final BooleanSupplier stop) {
<ide> * delay retry by 3 second(s)
<ide> * subscribing
<ide> * } </pre>
<add> * <p>
<add> * Note that the inner {@code Publisher} returned by the handler function should signal
<add> * either {@code onNext}, {@code onError} or {@code onComplete} in response to the received
<add> * {@code Throwable} to indicate the operator should retry or terminate. If the upstream to
<add> * the operator is asynchronous, signalling onNext followed by onComplete immediately may
<add> * result in the sequence to be completed immediately. Similarly, if this inner
<add> * {@code Publisher} signals {@code onError} or {@code onComplete} while the upstream is
<add> * active, the sequence is terminated with the same signal immediately.
<add> * <p>
<add> * The following example demonstrates how to retry an asynchronous source with a delay:
<add> * <pre><code>
<add> * Maybe.timer(1, TimeUnit.SECONDS)
<add> * .doOnSubscribe(s -> System.out.println("subscribing"))
<add> * .map(v -> { throw new RuntimeException(); })
<add> * .retryWhen(errors -> {
<add> * AtomicInteger counter = new AtomicInteger();
<add> * return errors
<add> * .takeWhile(e -> counter.getAndIncrement() != 3)
<add> * .flatMap(e -> {
<add> * System.out.println("delay retry by " + counter.get() + " second(s)");
<add> * return Flowable.timer(counter.get(), TimeUnit.SECONDS);
<add> * });
<add> * })
<add> * .blockingGet();
<add> * </code></pre>
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code retryWhen} does not operate by default on a particular {@link Scheduler}.</dd>
<ide><path>src/main/java/io/reactivex/Observable.java
<ide> public final Observable<T> retryUntil(final BooleanSupplier stop) {
<ide> * resubscribe to the source ObservableSource.
<ide> * <p>
<ide> * <img width="640" height="430" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/retryWhen.f.png" alt="">
<del> *
<add> * <p>
<ide> * Example:
<ide> *
<ide> * This retries 3 times, each time incrementing the number of seconds it waits.
<ide> *
<ide> * <pre><code>
<del> * ObservableSource.create((Observer<? super String> s) -> {
<add> * Observable.create((ObservableEmitter<? super String> s) -> {
<ide> * System.out.println("subscribing");
<ide> * s.onError(new RuntimeException("always fails"));
<ide> * }).retryWhen(attempts -> {
<ide> * return attempts.zipWith(Observable.range(1, 3), (n, i) -> i).flatMap(i -> {
<ide> * System.out.println("delay retry by " + i + " second(s)");
<del> * return ObservableSource.timer(i, TimeUnit.SECONDS);
<add> * return Observable.timer(i, TimeUnit.SECONDS);
<ide> * });
<ide> * }).blockingForEach(System.out::println);
<ide> * </code></pre>
<ide> public final Observable<T> retryUntil(final BooleanSupplier stop) {
<ide> * delay retry by 3 second(s)
<ide> * subscribing
<ide> * } </pre>
<add> * <p>
<add> * Note that the inner {@code ObservableSource} returned by the handler function should signal
<add> * either {@code onNext}, {@code onError} or {@code onComplete} in response to the received
<add> * {@code Throwable} to indicate the operator should retry or terminate. If the upstream to
<add> * the operator is asynchronous, signalling onNext followed by onComplete immediately may
<add> * result in the sequence to be completed immediately. Similarly, if this inner
<add> * {@code ObservableSource} signals {@code onError} or {@code onComplete} while the upstream is
<add> * active, the sequence is terminated with the same signal immediately.
<add> * <p>
<add> * The following example demonstrates how to retry an asynchronous source with a delay:
<add> * <pre><code>
<add> * Observable.timer(1, TimeUnit.SECONDS)
<add> * .doOnSubscribe(s -> System.out.println("subscribing"))
<add> * .map(v -> { throw new RuntimeException(); })
<add> * .retryWhen(errors -> {
<add> * AtomicInteger counter = new AtomicInteger();
<add> * return errors
<add> * .takeWhile(e -> counter.getAndIncrement() != 3)
<add> * .flatMap(e -> {
<add> * System.out.println("delay retry by " + counter.get() + " second(s)");
<add> * return Observable.timer(counter.get(), TimeUnit.SECONDS);
<add> * });
<add> * })
<add> * .blockingSubscribe(System.out::println, System.out::println);
<add> * </code></pre>
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code retryWhen} does not operate by default on a particular {@link Scheduler}.</dd>
<ide><path>src/main/java/io/reactivex/Single.java
<ide> public final Single<T> retry(Predicate<? super Throwable> predicate) {
<ide> * function signals a value.
<ide> * <p>
<ide> * If the Publisher signals an onComplete, the resulting Single will signal a NoSuchElementException.
<add> * <p>
<add> * Note that the inner {@code Publisher} returned by the handler function should signal
<add> * either {@code onNext}, {@code onError} or {@code onComplete} in response to the received
<add> * {@code Throwable} to indicate the operator should retry or terminate. If the upstream to
<add> * the operator is asynchronous, signalling onNext followed by onComplete immediately may
<add> * result in the sequence to be completed immediately. Similarly, if this inner
<add> * {@code Publisher} signals {@code onError} or {@code onComplete} while the upstream is
<add> * active, the sequence is terminated with the same signal immediately.
<add> * <p>
<add> * The following example demonstrates how to retry an asynchronous source with a delay:
<add> * <pre><code>
<add> * Single.timer(1, TimeUnit.SECONDS)
<add> * .doOnSubscribe(s -> System.out.println("subscribing"))
<add> * .map(v -> { throw new RuntimeException(); })
<add> * .retryWhen(errors -> {
<add> * AtomicInteger counter = new AtomicInteger();
<add> * return errors
<add> * .takeWhile(e -> counter.getAndIncrement() != 3)
<add> * .flatMap(e -> {
<add> * System.out.println("delay retry by " + counter.get() + " second(s)");
<add> * return Flowable.timer(counter.get(), TimeUnit.SECONDS);
<add> * });
<add> * })
<add> * .blockingGet();
<add> * </code></pre>
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code retryWhen} does not operate by default on a particular {@link Scheduler}.</dd> | 5 |
Ruby | Ruby | fix failing cascade exception | 2ab2077235308aaa82dc430f1da8d6519fb7dac0 | <ide><path>actionpack/lib/action_dispatch/middleware/debug_exceptions.rb
<ide> def call(env)
<ide> begin
<ide> response = @app.call(env)
<ide>
<add> # TODO: Maybe this should be in the router itself
<ide> if response[1]['X-Cascade'] == 'pass'
<ide> raise ActionController::RoutingError, "No route matches [#{env['REQUEST_METHOD']}] #{env['PATH_INFO'].inspect}"
<ide> end
<ide> rescue Exception => exception
<ide> raise exception if env['action_dispatch.show_exceptions'] == false
<ide> end
<ide>
<del> response ? response : render_exception(env, exception)
<add> exception ? render_exception(env, exception) : response
<ide> end
<ide>
<ide> private
<ide><path>actionpack/lib/action_dispatch/middleware/show_exceptions.rb
<ide> def call(env)
<ide> raise exception if env['action_dispatch.show_exceptions'] == false
<ide> end
<ide>
<del> response ? response : render_exception_with_failsafe(env, exception)
<add> response || render_exception_with_failsafe(env, exception)
<ide> end
<ide>
<ide> private
<ide><path>actionpack/test/dispatch/debug_exceptions_test.rb
<ide> def call(env)
<ide> env['action_dispatch.show_detailed_exceptions'] = @detailed
<ide> req = ActionDispatch::Request.new(env)
<ide> case req.path
<add> when "/pass"
<add> [404, { "X-Cascade" => "pass" }, []]
<ide> when "/not_found"
<ide> raise ActionController::UnknownAction
<ide> when "/runtime_error"
<ide> def call(env)
<ide> end
<ide> end
<ide>
<add> test 'raise an exception on cascade pass' do
<add> @app = ProductionApp
<add> assert_raise ActionController::RoutingError do
<add> get "/pass", {}, {'action_dispatch.show_exceptions' => true}
<add> end
<add> end
<add>
<ide> test "rescue with diagnostics message" do
<ide> @app = DevelopmentApp
<ide> | 3 |
Ruby | Ruby | remove ruby 1.8 related code | f54b8468c739055164aa8f51e9680c43a51c4381 | <ide><path>activesupport/lib/active_support/core_ext/date_time/conversions.rb
<ide> def readable_inspect
<ide> alias_method :default_inspect, :inspect
<ide> alias_method :inspect, :readable_inspect
<ide>
<del> # Converts self to a Ruby Date object; time portion is discarded.
<del> def to_date
<del> ::Date.new(year, month, day)
<del> end unless instance_methods(false).include?(:to_date)
<del>
<ide> # Attempts to convert self to a Ruby Time object; returns self if out of range of Ruby Time class.
<ide> # If self has an offset other than 0, self will just be returned unaltered, since there's no clean way to map it to a Time.
<ide> def to_time
<ide> self.offset == 0 ? ::Time.utc_time(year, month, day, hour, min, sec, sec_fraction * 1000000) : self
<ide> end
<ide>
<del> # To be able to keep Times, Dates and DateTimes interchangeable on conversions.
<del> def to_datetime
<del> self
<del> end unless instance_methods(false).include?(:to_datetime)
<del>
<ide> def self.civil_from_format(utc_or_local, year, month=1, day=1, hour=0, min=0, sec=0)
<ide> offset = utc_or_local.to_sym == :local ? local_offset : 0
<ide> civil(year, month, day, hour, min, sec, offset)
<ide> end
<ide>
<del> # Converts datetime to an appropriate format for use in XML.
<del> def xmlschema
<del> strftime("%Y-%m-%dT%H:%M:%S%Z")
<del> end unless instance_methods(false).include?(:xmlschema)
<del>
<ide> # Converts self to a floating-point number of seconds since the Unix epoch.
<ide> def to_f
<ide> seconds_since_unix_epoch.to_f | 1 |
Python | Python | add multiberts conversion script | 9a9805fccf7f4802ce8438c86fe2c7e50465b80b | <ide><path>src/transformers/models/bert/convert_multiberts_checkpoint_to_pytorch.py
<add># Copyright 2021 The HuggingFace Team. All rights reserved.
<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>This script can be used to convert a head-less TF 2.x MultiBERTs model to PyTorch, as published on the official GitHub:
<add>https://github.com/tensorflow/models/tree/master/official/nlp/bert
<add>"""
<add>
<add>import argparse
<add>import os
<add>
<add>import tensorflow as tf
<add>import torch
<add>
<add>from transformers import BertConfig, BertForPreTraining
<add>from transformers.utils import logging
<add>
<add>
<add>logging.set_verbosity_info()
<add>logger = logging.get_logger(__name__)
<add>
<add>
<add>def convert_multibert_checkpoint_to_pytorch(tf_checkpoint_path, config_path, save_path):
<add> tf_path = os.path.abspath(tf_checkpoint_path)
<add> logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
<add>
<add> # Load weights from TF model
<add> init_vars = tf.train.list_variables(tf_path)
<add> names = []
<add> arrays = []
<add> config = BertConfig.from_pretrained(config_path)
<add> model = BertForPreTraining(config)
<add>
<add> layer_nums = []
<add> for full_name, shape in init_vars:
<add> array = tf.train.load_variable(tf_path, full_name)
<add> names.append(full_name)
<add> split_names = full_name.split("/")
<add> for name in split_names:
<add> if name.startswith("layer_"):
<add> layer_nums.append(int(name.split("_")[-1]))
<add>
<add> arrays.append(array)
<add> logger.info(f"Read a total of {len(arrays):,} layers")
<add>
<add> name_to_array = dict(zip(names, arrays))
<add>
<add> # Check that number of layers match
<add> assert config.num_hidden_layers == len(list(set(layer_nums)))
<add>
<add> state_dict = model.state_dict()
<add>
<add> # Need to do this explicitly as it is a buffer
<add> position_ids = state_dict["bert.embeddings.position_ids"]
<add> new_state_dict = {"bert.embeddings.position_ids": position_ids}
<add>
<add> # Encoder Layers
<add> for weight_name in names:
<add> pt_weight_name = weight_name.replace("kernel", "weight").replace("gamma", "weight").replace("beta", "bias")
<add> name_split = pt_weight_name.split("/")
<add> for name_idx, name in enumerate(name_split):
<add> if name.startswith("layer_"):
<add> name_split[name_idx] = name.replace("_", ".")
<add>
<add> if name_split[-1].endswith("embeddings"):
<add> name_split.append("weight")
<add>
<add> if name_split[0] == "cls":
<add> if name_split[-1] == "output_bias":
<add> name_split[-1] = "bias"
<add> if name_split[-1] == "output_weights":
<add> name_split[-1] = "weight"
<add>
<add> if name_split[-1] == "weight" and name_split[-2] == "dense":
<add> name_to_array[weight_name] = name_to_array[weight_name].T
<add>
<add> pt_weight_name = ".".join(name_split)
<add>
<add> new_state_dict[pt_weight_name] = torch.from_numpy(name_to_array[weight_name])
<add>
<add> new_state_dict["cls.predictions.decoder.weight"] = new_state_dict["bert.embeddings.word_embeddings.weight"].clone()
<add> new_state_dict["cls.predictions.decoder.bias"] = new_state_dict["cls.predictions.bias"].clone().T
<add> # Load State Dict
<add> model.load_state_dict(new_state_dict)
<add>
<add> # Save PreTrained
<add> logger.info(f"Saving pretrained model to {save_path}")
<add> model.save_pretrained(save_path)
<add>
<add> return model
<add>
<add>
<add>if __name__ == "__main__":
<add> parser = argparse.ArgumentParser()
<add> parser.add_argument(
<add> "--tf_checkpoint_path",
<add> type=str,
<add> default="./seed_0/bert.ckpt",
<add> required=False,
<add> help="Path to the TensorFlow 2.x checkpoint path.",
<add> )
<add> parser.add_argument(
<add> "--bert_config_file",
<add> type=str,
<add> default="./bert_config.json",
<add> required=False,
<add> help="The config json file corresponding to the BERT model. This specifies the model architecture.",
<add> )
<add> parser.add_argument(
<add> "--save_path",
<add> type=str,
<add> required=True,
<add> help="Path to the output PyTorch model (must include filename).",
<add> )
<add> args = parser.parse_args()
<add>
<add> convert_multibert_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.save_path) | 1 |
Python | Python | add whitespace and combined augmenters | 28ba31e793cf0a59e5ce14bd2e8f5c5d6e785ca2 | <ide><path>spacy/tests/training/test_augmenters.py
<ide> import pytest
<del>from spacy.training import Corpus
<add>from spacy.pipeline._parser_internals.nonproj import contains_cycle
<add>from spacy.training import Corpus, Example
<ide> from spacy.training.augment import create_orth_variants_augmenter
<ide> from spacy.training.augment import create_lower_casing_augmenter
<add>from spacy.training.augment import make_whitespace_variant
<ide> from spacy.lang.en import English
<del>from spacy.tokens import DocBin, Doc
<add>from spacy.tokens import DocBin, Doc, Span
<ide> from contextlib import contextmanager
<ide> import random
<ide>
<ide> def augment(nlp, example):
<ide> ents = [(e.start, e.end, e.label) for e in doc.ents]
<ide> assert [(e.start, e.end, e.label) for e in corpus[0].reference.ents] == ents
<ide> assert [(e.start, e.end, e.label) for e in corpus[1].reference.ents] == ents
<add>
<add>
<add>def test_make_whitespace_variant(nlp):
<add> # fmt: off
<add> text = "They flew to New York City.\nThen they drove to Washington, D.C."
<add> words = ["They", "flew", "to", "New", "York", "City", ".", "\n", "Then", "they", "drove", "to", "Washington", ",", "D.C."]
<add> spaces = [True, True, True, True, True, False, False, False, True, True, True, True, False, True, False]
<add> tags = ["PRP", "VBD", "IN", "NNP", "NNP", "NNP", ".", "_SP", "RB", "PRP", "VBD", "IN", "NNP", ",", "NNP"]
<add> lemmas = ["they", "fly", "to", "New", "York", "City", ".", "\n", "then", "they", "drive", "to", "Washington", ",", "D.C."]
<add> heads = [1, 1, 1, 4, 5, 2, 1, 10, 10, 10, 10, 10, 11, 12, 12]
<add> deps = ["nsubj", "ROOT", "prep", "compound", "compound", "pobj", "punct", "dep", "advmod", "nsubj", "ROOT", "prep", "pobj", "punct", "appos"]
<add> ents = ["O", "O", "O", "B-GPE", "I-GPE", "I-GPE", "O", "O", "O", "O", "O", "O", "B-GPE", "O", "B-GPE"]
<add> # fmt: on
<add> doc = Doc(
<add> nlp.vocab,
<add> words=words,
<add> spaces=spaces,
<add> tags=tags,
<add> lemmas=lemmas,
<add> heads=heads,
<add> deps=deps,
<add> ents=ents,
<add> )
<add> assert doc.text == text
<add> example = Example(nlp.make_doc(text), doc)
<add> # whitespace is only added internally in entity spans
<add> mod_ex = make_whitespace_variant(nlp, example, " ", 3)
<add> assert mod_ex.reference.ents[0].text == "New York City"
<add> mod_ex = make_whitespace_variant(nlp, example, " ", 4)
<add> assert mod_ex.reference.ents[0].text == "New York City"
<add> mod_ex = make_whitespace_variant(nlp, example, " ", 5)
<add> assert mod_ex.reference.ents[0].text == "New York City"
<add> mod_ex = make_whitespace_variant(nlp, example, " ", 6)
<add> assert mod_ex.reference.ents[0].text == "New York City"
<add> # add a space at every possible position
<add> for i in range(len(doc) + 1):
<add> mod_ex = make_whitespace_variant(nlp, example, " ", i)
<add> assert mod_ex.reference[i].is_space
<add> # adds annotation when the doc contains at least partial annotation
<add> assert [t.tag_ for t in mod_ex.reference] == tags[:i] + ["_SP"] + tags[i:]
<add> assert [t.lemma_ for t in mod_ex.reference] == lemmas[:i] + [" "] + lemmas[i:]
<add> assert [t.dep_ for t in mod_ex.reference] == deps[:i] + ["dep"] + deps[i:]
<add> # does not add partial annotation if doc does not contain this feature
<add> assert not mod_ex.reference.has_annotation("POS")
<add> assert not mod_ex.reference.has_annotation("MORPH")
<add> # produces well-formed trees
<add> assert not contains_cycle([t.head.i for t in mod_ex.reference])
<add> assert len(list(doc.sents)) == 2
<add> if i == 0:
<add> assert mod_ex.reference[i].head.i == 1
<add> else:
<add> assert mod_ex.reference[i].head.i == i - 1
<add> # adding another space also produces well-formed trees
<add> for j in (3, 8, 10):
<add> mod_ex2 = make_whitespace_variant(nlp, mod_ex, "\t\t\n", j)
<add> assert not contains_cycle([t.head.i for t in mod_ex2.reference])
<add> assert len(list(doc.sents)) == 2
<add> assert mod_ex2.reference[j].head.i == j - 1
<add> # entities are well-formed
<add> assert len(doc.ents) == len(mod_ex.reference.ents)
<add> for ent in mod_ex.reference.ents:
<add> assert not ent[0].is_space
<add> assert not ent[-1].is_space
<add>
<add> # no modifications if:
<add> # partial dependencies
<add> example.reference[0].dep_ = ""
<add> mod_ex = make_whitespace_variant(nlp, example, " ", 5)
<add> assert mod_ex.text == example.reference.text
<add> example.reference[0].dep_ = "nsubj" # reset
<add>
<add> # spans
<add> example.reference.spans["spans"] = [example.reference[0:5]]
<add> mod_ex = make_whitespace_variant(nlp, example, " ", 5)
<add> assert mod_ex.text == example.reference.text
<add> del example.reference.spans["spans"] # reset
<add>
<add> # links
<add> example.reference.ents = [Span(doc, 0, 2, label="ENT", kb_id="Q123")]
<add> mod_ex = make_whitespace_variant(nlp, example, " ", 5)
<add> assert mod_ex.text == example.reference.text
<ide><path>spacy/training/augment.py
<ide> from typing import Callable, Iterator, Dict, List, Tuple, TYPE_CHECKING
<add>from typing import Optional
<ide> import random
<ide> import itertools
<ide> from functools import partial
<ide> from ..language import Language # noqa: F401
<ide>
<ide>
<del>class OrthVariantsSingle(BaseModel):
<del> tags: List[StrictStr]
<del> variants: List[StrictStr]
<del>
<add>@registry.augmenters("spacy.combined_augmenter.v1")
<add>def create_combined_augmenter(
<add> lower_level: float,
<add> orth_level: float,
<add> orth_variants: Optional[Dict[str, List[Dict]]],
<add> whitespace_level: float,
<add> whitespace_per_token: float,
<add> whitespace_variants: Optional[List[str]],
<add>) -> Callable[["Language", Example], Iterator[Example]]:
<add> """Create a data augmentation callback that uses orth-variant replacement.
<add> The callback can be added to a corpus or other data iterator during training.
<ide>
<del>class OrthVariantsPaired(BaseModel):
<del> tags: List[StrictStr]
<del> variants: List[List[StrictStr]]
<add> lower_level (float): The percentage of texts that will be lowercased.
<add> orth_level (float): The percentage of texts that will be augmented.
<add> orth_variants (Optional[Dict[str, List[Dict]]]): A dictionary containing the
<add> single and paired orth variants. Typically loaded from a JSON file.
<add> whitespace_level (float): The percentage of texts that will have whitespace
<add> tokens inserted.
<add> whitespace_per_token (float): The number of whitespace tokens to insert in
<add> the modified doc as a percentage of the doc length.
<add> whitespace_variants (Optional[List[str]]): The whitespace token texts.
<add> RETURNS (Callable[[Language, Example], Iterator[Example]]): The augmenter.
<add> """
<add> return partial(
<add> combined_augmenter,
<add> lower_level=lower_level,
<add> orth_level=orth_level,
<add> orth_variants=orth_variants,
<add> whitespace_level=whitespace_level,
<add> whitespace_per_token=whitespace_per_token,
<add> whitespace_variants=whitespace_variants,
<add> )
<ide>
<ide>
<del>class OrthVariants(BaseModel):
<del> paired: List[OrthVariantsPaired] = []
<del> single: List[OrthVariantsSingle] = []
<add>def combined_augmenter(
<add> nlp: "Language",
<add> example: Example,
<add> *,
<add> lower_level: float = 0.0,
<add> orth_level: float = 0.0,
<add> orth_variants: Optional[Dict[str, List[Dict]]] = None,
<add> whitespace_level: float = 0.0,
<add> whitespace_per_token: float = 0.0,
<add> whitespace_variants: Optional[List[str]] = None,
<add>) -> Iterator[Example]:
<add> if random.random() < lower_level:
<add> example = make_lowercase_variant(nlp, example)
<add> if orth_variants and random.random() < orth_level:
<add> raw_text = example.text
<add> orig_dict = example.to_dict()
<add> variant_text, variant_token_annot = make_orth_variants(
<add> nlp,
<add> raw_text,
<add> orig_dict["token_annotation"],
<add> orth_variants,
<add> lower=False,
<add> )
<add> orig_dict["token_annotation"] = variant_token_annot
<add> example = example.from_dict(nlp.make_doc(variant_text), orig_dict)
<add> if whitespace_variants and random.random() < whitespace_level:
<add> for _ in range(int(len(example.reference) * whitespace_per_token)):
<add> example = make_whitespace_variant(
<add> nlp,
<add> example,
<add> random.choice(whitespace_variants),
<add> random.randrange(0, len(example.reference)),
<add> )
<add> yield example
<ide>
<ide>
<ide> @registry.augmenters("spacy.orth_variants.v1")
<ide> def create_orth_variants_augmenter(
<del> level: float, lower: float, orth_variants: OrthVariants
<add> level: float, lower: float, orth_variants: Dict[str, List[Dict]]
<ide> ) -> Callable[["Language", Example], Iterator[Example]]:
<ide> """Create a data augmentation callback that uses orth-variant replacement.
<ide> The callback can be added to a corpus or other data iterator during training.
<ide>
<ide> level (float): The percentage of texts that will be augmented.
<ide> lower (float): The percentage of texts that will be lowercased.
<del> orth_variants (Dict[str, dict]): A dictionary containing the single and
<del> paired orth variants. Typically loaded from a JSON file.
<add> orth_variants (Dict[str, List[Dict]]): A dictionary containing
<add> the single and paired orth variants. Typically loaded from a JSON file.
<ide> RETURNS (Callable[[Language, Example], Iterator[Example]]): The augmenter.
<ide> """
<ide> return partial(
<ide> def lower_casing_augmenter(
<ide> if random.random() >= level:
<ide> yield example
<ide> else:
<del> example_dict = example.to_dict()
<del> doc = nlp.make_doc(example.text.lower())
<del> example_dict["token_annotation"]["ORTH"] = [t.lower_ for t in example.reference]
<del> yield example.from_dict(doc, example_dict)
<add> yield make_lowercase_variant(nlp, example)
<add>
<add>
<add>def make_lowercase_variant(nlp: "Language", example: Example):
<add> example_dict = example.to_dict()
<add> doc = nlp.make_doc(example.text.lower())
<add> example_dict["token_annotation"]["ORTH"] = [t.lower_ for t in example.reference]
<add> return example.from_dict(doc, example_dict)
<ide>
<ide>
<ide> def orth_variants_augmenter(
<ide> nlp: "Language",
<ide> example: Example,
<del> orth_variants: Dict,
<add> orth_variants: Dict[str, List[Dict]],
<ide> *,
<ide> level: float = 0.0,
<ide> lower: float = 0.0,
<ide> def make_orth_variants(
<ide> pair_idx = pair.index(words[word_idx])
<ide> words[word_idx] = punct_choices[punct_idx][pair_idx]
<ide> token_dict["ORTH"] = words
<del> # construct modified raw text from words and spaces
<add> raw = construct_modified_raw_text(token_dict)
<add> return raw, token_dict
<add>
<add>
<add>def make_whitespace_variant(
<add> nlp: "Language",
<add> example: Example,
<add> whitespace: str,
<add> position: int,
<add>) -> Example:
<add> """Insert the whitespace token at the specified token offset in the doc.
<add> This is primarily intended for v2-compatible training data that doesn't
<add> include links or spans. If the document includes links, spans, or partial
<add> dependency annotation, it is returned without modifications.
<add>
<add> The augmentation follows the basics of the v2 space attachment policy, but
<add> without a distinction between "real" and other tokens, so space tokens
<add> may be attached to space tokens:
<add> - at the beginning of a sentence attach the space token to the following
<add> token
<add> - otherwise attach the space token to the preceding token
<add>
<add> The augmenter does not attempt to consolidate adjacent whitespace in the
<add> same way that the tokenizer would.
<add>
<add> The following annotation is used for the space token:
<add> TAG: "_SP"
<add> MORPH: ""
<add> POS: "SPACE"
<add> LEMMA: ORTH
<add> DEP: "dep"
<add> SENT_START: False
<add>
<add> The annotation for each attribute is only set for the space token if there
<add> is already at least partial annotation for that attribute in the original
<add> example.
<add>
<add> RETURNS (Example): Example with one additional space token.
<add> """
<add> example_dict = example.to_dict()
<add> doc_dict = example_dict.get("doc_annotation", {})
<add> token_dict = example_dict.get("token_annotation", {})
<add> # returned unmodified if:
<add> # - doc is empty
<add> # - words are not defined
<add> # - links are defined (only character-based offsets, which is more a quirk
<add> # of Example.to_dict than a technical constraint)
<add> # - spans are defined
<add> # - there are partial dependencies
<add> if (
<add> len(example.reference) == 0
<add> or "ORTH" not in token_dict
<add> or len(doc_dict.get("links", [])) > 0
<add> or len(example.reference.spans) > 0
<add> or (
<add> example.reference.has_annotation("DEP")
<add> and not example.reference.has_annotation("DEP", require_complete=True)
<add> )
<add> ):
<add> return example
<add> words = token_dict.get("ORTH", [])
<add> length = len(words)
<add> assert 0 <= position <= length
<add> if example.reference.has_annotation("ENT_TYPE"):
<add> # I-ENTITY if between B/I-ENTITY and I/L-ENTITY otherwise O
<add> entity = "O"
<add> if position > 1 and position < length:
<add> ent_prev = doc_dict["entities"][position - 1]
<add> ent_next = doc_dict["entities"][position]
<add> if "-" in ent_prev and "-" in ent_next:
<add> ent_iob_prev = ent_prev.split("-")[0]
<add> ent_type_prev = ent_prev.split("-", 1)[1]
<add> ent_iob_next = ent_next.split("-")[0]
<add> ent_type_next = ent_next.split("-", 1)[1]
<add> if (
<add> ent_iob_prev in ("B", "I")
<add> and ent_iob_next in ("I", "L")
<add> and ent_type_prev == ent_type_next
<add> ):
<add> entity = f"I-{ent_type_prev}"
<add> doc_dict["entities"].insert(position, entity)
<add> else:
<add> del doc_dict["entities"]
<add> token_dict["ORTH"].insert(position, whitespace)
<add> token_dict["SPACY"].insert(position, False)
<add> if example.reference.has_annotation("TAG"):
<add> token_dict["TAG"].insert(position, "_SP")
<add> else:
<add> del token_dict["TAG"]
<add> if example.reference.has_annotation("LEMMA"):
<add> token_dict["LEMMA"].insert(position, whitespace)
<add> else:
<add> del token_dict["LEMMA"]
<add> if example.reference.has_annotation("POS"):
<add> token_dict["POS"].insert(position, "SPACE")
<add> else:
<add> del token_dict["POS"]
<add> if example.reference.has_annotation("MORPH"):
<add> token_dict["MORPH"].insert(position, "")
<add> else:
<add> del token_dict["MORPH"]
<add> if example.reference.has_annotation("DEP", require_complete=True):
<add> if position == 0:
<add> token_dict["HEAD"].insert(position, 0)
<add> else:
<add> token_dict["HEAD"].insert(position, position - 1)
<add> for i in range(len(token_dict["HEAD"])):
<add> if token_dict["HEAD"][i] >= position:
<add> token_dict["HEAD"][i] += 1
<add> token_dict["DEP"].insert(position, "dep")
<add> else:
<add> del token_dict["HEAD"]
<add> del token_dict["DEP"]
<add> if example.reference.has_annotation("SENT_START"):
<add> token_dict["SENT_START"].insert(position, False)
<add> else:
<add> del token_dict["SENT_START"]
<add> raw = construct_modified_raw_text(token_dict)
<add> return Example.from_dict(nlp.make_doc(raw), example_dict)
<add>
<add>
<add>def construct_modified_raw_text(token_dict):
<add> """Construct modified raw text from words and spaces."""
<ide> raw = ""
<ide> for orth, spacy in zip(token_dict["ORTH"], token_dict["SPACY"]):
<ide> raw += orth
<ide> if spacy:
<ide> raw += " "
<del> return raw, token_dict
<add> return raw | 2 |
Javascript | Javascript | add lint task | 9d79b99874a5f52f0b83ca11dd45a7302adebdae | <ide><path>Gruntfile.js
<ide> module.exports = function( grunt ) {
<ide> // Integrate jQuery specific tasks
<ide> grunt.loadTasks( "build/tasks" );
<ide>
<del> // Alias bower to bowercopy
<ide> grunt.registerTask( "bower", "bowercopy" );
<add> grunt.registerTask( "lint", [ "jshint", "jscs" ] );
<ide>
<ide> // Short list as a high frequency watch task
<del> grunt.registerTask( "dev", [ "build:*:*", "jshint", "jscs" ] );
<add> grunt.registerTask( "dev", [ "build:*:*", "lint" ] );
<ide>
<ide> // Default grunt
<ide> grunt.registerTask( "default", [ "jsonlint", "dev", "uglify", "dist:*", "compare_size" ] ); | 1 |
Javascript | Javascript | optimize one function case | 050d42517330f9bbed73d37c13de84ea83a87230 | <ide><path>src/compose.js
<ide> export default function compose(...funcs) {
<ide> if (funcs.length === 0) {
<ide> return arg => arg
<del> } else {
<del> const last = funcs[funcs.length - 1]
<del> const rest = funcs.slice(0, -1)
<del> return (...args) => rest.reduceRight((composed, f) => f(composed), last(...args))
<ide> }
<add>
<add> if (funcs.length === 1) {
<add> return funcs[0]
<add> }
<add>
<add> const last = funcs[funcs.length - 1]
<add> const rest = funcs.slice(0, -1)
<add> return (...args) => rest.reduceRight((composed, f) => f(composed), last(...args))
<ide> }
<ide><path>test/compose.spec.js
<ide> describe('Utils', () => {
<ide> expect(compose()(3)).toBe(3)
<ide> expect(compose()()).toBe(undefined)
<ide> })
<add>
<add> it('returns the first function if given only one', () => {
<add> const fn = () => {}
<add>
<add> expect(compose(fn)).toBe(fn)
<add> })
<ide> })
<ide> }) | 2 |
PHP | PHP | move is_array check to internal method | 3509d0b31d6c17d97b7e2e0d719c63a9c3837aa3 | <ide><path>src/Illuminate/Support/Collection.php
<ide> class Collection implements ArrayAccess, Arrayable, Countable, IteratorAggregate
<ide> */
<ide> public function __construct($items = [])
<ide> {
<del> $this->items = is_array($items) ? $items : $this->getArrayableItems($items);
<add> $this->items = $this->getArrayableItems($items);
<ide> }
<ide>
<ide> /**
<ide> public function __toString()
<ide> */
<ide> protected function getArrayableItems($items)
<ide> {
<del> if ($items instanceof self) {
<add> if (is_array($items)) {
<add> return $items;
<add> } elseif ($items instanceof self) {
<ide> return $items->all();
<ide> } elseif ($items instanceof Arrayable) {
<ide> return $items->toArray(); | 1 |
Text | Text | change container name to id as actual results | d76fba0191fc64759febc1ee22c6bc28ff49b3d6 | <ide><path>docs/reference/commandline/stats.md
<ide> Running `docker stats` on all running containers
<ide>
<ide> $ docker stats
<ide> CONTAINER CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O
<del> redis1 0.07% 796 KB / 64 MB 1.21% 788 B / 648 B 3.568 MB / 512 KB
<del> redis2 0.07% 2.746 MB / 64 MB 4.29% 1.266 KB / 648 B 12.4 MB / 0 B
<del> nginx1 0.03% 4.583 MB / 64 MB 6.30% 2.854 KB / 648 B 27.7 MB / 0 B
<add> 1285939c1fd3 0.07% 796 KB / 64 MB 1.21% 788 B / 648 B 3.568 MB / 512 KB
<add> 9c76f7834ae2 0.07% 2.746 MB / 64 MB 4.29% 1.266 KB / 648 B 12.4 MB / 0 B
<add> d1ea048f04e4 0.03% 4.583 MB / 64 MB 6.30% 2.854 KB / 648 B 27.7 MB / 0 B
<ide>
<ide> Running `docker stats` on multiple containers by name and id.
<ide>
<ide><path>man/docker-stats.1.md
<ide> Running `docker stats` on all running containers
<ide>
<ide> $ docker stats
<ide> CONTAINER CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O
<del> redis1 0.07% 796 KB / 64 MB 1.21% 788 B / 648 B 3.568 MB / 512 KB
<del> redis2 0.07% 2.746 MB / 64 MB 4.29% 1.266 KB / 648 B 12.4 MB / 0 B
<del> nginx1 0.03% 4.583 MB / 64 MB 6.30% 2.854 KB / 648 B 27.7 MB / 0 B
<add> 1285939c1fd3 0.07% 796 KB / 64 MB 1.21% 788 B / 648 B 3.568 MB / 512 KB
<add> 9c76f7834ae2 0.07% 2.746 MB / 64 MB 4.29% 1.266 KB / 648 B 12.4 MB / 0 B
<add> d1ea048f04e4 0.03% 4.583 MB / 64 MB 6.30% 2.854 KB / 648 B 27.7 MB / 0 B
<ide>
<ide> Running `docker stats` on multiple containers by name and id.
<ide> | 2 |
Ruby | Ruby | require "formula" only when necessary | c6719e58542df880648bec4de8e7114f33776eca | <ide><path>Library/Homebrew/dev-cmd/cat.rb
<ide> # frozen_string_literal: true
<ide>
<ide> require "cli/parser"
<del>require "formula"
<ide>
<ide> module Homebrew
<ide> extend T::Sig
<ide> def cat
<ide>
<ide> cd HOMEBREW_REPOSITORY
<ide> pager = if Homebrew::EnvConfig.bat?
<add> require "formula"
<add>
<ide> unless Formula["bat"].any_version_installed?
<ide> # The user might want to capture the output of `brew cat ...`
<ide> # Redirect stdout to stderr | 1 |
Javascript | Javascript | remove callback page | dcb637897537327c914a4ed1029de4d3d146bfa7 | <ide><path>packages/learn/src/pages/callback.js
<del>import React from 'react';
<del>import Auth from '../auth';
<del>
<del>function AuthCallBack() {
<del> const auth = new Auth();
<del> auth.handleAuthentication();
<del> return <h2>One moment please...</h2>;
<del>}
<del>
<del>AuthCallBack.displayName = 'AuthCallBack';
<del>
<del>export default AuthCallBack; | 1 |
PHP | PHP | fix auth contract | e5535493564984c7b17b524ec6a368a66038cb16 | <ide><path>src/Illuminate/Auth/Guard.php
<ide> public function validate(array $credentials = array())
<ide> * Attempt to authenticate using HTTP Basic Auth.
<ide> *
<ide> * @param string $field
<del> * @param \Symfony\Component\HttpFoundation\Request $request
<ide> * @return \Symfony\Component\HttpFoundation\Response|null
<ide> */
<del> public function basic($field = 'email', Request $request = null)
<add> public function basic($field = 'email')
<ide> {
<ide> if ($this->check()) return;
<ide>
<del> $request = $request ?: $this->getRequest();
<del>
<ide> // If a username is set on the HTTP basic request, we will return out without
<ide> // interrupting the request lifecycle. Otherwise, we'll need to generate a
<ide> // request indicating that the given credentials were invalid for login.
<del> if ($this->attemptBasic($request, $field)) return;
<add> if ($this->attemptBasic($this->getRequest(), $field)) return;
<ide>
<ide> return $this->getBasicResponse();
<ide> }
<ide> public function basic($field = 'email', Request $request = null)
<ide> * Perform a stateless HTTP Basic login attempt.
<ide> *
<ide> * @param string $field
<del> * @param \Symfony\Component\HttpFoundation\Request $request
<ide> * @return \Symfony\Component\HttpFoundation\Response|null
<ide> */
<del> public function onceBasic($field = 'email', Request $request = null)
<add> public function onceBasic($field = 'email')
<ide> {
<del> $request = $request ?: $this->getRequest();
<del>
<del> if ( ! $this->once($this->getBasicCredentials($request, $field)))
<add> if ( ! $this->once($this->getBasicCredentials($this->getRequest(), $field)))
<ide> {
<ide> return $this->getBasicResponse();
<ide> }
<ide><path>src/Illuminate/Contracts/Auth/Authenticator.php
<ide> public function once(array $credentials = array());
<ide> */
<ide> public function attempt(array $credentials = array(), $remember = false, $login = true);
<ide>
<add> /**
<add> * Attempt to authenticate using HTTP Basic Auth.
<add> *
<add> * @param string $field
<add> * @return \Symfony\Component\HttpFoundation\Response|null
<add> */
<add> public function basic($field = 'email');
<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>
<ide> /**
<ide> * Validate a user's credentials.
<ide> *
<ide><path>tests/Auth/AuthGuardTest.php
<ide> public function testBasicReturnsNullOnValidAttempt()
<ide> $guard->shouldReceive('check')->once()->andReturn(false);
<ide> $guard->shouldReceive('attempt')->once()->with(array('email' => 'foo@bar.com', 'password' => 'secret'))->andReturn(true);
<ide> $request = Symfony\Component\HttpFoundation\Request::create('/', 'GET', array(), array(), array(), array('PHP_AUTH_USER' => 'foo@bar.com', 'PHP_AUTH_PW' => 'secret'));
<add> $guard->setRequest($request);
<ide>
<del> $guard->basic('email', $request);
<add> $guard->basic('email');
<ide> }
<ide>
<ide>
<ide> public function testBasicReturnsNullWhenAlreadyLoggedIn()
<ide> $guard->shouldReceive('check')->once()->andReturn(true);
<ide> $guard->shouldReceive('attempt')->never();
<ide> $request = Symfony\Component\HttpFoundation\Request::create('/', 'GET', array(), array(), array(), array('PHP_AUTH_USER' => 'foo@bar.com', 'PHP_AUTH_PW' => 'secret'));
<add> $guard->setRequest($request);
<ide>
<ide> $guard->basic('email', $request);
<ide> }
<ide> public function testBasicReturnsResponseOnFailure()
<ide> $guard->shouldReceive('check')->once()->andReturn(false);
<ide> $guard->shouldReceive('attempt')->once()->with(array('email' => 'foo@bar.com', 'password' => 'secret'))->andReturn(false);
<ide> $request = Symfony\Component\HttpFoundation\Request::create('/', 'GET', array(), array(), array(), array('PHP_AUTH_USER' => 'foo@bar.com', 'PHP_AUTH_PW' => 'secret'));
<add> $guard->setRequest($request);
<ide> $response = $guard->basic('email', $request);
<ide>
<ide> $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $response); | 3 |
Text | Text | fix bad docs format | 6b1fcf3e6ae29675b1a825fdf0f48c9ba8e47489 | <ide><path>libnetwork/docs/remote.md
<ide> If the remote process cannot decode, or otherwise detects a syntactic problem wi
<ide> If the remote process can decode the request, but cannot complete the operation, it must send a response in the form
<ide>
<ide> {
<del> "Err": string
<add> "Err": string
<ide> }
<ide>
<ide> The string value supplied may appear in logs, so should not include confidential information.
<ide> The string value supplied may appear in logs, so should not include confidential
<ide> When loaded, a remote driver process receives an HTTP POST on the URL `/Plugin.Activate` with no payload. It must respond with a manifest of the form
<ide>
<ide> {
<del> "Implements": ["NetworkDriver"]
<add> "Implements": ["NetworkDriver"]
<ide> }
<ide>
<ide> Other entries in the list value are allowed; `"NetworkDriver"` indicates that the plugin should be registered with LibNetwork as a driver.
<ide> Value of "Scope" should be either "local" or "global" which indicates the capabi
<ide> When the proxy is asked to create a network, the remote process shall receive a POST to the URL `/NetworkDriver.CreateNetwork` of the form
<ide>
<ide> {
<del> "NetworkID": string,
<del> "Options": {
<del> ...
<del> }
<add> "NetworkID": string,
<add> "Options": {
<add> ...
<add> }
<ide> }
<ide>
<ide> The `NetworkID` value is generated by LibNetwork. The `Options` value is the arbitrary map given to the proxy by LibNetwork.
<ide> The response indicating success is empty:
<ide> When a network owned by the remote driver is deleted, the remote process shall receive a POST to the URL `/NetworkDriver.DeleteNetwork` of the form
<ide>
<ide> {
<del> "NetworkID": string
<add> "NetworkID": string
<ide> }
<ide>
<ide> The success response is empty:
<ide> The success response is empty:
<ide> When the proxy is asked to create an endpoint, the remote process shall receive a POST to the URL `/NetworkDriver.CreateEndpoint` of the form
<ide>
<ide> {
<del> "NetworkID": string,
<del> "EndpointID": string,
<del> "Options": {
<del> ...
<del> },
<del> "Interface": {
<del> "Address": string,
<del> "AddressIPv6": string,
<del> "MacAddress": string
<del> }
<add> "NetworkID": string,
<add> "EndpointID": string,
<add> "Options": {
<add> ...
<add> },
<add> "Interface": {
<add> "Address": string,
<add> "AddressIPv6": string,
<add> "MacAddress": string
<add> }
<ide> }
<ide>
<ide> The `NetworkID` is the generated identifier for the network to which the endpoint belongs; the `EndpointID` is a generated identifier for the endpoint.
<ide> The `Interface` value is of the form given. The fields in the `Interface` may be
<ide> A success response is of the form
<ide>
<ide> {
<del> "Interface": {
<del> "Address": string,
<del> "AddressIPv6": string,
<del> "MacAddress": string
<del> }
<add> "Interface": {
<add> "Address": string,
<add> "AddressIPv6": string,
<add> "MacAddress": string
<add> }
<ide> }
<ide>
<ide> with values in the `Interface` as above. As far as the value of `Interface` is concerned, `MacAddress` and either or both of `Address` and `AddressIPv6` must be given.
<ide> If the remote process was supplied a non-empty value in `Interface`, it must res
<ide> The proxy may be asked for "operational info" on an endpoint. When this happens, the remote process shall receive a POST to `/NetworkDriver.EndpointOperInfo` of the form
<ide>
<ide> {
<del> "NetworkID": string,
<del> "EndpointID": string
<add> "NetworkID": string,
<add> "EndpointID": string
<ide> }
<ide>
<ide> where `NetworkID` and `EndpointID` have meanings as above. It must send a response of the form
<ide>
<ide> {
<del> "Value": { ... }
<add> "Value": { ... }
<ide> }
<ide>
<ide> where the value of the `Value` field is an arbitrary (possibly empty) map.
<ide> where the value of the `Value` field is an arbitrary (possibly empty) map.
<ide> When an endpoint is deleted, the remote process shall receive a POST to the URL `/NetworkDriver.DeleteEndpoint` with a body of the form
<ide>
<ide> {
<del> "NetworkID": string,
<del> "EndpointID": string
<add> "NetworkID": string,
<add> "EndpointID": string
<ide> }
<ide>
<ide> where `NetworkID` and `EndpointID` have meanings as above. A success response is empty:
<ide> where `NetworkID` and `EndpointID` have meanings as above. A success response is
<ide> When a sandbox is given an endpoint, the remote process shall receive a POST to the URL `NetworkDriver.Join` of the form
<ide>
<ide> {
<del> "NetworkID": string,
<del> "EndpointID": string,
<del> "SandboxKey": string,
<del> "Options": { ... }
<add> "NetworkID": string,
<add> "EndpointID": string,
<add> "SandboxKey": string,
<add> "Options": { ... }
<ide> }
<ide>
<ide> The `NetworkID` and `EndpointID` have meanings as above. The `SandboxKey` identifies the sandbox. `Options` is an arbitrary map as supplied to the proxy.
<ide>
<ide> The response must have the form
<ide>
<ide> {
<del> "InterfaceName": {
<del> SrcName: string,
<del> DstPrefix: string
<del> },
<del> "Gateway": string,
<del> "GatewayIPv6": string,
<del> "StaticRoutes": [{
<del> "Destination": string,
<del> "RouteType": int,
<del> "NextHop": string,
<del> }, ...]
<add> "InterfaceName": {
<add> SrcName: string,
<add> DstPrefix: string
<add> },
<add> "Gateway": string,
<add> "GatewayIPv6": string,
<add> "StaticRoutes": [{
<add> "Destination": string,
<add> "RouteType": int,
<add> "NextHop": string,
<add> }, ...]
<ide> }
<ide>
<ide> `Gateway` is optional and if supplied is an IP address as a string; e.g., `"192.168.0.1"`. `GatewayIPv6` is optional and if supplied is an IPv6 address as a string; e.g., `"fe80::7809:baff:fec6:7744"`.
<ide> Routes are either given a `RouteType` of `0` and a value for `NextHop`; or, a `R
<ide> If the proxy is asked to remove an endpoint from a sandbox, the remote process shall receive a POST to the URL `/NetworkDriver.Leave` of the form
<ide>
<ide> {
<del> "NetworkID": string,
<del> "EndpointID": string
<add> "NetworkID": string,
<add> "EndpointID": string
<ide> }
<ide>
<ide> where `NetworkID` and `EndpointID` have meanings as above. The success response is empty: | 1 |
PHP | PHP | build remaining methods on arraycontext | 669cd696c188c2aebf448c65f83408115659fa5e | <ide><path>src/View/Form/ArrayContext.php
<ide> public function val($field) {
<ide> * @return boolean
<ide> */
<ide> public function isRequired($field) {
<add> if (!is_array($this->_context['required'])) {
<add> return false;
<add> }
<add> $required = Hash::get($this->_context['required'], $field);
<add> return (bool)$required;
<ide> }
<ide>
<ide> /**
<ide> public function isRequired($field) {
<ide> * @see Cake\Database\Type
<ide> */
<ide> public function type($field) {
<del>
<add> if (!is_array($this->_context['schema'])) {
<add> return false;
<add> }
<add> $schema = Hash::get($this->_context['schema'], $field);
<add> return isset($schema['type']) ? $schema['type'] : null;
<ide> }
<ide>
<ide> /**
<ide> public function type($field) {
<ide> * @return array An array of data describing the additional attributes on a field.
<ide> */
<ide> public function attributes($field) {
<del>
<add> if (!is_array($this->_context['schema'])) {
<add> return [];
<add> }
<add> $schema = Hash::get($this->_context['schema'], $field);
<add> $whitelist = ['length' => null, 'precision' => null];
<add> return array_intersect_key($schema, $whitelist);
<ide> }
<ide>
<ide> }
<ide><path>tests/TestCase/View/Form/ArrayContextTest.php
<ide> public function testValMissing() {
<ide> $this->assertNull($context->val('Comments.field'));
<ide> }
<ide>
<add>/**
<add> * Test isRequired
<add> *
<add> * @return void
<add> */
<ide> public function testIsRequired() {
<del> $this->markTestIncomplete();
<add> $context = new ArrayContext($this->request, [
<add> 'required' => [
<add> 'Comments' => [
<add> 'required' => true,
<add> 'nope' => false
<add> ]
<add> ]
<add> ]);
<add> $this->assertTrue($context->isRequired('Comments.required'));
<add> $this->assertFalse($context->isRequired('Comments.nope'));
<add> $this->assertFalse($context->isRequired('Articles.id'));
<ide> }
<ide>
<add>/**
<add> * Test isRequired when the required key is omitted
<add> *
<add> * @return void
<add> */
<ide> public function testIsRequiredUndefined() {
<del> $this->markTestIncomplete();
<add> $context = new ArrayContext($this->request, []);
<add> $this->assertFalse($context->isRequired('Comments.field'));
<ide> }
<ide>
<del> public function testIsType() {
<del> $this->markTestIncomplete();
<add>/**
<add> * Test the type method.
<add> *
<add> * @return void
<add> */
<add> public function testType() {
<add> $context = new ArrayContext($this->request, [
<add> 'schema' => [
<add> 'Comments' => [
<add> 'id' => ['type' => 'integer'],
<add> 'comment' => ['length' => 255]
<add> ]
<add> ]
<add> ]);
<add> $this->assertNull($context->type('Comments.undefined'));
<add> $this->assertEquals('integer', $context->type('Comments.id'));
<add> $this->assertNull($context->type('Comments.comment'));
<ide> }
<ide>
<add>/**
<add> * Test the type method when the data is missing.
<add> *
<add> * @return void
<add> */
<ide> public function testIsTypeUndefined() {
<del> $this->markTestIncomplete();
<add> $context = new ArrayContext($this->request, []);
<add> $this->assertNull($context->type('Comments.undefined'));
<ide> }
<ide>
<add>/**
<add> * Test fetching attributes.
<add> *
<add> * @return void
<add> */
<ide> public function testAttributes() {
<del> $this->markTestIncomplete();
<add> $context = new ArrayContext($this->request, [
<add> 'schema' => [
<add> 'Comments' => [
<add> 'id' => ['type' => 'integer'],
<add> 'comment' => ['type' => 'string', 'length' => 255],
<add> 'decimal' => ['type' => 'decimal', 'precision' => 2, 'length' => 5],
<add> 'floaty' => ['type' => 'float', 'precision' => 2, 'length' => 5],
<add> ]
<add> ]
<add> ]);
<add> $this->assertEquals([], $context->attributes('Comments.id'));
<add> $this->assertEquals(['length' => 255], $context->attributes('Comments.comment'));
<add> $this->assertEquals(['precision' => 2, 'length' => 5], $context->attributes('Comments.decimal'));
<add> $this->assertEquals(['precision' => 2, 'length' => 5], $context->attributes('Comments.floaty'));
<ide> }
<ide>
<ide> } | 2 |
Text | Text | add note on force_authenticate + refresh_from_db | aecca9d8e83ed42cf6d4b04de84d82dd185e2aa7 | <ide><path>docs/api-guide/testing.md
<ide> For example, when forcibly authenticating using a token, you might do something
<ide>
<ide> ---
<ide>
<add>**Note**: `force_authenticate` directly sets `request.user` to the in-memory `user` instance. If you are re-using the same `user` instance across multiple tests that update the saved `user` state, you may need to call [`refresh_from_db()`][refresh_from_db_docs] between tests.
<add>
<add>---
<add>
<ide> **Note**: When using `APIRequestFactory`, the object that is returned is Django's standard `HttpRequest`, and not REST framework's `Request` object, which is only generated once the view is called.
<ide>
<ide> This means that setting attributes directly on the request object may not always have the effect you expect. For example, setting `.token` directly will have no effect, and setting `.user` directly will only work if session authentication is being used.
<ide> For example, to add support for using `format='html'` in test requests, you migh
<ide> [client]: https://docs.djangoproject.com/en/stable/topics/testing/tools/#the-test-client
<ide> [requestfactory]: https://docs.djangoproject.com/en/stable/topics/testing/advanced/#django.test.client.RequestFactory
<ide> [configuration]: #configuration
<add>[refresh_from_db_docs]: https://docs.djangoproject.com/en/1.11/ref/models/instances/#django.db.models.Model.refresh_from_db | 1 |
Python | Python | remove unneeded parentheses from python files | 3cd317e19ab3e533c12343d880d929c9925b4243 | <ide><path>tests/core/test_core.py
<ide> def test_illegal_args_forbidden(self):
<ide> illegal_argument_1234='hello?',
<ide> )
<ide> self.assertIn(
<del> ('Invalid arguments were passed to BashOperator (task_id: test_illegal_args).'),
<add> 'Invalid arguments were passed to BashOperator (task_id: test_illegal_args).',
<ide> str(ctx.exception),
<ide> )
<ide>
<ide><path>tests/utils/test_operator_helpers.py
<ide> def callable11(*, ds_nodash, **kwargs):
<ide> KWARGS,
<ide> (KWARGS,),
<ide> ),
<del> (callable6, (1,), KWARGS, ((1, "20200101"))),
<del> (callable7, (1,), KWARGS, ((1, KWARGS))),
<del> (callable8, (1, 2), KWARGS, ((1, (2,), KWARGS))),
<del> (callable9, (1, 2), KWARGS, (((1, 2), KWARGS))),
<del> (callable10, (1,), KWARGS, ((1, "20200101"))),
<add> (callable6, (1,), KWARGS, (1, "20200101")),
<add> (callable7, (1,), KWARGS, (1, KWARGS)),
<add> (callable8, (1, 2), KWARGS, (1, (2,), KWARGS)),
<add> (callable9, (1, 2), KWARGS, ((1, 2), KWARGS)),
<add> (callable10, (1,), KWARGS, (1, "20200101")),
<ide> (
<ide> callable11,
<ide> (), | 2 |
Text | Text | add v3.10.0-beta.3 to changelog | 9c485789e408dffbc6f1d94b0defdaffc4e168e0 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### v3.10.0-beta.3 (April 15, 2019)
<add>
<add>- [#17859](https://github.com/emberjs/ember.js/pull/17859) [BUGFIX] Fixes a regression in the legacy build
<add>- [#17891](https://github.com/emberjs/ember.js/pull/17891) [BUGFIX] Loosen "engines" restriction for Node versions
<add>- [#17900](https://github.com/emberjs/ember.js/pull/17900) [BUGFIX] Fix version for APP_CTRL_ROUTER_PROPS deprecation flag
<add>
<ide> ### v3.9.1 (April 09, 2019)
<ide>
<ide> - [#17870](https://github.com/emberjs/ember.js/pull/17870) / [#17871](https://github.com/emberjs/ember.js/pull/17871) [BUGFIX] Fix issue where `...attributes` may incorrectly overwrite attributes, depending on its position. | 1 |
Python | Python | break long lines + pep8 | 02ae0e3ea9fb3567c12e8d0c93ae8dbd4977623e | <ide><path>benchmarks/benchmarks/bench_app.py
<ide> def setup(self, update):
<ide> dy2 = (dy * dy)
<ide>
<ide> def num_update(u, dx2, dy2):
<del> u[1:(-1), 1:(-1)] = ((((u[2:, 1:(-1)] + u[:(-2), 1:(-1)]) * dy2) + ((u[1:(-1), 2:] + u[1:(-1), :(-2)]) * dx2)) / (2 * (dx2 + dy2)))
<add> u[1:(-1), 1:(-1)] = ((((u[2:, 1:(-1)] + u[:(-2), 1:(-1)]) * dy2) +
<add> ((u[1:(-1), 2:] + u[1:(-1), :(-2)]) * dx2))
<add> / (2 * (dx2 + dy2)))
<ide>
<ide> def num_inplace(u, dx2, dy2):
<ide> tmp = u[:(-2), 1:(-1)].copy()
<ide> def num_inplace(u, dx2, dy2):
<ide> np.add(tmp2, u[1:(-1), :(-2)], out=tmp2)
<ide> np.multiply(tmp2, dx2, out=tmp2)
<ide> np.add(tmp, tmp2, out=tmp)
<del> np.multiply(tmp, (1.0 / (2.0 * (dx2 + dy2))), out=u[1:(-1), 1:(-1)])
<add> np.multiply(tmp, (1.0 / (2.0 * (dx2 + dy2))),
<add> out=u[1:(-1), 1:(-1)])
<ide>
<ide> def laplace(N, Niter=100, func=num_update, args=()):
<ide> u = np.zeros([N, N], order='C')
<ide> def setup(self):
<ide> nfeat = 100
<ide> ntime = 200
<ide>
<del> self.arrays = [np.random.normal(size=(ntime, nfeat)) for i in xrange(nsubj)]
<add> self.arrays = [np.random.normal(size=(ntime, nfeat))
<add> for i in xrange(nsubj)]
<ide>
<ide> def maxes_of_dots(self, arrays):
<ide> """
<ide><path>benchmarks/benchmarks/bench_indexing.py
<ide> def setup(self, indexes, sel, op):
<ide> 'indexes_rand_': indexes_rand_}
<ide>
<ide> if sys.version_info[0] >= 3:
<del> code = "def run():\n for a in squares_.values(): a[%s]%s" % (sel, op)
<add> code = "def run():\n for a in squares_.values(): a[%s]%s"
<ide> else:
<del> code = "def run():\n for a in squares_.itervalues(): a[%s]%s" % (sel, op)
<add> code = "def run():\n for a in squares_.itervalues(): a[%s]%s"
<add> code = code % (sel, op)
<ide>
<ide> six.exec_(code, ns)
<ide> self.func = ns['run']
<ide><path>benchmarks/benchmarks/bench_linalg.py
<ide>
<ide> import numpy as np
<ide>
<add>
<ide> class Eindot(Benchmark):
<ide> def setup(self):
<ide> self.a = np.arange(60000.0).reshape(150, 400)
<ide><path>benchmarks/benchmarks/common.py
<ide>
<ide> # a set of interesting types to test
<ide> TYPES1 = [
<del> 'int16', 'float16',
<del> 'int32', 'float32',
<del> 'int64', 'float64', 'complex64',
<del> 'longfloat', 'complex128',
<del> 'complex256',
<del> ]
<add> 'int16', 'float16',
<add> 'int32', 'float32',
<add> 'int64', 'float64', 'complex64',
<add> 'longfloat', 'complex128',
<add> 'complex256',
<add>]
<ide>
<ide> # values which will be used to construct our sample data matrices
<ide> # replicate 10 times to speed up initial imports of this helper
<ide> # and generate some redundancy
<ide> values = [random.uniform(0, 100) for x in range(nx*ny/10)]*10
<ide>
<del>squares = {t: numpy.array(values, dtype=getattr(numpy, t)).reshape((nx, ny))
<add>squares = {t: numpy.array(values,
<add> dtype=getattr(numpy, t)).reshape((nx, ny))
<ide> for t in TYPES1}
<ide>
<ide> # adjust complex ones to have non-degenerated imagery part -- use
<ide> v += v.T*1j
<ide>
<ide> # smaller squares
<del>squares_ = {t: s[:nxs, :nys] for t, s in squares.iteritems()}
<add>squares_ = {t: s[:nxs, :nys] for t, s in squares.iteritems()}
<ide> # vectors
<del>vectors = {t: s[0] for t, s in squares.iteritems()}
<add>vectors = {t: s[0] for t, s in squares.iteritems()}
<ide>
<ide> indexes = range(nx)
<ide> # so we do not have all items
<ide><path>runtests.py
<ide> def main(argv):
<ide> gcov_reset_counters()
<ide>
<ide> if args.debug and args.bench:
<del> print("*** Benchmarks should not be run against debug version; remove -g flag ***")
<add> print("*** Benchmarks should not be run against debug "
<add> "version; remove -g flag ***")
<ide>
<ide> if not args.no_build:
<ide> site_dir = build_project(args)
<ide> def main(argv):
<ide>
<ide> # Check for uncommitted files
<ide> if commit_b == 'HEAD':
<del> r1 = subprocess.call(['git', 'diff-index', '--quiet', '--cached', 'HEAD'])
<add> r1 = subprocess.call(['git', 'diff-index', '--quiet',
<add> '--cached', 'HEAD'])
<ide> r2 = subprocess.call(['git', 'diff-files', '--quiet'])
<ide> if r1 != 0 or r2 != 0:
<ide> print("*"*80)
<del> print("WARNING: you have uncommitted changes --- these will NOT be benchmarked!")
<add> print("WARNING: you have uncommitted changes --- "
<add> "these will NOT be benchmarked!")
<ide> print("*"*80)
<ide>
<ide> # Fix commit ids (HEAD is local to current repo)
<del> p = subprocess.Popen(['git', 'rev-parse', commit_b], stdout=subprocess.PIPE)
<add> p = subprocess.Popen(['git', 'rev-parse', commit_b],
<add> stdout=subprocess.PIPE)
<ide> out, err = p.communicate()
<ide> commit_b = out.strip()
<ide>
<del> p = subprocess.Popen(['git', 'rev-parse', commit_a], stdout=subprocess.PIPE)
<add> p = subprocess.Popen(['git', 'rev-parse', commit_a],
<add> stdout=subprocess.PIPE)
<ide> out, err = p.communicate()
<ide> commit_a = out.strip()
<ide> | 5 |
PHP | PHP | get blade compiler from engine resolver | b1af5287d00d9cf72df20e189b9140e0bc23aaaa | <ide><path>src/Illuminate/Foundation/Console/ViewCacheCommand.php
<ide> public function handle()
<ide> */
<ide> protected function compileViews(Collection $views)
<ide> {
<del> $compiler = $this->laravel['blade.compiler'];
<add> $compiler = $this->laravel['view']->getEngineResolver()->resolve('blade')->getCompiler();
<ide>
<ide> $views->map(function (SplFileInfo $file) use ($compiler) {
<ide> $compiler->compile($file->getRealPath()); | 1 |
Python | Python | update flaubert with tf decorator | 277fc2cc782d8c5c28ec399b1ee2fc1c6aed7b6e | <ide><path>src/transformers/models/flaubert/modeling_tf_flaubert.py
<ide> TFPreTrainedModel,
<ide> TFSharedEmbeddings,
<ide> get_initializer,
<del> input_processing,
<ide> keras_serializable,
<add> unpack_inputs,
<ide> )
<ide> from ...tf_utils import shape_list
<ide> from ...utils import logging
<ide> def __init__(self, config, *inputs, **kwargs):
<ide> super().__init__(config, *inputs, **kwargs)
<ide> self.transformer = TFFlaubertMainLayer(config, name="transformer")
<ide>
<add> @unpack_inputs
<ide> @add_start_docstrings_to_model_forward(FLAUBERT_INPUTS_DOCSTRING)
<ide> @add_code_sample_docstrings(
<ide> processor_class=_TOKENIZER_FOR_DOC,
<ide> def call(
<ide> training: Optional[bool] = False,
<ide> **kwargs,
<ide> ) -> Union[Tuple, TFBaseModelOutput]:
<del> inputs = input_processing(
<del> func=self.call,
<del> config=self.config,
<add> outputs = self.transformer(
<ide> input_ids=input_ids,
<ide> attention_mask=attention_mask,
<ide> langs=langs,
<ide> def call(
<ide> output_hidden_states=output_hidden_states,
<ide> return_dict=return_dict,
<ide> training=training,
<del> kwargs_call=kwargs,
<del> )
<del> outputs = self.transformer(
<del> input_ids=inputs["input_ids"],
<del> attention_mask=inputs["attention_mask"],
<del> langs=inputs["langs"],
<del> token_type_ids=inputs["token_type_ids"],
<del> position_ids=inputs["position_ids"],
<del> lengths=inputs["lengths"],
<del> cache=inputs["cache"],
<del> head_mask=inputs["head_mask"],
<del> inputs_embeds=inputs["inputs_embeds"],
<del> output_attentions=inputs["output_attentions"],
<del> output_hidden_states=inputs["output_hidden_states"],
<del> return_dict=inputs["return_dict"],
<del> training=inputs["training"],
<ide> )
<ide>
<ide> return outputs
<ide> def set_input_embeddings(self, value):
<ide> self.embeddings.weight = value
<ide> self.embeddings.vocab_size = shape_list(value)[0]
<ide>
<add> @unpack_inputs
<ide> def call(
<ide> self,
<ide> input_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
<ide> def call(
<ide> **kwargs,
<ide> ) -> Union[Tuple, TFBaseModelOutput]:
<ide> # removed: src_enc=None, src_len=None
<del> inputs = input_processing(
<del> func=self.call,
<del> config=self.config,
<del> input_ids=input_ids,
<del> attention_mask=attention_mask,
<del> langs=langs,
<del> token_type_ids=token_type_ids,
<del> position_ids=position_ids,
<del> lengths=lengths,
<del> cache=cache,
<del> head_mask=head_mask,
<del> inputs_embeds=inputs_embeds,
<del> output_attentions=output_attentions,
<del> output_hidden_states=output_hidden_states,
<del> return_dict=return_dict,
<del> training=training,
<del> kwargs_call=kwargs,
<del> )
<ide>
<del> if inputs["input_ids"] is not None and inputs["inputs_embeds"] is not None:
<add> if input_ids is not None and inputs_embeds is not None:
<ide> raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
<del> elif inputs["input_ids"] is not None:
<del> bs, slen = shape_list(inputs["input_ids"])
<del> elif inputs["inputs_embeds"] is not None:
<del> bs, slen = shape_list(inputs["inputs_embeds"])[:2]
<add> elif input_ids is not None:
<add> bs, slen = shape_list(input_ids)
<add> elif inputs_embeds is not None:
<add> bs, slen = shape_list(inputs_embeds)[:2]
<ide> else:
<ide> raise ValueError("You have to specify either input_ids or inputs_embeds")
<ide>
<del> if inputs["lengths"] is None:
<del> if inputs["input_ids"] is not None:
<del> inputs["lengths"] = tf.reduce_sum(
<del> tf.cast(tf.not_equal(inputs["input_ids"], self.pad_index), dtype=inputs["input_ids"].dtype), axis=1
<add> if lengths is None:
<add> if input_ids is not None:
<add> lengths = tf.reduce_sum(
<add> tf.cast(tf.not_equal(input_ids, self.pad_index), dtype=input_ids.dtype), axis=1
<ide> )
<ide> else:
<del> inputs["lengths"] = tf.convert_to_tensor([slen] * bs)
<add> lengths = tf.convert_to_tensor([slen] * bs)
<ide> # mask = input_ids != self.pad_index
<ide>
<ide> # check inputs
<ide> # assert shape_list(lengths)[0] == bs
<ide> if tf.executing_eagerly():
<ide> tf.debugging.assert_equal(
<del> shape_list(inputs["lengths"])[0], bs
<del> ), f"Expected batch size {shape_list(inputs['lengths'])[0]} and received batch size {bs} mismatched"
<add> shape_list(lengths)[0], bs
<add> ), f"Expected batch size {shape_list(lengths)[0]} and received batch size {bs} mismatched"
<ide> # assert lengths.max().item() <= slen
<ide> # input_ids = input_ids.transpose(0, 1) # batch size as dimension 0
<ide> # assert (src_enc is None) == (src_len is None)
<ide> def call(
<ide> # assert src_enc.size(0) == bs
<ide>
<ide> # generate masks
<del> mask, attn_mask = get_masks(slen, inputs["lengths"], self.causal, padding_mask=inputs["attention_mask"])
<add> mask, attn_mask = get_masks(slen, lengths, self.causal, padding_mask=attention_mask)
<ide> # if self.is_decoder and src_enc is not None:
<ide> # src_mask = torch.arange(src_len.max(), dtype=torch.long, device=lengths.device) < src_len[:, None]
<ide>
<ide> # position_ids
<del> if inputs["position_ids"] is None:
<del> inputs["position_ids"] = tf.expand_dims(tf.range(slen), axis=0)
<del> inputs["position_ids"] = tf.tile(inputs["position_ids"], (bs, 1))
<add> if position_ids is None:
<add> position_ids = tf.expand_dims(tf.range(slen), axis=0)
<add> position_ids = tf.tile(position_ids, (bs, 1))
<ide>
<ide> if tf.executing_eagerly():
<ide> # assert shape_list(position_ids) == [bs, slen] # (slen, bs)
<ide> tf.debugging.assert_equal(
<del> shape_list(inputs["position_ids"]), [bs, slen]
<del> ), f"Position id shape {shape_list(inputs['position_ids'])} and input shape {[bs, slen]} mismatched"
<add> shape_list(position_ids), [bs, slen]
<add> ), f"Position id shape {shape_list(position_ids)} and input shape {[bs, slen]} mismatched"
<ide> # position_ids = position_ids.transpose(0, 1)
<ide>
<ide> # langs
<del> if inputs["langs"] is not None and tf.executing_eagerly():
<add> if langs is not None and tf.executing_eagerly():
<ide> # assert shape_list(langs) == [bs, slen] # (slen, bs)
<ide> tf.debugging.assert_equal(
<del> shape_list(inputs["langs"]), [bs, slen]
<del> ), f"Lang shape {shape_list(inputs['langs'])} and input shape {[bs, slen]} mismatched"
<add> shape_list(langs), [bs, slen]
<add> ), f"Lang shape {shape_list(langs)} and input shape {[bs, slen]} mismatched"
<ide> # langs = langs.transpose(0, 1)
<ide>
<ide> # Prepare head mask if needed
<ide> # 1.0 in head_mask indicate we keep the head
<ide> # attention_probs has shape bsz x n_heads x N x N
<ide> # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
<ide> # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x qlen x klen]
<del> if inputs["head_mask"] is not None:
<add> if head_mask is not None:
<ide> raise NotImplementedError
<ide> else:
<del> inputs["head_mask"] = [None] * self.n_layers
<add> head_mask = [None] * self.n_layers
<ide>
<ide> # do not recompute cached elements
<del> if inputs["cache"] is not None and inputs["input_ids"] is not None:
<del> _slen = slen - inputs["cache"]["slen"]
<del> inputs["input_ids"] = inputs["input_ids"][:, -_slen:]
<del> inputs["position_ids"] = inputs["position_ids"][:, -_slen:]
<del> if inputs["langs"] is not None:
<del> inputs["langs"] = inputs["langs"][:, -_slen:]
<add> if cache is not None and input_ids is not None:
<add> _slen = slen - cache["slen"]
<add> input_ids = input_ids[:, -_slen:]
<add> position_ids = position_ids[:, -_slen:]
<add> if langs is not None:
<add> langs = langs[:, -_slen:]
<ide> mask = mask[:, -_slen:]
<ide> attn_mask = attn_mask[:, -_slen:]
<ide>
<ide> # embeddings
<del> if inputs["inputs_embeds"] is None:
<del> inputs["inputs_embeds"] = self.embeddings(inputs["input_ids"])
<add> if inputs_embeds is None:
<add> inputs_embeds = self.embeddings(input_ids)
<ide>
<del> tensor = inputs["inputs_embeds"] + tf.gather(self.position_embeddings, inputs["position_ids"])
<add> tensor = inputs_embeds + tf.gather(self.position_embeddings, position_ids)
<ide>
<del> if inputs["langs"] is not None and self.use_lang_emb:
<del> tensor = tensor + tf.gather(self.lang_embeddings, inputs["langs"])
<del> if inputs["token_type_ids"] is not None:
<del> tensor = tensor + self.embeddings(inputs["token_type_ids"])
<add> if langs is not None and self.use_lang_emb:
<add> tensor = tensor + tf.gather(self.lang_embeddings, langs)
<add> if token_type_ids is not None:
<add> tensor = tensor + self.embeddings(token_type_ids)
<ide>
<ide> tensor = self.layer_norm_emb(tensor)
<del> tensor = self.dropout(tensor, training=inputs["training"])
<add> tensor = self.dropout(tensor, training=training)
<ide> mask = tf.cast(mask, dtype=tensor.dtype)
<ide> tensor = tensor * tf.expand_dims(mask, axis=-1)
<ide>
<ide> # hidden_states and attentions cannot be None in graph mode.
<del> hidden_states = () if inputs["output_hidden_states"] else None
<del> attentions = () if inputs["output_attentions"] else None
<add> hidden_states = () if output_hidden_states else None
<add> attentions = () if output_attentions else None
<ide>
<ide> # transformer layers
<ide> for i in range(self.n_layers):
<ide> # LayerDrop
<ide> dropout_probability = random.uniform(0, 1)
<ide>
<del> if inputs["training"] and (dropout_probability < self.layerdrop):
<add> if training and (dropout_probability < self.layerdrop):
<ide> continue
<ide>
<del> if inputs["output_hidden_states"]:
<add> if output_hidden_states:
<ide> hidden_states = hidden_states + (tensor,)
<ide>
<ide> # self attention
<ide> def call(
<ide> tensor,
<ide> attn_mask,
<ide> None,
<del> inputs["cache"],
<del> inputs["head_mask"][i],
<del> inputs["output_attentions"],
<del> training=inputs["training"],
<add> cache,
<add> head_mask[i],
<add> output_attentions,
<add> training=training,
<ide> )
<ide> attn = attn_outputs[0]
<ide>
<del> if inputs["output_attentions"]:
<add> if output_attentions:
<ide> attentions = attentions + (attn_outputs[1],)
<ide>
<del> attn = self.dropout(attn, training=inputs["training"])
<add> attn = self.dropout(attn, training=training)
<ide> tensor = tensor + attn
<ide> tensor = self.layer_norm1[i](tensor)
<ide> else:
<ide> def call(
<ide> tensor_normalized,
<ide> attn_mask,
<ide> None,
<del> inputs["cache"],
<del> inputs["head_mask"][i],
<del> inputs["output_attentions"],
<del> training=inputs["training"],
<add> cache,
<add> head_mask[i],
<add> output_attentions,
<add> training=training,
<ide> )
<ide> attn = attn_outputs[0]
<ide>
<del> if inputs["output_attentions"]:
<add> if output_attentions:
<ide> attentions = attentions + (attn_outputs[1],)
<ide>
<del> attn = self.dropout(attn, training=inputs["training"])
<add> attn = self.dropout(attn, training=training)
<ide> tensor = tensor + attn
<ide>
<ide> # encoder attention (for decoder only)
<ide> def call(
<ide> tensor = tensor * tf.expand_dims(mask, axis=-1)
<ide>
<ide> # Add last hidden state
<del> if inputs["output_hidden_states"]:
<add> if output_hidden_states:
<ide> hidden_states = hidden_states + (tensor,)
<ide>
<ide> # update cache length
<del> if inputs["cache"] is not None:
<del> inputs["cache"]["slen"] += tensor.size(1)
<add> if cache is not None:
<add> cache["slen"] += tensor.size(1)
<ide>
<ide> # move back sequence length to dimension 0
<ide> # tensor = tensor.transpose(0, 1)
<ide>
<del> if not inputs["return_dict"]:
<add> if not return_dict:
<ide> return tuple(v for v in [tensor, hidden_states, attentions] if v is not None)
<ide>
<ide> return TFBaseModelOutput(last_hidden_state=tensor, hidden_states=hidden_states, attentions=attentions)
<ide> def prepare_inputs_for_generation(self, inputs, **kwargs):
<ide> langs = None
<ide> return {"input_ids": inputs, "langs": langs}
<ide>
<add> @unpack_inputs
<ide> @add_start_docstrings_to_model_forward(FLAUBERT_INPUTS_DOCSTRING)
<ide> @add_code_sample_docstrings(
<ide> processor_class=_TOKENIZER_FOR_DOC,
<ide> def call(
<ide> training: Optional[bool] = False,
<ide> **kwargs,
<ide> ) -> Union[Tuple, TFFlaubertWithLMHeadModelOutput]:
<del> inputs = input_processing(
<del> func=self.call,
<del> config=self.config,
<add>
<add> transformer_outputs = self.transformer(
<ide> input_ids=input_ids,
<ide> attention_mask=attention_mask,
<ide> langs=langs,
<ide> def call(
<ide> output_hidden_states=output_hidden_states,
<ide> return_dict=return_dict,
<ide> training=training,
<del> kwargs_call=kwargs,
<del> )
<del> transformer_outputs = self.transformer(
<del> input_ids=inputs["input_ids"],
<del> attention_mask=inputs["attention_mask"],
<del> langs=inputs["langs"],
<del> token_type_ids=inputs["token_type_ids"],
<del> position_ids=inputs["position_ids"],
<del> lengths=inputs["lengths"],
<del> cache=inputs["cache"],
<del> head_mask=inputs["head_mask"],
<del> inputs_embeds=inputs["inputs_embeds"],
<del> output_attentions=inputs["output_attentions"],
<del> output_hidden_states=inputs["output_hidden_states"],
<del> return_dict=inputs["return_dict"],
<del> training=inputs["training"],
<ide> )
<ide> output = transformer_outputs[0]
<ide> outputs = self.pred_layer(output)
<ide>
<del> if not inputs["return_dict"]:
<add> if not return_dict:
<ide> return (outputs,) + transformer_outputs[1:]
<ide>
<ide> return TFFlaubertWithLMHeadModelOutput( | 1 |
Python | Python | run kubernetespodoperator tests on any executor | 68f13f0c54fc9d0575670498ce732b801a4d3b7a | <ide><path>kubernetes_tests/test_kubernetes_pod_operator.py
<ide> from airflow.providers.cncf.kubernetes.utils.xcom_sidecar import PodDefaults
<ide> from airflow.utils import timezone
<ide> from airflow.version import version as airflow_version
<del>from kubernetes_tests.test_base import EXECUTOR
<ide>
<ide>
<ide> def create_context(task):
<ide> def get_kubeconfig_path():
<ide> return kubeconfig_path if kubeconfig_path else os.path.expanduser('~/.kube/config')
<ide>
<ide>
<del>@pytest.mark.skipif(EXECUTOR != 'KubernetesExecutor', reason="Only runs on KubernetesExecutor")
<ide> class TestKubernetesPodOperatorSystem(unittest.TestCase):
<ide> def get_current_task_name(self):
<ide> # reverse test name to make pod name unique (it has limited length)
<ide><path>kubernetes_tests/test_kubernetes_pod_operator_backcompat.py
<ide> from airflow.utils import timezone
<ide> from airflow.utils.state import State
<ide> from airflow.version import version as airflow_version
<del>from kubernetes_tests.test_base import EXECUTOR
<ide>
<ide> # noinspection DuplicatedCode
<ide>
<ide> def create_context(task):
<ide>
<ide>
<ide> # noinspection DuplicatedCode,PyUnusedLocal
<del>@pytest.mark.skipif(EXECUTOR != 'KubernetesExecutor', reason="Only runs on KubernetesExecutor")
<ide> class TestKubernetesPodOperatorSystem(unittest.TestCase):
<ide> def get_current_task_name(self):
<ide> # reverse test name to make pod name unique (it has limited length) | 2 |
Javascript | Javascript | add winreg to snapshot ignore list | 233e5190071ea5db37c2da6c9a7ce219b5857c42 | <ide><path>script/lib/generate-startup-snapshot.js
<ide> module.exports = function (packagedAppPath) {
<ide> relativePath === path.join('..', 'node_modules', 'tar', 'tar.js') ||
<ide> relativePath === path.join('..', 'node_modules', 'temp', 'lib', 'temp.js') ||
<ide> relativePath === path.join('..', 'node_modules', 'tmp', 'lib', 'tmp.js') ||
<del> relativePath === path.join('..', 'node_modules', 'tree-sitter', 'index.js')
<add> relativePath === path.join('..', 'node_modules', 'tree-sitter', 'index.js') ||
<add> relativePath === path.join('..', 'node_modules', 'winreg', 'lib', 'registry.js')
<ide> )
<ide> }
<ide> }).then((snapshotScript) => { | 1 |
Text | Text | add security message to readme | 9e2cc4fcd9c28f80877d930cb5cc6076428e8ef8 | <ide><path>README.md
<ide> applications and databases.
<ide>
<ide> 
<ide>
<add>## Security Disclosure
<add>
<add>Security is very important to us. If you have any issue regarding security, please disclose the information responsibly by sending an email to security@docker.com and not by creating a github issue.
<add>
<ide> ## Better than VMs
<ide>
<ide> A common method for distributing applications and sandboxing their | 1 |
Javascript | Javascript | use font.prototype.binddom to insert fonts on page | 803139127ad799d5d0854d726cb538eb17ad3ce1 | <ide><path>worker/client.js
<ide> function FontWorker() {
<ide> throw "Unkown action from worker: " + data.action;
<ide> }
<ide> }.bind(this);
<add>
<add> this.$handleFontLoadedCallback = this.handleFontLoadedCallback.bind(this);
<ide> }
<ide>
<ide> FontWorker.prototype = {
<add> handleFontLoadedCallback: function() {
<add> // Decrease the number of fonts wainting to be loaded.
<add> this.fontsWaiting--;
<add> // If all fonts are available now, then call all the callbacks.
<add> if (this.fontsWaiting == 0) {
<add> var callbacks = this.fontsWaitingCallbacks;
<add> for (var i = 0; i < callbacks.length; i++) {
<add> callbacks[i]();
<add> }
<add> this.fontsWaitingCallbacks.length = 0;
<add> }
<add> },
<add>
<ide> actionHandler: {
<ide> "log": function(data) {
<ide> console.log.apply(console, data);
<ide> FontWorker.prototype = {
<ide> Fonts[name].properties = {
<ide> encoding: data[name].encoding
<ide> }
<del> var base64 = window.btoa(data[name].str);
<del>
<del> // Add the @font-face rule to the document
<del> var url = "url(data:font/opentype;base64," + base64 + ");";
<del> var rule = "@font-face { font-family:'" + name + "';src:" + url + "}";
<del> var styleSheet = document.styleSheets[0];
<del> styleSheet.insertRule(rule, styleSheet.length);
<del>
<del> // Just adding the font-face to the DOM doesn't make it load. It
<del> // seems it's loaded once Gecko notices it's used. Therefore,
<del> // add a div on the page using the loaded font.
<del> var div = document.createElement("div");
<del> var style = 'font-family:"' + name +
<del> '";position: absolute;top:-99999;left:-99999;z-index:-99999';
<del> div.setAttribute("style", style);
<del> document.body.appendChild(div);
<del> this.fontsWaiting --;
<del> }
<del>
<del> if (this.fontsWaiting == 0) {
<del> console.timeEnd("ensureFonts");
<add>
<add> // Call `Font.prototype.bindDOM` to make the font get loaded on the page.
<add> Font.prototype.bindDOM.call(
<add> Fonts[name],
<add> data[name].str,
<add> // IsLoadedCallback.
<add> this.$handleFontLoadedCallback
<add> );
<ide> }
<del>
<del> // This timeout is necessary right now to make sure the fonts are really
<del> // loaded at the point the callbacks are called.
<del> setTimeout(function() {
<del> // If all fonts are available now, then call all the callbacks.
<del> if (this.fontsWaiting == 0) {
<del> var callbacks = this.fontsWaitingCallbacks;
<del> for (var i = 0; i < callbacks.length; i++) {
<del> callbacks[i]();
<del> }
<del> this.fontsWaitingCallbacks.length = 0;
<del> }
<del> }.bind(this), 100);
<ide> }
<ide> },
<ide>
<ide> FontWorker.prototype = {
<ide> // Store only the data on Fonts that is needed later on, such that we
<ide> // hold track on as lease memory as possible.
<ide> Fonts[font.name] = {
<add> name: font.name,
<add> mimetype: font.mimetype,
<ide> // This is set later on the worker replay. For some fonts, the encoding
<ide> // is calculated during the conversion process happening on the worker
<ide> // and therefore is not available right now. | 1 |
Text | Text | translate tip-16 to korean | 452f2f282f85ced053650cfac9997183a8a17ecf | <ide><path>docs/tips/16-references-to-components.ko-KR.md
<add>---
<add>id: references-to-components-ko-KR
<add>title: 컴포넌트 참조
<add>layout: tips
<add>permalink: references-to-components-ko-KR.html
<add>prev: expose-component-functions-ko-KR.html
<add>next: children-undefined-ko-KR.html
<add>---
<add>
<add>애플리케이션의 일부에서만 React 컴포넌트를 사용중이거나 코드를 React로 전환하고 있다면, 컴포넌트의 참조를 보존할 필요가 있을 것입니다. `React.render`는 마운트된 컴포넌트의 참조를 반환합니다:
<add>
<add>```js
<add>var myComponent = React.render(<MyComponent />, myContainer);
<add>```
<add>
<add>명심하세요, JSX는 컴포넌트 인스턴스를 반환하지 않습니다! 단지 마운트된 컴포넌트가 어떻게 보일지 알려주는 간단한 서술인 **ReactElement**일 뿐입니다.
<add>
<add>```js
<add>var myComponentElement = <MyComponent />; // ReactElement일 뿐입니다.
<add>
<add>// 코드들이 여기 위치하게 됩니다...
<add>
<add>var myComponentInstance = React.render(myComponentElement, myContainer);
<add>```
<add>
<add>> 주의:
<add>>
<add>> 이는 최상위 레벨에서만 사용되어야 합니다. 컴포넌트의 내부에서는 `prop`과 `state`가 자식컴포넌트와의 통신을 제어하며, [refs](http://facebook.github.io/react/docs/more-about-refs-ko-KR.html)를 통해서만 컴포넌트를 참조할 수 있습니다. | 1 |
Python | Python | assert filename match | da4c9cee06e6a25470619fa20c1454cc78407d24 | <ide><path>spacy/en/download.py
<ide> def install_data(url, path, filename):
<ide> except FileExistsError:
<ide> pass
<ide>
<del> filename = download_file(url, os.path.join(path, filename))
<del> t = tarfile.open(filename)
<add> download_path = os.path.join(path, filename)
<add> tmp = download_file(url, download_path)
<add> assert tmp == download_path
<add> t = tarfile.open(download_path)
<ide> t.extractall(path)
<ide>
<ide> | 1 |
Python | Python | remove tree view | 631722992e76827ecee61797edd3ab218e28c94a | <ide><path>glances/main.py
<ide> def init_args(self):
<ide> if not WINDOWS:
<ide> parser.add_argument('--hide-kernel-threads', action='store_true', default=False,
<ide> dest='no_kernel_threads', help='hide kernel threads in process list (not available on Windows)')
<del> # if LINUX:
<del> # parser.add_argument('--tree', action='store_true', default=False,
<del> # dest='process_tree', help='display processes as a tree (Linux only)')
<ide> parser.add_argument('-b', '--byte', action='store_true', default=False,
<ide> dest='byte', help='display network rate in byte per second')
<ide> parser.add_argument('--diskio-show-ramfs', action='store_true', default=False,
<ide><path>glances/outputs/glances_curses.py
<ide> def display(self, stats, cs_status=None):
<ide> self.get_stats_display_height(__stat_display["docker"])))
<ide>
<ide> try:
<del> if self.args.enable_process_extended and not self.args.process_tree:
<add> if self.args.enable_process_extended:
<ide> max_processes_displayed -= 4
<ide> except AttributeError:
<ide> pass
<ide><path>glances/plugins/glances_processcount.py
<ide> def msg_curse(self, args=None, max_width=None):
<ide> else:
<ide> msg = 'sorted by {}'.format(glances_processes.sort_key)
<ide> ret.append(self.curse_add_line(msg))
<del> ret[-1]["msg"] += ", %s view" % ("tree" if glances_processes.is_tree_enabled() else "flat")
<del> # if args.disable_irix:
<del> # ret[-1]["msg"] += " - IRIX off"
<ide>
<ide> # Return the message with decoration
<ide> return ret
<ide><path>glances/plugins/glances_processlist.py
<ide> def update(self):
<ide> # Update stats using the standard system lib
<ide> # Note: Update is done in the processcount plugin
<ide> # Just return the processes list
<del> if glances_processes.is_tree_enabled():
<del> self.stats = glances_processes.gettree()
<del> else:
<del> self.stats = glances_processes.getlist()
<add> self.stats = glances_processes.getlist()
<ide>
<ide> # Get the max values (dict)
<ide> # Use Deep copy to avoid change between update and display
<ide> def update(self):
<ide>
<ide> return self.stats
<ide>
<del> def get_process_tree_curses_data(self, node, args, first_level=True, max_node_count=None):
<del> """Get curses data to display for a process tree."""
<del> ret = []
<del> node_count = 0
<del> if not node.is_root and ((max_node_count is None) or (max_node_count > 0)):
<del> node_data = self.get_process_curses_data(node.stats, False, args)
<del> node_count += 1
<del> ret.extend(node_data)
<del> for child in node.iter_children():
<del> # stop if we have enough nodes to display
<del> if max_node_count is not None and node_count >= max_node_count:
<del> break
<del>
<del> if max_node_count is None:
<del> children_max_node_count = None
<del> else:
<del> children_max_node_count = max_node_count - node_count
<del> child_data = self.get_process_tree_curses_data(child,
<del> args,
<del> first_level=node.is_root,
<del> max_node_count=children_max_node_count)
<del> if max_node_count is None:
<del> node_count += len(child)
<del> else:
<del> node_count += min(children_max_node_count, len(child))
<del>
<del> if not node.is_root:
<del> child_data = self.add_tree_decoration(child_data, child is node.children[-1], first_level)
<del> ret.extend(child_data)
<del> return ret
<del>
<del> def add_tree_decoration(self, child_data, is_last_child, first_level):
<del> """Add tree curses decoration and indentation to a subtree."""
<del> # find process command indices in messages
<del> pos = []
<del> for i, m in enumerate(child_data):
<del> if m.get("_tree_decoration", False):
<del> del m["_tree_decoration"]
<del> pos.append(i)
<del>
<del> # add new curses items for tree decoration
<del> new_child_data = []
<del> new_pos = []
<del> for i, m in enumerate(child_data):
<del> if i in pos:
<del> new_pos.append(len(new_child_data))
<del> new_child_data.append(self.curse_add_line(""))
<del> new_child_data[-1]["_tree_decoration"] = True
<del> new_child_data.append(m)
<del> child_data = new_child_data
<del> pos = new_pos
<del>
<del> if pos:
<del> # draw node prefix
<del> if is_last_child:
<del> prefix = "└─"
<del> else:
<del> prefix = "├─"
<del> child_data[pos[0]]["msg"] = prefix
<del>
<del> # add indentation
<del> for i in pos:
<del> spacing = 2
<del> if first_level:
<del> spacing = 1
<del> elif is_last_child and (i is not pos[0]):
<del> # compensate indentation for missing '│' char
<del> spacing = 3
<del> child_data[i]["msg"] = "%s%s" % (" " * spacing, child_data[i]["msg"])
<del>
<del> if not is_last_child:
<del> # add '│' tree decoration
<del> for i in pos[1:]:
<del> old_str = child_data[i]["msg"]
<del> if first_level:
<del> child_data[i]["msg"] = " │" + old_str[2:]
<del> else:
<del> child_data[i]["msg"] = old_str[:2] + "│" + old_str[3:]
<del>
<del> return child_data
<del>
<ide> def get_nice_alert(self, value):
<ide> """Return the alert relative to the Nice configuration list"""
<ide> value = str(value)
<ide> def get_process_curses_data(self, p, first, args):
<ide> if os.path.isdir(path) and not args.process_short_name:
<ide> msg = ' {}'.format(path) + os.sep
<ide> ret.append(self.curse_add_line(msg, splittable=True))
<del> if glances_processes.is_tree_enabled():
<del> # mark position to add tree decoration
<del> ret[-1]["_tree_decoration"] = True
<ide> ret.append(self.curse_add_line(cmd, decoration='PROCESS', splittable=True))
<ide> else:
<ide> msg = ' {}'.format(cmd)
<ide> ret.append(self.curse_add_line(msg, decoration='PROCESS', splittable=True))
<del> if glances_processes.is_tree_enabled():
<del> # mark position to add tree decoration
<del> ret[-1]["_tree_decoration"] = True
<ide> if arguments:
<ide> msg = ' {}'.format(arguments)
<ide> ret.append(self.curse_add_line(msg, splittable=True))
<ide> def msg_curse(self, args=None, max_width=None):
<ide> self.__msg_curse_header(ret, process_sort_key, args)
<ide>
<ide> # Process list
<del> if glances_processes.is_tree_enabled():
<del> ret.extend(self.get_process_tree_curses_data(
<del> self.__sort_stats(process_sort_key), args, first_level=True,
<del> max_node_count=glances_processes.max_processes))
<del> else:
<del> # Loop over processes (sorted by the sort key previously compute)
<del> first = True
<del> for p in self.__sort_stats(process_sort_key):
<del> ret.extend(self.get_process_curses_data(p, first, args))
<del> # End of extended stats
<del> first = False
<del> if glances_processes.process_filter is not None:
<del> if args.reset_minmax_tag:
<del> args.reset_minmax_tag = not args.reset_minmax_tag
<del> self.__mmm_reset()
<del> self.__msg_curse_sum(ret, args=args)
<del> self.__msg_curse_sum(ret, mmm='min', args=args)
<del> self.__msg_curse_sum(ret, mmm='max', args=args)
<add> # Loop over processes (sorted by the sort key previously compute)
<add> first = True
<add> for p in self.__sort_stats(process_sort_key):
<add> ret.extend(self.get_process_curses_data(p, first, args))
<add> # End of extended stats
<add> first = False
<add> if glances_processes.process_filter is not None:
<add> if args.reset_minmax_tag:
<add> args.reset_minmax_tag = not args.reset_minmax_tag
<add> self.__mmm_reset()
<add> self.__msg_curse_sum(ret, args=args)
<add> self.__msg_curse_sum(ret, mmm='min', args=args)
<add> self.__msg_curse_sum(ret, mmm='max', args=args)
<ide>
<ide> # Return the message with decoration
<ide> return ret
<ide> def __mmm_key(self, key, indice):
<ide> def __sort_stats(self, sortedby=None):
<ide> """Return the stats (dict) sorted by (sortedby)."""
<ide> return sort_stats(self.stats, sortedby,
<del> tree=glances_processes.is_tree_enabled(),
<ide> reverse=glances_processes.sort_reverse)
<ide>
<ide> def __max_pid_size(self):
<ide><path>glances/processes.py
<ide> def __init__(self, cache_timeout=60):
<ide> # value = [ read_bytes_old, write_bytes_old ]
<ide> self.io_old = {}
<ide>
<del> # Wether or not to enable process tree
<del> self._enable_tree = False
<del> self.process_tree = None
<del>
<ide> # Init stats
<ide> self.auto_sort = True
<ide> self._sort_key = 'cpu_percent'
<ide> def disable_kernel_threads(self):
<ide> """Ignore kernel threads in process list."""
<ide> self.no_kernel_threads = True
<ide>
<del> def enable_tree(self):
<del> """Enable process tree."""
<del> self._enable_tree = True
<del>
<del> def is_tree_enabled(self):
<del> """Return True if process tree is enabled, False instead."""
<del> return self._enable_tree
<del>
<ide> @property
<ide> def sort_reverse(self):
<ide> """Return True to sort processes in reverse 'key' order, False instead."""
<ide> def getlist(self, sortedby=None):
<ide> """Get the processlist."""
<ide> return self.processlist
<ide>
<del> def gettree(self):
<del> """Get the process tree."""
<del> return self.process_tree
<del>
<ide> @property
<ide> def sort_key(self):
<ide> """Get the current sort key."""
<ide> def sort_key(self, key):
<ide>
<ide> # TODO: move this global function (also used in glances_processlist
<ide> # and logs) inside the GlancesProcesses class
<del>def sort_stats(stats, sortedby=None, tree=False, reverse=True):
<add>def sort_stats(stats, sortedby=None, reverse=True):
<ide> """Return the stats (dict) sorted by (sortedby)
<ide> Reverse the sort if reverse is True."""
<ide> if sortedby is None:
<ide> # No need to sort...
<ide> return stats
<ide>
<del> if sortedby == 'io_counters' and not tree:
<add> if sortedby == 'io_counters':
<ide> # Specific case for io_counters
<ide> # Sum of io_r + io_w
<ide> try:
<ide> def sort_stats(stats, sortedby=None, tree=False, reverse=True):
<ide> reverse=reverse)
<ide> else:
<ide> # Others sorts
<del> if tree:
<del> stats.set_sorting(sortedby, reverse)
<del> else:
<del> try:
<del> stats.sort(key=operator.itemgetter(sortedby),
<del> reverse=reverse)
<del> except (KeyError, TypeError):
<del> stats.sort(key=operator.itemgetter('name'),
<del> reverse=False)
<add> try:
<add> stats.sort(key=operator.itemgetter(sortedby),
<add> reverse=reverse)
<add> except (KeyError, TypeError):
<add> stats.sort(key=operator.itemgetter('name'),
<add> reverse=False)
<ide>
<ide> return stats
<ide>
<ide><path>glances/standalone.py
<ide> def __init__(self, config=None, args=None):
<ide> # Ignore kernel threads in process list
<ide> glances_processes.disable_kernel_threads()
<ide>
<del> # try:
<del> # if args.process_tree:
<del> # # Enable process tree view
<del> # glances_processes.enable_tree()
<del> # except AttributeError:
<del> # pass
<del>
<ide> # Initial system informations update
<ide> self.stats.update()
<ide> | 6 |
Javascript | Javascript | preserve dom node when updating empty component | db589a717510d1a2d235d934a0eec4b5609b4e0b | <ide><path>src/renderers/shared/reconciler/ReactChildReconciler.js
<ide> var ReactChildReconciler = {
<ide> var prevChild = prevChildren && prevChildren[name];
<ide> var prevElement = prevChild && prevChild._currentElement;
<ide> var nextElement = nextChildren[name];
<del> if (shouldUpdateReactComponent(prevElement, nextElement)) {
<add> if (prevChild != null &&
<add> shouldUpdateReactComponent(prevElement, nextElement)) {
<ide> ReactReconciler.receiveComponent(
<ide> prevChild, nextElement, transaction, context
<ide> );
<ide><path>src/renderers/shared/reconciler/__tests__/ReactEmptyComponent-test.js
<ide> describe('ReactEmptyComponent', function() {
<ide> ReactTestUtils.renderIntoDocument(<Parent />);
<ide> }).not.toThrow();
<ide> });
<add>
<add> it('preserves the dom node during updates', function() {
<add> var Empty = React.createClass({
<add> render: function() {
<add> return null;
<add> },
<add> });
<add>
<add> var container = document.createElement('div');
<add>
<add> ReactDOM.render(<Empty />, container);
<add> var noscript1 = container.firstChild;
<add> expect(noscript1.tagName).toBe('NOSCRIPT');
<add>
<add> // This update shouldn't create a DOM node
<add> ReactDOM.render(<Empty />, container);
<add> var noscript2 = container.firstChild;
<add> expect(noscript2.tagName).toBe('NOSCRIPT');
<add>
<add> expect(noscript1).toBe(noscript2);
<add> });
<ide> });
<ide><path>src/renderers/shared/reconciler/shouldUpdateReactComponent.js
<ide> * @protected
<ide> */
<ide> function shouldUpdateReactComponent(prevElement, nextElement) {
<del> if (prevElement != null && nextElement != null) {
<del> var prevType = typeof prevElement;
<del> var nextType = typeof nextElement;
<del> if (prevType === 'string' || prevType === 'number') {
<del> return (nextType === 'string' || nextType === 'number');
<del> } else {
<del> return (
<del> nextType === 'object' &&
<del> prevElement.type === nextElement.type &&
<del> prevElement.key === nextElement.key
<del> );
<del> }
<add> var prevEmpty = prevElement === null || prevElement === false;
<add> var nextEmpty = nextElement === null || nextElement === false;
<add> if (prevEmpty || nextEmpty) {
<add> return prevEmpty === nextEmpty;
<add> }
<add>
<add> var prevType = typeof prevElement;
<add> var nextType = typeof nextElement;
<add> if (prevType === 'string' || prevType === 'number') {
<add> return (nextType === 'string' || nextType === 'number');
<add> } else {
<add> return (
<add> nextType === 'object' &&
<add> prevElement.type === nextElement.type &&
<add> prevElement.key === nextElement.key
<add> );
<ide> }
<ide> return false;
<ide> } | 3 |
PHP | PHP | apply fixes from styleci | efdab6e774de2b73ec985ae3c965481864bb9c3e | <ide><path>src/Illuminate/View/ComponentAttributeBag.php
<ide> class ComponentAttributeBag implements ArrayAccess, Htmlable, IteratorAggregate
<ide> {
<ide> use Macroable;
<del>
<add>
<ide> /**
<ide> * The raw array of attributes.
<ide> * | 1 |
PHP | PHP | fix github provider | cf33cae228a199ae304aada1584c00da7ecad86a | <ide><path>laravel/cli/tasks/bundle/providers/github.php
<ide> public function install($bundle)
<ide> // If the installation target directory doesn't exist, we will create
<ide> // it recursively so that we can properly add the Git submodule for
<ide> // the bundle when we install.
<del> if ( ! is_dir(path('bundle').$path))
<add> if ( ! is_dir(dirname(path('bundle').$path)))
<ide> {
<del> mkdir(path('bundle').$path, 0777, true);
<add> mkdir(dirname(path('bundle').$path), 0777, true);
<ide> }
<ide>
<ide> // We need to just extract the basename of the bundle path when | 1 |
Text | Text | fix broken link in errors.md | ddc60c785877c62dd0aae211c52ad9ac55253712 | <ide><path>doc/api/errors.md
<ide> The native call from `process.cpuUsage` could not be processed.
<ide> [`new URLSearchParams(iterable)`]: url.md#url_new_urlsearchparams_iterable
<ide> [`package.json`]: packages.md#packages_node_js_package_json_field_definitions
<ide> [`postMessage()`]: worker_threads.md#worker_threads_port_postmessage_value_transferlist
<del>[`process.on('exit')`]: process.md#Event:-`'exit'`
<add>[`process.on('exit')`]: process.md#process_event_exit
<ide> [`process.send()`]: process.md#process_process_send_message_sendhandle_options_callback
<ide> [`process.setUncaughtExceptionCaptureCallback()`]: process.md#process_process_setuncaughtexceptioncapturecallback_fn
<ide> [`readable._read()`]: stream.md#stream_readable_read_size_1 | 1 |
Python | Python | fix zerodivisionerror and epoch counting | 4c62c6021aa3341eff4c0bb87fea72fea22eb701 | <ide><path>src/transformers/trainer.py
<ide> def train(self, model_path: Optional[str] = None, trial: Union["optuna.Trial", D
<ide>
<ide> # Data loader and number of training steps
<ide> train_dataloader = self.get_train_dataloader()
<add> num_update_steps_per_epoch = len(train_dataloader) // self.args.gradient_accumulation_steps
<add> num_update_steps_per_epoch = max(num_update_steps_per_epoch, 1)
<ide> if self.args.max_steps > 0:
<ide> t_total = self.args.max_steps
<del> num_train_epochs = (
<del> self.args.max_steps // (len(train_dataloader) // self.args.gradient_accumulation_steps) + 1
<add> num_train_epochs = self.args.max_steps // num_update_steps_per_epoch + int(
<add> self.args.max_steps % num_update_steps_per_epoch > 0
<ide> )
<ide> else:
<del> t_total = int(len(train_dataloader) // self.args.gradient_accumulation_steps * self.args.num_train_epochs)
<add> t_total = int(num_update_steps_per_epoch * self.args.num_train_epochs)
<ide> num_train_epochs = self.args.num_train_epochs
<ide> self.args.max_steps = t_total
<ide>
<ide> def train(self, model_path: Optional[str] = None, trial: Union["optuna.Trial", D
<ide> self.global_step = int(model_path.split("-")[-1].split(os.path.sep)[0])
<ide> self.total_flos = getattr(model.config, "total_flos", 0)
<ide>
<del> epochs_trained = self.global_step // (len(train_dataloader) // self.args.gradient_accumulation_steps)
<del> steps_trained_in_current_epoch = self.global_step % (
<del> len(train_dataloader) // self.args.gradient_accumulation_steps
<del> )
<add> epochs_trained = self.global_step // num_update_steps_per_epoch
<add> steps_trained_in_current_epoch = self.global_step % (num_update_steps_per_epoch)
<ide>
<ide> logger.info(" Continuing training from checkpoint, will skip to saved global_step")
<ide> logger.info(" Continuing training from epoch %d", epochs_trained)
<ide><path>tests/test_trainer.py
<ide> def test_trainer_iterable_dataset(self):
<ide> trainer = Trainer(model=model, args=training_args, train_dataset=train_dataset)
<ide> loader = trainer.get_train_dataloader()
<ide> self.assertIsInstance(loader, torch.utils.data.DataLoader)
<add>
<add> def test_num_train_epochs_in_training(self):
<add> # len(train_dl) < gradient_accumulation_steps shouldn't give ``ZeroDivisionError`` when ``max_steps`` is given.
<add> # It should give 1 update step for each epoch.
<add> trainer = get_regression_trainer(
<add> max_steps=3, train_len=64, per_device_train_batch_size=16, gradient_accumulation_steps=5
<add> )
<add> train_output = trainer.train()
<add> self.assertEqual(train_output.global_step, 3)
<add>
<add> # Even ``max_steps`` is not specified, we still expect 1 update step for each epoch if
<add> # len(train_dl) < gradient_accumulation_steps.
<add> trainer = get_regression_trainer(train_len=64, per_device_train_batch_size=16, gradient_accumulation_steps=5)
<add> train_output = trainer.train()
<add> self.assertEqual(train_output.global_step, int(self.n_epochs)) | 2 |
PHP | PHP | add throwwith to the http client response | c131f471af6e3a45593adbe0ed3bbea074f85500 | <ide><path>src/Illuminate/Http/Client/Response.php
<ide> public function toPsrResponse()
<ide> * @throws \Illuminate\Http\Client\RequestException
<ide> */
<ide> public function throw()
<add> {
<add> return $this->throwWith(function () {
<add> //
<add> });
<add> }
<add>
<add> /**
<add> * Execute the callback and throw an exception if a server of client error occurred.
<add> *
<add> * @param \Closure $callback
<add> * @return $this
<add> *
<add> * @throws \Illuminate\Http\Client\RequestException
<add> */
<add> public function throwWith($callback)
<ide> {
<ide> if ($this->serverError() || $this->clientError()) {
<add> $callback($this);
<add>
<ide> throw new RequestException($this);
<ide> }
<ide>
<ide><path>tests/Http/HttpClientTest.php
<ide> public function testRequestExceptionEmptyBody()
<ide> throw new RequestException(new Response($response));
<ide> }
<ide>
<add> public function testThrowWithCallsClosureOnError()
<add> {
<add> $status = 0;
<add> $client = $this->factory->fake([
<add> 'laravel.com' => $this->factory::response('', 401),
<add> ]);
<add> $response = $client->get('laravel.com');
<add>
<add> try {
<add> $response->throwWith(function ($response) use (&$status) {
<add> $status = $response->status();
<add> });
<add> } catch (RequestException $e) {
<add> //
<add> }
<add>
<add> $this->assertSame(401, $status);
<add> $this->assertSame(401, $response->status());
<add> }
<add>
<add> public function testThrowWithDoesntCallClosureOnSuccess()
<add> {
<add> $status = 0;
<add> $client = $this->factory->fake([
<add> 'laravel.com' => $this->factory::response('', 201),
<add> ]);
<add> $response = $client->get('laravel.com');
<add>
<add> $response->throwWith(function ($response) use (&$status) {
<add> $status = $response->status();
<add> });
<add>
<add> $this->assertSame(0, $status);
<add> $this->assertSame(201, $response->status());
<add> }
<add>
<ide> public function testSinkToFile()
<ide> {
<ide> $this->factory->fakeSequence()->push('abc123'); | 2 |
Python | Python | fix xfail marker | 188ccd575072704ea870fac60b5cde4c29d822bd | <ide><path>spacy/tests/regression/test_issue3356.py
<ide> if compat.is_python2:
<ide> # If we have this test in Python 3, pytest chokes, as it can't print the
<ide> # string above in the xpass message.
<del> @pytest.xfail
<add> @pytest.mark.xfail
<ide> def test_issue3356():
<ide> pattern = re.compile(prefix_search.decode("utf8"))
<ide> assert not pattern.search(u"hello") | 1 |
Java | Java | fix inappropriate eager init | 834ebc44f8ddef719603f6f1ed70ef83bb337f2a | <ide><path>spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java
<ide> public String[] getBeanNamesForType(ResolvableType type) {
<ide> public String[] getBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) {
<ide> Class<?> resolved = type.resolve();
<ide> if (resolved != null && !type.hasGenerics()) {
<del> return getBeanNamesForType(resolved, includeNonSingletons, includeNonSingletons);
<add> return getBeanNamesForType(resolved, includeNonSingletons, allowEagerInit);
<ide> }
<ide> else {
<del> return doGetBeanNamesForType(type, includeNonSingletons, includeNonSingletons);
<add> return doGetBeanNamesForType(type, includeNonSingletons, allowEagerInit);
<ide> }
<ide> }
<ide> | 1 |
Javascript | Javascript | add static injection for feature flags | dee604dbe287b34918073110c425078583f8fd9a | <ide><path>scripts/rollup/build.js
<ide> function getPlugins(
<ide> hasteName,
<ide> moduleType,
<ide> manglePropertiesOnProd,
<del> modulesToStub
<add> modulesToStub,
<add> featureFlags
<ide> ) {
<ide> const plugins = [
<ide> babel(updateBabelConfig(babelOpts, bundleType)),
<ide> function getPlugins(
<ide>
<ide> const replaceModules = Modules.getDefaultReplaceModules(
<ide> bundleType,
<del> modulesToStub
<add> modulesToStub,
<add> featureFlags
<ide> );
<ide>
<ide> // We have to do this check because Rollup breaks on empty object.
<ide> function createBundle(bundle, bundleType) {
<ide> bundle.hasteName,
<ide> bundle.moduleType,
<ide> bundle.manglePropertiesOnProd,
<del> bundle.modulesToStub
<add> bundle.modulesToStub,
<add> bundle.featureFlags
<ide> ),
<ide> })
<ide> .then(result =>
<ide><path>scripts/rollup/modules.js
<ide> function ignoreFBModules() {
<ide> return [
<ide> // At FB, we don't know them statically:
<ide> 'ReactFeatureFlags',
<del> 'ReactDOMFeatureFlags',
<ide> // In FB bundles, we preserve an inline require to ReactCurrentOwner.
<ide> // See the explanation in FB version of ReactCurrentOwner in www:
<ide> 'ReactCurrentOwner',
<ide> function getAliases(paths, bundleType, moduleType, extractErrors) {
<ide> );
<ide> }
<ide>
<del>function getDefaultReplaceModules(bundleType, bundleModulesToStub) {
<add>function replaceFeatureFlags(featureFlags) {
<add> if (!featureFlags) {
<add> return {};
<add> }
<add> return {
<add> "'ReactFeatureFlags'": `'${resolve(featureFlags)}'`,
<add> };
<add>}
<add>
<add>function getDefaultReplaceModules(
<add> bundleType,
<add> bundleModulesToStub,
<add> featureFlags
<add>) {
<ide> return Object.assign(
<ide> {},
<ide> replaceFbjsModuleAliases(bundleType),
<ide> replaceDevOnlyStubbedModules(bundleType),
<ide> replaceLegacyModuleAliases(bundleType),
<del> replaceBundleStubModules(bundleModulesToStub)
<add> replaceBundleStubModules(bundleModulesToStub),
<add> replaceFeatureFlags(featureFlags)
<ide> );
<ide> }
<ide>
<ide><path>src/renderers/dom/fiber/ReactDOMFiberEntry.js
<ide> var DOMNamespaces = require('DOMNamespaces');
<ide> var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment');
<ide> var ReactBrowserEventEmitter = require('ReactBrowserEventEmitter');
<ide> var ReactControlledComponent = require('ReactControlledComponent');
<add>var ReactFeatureFlags = require('ReactFeatureFlags');
<ide> var ReactDOMComponentTree = require('ReactDOMComponentTree');
<del>var ReactDOMFeatureFlags = require('ReactDOMFeatureFlags');
<ide> var ReactDOMFiberComponent = require('ReactDOMFiberComponent');
<ide> var ReactDOMFrameScheduling = require('ReactDOMFrameScheduling');
<ide> var ReactGenericBatching = require('ReactGenericBatching');
<ide> var DOMRenderer = ReactFiberReconciler({
<ide>
<ide> scheduleDeferredCallback: ReactDOMFrameScheduling.rIC,
<ide>
<del> useSyncScheduling: !ReactDOMFeatureFlags.fiberAsyncScheduling,
<add> useSyncScheduling: !ReactFeatureFlags.enableAsyncSchedulingByDefaultInReactDOM,
<ide> });
<ide>
<ide> ReactGenericBatching.injection.injectFiberBatchedUpdates(
<ide><path>src/renderers/dom/shared/ReactDOMFeatureFlags.js
<del>/**
<del> * Copyright (c) 2013-present, Facebook, Inc.
<del> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<del> *
<del> * @providesModule ReactDOMFeatureFlags
<del> */
<del>
<del>'use strict';
<del>
<del>var ReactDOMFeatureFlags = {
<del> fiberAsyncScheduling: false,
<del>};
<del>
<del>module.exports = ReactDOMFeatureFlags;
<ide><path>src/renderers/shared/utils/ReactFeatureFlags.js
<ide>
<ide> 'use strict';
<ide>
<del>var ReactFeatureFlags = {
<add>export type FeatureFlags = {|
<add> enableAsyncSubtreeAPI: boolean,
<add> enableAsyncSchedulingByDefaultInReactDOM: boolean,
<add>|};
<add>
<add>var ReactFeatureFlags: FeatureFlags = {
<ide> enableAsyncSubtreeAPI: true,
<add> enableAsyncSchedulingByDefaultInReactDOM: false,
<ide> };
<ide>
<add>if (__DEV__) {
<add> if (Object.freeze) {
<add> Object.freeze(ReactFeatureFlags);
<add> }
<add>}
<add>
<ide> module.exports = ReactFeatureFlags; | 5 |
Mixed | Javascript | support custom dispatchers | 09f4190d0d7c5d2f6616abf3f1c98be43cdc0bec | <ide><path>README.md
<ide> export function decrement() {
<ide>
<ide> // Can also be async if you return a function
<ide> export function incrementAsync() {
<del> return perform => {
<add> return dispatch => {
<ide> setTimeout(() => {
<del> // Yay! Can invoke sync or async actions with `perform`
<del> perform(increment());
<add> // Yay! Can invoke sync or async actions with `dispatch`
<add> dispatch(increment());
<ide> }, 1000);
<ide> };
<ide> }
<ide>
<ide>
<ide> // Could also read state of a store in the callback form
<ide> export function incrementIfOdd() {
<del> return (perform, { counter }) => {
<add> return (dispatch, { counter }) => {
<ide> if (counter % 2 === 0) {
<ide> return;
<ide> }
<ide>
<del> perform(increment());
<add> dispatch(increment());
<ide> };
<ide> }
<ide> ```
<ide> export default class Counter {
<ide>
<ide> ```js
<ide> // The smart component may observe stores using `<Connector />`,
<del>// and bind actions to the dispatcher with `bindActions`.
<add>// and bind actions to the dispatcher with `bindActionCreators`.
<ide>
<ide> import React from 'react';
<del>import { Connector, bindActions } from 'redux';
<add>import { Connector, bindActionCreators } from 'redux';
<ide> import Counter from '../components/Counter';
<ide> import * as CounterActions from '../actions/CounterActions';
<ide>
<ide> export default class CounterApp {
<ide> render() {
<ide> return (
<ide> <Connector select={select}>
<del> {({ counter, dispatcher }) =>
<add> {({ counter, dispatch }) =>
<ide> /* Yes this is child as a function. */
<ide> <Counter counter={counter}
<del> {...bindActions(CounterActions, dispatcher)} />
<add> {...bindActionCreators(CounterActions, dispatch)} />
<ide> }
<ide> </Connector>
<ide> );
<ide> The `@connect` decorator lets you create smart components less verbosely:
<ide>
<ide> ```js
<ide> import React from 'react';
<del>import { connect, bindActions } from 'redux';
<add>import { connect, bindActionCreators } from 'redux';
<ide> import Counter from '../components/Counter';
<ide> import * as CounterActions from '../actions/CounterActions';
<ide>
<ide> import * as CounterActions from '../actions/CounterActions';
<ide> }))
<ide> export default class CounterApp {
<ide> render() {
<del> const { counter, dispatcher } = this.props;
<add> const { counter, dispatch } = this.props;
<ide> return (
<ide> <Counter counter={counter}
<del> {...bindActions(CounterActions, dispatcher)} />
<add> {...bindActionCreators(CounterActions, dispatch)} />
<ide> );
<ide> }
<ide> }
<ide> ```
<ide>
<del>#### The root component
<add>#### Initializing Redux
<ide>
<del>Decorate your top-level component with `@provider(dispatcher)` (or `<Provider dispatcher={dispatcher}>` inside) to bind it to a Redux dispatcher instance.
<del>
<del>Redux dispatcher accepts a single Store as an argument. Usually Flux apps have many Stores, so Redux provides a `composeStore` method that turns an object with Store functions as values (such as what you'd get from `import * as stores`) into a Store that [composes](https://gist.github.com/gaearon/d77ca812015c0356654f) them.
<del>
<del>Think of `composeStores` as a “higher-order” Store because it creates a Store from several Stores. (You don't have to use it! You can just pass your own top-level Store function if that's what you prefer.)
<add>The simplest way to initialize a Redux instance is to give it an object whose values are your Store functions, and whose keys are their names. You may `import *` from the file with all your Store definitions to obtain such an object:
<ide>
<ide> ```js
<del>import React from 'react';
<del>import { createDispatcher, Provider, composeStores } from 'redux';
<del>import CounterApp from './CounterApp';
<del>import TodoApp from './TodoApp';
<add>import { createRedux, Provider } from 'redux';
<ide> import * as stores from '../stores/index';
<ide>
<del>const dispatcher = createDispatcher(composeStores(stores));
<add>const redux = createRedux(stores);
<add>```
<add>
<add>Then pass `redux` as a prop to `<Provider>` component in the root component of your app, and you're all set:
<ide>
<add>```js
<ide> export default class App {
<ide> render() {
<ide> return (
<del> <Provider dispatcher={dispatcher}>
<add> <Provider redux={redux}>
<ide> {() =>
<del> /* Yep, function as a child. */
<del> <div>
<del> <CounterApp />
<del> <TodoApp />
<del> </div>
<add> <CounterApp />
<ide> }
<ide> </Provider>
<ide> );
<ide> }
<ide> }
<ide> ```
<ide>
<add>#### Running the same code on client and server
<add>
<add>The `redux` instance returned by `createRedux` also has the `dispatch(action)`, `subscribe()` and `getState()` methods that you may call outside the React components.
<add>
<add>You may optionally specify the initial state as the second argument to `createRedux`. This is useful for hydrating the state you received from running Redux on the server:
<add>
<add>```js
<add>// server
<add>const redux = createRedux(stores);
<add>redux.dispatch(MyActionCreators.doSomething()); // fire action creators to fill the state
<add>const state = redux.getState(); // somehow pass this state to the client
<add>
<add>// client
<add>const initialState = window.STATE_FROM_SERVER;
<add>const redux = createRedux(stores, initialState);
<add>```
<add>
<add>#### Additional customization
<add>
<add>There is also a longer way to do the same thing, if you need additional customization.
<add>
<add>This:
<add>
<add>```js
<add>import { createRedux } from 'redux';
<add>import * as stores from '../stores/index';
<add>
<add>const redux = createRedux(stores);
<add>```
<add>
<add>is in fact a shortcut for this:
<add>
<add>```js
<add>import { createRedux, createDispatcher, composeStores } from 'redux';
<add>import * as stores from '../stores/index';
<add>
<add>// Compose all your Stores into a single Store function with `composeStores`:
<add>const store = composeStores(stores);
<add>
<add>// Create a Dispatcher function for your composite Store:
<add>const dispatcher = createDispatcher(store);
<add>
<add>// Create a Redux instance using the dispatcher function:
<add>const redux = createRedux(dispatcher);
<add>```
<add>
<add>Why would you want to write it longer? Maybe you're an advanced user and want to provide a custom Dispatcher function, or maybe you have a different idea of how to compose your Stores (or you're satisfied with a single Store). Redux lets you do all of this.
<add>
<add>When in doubt, use the shorter option!
<add>
<ide> ## FAQ
<ide>
<ide> ### How does hot reloading work?
<ide><path>examples/actions/CounterActions.js
<ide> export function increment() {
<ide> }
<ide>
<ide> export function incrementIfOdd() {
<del> return (perform, { counter }) => {
<add> return (dispatch, { counter }) => {
<ide> if (counter % 2 === 0) {
<ide> return;
<ide> }
<ide>
<del> perform(increment());
<add> dispatch(increment());
<ide> };
<ide> }
<ide>
<ide> export function incrementAsync() {
<del> return perform => {
<add> return dispatch => {
<ide> setTimeout(() => {
<del> perform(increment());
<add> dispatch(increment());
<ide> }, 1000);
<ide> };
<ide> }
<ide><path>examples/containers/App.js
<ide> import React from 'react';
<del>import { createDispatcher, Provider, composeStores } from 'redux';
<ide> import CounterApp from './CounterApp';
<ide> import TodoApp from './TodoApp';
<add>import { createRedux, Provider } from 'redux';
<ide> import * as stores from '../stores/index';
<ide>
<del>const dispatcher = createDispatcher(composeStores(stores));
<add>const redux = createRedux(stores);
<ide>
<ide> export default class App {
<ide> render() {
<ide> return (
<del> <Provider dispatcher={dispatcher}>
<add> <Provider redux={redux}>
<ide> {() =>
<ide> <div>
<ide> <CounterApp />
<ide><path>examples/containers/CounterApp.js
<ide> import React from 'react';
<del>import { connect, bindActions } from 'redux';
<add>import { connect, bindActionCreators } from 'redux';
<ide> import Counter from '../components/Counter';
<ide> import * as CounterActions from '../actions/CounterActions';
<ide>
<ide> import * as CounterActions from '../actions/CounterActions';
<ide> }))
<ide> export default class CounterApp {
<ide> render() {
<del> const { counter, dispatcher } = this.props;
<add> const { counter, dispatch } = this.props;
<ide> return (
<ide> <Counter counter={counter}
<del> {...bindActions(CounterActions, dispatcher)} />
<add> {...bindActionCreators(CounterActions, dispatch)} />
<ide> );
<ide> }
<ide> }
<ide><path>examples/containers/TodoApp.js
<ide> import React from 'react';
<del>import { bindActions, Connector } from 'redux';
<add>import { bindActionCreators, Connector } from 'redux';
<ide> import AddTodo from '../components/AddTodo';
<ide> import TodoList from '../components/TodoList';
<ide> import * as TodoActions from '../actions/TodoActions';
<ide> export default class TodoApp {
<ide> );
<ide> }
<ide>
<del> renderChild({ todos, dispatcher }) {
<del> const actions = bindActions(TodoActions, dispatcher);
<add> renderChild({ todos, dispatch }) {
<add> const actions = bindActionCreators(TodoActions, dispatch);
<ide> return (
<ide> <div>
<ide> <AddTodo {...actions} />
<ide><path>src/Dispatcher.js
<del>function dispatch(store, atom, action) {
<del> return store(atom, action);
<del>}
<del>
<del>export default class Dispatcher {
<del> constructor(store) {
<del> this.perform = this.perform.bind(this);
<del> this.store = store;
<del> this.initialize();
<del> }
<del>
<del> initialize({ atom, subscriptions = [] } = {}) {
<del> this.atom = atom;
<del> this.subscriptions = subscriptions;
<del> this.dispatch({});
<del> }
<del>
<del> dispose() {
<del> const { atom, subscriptions } = this;
<del> delete this.atom;
<del> this.subscriptions = [];
<del> return { atom, subscriptions };
<del> }
<del>
<del> dispatch(action) {
<del> const nextAtom = dispatch(this.store, this.atom, action);
<del> this.setAtom(nextAtom);
<del> }
<del>
<del> perform(action) {
<del> return typeof action === 'function'
<del> ? action(this.perform, this.atom)
<del> : this.dispatch(action);
<del> }
<del>
<del> getAtom() {
<del> return this.atom;
<del> }
<del>
<del> setAtom(atom) {
<del> this.atom = atom;
<del> this.emitChange();
<del> }
<del>
<del> subscribe(listener) {
<del> this.subscriptions.push(listener);
<del> listener(this.atom);
<del>
<del> return () => {
<del> const index = this.subscriptions.indexOf(listener);
<del> this.subscriptions.splice(index, 1);
<del> };
<del> }
<del>
<del> emitChange() {
<del> const { atom, subscriptions } = this;
<del> subscriptions.forEach(listener => listener(atom));
<del> }
<del>}
<ide><path>src/Redux.js
<add>import createDispatcher from './createDispatcher';
<add>import composeStores from './utils/composeStores';
<add>
<add>export default class Redux {
<add> constructor(dispatcher, initialState) {
<add> if (typeof dispatcher === 'object') {
<add> // A shortcut notation to use the default dispatcher
<add> dispatcher = createDispatcher(composeStores(dispatcher));
<add> }
<add>
<add> this.state = initialState;
<add> this.listeners = [];
<add> this.replaceDispatcher(dispatcher);
<add> }
<add>
<add> getDispatcher() {
<add> return this.dispatcher;
<add> }
<add>
<add> replaceDispatcher(nextDispatcher) {
<add> this.dispatcher = nextDispatcher;
<add> this.dispatchFn = nextDispatcher(this.state, ::this.setState);
<add> }
<add>
<add> dispatch(action) {
<add> return this.dispatchFn(action);
<add> }
<add>
<add> getState() {
<add> return this.state;
<add> }
<add>
<add> setState(nextState) {
<add> this.state = nextState;
<add> this.listeners.forEach(listener => listener());
<add> }
<add>
<add> subscribe(listener) {
<add> this.listeners.push(listener);
<add>
<add> return () => {
<add> const index = this.listeners.indexOf(listener);
<add> this.listeners.splice(index, 1);
<add> };
<add> }
<add>}
<ide><path>src/components/Connector.js
<ide> export default class Connector extends Component {
<ide>
<ide> this.handleChange = this.handleChange.bind(this);
<ide> this.unsubscribe = context.redux.subscribe(this.handleChange);
<add> this.handleChange();
<ide> }
<ide>
<ide> componentWillReceiveProps(nextProps) {
<ide> if (nextProps.select !== this.props.select) {
<ide> // Force the state slice recalculation
<del> const atom = this.context.redux.getAtom();
<del> this.handleChange(atom);
<add> this.handleChange();
<ide> }
<ide> }
<ide>
<ide> componentWillUnmount() {
<ide> this.unsubscribe();
<ide> }
<ide>
<del> handleChange(atom) {
<del> const slice = this.props.select(atom);
<add> handleChange() {
<add> const state = this.context.redux.getState();
<add> const slice = this.props.select(state);
<add>
<ide> if (this.state) {
<ide> this.setState({ slice });
<ide> } else {
<ide> export default class Connector extends Component {
<ide> const { redux } = this.context;
<ide>
<ide> return children({
<del> dispatcher: redux,
<add> dispatch: ::redux.dispatch,
<ide> ...slice
<ide> });
<ide> }
<ide><path>src/components/Provider.js
<del>import { PropTypes } from 'react';
<add>import { Component, PropTypes } from 'react';
<ide>
<del>const dispatcherShape = PropTypes.shape({
<add>const reduxShape = PropTypes.shape({
<ide> subscribe: PropTypes.func.isRequired,
<del> perform: PropTypes.func.isRequired,
<del> getAtom: PropTypes.func.isRequired
<add> dispatch: PropTypes.func.isRequired,
<add> getState: PropTypes.func.isRequired
<ide> });
<ide>
<del>export default class Provider {
<add>export default class Provider extends Component {
<ide> static propTypes = {
<del> dispatcher: dispatcherShape.isRequired,
<add> redux: reduxShape.isRequired,
<ide> children: PropTypes.func.isRequired
<ide> };
<ide>
<ide> static childContextTypes = {
<del> redux: dispatcherShape.isRequired
<add> redux: reduxShape.isRequired
<ide> };
<ide>
<ide> getChildContext() {
<del> return { redux: this };
<add> return { redux: this.state.redux };
<ide> }
<ide>
<del> constructor() {
<del> this.dispatch = this.dispatch.bind(this);
<add> constructor(props, context) {
<add> super(props, context);
<add> this.state = { redux: props.redux };
<ide> }
<ide>
<ide> componentWillReceiveProps(nextProps) {
<del> nextProps.dispatcher.initialize(
<del> this.props.dispatcher.dispose()
<del> );
<del> }
<del>
<del> subscribe(listener) {
<del> return this.props.dispatcher.subscribe(listener);
<del> }
<del>
<del> dispatch(action) {
<del> return this.props.dispatcher.dispatch(action);
<del> }
<del>
<del> perform(actionCreator, ...args) {
<del> return this.props.dispatcher.perform(actionCreator, ...args);
<del> }
<del>
<del> getAtom() {
<del> return this.props.dispatcher.getAtom();
<add> const nextDispatcher = nextProps.redux.getDispatcher();
<add> this.state.redux.replaceDispatcher(nextDispatcher);
<ide> }
<ide>
<ide> render() {
<ide><path>src/components/provide.js
<ide> import React from 'react';
<ide> import Provider from './Provider';
<ide> import getDisplayName from '../utils/getDisplayName';
<ide>
<del>export default function provide(store) {
<add>export default function provide(redux) {
<ide> return DecoratedComponent => class ProviderDecorator {
<ide> static displayName = `Provider(${getDisplayName(DecoratedComponent)})`;
<ide>
<ide> render() {
<ide> return (
<del> <Provider store={store}>
<add> <Provider redux={redux}>
<ide> {props => <DecoratedComponent {...this.props} {...props} />}
<ide> </Provider>
<ide> );
<ide><path>src/createDispatcher.js
<del>import Dispatcher from './Dispatcher';
<add>export default function createDispatcher(store) {
<add> return function dispatcher(initialState, setState) {
<add> let state = store(initialState, {});
<add> setState(state);
<ide>
<del>export default function createDispatcher(...args) {
<del> const dispatcher = new Dispatcher(...args);
<add> function dispatchSync(action) {
<add> state = store(state, action);
<add> setState(state);
<add> return action;
<add> }
<ide>
<del> return {
<del> subscribe: ::dispatcher.subscribe,
<del> perform: ::dispatcher.perform,
<del> getAtom: ::dispatcher.getAtom,
<del> setAtom: ::dispatcher.setAtom,
<del> initialize: ::dispatcher.initialize,
<del> dispose: ::dispatcher.dispose
<add> function dispatch(action) {
<add> return typeof action === 'function' ?
<add> action(dispatch, state) :
<add> dispatchSync(action);
<add> }
<add>
<add> return dispatch;
<ide> };
<ide> }
<ide><path>src/createRedux.js
<add>import Redux from './Redux';
<add>
<add>export default function createRedux(...args) {
<add> const redux = new Redux(...args);
<add>
<add> return {
<add> subscribe: ::redux.subscribe,
<add> dispatch: ::redux.dispatch,
<add> getState: ::redux.getState,
<add> getDispatcher: ::redux.getDispatcher,
<add> replaceDispatcher: ::redux.replaceDispatcher
<add> };
<add>}
<ide><path>src/index.js
<ide> // Core
<add>export createRedux from './createRedux';
<ide> export createDispatcher from './createDispatcher';
<ide>
<ide> // Wrapper components
<ide> export connect from './components/connect';
<ide>
<ide> // Utilities
<ide> export composeStores from './utils/composeStores';
<del>export bindActions from './utils/bindActions';
<add>export bindActionCreators from './utils/bindActionCreators';
<ide><path>src/utils/bindActionCreators.js
<add>import mapValues from 'lodash/object/mapValues';
<add>
<add>export default function bindActionCreators(actionCreators, dispatch) {
<add> return mapValues(actionCreators, actionCreator =>
<add> (...args) => dispatch(actionCreator(...args))
<add> );
<add>}
<ide><path>src/utils/bindActions.js
<del>import mapValues from 'lodash/object/mapValues';
<del>
<del>export default function bindActions(actionCreators, dispatcher) {
<del> return mapValues(actionCreators, actionCreator =>
<del> (...args) => dispatcher.perform(actionCreator(...args))
<del> );
<del>} | 15 |
Javascript | Javascript | remove enqueuecallback from updater api | f4c0c9997362730c2b5182d6a7db19e5e4f9fee5 | <ide><path>src/isomorphic/modern/class/ReactNoopUpdateQueue.js
<ide> var ReactNoopUpdateQueue = {
<ide> return false;
<ide> },
<ide>
<del> /**
<del> * Enqueue a callback that will be executed after all the pending updates
<del> * have processed.
<del> *
<del> * @param {ReactClass} publicInstance The instance to use as `this` context.
<del> * @param {?function} callback Called after state is updated.
<del> * @internal
<del> */
<del> enqueueCallback: function(publicInstance, callback) { },
<del>
<ide> /**
<ide> * Forces an update. This should only be invoked when it is known with
<ide> * certainty that we are **not** in a DOM transaction.
<ide> var ReactNoopUpdateQueue = {
<ide> * `componentWillUpdate` and `componentDidUpdate`.
<ide> *
<ide> * @param {ReactClass} publicInstance The instance that should rerender.
<add> * @param {?function} callback Called after component is updated.
<add> * @param {?string} Name of the calling function in the public API.
<ide> * @internal
<ide> */
<del> enqueueForceUpdate: function(publicInstance) {
<add> enqueueForceUpdate: function(publicInstance, callback, callerName) {
<ide> warnNoop(publicInstance, 'forceUpdate');
<ide> },
<ide>
<ide> var ReactNoopUpdateQueue = {
<ide> *
<ide> * @param {ReactClass} publicInstance The instance that should rerender.
<ide> * @param {object} completeState Next state.
<add> * @param {?function} callback Called after component is updated.
<add> * @param {?string} Name of the calling function in the public API.
<ide> * @internal
<ide> */
<del> enqueueReplaceState: function(publicInstance, completeState) {
<add> enqueueReplaceState: function(publicInstance, completeState, callback, callerName) {
<ide> warnNoop(publicInstance, 'replaceState');
<ide> },
<ide>
<ide> var ReactNoopUpdateQueue = {
<ide> *
<ide> * @param {ReactClass} publicInstance The instance that should rerender.
<ide> * @param {object} partialState Next partial state to be merged with state.
<add> * @param {?function} callback Called after component is updated.
<add> * @param {?string} Name of the calling function in the public API.
<ide> * @internal
<ide> */
<del> enqueueSetState: function(publicInstance, partialState) {
<add> enqueueSetState: function(publicInstance, partialState, callback, callerName) {
<ide> warnNoop(publicInstance, 'setState');
<ide> },
<ide> };
<ide><path>src/renderers/dom/stack/server/ReactServerUpdateQueue.js
<ide> class ReactServerUpdateQueue {
<ide> return false;
<ide> }
<ide>
<del> /**
<del> * Enqueue a callback that will be executed after all the pending updates
<del> * have processed.
<del> *
<del> * @param {ReactClass} publicInstance The instance to use as `this` context.
<del> * @param {?function} callback Called after state is updated.
<del> * @internal
<del> */
<del> enqueueCallback(publicInstance: ReactComponent<any, any, any>, callback?: Function, callerName?: string) {
<del> if (this.transaction.isInTransaction()) {
<del> ReactUpdateQueue.enqueueCallback(publicInstance, callback, callerName);
<del> }
<del> }
<del>
<ide> /**
<ide> * Forces an update. This should only be invoked when it is known with
<ide> * certainty that we are **not** in a DOM transaction.
<ide> class ReactServerUpdateQueue {
<ide> * `componentWillUpdate` and `componentDidUpdate`.
<ide> *
<ide> * @param {ReactClass} publicInstance The instance that should rerender.
<add> * @param {?function} callback Called after component is updated.
<add> * @param {?string} Name of the calling function in the public API.
<ide> * @internal
<ide> */
<del> enqueueForceUpdate(publicInstance: ReactComponent<any, any, any>) {
<add> enqueueForceUpdate(publicInstance: ReactComponent<any, any, any>, callback?: Function, callerName?: string) {
<ide> if (this.transaction.isInTransaction()) {
<del> ReactUpdateQueue.enqueueForceUpdate(publicInstance);
<add> ReactUpdateQueue.enqueueForceUpdate(publicInstance, callback, callerName);
<ide> } else {
<ide> warnNoop(publicInstance, 'forceUpdate');
<ide> }
<ide> class ReactServerUpdateQueue {
<ide> *
<ide> * @param {ReactClass} publicInstance The instance that should rerender.
<ide> * @param {object|function} completeState Next state.
<add> * @param {?function} callback Called after component is updated.
<add> * @param {?string} Name of the calling function in the public API.
<ide> * @internal
<ide> */
<del> enqueueReplaceState(publicInstance: ReactComponent<any, any, any>, completeState: Object|Function) {
<add> enqueueReplaceState(
<add> publicInstance: ReactComponent<any, any, any>,
<add> completeState: Object|Function,
<add> callback?: Function,
<add> callerName?: string
<add> ) {
<ide> if (this.transaction.isInTransaction()) {
<del> ReactUpdateQueue.enqueueReplaceState(publicInstance, completeState);
<add> ReactUpdateQueue.enqueueReplaceState(publicInstance, completeState, callback, callerName);
<ide> } else {
<ide> warnNoop(publicInstance, 'replaceState');
<ide> }
<ide> class ReactServerUpdateQueue {
<ide> * @param {object|function} partialState Next partial state to be merged with state.
<ide> * @internal
<ide> */
<del> enqueueSetState(publicInstance: ReactComponent<any, any, any>, partialState: Object|Function) {
<add> enqueueSetState(
<add> publicInstance: ReactComponent<any, any, any>,
<add> partialState: Object|Function,
<add> callback?: Function,
<add> callerName?: string
<add> ) {
<ide> if (this.transaction.isInTransaction()) {
<del> ReactUpdateQueue.enqueueSetState(publicInstance, partialState);
<add> ReactUpdateQueue.enqueueSetState(publicInstance, partialState, callback, callerName);
<ide> } else {
<ide> warnNoop(publicInstance, 'setState');
<ide> }
<ide><path>src/renderers/shared/fiber/ReactFiberClassComponent.js
<ide> var {
<ide> addUpdate,
<ide> addReplaceUpdate,
<ide> addForceUpdate,
<del> addCallback,
<ide> beginUpdateQueue,
<ide> } = require('ReactFiberUpdateQueue');
<ide> var { hasContextChanged } = require('ReactFiberContext');
<ide> module.exports = function(
<ide> addForceUpdate(fiber, callback || null, priorityLevel);
<ide> scheduleUpdate(fiber, priorityLevel);
<ide> },
<del> enqueueCallback(instance, callback) {
<del> const fiber = ReactInstanceMap.get(instance);
<del> const priorityLevel = getPriorityContext();
<del> addCallback(fiber, callback || null, priorityLevel);
<del> scheduleUpdate(fiber, priorityLevel);
<del> },
<ide> };
<ide>
<ide> function checkShouldComponentUpdate(workInProgress, oldProps, newProps, newState, newContext) {
<ide><path>src/renderers/shared/fiber/ReactFiberUpdateQueue.js
<ide> function addForceUpdate(
<ide> }
<ide> exports.addForceUpdate = addForceUpdate;
<ide>
<del>
<del>function addCallback(
<del> fiber : Fiber,
<del> callback: Callback,
<del> priorityLevel : PriorityLevel
<del>) : void {
<del> const update : Update = {
<del> priorityLevel,
<del> partialState: null,
<del> callback,
<del> isReplace: false,
<del> isForced: false,
<del> isTopLevelUnmount: false,
<del> next: null,
<del> };
<del> insertUpdate(fiber, update);
<del>}
<del>exports.addCallback = addCallback;
<del>
<ide> function getPendingPriority(queue : UpdateQueue) : PriorityLevel {
<ide> return queue.first ? queue.first.priorityLevel : NoWork;
<ide> }
<ide><path>src/renderers/shared/stack/reconciler/ReactUpdateQueue.js
<ide> var ReactUpdateQueue = {
<ide> }
<ide> },
<ide>
<del> /**
<del> * Enqueue a callback that will be executed after all the pending updates
<del> * have processed.
<del> *
<del> * @param {ReactClass} publicInstance The instance to use as `this` context.
<del> * @param {?function} callback Called after state is updated.
<del> * @param {string} callerName Name of the calling function in the public API.
<del> * @internal
<del> */
<del> enqueueCallback: function(publicInstance, callback, callerName) {
<del> ReactUpdateQueue.validateCallback(callback, callerName);
<del> var internalInstance = getInternalInstanceReadyForUpdate(publicInstance);
<del>
<del> // Previously we would throw an error if we didn't have an internal
<del> // instance. Since we want to make it a no-op instead, we mirror the same
<del> // behavior we have in other enqueue* methods.
<del> // We also need to ignore callbacks in componentWillMount. See
<del> // enqueueUpdates.
<del> if (!internalInstance) {
<del> return null;
<del> }
<del>
<del> if (internalInstance._pendingCallbacks) {
<del> internalInstance._pendingCallbacks.push(callback);
<del> } else {
<del> internalInstance._pendingCallbacks = [callback];
<del> }
<del> // TODO: The callback here is ignored when setState is called from
<del> // componentWillMount. Either fix it or disallow doing so completely in
<del> // favor of getInitialState. Alternatively, we can disallow
<del> // componentWillMount during server-side rendering.
<del> enqueueUpdate(internalInstance);
<del> },
<del>
<ide> enqueueCallbackInternal: function(internalInstance, callback) {
<ide> if (internalInstance._pendingCallbacks) {
<ide> internalInstance._pendingCallbacks.push(callback); | 5 |
Javascript | Javascript | improve support properties computation | 44cb97e0cfc8d3e62bef7c621bfeba6fe4f65d7c | <ide><path>src/css/support.js
<ide> define( [
<ide> // Executing both pixelPosition & boxSizingReliable tests require only one layout
<ide> // so they're executed at the same time to save the second computation.
<ide> function computeStyleTests() {
<add>
<add> // This is a singleton, we need to execute it only once
<add> if ( !div ) {
<add> return;
<add> }
<add>
<ide> div.style.cssText =
<ide> "box-sizing:border-box;" +
<ide> "position:relative;display:block;" +
<ide> define( [
<ide>
<ide> var divStyle = window.getComputedStyle( div );
<ide> pixelPositionVal = divStyle.top !== "1%";
<add>
<add> // Support: Android 4.0 - 4.3 only, Firefox <=3 - 44+
<ide> reliableMarginLeftVal = divStyle.marginLeft === "2px";
<ide> boxSizingReliableVal = divStyle.width === "4px";
<ide>
<ide> define( [
<ide> pixelMarginRightVal = divStyle.marginRight === "4px";
<ide>
<ide> documentElement.removeChild( container );
<add>
<add> // Nullify the div so it wouldn't be stored in the memory and
<add> // it will also be a sign that checks already performed
<add> div = null;
<ide> }
<ide>
<ide> jQuery.extend( support, {
<ide> pixelPosition: function() {
<del>
<del> // This test is executed only once but we still do memoizing
<del> // since we can use the boxSizingReliable pre-computing.
<del> // No need to check if the test was already performed, though.
<ide> computeStyleTests();
<ide> return pixelPositionVal;
<ide> },
<ide> boxSizingReliable: function() {
<del> if ( boxSizingReliableVal == null ) {
<del> computeStyleTests();
<del> }
<add> computeStyleTests();
<ide> return boxSizingReliableVal;
<ide> },
<ide> pixelMarginRight: function() {
<del>
<del> // Support: Android 4.0 - 4.3 only
<del> // We're checking for boxSizingReliableVal here instead of pixelMarginRightVal
<del> // since that compresses better and they're computed together anyway.
<del> if ( boxSizingReliableVal == null ) {
<del> computeStyleTests();
<del> }
<add> computeStyleTests();
<ide> return pixelMarginRightVal;
<ide> },
<ide> reliableMarginLeft: function() {
<del>
<del> // Support: Android 4.0 - 4.3 only, Firefox <=3 - 44+
<del> if ( boxSizingReliableVal == null ) {
<del> computeStyleTests();
<del> }
<add> computeStyleTests();
<ide> return reliableMarginLeftVal;
<ide> }
<ide> } ); | 1 |
Javascript | Javascript | fix amp test flake | c731d591497780ace9ab2e9eb0758bfa6416fbe3 | <ide><path>test/integration/amphtml/test/index.test.js
<ide> /* eslint-env jest */
<ide>
<del>import { join } from 'path'
<del>import cheerio from 'cheerio'
<del>import webdriver from 'next-webdriver'
<ide> import { validateAMP } from 'amp-test-utils'
<add>import cheerio from 'cheerio'
<ide> import {
<ide> accessSync,
<add> readFile,
<ide> readFileSync,
<del> writeFileSync,
<ide> writeFile,
<del> readFile,
<add> writeFileSync,
<ide> } from 'fs-extra'
<ide> import {
<del> waitFor,
<del> nextServer,
<del> nextBuild,
<del> startApp,
<del> stopApp,
<del> renderViaHTTP,
<ide> check,
<del> getBrowserBodyText,
<ide> findPort,
<del> launchApp,
<add> getBrowserBodyText,
<ide> killApp,
<add> launchApp,
<add> nextBuild,
<add> nextServer,
<add> renderViaHTTP,
<add> startApp,
<add> stopApp,
<add> waitFor,
<ide> } from 'next-test-utils'
<add>import webdriver from 'next-webdriver'
<add>import { join } from 'path'
<ide>
<ide> const appDir = join(__dirname, '../')
<ide> let appPort
<ide> describe('AMP Usage', () => {
<ide>
<ide> it('should detect changes to component and refresh an AMP page', async () => {
<ide> const browser = await webdriver(dynamicAppPort, '/hmr/comp')
<del> const text = await browser.elementByCss('#hello-comp').text()
<del> expect(text).toBe('hello')
<add> await check(() => browser.elementByCss('#hello-comp').text(), /hello/)
<ide>
<ide> const testComp = join(__dirname, '../components/hello.js')
<ide>
<ide> describe('AMP Usage', () => {
<ide> await renderViaHTTP(dynamicAppPort, '/hmr/test')
<ide>
<ide> browser = await webdriver(dynamicAppPort, '/hmr/amp')
<del> const text = await browser.elementByCss('p').text()
<del> const origDate = await browser.elementByCss('span').text()
<del> expect(text).toBe(`I'm an AMP page!`)
<add> await check(() => browser.elementByCss('p').text(), /I'm an AMP page!/)
<ide>
<add> const origDate = await browser.elementByCss('span').text()
<ide> const hmrTestPagePath = join(
<ide> __dirname,
<ide> '../', | 1 |
PHP | PHP | add support for tinyblob, mediumblob and longblob | fe78749404cfe7db6377a215d03eacf8a4eea0e5 | <ide><path>src/Database/Schema/MysqlSchema.php
<ide> protected function _convertColumn($column)
<ide> return ['type' => 'text', 'length' => $length];
<ide> }
<ide> if (strpos($col, 'blob') !== false || $col === 'binary') {
<add> $lengthName = substr($col, 0, -4);
<add> $length = isset(Table::$columnLengths[$lengthName]) ? Table::$columnLengths[$lengthName] : null;
<ide> return ['type' => 'binary', 'length' => $length];
<ide> }
<ide> if (strpos($col, 'float') !== false || strpos($col, 'double') !== false) {
<ide> public function columnSql(Table $table, $name)
<ide> 'integer' => ' INTEGER',
<ide> 'biginteger' => ' BIGINT',
<ide> 'boolean' => ' BOOLEAN',
<del> 'binary' => ' LONGBLOB',
<ide> 'float' => ' FLOAT',
<ide> 'decimal' => ' DECIMAL',
<ide> 'date' => ' DATE',
<ide> public function columnSql(Table $table, $name)
<ide> $specialMap = [
<ide> 'string' => true,
<ide> 'text' => true,
<add> 'binary' => true,
<ide> ];
<ide> if (isset($typeMap[$data['type']])) {
<ide> $out .= $typeMap[$data['type']];
<ide> public function columnSql(Table $table, $name)
<ide> $out .= ' ' . strtoupper($length) . 'TEXT';
<ide> }
<ide>
<add> break;
<add> case 'binary':
<add> $isKnownLength = in_array($data['length'], Table::$columnLengths);
<add> if (empty($data['length']) || !$isKnownLength) {
<add> $out .= ' BLOB';
<add> break;
<add> }
<add>
<add> if ($isKnownLength) {
<add> $length = array_search($data['length'], Table::$columnLengths);
<add> $out .= ' ' . strtoupper($length) . 'BLOB';
<add> }
<add>
<ide> break;
<ide> }
<ide> }
<ide><path>src/Database/Schema/SqlserverSchema.php
<ide> public function columnSql(Table $table, $name)
<ide> 'integer' => ' INTEGER',
<ide> 'biginteger' => ' BIGINT',
<ide> 'boolean' => ' BIT',
<del> 'binary' => ' VARBINARY(MAX)',
<ide> 'float' => ' FLOAT',
<ide> 'decimal' => ' DECIMAL',
<ide> 'date' => ' DATE',
<ide> public function columnSql(Table $table, $name)
<ide> $out .= ' NVARCHAR(MAX)';
<ide> }
<ide>
<add> if ($data['type'] === 'binary') {
<add> $out .= ' VARBINARY';
<add>
<add> if ($data['length'] !== Table::LENGTH_TINY) {
<add> $out .= '(MAX)';
<add> } else {
<add> $out .= sprintf('(%s)', Table::LENGTH_TINY);
<add> }
<add> }
<add>
<ide> if ($data['type'] === 'string' || ($data['type'] === 'text' && $data['length'] === Table::LENGTH_TINY)) {
<ide> $type = ' NVARCHAR';
<ide>
<ide><path>tests/Fixture/SessionsFixture.php
<ide> */
<ide> namespace Cake\Test\Fixture;
<ide>
<add>use Cake\Database\Schema\Table;
<ide> use Cake\TestSuite\Fixture\TestFixture;
<ide>
<ide> /**
<ide> class SessionsFixture extends TestFixture
<ide> */
<ide> public $fields = [
<ide> 'id' => ['type' => 'string', 'length' => 128],
<del> 'data' => ['type' => 'binary', 'null' => true],
<add> 'data' => ['type' => 'binary', 'length' => Table::LENGTH_MEDIUM, 'null' => true],
<ide> 'expires' => ['type' => 'integer', 'length' => 11, 'null' => true],
<ide> '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['id']]]
<ide> ];
<ide><path>tests/TestCase/Database/Schema/MysqlSchemaTest.php
<ide> public static function convertColumnProvider()
<ide> 'CHAR(36)',
<ide> ['type' => 'uuid', 'length' => null]
<ide> ],
<add> [
<add> 'TEXT',
<add> ['type' => 'text', 'length' => null]
<add> ],
<ide> [
<ide> 'TINYTEXT',
<ide> ['type' => 'text', 'length' => Table::LENGTH_TINY]
<ide> public static function convertColumnProvider()
<ide> 'LONGTEXT',
<ide> ['type' => 'text', 'length' => Table::LENGTH_LONG]
<ide> ],
<add> [
<add> 'TINYBLOB',
<add> ['type' => 'binary', 'length' => Table::LENGTH_TINY]
<add> ],
<ide> [
<ide> 'BLOB',
<ide> ['type' => 'binary', 'length' => null]
<ide> ],
<ide> [
<ide> 'MEDIUMBLOB',
<del> ['type' => 'binary', 'length' => null]
<add> ['type' => 'binary', 'length' => Table::LENGTH_MEDIUM]
<add> ],
<add> [
<add> 'LONGBLOB',
<add> ['type' => 'binary', 'length' => Table::LENGTH_LONG]
<ide> ],
<ide> [
<ide> 'FLOAT',
<ide> public static function columnSqlProvider()
<ide> ['type' => 'text', 'length' => Table::LENGTH_LONG, 'null' => false],
<ide> '`body` LONGTEXT NOT NULL'
<ide> ],
<add> // Blob / binary
<add> [
<add> 'body',
<add> ['type' => 'binary', 'null' => false],
<add> '`body` BLOB NOT NULL'
<add> ],
<add> [
<add> 'body',
<add> ['type' => 'binary', 'length' => Table::LENGTH_TINY, 'null' => false],
<add> '`body` TINYBLOB NOT NULL'
<add> ],
<add> [
<add> 'body',
<add> ['type' => 'binary', 'length' => Table::LENGTH_MEDIUM, 'null' => false],
<add> '`body` MEDIUMBLOB NOT NULL'
<add> ],
<add> [
<add> 'body',
<add> ['type' => 'binary', 'length' => Table::LENGTH_LONG, 'null' => false],
<add> '`body` LONGBLOB NOT NULL'
<add> ],
<ide> // Integers
<ide> [
<ide> 'post_id',
<ide><path>tests/TestCase/Database/Schema/PostgresSchemaTest.php
<ide> public static function columnSqlProvider()
<ide> [
<ide> 'body',
<ide> ['type' => 'text', 'length' => Table::LENGTH_TINY, 'null' => false],
<del> '"body" VARCHAR(' . Table::LENGTH_TINY . ') NOT NULL'
<add> sprintf('"body" VARCHAR(%s) NOT NULL', Table::LENGTH_TINY)
<ide> ],
<ide> [
<ide> 'body',
<ide><path>tests/TestCase/Database/Schema/SqlserverSchemaTest.php
<ide> public static function columnSqlProvider()
<ide> [
<ide> 'body',
<ide> ['type' => 'text', 'length' => Table::LENGTH_TINY, 'null' => false],
<del> '[body] NVARCHAR(' . Table::LENGTH_TINY . ') NOT NULL'
<add> sprintf('[body] NVARCHAR(%s) NOT NULL', Table::LENGTH_TINY)
<ide> ],
<ide> [
<ide> 'body',
<ide> public static function columnSqlProvider()
<ide> // Binary
<ide> [
<ide> 'img',
<del> ['type' => 'binary'],
<add> ['type' => 'binary', 'length' => null],
<add> '[img] VARBINARY(MAX)'
<add> ],
<add> [
<add> 'img',
<add> ['type' => 'binary', 'length' => Table::LENGTH_TINY],
<add> sprintf('[img] VARBINARY(%s)', Table::LENGTH_TINY)
<add> ],
<add> [
<add> 'img',
<add> ['type' => 'binary', 'length' => Table::LENGTH_MEDIUM],
<add> '[img] VARBINARY(MAX)'
<add> ],
<add> [
<add> 'img',
<add> ['type' => 'binary', 'length' => Table::LENGTH_LONG],
<ide> '[img] VARBINARY(MAX)'
<ide> ],
<ide> // Boolean | 6 |
Java | Java | ensure environment.shutdown() in reactor2tcpclient | bd40a93604bbff9e41085639628114fc0c0898c2 | <ide><path>spring-messaging/src/main/java/org/springframework/messaging/tcp/reactor/Reactor2TcpClient.java
<ide>
<ide> private final EventLoopGroup eventLoopGroup;
<ide>
<add> private final Environment environment;
<add>
<ide> private final TcpClientFactory<Message<P>, Message<P>> tcpClientSpecFactory;
<ide>
<ide> private final List<TcpClient<Message<P>, Message<P>>> tcpClients =
<ide> public Reactor2TcpClient(final String host, final int port, final Codec<Buffer,
<ide> // Reactor 2.0.5 requires NioEventLoopGroup vs 2.0.6+ requires EventLoopGroup
<ide> final NioEventLoopGroup nioEventLoopGroup = initEventLoopGroup();
<ide> this.eventLoopGroup = nioEventLoopGroup;
<add> this.environment = new Environment(new SynchronousDispatcherConfigReader());
<ide>
<ide> this.tcpClientSpecFactory = new TcpClientFactory<Message<P>, Message<P>>() {
<ide> @Override
<ide> public TcpClientSpec<Message<P>, Message<P>> apply(TcpClientSpec<Message<P>, Message<P>> spec) {
<ide> return spec
<del> .env(new Environment(new SynchronousDispatcherConfigReader()))
<add> .env(environment)
<ide> .codec(codec)
<ide> .connect(host, port)
<ide> .options(createClientSocketOptions());
<ide> public Reactor2TcpClient(TcpClientFactory<Message<P>, Message<P>> tcpClientSpecF
<ide> Assert.notNull(tcpClientSpecFactory, "'tcpClientClientFactory' must not be null");
<ide> this.tcpClientSpecFactory = tcpClientSpecFactory;
<ide> this.eventLoopGroup = null;
<add> this.environment = null;
<ide> }
<ide>
<ide>
<ide> public void operationComplete(Future<Object> future) throws Exception {
<ide> promise = eventLoopPromise;
<ide> }
<ide>
<add> if (this.environment != null) {
<add> promise.onComplete(new Consumer<Promise<Void>>() {
<add> @Override
<add> public void accept(Promise<Void> voidPromise) {
<add> environment.shutdown();
<add> }
<add> });
<add> }
<add>
<ide> return new PassThroughPromiseToListenableFutureAdapter<Void>(promise);
<ide> }
<ide> | 1 |
Javascript | Javascript | remove workaround for ie6/7 | e5190982c40d7ac8ab9bdb2e7e4334f0e123ef66 | <ide><path>src/ajax.js
<ide> define([
<ide> ], function( jQuery, rnotwhite, nonce, rquery ) {
<ide>
<ide> var
<del> // Document location
<del> ajaxLocParts,
<del> ajaxLocation,
<del>
<ide> rhash = /#.*$/,
<ide> rts = /([?&])_=[^&]*/,
<ide> rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,
<ide> var
<ide> transports = {},
<ide>
<ide> // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
<del> allTypes = "*/".concat("*");
<del>
<del>// Support: IE6
<del>// Exception accessing window.location.href if document.domain is set (#8138)
<del>try {
<del> ajaxLocation = location.href;
<del>} catch( e ) {
<del> // Use the href attribute of an A element
<del> // since IE will modify it given document.location
<del> ajaxLocation = document.createElement( "a" );
<del> ajaxLocation.href = "";
<del> ajaxLocation = ajaxLocation.href;
<del>}
<add> allTypes = "*/".concat( "*" ),
<add>
<add> // Document location
<add> ajaxLocation = location.href,
<ide>
<del>// Segment location into parts
<del>ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
<add> // Segment location into parts
<add> ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
<ide>
<ide> // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
<ide> function addToPrefiltersOrTransports( structure ) { | 1 |
Java | Java | add accessor methods to httpputformcontentfilter | 8417831602fb1f3ea873d88cd09090f878db73d3 | <ide><path>spring-web/src/main/java/org/springframework/web/filter/HttpPutFormContentFilter.java
<ide> /*
<del> * Copyright 2002-2016 the original author or authors.
<add> * Copyright 2002-2017 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.http.converter.FormHttpMessageConverter;
<ide> import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter;
<ide> import org.springframework.http.server.ServletServerHttpRequest;
<add>import org.springframework.util.Assert;
<ide> import org.springframework.util.LinkedMultiValueMap;
<ide> import org.springframework.util.MultiValueMap;
<ide>
<ide> */
<ide> public class HttpPutFormContentFilter extends OncePerRequestFilter {
<ide>
<del> private final FormHttpMessageConverter formConverter = new AllEncompassingFormHttpMessageConverter();
<add> private FormHttpMessageConverter formConverter = new AllEncompassingFormHttpMessageConverter();
<ide>
<ide>
<add> /**
<add> * Set the converter to use for parsing form content.
<add> * <p>By default this is an instnace of {@link AllEncompassingFormHttpMessageConverter}.
<add> */
<add> public void setFormConverter(FormHttpMessageConverter converter) {
<add> Assert.notNull(converter, "FormHttpMessageConverter is required.");
<add> this.formConverter = converter;
<add> }
<add>
<add> public FormHttpMessageConverter getFormConverter() {
<add> return this.formConverter;
<add> }
<add>
<ide> /**
<ide> * The default character set to use for reading form data.
<add> * This is a shortcut for:<br>
<add> * {@code getFormConverter.setCharset(charset)}.
<ide> */
<ide> public void setCharset(Charset charset) {
<ide> this.formConverter.setCharset(charset); | 1 |
Text | Text | move installation instructions to the top | 41cc5f3f596747ec72da9d3e034a00dd7c250ee8 | <ide><path>examples/README.md
<ide> # Examples
<ide>
<del>Version 2.9 of 🤗 Transformers introduces a new [`Trainer`](https://github.com/huggingface/transformers/blob/master/src/transformers/trainer.py) class for PyTorch, and its equivalent [`TFTrainer`](https://github.com/huggingface/transformers/blob/master/src/transformers/trainer_tf.py) for TF 2.
<add>Version 2.9 of 🤗 Transformers introduced a new [`Trainer`](https://github.com/huggingface/transformers/blob/master/src/transformers/trainer.py) class for PyTorch, and its equivalent [`TFTrainer`](https://github.com/huggingface/transformers/blob/master/src/transformers/trainer_tf.py) for TF 2.
<ide> Running the examples requires PyTorch 1.3.1+ or TensorFlow 2.2+.
<ide>
<ide> Here is the list of all our examples:
<ide> - **grouped by task** (all official examples work for multiple models)
<ide> - with information on whether they are **built on top of `Trainer`/`TFTrainer`** (if not, they still work, they might just lack some features),
<del>- whether they also include examples for **`pytorch-lightning`**, which is a great fully-featured, general-purpose training library for PyTorch,
<ide> - links to **Colab notebooks** to walk through the scripts and run them easily,
<ide> - links to **Cloud deployments** to be able to deploy large-scale trainings in the Cloud with little to no setup.
<ide>
<del>This is still a work-in-progress – in particular documentation is still sparse – so please **contribute improvements/pull requests.**
<del>
<del>
<del>## The Big Table of Tasks
<del>
<del>| Task | Example datasets | Trainer support | TFTrainer support | pytorch-lightning | Colab
<del>|---|---|:---:|:---:|:---:|:---:|
<del>| [**`language-modeling`**](https://github.com/huggingface/transformers/tree/master/examples/language-modeling) | Raw text | ✅ | - | - | [](https://colab.research.google.com/github/huggingface/blog/blob/master/notebooks/01_how_to_train.ipynb)
<del>| [**`text-classification`**](https://github.com/huggingface/transformers/tree/master/examples/text-classification) | GLUE, XNLI | ✅ | ✅ | ✅ | [](https://colab.research.google.com/github/huggingface/blog/blob/master/notebooks/trainer/01_text_classification.ipynb)
<del>| [**`token-classification`**](https://github.com/huggingface/transformers/tree/master/examples/token-classification) | CoNLL NER | ✅ | ✅ | ✅ | -
<del>| [**`multiple-choice`**](https://github.com/huggingface/transformers/tree/master/examples/multiple-choice) | SWAG, RACE, ARC | ✅ | ✅ | - | [](https://colab.research.google.com/github/ViktorAlm/notebooks/blob/master/MPC_GPU_Demo_for_TF_and_PT.ipynb)
<del>| [**`question-answering`**](https://github.com/huggingface/transformers/tree/master/examples/question-answering) | SQuAD | ✅ | ✅ | - | -
<del>| [**`text-generation`**](https://github.com/huggingface/transformers/tree/master/examples/text-generation) | - | n/a | n/a | n/a | [](https://colab.research.google.com/github/huggingface/blog/blob/master/notebooks/02_how_to_generate.ipynb)
<del>| [**`distillation`**](https://github.com/huggingface/transformers/tree/master/examples/distillation) | All | - | - | - | -
<del>| [**`summarization`**](https://github.com/huggingface/transformers/tree/master/examples/seq2seq) | CNN/Daily Mail | ✅ | - | ✅ | -
<del>| [**`translation`**](https://github.com/huggingface/transformers/tree/master/examples/seq2seq) | WMT | ✅ | - | ✅ | -
<del>| [**`bertology`**](https://github.com/huggingface/transformers/tree/master/examples/bertology) | - | - | - | - | -
<del>| [**`adversarial`**](https://github.com/huggingface/transformers/tree/master/examples/adversarial) | HANS | ✅ | - | - | -
<del>
<del>
<del><br>
<ide>
<ide> ## Important note
<ide>
<ide> **Important**
<del>To make sure you can successfully run the latest versions of the example scripts, you have to install the library from source and install some example-specific requirements.
<add>
<add>To make sure you can successfully run the latest versions of the example scripts, you have to **install the library from source** and install some example-specific requirements.
<ide> Execute the following steps in a new virtual environment:
<ide>
<ide> ```bash
<ide> pip install .
<ide> pip install -r ./examples/requirements.txt
<ide> ```
<ide>
<add>Alternatively, you can run the version of the examples as they were for your current version of Transformers via (for instance with v3.4.0):
<add>```bash
<add>git checkout tags/v3.4.0
<add>```
<add>
<add>## The Big Table of Tasks
<add>
<add>| Task | Example datasets | Trainer support | TFTrainer support | Colab
<add>|---|---|:---:|:---:|:---:|:---:|
<add>| [**`language-modeling`**](https://github.com/huggingface/transformers/tree/master/examples/language-modeling) | Raw text | ✅ | - | [](https://colab.research.google.com/github/huggingface/blog/blob/master/notebooks/01_how_to_train.ipynb)
<add>| [**`text-classification`**](https://github.com/huggingface/transformers/tree/master/examples/text-classification) | GLUE, XNLI | ✅ | ✅ | [](https://colab.research.google.com/github/huggingface/blog/blob/master/notebooks/trainer/01_text_classification.ipynb)
<add>| [**`token-classification`**](https://github.com/huggingface/transformers/tree/master/examples/token-classification) | CoNLL NER | ✅ | ✅ | -
<add>| [**`multiple-choice`**](https://github.com/huggingface/transformers/tree/master/examples/multiple-choice) | SWAG, RACE, ARC | ✅ | ✅ | [](https://colab.research.google.com/github/ViktorAlm/notebooks/blob/master/MPC_GPU_Demo_for_TF_and_PT.ipynb)
<add>| [**`question-answering`**](https://github.com/huggingface/transformers/tree/master/examples/question-answering) | SQuAD | ✅ | ✅ | -
<add>| [**`text-generation`**](https://github.com/huggingface/transformers/tree/master/examples/text-generation) | - | n/a | n/a | [](https://colab.research.google.com/github/huggingface/blog/blob/master/notebooks/02_how_to_generate.ipynb)
<add>| [**`distillation`**](https://github.com/huggingface/transformers/tree/master/examples/distillation) | All | - | - | -
<add>| [**`summarization`**](https://github.com/huggingface/transformers/tree/master/examples/seq2seq) | CNN/Daily Mail | ✅ | - | -
<add>| [**`translation`**](https://github.com/huggingface/transformers/tree/master/examples/seq2seq) | WMT | ✅ | - | | -
<add>| [**`bertology`**](https://github.com/huggingface/transformers/tree/master/examples/bertology) | - | - | - | -
<add>| [**`adversarial`**](https://github.com/huggingface/transformers/tree/master/examples/adversarial) | HANS | ✅ | - | -
<add>
<add>
<add><br>
<add>
<ide> ## One-click Deploy to Cloud (wip)
<ide>
<ide> **Coming soon!** | 1 |
Ruby | Ruby | drop extra variable from test | 48b6860b796d4fa46efd00346d91aaec5fc84cbd | <ide><path>activesupport/test/load_paths_test.rb
<ide> def test_uniq_load_paths
<ide> }
<ide> load_paths_count[File.expand_path('../../lib', __FILE__)] -= 1
<ide>
<del> filtered = load_paths_count.select { |k, v| v > 1 }
<del> assert filtered.empty?, filtered.inspect
<add> load_paths_count.select! { |k, v| v > 1 }
<add> assert load_paths_count.empty?, load_paths_count.inspect
<ide> end
<ide> end | 1 |
Text | Text | fix broken markdown link in 'line' docs | 7c11c81d961751db1499a35e3f163b56d4d65ab1 | <ide><path>docs/charts/line.md
<ide> The style of each point can be controlled with the following properties:
<ide> | `pointHitRadius` | The pixel size of the non-displayed point that reacts to mouse events.
<ide> | `pointRadius` | The radius of the point shape. If set to 0, the point is not rendered.
<ide> | `pointRotation` | The rotation of the point in degrees.
<del>| `pointStyle` | Style of the point. [more...](../configuration/elements#point-styles)
<add>| `pointStyle` | Style of the point. [more...](../configuration/elements.md#point-styles)
<ide>
<ide> All these values, if `undefined`, fallback first to the dataset options then to the associated [`elements.point.*`](../configuration/elements.md#point-configuration) options.
<ide> | 1 |
Javascript | Javascript | add webpack configs and gulp webpack build tasks | 07fc22f86a4020be10b7727df9214dcbf5e328ad | <ide><path>gulpfile.js
<del>require('babel/register');
<add>require('babel-core/register');
<ide> var gulp = require('gulp'),
<ide> path = require('path'),
<ide>
<ide> var paths = {
<ide>
<ide> node: {
<ide> src: './client',
<del> dest: 'server/server'
<add> dest: 'common/app'
<ide> },
<ide>
<ide> syncWatch: [
<ide> gulp.task('loopback', function() {
<ide> });
<ide>
<ide> gulp.task('pack-client', function() {
<del> return gulp.src(paths.client.src)
<add> return gulp.src(webpackConfig.entry)
<ide> .pipe(webpack(webpackConfig))
<del> .pipe(gulp.dest(paths.client.dest));
<add> .pipe(gulp.dest(webpackConfig.output.path));
<ide> });
<ide>
<ide> gulp.task('pack-node', function() {
<del> return gulp.src(paths.node.src)
<add> return gulp.src(webpackConfigNode.entry)
<ide> .pipe(webpack(webpackConfigNode))
<del> .pipe(gulp.dest(paths.node.dest));
<add> .pipe(gulp.dest(webpackConfigNode.output.path));
<ide> });
<ide>
<ide> gulp.task('pack', ['pack-client', 'pack-node']);
<ide><path>webpack.config.js
<ide> module.exports = {
<ide> devtool: 'sourcemap',
<ide> entry: './client',
<ide> output: {
<del> filename: 'fcc.js',
<add> filename: 'bundle.js',
<ide> path: path.join(__dirname, '/public/js'),
<ide> publicPath: 'public/'
<ide> },
<ide><path>webpack.config.node.js
<ide> var nodeModules = fs.readdirSync('node_modules')
<ide> module.exports = {
<ide> devtool: 'sourcemap',
<ide> target: 'node',
<del> entry: './server/appEntry',
<add> entry: './common/app',
<ide> // keeps webpack from bundling modules
<ide> externals: nodeModules,
<ide> output: {
<del> filename: 'fcc.js',
<del> path: path.join(__dirname, '/public/js'),
<add> filename: 'app-stream.bundle.js',
<add> path: path.join(__dirname, '/server'),
<ide> publicPath: 'public/'
<ide> },
<ide> module: { | 3 |
Python | Python | catch adress already in use message more propely | 2baf73ff0e4a8eb41c1456363dd88bd5be9d1aee | <ide><path>glances/outputs/glances_bottle.py
<ide> from io import open
<ide> import webbrowser
<ide> import zlib
<add>import socket
<ide>
<ide> from glances.compat import b
<ide> from glances.timer import Timer
<ide> def start(self, stats):
<ide> new=2,
<ide> autoraise=1)
<ide>
<del> self._app.run(host=self.args.bind_address,
<del> port=self.args.port,
<del> quiet=not self.args.debug)
<add> try:
<add> self._app.run(host=self.args.bind_address,
<add> port=self.args.port,
<add> quiet=not self.args.debug)
<add> except socket.error as e:
<add> logger.critical('Error: Can not ran Glances Web server ({})'.format(e))
<ide>
<ide> def end(self):
<ide> """End the bottle.""" | 1 |
Python | Python | remove `level=` keyword from test arguments | 6a2bc5e3548ff8e3b1fcd1a6d7a4ee263c17aa0b | <ide><path>numpy/core/tests/test_getlimits.py
<ide> def test_singleton(self):
<ide> assert_equal(id(ftype), id(ftype2))
<ide>
<ide> class TestLongdouble(object):
<del> def test_singleton(self,level=2):
<add> def test_singleton(self):
<ide> ftype = finfo(longdouble)
<ide> ftype2 = finfo(longdouble)
<ide> assert_equal(id(ftype), id(ftype2))
<ide><path>numpy/core/tests/test_regression.py
<ide> )
<ide> from numpy.compat import asbytes, asunicode, long
<ide>
<del>rlevel = 1
<ide>
<ide> class TestRegression(object):
<del> def test_invalid_round(self, level=rlevel):
<add> def test_invalid_round(self):
<ide> # Ticket #3
<ide> v = 4.7599999999999998
<ide> assert_array_equal(np.array([v]), np.array(v))
<ide>
<del> def test_mem_empty(self, level=rlevel):
<add> def test_mem_empty(self):
<ide> # Ticket #7
<ide> np.empty((1,), dtype=[('x', np.int64)])
<ide>
<del> def test_pickle_transposed(self, level=rlevel):
<add> def test_pickle_transposed(self):
<ide> # Ticket #16
<ide> a = np.transpose(np.array([[2, 9], [7, 0], [3, 8]]))
<ide> f = BytesIO()
<ide> def test_pickle_transposed(self, level=rlevel):
<ide> f.close()
<ide> assert_array_equal(a, b)
<ide>
<del> def test_typeNA(self, level=rlevel):
<add> def test_typeNA(self):
<ide> # Ticket #31
<ide> assert_equal(np.typeNA[np.int64], 'Int64')
<ide> assert_equal(np.typeNA[np.uint64], 'UInt64')
<ide>
<del> def test_dtype_names(self, level=rlevel):
<add> def test_dtype_names(self):
<ide> # Ticket #35
<ide> # Should succeed
<ide> np.dtype([(('name', 'label'), np.int32, 3)])
<ide>
<del> def test_reduce(self, level=rlevel):
<add> def test_reduce(self):
<ide> # Ticket #40
<ide> assert_almost_equal(np.add.reduce([1., .5], dtype=None), 1.5)
<ide>
<del> def test_zeros_order(self, level=rlevel):
<add> def test_zeros_order(self):
<ide> # Ticket #43
<ide> np.zeros([3], int, 'C')
<ide> np.zeros([3], order='C')
<ide> np.zeros([3], int, order='C')
<ide>
<del> def test_asarray_with_order(self, level=rlevel):
<add> def test_asarray_with_order(self):
<ide> # Check that nothing is done when order='F' and array C/F-contiguous
<ide> a = np.ones(2)
<ide> assert_(a is np.asarray(a, order='F'))
<ide>
<del> def test_ravel_with_order(self, level=rlevel):
<add> def test_ravel_with_order(self):
<ide> # Check that ravel works when order='F' and array C/F-contiguous
<ide> a = np.ones(2)
<ide> assert_(not a.ravel('F').flags.owndata)
<ide>
<del> def test_sort_bigendian(self, level=rlevel):
<add> def test_sort_bigendian(self):
<ide> # Ticket #47
<ide> a = np.linspace(0, 10, 11)
<ide> c = a.astype(np.dtype('<f8'))
<ide> c.sort()
<ide> assert_array_almost_equal(c, a)
<ide>
<del> def test_negative_nd_indexing(self, level=rlevel):
<add> def test_negative_nd_indexing(self):
<ide> # Ticket #49
<ide> c = np.arange(125).reshape((5, 5, 5))
<ide> origidx = np.array([-1, 0, 1])
<ide> idx = np.array(origidx)
<ide> c[idx]
<ide> assert_array_equal(idx, origidx)
<ide>
<del> def test_char_dump(self, level=rlevel):
<add> def test_char_dump(self):
<ide> # Ticket #50
<ide> f = BytesIO()
<ide> ca = np.char.array(np.arange(1000, 1010), itemsize=4)
<ide> def test_char_dump(self, level=rlevel):
<ide> ca = np.load(f)
<ide> f.close()
<ide>
<del> def test_noncontiguous_fill(self, level=rlevel):
<add> def test_noncontiguous_fill(self):
<ide> # Ticket #58.
<ide> a = np.zeros((5, 3))
<ide> b = a[:, :2,]
<ide> def rs():
<ide>
<ide> assert_raises(AttributeError, rs)
<ide>
<del> def test_bool(self, level=rlevel):
<add> def test_bool(self):
<ide> # Ticket #60
<ide> np.bool_(1) # Should succeed
<ide>
<del> def test_indexing1(self, level=rlevel):
<add> def test_indexing1(self):
<ide> # Ticket #64
<ide> descr = [('x', [('y', [('z', 'c16', (2,)),]),]),]
<ide> buffer = ((([6j, 4j],),),)
<ide> h = np.array(buffer, dtype=descr)
<ide> h['x']['y']['z']
<ide>
<del> def test_indexing2(self, level=rlevel):
<add> def test_indexing2(self):
<ide> # Ticket #65
<ide> descr = [('x', 'i4', (2,))]
<ide> buffer = ([3, 2],)
<ide> h = np.array(buffer, dtype=descr)
<ide> h['x']
<ide>
<del> def test_round(self, level=rlevel):
<add> def test_round(self):
<ide> # Ticket #67
<ide> x = np.array([1+2j])
<ide> assert_almost_equal(x**(-1), [1/(1+2j)])
<ide>
<del> def test_scalar_compare(self, level=rlevel):
<add> def test_scalar_compare(self):
<ide> # Trac Ticket #72
<ide> # https://github.com/numpy/numpy/issues/565
<ide> a = np.array(['test', 'auto'])
<ide> def test_scalar_compare(self, level=rlevel):
<ide> assert_(b != 'auto')
<ide> assert_(b[0] != 'auto')
<ide>
<del> def test_unicode_swapping(self, level=rlevel):
<add> def test_unicode_swapping(self):
<ide> # Ticket #79
<ide> ulen = 1
<ide> ucs_value = u'\U0010FFFF'
<ide> ua = np.array([[[ucs_value*ulen]*2]*3]*4, dtype='U%s' % ulen)
<ide> ua.newbyteorder() # Should succeed.
<ide>
<del> def test_object_array_fill(self, level=rlevel):
<add> def test_object_array_fill(self):
<ide> # Ticket #86
<ide> x = np.zeros(1, 'O')
<ide> x.fill([])
<ide>
<del> def test_mem_dtype_align(self, level=rlevel):
<add> def test_mem_dtype_align(self):
<ide> # Ticket #93
<ide> assert_raises(TypeError, np.dtype,
<ide> {'names':['a'], 'formats':['foo']}, align=1)
<ide> def test_mem_dtype_align(self, level=rlevel):
<ide> platform.architecture()[0] == "64bit"),
<ide> "numpy.intp('0xff', 16) not supported on Py3, "
<ide> "as it does not inherit from Python int")
<del> def test_intp(self, level=rlevel):
<add> def test_intp(self):
<ide> # Ticket #99
<ide> i_width = np.int_(0).nbytes*2 - 1
<ide> np.intp('0x' + 'f'*i_width, 16)
<ide> def test_intp(self, level=rlevel):
<ide> assert_equal(255, np.intp('0xFF', 16))
<ide> assert_equal(1024, np.intp(1024))
<ide>
<del> def test_endian_bool_indexing(self, level=rlevel):
<add> def test_endian_bool_indexing(self):
<ide> # Ticket #105
<ide> a = np.arange(10., dtype='>f8')
<ide> b = np.arange(10., dtype='<f8')
<ide> def test_endian_bool_indexing(self, level=rlevel):
<ide> assert_(np.all(a[ya] > 0.5))
<ide> assert_(np.all(b[yb] > 0.5))
<ide>
<del> def test_endian_where(self, level=rlevel):
<add> def test_endian_where(self):
<ide> # GitHub issue #369
<ide> net = np.zeros(3, dtype='>f4')
<ide> net[1] = 0.00458849
<ide> def test_endian_where(self, level=rlevel):
<ide> correct = np.array([ 0.60520202, 0.00458849, 0.60520202])
<ide> assert_array_almost_equal(test, correct)
<ide>
<del> def test_endian_recarray(self, level=rlevel):
<add> def test_endian_recarray(self):
<ide> # Ticket #2185
<ide> dt = np.dtype([
<ide> ('head', '>u4'),
<ide> def test_endian_recarray(self, level=rlevel):
<ide> buf[0]['data'][0] = d
<ide> assert_(buf[0]['head'] == 1)
<ide>
<del> def test_mem_dot(self, level=rlevel):
<add> def test_mem_dot(self):
<ide> # Ticket #106
<ide> x = np.random.randn(0, 1)
<ide> y = np.random.randn(10, 1)
<ide> def test_mem_dot(self, level=rlevel):
<ide> np.core.multiarray.dot(x, np.transpose(y), out=z)
<ide> assert_equal(_z, np.ones(10))
<ide>
<del> def test_arange_endian(self, level=rlevel):
<add> def test_arange_endian(self):
<ide> # Ticket #111
<ide> ref = np.arange(10)
<ide> x = np.arange(10, dtype='<f8')
<ide> assert_array_equal(ref, x)
<ide> x = np.arange(10, dtype='>f8')
<ide> assert_array_equal(ref, x)
<ide>
<del> def test_argmax(self, level=rlevel):
<add> def test_argmax(self):
<ide> # Ticket #119
<ide> a = np.random.normal(0, 1, (4, 5, 6, 7, 8))
<ide> for i in range(a.ndim):
<ide> a.argmax(i) # Should succeed
<ide>
<del> def test_mem_divmod(self, level=rlevel):
<add> def test_mem_divmod(self):
<ide> # Ticket #126
<ide> for i in range(10):
<ide> divmod(np.array([i])[0], 10)
<ide>
<del> def test_hstack_invalid_dims(self, level=rlevel):
<add> def test_hstack_invalid_dims(self):
<ide> # Ticket #128
<ide> x = np.arange(9).reshape((3, 3))
<ide> y = np.array([0, 0, 0])
<ide> assert_raises(ValueError, np.hstack, (x, y))
<ide>
<del> def test_squeeze_type(self, level=rlevel):
<add> def test_squeeze_type(self):
<ide> # Ticket #133
<ide> a = np.array([3])
<ide> b = np.array(3)
<ide> assert_(type(a.squeeze()) is np.ndarray)
<ide> assert_(type(b.squeeze()) is np.ndarray)
<ide>
<del> def test_add_identity(self, level=rlevel):
<add> def test_add_identity(self):
<ide> # Ticket #143
<ide> assert_equal(0, np.add.identity)
<ide>
<ide> def test_numpy_float_python_long_addition(self):
<ide> a = np.float_(23.) + 2**135
<ide> assert_equal(a, 23. + 2**135)
<ide>
<del> def test_binary_repr_0(self, level=rlevel):
<add> def test_binary_repr_0(self):
<ide> # Ticket #151
<ide> assert_equal('0', np.binary_repr(0))
<ide>
<del> def test_rec_iterate(self, level=rlevel):
<add> def test_rec_iterate(self):
<ide> # Ticket #160
<ide> descr = np.dtype([('i', int), ('f', float), ('s', '|S3')])
<ide> x = np.rec.array([(1, 1.1, '1.0'),
<ide> (2, 2.2, '2.0')], dtype=descr)
<ide> x[0].tolist()
<ide> [i for i in x[0]]
<ide>
<del> def test_unicode_string_comparison(self, level=rlevel):
<add> def test_unicode_string_comparison(self):
<ide> # Ticket #190
<ide> a = np.array('hello', np.unicode_)
<ide> b = np.array('world')
<ide> a == b
<ide>
<del> def test_tobytes_FORTRANORDER_discontiguous(self, level=rlevel):
<add> def test_tobytes_FORTRANORDER_discontiguous(self):
<ide> # Fix in r2836
<ide> # Create non-contiguous Fortran ordered array
<ide> x = np.array(np.random.rand(3, 3), order='F')[:, :2]
<ide> assert_array_almost_equal(x.ravel(), np.fromstring(x.tobytes()))
<ide>
<del> def test_flat_assignment(self, level=rlevel):
<add> def test_flat_assignment(self):
<ide> # Correct behaviour of ticket #194
<ide> x = np.empty((3, 1))
<ide> x.flat = np.arange(3)
<ide> assert_array_almost_equal(x, [[0], [1], [2]])
<ide> x.flat = np.arange(3, dtype=float)
<ide> assert_array_almost_equal(x, [[0], [1], [2]])
<ide>
<del> def test_broadcast_flat_assignment(self, level=rlevel):
<add> def test_broadcast_flat_assignment(self):
<ide> # Ticket #194
<ide> x = np.empty((3, 1))
<ide>
<ide> def assign(a, b, c):
<ide> assert_raises(ValueError, assign, a, r, np.nan)
<ide> a[r] = np.array(np.nan)
<ide>
<del> def test_unpickle_dtype_with_object(self, level=rlevel):
<add> def test_unpickle_dtype_with_object(self):
<ide> # Implemented in r2840
<ide> dt = np.dtype([('x', int), ('y', np.object_), ('z', 'O')])
<ide> f = BytesIO()
<ide> def test_unpickle_dtype_with_object(self, level=rlevel):
<ide> f.close()
<ide> assert_equal(dt, dt_)
<ide>
<del> def test_mem_array_creation_invalid_specification(self, level=rlevel):
<add> def test_mem_array_creation_invalid_specification(self):
<ide> # Ticket #196
<ide> dt = np.dtype([('x', int), ('y', np.object_)])
<ide> # Wrong way
<ide> assert_raises(ValueError, np.array, [1, 'object'], dt)
<ide> # Correct way
<ide> np.array([(1, 'object')], dt)
<ide>
<del> def test_recarray_single_element(self, level=rlevel):
<add> def test_recarray_single_element(self):
<ide> # Ticket #202
<ide> a = np.array([1, 2, 3], dtype=np.int32)
<ide> b = a.copy()
<ide> r = np.rec.array(a, shape=1, formats=['3i4'], names=['d'])
<ide> assert_array_equal(a, b)
<ide> assert_equal(a, r[0][0])
<ide>
<del> def test_zero_sized_array_indexing(self, level=rlevel):
<add> def test_zero_sized_array_indexing(self):
<ide> # Ticket #205
<ide> tmp = np.array([])
<ide>
<ide> def index_tmp():
<ide>
<ide> assert_raises(IndexError, index_tmp)
<ide>
<del> def test_chararray_rstrip(self, level=rlevel):
<add> def test_chararray_rstrip(self):
<ide> # Ticket #222
<ide> x = np.chararray((1,), 5)
<ide> x[0] = b'a '
<ide> x = x.rstrip()
<ide> assert_equal(x[0], b'a')
<ide>
<del> def test_object_array_shape(self, level=rlevel):
<add> def test_object_array_shape(self):
<ide> # Ticket #239
<ide> assert_equal(np.array([[1, 2], 3, 4], dtype=object).shape, (3,))
<ide> assert_equal(np.array([[1, 2], [3, 4]], dtype=object).shape, (2, 2))
<ide> def test_object_array_shape(self, level=rlevel):
<ide> assert_equal(np.array([[], [], []], dtype=object).shape, (3, 0))
<ide> assert_equal(np.array([[3, 4], [5, 6], None], dtype=object).shape, (3,))
<ide>
<del> def test_mem_around(self, level=rlevel):
<add> def test_mem_around(self):
<ide> # Ticket #243
<ide> x = np.zeros((1,))
<ide> y = [0]
<ide> decimal = 6
<ide> np.around(abs(x-y), decimal) <= 10.0**(-decimal)
<ide>
<del> def test_character_array_strip(self, level=rlevel):
<add> def test_character_array_strip(self):
<ide> # Ticket #246
<ide> x = np.char.array(("x", "x ", "x "))
<ide> for c in x:
<ide> assert_equal(c, "x")
<ide>
<del> def test_lexsort(self, level=rlevel):
<add> def test_lexsort(self):
<ide> # Lexsort memory error
<ide> v = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
<ide> assert_equal(np.lexsort(v), 0)
<ide> def test_pickle_py2_bytes_encoding(self):
<ide> for name in result.dtype.names:
<ide> assert_(isinstance(name, str))
<ide>
<del> def test_pickle_dtype(self, level=rlevel):
<add> def test_pickle_dtype(self):
<ide> # Ticket #251
<ide> pickle.dumps(float)
<ide>
<del> def test_swap_real(self, level=rlevel):
<add> def test_swap_real(self):
<ide> # Ticket #265
<ide> assert_equal(np.arange(4, dtype='>c8').imag.max(), 0.0)
<ide> assert_equal(np.arange(4, dtype='<c8').imag.max(), 0.0)
<ide> assert_equal(np.arange(4, dtype='>c8').real.max(), 3.0)
<ide> assert_equal(np.arange(4, dtype='<c8').real.max(), 3.0)
<ide>
<del> def test_object_array_from_list(self, level=rlevel):
<add> def test_object_array_from_list(self):
<ide> # Ticket #270
<ide> assert_(np.array([1, 'A', None]).shape == (3,))
<ide>
<del> def test_multiple_assign(self, level=rlevel):
<add> def test_multiple_assign(self):
<ide> # Ticket #273
<ide> a = np.zeros((3, 1), int)
<ide> a[[1, 2]] = 1
<ide>
<del> def test_empty_array_type(self, level=rlevel):
<add> def test_empty_array_type(self):
<ide> assert_equal(np.array([]).dtype, np.zeros(0).dtype)
<ide>
<del> def test_void_copyswap(self, level=rlevel):
<add> def test_void_copyswap(self):
<ide> dt = np.dtype([('one', '<i4'), ('two', '<i4')])
<ide> x = np.array((1, 2), dtype=dt)
<ide> x = x.byteswap()
<ide> assert_(x['one'] > 1 and x['two'] > 2)
<ide>
<del> def test_method_args(self, level=rlevel):
<add> def test_method_args(self):
<ide> # Make sure methods and functions have same default axis
<ide> # keyword and arguments
<ide> funcs1 = ['argmax', 'argmin', 'sum', ('product', 'prod'),
<ide> def test_method_args(self, level=rlevel):
<ide> res2 = getattr(np, func)(arr1, arr2)
<ide> assert_(abs(res1-res2).max() < 1e-8, func)
<ide>
<del> def test_mem_lexsort_strings(self, level=rlevel):
<add> def test_mem_lexsort_strings(self):
<ide> # Ticket #298
<ide> lst = ['abc', 'cde', 'fgh']
<ide> np.lexsort((lst,))
<ide>
<del> def test_fancy_index(self, level=rlevel):
<add> def test_fancy_index(self):
<ide> # Ticket #302
<ide> x = np.array([1, 2])[np.array([0])]
<ide> assert_equal(x.shape, (1,))
<ide>
<del> def test_recarray_copy(self, level=rlevel):
<add> def test_recarray_copy(self):
<ide> # Ticket #312
<ide> dt = [('x', np.int16), ('y', np.float64)]
<ide> ra = np.array([(1, 2.3)], dtype=dt)
<ide> rb = np.rec.array(ra, dtype=dt)
<ide> rb['x'] = 2.
<ide> assert_(ra['x'] != rb['x'])
<ide>
<del> def test_rec_fromarray(self, level=rlevel):
<add> def test_rec_fromarray(self):
<ide> # Ticket #322
<ide> x1 = np.array([[1, 2], [3, 4], [5, 6]])
<ide> x2 = np.array(['a', 'dd', 'xyz'])
<ide> x3 = np.array([1.1, 2, 3])
<ide> np.rec.fromarrays([x1, x2, x3], formats="(2,)i4,a3,f8")
<ide>
<del> def test_object_array_assign(self, level=rlevel):
<add> def test_object_array_assign(self):
<ide> x = np.empty((2, 2), object)
<ide> x.flat[2] = (1, 2, 3)
<ide> assert_equal(x.flat[2], (1, 2, 3))
<ide>
<del> def test_ndmin_float64(self, level=rlevel):
<add> def test_ndmin_float64(self):
<ide> # Ticket #324
<ide> x = np.array([1, 2, 3], dtype=np.float64)
<ide> assert_equal(np.array(x, dtype=np.float32, ndmin=2).ndim, 2)
<ide> assert_equal(np.array(x, dtype=np.float64, ndmin=2).ndim, 2)
<ide>
<del> def test_ndmin_order(self, level=rlevel):
<add> def test_ndmin_order(self):
<ide> # Issue #465 and related checks
<ide> assert_(np.array([1, 2], order='C', ndmin=3).flags.c_contiguous)
<ide> assert_(np.array([1, 2], order='F', ndmin=3).flags.f_contiguous)
<ide> assert_(np.array(np.ones((2, 2), order='F'), ndmin=3).flags.f_contiguous)
<ide> assert_(np.array(np.ones((2, 2), order='C'), ndmin=3).flags.c_contiguous)
<ide>
<del> def test_mem_axis_minimization(self, level=rlevel):
<add> def test_mem_axis_minimization(self):
<ide> # Ticket #327
<ide> data = np.arange(5)
<ide> data = np.add.outer(data, data)
<ide>
<del> def test_mem_float_imag(self, level=rlevel):
<add> def test_mem_float_imag(self):
<ide> # Ticket #330
<ide> np.float64(1.0).imag
<ide>
<del> def test_dtype_tuple(self, level=rlevel):
<add> def test_dtype_tuple(self):
<ide> # Ticket #334
<ide> assert_(np.dtype('i4') == np.dtype(('i4', ())))
<ide>
<del> def test_dtype_posttuple(self, level=rlevel):
<add> def test_dtype_posttuple(self):
<ide> # Ticket #335
<ide> np.dtype([('col1', '()i4')])
<ide>
<del> def test_numeric_carray_compare(self, level=rlevel):
<add> def test_numeric_carray_compare(self):
<ide> # Ticket #341
<ide> assert_equal(np.array(['X'], 'c'), b'X')
<ide>
<del> def test_string_array_size(self, level=rlevel):
<add> def test_string_array_size(self):
<ide> # Ticket #342
<ide> assert_raises(ValueError,
<ide> np.array, [['X'], ['X', 'X', 'X']], '|S1')
<ide>
<del> def test_dtype_repr(self, level=rlevel):
<add> def test_dtype_repr(self):
<ide> # Ticket #344
<ide> dt1 = np.dtype(('uint32', 2))
<ide> dt2 = np.dtype(('uint32', (2,)))
<ide> assert_equal(dt1.__repr__(), dt2.__repr__())
<ide>
<del> def test_reshape_order(self, level=rlevel):
<add> def test_reshape_order(self):
<ide> # Make sure reshape order works.
<ide> a = np.arange(6).reshape(2, 3, order='F')
<ide> assert_equal(a, [[0, 2, 4], [1, 3, 5]])
<ide> a = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
<ide> b = a[:, 1]
<ide> assert_equal(b.reshape(2, 2, order='F'), [[2, 6], [4, 8]])
<ide>
<del> def test_reshape_zero_strides(self, level=rlevel):
<add> def test_reshape_zero_strides(self):
<ide> # Issue #380, test reshaping of zero strided arrays
<ide> a = np.ones(1)
<ide> a = np.lib.stride_tricks.as_strided(a, shape=(5,), strides=(0,))
<ide> assert_(a.reshape(5, 1).strides[0] == 0)
<ide>
<del> def test_reshape_zero_size(self, level=rlevel):
<add> def test_reshape_zero_size(self):
<ide> # GitHub Issue #2700, setting shape failed for 0-sized arrays
<ide> a = np.ones((0, 2))
<ide> a.shape = (-1, 2)
<ide> def test_reshape_trailing_ones_strides(self):
<ide> assert_equal(a.reshape(3, 2, 1, 1, order='F').strides, strides_f)
<ide> assert_equal(np.array(0, dtype=np.int32).reshape(1, 1).strides, (4, 4))
<ide>
<del> def test_repeat_discont(self, level=rlevel):
<add> def test_repeat_discont(self):
<ide> # Ticket #352
<ide> a = np.arange(12).reshape(4, 3)[:, 2]
<ide> assert_equal(a.repeat(3), [2, 2, 2, 5, 5, 5, 8, 8, 8, 11, 11, 11])
<ide>
<del> def test_array_index(self, level=rlevel):
<add> def test_array_index(self):
<ide> # Make sure optimization is not called in this case.
<ide> a = np.array([1, 2, 3])
<ide> a2 = np.array([[1, 2, 3]])
<ide> assert_equal(a[np.where(a == 3)], a2[np.where(a2 == 3)])
<ide>
<del> def test_object_argmax(self, level=rlevel):
<add> def test_object_argmax(self):
<ide> a = np.array([1, 2, 3], dtype=object)
<ide> assert_(a.argmax() == 2)
<ide>
<del> def test_recarray_fields(self, level=rlevel):
<add> def test_recarray_fields(self):
<ide> # Ticket #372
<ide> dt0 = np.dtype([('f0', 'i4'), ('f1', 'i4')])
<ide> dt1 = np.dtype([('f0', 'i8'), ('f1', 'i8')])
<ide> def test_recarray_fields(self, level=rlevel):
<ide> np.rec.fromarrays([(1, 2), (3, 4)])]:
<ide> assert_(a.dtype in [dt0, dt1])
<ide>
<del> def test_random_shuffle(self, level=rlevel):
<add> def test_random_shuffle(self):
<ide> # Ticket #374
<ide> a = np.arange(5).reshape((5, 1))
<ide> b = a.copy()
<ide> np.random.shuffle(b)
<ide> assert_equal(np.sort(b, axis=0), a)
<ide>
<del> def test_refcount_vdot(self, level=rlevel):
<add> def test_refcount_vdot(self):
<ide> # Changeset #3443
<ide> _assert_valid_refcount(np.vdot)
<ide>
<del> def test_startswith(self, level=rlevel):
<add> def test_startswith(self):
<ide> ca = np.char.array(['Hi', 'There'])
<ide> assert_equal(ca.startswith('H'), [True, False])
<ide>
<del> def test_noncommutative_reduce_accumulate(self, level=rlevel):
<add> def test_noncommutative_reduce_accumulate(self):
<ide> # Ticket #413
<ide> tosubtract = np.arange(5)
<ide> todivide = np.array([2.0, 0.5, 0.25])
<ide> def test_noncommutative_reduce_accumulate(self, level=rlevel):
<ide> assert_array_equal(np.divide.accumulate(todivide),
<ide> np.array([2., 4., 16.]))
<ide>
<del> def test_convolve_empty(self, level=rlevel):
<add> def test_convolve_empty(self):
<ide> # Convolve should raise an error for empty input array.
<ide> assert_raises(ValueError, np.convolve, [], [1])
<ide> assert_raises(ValueError, np.convolve, [1], [])
<ide>
<del> def test_multidim_byteswap(self, level=rlevel):
<add> def test_multidim_byteswap(self):
<ide> # Ticket #449
<ide> r = np.array([(1, (0, 1, 2))], dtype="i2,3i2")
<ide> assert_array_equal(r.byteswap(),
<ide> np.array([(256, (0, 256, 512))], r.dtype))
<ide>
<del> def test_string_NULL(self, level=rlevel):
<add> def test_string_NULL(self):
<ide> # Changeset 3557
<ide> assert_equal(np.array("a\x00\x0b\x0c\x00").item(),
<ide> 'a\x00\x0b\x0c')
<ide>
<del> def test_junk_in_string_fields_of_recarray(self, level=rlevel):
<add> def test_junk_in_string_fields_of_recarray(self):
<ide> # Ticket #483
<ide> r = np.array([[b'abc']], dtype=[('var1', '|S20')])
<ide> assert_(asbytes(r['var1'][0][0]) == b'abc')
<ide>
<del> def test_take_output(self, level=rlevel):
<add> def test_take_output(self):
<ide> # Ensure that 'take' honours output parameter.
<ide> x = np.arange(12).reshape((3, 4))
<ide> a = np.take(x, [0, 2], axis=1)
<ide> def test_take_object_fail(self):
<ide> if HAS_REFCOUNT:
<ide> assert_(ref_d == sys.getrefcount(d))
<ide>
<del> def test_array_str_64bit(self, level=rlevel):
<add> def test_array_str_64bit(self):
<ide> # Ticket #501
<ide> s = np.array([1, np.nan], dtype=np.float64)
<ide> with np.errstate(all='raise'):
<ide> np.array_str(s) # Should succeed
<ide>
<del> def test_frompyfunc_endian(self, level=rlevel):
<add> def test_frompyfunc_endian(self):
<ide> # Ticket #503
<ide> from math import radians
<ide> uradians = np.frompyfunc(radians, 1, 1)
<ide> def test_frompyfunc_endian(self, level=rlevel):
<ide> assert_almost_equal(uradians(big_endian).astype(float),
<ide> uradians(little_endian).astype(float))
<ide>
<del> def test_mem_string_arr(self, level=rlevel):
<add> def test_mem_string_arr(self):
<ide> # Ticket #514
<ide> s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
<ide> t = []
<ide> np.hstack((t, s))
<ide>
<del> def test_arr_transpose(self, level=rlevel):
<add> def test_arr_transpose(self):
<ide> # Ticket #516
<ide> x = np.random.rand(*(2,)*16)
<ide> x.transpose(list(range(16))) # Should succeed
<ide>
<del> def test_string_mergesort(self, level=rlevel):
<add> def test_string_mergesort(self):
<ide> # Ticket #540
<ide> x = np.array(['a']*32)
<ide> assert_array_equal(x.argsort(kind='m'), np.arange(32))
<ide>
<del> def test_argmax_byteorder(self, level=rlevel):
<add> def test_argmax_byteorder(self):
<ide> # Ticket #546
<ide> a = np.arange(3, dtype='>f')
<ide> assert_(a[a.argmax()] == a.max())
<ide>
<del> def test_rand_seed(self, level=rlevel):
<add> def test_rand_seed(self):
<ide> # Ticket #555
<ide> for l in np.arange(4):
<ide> np.random.seed(l)
<ide>
<del> def test_mem_deallocation_leak(self, level=rlevel):
<add> def test_mem_deallocation_leak(self):
<ide> # Ticket #562
<ide> a = np.zeros(5, dtype=float)
<ide> b = np.array(a, dtype=float)
<ide> def test_mem_on_invalid_dtype(self):
<ide> "Ticket #583"
<ide> assert_raises(ValueError, np.fromiter, [['12', ''], ['13', '']], str)
<ide>
<del> def test_dot_negative_stride(self, level=rlevel):
<add> def test_dot_negative_stride(self):
<ide> # Ticket #588
<ide> x = np.array([[1, 5, 25, 125., 625]])
<ide> y = np.array([[20.], [160.], [640.], [1280.], [1024.]])
<ide> z = y[::-1].copy()
<ide> y2 = y[::-1]
<ide> assert_equal(np.dot(x, z), np.dot(x, y2))
<ide>
<del> def test_object_casting(self, level=rlevel):
<add> def test_object_casting(self):
<ide> # This used to trigger the object-type version of
<ide> # the bitwise_or operation, because float64 -> object
<ide> # casting succeeds
<ide> def rs():
<ide>
<ide> assert_raises(TypeError, rs)
<ide>
<del> def test_unicode_scalar(self, level=rlevel):
<add> def test_unicode_scalar(self):
<ide> # Ticket #600
<ide> x = np.array(["DROND", "DROND1"], dtype="U6")
<ide> el = x[1]
<ide> new = pickle.loads(pickle.dumps(el))
<ide> assert_equal(new, el)
<ide>
<del> def test_arange_non_native_dtype(self, level=rlevel):
<add> def test_arange_non_native_dtype(self):
<ide> # Ticket #616
<ide> for T in ('>f4', '<f4'):
<ide> dt = np.dtype(T)
<ide> assert_equal(np.arange(0, dtype=dt).dtype, dt)
<ide> assert_equal(np.arange(0.5, dtype=dt).dtype, dt)
<ide> assert_equal(np.arange(5, dtype=dt).dtype, dt)
<ide>
<del> def test_bool_flat_indexing_invalid_nr_elements(self, level=rlevel):
<add> def test_bool_flat_indexing_invalid_nr_elements(self):
<ide> s = np.ones(10, dtype=float)
<ide> x = np.array((15,), dtype=float)
<ide>
<ide> def ia(x, s, v):
<ide> assert_raises(ValueError, ia, x.flat, s, np.zeros(9, dtype=float))
<ide> assert_raises(ValueError, ia, x.flat, s, np.zeros(11, dtype=float))
<ide>
<del> def test_mem_scalar_indexing(self, level=rlevel):
<add> def test_mem_scalar_indexing(self):
<ide> # Ticket #603
<ide> x = np.array([0], dtype=float)
<ide> index = np.array(0, dtype=np.int32)
<ide> x[index]
<ide>
<del> def test_binary_repr_0_width(self, level=rlevel):
<add> def test_binary_repr_0_width(self):
<ide> assert_equal(np.binary_repr(0, width=3), '000')
<ide>
<del> def test_fromstring(self, level=rlevel):
<add> def test_fromstring(self):
<ide> assert_equal(np.fromstring("12:09:09", dtype=int, sep=":"),
<ide> [12, 9, 9])
<ide>
<del> def test_searchsorted_variable_length(self, level=rlevel):
<add> def test_searchsorted_variable_length(self):
<ide> x = np.array(['a', 'aa', 'b'])
<ide> y = np.array(['d', 'e'])
<ide> assert_equal(x.searchsorted(y), [3, 3])
<ide>
<del> def test_string_argsort_with_zeros(self, level=rlevel):
<add> def test_string_argsort_with_zeros(self):
<ide> # Check argsort for strings containing zeros.
<ide> x = np.fromstring("\x00\x02\x00\x01", dtype="|S2")
<ide> assert_array_equal(x.argsort(kind='m'), np.array([1, 0]))
<ide> assert_array_equal(x.argsort(kind='q'), np.array([1, 0]))
<ide>
<del> def test_string_sort_with_zeros(self, level=rlevel):
<add> def test_string_sort_with_zeros(self):
<ide> # Check sort for strings containing zeros.
<ide> x = np.fromstring("\x00\x02\x00\x01", dtype="|S2")
<ide> y = np.fromstring("\x00\x01\x00\x02", dtype="|S2")
<ide> assert_array_equal(np.sort(x, kind="q"), y)
<ide>
<del> def test_copy_detection_zero_dim(self, level=rlevel):
<add> def test_copy_detection_zero_dim(self):
<ide> # Ticket #658
<ide> np.indices((0, 3, 4)).T.reshape(-1, 3)
<ide>
<del> def test_flat_byteorder(self, level=rlevel):
<add> def test_flat_byteorder(self):
<ide> # Ticket #657
<ide> x = np.arange(10)
<ide> assert_array_equal(x.astype('>i4'), x.astype('<i4').flat[:])
<ide> assert_array_equal(x.astype('>i4').flat[:], x.astype('<i4'))
<ide>
<del> def test_uint64_from_negative(self, level=rlevel):
<add> def test_uint64_from_negative(self):
<ide> assert_equal(np.uint64(-2), np.uint64(18446744073709551614))
<ide>
<del> def test_sign_bit(self, level=rlevel):
<add> def test_sign_bit(self):
<ide> x = np.array([0, -0.0, 0])
<ide> assert_equal(str(np.abs(x)), '[ 0. 0. 0.]')
<ide>
<del> def test_flat_index_byteswap(self, level=rlevel):
<add> def test_flat_index_byteswap(self):
<ide> for dt in (np.dtype('<i4'), np.dtype('>i4')):
<ide> x = np.array([-1, 0, 1], dtype=dt)
<ide> assert_equal(x.flat[0].dtype, x[0].dtype)
<ide>
<del> def test_copy_detection_corner_case(self, level=rlevel):
<add> def test_copy_detection_corner_case(self):
<ide> # Ticket #658
<ide> np.indices((0, 3, 4)).T.reshape(-1, 3)
<ide>
<ide> # Cannot test if NPY_RELAXED_STRIDES_CHECKING changes the strides.
<ide> # With NPY_RELAXED_STRIDES_CHECKING the test becomes superfluous,
<ide> # 0-sized reshape itself is tested elsewhere.
<ide> @dec.skipif(np.ones(1).strides[0] == np.iinfo(np.intp).max)
<del> def test_copy_detection_corner_case2(self, level=rlevel):
<add> def test_copy_detection_corner_case2(self):
<ide> # Ticket #771: strides are not set correctly when reshaping 0-sized
<ide> # arrays
<ide> b = np.indices((0, 3, 4)).T.reshape(-1, 3)
<ide> assert_equal(b.strides, (3 * b.itemsize, b.itemsize))
<ide>
<del> def test_object_array_refcounting(self, level=rlevel):
<add> def test_object_array_refcounting(self):
<ide> # Ticket #633
<ide> if not hasattr(sys, 'getrefcount'):
<ide> return
<ide> def test_object_array_refcounting(self, level=rlevel):
<ide>
<ide> del tmp # Avoid pyflakes unused variable warning
<ide>
<del> def test_mem_custom_float_to_array(self, level=rlevel):
<add> def test_mem_custom_float_to_array(self):
<ide> # Ticket 702
<ide> class MyFloat(object):
<ide> def __float__(self):
<ide> def __float__(self):
<ide> tmp = np.atleast_1d([MyFloat()])
<ide> tmp.astype(float) # Should succeed
<ide>
<del> def test_object_array_refcount_self_assign(self, level=rlevel):
<add> def test_object_array_refcount_self_assign(self):
<ide> # Ticket #711
<ide> class VictimObject(object):
<ide> deleted = False
<ide> def __del__(self):
<ide> arr[:] = arr # trying to induce a segfault by doing it again...
<ide> assert_(not arr[0].deleted)
<ide>
<del> def test_mem_fromiter_invalid_dtype_string(self, level=rlevel):
<add> def test_mem_fromiter_invalid_dtype_string(self):
<ide> x = [1, 2, 3]
<ide> assert_raises(ValueError,
<ide> np.fromiter, [xi for xi in x], dtype='S')
<ide>
<del> def test_reduce_big_object_array(self, level=rlevel):
<add> def test_reduce_big_object_array(self):
<ide> # Ticket #713
<ide> oldsize = np.setbufsize(10*16)
<ide> a = np.array([None]*161, object)
<ide> assert_(not np.any(a))
<ide> np.setbufsize(oldsize)
<ide>
<del> def test_mem_0d_array_index(self, level=rlevel):
<add> def test_mem_0d_array_index(self):
<ide> # Ticket #714
<ide> np.zeros(10)[np.array(0)]
<ide>
<del> def test_floats_from_string(self, level=rlevel):
<add> def test_floats_from_string(self):
<ide> # Ticket #640, floats from string
<ide> fsingle = np.single('1.234')
<ide> fdouble = np.double('1.234')
<ide> def test_floats_from_string(self, level=rlevel):
<ide> assert_almost_equal(fdouble, 1.234)
<ide> assert_almost_equal(flongdouble, 1.234)
<ide>
<del> def test_nonnative_endian_fill(self, level=rlevel):
<add> def test_nonnative_endian_fill(self):
<ide> # Non-native endian arrays were incorrectly filled with scalars
<ide> # before r5034.
<ide> if sys.byteorder == 'little':
<ide> def test_nonnative_endian_fill(self, level=rlevel):
<ide> x.fill(1)
<ide> assert_equal(x, np.array([1], dtype=dtype))
<ide>
<del> def test_dot_alignment_sse2(self, level=rlevel):
<add> def test_dot_alignment_sse2(self):
<ide> # Test for ticket #551, changeset r5140
<ide> x = np.zeros((30, 40))
<ide> y = pickle.loads(pickle.dumps(x))
<ide> def test_dot_alignment_sse2(self, level=rlevel):
<ide> # This shouldn't cause a segmentation fault:
<ide> np.dot(z, y)
<ide>
<del> def test_astype_copy(self, level=rlevel):
<add> def test_astype_copy(self):
<ide> # Ticket #788, changeset r5155
<ide> # The test data file was generated by scipy.io.savemat.
<ide> # The dtype is float64, but the isbuiltin attribute is 0.
<ide> def test_astype_copy(self, level=rlevel):
<ide> assert_((xp.__array_interface__['data'][0] !=
<ide> xpd.__array_interface__['data'][0]))
<ide>
<del> def test_compress_small_type(self, level=rlevel):
<add> def test_compress_small_type(self):
<ide> # Ticket #789, changeset 5217.
<ide> # compress with out argument segfaulted if cannot cast safely
<ide> import numpy as np
<ide> def test_compress_small_type(self, level=rlevel):
<ide> except TypeError:
<ide> pass
<ide>
<del> def test_attributes(self, level=rlevel):
<add> def test_attributes(self):
<ide> # Ticket #791
<ide> class TestArray(np.ndarray):
<ide> def __new__(cls, data, info):
<ide> def __array_finalize__(self, obj):
<ide> assert_(type(dat.nonzero()[0]) is np.ndarray)
<ide> assert_(type(dat.nonzero()[1]) is np.ndarray)
<ide>
<del> def test_recarray_tolist(self, level=rlevel):
<add> def test_recarray_tolist(self):
<ide> # Ticket #793, changeset r5215
<ide> # Comparisons fail for NaN, so we can't use random memory
<ide> # for the test.
<ide> def test_nonscalar_item_method(self):
<ide> a = np.arange(5)
<ide> assert_raises(ValueError, a.item)
<ide>
<del> def test_char_array_creation(self, level=rlevel):
<add> def test_char_array_creation(self):
<ide> a = np.array('123', dtype='c')
<ide> b = np.array([b'1', b'2', b'3'])
<ide> assert_equal(a, b)
<ide>
<del> def test_unaligned_unicode_access(self, level=rlevel):
<add> def test_unaligned_unicode_access(self):
<ide> # Ticket #825
<ide> for i in range(1, 9):
<ide> msg = 'unicode offset: %d chars' % i
<ide> def test_unaligned_unicode_access(self, level=rlevel):
<ide> else:
<ide> assert_equal(str(x), "[('a', u'b')]", err_msg=msg)
<ide>
<del> def test_sign_for_complex_nan(self, level=rlevel):
<add> def test_sign_for_complex_nan(self):
<ide> # Ticket 794.
<ide> with np.errstate(invalid='ignore'):
<ide> C = np.array([-np.inf, -2+1j, 0, 2-1j, np.inf, np.nan])
<ide> have = np.sign(C)
<ide> want = np.array([-1+0j, -1+0j, 0+0j, 1+0j, 1+0j, np.nan])
<ide> assert_equal(have, want)
<ide>
<del> def test_for_equal_names(self, level=rlevel):
<add> def test_for_equal_names(self):
<ide> # Ticket #674
<ide> dt = np.dtype([('foo', float), ('bar', float)])
<ide> a = np.zeros(10, dt)
<ide> def test_for_equal_names(self, level=rlevel):
<ide> assert_(a.dtype.names[0] == "notfoo")
<ide> assert_(a.dtype.names[1] == "bar")
<ide>
<del> def test_for_object_scalar_creation(self, level=rlevel):
<add> def test_for_object_scalar_creation(self):
<ide> # Ticket #816
<ide> a = np.object_()
<ide> b = np.object_(3)
<ide> def test_array_resize_method_system_error(self):
<ide> x = np.array([[0, 1], [2, 3]])
<ide> assert_raises(TypeError, x.resize, (2, 2), order='C')
<ide>
<del> def test_for_zero_length_in_choose(self, level=rlevel):
<add> def test_for_zero_length_in_choose(self):
<ide> "Ticket #882"
<ide> a = np.array(1)
<ide> assert_raises(ValueError, lambda x: x.choose([]), a)
<ide> def test_array_ndmin_overflow(self):
<ide> "Ticket #947."
<ide> assert_raises(ValueError, lambda: np.array([1], ndmin=33))
<ide>
<del> def test_void_scalar_with_titles(self, level=rlevel):
<add> def test_void_scalar_with_titles(self):
<ide> # No ticket
<ide> data = [('john', 4), ('mary', 5)]
<ide> dtype1 = [(('source:yy', 'name'), 'O'), (('source:xx', 'id'), int)]
<ide> def test_log1p_compiler_shenanigans(self):
<ide> # Check if log1p is behaving on 32 bit intel systems.
<ide> assert_(np.isfinite(np.log1p(np.exp2(-53))))
<ide>
<del> def test_fromiter_comparison(self, level=rlevel):
<add> def test_fromiter_comparison(self):
<ide> a = np.fromiter(list(range(10)), dtype='b')
<ide> b = np.fromiter(list(range(10)), dtype='B')
<ide> assert_(np.alltrue(a == np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])))
<ide><path>numpy/core/tests/test_scalarmath.py
<ide> # This compares scalarmath against ufuncs.
<ide>
<ide> class TestTypes(object):
<del> def test_types(self, level=1):
<add> def test_types(self):
<ide> for atype in types:
<ide> a = atype(1)
<ide> assert_(a == 1, "error with %r: got %r" % (atype, a))
<ide>
<del> def test_type_add(self, level=1):
<add> def test_type_add(self):
<ide> # list of types
<ide> for k, atype in enumerate(types):
<ide> a_scalar = atype(3)
<ide> def test_type_add(self, level=1):
<ide> "error with types (%d/'%c' + %d/'%c')" %
<ide> (k, np.dtype(atype).char, l, np.dtype(btype).char))
<ide>
<del> def test_type_create(self, level=1):
<add> def test_type_create(self):
<ide> for k, atype in enumerate(types):
<ide> a = np.array([1, 2, 3], atype)
<ide> b = atype([1, 2, 3])
<ide><path>numpy/lib/tests/test_regression.py
<ide> )
<ide> from numpy.compat import unicode
<ide>
<del>rlevel = 1
<del>
<ide>
<ide> class TestRegression(object):
<del> def test_poly1d(self, level=rlevel):
<add> def test_poly1d(self):
<ide> # Ticket #28
<ide> assert_equal(np.poly1d([1]) - np.poly1d([1, 0]),
<ide> np.poly1d([-1, 1]))
<ide>
<del> def test_cov_parameters(self, level=rlevel):
<add> def test_cov_parameters(self):
<ide> # Ticket #91
<ide> x = np.random.random((3, 3))
<ide> y = x.copy()
<ide> np.cov(x, rowvar=1)
<ide> np.cov(y, rowvar=0)
<ide> assert_array_equal(x, y)
<ide>
<del> def test_mem_digitize(self, level=rlevel):
<add> def test_mem_digitize(self):
<ide> # Ticket #95
<ide> for i in range(100):
<ide> np.digitize([1, 2, 3, 4], [1, 3])
<ide> np.digitize([0, 1, 2, 3, 4], [1, 3])
<ide>
<del> def test_unique_zero_sized(self, level=rlevel):
<add> def test_unique_zero_sized(self):
<ide> # Ticket #205
<ide> assert_array_equal([], np.unique(np.array([])))
<ide>
<del> def test_mem_vectorise(self, level=rlevel):
<add> def test_mem_vectorise(self):
<ide> # Ticket #325
<ide> vt = np.vectorize(lambda *args: args)
<ide> vt(np.zeros((1, 2, 1)), np.zeros((2, 1, 1)), np.zeros((1, 1, 2)))
<ide> vt(np.zeros((1, 2, 1)), np.zeros((2, 1, 1)), np.zeros((1,
<ide> 1, 2)), np.zeros((2, 2)))
<ide>
<del> def test_mgrid_single_element(self, level=rlevel):
<add> def test_mgrid_single_element(self):
<ide> # Ticket #339
<ide> assert_array_equal(np.mgrid[0:0:1j], [0])
<ide> assert_array_equal(np.mgrid[0:0], [])
<ide>
<del> def test_refcount_vectorize(self, level=rlevel):
<add> def test_refcount_vectorize(self):
<ide> # Ticket #378
<ide> def p(x, y):
<ide> return 123
<ide> v = np.vectorize(p)
<ide> _assert_valid_refcount(v)
<ide>
<del> def test_poly1d_nan_roots(self, level=rlevel):
<add> def test_poly1d_nan_roots(self):
<ide> # Ticket #396
<ide> p = np.poly1d([np.nan, np.nan, 1], r=0)
<ide> assert_raises(np.linalg.LinAlgError, getattr, p, "r")
<ide>
<del> def test_mem_polymul(self, level=rlevel):
<add> def test_mem_polymul(self):
<ide> # Ticket #448
<ide> np.polymul([], [1.])
<ide>
<del> def test_mem_string_concat(self, level=rlevel):
<add> def test_mem_string_concat(self):
<ide> # Ticket #469
<ide> x = np.array([])
<ide> np.append(x, 'asdasd\tasdasd')
<ide>
<del> def test_poly_div(self, level=rlevel):
<add> def test_poly_div(self):
<ide> # Ticket #553
<ide> u = np.poly1d([1, 2, 3])
<ide> v = np.poly1d([1, 2, 3, 4, 5])
<ide> q, r = np.polydiv(u, v)
<ide> assert_equal(q*v + r, u)
<ide>
<del> def test_poly_eq(self, level=rlevel):
<add> def test_poly_eq(self):
<ide> # Ticket #554
<ide> x = np.poly1d([1, 2, 3])
<ide> y = np.poly1d([3, 4])
<ide> def test_ndenumerate_crash(self):
<ide> # Shouldn't crash:
<ide> list(np.ndenumerate(np.array([[]])))
<ide>
<del> def test_asfarray_none(self, level=rlevel):
<add> def test_asfarray_none(self):
<ide> # Test for changeset r5065
<ide> assert_array_equal(np.array([np.nan]), np.asfarray([None]))
<ide>
<del> def test_large_fancy_indexing(self, level=rlevel):
<add> def test_large_fancy_indexing(self):
<ide> # Large enough to fail on 64-bit.
<ide> nbits = np.dtype(np.intp).itemsize * 8
<ide> thesize = int((2**nbits)**(1.0/5.0)+1)
<ide> def dp2():
<ide> assert_raises(ValueError, dp)
<ide> assert_raises(ValueError, dp2)
<ide>
<del> def test_void_coercion(self, level=rlevel):
<add> def test_void_coercion(self):
<ide> dt = np.dtype([('a', 'f4'), ('b', 'i4')])
<ide> x = np.zeros((1,), dt)
<ide> assert_(np.r_[x, x].dtype == dt)
<ide>
<del> def test_who_with_0dim_array(self, level=rlevel):
<add> def test_who_with_0dim_array(self):
<ide> # ticket #1243
<ide> import os
<ide> import sys
<ide><path>numpy/lib/tests/test_shape_base.py
<ide> def test_simple(self):
<ide> assert_array_equal(
<ide> apply_along_axis(len, 0, a), len(a)*np.ones(a.shape[1]))
<ide>
<del> def test_simple101(self, level=11):
<add> def test_simple101(self):
<ide> a = np.ones((10, 101), 'd')
<ide> assert_array_equal(
<ide> apply_along_axis(len, 0, a), len(a)*np.ones(a.shape[1]))
<ide><path>numpy/linalg/tests/test_regression.py
<ide> )
<ide>
<ide>
<del>rlevel = 1
<del>
<del>
<ide> class TestRegression(object):
<ide>
<del> def test_eig_build(self, level=rlevel):
<add> def test_eig_build(self):
<ide> # Ticket #652
<ide> rva = array([1.03221168e+02 + 0.j,
<ide> -1.91843603e+01 + 0.j,
<ide> def test_eig_build(self, level=rlevel):
<ide> rva.sort()
<ide> assert_array_almost_equal(va, rva)
<ide>
<del> def test_eigh_build(self, level=rlevel):
<add> def test_eigh_build(self):
<ide> # Ticket 662.
<ide> rvals = [68.60568999, 89.57756725, 106.67185574]
<ide>
<ide> def test_eigh_build(self, level=rlevel):
<ide> vals, vecs = linalg.eigh(cov)
<ide> assert_array_almost_equal(vals, rvals)
<ide>
<del> def test_svd_build(self, level=rlevel):
<add> def test_svd_build(self):
<ide> # Ticket 627.
<ide> a = array([[0., 1.], [1., 1.], [2., 1.], [3., 1.]])
<ide> m, n = a.shape
<ide><path>numpy/ma/tests/test_regression.py
<ide> suppress_warnings
<ide> )
<ide>
<del>rlevel = 1
<del>
<ide>
<ide> class TestRegression(object):
<del> def test_masked_array_create(self,level=rlevel):
<add> def test_masked_array_create(self):
<ide> # Ticket #17
<ide> x = np.ma.masked_array([0, 1, 2, 3, 0, 4, 5, 6],
<ide> mask=[0, 0, 0, 1, 1, 1, 0, 0])
<ide> assert_array_equal(np.ma.nonzero(x), [[1, 2, 6, 7]])
<ide>
<del> def test_masked_array(self,level=rlevel):
<add> def test_masked_array(self):
<ide> # Ticket #61
<ide> np.ma.array(1, mask=[1])
<ide>
<del> def test_mem_masked_where(self,level=rlevel):
<add> def test_mem_masked_where(self):
<ide> # Ticket #62
<ide> from numpy.ma import masked_where, MaskType
<ide> a = np.zeros((1, 1))
<ide> b = np.zeros(a.shape, MaskType)
<ide> c = masked_where(b, a)
<ide> a-c
<ide>
<del> def test_masked_array_multiply(self,level=rlevel):
<add> def test_masked_array_multiply(self):
<ide> # Ticket #254
<ide> a = np.ma.zeros((4, 1))
<ide> a[2, 0] = np.ma.masked
<ide> b = np.zeros((4, 2))
<ide> a*b
<ide> b*a
<ide>
<del> def test_masked_array_repeat(self, level=rlevel):
<add> def test_masked_array_repeat(self):
<ide> # Ticket #271
<ide> np.ma.array([1], mask=False).repeat(10)
<ide>
<ide><path>numpy/matrixlib/tests/test_regression.py
<ide> run_module_suite, assert_, assert_equal, assert_raises
<ide> )
<ide>
<del>rlevel = 1
<ide>
<ide> class TestRegression(object):
<del> def test_kron_matrix(self, level=rlevel):
<add> def test_kron_matrix(self):
<ide> # Ticket #71
<ide> x = np.matrix('[1 0; 1 0]')
<ide> assert_equal(type(np.kron(x, x)), type(x))
<ide>
<del> def test_matrix_properties(self,level=rlevel):
<add> def test_matrix_properties(self):
<ide> # Ticket #125
<ide> a = np.matrix([1.0], dtype=float)
<ide> assert_(type(a.real) is np.matrix)
<ide> def test_matrix_properties(self,level=rlevel):
<ide> assert_(type(c) is np.ndarray)
<ide> assert_(type(d) is np.ndarray)
<ide>
<del> def test_matrix_multiply_by_1d_vector(self, level=rlevel):
<add> def test_matrix_multiply_by_1d_vector(self):
<ide> # Ticket #473
<ide> def mul():
<ide> np.mat(np.eye(2))*np.ones(2)
<ide>
<ide> assert_raises(ValueError, mul)
<ide>
<del> def test_matrix_std_argmax(self,level=rlevel):
<add> def test_matrix_std_argmax(self):
<ide> # Ticket #83
<ide> x = np.asmatrix(np.random.uniform(0, 1, (3, 3)))
<ide> assert_equal(x.std().shape, ()) | 8 |
Go | Go | fix flaky testlogssincefuturefollow | 4928121992cbf3f40ec86909526534d90eb6482e | <ide><path>integration-cli/docker_cli_logs_test.go
<ide> import (
<ide> "io"
<ide> "os/exec"
<ide> "regexp"
<del> "strconv"
<ide> "strings"
<ide> "time"
<ide>
<ide> func (s *DockerSuite) TestLogsSince(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestLogsSinceFutureFollow(c *check.C) {
<ide> testRequires(c, DaemonIsLinux)
<del> out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", `for i in $(seq 1 5); do date +%s; sleep 1; done`)
<del> id := strings.TrimSpace(out)
<add> name := "testlogssincefuturefollow"
<add> out, _ := dockerCmd(c, "run", "-d", "--name", name, "busybox", "/bin/sh", "-c", `for i in $(seq 1 5); do echo log$i; sleep 1; done`)
<add>
<add> // Extract one timestamp from the log file to give us a starting point for
<add> // our `--since` argument. Because the log producer runs in the background,
<add> // we need to check repeatedly for some output to be produced.
<add> var timestamp string
<add> for i := 0; i != 5 && timestamp == ""; i++ {
<add> if out, _ = dockerCmd(c, "logs", "-t", name); out == "" {
<add> time.Sleep(time.Millisecond * 100) // Retry
<add> } else {
<add> timestamp = strings.Split(strings.Split(out, "\n")[0], " ")[0]
<add> }
<add> }
<ide>
<del> now := daemonTime(c).Unix()
<del> since := now + 2
<del> out, _ = dockerCmd(c, "logs", "-f", fmt.Sprintf("--since=%v", since), id)
<add> c.Assert(timestamp, checker.Not(checker.Equals), "")
<add> t, err := time.Parse(time.RFC3339Nano, timestamp)
<add> c.Assert(err, check.IsNil)
<add>
<add> since := t.Unix() + 2
<add> out, _ = dockerCmd(c, "logs", "-t", "-f", fmt.Sprintf("--since=%v", since), name)
<ide> lines := strings.Split(strings.TrimSpace(out), "\n")
<ide> c.Assert(lines, checker.Not(checker.HasLen), 0)
<ide> for _, v := range lines {
<del> ts, err := strconv.ParseInt(v, 10, 64)
<del> c.Assert(err, checker.IsNil, check.Commentf("cannot parse timestamp output from log: '%v'\nout=%s", v, out))
<del> c.Assert(ts >= since, checker.Equals, true, check.Commentf("earlier log found. since=%v logdate=%v", since, ts))
<add> ts, err := time.Parse(time.RFC3339Nano, strings.Split(v, " ")[0])
<add> c.Assert(err, checker.IsNil, check.Commentf("cannot parse timestamp output from log: '%v'", v))
<add> c.Assert(ts.Unix() >= since, checker.Equals, true, check.Commentf("earlier log found. since=%v logdate=%v", since, ts))
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestLogsFollowSlowStdoutConsumer(c *check.C) {
<ide> actual := bytes1 + bytes2
<ide> expected := 200000
<ide> c.Assert(actual, checker.Equals, expected)
<del>
<ide> }
<ide>
<ide> func (s *DockerSuite) TestLogsFollowGoroutinesWithStdout(c *check.C) { | 1 |
PHP | PHP | add ably entry | 5182e9c6de805e025fb4cfad63c210c3197002ab | <ide><path>config/broadcasting.php
<ide> ],
<ide> ],
<ide>
<add> 'ably' => [
<add> 'driver' => 'ably',
<add> 'key' => env('ABLY_KEY'),
<add> ],
<add>
<ide> 'redis' => [
<ide> 'driver' => 'redis',
<ide> 'connection' => 'default', | 1 |
PHP | PHP | add tests to cover any added or modified code | 7128e69832141b86271c65c27bc4f1c0e99af443 | <ide><path>tests/Database/DatabasePostgresBuilderTest.php
<add><?php
<add>
<add>namespace Illuminate\Tests\Database;
<add>
<add>use Illuminate\Database\Connection;
<add>use Illuminate\Database\Query\Processors\PostgresProcessor;
<add>use Illuminate\Database\Schema\Grammars\PostgresGrammar;
<add>use Illuminate\Database\Schema\PostgresBuilder;
<add>use Mockery as m;
<add>use PHPUnit\Framework\TestCase;
<add>
<add>class DatabasePostgresBuilderTest extends TestCase
<add>{
<add> protected function tearDown(): void
<add> {
<add> m::close();
<add> }
<add>
<add> /**
<add> * Ensure that when the reference is unqualified (i.e., does not contain a
<add> * database name or a schema), and the search_path is empty, the database
<add> * specified on the connection is used, and the default schema ('public')
<add> * is used.
<add> */
<add> public function testWhenSearchPathEmptyHasTableWithUnqualifiedReferenceIsCorrect()
<add> {
<add> $connection = $this->getConnection();
<add> $connection->shouldReceive('getConfig')->with('search_path')->andReturn(null);
<add> $grammar = m::mock(PostgresGrammar::class);
<add> $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar);
<add> $grammar->shouldReceive('compileTableExists')->andReturn("select * from information_schema.tables where table_catalog = ? and table_schema = ? and table_name = ? and table_type = 'BASE TABLE'");
<add> $connection->shouldReceive('select')->with("select * from information_schema.tables where table_catalog = ? and table_schema = ? and table_name = ? and table_type = 'BASE TABLE'", ['laravel', 'public', 'foo'])->andReturn(['countable_result']);
<add> $connection->shouldReceive('getTablePrefix');
<add> $connection->shouldReceive('getConfig')->with('database')->andReturn('laravel');
<add> $builder = $this->getBuilder($connection);
<add>
<add> $builder->hasTable('foo');
<add> }
<add>
<add> /**
<add> * Ensure that when the reference is unqualified (i.e., does not contain a
<add> * database name or a schema), and the first schema in the search_path is
<add> * NOT the default ('public'), the database specified on the connection is
<add> * used, and the first schema in the search_path is used.
<add> */
<add> public function testWhenSearchPathNotEmptyHasTableWithUnqualifiedSchemaReferenceIsCorrect()
<add> {
<add> $connection = $this->getConnection();
<add> $connection->shouldReceive('getConfig')->with('search_path')->andReturn('myapp,public');
<add> $grammar = m::mock(PostgresGrammar::class);
<add> $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar);
<add> $grammar->shouldReceive('compileTableExists')->andReturn("select * from information_schema.tables where table_catalog = ? and table_schema = ? and table_name = ? and table_type = 'BASE TABLE'");
<add> $connection->shouldReceive('select')->with("select * from information_schema.tables where table_catalog = ? and table_schema = ? and table_name = ? and table_type = 'BASE TABLE'", ['laravel', 'myapp', 'foo'])->andReturn(['countable_result']);
<add> $connection->shouldReceive('getTablePrefix');
<add> $connection->shouldReceive('getConfig')->with('database')->andReturn('laravel');
<add> $builder = $this->getBuilder($connection);
<add>
<add> $builder->hasTable('foo');
<add> }
<add>
<add> /**
<add> * Ensure that when the reference is qualified only with a schema, that
<add> * the database specified on the connection is used, and the specified
<add> * schema is used, even if it is not within the search_path.
<add> */
<add> public function testWhenSchemaNotInSearchPathHasTableWithQualifiedSchemaReferenceIsCorrect()
<add> {
<add> $connection = $this->getConnection();
<add> $connection->shouldReceive('getConfig')->with('search_path')->andReturn('public');
<add> $grammar = m::mock(PostgresGrammar::class);
<add> $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar);
<add> $grammar->shouldReceive('compileTableExists')->andReturn("select * from information_schema.tables where table_catalog = ? and table_schema = ? and table_name = ? and table_type = 'BASE TABLE'");
<add> $connection->shouldReceive('select')->with("select * from information_schema.tables where table_catalog = ? and table_schema = ? and table_name = ? and table_type = 'BASE TABLE'", ['laravel', 'myapp', 'foo'])->andReturn(['countable_result']);
<add> $connection->shouldReceive('getTablePrefix');
<add> $connection->shouldReceive('getConfig')->with('database')->andReturn('laravel');
<add> $builder = $this->getBuilder($connection);
<add>
<add> $builder->hasTable('myapp.foo');
<add> }
<add>
<add> /**
<add> * Ensure that when the reference is qualified with a database AND a schema,
<add> * and the database is NOT the database configured for the connection, the
<add> * specified database is used instead.
<add> */
<add> public function testWhenDatabaseNotDefaultHasTableWithFullyQualifiedReferenceIsCorrect()
<add> {
<add> $connection = $this->getConnection();
<add> $connection->shouldReceive('getConfig')->with('search_path')->andReturn('public');
<add> $grammar = m::mock(PostgresGrammar::class);
<add> $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar);
<add> $grammar->shouldReceive('compileTableExists')->andReturn("select * from information_schema.tables where table_catalog = ? and table_schema = ? and table_name = ? and table_type = 'BASE TABLE'");
<add> $connection->shouldReceive('select')->with("select * from information_schema.tables where table_catalog = ? and table_schema = ? and table_name = ? and table_type = 'BASE TABLE'", ['mydatabase', 'myapp', 'foo'])->andReturn(['countable_result']);
<add> $connection->shouldReceive('getTablePrefix');
<add> $connection->shouldReceive('getConfig')->with('database')->andReturn('laravel');
<add> $builder = $this->getBuilder($connection);
<add>
<add> $builder->hasTable('mydatabase.myapp.foo');
<add> }
<add>
<add> /**
<add> * Ensure that when the reference is unqualified (i.e., does not contain a
<add> * database name or a schema), and the search_path is empty, the database
<add> * specified on the connection is used, and the default schema ('public')
<add> * is used.
<add> */
<add> public function testWhenSearchPathEmptyGetColumnListingWithUnqualifiedReferenceIsCorrect()
<add> {
<add> $connection = $this->getConnection();
<add> $connection->shouldReceive('getConfig')->with('search_path')->andReturn(null);
<add> $grammar = m::mock(PostgresGrammar::class);
<add> $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar);
<add> $grammar->shouldReceive('compileColumnListing')->andReturn('select column_name from information_schema.columns where table_catalog = ? and table_schema = ? and table_name = ?');
<add> $connection->shouldReceive('select')->with('select column_name from information_schema.columns where table_catalog = ? and table_schema = ? and table_name = ?', ['laravel', 'public', 'foo'])->andReturn(['countable_result']);
<add> $connection->shouldReceive('getTablePrefix');
<add> $connection->shouldReceive('getConfig')->with('database')->andReturn('laravel');
<add> $processor = m::mock(PostgresProcessor::class);
<add> $connection->shouldReceive('getPostProcessor')->andReturn($processor);
<add> $processor->shouldReceive('processColumnListing')->andReturn(['some_column']);
<add> $builder = $this->getBuilder($connection);
<add>
<add> $builder->getColumnListing('foo');
<add> }
<add>
<add> /**
<add> * Ensure that when the reference is unqualified (i.e., does not contain a
<add> * database name or a schema), and the first schema in the search_path is
<add> * NOT the default ('public'), the database specified on the connection is
<add> * used, and the first schema in the search_path is used.
<add> */
<add> public function testWhenSearchPathNotEmptyGetColumnListingWithUnqualifiedSchemaReferenceIsCorrect()
<add> {
<add> $connection = $this->getConnection();
<add> $connection->shouldReceive('getConfig')->with('search_path')->andReturn('myapp,public');
<add> $grammar = m::mock(PostgresGrammar::class);
<add> $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar);
<add> $grammar->shouldReceive('compileColumnListing')->andReturn('select column_name from information_schema.columns where table_catalog = ? and table_schema = ? and table_name = ?');
<add> $connection->shouldReceive('select')->with('select column_name from information_schema.columns where table_catalog = ? and table_schema = ? and table_name = ?', ['laravel', 'myapp', 'foo'])->andReturn(['countable_result']);
<add> $connection->shouldReceive('getTablePrefix');
<add> $connection->shouldReceive('getConfig')->with('database')->andReturn('laravel');
<add> $processor = m::mock(PostgresProcessor::class);
<add> $connection->shouldReceive('getPostProcessor')->andReturn($processor);
<add> $processor->shouldReceive('processColumnListing')->andReturn(['some_column']);
<add> $builder = $this->getBuilder($connection);
<add>
<add> $builder->getColumnListing('foo');
<add> }
<add>
<add> /**
<add> * Ensure that when the reference is qualified only with a schema, that
<add> * the database specified on the connection is used, and the specified
<add> * schema is used, even if it is not within the search_path.
<add> */
<add> public function testWhenSchemaNotInSearchPathGetColumnListingWithQualifiedSchemaReferenceIsCorrect()
<add> {
<add> $connection = $this->getConnection();
<add> $connection->shouldReceive('getConfig')->with('search_path')->andReturn('public');
<add> $grammar = m::mock(PostgresGrammar::class);
<add> $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar);
<add> $grammar->shouldReceive('compileColumnListing')->andReturn('select column_name from information_schema.columns where table_catalog = ? and table_schema = ? and table_name = ?');
<add> $connection->shouldReceive('select')->with('select column_name from information_schema.columns where table_catalog = ? and table_schema = ? and table_name = ?', ['laravel', 'myapp', 'foo'])->andReturn(['countable_result']);
<add> $connection->shouldReceive('getTablePrefix');
<add> $connection->shouldReceive('getConfig')->with('database')->andReturn('laravel');
<add> $processor = m::mock(PostgresProcessor::class);
<add> $connection->shouldReceive('getPostProcessor')->andReturn($processor);
<add> $processor->shouldReceive('processColumnListing')->andReturn(['some_column']);
<add> $builder = $this->getBuilder($connection);
<add>
<add> $builder->getColumnListing('myapp.foo');
<add> }
<add>
<add> /**
<add> * Ensure that when the reference is qualified with a database AND a schema,
<add> * and the database is NOT the database configured for the connection, the
<add> * specified database is used instead.
<add> */
<add> public function testWhenDatabaseNotDefaultGetColumnListingWithFullyQualifiedReferenceIsCorrect()
<add> {
<add> $connection = $this->getConnection();
<add> $connection->shouldReceive('getConfig')->with('search_path')->andReturn('public');
<add> $grammar = m::mock(PostgresGrammar::class);
<add> $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar);
<add> $grammar->shouldReceive('compileColumnListing')->andReturn('select column_name from information_schema.columns where table_catalog = ? and table_schema = ? and table_name = ?');
<add> $connection->shouldReceive('select')->with('select column_name from information_schema.columns where table_catalog = ? and table_schema = ? and table_name = ?', ['mydatabase', 'myapp', 'foo'])->andReturn(['countable_result']);
<add> $connection->shouldReceive('getTablePrefix');
<add> $connection->shouldReceive('getConfig')->with('database')->andReturn('laravel');
<add> $processor = m::mock(PostgresProcessor::class);
<add> $connection->shouldReceive('getPostProcessor')->andReturn($processor);
<add> $processor->shouldReceive('processColumnListing')->andReturn(['some_column']);
<add> $builder = $this->getBuilder($connection);
<add>
<add> $builder->getColumnListing('mydatabase.myapp.foo');
<add> }
<add>
<add> protected function getConnection()
<add> {
<add> return m::mock(Connection::class);
<add> }
<add>
<add> protected function getBuilder($connection)
<add> {
<add> return new PostgresBuilder($connection);
<add> }
<add>
<add> protected function getGrammar()
<add> {
<add> return new PostgresGrammar;
<add> }
<add>}
<ide><path>tests/Database/DatabasePostgresSchemaGrammarTest.php
<ide> public function testDropAllTypesEscapesTableNames()
<ide> $this->assertSame('drop type "alpha","beta","gamma" cascade', $statement);
<ide> }
<ide>
<add> public function testCompileTableExists()
<add> {
<add> $statement = $this->getGrammar()->compileTableExists();
<add>
<add> $this->assertSame('select * from information_schema.tables where table_catalog = ? and table_schema = ? and table_name = ? and table_type = \'BASE TABLE\'', $statement);
<add> }
<add>
<add> public function testCompileColumnListing()
<add> {
<add> $statement = $this->getGrammar()->compileColumnListing();
<add>
<add> $this->assertSame('select column_name from information_schema.columns where table_catalog = ? and table_schema = ? and table_name = ?', $statement);
<add> }
<add>
<ide> protected function getConnection()
<ide> {
<ide> return m::mock(Connection::class); | 2 |
Ruby | Ruby | rescue only formulaunavailableerror | d6b5e4f2ed856badb572eea2bbc76d2335ec58ab | <ide><path>Library/Homebrew/cmd/audit.rb
<ide> def audit_deps
<ide> f.deps.each do |dep|
<ide> begin
<ide> dep_f = dep.to_formula
<del> rescue
<add> rescue FormulaUnavailableError
<ide> problem "Can't find dependency #{dep.name.inspect}."
<ide> end
<ide> | 1 |
Text | Text | change comma to semicolon | 817325d68e2aa3ee7bbfc2d7f453c7e656150e79 | <ide><path>curriculum/challenges/english/04-data-visualization/data-visualization-with-d3/create-a-bar-for-each-data-point-in-the-set.english.md
<ide> There are a few differences working with <code>rect</code> elements instead of <
<ide>
<ide> ## Instructions
<ide> <section id='instructions'>
<del>Use the <code>data()</code>, <code>enter()</code>, and <code>append()</code> methods to create and append a <code>rect</code> for each item in <code>dataset</code>. The bars should display all on top of each other, this will be fixed in the next challenge.
<add>Use the <code>data()</code>, <code>enter()</code>, and <code>append()</code> methods to create and append a <code>rect</code> for each item in <code>dataset</code>. The bars should display all on top of each other; this will be fixed in the next challenge.
<ide> </section>
<ide>
<ide> ## Tests | 1 |
Javascript | Javascript | add concurrentroot property to reactnativetypes | c96b78e0e7cd9e6ef7c0464748a50cf8510dde81 | <ide><path>packages/react-native-renderer/src/ReactNativeTypes.js
<ide> export type ReactFabricType = {
<ide> element: Element<ElementType>,
<ide> containerTag: number,
<ide> callback: ?() => void,
<add> concurrentRoot: ?boolean,
<ide> ): ?ElementRef<ElementType>,
<ide> unmountComponentAtNode(containerTag: number): void,
<ide> ...
<ide><path>scripts/rollup/shims/react-native/ReactFabric.js
<ide>
<ide> import {BatchedBridge} from 'react-native/Libraries/ReactPrivate/ReactNativePrivateInterface';
<ide>
<del>// TODO @sema: Adjust types
<del>import type {ReactNativeType} from './ReactNativeTypes';
<add>import type {ReactFabricType} from './ReactNativeTypes';
<ide>
<ide> let ReactFabric;
<ide>
<ide> if (global.RN$Bridgeless) {
<ide> BatchedBridge.registerCallableModule('ReactFabric', ReactFabric);
<ide> }
<ide>
<del>module.exports = (ReactFabric: ReactNativeType);
<add>module.exports = (ReactFabric: ReactFabricType); | 2 |
Javascript | Javascript | fix invocations of angular.mock.dump | e8e07502776e48bf48b83a836f7422d164cbb1d7 | <ide><path>test/helpers/testabilityPatch.js
<ide> function isCssVisible(node) {
<ide>
<ide> function assertHidden(node) {
<ide> if (isCssVisible(node)) {
<del> throw new Error('Node should be hidden but was visible: ' + angular.module.ngMock.dump(node));
<add> throw new Error('Node should be hidden but was visible: ' + angular.mock.dump(node));
<ide> }
<ide> }
<ide>
<ide> function assertVisible(node) {
<ide> if (!isCssVisible(node)) {
<del> throw new Error('Node should be visible but was hidden: ' + angular.module.ngMock.dump(node));
<add> throw new Error('Node should be visible but was hidden: ' + angular.mock.dump(node));
<ide> }
<ide> }
<ide> | 1 |
Go | Go | improve name generation on concurrent requests | 6ec86cb6e517bfb5ded818244b9db9510a2ed0b9 | <ide><path>daemon/daemon.go
<ide> import (
<ide> "github.com/dotcloud/docker/pkg/graphdb"
<ide> "github.com/dotcloud/docker/pkg/label"
<ide> "github.com/dotcloud/docker/pkg/mount"
<add> "github.com/dotcloud/docker/pkg/namesgenerator"
<ide> "github.com/dotcloud/docker/pkg/networkfs/resolvconf"
<ide> "github.com/dotcloud/docker/pkg/selinux"
<ide> "github.com/dotcloud/docker/pkg/sysinfo"
<ide> func (daemon *Daemon) register(container *Container, updateSuffixarray bool) err
<ide>
<ide> func (daemon *Daemon) ensureName(container *Container) error {
<ide> if container.Name == "" {
<del> name, err := generateRandomName(daemon)
<add> name, err := daemon.generateNewName(container.ID)
<ide> if err != nil {
<del> name = utils.TruncateID(container.ID)
<add> return err
<ide> }
<ide> container.Name = name
<ide>
<ide> if err := container.ToDisk(); err != nil {
<ide> utils.Debugf("Error saving container name %s", err)
<ide> }
<del> if !daemon.containerGraph.Exists(name) {
<del> if _, err := daemon.containerGraph.Set(name, container.ID); err != nil {
<del> utils.Debugf("Setting default id - %s", err)
<del> }
<del> }
<ide> }
<ide> return nil
<ide> }
<ide> func (daemon *Daemon) restore() error {
<ide> // Any containers that are left over do not exist in the graph
<ide> for _, container := range containers {
<ide> // Try to set the default name for a container if it exists prior to links
<del> container.Name, err = generateRandomName(daemon)
<add> container.Name, err = daemon.generateNewName(container.ID)
<ide> if err != nil {
<del> container.Name = utils.TruncateID(container.ID)
<del> }
<del>
<del> if _, err := daemon.containerGraph.Set(container.Name, container.ID); err != nil {
<ide> utils.Debugf("Setting default id - %s", err)
<ide> }
<ide> registerContainer(container)
<ide> func (daemon *Daemon) generateIdAndName(name string) (string, string, error) {
<ide> )
<ide>
<ide> if name == "" {
<del> name, err = generateRandomName(daemon)
<del> if err != nil {
<del> name = utils.TruncateID(id)
<del> }
<del> } else {
<del> if !validContainerNamePattern.MatchString(name) {
<del> return "", "", fmt.Errorf("Invalid container name (%s), only %s are allowed", name, validContainerNameChars)
<add> if name, err = daemon.generateNewName(id); err != nil {
<add> return "", "", err
<ide> }
<add> return id, name, nil
<ide> }
<add>
<add> if name, err = daemon.reserveName(id, name); err != nil {
<add> return "", "", err
<add> }
<add>
<add> return id, name, nil
<add>}
<add>
<add>func (daemon *Daemon) reserveName(id, name string) (string, error) {
<add> if !validContainerNamePattern.MatchString(name) {
<add> return "", fmt.Errorf("Invalid container name (%s), only %s are allowed", name, validContainerNameChars)
<add> }
<add>
<ide> if name[0] != '/' {
<ide> name = "/" + name
<ide> }
<del> // Set the enitity in the graph using the default name specified
<add>
<ide> if _, err := daemon.containerGraph.Set(name, id); err != nil {
<ide> if !graphdb.IsNonUniqueNameError(err) {
<del> return "", "", err
<add> return "", err
<ide> }
<ide>
<ide> conflictingContainer, err := daemon.GetByName(name)
<ide> if err != nil {
<ide> if strings.Contains(err.Error(), "Could not find entity") {
<del> return "", "", err
<add> return "", err
<ide> }
<ide>
<ide> // Remove name and continue starting the container
<ide> if err := daemon.containerGraph.Delete(name); err != nil {
<del> return "", "", err
<add> return "", err
<ide> }
<ide> } else {
<ide> nameAsKnownByUser := strings.TrimPrefix(name, "/")
<del> return "", "", fmt.Errorf(
<add> return "", fmt.Errorf(
<ide> "Conflict, The name %s is already assigned to %s. You have to delete (or rename) that container to be able to assign %s to a container again.", nameAsKnownByUser,
<ide> utils.TruncateID(conflictingContainer.ID), nameAsKnownByUser)
<ide> }
<ide> }
<del> return id, name, nil
<add> return name, nil
<add>}
<add>
<add>func (daemon *Daemon) generateNewName(id string) (string, error) {
<add> var name string
<add> for i := 1; i < 6; i++ {
<add> name = namesgenerator.GetRandomName(i)
<add> if name[0] != '/' {
<add> name = "/" + name
<add> }
<add>
<add> if _, err := daemon.containerGraph.Set(name, id); err != nil {
<add> if !graphdb.IsNonUniqueNameError(err) {
<add> return "", err
<add> }
<add> continue
<add> }
<add> return name, nil
<add> }
<add>
<add> name = "/" + utils.TruncateID(id)
<add> if _, err := daemon.containerGraph.Set(name, id); err != nil {
<add> return "", err
<add> }
<add> return name, nil
<ide> }
<ide>
<ide> func (daemon *Daemon) generateHostname(id string, config *runconfig.Config) {
<ide><path>daemon/utils.go
<ide> package daemon
<ide>
<ide> import (
<ide> "fmt"
<add> "strings"
<add>
<ide> "github.com/dotcloud/docker/nat"
<del> "github.com/dotcloud/docker/pkg/namesgenerator"
<ide> "github.com/dotcloud/docker/runconfig"
<del> "strings"
<ide> )
<ide>
<ide> func migratePortMappings(config *runconfig.Config, hostConfig *runconfig.HostConfig) error {
<ide> func mergeLxcConfIntoOptions(hostConfig *runconfig.HostConfig, driverConfig map[
<ide> driverConfig["lxc"] = lxc
<ide> }
<ide> }
<del>
<del>type checker struct {
<del> daemon *Daemon
<del>}
<del>
<del>func (c *checker) Exists(name string) bool {
<del> return c.daemon.containerGraph.Exists("/" + name)
<del>}
<del>
<del>// Generate a random and unique name
<del>func generateRandomName(daemon *Daemon) (string, error) {
<del> return namesgenerator.GenerateRandomName(&checker{daemon})
<del>}
<ide><path>pkg/namesgenerator/names-generator.go
<ide> import (
<ide> "time"
<ide> )
<ide>
<del>type NameChecker interface {
<del> Exists(name string) bool
<del>}
<del>
<ide> var (
<ide> left = [...]string{"happy", "jolly", "dreamy", "sad", "angry", "pensive", "focused", "sleepy", "grave", "distracted", "determined", "stoic", "stupefied", "sharp", "agitated", "cocky", "tender", "goofy", "furious", "desperate", "hopeful", "compassionate", "silly", "lonely", "condescending", "naughty", "kickass", "drunk", "boring", "nostalgic", "ecstatic", "insane", "cranky", "mad", "jovial", "sick", "hungry", "thirsty", "elegant", "backstabbing", "clever", "trusting", "loving", "suspicious", "berserk", "high", "romantic", "prickly", "evil"}
<ide> // Docker 0.7.x generates names from notable scientists and hackers.
<ide> var (
<ide> right = [...]string{"lovelace", "franklin", "tesla", "einstein", "bohr", "davinci", "pasteur", "nobel", "curie", "darwin", "turing", "ritchie", "torvalds", "pike", "thompson", "wozniak", "galileo", "euclid", "newton", "fermat", "archimedes", "poincare", "heisenberg", "feynman", "hawking", "fermi", "pare", "mccarthy", "engelbart", "babbage", "albattani", "ptolemy", "bell", "wright", "lumiere", "morse", "mclean", "brown", "bardeen", "brattain", "shockley", "goldstine", "hoover", "hopper", "bartik", "sammet", "jones", "perlman", "wilson", "kowalevski", "hypatia", "goodall", "mayer", "elion", "blackwell", "lalande", "kirch", "ardinghelli", "colden", "almeida", "leakey", "meitner", "mestorf", "rosalind", "sinoussi", "carson", "mcclintock", "yonath"}
<ide> )
<ide>
<del>func GenerateRandomName(checker NameChecker) (string, error) {
<del> retry := 5
<add>func GetRandomName(retry int) string {
<ide> rand.Seed(time.Now().UnixNano())
<add>
<add>begin:
<ide> name := fmt.Sprintf("%s_%s", left[rand.Intn(len(left))], right[rand.Intn(len(right))])
<del> for checker != nil && checker.Exists(name) && retry > 0 || name == "boring_wozniak" /* Steve Wozniak is not boring */ {
<del> name = fmt.Sprintf("%s%d", name, rand.Intn(10))
<del> retry = retry - 1
<add> if name == "boring_wozniak" /* Steve Wozniak is not boring */ {
<add> goto begin
<ide> }
<del> if retry == 0 {
<del> return name, fmt.Errorf("Error generating random name")
<add>
<add> if retry > 0 {
<add> name = fmt.Sprintf("%s%d", name, rand.Intn(10))
<ide> }
<del> return name, nil
<add> return name
<ide> }
<ide><path>pkg/namesgenerator/names-generator_test.go
<ide> import (
<ide> "testing"
<ide> )
<ide>
<del>type FalseChecker struct{}
<del>
<del>func (n *FalseChecker) Exists(name string) bool {
<del> return false
<del>}
<del>
<del>type TrueChecker struct{}
<del>
<del>func (n *TrueChecker) Exists(name string) bool {
<del> return true
<del>}
<del>
<del>func TestGenerateRandomName(t *testing.T) {
<del> if _, err := GenerateRandomName(&FalseChecker{}); err != nil {
<del> t.Error(err)
<del> }
<del>
<del> if _, err := GenerateRandomName(&TrueChecker{}); err == nil {
<del> t.Error("An error was expected")
<del> }
<del>
<del>}
<del>
<ide> // Make sure the generated names are awesome
<ide> func TestGenerateAwesomeNames(t *testing.T) {
<del> name, err := GenerateRandomName(&FalseChecker{})
<del> if err != nil {
<del> t.Error(err)
<del> }
<add> name := GetRandomName(0)
<ide> if !isAwesome(name) {
<ide> t.Fatalf("Generated name '%s' is not awesome.", name)
<ide> } | 4 |
Python | Python | add assert message for errorhandler exception type | 846ee2c62e369ed06190b8791088748bd3a83557 | <ide><path>src/flask/app.py
<ide> def _get_exc_class_and_code(exc_class_or_code):
<ide> else:
<ide> exc_class = exc_class_or_code
<ide>
<del> assert issubclass(exc_class, Exception)
<add> assert issubclass(
<add> exc_class, Exception
<add> ), "Custom exceptions must be subclasses of Exception."
<ide>
<ide> if issubclass(exc_class, HTTPException):
<ide> return exc_class, exc_class.code
<ide><path>tests/test_user_error_handler.py
<ide> def test_error_handler_no_match(app, client):
<ide> class CustomException(Exception):
<ide> pass
<ide>
<add> class UnacceptableCustomException(BaseException):
<add> pass
<add>
<ide> @app.errorhandler(CustomException)
<ide> def custom_exception_handler(e):
<ide> assert isinstance(e, CustomException)
<ide> return "custom"
<ide>
<add> with pytest.raises(
<add> AssertionError, match="Custom exceptions must be subclasses of Exception."
<add> ):
<add> app.register_error_handler(UnacceptableCustomException, None)
<add>
<ide> @app.errorhandler(500)
<ide> def handle_500(e):
<ide> assert isinstance(e, InternalServerError) | 2 |
PHP | PHP | fix discrepencies, thanks @admad | 2bd04dbf93209f4222f6391d65dfc1143bcfbe53 | <ide><path>src/Mailer/MailerAwareTrait.php
<ide> trait MailerAwareTrait
<ide> * Returns a mailer instance.
<ide> *
<ide> * @param string $name Mailer's name.
<del> * @param Cake\Mailer\Email|null $email Email instance.
<del> * @return Cake\Mailer\Mailer
<del> * @throws Cake\Mailer\Exception\MissingMailerException if undefined mailer class.
<add> * @param \Cake\Mailer\Email|null $email Email instance.
<add> * @return \Cake\Mailer\Mailer
<add> * @throws \Cake\Mailer\Exception\MissingMailerException if undefined mailer class.
<ide> */
<ide> public function getMailer($name, Email $email = null)
<ide> {
<ide> public function getMailer($name, Email $email = null)
<ide>
<ide> $className = App::className($name, 'Mailer', 'Mailer');
<ide>
<del> if (empty($className) || !class_exists($className)) {
<add> if (empty($className)) {
<ide> throw new MissingMailerException(compact('name'));
<ide> }
<ide>
<ide><path>tests/TestCase/Mailer/MailerAwareTraitTest.php
<ide> class Stub
<ide> class MailerAwareTraitTest extends TestCase
<ide> {
<ide>
<del>
<ide> /**
<ide> * Test getMailer
<ide> * | 2 |
Python | Python | detect failed auth for vps.net | 7b28b2d0d26bb8dde77da3c8aa8b9f9557dda490 | <ide><path>libcloud/drivers/vpsnet.py
<ide> VPS.net driver
<ide> """
<ide> from libcloud.providers import Provider
<del>from libcloud.types import NodeState
<add>from libcloud.types import NodeState, InvalidCredsException
<ide> from libcloud.base import Node, Response, ConnectionUserAndKey, NodeDriver, NodeSize, NodeImage, NodeLocation
<ide>
<ide> import base64
<ide> def parse_body(self):
<ide> except ValueError:
<ide> return self.body
<ide>
<add> def success(self):
<add> # vps.net wrongly uses 406 for invalid auth creds
<add> if self.status == 406 or self.status == 403:
<add> raise InvalidCredsException()
<add> return True
<add>
<ide> def parse_error(self):
<ide> try:
<ide> errors = json.loads(self.body)['errors'][0] | 1 |
Javascript | Javascript | handle enoent correctly on windows | 323120b5c943c0ec04c482c4414c23c01a27f4fc | <ide><path>lib/child_process.js
<ide> ChildProcess.prototype.spawn = function(options) {
<ide> if (stdio.handle) {
<ide> // when i === 0 - we're dealing with stdin
<ide> // (which is the only one writable pipe)
<del> stdio.socket = createSocket(stdio.handle, i > 0);
<add> stdio.socket = createSocket(self.pid !== 0 ? stdio.handle : null, i > 0);
<ide>
<del> if (i > 0) {
<add> if (i > 0 && self.pid !== 0) {
<ide> self._closesNeeded++;
<ide> stdio.socket.on('close', function() {
<ide> maybeClose(self); | 1 |
Javascript | Javascript | use promises for async tests | b0b4a1a96fe512c339d76082a181f2907012792f | <ide><path>packages/ember-application/tests/system/visit_test.js
<ide> import EmberObject from 'ember-runtime/system/object';
<ide> import isEnabled from 'ember-metal/features';
<ide> import inject from 'ember-runtime/inject';
<ide> import run from 'ember-metal/run_loop';
<add>import { onerrorDefault } from 'ember-runtime/ext/rsvp';
<ide> import Application from 'ember-application/system/application';
<ide> import ApplicationInstance from 'ember-application/system/application-instance';
<ide> import Route from 'ember-routing/system/route';
<ide> function createApplication(integration) {
<ide> return App;
<ide> }
<ide>
<add>function expectAsyncError() {
<add> Ember.RSVP.off('error');
<add>}
<add>
<ide> if (isEnabled('ember-application-visit')) {
<ide> QUnit.module('Ember.Application - visit()', {
<ide> teardown() {
<add> Ember.RSVP.on('error', onerrorDefault);
<add>
<ide> if (instance) {
<ide> run(instance, 'destroy');
<ide> instance = null;
<ide> if (isEnabled('ember-application-visit')) {
<ide> // instance initializer that would normally get called on DOM ready
<ide> // does not fire.
<ide> QUnit.test('Applications with autoboot set to false do not autoboot', function(assert) {
<del> QUnit.expect(4);
<del> QUnit.stop();
<add> function delay(time) {
<add> return new Ember.RSVP.Promise(resolve => Ember.run.later(resolve, time));
<add> }
<ide>
<ide> let appBooted = 0;
<ide> let instanceBooted = 0;
<ide> if (isEnabled('ember-application-visit')) {
<ide> });
<ide>
<ide> // Continue after 500ms
<del> setTimeout(function() {
<del> QUnit.start();
<del> ok(appBooted === 0, '500ms elapsed without app being booted');
<del> ok(instanceBooted === 0, '500ms elapsed without instances being booted');
<del>
<del> QUnit.stop();
<del>
<del> run(function() {
<del> App.boot().then(
<del> () => {
<del> QUnit.start();
<del> assert.ok(appBooted === 1, 'app should boot when manually calling `app.boot()`');
<del> assert.ok(instanceBooted === 0, 'no instances should be booted automatically when manually calling `app.boot()');
<del> },
<del> (error) => {
<del> QUnit.start();
<del> assert.ok(false, 'the boot process failed with ' + error);
<del> }
<del> );
<del> });
<del> }, 500);
<add> return delay(500).then(() => {
<add> assert.ok(appBooted === 0, '500ms elapsed without app being booted');
<add> assert.ok(instanceBooted === 0, '500ms elapsed without instances being booted');
<add>
<add> return run(App, 'boot');
<add> }).then(() => {
<add> assert.ok(appBooted === 1, 'app should boot when manually calling `app.boot()`');
<add> assert.ok(instanceBooted === 0, 'no instances should be booted automatically when manually calling `app.boot()');
<add> });
<ide> });
<ide>
<ide> QUnit.test('calling visit() on app without first calling boot() should boot the app', function(assert) {
<del> QUnit.expect(2);
<del> QUnit.stop();
<del>
<ide> let appBooted = 0;
<ide> let instanceBooted = 0;
<ide>
<ide> if (isEnabled('ember-application-visit')) {
<ide> instanceBooted++;
<ide> }
<ide> });
<add> });
<ide>
<del> App.visit('/').then(
<del> () => {
<del> QUnit.start();
<del> assert.ok(appBooted === 1, 'the app should be booted`');
<del> assert.ok(instanceBooted === 1, 'an instances should be booted');
<del> },
<del> (error) => {
<del> QUnit.start();
<del> assert.ok(false, 'the boot process failed with ' + error);
<del> }
<del> );
<add> return run(App, 'visit', '/').then(() => {
<add> assert.ok(appBooted === 1, 'the app should be booted`');
<add> assert.ok(instanceBooted === 1, 'an instances should be booted');
<ide> });
<ide> });
<ide>
<ide> QUnit.test('calling visit() on an already booted app should not boot it again', function(assert) {
<del> QUnit.expect(6);
<del> QUnit.stop();
<del>
<ide> let appBooted = 0;
<ide> let instanceBooted = 0;
<ide>
<ide> if (isEnabled('ember-application-visit')) {
<ide> instanceBooted++;
<ide> }
<ide> });
<add> });
<ide>
<del> App.boot().then(() => {
<del> QUnit.start();
<del> assert.ok(appBooted === 1, 'the app should be booted');
<del> assert.ok(instanceBooted === 0, 'no instances should be booted');
<del> QUnit.stop();
<del>
<del> return App.visit('/');
<del> }).then(() => {
<del> QUnit.start();
<del> assert.ok(appBooted === 1, 'the app should not be booted again');
<del> assert.ok(instanceBooted === 1, 'an instance should be booted');
<del> QUnit.stop();
<del>
<del> return App.visit('/');
<del> }).then(() => {
<del> QUnit.start();
<del> assert.ok(appBooted === 1, 'the app should not be booted again');
<del> assert.ok(instanceBooted === 2, 'another instance should be booted');
<del> }).catch((error) => {
<del> QUnit.start();
<del> assert.ok(false, 'the boot process failed with ' + error);
<del> });
<add> return run(App, 'boot').then(() => {
<add> assert.ok(appBooted === 1, 'the app should be booted');
<add> assert.ok(instanceBooted === 0, 'no instances should be booted');
<add>
<add> return run(App, 'visit', '/');
<add> }).then(() => {
<add> assert.ok(appBooted === 1, 'the app should not be booted again');
<add> assert.ok(instanceBooted === 1, 'an instance should be booted');
<add>
<add> return run(App, 'visit', '/');
<add> }).then(() => {
<add> assert.ok(appBooted === 1, 'the app should not be booted again');
<add> assert.ok(instanceBooted === 2, 'another instance should be booted');
<ide> });
<ide> });
<ide>
<ide> QUnit.test('visit() rejects on application boot failure', function(assert) {
<del> QUnit.expect(2);
<del> QUnit.stop();
<del>
<ide> run(function() {
<ide> createApplication();
<ide>
<ide> if (isEnabled('ember-application-visit')) {
<ide> throw new Error('boot failure');
<ide> }
<ide> });
<add> });
<ide>
<del> App.visit('/').then(
<del> () => {
<del> QUnit.start();
<del> assert.ok(false, 'It should not resolve the promise');
<del> },
<del> (error) => {
<del> QUnit.start();
<del> assert.ok(error instanceof Error, 'It should reject the promise with the boot error');
<del> assert.equal(error.message, 'boot failure');
<del> }
<del> );
<add> expectAsyncError();
<add>
<add> return run(App, 'visit', '/').then(() => {
<add> assert.ok(false, 'It should not resolve the promise');
<add> }, error => {
<add> assert.ok(error instanceof Error, 'It should reject the promise with the boot error');
<add> assert.equal(error.message, 'boot failure');
<ide> });
<ide> });
<ide>
<ide> QUnit.test('visit() rejects on instance boot failure', function(assert) {
<del> QUnit.expect(2);
<del> QUnit.stop();
<del>
<ide> run(function() {
<ide> createApplication();
<ide>
<ide> if (isEnabled('ember-application-visit')) {
<ide> throw new Error('boot failure');
<ide> }
<ide> });
<add> });
<ide>
<del> App.visit('/').then(
<del> () => {
<del> QUnit.start();
<del> assert.ok(false, 'It should not resolve the promise');
<del> },
<del> (error) => {
<del> QUnit.start();
<del> assert.ok(error instanceof Error, 'It should reject the promise with the boot error');
<del> assert.equal(error.message, 'boot failure');
<del> }
<del> );
<add> expectAsyncError();
<add>
<add> return run(App, 'visit', '/').then(() => {
<add> assert.ok(false, 'It should not resolve the promise');
<add> }, error => {
<add> assert.ok(error instanceof Error, 'It should reject the promise with the boot error');
<add> assert.equal(error.message, 'boot failure');
<ide> });
<ide> });
<ide>
<ide> QUnit.test('visit() follows redirects', function(assert) {
<del> QUnit.expect(2);
<del> QUnit.stop();
<del>
<ide> run(function() {
<ide> createApplication();
<ide>
<ide> if (isEnabled('ember-application-visit')) {
<ide> this.transitionTo('c', params.b);
<ide> }
<ide> }));
<add> });
<ide>
<del> App.visit('/a').then(
<del> (instance) => {
<del> QUnit.start();
<del> assert.ok(instance instanceof ApplicationInstance, 'promise is resolved with an ApplicationInstance');
<del> assert.equal(instance.getURL(), '/c/zomg', 'It should follow all redirects');
<del> },
<del> (error) => {
<del> QUnit.start();
<del> assert.ok(false, 'The visit() promise was rejected: ' + error);
<del> }
<del> );
<add> return run(App, 'visit', '/a').then(instance => {
<add> assert.ok(instance instanceof ApplicationInstance, 'promise is resolved with an ApplicationInstance');
<add> assert.equal(instance.getURL(), '/c/zomg', 'It should follow all redirects');
<ide> });
<ide> });
<ide>
<ide> QUnit.test('visit() rejects if an error occured during a transition', function(assert) {
<del> QUnit.expect(2);
<del> QUnit.stop();
<del>
<ide> run(function() {
<ide> createApplication();
<ide>
<ide> if (isEnabled('ember-application-visit')) {
<ide> throw new Error('transition failure');
<ide> }
<ide> }));
<add> });
<ide>
<del> App.visit('/a').then(
<del> () => {
<del> QUnit.start();
<del> assert.ok(false, 'It should not resolve the promise');
<del> },
<del> (error) => {
<del> QUnit.start();
<del> assert.ok(error instanceof Error, 'It should reject the promise with the boot error');
<del> assert.equal(error.message, 'transition failure');
<del> }
<del> );
<add> expectAsyncError();
<add>
<add> return run(App, 'visit', '/a').then(() => {
<add> assert.ok(false, 'It should not resolve the promise');
<add> }, error => {
<add> assert.ok(error instanceof Error, 'It should reject the promise with the boot error');
<add> assert.equal(error.message, 'transition failure');
<ide> });
<ide> });
<ide>
<ide> QUnit.test('visit() chain', function(assert) {
<del> QUnit.expect(8);
<del> QUnit.stop();
<del>
<ide> run(function() {
<ide> createApplication();
<ide>
<ide> if (isEnabled('ember-application-visit')) {
<ide> this.route('b');
<ide> this.route('c');
<ide> });
<add> });
<ide>
<del> App.visit('/').then((instance) => {
<del> QUnit.start();
<del> assert.ok(instance instanceof ApplicationInstance, 'promise is resolved with an ApplicationInstance');
<del> assert.equal(instance.getURL(), '/');
<del>
<del> QUnit.stop();
<del> return instance.visit('/a');
<del> }).then((instance) => {
<del> QUnit.start();
<del> assert.ok(instance instanceof ApplicationInstance, 'promise is resolved with an ApplicationInstance');
<del> assert.equal(instance.getURL(), '/a');
<del>
<del> QUnit.stop();
<del> return instance.visit('/b');
<del> }).then((instance) => {
<del> QUnit.start();
<del> assert.ok(instance instanceof ApplicationInstance, 'promise is resolved with an ApplicationInstance');
<del> assert.equal(instance.getURL(), '/b');
<del>
<del> QUnit.stop();
<del> return instance.visit('/c');
<del> }).then((instance) => {
<del> QUnit.start();
<del> assert.ok(instance instanceof ApplicationInstance, 'promise is resolved with an ApplicationInstance');
<del> assert.equal(instance.getURL(), '/c');
<del> }).catch((error) => {
<del> QUnit.start();
<del> assert.ok(false, 'The visit() promise was rejected: ' + error);
<del> });
<add> return run(App, 'visit', '/').then(instance => {
<add> assert.ok(instance instanceof ApplicationInstance, 'promise is resolved with an ApplicationInstance');
<add> assert.equal(instance.getURL(), '/');
<add>
<add> return instance.visit('/a');
<add> }).then(instance => {
<add> assert.ok(instance instanceof ApplicationInstance, 'promise is resolved with an ApplicationInstance');
<add> assert.equal(instance.getURL(), '/a');
<add>
<add> return instance.visit('/b');
<add> }).then(instance => {
<add> assert.ok(instance instanceof ApplicationInstance, 'promise is resolved with an ApplicationInstance');
<add> assert.equal(instance.getURL(), '/b');
<add>
<add> return instance.visit('/c');
<add> }).then(instance => {
<add> assert.ok(instance instanceof ApplicationInstance, 'promise is resolved with an ApplicationInstance');
<add> assert.equal(instance.getURL(), '/c');
<ide> });
<ide> });
<ide>
<ide> QUnit.test('visit() returns a promise that resolves when the view has rendered', function(assert) {
<del> QUnit.expect(3);
<del> QUnit.stop();
<del>
<ide> run(function() {
<ide> createApplication();
<ide>
<ide> if (isEnabled('ember-application-visit')) {
<ide>
<ide> assert.strictEqual(Ember.$('#qunit-fixture').children().length, 0, 'there are no elements in the fixture element');
<ide>
<del> run(function() {
<del> App.visit('/').then(function(instance) {
<del> QUnit.start();
<del> assert.ok(instance instanceof ApplicationInstance, 'promise is resolved with an ApplicationInstance');
<del> assert.equal(Ember.$('#qunit-fixture > .ember-view h1').text(), 'Hello world', 'the application was rendered once the promise resolves');
<del> }, function(error) {
<del> QUnit.start();
<del> assert.ok(false, 'The visit() promise was rejected: ' + error);
<del> });
<add> return run(App, 'visit', '/').then(instance => {
<add> assert.ok(instance instanceof ApplicationInstance, 'promise is resolved with an ApplicationInstance');
<add> assert.equal(Ember.$('#qunit-fixture > .ember-view h1').text(), 'Hello world', 'the application was rendered once the promise resolves');
<ide> });
<ide> });
<ide>
<ide> QUnit.test('Views created via visit() are not added to the global views hash', function(assert) {
<del> QUnit.expect(6);
<del> QUnit.stop();
<del>
<ide> run(function() {
<ide> createApplication();
<ide>
<ide> if (isEnabled('ember-application-visit')) {
<ide>
<ide> assert.strictEqual(Ember.$('#qunit-fixture').children().length, 0, 'there are no elements in the fixture element');
<ide>
<del> run(function() {
<del> App.visit('/').then(function(instance) {
<del> QUnit.start();
<del> assert.ok(instance instanceof ApplicationInstance, 'promise is resolved with an ApplicationInstance');
<del> assert.equal(Ember.$('#qunit-fixture > #my-cool-app h1').text(), 'Hello world', 'the application was rendered once the promise resolves');
<del> assert.strictEqual(View.views['my-cool-app'], undefined, 'view was not registered globally');
<del>
<del> function lookup(fullName) {
<del> if (isEnabled('ember-registry-container-reform')) {
<del> return instance.lookup(fullName);
<del> } else {
<del> return instance.container.lookup(fullName);
<del> }
<add> return run(App, 'visit', '/').then(instance => {
<add> assert.ok(instance instanceof ApplicationInstance, 'promise is resolved with an ApplicationInstance');
<add> assert.equal(Ember.$('#qunit-fixture > #my-cool-app h1').text(), 'Hello world', 'the application was rendered once the promise resolves');
<add> assert.strictEqual(View.views['my-cool-app'], undefined, 'view was not registered globally');
<add>
<add> function lookup(fullName) {
<add> if (isEnabled('ember-registry-container-reform')) {
<add> return instance.lookup(fullName);
<add> } else {
<add> return instance.container.lookup(fullName);
<ide> }
<add> }
<ide>
<del> assert.ok(lookup('-view-registry:main')['my-cool-app'] instanceof View, 'view was registered on the instance\'s view registry');
<del> assert.ok(lookup('-view-registry:main')['child-view'] instanceof View, 'child view was registered on the instance\'s view registry');
<del> }, function(error) {
<del> QUnit.start();
<del> assert.ok(false, 'The visit() promise was rejected: ' + error);
<del> });
<add> assert.ok(lookup('-view-registry:main')['my-cool-app'] instanceof View, 'view was registered on the instance\'s view registry');
<add> assert.ok(lookup('-view-registry:main')['child-view'] instanceof View, 'child view was registered on the instance\'s view registry');
<ide> });
<ide> });
<ide>
<ide> if (isEnabled('ember-application-visit')) {
<ide> }
<ide> });
<ide>
<del> QUnit.test('FastBoot-style setup', function(assert) {
<del> QUnit.expect(15);
<del> QUnit.stop();
<add> if (document.implementation && typeof document.implementation.createHTMLDocument === 'function') {
<add> QUnit.test('FastBoot-style setup', function(assert) {
<add> let initCalled = false;
<add> let didInsertElementCalled = false;
<ide>
<del> let initCalled = false;
<del> let didInsertElementCalled = false;
<del>
<del> run(function() {
<del> createApplication(true);
<add> run(function() {
<add> createApplication(true);
<ide>
<del> App.Router.map(function() {
<del> this.route('a');
<del> this.route('b');
<del> });
<add> App.Router.map(function() {
<add> this.route('a');
<add> this.route('b');
<add> });
<ide>
<del> App.register('template:application', compile('<h1>Hello world</h1>\n{{outlet}}'));
<add> App.register('template:application', compile('<h1>Hello world</h1>\n{{outlet}}'));
<ide>
<del> App.register('template:a', compile('<h2>Welcome to {{x-foo page="A"}}</h2>'));
<add> App.register('template:a', compile('<h2>Welcome to {{x-foo page="A"}}</h2>'));
<ide>
<del> App.register('template:b', compile('<h2>{{x-foo page="B"}}</h2>'));
<add> App.register('template:b', compile('<h2>{{x-foo page="B"}}</h2>'));
<ide>
<del> App.register('template:components/x-foo', compile('Page {{page}}'));
<add> App.register('template:components/x-foo', compile('Page {{page}}'));
<ide>
<del> App.register('component:x-foo', Component.extend({
<del> tagName: 'span',
<del> init() {
<del> this._super();
<del> initCalled = true;
<del> },
<del> didInsertElement() {
<del> didInsertElementCalled = true;
<del> }
<del> }));
<del> });
<add> App.register('component:x-foo', Component.extend({
<add> tagName: 'span',
<add> init() {
<add> this._super();
<add> initCalled = true;
<add> },
<add> didInsertElement() {
<add> didInsertElementCalled = true;
<add> }
<add> }));
<add> });
<ide>
<del> assert.strictEqual(Ember.$('#qunit-fixture').children().length, 0, 'there are no elements in the fixture element');
<add> assert.strictEqual(Ember.$('#qunit-fixture').children().length, 0, 'there are no elements in the fixture element');
<ide>
<del> function makeFakeDom() {
<del> // TODO: use simple-dom
<del> return document.implementation.createHTMLDocument();
<del> }
<add> function makeForiegnDocument() {
<add> // TODO: use simple-dom
<add> return document.implementation.createHTMLDocument();
<add> }
<ide>
<del> let a = run(function() {
<del> let dom = makeFakeDom();
<add> let a = run(function() {
<add> let dom = makeForiegnDocument();
<ide>
<del> return App.visit('/a', { isBrowser: false, document: dom, rootElement: dom.body }).then(instance => {
<del> QUnit.start();
<del> assert.ok(instance instanceof ApplicationInstance, 'promise is resolved with an ApplicationInstance');
<del> assert.equal(instance.getURL(), '/a');
<add> return App.visit('/a', { isBrowser: false, document: dom, rootElement: dom.body }).then(instance => {
<add> QUnit.start();
<add> assert.ok(instance instanceof ApplicationInstance, 'promise is resolved with an ApplicationInstance');
<add> assert.equal(instance.getURL(), '/a');
<ide>
<del> let serialized = dom.body.innerHTML;
<del> let $parsed = Ember.$(serialized);
<add> let serialized = dom.body.innerHTML;
<add> let $parsed = Ember.$(serialized);
<ide>
<del> assert.equal($parsed.find('h1').text(), 'Hello world');
<del> assert.equal($parsed.find('h2').text(), 'Welcome to Page A');
<add> assert.equal($parsed.find('h1').text(), 'Hello world');
<add> assert.equal($parsed.find('h2').text(), 'Welcome to Page A');
<ide>
<del> assert.ok(initCalled, 'Component#init should be called');
<del> assert.ok(!didInsertElementCalled, 'Component#didInsertElement should not be called');
<add> assert.ok(initCalled, 'Component#init should be called');
<add> assert.ok(!didInsertElementCalled, 'Component#didInsertElement should not be called');
<ide>
<del> assert.strictEqual(Ember.$('#qunit-fixture').children().length, 0, 'there are no elements in the fixture element');
<del> QUnit.stop();
<add> assert.strictEqual(Ember.$('#qunit-fixture').children().length, 0, 'there are no elements in the fixture element');
<add> QUnit.stop();
<add> });
<ide> });
<del> });
<ide>
<del> let b = run(function() {
<del> let dom = makeFakeDom();
<add> let b = run(function() {
<add> let dom = makeForiegnDocument();
<ide>
<del> return App.visit('/b', { isBrowser: false, document: dom, rootElement: dom.body }).then(instance => {
<del> QUnit.start();
<del> assert.ok(instance instanceof ApplicationInstance, 'promise is resolved with an ApplicationInstance');
<del> assert.equal(instance.getURL(), '/b');
<add> return App.visit('/b', { isBrowser: false, document: dom, rootElement: dom.body }).then(instance => {
<add> QUnit.start();
<add> assert.ok(instance instanceof ApplicationInstance, 'promise is resolved with an ApplicationInstance');
<add> assert.equal(instance.getURL(), '/b');
<ide>
<del> let serialized = dom.body.innerHTML;
<del> let $parsed = Ember.$(serialized);
<add> let serialized = dom.body.innerHTML;
<add> let $parsed = Ember.$(serialized);
<ide>
<del> assert.equal($parsed.find('h1').text(), 'Hello world');
<del> assert.equal($parsed.find('h2').text(), 'Page B');
<add> assert.equal($parsed.find('h1').text(), 'Hello world');
<add> assert.equal($parsed.find('h2').text(), 'Page B');
<ide>
<del> assert.ok(initCalled, 'Component#init should be called');
<del> assert.ok(!didInsertElementCalled, 'Component#didInsertElement should not be called');
<add> assert.ok(initCalled, 'Component#init should be called');
<add> assert.ok(!didInsertElementCalled, 'Component#didInsertElement should not be called');
<ide>
<del> assert.strictEqual(Ember.$('#qunit-fixture').children().length, 0, 'there are no elements in the fixture element');
<del> QUnit.stop();
<add> assert.strictEqual(Ember.$('#qunit-fixture').children().length, 0, 'there are no elements in the fixture element');
<add> QUnit.stop();
<add> });
<ide> });
<del> });
<ide>
<del> Ember.RSVP.all([a, b]).finally(() => QUnit.start());
<del> });
<add> return Ember.RSVP.all([a, b]);
<add> });
<add> }
<ide>
<ide> QUnit.test('Ember Islands-style setup', function(assert) {
<del> QUnit.expect(14);
<del> QUnit.stop();
<del>
<ide> let xFooInitCalled = false;
<ide> let xFooDidInsertElementCalled = false;
<ide>
<ide> if (isEnabled('ember-application-visit')) {
<ide> let $bar = Ember.$('<div />').appendTo('#qunit-fixture');
<ide>
<ide> let data = encodeURIComponent(JSON.stringify({ name: 'Godfrey' }));
<del> run(function() {
<del> Ember.RSVP.all([
<del> App.visit(`/x-foo?data=${data}`, { rootElement: $foo[0] }),
<del> App.visit('/x-bar', { rootElement: $bar[0] })
<del> ]).then(() => {
<del> QUnit.start();
<del>
<del> assert.ok(xFooInitCalled);
<del> assert.ok(xFooDidInsertElementCalled);
<ide>
<del> assert.ok(xBarInitCalled);
<del> assert.ok(xBarDidInsertElementCalled);
<add> return Ember.RSVP.all([
<add> run(App, 'visit', `/x-foo?data=${data}`, { rootElement: $foo[0] }),
<add> run(App, 'visit', '/x-bar', { rootElement: $bar[0] })
<add> ]).then(() => {
<add> assert.ok(xFooInitCalled);
<add> assert.ok(xFooDidInsertElementCalled);
<ide>
<del> assert.equal($foo.find('h1').text(), 'X-Foo');
<del> assert.equal($foo.find('p').text(), 'Hello Godfrey, I have been clicked 0 times (0 times combined)!');
<del> assert.ok($foo.text().indexOf('X-Bar') === -1);
<add> assert.ok(xBarInitCalled);
<add> assert.ok(xBarDidInsertElementCalled);
<ide>
<del> assert.equal($bar.find('h1').text(), 'X-Bar');
<del> assert.equal($bar.find('button').text(), 'Join 0 others in clicking me!');
<del> assert.ok($bar.text().indexOf('X-Foo') === -1);
<add> assert.equal($foo.find('h1').text(), 'X-Foo');
<add> assert.equal($foo.find('p').text(), 'Hello Godfrey, I have been clicked 0 times (0 times combined)!');
<add> assert.ok($foo.text().indexOf('X-Bar') === -1);
<ide>
<del> run(function() {
<del> $foo.find('x-foo').click();
<del> });
<add> assert.equal($bar.find('h1').text(), 'X-Bar');
<add> assert.equal($bar.find('button').text(), 'Join 0 others in clicking me!');
<add> assert.ok($bar.text().indexOf('X-Foo') === -1);
<ide>
<del> assert.equal($foo.find('p').text(), 'Hello Godfrey, I have been clicked 1 times (1 times combined)!');
<del> assert.equal($bar.find('button').text(), 'Join 1 others in clicking me!');
<add> run(function() {
<add> $foo.find('x-foo').click();
<add> });
<ide>
<del> run(function() {
<del> $bar.find('button').click();
<del> $bar.find('button').click();
<del> });
<add> assert.equal($foo.find('p').text(), 'Hello Godfrey, I have been clicked 1 times (1 times combined)!');
<add> assert.equal($bar.find('button').text(), 'Join 1 others in clicking me!');
<ide>
<del> assert.equal($foo.find('p').text(), 'Hello Godfrey, I have been clicked 1 times (3 times combined)!');
<del> assert.equal($bar.find('button').text(), 'Join 3 others in clicking me!');
<add> run(function() {
<add> $bar.find('button').click();
<add> $bar.find('button').click();
<ide> });
<add>
<add> assert.equal($foo.find('p').text(), 'Hello Godfrey, I have been clicked 1 times (3 times combined)!');
<add> assert.equal($bar.find('button').text(), 'Join 3 others in clicking me!');
<ide> });
<ide> });
<ide>
<ide> QUnit.test('Resource-discovery setup', function(assert) {
<del> QUnit.expect(26);
<del> QUnit.stop();
<del>
<ide> let xFooInstances = 0;
<ide>
<ide> run(function() {
<ide> if (isEnabled('ember-application-visit')) {
<ide> }
<ide> }
<ide>
<del> let a = run(function() {
<del> return App.visit('/a', { isBrowser: false, shouldRender: false }).then((instance) => {
<del> QUnit.start();
<del> assert.ok(instance instanceof ApplicationInstance, 'promise is resolved with an ApplicationInstance');
<add> let a = run(App, 'visit', '/a', { isBrowser: false, shouldRender: false }).then(instance => {
<add> assert.ok(instance instanceof ApplicationInstance, 'promise is resolved with an ApplicationInstance');
<ide>
<del> assert.strictEqual(Ember.$('#qunit-fixture').children().length, 0, 'there are no elements in the fixture element');
<del> assert.strictEqual(xFooInstances, 0, 'did not create any x-foo components');
<add> assert.strictEqual(Ember.$('#qunit-fixture').children().length, 0, 'there are no elements in the fixture element');
<add> assert.strictEqual(xFooInstances, 0, 'did not create any x-foo components');
<ide>
<del> let viewRegistry = lookup(instance, '-view-registry:main');
<del> assert.strictEqual(Object.keys(viewRegistry).length, 0, 'did not create any views');
<add> let viewRegistry = lookup(instance, '-view-registry:main');
<add> assert.strictEqual(Object.keys(viewRegistry).length, 0, 'did not create any views');
<ide>
<del> let networkService = lookup(instance, 'service:network');
<del> assert.deepEqual(networkService.get('requests'), ['/a', '/b', '/c']);
<del> QUnit.stop();
<del> });
<add> let networkService = lookup(instance, 'service:network');
<add> assert.deepEqual(networkService.get('requests'), ['/a', '/b', '/c']);
<ide> });
<ide>
<del> let b = run(function() {
<del> return App.visit('/b', { isBrowser: false, shouldRender: false }).then((instance) => {
<del> QUnit.start();
<del> assert.ok(instance instanceof ApplicationInstance, 'promise is resolved with an ApplicationInstance');
<add> let b = run(App, 'visit', '/b', { isBrowser: false, shouldRender: false }).then(instance => {
<add> assert.ok(instance instanceof ApplicationInstance, 'promise is resolved with an ApplicationInstance');
<ide>
<del> assert.strictEqual(Ember.$('#qunit-fixture').children().length, 0, 'there are no elements in the fixture element');
<del> assert.strictEqual(xFooInstances, 0, 'did not create any x-foo components');
<add> assert.strictEqual(Ember.$('#qunit-fixture').children().length, 0, 'there are no elements in the fixture element');
<add> assert.strictEqual(xFooInstances, 0, 'did not create any x-foo components');
<ide>
<del> let viewRegistry = lookup(instance, '-view-registry:main');
<del> assert.strictEqual(Object.keys(viewRegistry).length, 0, 'did not create any views');
<add> let viewRegistry = lookup(instance, '-view-registry:main');
<add> assert.strictEqual(Object.keys(viewRegistry).length, 0, 'did not create any views');
<ide>
<del> let networkService = lookup(instance, 'service:network');
<del> assert.deepEqual(networkService.get('requests'), ['/b', '/c']);
<del> QUnit.stop();
<del> });
<add> let networkService = lookup(instance, 'service:network');
<add> assert.deepEqual(networkService.get('requests'), ['/b', '/c']);
<ide> });
<ide>
<del> let c = run(function() {
<del> return App.visit('/c', { isBrowser: false, shouldRender: false }).then((instance) => {
<del> QUnit.start();
<del> assert.ok(instance instanceof ApplicationInstance, 'promise is resolved with an ApplicationInstance');
<add> let c = run(App, 'visit', '/c', { isBrowser: false, shouldRender: false }).then(instance => {
<add> assert.ok(instance instanceof ApplicationInstance, 'promise is resolved with an ApplicationInstance');
<ide>
<del> assert.strictEqual(Ember.$('#qunit-fixture').children().length, 0, 'there are no elements in the fixture element');
<del> assert.strictEqual(xFooInstances, 0, 'did not create any x-foo components');
<add> assert.strictEqual(Ember.$('#qunit-fixture').children().length, 0, 'there are no elements in the fixture element');
<add> assert.strictEqual(xFooInstances, 0, 'did not create any x-foo components');
<ide>
<del> let viewRegistry = lookup(instance, '-view-registry:main');
<del> assert.strictEqual(Object.keys(viewRegistry).length, 0, 'did not create any views');
<add> let viewRegistry = lookup(instance, '-view-registry:main');
<add> assert.strictEqual(Object.keys(viewRegistry).length, 0, 'did not create any views');
<ide>
<del> let networkService = lookup(instance, 'service:network');
<del> assert.deepEqual(networkService.get('requests'), ['/c']);
<del> QUnit.stop();
<del> });
<add> let networkService = lookup(instance, 'service:network');
<add> assert.deepEqual(networkService.get('requests'), ['/c']);
<ide> });
<ide>
<del> let d = run(function() {
<del> return App.visit('/d', { isBrowser: false, shouldRender: false }).then((instance) => {
<del> QUnit.start();
<del> assert.ok(instance instanceof ApplicationInstance, 'promise is resolved with an ApplicationInstance');
<add> let d = run(App, 'visit', '/d', { isBrowser: false, shouldRender: false }).then(instance => {
<add> assert.ok(instance instanceof ApplicationInstance, 'promise is resolved with an ApplicationInstance');
<ide>
<del> assert.strictEqual(Ember.$('#qunit-fixture').children().length, 0, 'there are no elements in the fixture element');
<del> assert.strictEqual(xFooInstances, 0, 'did not create any x-foo components');
<add> assert.strictEqual(Ember.$('#qunit-fixture').children().length, 0, 'there are no elements in the fixture element');
<add> assert.strictEqual(xFooInstances, 0, 'did not create any x-foo components');
<ide>
<del> let viewRegistry = lookup(instance, '-view-registry:main');
<del> assert.strictEqual(Object.keys(viewRegistry).length, 0, 'did not create any views');
<add> let viewRegistry = lookup(instance, '-view-registry:main');
<add> assert.strictEqual(Object.keys(viewRegistry).length, 0, 'did not create any views');
<ide>
<del> let networkService = lookup(instance, 'service:network');
<del> assert.deepEqual(networkService.get('requests'), ['/d', '/e']);
<del> QUnit.stop();
<del> });
<add> let networkService = lookup(instance, 'service:network');
<add> assert.deepEqual(networkService.get('requests'), ['/d', '/e']);
<ide> });
<ide>
<del> let e = run(function() {
<del> return App.visit('/e', { isBrowser: false, shouldRender: false }).then((instance) => {
<del> QUnit.start();
<del> assert.ok(instance instanceof ApplicationInstance, 'promise is resolved with an ApplicationInstance');
<add> let e = run(App, 'visit', '/e', { isBrowser: false, shouldRender: false }).then(instance => {
<add> assert.ok(instance instanceof ApplicationInstance, 'promise is resolved with an ApplicationInstance');
<ide>
<del> assert.strictEqual(Ember.$('#qunit-fixture').children().length, 0, 'there are no elements in the fixture element');
<del> assert.strictEqual(xFooInstances, 0, 'did not create any x-foo components');
<add> assert.strictEqual(Ember.$('#qunit-fixture').children().length, 0, 'there are no elements in the fixture element');
<add> assert.strictEqual(xFooInstances, 0, 'did not create any x-foo components');
<ide>
<del> let viewRegistry = lookup(instance, '-view-registry:main');
<del> assert.strictEqual(Object.keys(viewRegistry).length, 0, 'did not create any views');
<add> let viewRegistry = lookup(instance, '-view-registry:main');
<add> assert.strictEqual(Object.keys(viewRegistry).length, 0, 'did not create any views');
<ide>
<del> let networkService = lookup(instance, 'service:network');
<del> assert.deepEqual(networkService.get('requests'), ['/e']);
<del> QUnit.stop();
<del> });
<add> let networkService = lookup(instance, 'service:network');
<add> assert.deepEqual(networkService.get('requests'), ['/e']);
<ide> });
<ide>
<del> Ember.RSVP.all([a, b, c, d, e]).finally(() => QUnit.start());
<add> return Ember.RSVP.all([a, b, c, d, e]);
<ide> });
<ide>
<ide> QUnit.skip('Test setup', function(assert) { | 1 |
PHP | PHP | add some default context to logs if we know it | 23b7d6b45c675bcd93e9f1fb9cd33e71779142c6 | <ide><path>src/Illuminate/Foundation/Exceptions/Handler.php
<ide> use Psr\Log\LoggerInterface;
<ide> use Illuminate\Http\Response;
<ide> use Illuminate\Routing\Router;
<add>use Illuminate\Support\Facades\Auth;
<ide> use Illuminate\Http\RedirectResponse;
<ide> use Illuminate\Auth\AuthenticationException;
<ide> use Illuminate\Contracts\Container\Container;
<ide> public function report(Exception $e)
<ide> throw $e; // throw the original exception
<ide> }
<ide>
<del> $logger->error($e);
<add> $logger->error($e, $this->context());
<ide> }
<ide>
<ide> /**
<ide> protected function shouldntReport(Exception $e)
<ide> }));
<ide> }
<ide>
<add> /**
<add> * Get the default context variables for logging.
<add> *
<add> * @return array
<add> */
<add> protected function context()
<add> {
<add> return array_filter([
<add> 'userId' => Auth::id(),
<add> 'email' => Auth::check() && isset(Auth::user()->email)
<add> ? Auth::user()->email : null,
<add> ]);
<add> }
<add>
<ide> /**
<ide> * Render an exception into a response.
<ide> * | 1 |
Javascript | Javascript | remove error 'stack' property changes | 7e916455b36dc9ca4d4afc1e44cade90006d00e3 | <ide><path>src/ngMock/angular-mocks.js
<ide> if(window.jasmine || window.mocha) {
<ide> *
<ide> * @param {...Function} fns any number of functions which will be injected using the injector.
<ide> */
<add>
<add>
<add>
<add> var ErrorAddingDeclarationLocationStack = function(e, errorForStack) {
<add> this.message = e.message;
<add> this.name = e.name;
<add> if (e.line) this.line = e.line;
<add> if (e.sourceId) this.sourceId = e.sourceId;
<add> if (e.stack && errorForStack)
<add> this.stack = e.stack + '\n' + errorForStack.stack;
<add> if (e.stackArray) this.stackArray = e.stackArray;
<add> };
<add> ErrorAddingDeclarationLocationStack.prototype.toString = Error.prototype.toString;
<add>
<ide> window.inject = angular.mock.inject = function() {
<ide> var blockFns = Array.prototype.slice.call(arguments, 0);
<ide> var errorForStack = new Error('Declaration Location');
<ide> if(window.jasmine || window.mocha) {
<ide> injector.invoke(blockFns[i] || angular.noop, this);
<ide> /* jshint +W040 */
<ide> } catch (e) {
<del> if(e.stack && errorForStack) e.stack += '\n' + errorForStack.stack;
<add> if (e.stack && errorForStack) {
<add> throw new ErrorAddingDeclarationLocationStack(e, errorForStack);
<add> }
<ide> throw e;
<ide> } finally {
<ide> errorForStack = null;
<ide><path>test/ngMock/angular-mocksSpec.js
<ide> describe('ngMock', function() {
<ide> expect(log).toEqual('module;inject;')
<ide> });
<ide> });
<add>
<add> // We don't run the following tests on IE8.
<add> // IE8 throws "Object does not support this property or method." error,
<add> // when thrown from a function defined on window (which `inject` is).
<add> if (msie <= 8) return;
<add>
<add> it('should not change thrown Errors', function() {
<add> expect(function(){
<add> throw new Error('test message');
<add> }).toThrow('test message');
<add> });
<add>
<add> it('should not change thrown strings', function(){
<add> expect(function(){
<add> throw 'test message';
<add> }).toThrow('test message');
<add> });
<ide> });
<ide> });
<ide> | 2 |
PHP | PHP | remove uneeded instances of set | fb066272d76243f3b89b343bb1a2a2d7ba2a1536 | <ide><path>lib/Cake/Console/Command/AclShell.php
<ide> use Cake\Controller\Component\AclComponent;
<ide> use Cake\Core\Configure;
<ide> use Cake\Utility\Hash;
<del>use Cake\Utility\Set;
<ide>
<ide> /**
<ide> * Shell for ACL management. This console is known to have issues with zend.ze1_compatibility_mode
<ide><path>lib/Cake/Console/Command/Task/ExtractTask.php
<ide> use Cake\Utility\Folder;
<ide> use Cake\Utility\Hash;
<ide> use Cake\Utility\Inflector;
<del>use Cake\Utility\Set;
<ide>
<ide> /**
<ide> * Language string extractor
<ide><path>lib/Cake/Controller/Component/Acl/DbAcl.php
<ide> use Cake\Core\Object;
<ide> use Cake\Utility\ClassRegistry;
<ide> use Cake\Utility\Hash;
<del>use Cake\Utility\Set;
<ide>
<ide> /**
<ide> * DbAcl implements an ACL control system in the database. ARO's and ACO's are
<ide><path>lib/Cake/Controller/Component/AclComponent.php
<ide> use Cake\Error;
<ide> use Cake\Utility\ClassRegistry;
<ide> use Cake\Utility\Inflector;
<del>use Cake\Utility\Set;
<ide>
<ide> /**
<ide> * Access Control List factory class.
<ide><path>lib/Cake/Controller/Component/Auth/BaseAuthenticate.php
<ide> use Cake\Utility\ClassRegistry;
<ide> use Cake\Utility\Hash;
<ide> use Cake\Utility\Security;
<del>use Cake\Utility\Set;
<ide>
<ide> /**
<ide> * Base Authentication class with common methods and properties.
<ide><path>lib/Cake/Controller/Component/Auth/BaseAuthorize.php
<ide> use Cake\Network\Response;
<ide> use Cake\Utility\Hash;
<ide> use Cake\Utility\Inflector;
<del>use Cake\Utility\Set;
<ide>
<ide> /**
<ide> * Abstract base authorization adapter for AuthComponent.
<ide><path>lib/Cake/Controller/Component/AuthComponent.php
<ide> use Cake\Utility\Debugger;
<ide> use Cake\Utility\Hash;
<ide> use Cake\Utility\Security;
<del>use Cake\Utility\Set;
<ide>
<ide> /**
<ide> * Authentication control component class
<ide><path>lib/Cake/Controller/Component/CookieComponent.php
<ide> use Cake\Network\Response;
<ide> use Cake\Utility\Hash;
<ide> use Cake\Utility\Security;
<del>use Cake\Utility\Set;
<ide>
<ide> /**
<ide> * Cookie Component.
<ide><path>lib/Cake/Controller/Component/PaginatorComponent.php
<ide> use Cake\Controller\ComponentCollection;
<ide> use Cake\Error;
<ide> use Cake\Utility\Hash;
<del>use Cake\Utility\Set;
<ide>
<ide> /**
<ide> * This component is used to handle automatic model data pagination. The primary way to use this
<ide><path>lib/Cake/Controller/Component/SecurityComponent.php
<ide> use Cake\Network\Request;
<ide> use Cake\Utility\Hash;
<ide> use Cake\Utility\Security;
<del>use Cake\Utility\Set;
<ide>
<ide> /**
<ide> * The Security Component creates an easy way to integrate tighter security in
<ide><path>lib/Cake/Core/Configure.php
<ide> use Cake\Configure\PhpReader;
<ide> use Cake\Error;
<ide> use Cake\Utility\Hash;
<del>use Cake\Utility\Set;
<ide>
<ide> /**
<ide> * Configuration class. Used for managing runtime configuration information.
<ide><path>lib/Cake/Core/Object.php
<ide> use Cake\Routing\Dispatcher;
<ide> use Cake\Routing\Router;
<ide> use Cake\Utility\Hash;
<del>use Cake\Utility\Set;
<ide>
<ide> /**
<ide> * Object class provides a few generic methods used in several subclasses.
<ide><path>lib/Cake/Model/Behavior/ContainableBehavior.php
<ide> namespace Cake\Model\Behavior;
<ide> use Cake\Model\Model;
<ide> use Cake\Model\ModelBehavior;
<del>use Cake\Utility\Set;
<add>use Cake\Utility\Hash;
<ide>
<ide> /**
<ide> * Behavior to allow for dynamic and atomic manipulation of a Model's associations
<ide><path>lib/Cake/Model/Behavior/TreeBehavior.php
<ide> use Cake\Model\ConnectionManager;
<ide> use Cake\Model\Model;
<ide> use Cake\Model\ModelBehavior;
<add>use Cake\Utility\Hash;
<ide>
<ide> /**
<ide> * Tree Behavior.
<ide><path>lib/Cake/Network/Http/HttpSocket.php
<ide> use Cake\Network\Socket;
<ide> use Cake\Utility\Hash;
<ide> use Cake\Utility\Inflector;
<del>use Cake\Utility\Set;
<ide>
<ide> /**
<ide> * Cake network socket connection class.
<ide><path>lib/Cake/Network/Request.php
<ide> use Cake\Core\Configure;
<ide> use Cake\Error;
<ide> use Cake\Utility\Hash;
<del>use Cake\Utility\Set;
<ide>
<ide> /**
<ide> * A class that helps wrap Request information and particulars about a single request.
<ide> protected function _processFileData($path, $data, $field) {
<ide> $this->_processFileData($newPath, $fields, $field);
<ide> } else {
<ide> $newPath .= '.' . $field;
<del> $this->data = Set::insert($this->data, $newPath, $fields);
<add> $this->data = Hash::insert($this->data, $newPath, $fields);
<ide> }
<ide> }
<ide> }
<ide><path>lib/Cake/Routing/Router.php
<ide> use Cake\Routing\Route\Route;
<ide> use Cake\Utility\Hash;
<ide> use Cake\Utility\Inflector;
<del>use Cake\Utility\Set;
<ide>
<ide> /**
<ide> * Parses the request URL into controller, action, and parameters. Uses the connected routes
<ide><path>lib/Cake/Test/TestApp/Model/PaginatorControllerPost.php
<ide> */
<ide> namespace TestApp\Model;
<ide> use Cake\TestSuite\Fixture\TestModel;
<del>use Cake\Utility\Set;
<add>use Cake\Utility\Hash;
<ide>
<ide> /**
<ide> * PaginatorControllerPost class
<ide> public function beforeFind($query) {
<ide> public function find($conditions = null, $fields = array(), $order = null, $recursive = null) {
<ide> if ($conditions == 'popular') {
<ide> $conditions = array($this->name . '.' . $this->primaryKey .' > ' => '1');
<del> $options = Set::merge($fields, compact('conditions'));
<add> $options = Hash::merge($fields, compact('conditions'));
<ide> return parent::find('all', $options);
<ide> }
<ide> return parent::find($conditions, $fields);
<ide><path>lib/Cake/Test/TestCase/Console/ShellTest.php
<ide> use Cake\TestSuite\TestCase;
<ide> use Cake\Utility\Folder;
<ide> use Cake\Utility\Hash;
<del>use Cake\Utility\Set;
<ide>
<ide> /**
<ide> * ShellTestShell class
<ide><path>lib/Cake/Test/TestCase/Controller/ControllerTest.php
<ide> use Cake\TestSuite\TestCase;
<ide> use Cake\Utility\ClassRegistry;
<ide> use Cake\Utility\Hash;
<del>use Cake\Utility\Set;
<ide> use TestPlugin\Controller\TestPluginController;
<ide>
<ide> /**
<ide><path>lib/Cake/Test/TestCase/Network/Http/HttpSocketTest.php
<ide> use Cake\Network\Http\HttpSocket;
<ide> use Cake\TestSuite\TestCase;
<ide> use Cake\Utility\Hash;
<del>use Cake\Utility\Set;
<ide>
<ide> /**
<ide> * TestAuthentication class
<ide><path>lib/Cake/TestSuite/Fixture/TestFixture.php
<ide> use Cake\Utility\ClassRegistry;
<ide> use Cake\Utility\Hash;
<ide> use Cake\Utility\Inflector;
<del>use Cake\Utility\Set;
<ide>
<ide> /**
<ide> * TestFixture is responsible for building and destroying tables to be used
<ide><path>lib/Cake/View/XmlView.php
<ide> namespace Cake\View;
<ide> use Cake\Controller\Controller;
<ide> use Cake\Network\Response;
<del>use Cake\Utility\Set;
<add>use Cake\Utility\Hash;
<ide> use Cake\Utility\Xml;
<ide>
<ide> /**
<ide> public function render($view = null, $layout = null) {
<ide> }
<ide> } else {
<ide> $data = isset($this->viewVars[$serialize]) ? $this->viewVars[$serialize] : null;
<del> if (is_array($data) && Set::numeric(array_keys($data))) {
<add> if (is_array($data) && Hash::numeric(array_keys($data))) {
<ide> $data = array('response' => array($serialize => $data));
<ide> }
<ide> } | 23 |
Javascript | Javascript | remove assert message and add block scope | 1ebd966d2cef9d026b947c3c36d49c9989a60701 | <ide><path>test/parallel/test-crypto-binary-default.js
<ide> assert.throws(function() {
<ide> }, /^Error: not enough data$/);
<ide>
<ide> // Test HMAC
<del>const hmacHash = crypto.createHmac('sha1', 'Node')
<del> .update('some data')
<del> .update('to hmac')
<del> .digest('hex');
<del>assert.strictEqual(hmacHash, '19fd6e1ba73d9ed2224dd5094a71babe85d9a892');
<add>{
<add> const hmacHash = crypto.createHmac('sha1', 'Node')
<add> .update('some data')
<add> .update('to hmac')
<add> .digest('hex');
<add> assert.strictEqual(hmacHash, '19fd6e1ba73d9ed2224dd5094a71babe85d9a892');
<add>}
<ide>
<ide> // Test HMAC-SHA-* (rfc 4231 Test Cases)
<del>const rfc4231 = [
<del> {
<del> key: Buffer.from('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'),
<del> data: Buffer.from('4869205468657265', 'hex'), // 'Hi There'
<del> hmac: {
<del> sha224: '896fb1128abbdf196832107cd49df33f47b4b1169912ba4f53684b22',
<del> sha256:
<del> 'b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c' +
<del> '2e32cff7',
<del> sha384:
<del> 'afd03944d84895626b0825f4ab46907f15f9dadbe4101ec682aa034c' +
<del> '7cebc59cfaea9ea9076ede7f4af152e8b2fa9cb6',
<del> sha512:
<del> '87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b305' +
<del> '45e17cdedaa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f170' +
<del> '2e696c203a126854'
<del> }
<del> },
<del> {
<del> key: Buffer.from('4a656665', 'hex'), // 'Jefe'
<del> data: Buffer.from('7768617420646f2079612077616e7420666f72206e6f74686' +
<del> '96e673f', 'hex'), // 'what do ya want for nothing?'
<del> hmac: {
<del> sha224: 'a30e01098bc6dbbf45690f3a7e9e6d0f8bbea2a39e6148008fd05e44',
<del> sha256:
<del> '5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b9' +
<del> '64ec3843',
<del> sha384:
<del> 'af45d2e376484031617f78d2b58a6b1b9c7ef464f5a01b47e42ec373' +
<del> '6322445e8e2240ca5e69e2c78b3239ecfab21649',
<del> sha512:
<del> '164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7' +
<del> 'ea2505549758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b' +
<del> '636e070a38bce737'
<del> }
<del> },
<del> {
<del> key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'),
<del> data: Buffer.from('ddddddddddddddddddddddddddddddddddddddddddddddddd' +
<del> 'ddddddddddddddddddddddddddddddddddddddddddddddddddd',
<del> 'hex'),
<del> hmac: {
<del> sha224: '7fb3cb3588c6c1f6ffa9694d7d6ad2649365b0c1f65d69d1ec8333ea',
<del> sha256:
<del> '773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514' +
<del> 'ced565fe',
<del> sha384:
<del> '88062608d3e6ad8a0aa2ace014c8a86f0aa635d947ac9febe83ef4e5' +
<del> '5966144b2a5ab39dc13814b94e3ab6e101a34f27',
<del> sha512:
<del> 'fa73b0089d56a284efb0f0756c890be9b1b5dbdd8ee81a3655f83e33' +
<del> 'b2279d39bf3e848279a722c806b485a47e67c807b946a337bee89426' +
<del> '74278859e13292fb'
<del> }
<del> },
<del> {
<del> key: Buffer.from('0102030405060708090a0b0c0d0e0f10111213141516171819',
<del> 'hex'),
<del> data: Buffer.from('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' +
<del> 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd',
<del> 'hex'),
<del> hmac: {
<del> sha224: '6c11506874013cac6a2abc1bb382627cec6a90d86efc012de7afec5a',
<del> sha256:
<del> '82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff4' +
<del> '6729665b',
<del> sha384:
<del> '3e8a69b7783c25851933ab6290af6ca77a9981480850009cc5577c6e' +
<del> '1f573b4e6801dd23c4a7d679ccf8a386c674cffb',
<del> sha512:
<del> 'b0ba465637458c6990e5a8c5f61d4af7e576d97ff94b872de76f8050' +
<del> '361ee3dba91ca5c11aa25eb4d679275cc5788063a5f19741120c4f2d' +
<del> 'e2adebeb10a298dd'
<del> }
<del> },
<del>
<del> {
<del> key: Buffer.from('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'),
<del> // 'Test With Truncation'
<del> data: Buffer.from('546573742057697468205472756e636174696f6e', 'hex'),
<del> hmac: {
<del> sha224: '0e2aea68a90c8d37c988bcdb9fca6fa8',
<del> sha256: 'a3b6167473100ee06e0c796c2955552b',
<del> sha384: '3abf34c3503b2a23a46efc619baef897',
<del> sha512: '415fad6271580a531d4179bc891d87a6'
<add>{
<add> const rfc4231 = [
<add> {
<add> key: Buffer.from('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'),
<add> data: Buffer.from('4869205468657265', 'hex'), // 'Hi There'
<add> hmac: {
<add> sha224: '896fb1128abbdf196832107cd49df33f47b4b1169912ba4f53684b22',
<add> sha256:
<add> 'b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c' +
<add> '2e32cff7',
<add> sha384:
<add> 'afd03944d84895626b0825f4ab46907f15f9dadbe4101ec682aa034c' +
<add> '7cebc59cfaea9ea9076ede7f4af152e8b2fa9cb6',
<add> sha512:
<add> '87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b305' +
<add> '45e17cdedaa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f170' +
<add> '2e696c203a126854'
<add> }
<ide> },
<del> truncate: true
<del> },
<del> {
<del> key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<del> 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<del> 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<del> 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<del> 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<del> 'aaaaaaaaaaaa', 'hex'),
<del> // 'Test Using Larger Than Block-Size Key - Hash Key First'
<del> data: Buffer.from('54657374205573696e67204c6172676572205468616e20426' +
<del> 'c6f636b2d53697a65204b6579202d2048617368204b657920' +
<del> '4669727374', 'hex'),
<del> hmac: {
<del> sha224: '95e9a0db962095adaebe9b2d6f0dbce2d499f112f2d2b7273fa6870e',
<del> sha256:
<del> '60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f' +
<del> '0ee37f54',
<del> sha384:
<del> '4ece084485813e9088d2c63a041bc5b44f9ef1012a2b588f3cd11f05' +
<del> '033ac4c60c2ef6ab4030fe8296248df163f44952',
<del> sha512:
<del> '80b24263c7c1a3ebb71493c1dd7be8b49b46d1f41b4aeec1121b0137' +
<del> '83f8f3526b56d037e05f2598bd0fd2215d6a1e5295e64f73f63f0aec' +
<del> '8b915a985d786598'
<del> }
<del> },
<del> {
<del> key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<del> 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<del> 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<del> 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<del> 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<del> 'aaaaaaaaaaaa', 'hex'),
<del> // 'This is a test using a larger than block-size key and a larger ' +
<del> // 'than block-size data. The key needs to be hashed before being ' +
<del> // 'used by the HMAC algorithm.'
<del> data: Buffer.from('5468697320697320612074657374207573696e672061206c6' +
<del> '172676572207468616e20626c6f636b2d73697a65206b6579' +
<del> '20616e642061206c6172676572207468616e20626c6f636b2' +
<del> 'd73697a6520646174612e20546865206b6579206e65656473' +
<del> '20746f20626520686173686564206265666f7265206265696' +
<del> 'e6720757365642062792074686520484d414320616c676f72' +
<del> '6974686d2e', 'hex'),
<del> hmac: {
<del> sha224: '3a854166ac5d9f023f54d517d0b39dbd946770db9c2b95c9f6f565d1',
<del> sha256:
<del> '9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f5153' +
<del> '5c3a35e2',
<del> sha384:
<del> '6617178e941f020d351e2f254e8fd32c602420feb0b8fb9adccebb82' +
<del> '461e99c5a678cc31e799176d3860e6110c46523e',
<del> sha512:
<del> 'e37b6a775dc87dbaa4dfa9f96e5e3ffddebd71f8867289865df5a32d' +
<del> '20cdc944b6022cac3c4982b10d5eeb55c3e4de15134676fb6de04460' +
<del> '65c97440fa8c6a58'
<add> {
<add> key: Buffer.from('4a656665', 'hex'), // 'Jefe'
<add> data: Buffer.from('7768617420646f2079612077616e7420666f72206e6f74686' +
<add> '96e673f', 'hex'), // 'what do ya want for nothing?'
<add> hmac: {
<add> sha224: 'a30e01098bc6dbbf45690f3a7e9e6d0f8bbea2a39e6148008fd05e44',
<add> sha256:
<add> '5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b9' +
<add> '64ec3843',
<add> sha384:
<add> 'af45d2e376484031617f78d2b58a6b1b9c7ef464f5a01b47e42ec373' +
<add> '6322445e8e2240ca5e69e2c78b3239ecfab21649',
<add> sha512:
<add> '164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7' +
<add> 'ea2505549758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b' +
<add> '636e070a38bce737'
<add> }
<add> },
<add> {
<add> key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'),
<add> data: Buffer.from('ddddddddddddddddddddddddddddddddddddddddddddddddd' +
<add> 'ddddddddddddddddddddddddddddddddddddddddddddddddddd',
<add> 'hex'),
<add> hmac: {
<add> sha224: '7fb3cb3588c6c1f6ffa9694d7d6ad2649365b0c1f65d69d1ec8333ea',
<add> sha256:
<add> '773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514' +
<add> 'ced565fe',
<add> sha384:
<add> '88062608d3e6ad8a0aa2ace014c8a86f0aa635d947ac9febe83ef4e5' +
<add> '5966144b2a5ab39dc13814b94e3ab6e101a34f27',
<add> sha512:
<add> 'fa73b0089d56a284efb0f0756c890be9b1b5dbdd8ee81a3655f83e33' +
<add> 'b2279d39bf3e848279a722c806b485a47e67c807b946a337bee89426' +
<add> '74278859e13292fb'
<add> }
<add> },
<add> {
<add> key: Buffer.from('0102030405060708090a0b0c0d0e0f10111213141516171819',
<add> 'hex'),
<add> data: Buffer.from('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' +
<add> 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd',
<add> 'hex'),
<add> hmac: {
<add> sha224: '6c11506874013cac6a2abc1bb382627cec6a90d86efc012de7afec5a',
<add> sha256:
<add> '82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff4' +
<add> '6729665b',
<add> sha384:
<add> '3e8a69b7783c25851933ab6290af6ca77a9981480850009cc5577c6e' +
<add> '1f573b4e6801dd23c4a7d679ccf8a386c674cffb',
<add> sha512:
<add> 'b0ba465637458c6990e5a8c5f61d4af7e576d97ff94b872de76f8050' +
<add> '361ee3dba91ca5c11aa25eb4d679275cc5788063a5f19741120c4f2d' +
<add> 'e2adebeb10a298dd'
<add> }
<add> },
<add> {
<add> key: Buffer.from('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'),
<add> // 'Test With Truncation'
<add> data: Buffer.from('546573742057697468205472756e636174696f6e', 'hex'),
<add> hmac: {
<add> sha224: '0e2aea68a90c8d37c988bcdb9fca6fa8',
<add> sha256: 'a3b6167473100ee06e0c796c2955552b',
<add> sha384: '3abf34c3503b2a23a46efc619baef897',
<add> sha512: '415fad6271580a531d4179bc891d87a6'
<add> },
<add> truncate: true
<add> },
<add> {
<add> key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<add> 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<add> 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<add> 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<add> 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<add> 'aaaaaaaaaaaa', 'hex'),
<add> // 'Test Using Larger Than Block-Size Key - Hash Key First'
<add> data: Buffer.from('54657374205573696e67204c6172676572205468616e20426' +
<add> 'c6f636b2d53697a65204b6579202d2048617368204b657920' +
<add> '4669727374', 'hex'),
<add> hmac: {
<add> sha224: '95e9a0db962095adaebe9b2d6f0dbce2d499f112f2d2b7273fa6870e',
<add> sha256:
<add> '60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f' +
<add> '0ee37f54',
<add> sha384:
<add> '4ece084485813e9088d2c63a041bc5b44f9ef1012a2b588f3cd11f05' +
<add> '033ac4c60c2ef6ab4030fe8296248df163f44952',
<add> sha512:
<add> '80b24263c7c1a3ebb71493c1dd7be8b49b46d1f41b4aeec1121b0137' +
<add> '83f8f3526b56d037e05f2598bd0fd2215d6a1e5295e64f73f63f0aec' +
<add> '8b915a985d786598'
<add> }
<add> },
<add> {
<add> key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<add> 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<add> 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<add> 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<add> 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<add> 'aaaaaaaaaaaa', 'hex'),
<add> // 'This is a test using a larger than block-size key and a larger ' +
<add> // 'than block-size data. The key needs to be hashed before being ' +
<add> // 'used by the HMAC algorithm.'
<add> data: Buffer.from('5468697320697320612074657374207573696e672061206c6' +
<add> '172676572207468616e20626c6f636b2d73697a65206b6579' +
<add> '20616e642061206c6172676572207468616e20626c6f636b2' +
<add> 'd73697a6520646174612e20546865206b6579206e65656473' +
<add> '20746f20626520686173686564206265666f7265206265696' +
<add> 'e6720757365642062792074686520484d414320616c676f72' +
<add> '6974686d2e', 'hex'),
<add> hmac: {
<add> sha224: '3a854166ac5d9f023f54d517d0b39dbd946770db9c2b95c9f6f565d1',
<add> sha256:
<add> '9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f5153' +
<add> '5c3a35e2',
<add> sha384:
<add> '6617178e941f020d351e2f254e8fd32c602420feb0b8fb9adccebb82' +
<add> '461e99c5a678cc31e799176d3860e6110c46523e',
<add> sha512:
<add> 'e37b6a775dc87dbaa4dfa9f96e5e3ffddebd71f8867289865df5a32d' +
<add> '20cdc944b6022cac3c4982b10d5eeb55c3e4de15134676fb6de04460' +
<add> '65c97440fa8c6a58'
<add> }
<ide> }
<del> }
<del>];
<del>
<del>for (const testCase of rfc4231) {
<del> for (const hash in testCase.hmac) {
<del> let result = crypto.createHmac(hash, testCase.key)
<del> .update(testCase.data)
<del> .digest('hex');
<del> if (testCase.truncate) {
<del> result = result.substr(0, 32); // first 128 bits == 32 hex chars
<add> ];
<add>
<add> for (const testCase of rfc4231) {
<add> for (const hash in testCase.hmac) {
<add> let result = crypto.createHmac(hash, testCase.key)
<add> .update(testCase.data)
<add> .digest('hex');
<add> if (testCase.truncate) {
<add> result = result.substr(0, 32); // first 128 bits == 32 hex chars
<add> }
<add> assert.strictEqual(
<add> testCase.hmac[hash],
<add> result
<add> );
<ide> }
<del> assert.strictEqual(
<del> testCase.hmac[hash],
<del> result
<del> );
<ide> }
<ide> }
<ide>
<ide> // Test HMAC-MD5/SHA1 (rfc 2202 Test Cases)
<del>const rfc2202_md5 = [
<del> {
<del> key: Buffer.from('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'),
<del> data: 'Hi There',
<del> hmac: '9294727a3638bb1c13f48ef8158bfc9d'
<del> },
<del> {
<del> key: 'Jefe',
<del> data: 'what do ya want for nothing?',
<del> hmac: '750c783e6ab0b503eaa86e310a5db738'
<del> },
<del> {
<del> key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'),
<del> data: Buffer.from('ddddddddddddddddddddddddddddddddddddddddddddddddd' +
<del> 'ddddddddddddddddddddddddddddddddddddddddddddddddddd',
<del> 'hex'),
<del> hmac: '56be34521d144c88dbb8c733f0e8b3f6'
<del> },
<del> {
<del> key: Buffer.from('0102030405060708090a0b0c0d0e0f10111213141516171819',
<del> 'hex'),
<del> data: Buffer.from('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' +
<del> 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd' +
<del> 'cdcdcdcdcd',
<del> 'hex'),
<del> hmac: '697eaf0aca3a3aea3a75164746ffaa79'
<del> },
<del> {
<del> key: Buffer.from('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'),
<del> data: 'Test With Truncation',
<del> hmac: '56461ef2342edc00f9bab995690efd4c'
<del> },
<del> {
<del> key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<del> 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<del> 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<del> 'aaaaaaaaaaaaaaaaaaaaaa',
<del> 'hex'),
<del> data: 'Test Using Larger Than Block-Size Key - Hash Key First',
<del> hmac: '6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd'
<del> },
<del> {
<del> key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<del> 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<del> 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<del> 'aaaaaaaaaaaaaaaaaaaaaa',
<del> 'hex'),
<del> data:
<del> 'Test Using Larger Than Block-Size Key and Larger Than One ' +
<del> 'Block-Size Data',
<del> hmac: '6f630fad67cda0ee1fb1f562db3aa53e'
<del> }
<del>];
<del>const rfc2202_sha1 = [
<del> {
<del> key: Buffer.from('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'),
<del> data: 'Hi There',
<del> hmac: 'b617318655057264e28bc0b6fb378c8ef146be00'
<del> },
<del> {
<del> key: 'Jefe',
<del> data: 'what do ya want for nothing?',
<del> hmac: 'effcdf6ae5eb2fa2d27416d5f184df9c259a7c79'
<del> },
<del> {
<del> key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'),
<del> data: Buffer.from('ddddddddddddddddddddddddddddddddddddddddddddd' +
<del> 'ddddddddddddddddddddddddddddddddddddddddddddd' +
<del> 'dddddddddd',
<del> 'hex'),
<del> hmac: '125d7342b9ac11cd91a39af48aa17b4f63f175d3'
<del> },
<del> {
<del> key: Buffer.from('0102030405060708090a0b0c0d0e0f10111213141516171819',
<del> 'hex'),
<del> data: Buffer.from('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' +
<del> 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd' +
<del> 'cdcdcdcdcd',
<del> 'hex'),
<del> hmac: '4c9007f4026250c6bc8414f9bf50c86c2d7235da'
<del> },
<del> {
<del> key: Buffer.from('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'),
<del> data: 'Test With Truncation',
<del> hmac: '4c1a03424b55e07fe7f27be1d58bb9324a9a5a04'
<del> },
<del> {
<del> key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<del> 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<del> 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<del> 'aaaaaaaaaaaaaaaaaaaaaa',
<del> 'hex'),
<del> data: 'Test Using Larger Than Block-Size Key - Hash Key First',
<del> hmac: 'aa4ae5e15272d00e95705637ce8a3b55ed402112'
<del> },
<del> {
<del> key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<del> 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<del> 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<del> 'aaaaaaaaaaaaaaaaaaaaaa',
<del> 'hex'),
<del> data:
<del> 'Test Using Larger Than Block-Size Key and Larger Than One ' +
<del> 'Block-Size Data',
<del> hmac: 'e8e99d0f45237d786d6bbaa7965c7808bbff1a91'
<add>{
<add> const rfc2202_md5 = [
<add> {
<add> key: Buffer.from('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'),
<add> data: 'Hi There',
<add> hmac: '9294727a3638bb1c13f48ef8158bfc9d'
<add> },
<add> {
<add> key: 'Jefe',
<add> data: 'what do ya want for nothing?',
<add> hmac: '750c783e6ab0b503eaa86e310a5db738'
<add> },
<add> {
<add> key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'),
<add> data: Buffer.from('ddddddddddddddddddddddddddddddddddddddddddddddddd' +
<add> 'ddddddddddddddddddddddddddddddddddddddddddddddddddd',
<add> 'hex'),
<add> hmac: '56be34521d144c88dbb8c733f0e8b3f6'
<add> },
<add> {
<add> key: Buffer.from('0102030405060708090a0b0c0d0e0f10111213141516171819',
<add> 'hex'),
<add> data: Buffer.from('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' +
<add> 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd' +
<add> 'cdcdcdcdcd',
<add> 'hex'),
<add> hmac: '697eaf0aca3a3aea3a75164746ffaa79'
<add> },
<add> {
<add> key: Buffer.from('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'),
<add> data: 'Test With Truncation',
<add> hmac: '56461ef2342edc00f9bab995690efd4c'
<add> },
<add> {
<add> key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<add> 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<add> 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<add> 'aaaaaaaaaaaaaaaaaaaaaa',
<add> 'hex'),
<add> data: 'Test Using Larger Than Block-Size Key - Hash Key First',
<add> hmac: '6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd'
<add> },
<add> {
<add> key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<add> 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<add> 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<add> 'aaaaaaaaaaaaaaaaaaaaaa',
<add> 'hex'),
<add> data:
<add> 'Test Using Larger Than Block-Size Key and Larger Than One ' +
<add> 'Block-Size Data',
<add> hmac: '6f630fad67cda0ee1fb1f562db3aa53e'
<add> }
<add> ];
<add> const rfc2202_sha1 = [
<add> {
<add> key: Buffer.from('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'),
<add> data: 'Hi There',
<add> hmac: 'b617318655057264e28bc0b6fb378c8ef146be00'
<add> },
<add> {
<add> key: 'Jefe',
<add> data: 'what do ya want for nothing?',
<add> hmac: 'effcdf6ae5eb2fa2d27416d5f184df9c259a7c79'
<add> },
<add> {
<add> key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'),
<add> data: Buffer.from('ddddddddddddddddddddddddddddddddddddddddddddd' +
<add> 'ddddddddddddddddddddddddddddddddddddddddddddd' +
<add> 'dddddddddd',
<add> 'hex'),
<add> hmac: '125d7342b9ac11cd91a39af48aa17b4f63f175d3'
<add> },
<add> {
<add> key: Buffer.from('0102030405060708090a0b0c0d0e0f10111213141516171819',
<add> 'hex'),
<add> data: Buffer.from('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' +
<add> 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd' +
<add> 'cdcdcdcdcd',
<add> 'hex'),
<add> hmac: '4c9007f4026250c6bc8414f9bf50c86c2d7235da'
<add> },
<add> {
<add> key: Buffer.from('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'),
<add> data: 'Test With Truncation',
<add> hmac: '4c1a03424b55e07fe7f27be1d58bb9324a9a5a04'
<add> },
<add> {
<add> key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<add> 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<add> 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<add> 'aaaaaaaaaaaaaaaaaaaaaa',
<add> 'hex'),
<add> data: 'Test Using Larger Than Block-Size Key - Hash Key First',
<add> hmac: 'aa4ae5e15272d00e95705637ce8a3b55ed402112'
<add> },
<add> {
<add> key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<add> 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<add> 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' +
<add> 'aaaaaaaaaaaaaaaaaaaaaa',
<add> 'hex'),
<add> data:
<add> 'Test Using Larger Than Block-Size Key and Larger Than One ' +
<add> 'Block-Size Data',
<add> hmac: 'e8e99d0f45237d786d6bbaa7965c7808bbff1a91'
<add> }
<add> ];
<add>
<add> if (!common.hasFipsCrypto) {
<add> for (const testCase of rfc2202_md5) {
<add> assert.strictEqual(
<add> testCase.hmac,
<add> crypto.createHmac('md5', testCase.key)
<add> .update(testCase.data)
<add> .digest('hex')
<add> );
<add> }
<ide> }
<del>];
<del>
<del>if (!common.hasFipsCrypto) {
<del> for (const testCase of rfc2202_md5) {
<add> for (const testCase of rfc2202_sha1) {
<ide> assert.strictEqual(
<ide> testCase.hmac,
<del> crypto.createHmac('md5', testCase.key)
<add> crypto.createHmac('sha1', testCase.key)
<ide> .update(testCase.data)
<ide> .digest('hex')
<ide> );
<ide> }
<ide> }
<del>for (const testCase of rfc2202_sha1) {
<del> assert.strictEqual(
<del> testCase.hmac,
<del> crypto.createHmac('sha1', testCase.key)
<del> .update(testCase.data)
<del> .digest('hex')
<del> );
<del>}
<ide>
<ide> // Test hashing
<del>const a1 = crypto.createHash('sha1').update('Test123').digest('hex');
<del>const a2 = crypto.createHash('sha256').update('Test123').digest('base64');
<del>const a3 = crypto.createHash('sha512').update('Test123').digest(); // binary
<del>const a4 = crypto.createHash('sha1').update('Test123').digest('buffer');
<add>{
<add> const a1 = crypto.createHash('sha1').update('Test123').digest('hex');
<add> const a2 = crypto.createHash('sha256').update('Test123').digest('base64');
<add> const a3 = crypto.createHash('sha512').update('Test123').digest(); // binary
<add> const a4 = crypto.createHash('sha1').update('Test123').digest('buffer');
<ide>
<del>if (!common.hasFipsCrypto) {
<del> const a0 = crypto.createHash('md5').update('Test123').digest('latin1');
<del> assert.strictEqual(
<del> a0,
<del> 'h\u00ea\u00cb\u0097\u00d8o\fF!\u00fa+\u000e\u0017\u00ca\u00bd\u008c'
<del> );
<del>}
<add> if (!common.hasFipsCrypto) {
<add> const a0 = crypto.createHash('md5').update('Test123').digest('latin1');
<add> assert.strictEqual(
<add> a0,
<add> 'h\u00ea\u00cb\u0097\u00d8o\fF!\u00fa+\u000e\u0017\u00ca\u00bd\u008c'
<add> );
<add> }
<ide>
<del>assert.strictEqual(a1, '8308651804facb7b9af8ffc53a33a22d6a1c8ac2');
<add> assert.strictEqual(a1, '8308651804facb7b9af8ffc53a33a22d6a1c8ac2');
<ide>
<del>assert.strictEqual(a2, '2bX1jws4GYKTlxhloUB09Z66PoJZW+y+hq5R8dnx9l4=');
<add> assert.strictEqual(a2, '2bX1jws4GYKTlxhloUB09Z66PoJZW+y+hq5R8dnx9l4=');
<ide>
<del>assert.strictEqual(
<del> a3,
<del> '\u00c1(4\u00f1\u0003\u001fd\u0097!O\'\u00d4C/&Qz\u00d4' +
<del> '\u0094\u0015l\u00b8\u008dQ+\u00db\u001d\u00c4\u00b5}\u00b2' +
<del> '\u00d6\u0092\u00a3\u00df\u00a2i\u00a1\u009b\n\n*\u000f' +
<del> '\u00d7\u00d6\u00a2\u00a8\u0085\u00e3<\u0083\u009c\u0093' +
<del> '\u00c2\u0006\u00da0\u00a1\u00879(G\u00ed\'',
<del> 'Test SHA512 as assumed latin1'
<del>);
<add> // Test SHA512 as assumed latin1
<add> assert.strictEqual(
<add> a3,
<add> '\u00c1(4\u00f1\u0003\u001fd\u0097!O\'\u00d4C/&Qz\u00d4' +
<add> '\u0094\u0015l\u00b8\u008dQ+\u00db\u001d\u00c4\u00b5}\u00b2' +
<add> '\u00d6\u0092\u00a3\u00df\u00a2i\u00a1\u009b\n\n*\u000f' +
<add> '\u00d7\u00d6\u00a2\u00a8\u0085\u00e3<\u0083\u009c\u0093' +
<add> '\u00c2\u0006\u00da0\u00a1\u00879(G\u00ed\''
<add> );
<ide>
<del>assert.deepStrictEqual(
<del> a4,
<del> Buffer.from('8308651804facb7b9af8ffc53a33a22d6a1c8ac2', 'hex')
<del>);
<add> assert.deepStrictEqual(
<add> a4,
<add> Buffer.from('8308651804facb7b9af8ffc53a33a22d6a1c8ac2', 'hex')
<add> );
<add>}
<ide>
<ide> // Test multiple updates to same hash
<del>const h1 = crypto.createHash('sha1').update('Test123').digest('hex');
<del>const h2 = crypto.createHash('sha1').update('Test').update('123').digest('hex');
<del>assert.strictEqual(h1, h2);
<add>{
<add> const h1 = crypto.createHash('sha1').update('Test123').digest('hex');
<add> const h2 = crypto.createHash('sha1').update('Test').update('123')
<add> .digest('hex');
<add> assert.strictEqual(h1, h2);
<add>}
<ide>
<ide> // Test hashing for binary files
<del>const fn = fixtures.path('sample.png');
<del>const sha1Hash = crypto.createHash('sha1');
<del>const fileStream = fs.createReadStream(fn);
<del>fileStream.on('data', function(data) {
<del> sha1Hash.update(data);
<del>});
<del>fileStream.on('close', common.mustCall(function() {
<del> assert.strictEqual(
<del> sha1Hash.digest('hex'),
<del> '22723e553129a336ad96e10f6aecdf0f45e4149e'
<del> );
<del>}));
<add>{
<add> const fn = fixtures.path('sample.png');
<add> const sha1Hash = crypto.createHash('sha1');
<add> const fileStream = fs.createReadStream(fn);
<add> fileStream.on('data', function(data) {
<add> sha1Hash.update(data);
<add> });
<add> fileStream.on('close', common.mustCall(function() {
<add> assert.strictEqual(
<add> sha1Hash.digest('hex'),
<add> '22723e553129a336ad96e10f6aecdf0f45e4149e'
<add> );
<add> }));
<add>}
<ide>
<ide> // Unknown digest method should throw an error:
<ide> // https://github.com/nodejs/node-v0.x-archive/issues/2227
<ide> assert.throws(function() {
<ide> }, /^Error: Digest method not supported$/);
<ide>
<ide> // Test signing and verifying
<del>const s1 = crypto.createSign('SHA1')
<del> .update('Test123')
<del> .sign(keyPem, 'base64');
<del>const s1Verified = crypto.createVerify('SHA1')
<del> .update('Test')
<del> .update('123')
<del> .verify(certPem, s1, 'base64');
<del>assert.strictEqual(s1Verified, true);
<del>
<del>const s2 = crypto.createSign('SHA256')
<del> .update('Test123')
<del> .sign(keyPem); // binary
<del>const s2Verified = crypto.createVerify('SHA256')
<del> .update('Test')
<del> .update('123')
<del> .verify(certPem, s2); // binary
<del>assert.strictEqual(s2Verified, true);
<del>
<del>const s3 = crypto.createSign('SHA1')
<del> .update('Test123')
<del> .sign(keyPem, 'buffer');
<del>const s3Verified = crypto.createVerify('SHA1')
<del> .update('Test')
<del> .update('123')
<del> .verify(certPem, s3);
<del>assert.strictEqual(s3Verified, true);
<add>{
<add> const s1 = crypto.createSign('SHA1')
<add> .update('Test123')
<add> .sign(keyPem, 'base64');
<add> const s1Verified = crypto.createVerify('SHA1')
<add> .update('Test')
<add> .update('123')
<add> .verify(certPem, s1, 'base64');
<add> assert.strictEqual(s1Verified, true);
<add>
<add> const s2 = crypto.createSign('SHA256')
<add> .update('Test123')
<add> .sign(keyPem); // binary
<add> const s2Verified = crypto.createVerify('SHA256')
<add> .update('Test')
<add> .update('123')
<add> .verify(certPem, s2); // binary
<add> assert.strictEqual(s2Verified, true);
<add>
<add> const s3 = crypto.createSign('SHA1')
<add> .update('Test123')
<add> .sign(keyPem, 'buffer');
<add> const s3Verified = crypto.createVerify('SHA1')
<add> .update('Test')
<add> .update('123')
<add> .verify(certPem, s3);
<add> assert.strictEqual(s3Verified, true);
<add>}
<ide>
<ide>
<ide> function testCipher1(key) {
<ide> common.expectsError(
<ide>
<ide> // Test Diffie-Hellman with two parties sharing a secret,
<ide> // using various encodings as we go along
<del>const dh1 = crypto.createDiffieHellman(common.hasFipsCrypto ? 1024 : 256);
<del>const p1 = dh1.getPrime('buffer');
<del>const dh2 = crypto.createDiffieHellman(p1, 'base64');
<del>const key1 = dh1.generateKeys();
<del>const key2 = dh2.generateKeys('hex');
<del>const secret1 = dh1.computeSecret(key2, 'hex', 'base64');
<del>const secret2 = dh2.computeSecret(key1, 'latin1', 'buffer');
<del>
<del>assert.strictEqual(secret1, secret2.toString('base64'));
<del>
<del>// Create "another dh1" using generated keys from dh1,
<del>// and compute secret again
<del>const dh3 = crypto.createDiffieHellman(p1, 'buffer');
<del>const privkey1 = dh1.getPrivateKey();
<del>dh3.setPublicKey(key1);
<del>dh3.setPrivateKey(privkey1);
<del>
<del>assert.strictEqual(dh1.getPrime(), dh3.getPrime());
<del>assert.strictEqual(dh1.getGenerator(), dh3.getGenerator());
<del>assert.strictEqual(dh1.getPublicKey(), dh3.getPublicKey());
<del>assert.strictEqual(dh1.getPrivateKey(), dh3.getPrivateKey());
<del>
<del>const secret3 = dh3.computeSecret(key2, 'hex', 'base64');
<del>
<del>assert.strictEqual(secret1, secret3);
<del>
<del>// https://github.com/joyent/node/issues/2338
<del>const p = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' +
<del> '020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' +
<del> '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' +
<del> 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF';
<del>const d = crypto.createDiffieHellman(p, 'hex');
<del>assert.strictEqual(d.verifyError, DH_NOT_SUITABLE_GENERATOR);
<del>
<del>// Test RSA key signing/verification
<del>const rsaSign = crypto.createSign('SHA1');
<del>const rsaVerify = crypto.createVerify('SHA1');
<del>assert.ok(rsaSign instanceof crypto.Sign);
<del>assert.ok(rsaVerify instanceof crypto.Verify);
<del>
<del>rsaSign.update(rsaPubPem);
<del>const rsaSignature = rsaSign.sign(rsaKeyPem, 'hex');
<del>assert.strictEqual(
<del> rsaSignature,
<del> '5c50e3145c4e2497aadb0eabc83b342d0b0021ece0d4c4a064b7c' +
<del> '8f020d7e2688b122bfb54c724ac9ee169f83f66d2fe90abeb95e8' +
<del> 'e1290e7e177152a4de3d944cf7d4883114a20ed0f78e70e25ef0f' +
<del> '60f06b858e6af42a2f276ede95bbc6bc9a9bbdda15bd663186a6f' +
<del> '40819a7af19e577bb2efa5e579a1f5ce8a0d4ca8b8f6'
<del>);
<del>
<del>rsaVerify.update(rsaPubPem);
<del>assert.strictEqual(rsaVerify.verify(rsaPubPem, rsaSignature, 'hex'), true);
<add>{
<add> const dh1 = crypto.createDiffieHellman(common.hasFipsCrypto ? 1024 : 256);
<add> const p1 = dh1.getPrime('buffer');
<add> const dh2 = crypto.createDiffieHellman(p1, 'base64');
<add> const key1 = dh1.generateKeys();
<add> const key2 = dh2.generateKeys('hex');
<add> const secret1 = dh1.computeSecret(key2, 'hex', 'base64');
<add> const secret2 = dh2.computeSecret(key1, 'latin1', 'buffer');
<add>
<add> assert.strictEqual(secret1, secret2.toString('base64'));
<add>
<add> // Create "another dh1" using generated keys from dh1,
<add> // and compute secret again
<add> const dh3 = crypto.createDiffieHellman(p1, 'buffer');
<add> const privkey1 = dh1.getPrivateKey();
<add> dh3.setPublicKey(key1);
<add> dh3.setPrivateKey(privkey1);
<add>
<add> assert.strictEqual(dh1.getPrime(), dh3.getPrime());
<add> assert.strictEqual(dh1.getGenerator(), dh3.getGenerator());
<add> assert.strictEqual(dh1.getPublicKey(), dh3.getPublicKey());
<add> assert.strictEqual(dh1.getPrivateKey(), dh3.getPrivateKey());
<add>
<add> const secret3 = dh3.computeSecret(key2, 'hex', 'base64');
<add>
<add> assert.strictEqual(secret1, secret3);
<add>
<add> // https://github.com/joyent/node/issues/2338
<add> const p = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' +
<add> '020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' +
<add> '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' +
<add> 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF';
<add> const d = crypto.createDiffieHellman(p, 'hex');
<add> assert.strictEqual(d.verifyError, DH_NOT_SUITABLE_GENERATOR);
<add>
<add> // Test RSA key signing/verification
<add> const rsaSign = crypto.createSign('SHA1');
<add> const rsaVerify = crypto.createVerify('SHA1');
<add> assert.ok(rsaSign instanceof crypto.Sign);
<add> assert.ok(rsaVerify instanceof crypto.Verify);
<add>
<add> rsaSign.update(rsaPubPem);
<add> const rsaSignature = rsaSign.sign(rsaKeyPem, 'hex');
<add> assert.strictEqual(
<add> rsaSignature,
<add> '5c50e3145c4e2497aadb0eabc83b342d0b0021ece0d4c4a064b7c' +
<add> '8f020d7e2688b122bfb54c724ac9ee169f83f66d2fe90abeb95e8' +
<add> 'e1290e7e177152a4de3d944cf7d4883114a20ed0f78e70e25ef0f' +
<add> '60f06b858e6af42a2f276ede95bbc6bc9a9bbdda15bd663186a6f' +
<add> '40819a7af19e577bb2efa5e579a1f5ce8a0d4ca8b8f6'
<add> );
<ide>
<add> rsaVerify.update(rsaPubPem);
<add> assert.strictEqual(rsaVerify.verify(rsaPubPem, rsaSignature, 'hex'), true);
<add>}
<ide>
<ide> //
<ide> // Test RSA signing and verification | 1 |
Python | Python | fix env command in fabfile | fd816bbd1b6ed16cdc9ecbc022cd20153962189d | <ide><path>fabfile.py
<ide> def wrapped_local(cmd, env_vars=[]):
<ide>
<ide>
<ide> def env(lang='python2.7'):
<del> if path.exists(VENV_DIR):
<add> if VENV_DIR.exists():
<ide> local('rm -rf {env}'.format(env=VENV_DIR))
<ide> local('pip install virtualenv')
<ide> local('python -m virtualenv -p {lang} {env}'.format(lang=lang, env=VENV_DIR)) | 1 |
Javascript | Javascript | fix global table of content active element | 79ea22a531c8446710b43df5f6eeb0497719f302 | <ide><path>tools/doc/html.js
<ide> function toHTML({ input, content, filename, nodeVersion, versions }) {
<ide> .replace(/__VERSION__/g, nodeVersion)
<ide> .replace('__TOC__', content.toc)
<ide> .replace('__GTOC__', gtocHTML.replace(
<del> `class="nav-${id}`, `class="nav-${id} active`))
<add> `class="nav-${id}"`, `class="nav-${id} active"`))
<ide> .replace('__EDIT_ON_GITHUB__', editOnGitHub(filename))
<ide> .replace('__CONTENT__', content.toString());
<ide> | 1 |
Javascript | Javascript | remove unused properties | 8ca5749ff98a9cad88467b0d57a117b5c987ceb7 | <ide><path>packages/next-server/server/render.js
<ide> export function renderToHTML (req, res, pathname, query, opts) {
<ide> return doRender(req, res, pathname, query, opts)
<ide> }
<ide>
<del>export function renderErrorToHTML (err, req, res, pathname, query, opts = {}) {
<del> return doRender(req, res, pathname, query, { ...opts, err, page: '/_error' })
<add>// _pathname is for backwards compatibility
<add>export function renderErrorToHTML (err, req, res, _pathname, query, opts = {}) {
<add> return doRender(req, res, '/_error', query, { ...opts, err })
<ide> }
<ide>
<ide> function getPageFiles (buildManifest, page) {
<ide> function getPageFiles (buildManifest, page) {
<ide>
<ide> async function doRender (req, res, pathname, query, {
<ide> err,
<del> page,
<ide> buildId,
<ide> assetPrefix,
<ide> runtimeConfig,
<ide> distDir,
<del> dir,
<ide> dev = false,
<ide> staticMarkup = false,
<ide> nextExport
<ide> } = {}) {
<del> page = page || pathname
<del>
<ide> const documentPath = join(distDir, SERVER_DIRECTORY, CLIENT_STATIC_FILES_PATH, buildId, 'pages', '_document')
<ide> const appPath = join(distDir, SERVER_DIRECTORY, CLIENT_STATIC_FILES_PATH, buildId, 'pages', '_app')
<ide> let [buildManifest, reactLoadableManifest, Component, Document, App] = await Promise.all([
<ide> require(join(distDir, BUILD_MANIFEST)),
<ide> require(join(distDir, REACT_LOADABLE_MANIFEST)),
<del> requirePage(page, {distDir}),
<add> requirePage(pathname, {distDir}),
<ide> require(documentPath),
<ide> require(appPath)
<ide> ])
<ide> async function doRender (req, res, pathname, query, {
<ide> Component = Component.default || Component
<ide>
<ide> if (typeof Component !== 'function') {
<del> throw new Error(`The default export is not a React Component in page: "${page}"`)
<add> throw new Error(`The default export is not a React Component in page: "${pathname}"`)
<ide> }
<ide>
<ide> App = App.default || App
<ide> Document = Document.default || Document
<ide> const asPath = req.url
<del> const ctx = { err, req, res, pathname: page, query, asPath }
<del> const router = new Router(page, query, asPath)
<add> const ctx = { err, req, res, pathname, query, asPath }
<add> const router = new Router(pathname, query, asPath)
<ide> const props = await loadGetInitialProps(App, {Component, router, ctx})
<ide> const devFiles = buildManifest.devFiles
<ide> const files = [
<ide> ...new Set([
<del> ...getPageFiles(buildManifest, page),
<add> ...getPageFiles(buildManifest, pathname),
<ide> ...getPageFiles(buildManifest, '/_app'),
<ide> ...getPageFiles(buildManifest, '/_error')
<ide> ])
<ide> async function doRender (req, res, pathname, query, {
<ide> const doc = <Document {...{
<ide> __NEXT_DATA__: {
<ide> props, // The result of getInitialProps
<del> page, // The rendered page
<add> page: pathname, // The rendered page
<ide> query, // querystring parsed / passed by the user
<ide> buildId, // buildId is used to facilitate caching of page bundles, we send it to the client so that pageloader knows where to load bundles
<ide> assetPrefix: assetPrefix === '' ? undefined : assetPrefix, // send assetPrefix to the client side when configured, otherwise don't sent in the resulting HTML
<ide> async function doRender (req, res, pathname, query, {
<ide> dynamicIds: dynamicImportsIds.length === 0 ? undefined : dynamicImportsIds,
<ide> err: (err) ? serializeError(dev, err) : undefined // Error if one happened, otherwise don't sent in the resulting HTML
<ide> },
<del> dev,
<del> dir,
<ide> staticMarkup,
<del> buildManifest,
<ide> devFiles,
<ide> files,
<ide> dynamicImports,
<ide> export function sendHTML (req, res, html, method, { dev, generateEtags }) {
<ide>
<ide> if (dev) {
<ide> // In dev, we should not cache pages for any reason.
<del> // That's why we do this.
<ide> res.setHeader('Cache-Control', 'no-store, must-revalidate')
<ide> }
<ide> | 1 |
Ruby | Ruby | require active_support at the railties | 0bef6ff9af6be8d0def825a09188697526f7dae2 | <ide><path>activesupport/lib/active_support/i18n_railtie.rb
<add>require "active_support"
<ide> require "active_support/file_update_checker"
<ide> require "active_support/core_ext/array/wrap"
<ide>
<ide><path>activesupport/lib/active_support/railtie.rb
<add>require "active_support"
<ide> require "active_support/i18n_railtie"
<ide>
<ide> module ActiveSupport | 2 |
PHP | PHP | support multiple addresses in array | 64f6f170e9c8f61dd61ef6f75aae633f9547b8b9 | <ide><path>src/Illuminate/Notifications/Messages/MailMessage.php
<ide>
<ide> namespace Illuminate\Notifications\Messages;
<ide>
<add>use Traversable;
<add>use Illuminate\Contracts\Support\Arrayable;
<add>
<ide> class MailMessage extends SimpleMessage
<ide> {
<ide> /**
<ide> public function from($address, $name = null)
<ide> */
<ide> public function replyTo($address, $name = null)
<ide> {
<del> $this->replyTo[] = [$address, $name];
<add> if (is_array($address) || $address instanceof Arrayable || $address instanceof Traversable) {
<add> $this->replyTo += $this->prepareAddress($address);
<add> } else {
<add> $this->replyTo[] = [$address, $name];
<add> }
<ide>
<ide> return $this;
<ide> }
<ide>
<ide> /**
<ide> * Set the cc address for the mail message.
<ide> *
<del> * @param string $address
<add> * @param array|string $address
<ide> * @param string|null $name
<ide> * @return $this
<ide> */
<ide> public function cc($address, $name = null)
<ide> {
<del> $this->cc[] = [$address, $name];
<add> if (is_array($address) || $address instanceof Arrayable || $address instanceof Traversable) {
<add> $this->cc += $this->prepareAddress($address);
<add> } else {
<add> $this->cc[] = [$address, $name];
<add> }
<ide>
<ide> return $this;
<ide> }
<ide>
<ide> /**
<ide> * Set the bcc address for the mail message.
<ide> *
<del> * @param string $address
<add> * @param array|string $address
<ide> * @param string|null $name
<ide> * @return $this
<ide> */
<ide> public function bcc($address, $name = null)
<ide> {
<del> $this->bcc[] = [$address, $name];
<add> if (is_array($address) || $address instanceof Arrayable || $address instanceof Traversable) {
<add> $this->bcc += $this->prepareAddress($address);
<add> } else {
<add> $this->bcc[] = [$address, $name];
<add> }
<ide>
<ide> return $this;
<ide> }
<ide> public function data()
<ide> {
<ide> return array_merge($this->toArray(), $this->viewData);
<ide> }
<add>
<add> /**
<add> * Prepare address input for support multiple recipients.
<add> *
<add> * @param array $value
<add> * @return array
<add> */
<add> protected function prepareAddress($value)
<add> {
<add> $recipients = [];
<add> foreach ($value as $name => $address) {
<add> $recipients[] = [$address, is_numeric($name) ? null : $name];
<add> }
<add>
<add> return $recipients;
<add> }
<ide> }
<ide><path>tests/Notifications/NotificationMailMessageTest.php
<ide> public function testCcIsSetCorrectly()
<ide> ->cc('test@example.com', 'Test');
<ide>
<ide> $this->assertSame([['test@example.com', null], ['test@example.com', 'Test']], $message->cc);
<add>
<add> $message = new MailMessage;
<add> $message->cc(['test@example.com', 'Test' => 'test@example.com']);
<add>
<add> $this->assertSame([['test@example.com', null], ['test@example.com', 'Test']], $message->cc);
<ide> }
<ide>
<ide> public function testBccIsSetCorrectly()
<ide> public function testBccIsSetCorrectly()
<ide> ->bcc('test@example.com', 'Test');
<ide>
<ide> $this->assertSame([['test@example.com', null], ['test@example.com', 'Test']], $message->bcc);
<add>
<add> $message = new MailMessage;
<add> $message->bcc(['test@example.com', 'Test' => 'test@example.com']);
<add>
<add> $this->assertSame([['test@example.com', null], ['test@example.com', 'Test']], $message->bcc);
<ide> }
<ide>
<ide> public function testReplyToIsSetCorrectly()
<ide> public function testReplyToIsSetCorrectly()
<ide> ->replyTo('test@example.com', 'Test');
<ide>
<ide> $this->assertSame([['test@example.com', null], ['test@example.com', 'Test']], $message->replyTo);
<add>
<add> $message = new MailMessage;
<add> $message->replyTo(['test@example.com', 'Test' => 'test@example.com']);
<add>
<add> $this->assertSame([['test@example.com', null], ['test@example.com', 'Test']], $message->replyTo);
<ide> }
<ide> } | 2 |
Go | Go | update testswarmnetworkplugin test | 2cc2d059ded77c4c5afa6704194cae5bc0c64cf5 | <ide><path>integration-cli/docker_cli_swarm_test.go
<ide> func (s *DockerSwarmSuite) TestSwarmNetworkPlugin(c *check.C) {
<ide> d := s.AddDaemon(c, true, true)
<ide>
<ide> out, err := d.Cmd("network", "create", "-d", globalNetworkPlugin, "foo")
<del> c.Assert(err, checker.IsNil)
<del> c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
<del>
<del> name := "top"
<del> out, err = d.Cmd("service", "create", "--name", name, "--network", "foo", "busybox", "top")
<del> c.Assert(err, checker.IsNil)
<del> c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
<del>
<del> out, err = d.Cmd("service", "inspect", "--format", "{{range .Spec.Networks}}{{.Target}}{{end}}", name)
<del> c.Assert(err, checker.IsNil)
<del> c.Assert(strings.TrimSpace(out), checker.Equals, "foo")
<add> c.Assert(err, checker.NotNil)
<add> c.Assert(out, checker.Contains, "not supported in swarm mode")
<ide> }
<ide>
<ide> // Test case for #24712 | 1 |
PHP | PHP | fix datetime typehints | 02623f89912017f4dcea3c040139544bb74c14fa | <ide><path>src/Illuminate/Contracts/Mail/Mailable.php
<ide> public function queue(Queue $queue);
<ide> /**
<ide> * Deliver the queued message after the given delay.
<ide> *
<del> * @param \DateTime|int $delay
<add> * @param \DateTimeInterface|\DateInterval|int $delay
<ide> * @param \Illuminate\Contracts\Queue\Factory $queue
<ide> * @return mixed
<ide> */
<ide><path>src/Illuminate/Foundation/Bus/PendingDispatch.php
<ide> public function allOnQueue($queue)
<ide> /**
<ide> * Set the desired delay for the job.
<ide> *
<del> * @param \DateTime|int|null $delay
<add> * @param \DateTimeInterface|\DateInterval|int|null $delay
<ide> * @return $this
<ide> */
<ide> public function delay($delay)
<ide><path>src/Illuminate/Support/Testing/Fakes/QueueFake.php
<ide> public function pushRaw($payload, $queue = null, array $options = [])
<ide> /**
<ide> * Push a new job onto the queue after a delay.
<ide> *
<del> * @param \DateTime|int $delay
<add> * @param \DateTimeInterface|\DateInterval|int $delay
<ide> * @param string $job
<ide> * @param mixed $data
<ide> * @param string $queue
<ide> public function pushOn($queue, $job, $data = '')
<ide> * Push a new job onto the queue after a delay.
<ide> *
<ide> * @param string $queue
<del> * @param \DateTime|int $delay
<add> * @param \DateTimeInterface|\DateInterval|int $delay
<ide> * @param string $job
<ide> * @param mixed $data
<ide> * @return mixed | 3 |
Javascript | Javascript | add the tutorial collection to gdocs.js | 9701f0735b31661cc58f4a9ae8077bf6de17302e | <ide><path>gdocs.js
<ide> var fs = require('fs');
<ide> var collections = {
<ide> 'guide': 'http://docs.google.com/feeds/default/private/full/folder%3A0B9PsajIPqzmANGUwMGVhZmYtMTk1ZC00NTdmLWIxMDAtZGI5YWNlZjQ2YjZl/contents',
<ide> 'api': 'http://docs.google.com/feeds/default/private/full/folder%3A0B7Ovm8bUYiUDYjMwYTc2YWUtZTgzYy00YjIxLThlZDYtYWJlOTFlNzE2NzEw/contents',
<add> 'tutorial': 'http://docs.google.com/feeds/default/private/full/folder%3A0B9PsajIPqzmAYWMxYWE3MzYtYzdjYS00OGQxLWJhZjItYzZkMzJiZTRhZjFl/contents',
<ide> 'cookbook': 'http://docs.google.com/feeds/default/private/full/folder%3A0B7Ovm8bUYiUDNzkxZWM5ZTItN2M5NC00NWIxLTg2ZDMtMmYwNDY1NWM1MGU4/contents',
<ide> 'misc': 'http://docs.google.com/feeds/default/private/full/folder%3A0B7Ovm8bUYiUDZjVlNmZkYzQtMjZlOC00NmZhLWI5MjAtMGRjZjlkOGJkMDBi/contents'
<ide> } | 1 |
PHP | PHP | fix a bunch of boo boo tests | eb762a14227924d16f8af5a6b4bb27cd5917135c | <ide><path>tests/Database/DatabaseEloquentIntegrationTest.php
<ide> <?php
<ide>
<ide> use Illuminate\Database\Connection;
<add>use Illuminate\Database\Capsule\Manager as DB;
<ide> use Illuminate\Database\Eloquent\Model as Eloquent;
<ide> use Illuminate\Database\Eloquent\Relations\Relation;
<ide> use Illuminate\Pagination\AbstractPaginator as Paginator;
<del>use Illuminate\Database\Capsule\Manager as DB;
<ide>
<ide> class DatabaseEloquentIntegrationTest extends PHPUnit_Framework_TestCase
<ide> {
<ide> class DatabaseEloquentIntegrationTest extends PHPUnit_Framework_TestCase
<ide> public function setUp()
<ide> {
<ide> $db = new DB;
<add>
<ide> $db->addConnection([
<ide> 'driver' => 'sqlite',
<ide> 'database' => ':memory:',
<ide> ]);
<add>
<add> $db->addConnection([
<add> 'driver' => 'sqlite',
<add> 'database' => ':memory:',
<add> ], 'second_connection');
<add>
<ide> $db->bootEloquent();
<ide> $db->setAsGlobal();
<ide>
<del> $this->schema()->create('users', function ($table) {
<del> $table->increments('id');
<del> $table->string('email')->unique();
<del> $table->timestamps();
<del> });
<add> $this->createSchema();
<add> }
<ide>
<del> $this->schema()->create('friends', function ($table) {
<del> $table->integer('user_id');
<del> $table->integer('friend_id');
<del> });
<add> protected function createSchema()
<add> {
<add> foreach (['default', 'second_connection'] as $connection) {
<add> $this->schema($connection)->create('users', function ($table) {
<add> $table->increments('id');
<add> $table->string('email');
<add> $table->timestamps();
<add> });
<ide>
<del> $this->schema()->create('posts', function ($table) {
<del> $table->increments('id');
<del> $table->integer('user_id');
<del> $table->integer('parent_id')->nullable();
<del> $table->string('name');
<del> $table->timestamps();
<del> });
<add> $this->schema($connection)->create('friends', function ($table) {
<add> $table->integer('user_id');
<add> $table->integer('friend_id');
<add> });
<ide>
<del> $this->schema()->create('photos', function ($table) {
<del> $table->increments('id');
<del> $table->morphs('imageable');
<del> $table->string('name');
<del> $table->timestamps();
<del> });
<add> $this->schema($connection)->create('posts', function ($table) {
<add> $table->increments('id');
<add> $table->integer('user_id');
<add> $table->integer('parent_id')->nullable();
<add> $table->string('name');
<add> $table->timestamps();
<add> });
<add>
<add> $this->schema($connection)->create('photos', function ($table) {
<add> $table->increments('id');
<add> $table->morphs('imageable');
<add> $table->string('name');
<add> $table->timestamps();
<add> });
<add> }
<ide> }
<ide>
<ide> /**
<ide> public function setUp()
<ide> */
<ide> public function tearDown()
<ide> {
<del> $this->schema()->drop('users');
<del> $this->schema()->drop('friends');
<del> $this->schema()->drop('posts');
<del> $this->schema()->drop('photos');
<add> foreach (['default', 'second_connection'] as $connection) {
<add> $this->schema($connection)->drop('users');
<add> $this->schema($connection)->drop('friends');
<add> $this->schema($connection)->drop('posts');
<add> $this->schema($connection)->drop('photos');
<add> }
<ide>
<ide> Relation::morphMap([], false);
<ide> }
<ide> public function testOneToManyRelationship()
<ide>
<ide> public function testBasicModelHydration()
<ide> {
<del> EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);
<del> EloquentTestUser::create(['email' => 'abigailotwell@gmail.com']);
<add> $user = new EloquentTestUser(['email' => 'taylorotwell@gmail.com']);
<add> $user->setConnection('second_connection');
<add> $user->save();
<add>
<add> $user = new EloquentTestUser(['email' => 'abigailotwell@gmail.com']);
<add> $user->setConnection('second_connection');
<add> $user->save();
<ide>
<del> $models = EloquentTestUser::hydrateRaw('SELECT * FROM users WHERE email = ?', ['abigailotwell@gmail.com'], 'foo_connection');
<add> $models = EloquentTestUser::hydrateRaw('SELECT * FROM users WHERE email = ?', ['abigailotwell@gmail.com'], 'second_connection');
<ide>
<ide> $this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $models);
<ide> $this->assertInstanceOf('EloquentTestUser', $models[0]);
<ide> $this->assertEquals('abigailotwell@gmail.com', $models[0]->email);
<del> $this->assertEquals('foo_connection', $models[0]->getConnectionName());
<add> $this->assertEquals('second_connection', $models[0]->getConnectionName());
<ide> $this->assertEquals(1, $models->count());
<ide> }
<ide>
<ide> public function testMorphMapOverwritesCurrentMap()
<ide>
<ide> public function testEmptyMorphToRelationship()
<ide> {
<del> $photo = EloquentTestPhoto::create(['name' => 'Avatar 1']);
<add> $photo = new EloquentTestPhoto;
<ide>
<ide> $this->assertNull($photo->imageable);
<ide> }
<ide> public function testToArrayIncludesCustomFormattedTimestamps()
<ide> *
<ide> * @return Connection
<ide> */
<del> protected function connection()
<add> protected function connection($connection = 'default')
<ide> {
<del> return Eloquent::getConnectionResolver()->connection();
<add> return Eloquent::getConnectionResolver()->connection($connection);
<ide> }
<ide>
<ide> /**
<ide> * Get a schema builder instance.
<ide> *
<ide> * @return Schema\Builder
<ide> */
<del> protected function schema()
<add> protected function schema($connection = 'default')
<ide> {
<del> return $this->connection()->getSchemaBuilder();
<add> return $this->connection($connection)->getSchemaBuilder();
<ide> }
<ide> }
<ide>
<ide><path>tests/Database/DatabaseEloquentIntegrationWithTablePrefixTest.php
<ide> <?php
<ide>
<add>use Illuminate\Database\Capsule\Manager as DB;
<ide> use Illuminate\Database\Eloquent\Model as Eloquent;
<ide>
<del>class DatabaseEloquentIntegrationWithTablePrefixTest extends DatabaseEloquentIntegrationTest
<add>class DatabaseEloquentIntegrationWithTablePrefixTest
<ide> {
<ide> /**
<ide> * Bootstrap Eloquent.
<ide> *
<ide> * @return void
<ide> */
<del> public static function setUpBeforeClass()
<add> public function setUp()
<ide> {
<del> $resolver = new DatabaseIntegrationTestConnectionResolver;
<del> $resolver->connection()->setTablePrefix('prefix_');
<del> Eloquent::setConnectionResolver($resolver);
<add> $db = new DB;
<ide>
<del> Eloquent::setEventDispatcher(
<del> new Illuminate\Events\Dispatcher
<del> );
<add> $db->addConnection([
<add> 'driver' => 'sqlite',
<add> 'database' => ':memory:',
<add> ]);
<add>
<add> $db->bootEloquent();
<add> $db->setAsGlobal();
<add>
<add> Eloquent::getConnectionResolver()->connection()->setTablePrefix('prefix_');
<add>
<add> $this->createSchema();
<add> }
<add>
<add> protected function createSchema()
<add> {
<add> foreach (['default'] as $connection) {
<add> $this->schema($connection)->create('users', function ($table) {
<add> $table->increments('id');
<add> $table->string('email');
<add> $table->timestamps();
<add> });
<add>
<add> $this->schema($connection)->create('friends', function ($table) {
<add> $table->integer('user_id');
<add> $table->integer('friend_id');
<add> });
<add>
<add> $this->schema($connection)->create('posts', function ($table) {
<add> $table->increments('id');
<add> $table->integer('user_id');
<add> $table->integer('parent_id')->nullable();
<add> $table->string('name');
<add> $table->timestamps();
<add> });
<add>
<add> $this->schema($connection)->create('photos', function ($table) {
<add> $table->increments('id');
<add> $table->morphs('imageable');
<add> $table->string('name');
<add> $table->timestamps();
<add> });
<add> }
<add> }
<add>
<add> /**
<add> * Tear down the database schema.
<add> *
<add> * @return void
<add> */
<add> public function tearDown()
<add> {
<add> foreach (['default'] as $connection) {
<add> $this->schema($connection)->drop('users');
<add> $this->schema($connection)->drop('friends');
<add> $this->schema($connection)->drop('posts');
<add> $this->schema($connection)->drop('photos');
<add> }
<add>
<add> Relation::morphMap([], false);
<ide> }
<ide>
<ide> public function testBasicModelHydration() | 2 |
Javascript | Javascript | warn users when passing a weird object as options | b3bc5427969e15fd3663d9a1c57dbd1eb2c94805 | <ide><path>lib/webpack.js
<ide> function webpack(options, callback) {
<ide> return webpack(options);
<ide> }));
<ide> } else if(typeof options === "object") {
<add> if(!options.entry && !options.plugins) {
<add> throw new Error("Passed 'options' object don't look like a valid webpack configuration");
<add> }
<ide> new WebpackOptionsDefaulter().process(options);
<ide>
<ide> compiler = new Compiler(); | 1 |
Javascript | Javascript | rerender link on routing state change | e189688d40c738ce3ccbdde39f336d50e6909432 | <ide><path>packages/ember-routing-views/lib/views/link.js
<ide> var LinkComponent = EmberComponent.extend({
<ide>
<ide> if (get(this, 'loading')) { return get(this, 'loadingHref'); }
<ide>
<add> targetRouteName = this._handleOnlyQueryParamsSupplied(targetRouteName);
<add>
<ide> var routing = get(this, '_routing');
<ide> var queryParams = get(this, 'queryParams.values');
<ide> return routing.generateURL(targetRouteName, models, queryParams);
<ide> var LinkComponent = EmberComponent.extend({
<ide> }
<ide> }),
<ide>
<add> _handleOnlyQueryParamsSupplied(route) {
<add> var params = this.attrs.params.slice();
<add> var lastParam = params[params.length - 1];
<add> if (lastParam && lastParam.isQueryParams) {
<add> params.pop();
<add> }
<add> let onlyQueryParamsSupplied = (params.length === 0);
<add> if (onlyQueryParamsSupplied) {
<add> var appController = this.container.lookup('controller:application');
<add> if (appController) {
<add> return get(appController, 'currentRouteName');
<add> }
<add> }
<add> return route;
<add> },
<add>
<ide> /**
<ide> The default href value to use while a link-to is loading.
<ide> Only applies when tagName is 'a'
<ide> var LinkComponent = EmberComponent.extend({
<ide>
<ide> let targetRouteName;
<ide> let models = [];
<del> let onlyQueryParamsSupplied = (params.length === 0);
<del>
<del> if (onlyQueryParamsSupplied) {
<del> var appController = this.container.lookup('controller:application');
<del> if (appController) {
<del> targetRouteName = get(appController, 'currentRouteName');
<del> }
<del> } else {
<del> targetRouteName = params[0];
<add> targetRouteName = this._handleOnlyQueryParamsSupplied(params[0]);
<ide>
<del> for (let i = 1; i < params.length; i++) {
<del> models.push(params[i]);
<del> }
<add> for (let i = 1; i < params.length; i++) {
<add> models.push(params[i]);
<ide> }
<ide>
<ide> let resolvedQueryParams = getResolvedQueryParams(queryParams, targetRouteName);
<ide><path>packages/ember/tests/helpers/link_to_test.js
<ide> QUnit.test('{{link-to}} populates href with fully supplied query param values',
<ide> bootApplication();
<ide> equal(Ember.$('#the-link').attr('href'), '/?bar=NAW&foo=456', 'link has right href');
<ide> });
<add>
<add>QUnit.test('{{link-to}} with only query-params updates when route changes', function() {
<add> Router.map(function() {
<add> this.route('about');
<add> });
<add>
<add> if (isEnabled('ember-routing-route-configured-query-params')) {
<add> App.ApplicationRoute = Ember.Route.extend({
<add> queryParams: {
<add> foo: {
<add> defaultValue: '123'
<add> },
<add> bar: {
<add> defaultValue: 'yes'
<add> }
<add> }
<add> });
<add> } else {
<add> App.ApplicationController = Ember.Controller.extend({
<add> queryParams: ['foo', 'bar'],
<add> foo: '123',
<add> bar: 'yes'
<add> });
<add> }
<add>
<add> Ember.TEMPLATES.application = compile('{{#link-to (query-params foo=\'456\' bar=\'NAW\') id=\'the-link\'}}Index{{/link-to}}');
<add> bootApplication();
<add> equal(Ember.$('#the-link').attr('href'), '/?bar=NAW&foo=456', 'link has right href');
<add>
<add> Ember.run(function() {
<add> router.handleURL('/about');
<add> });
<add> equal(Ember.$('#the-link').attr('href'), '/about?bar=NAW&foo=456', 'link has right href');
<add>}); | 2 |
Python | Python | fix termination of asynloop | c06ae78bf6edd3ea7ed96aa2e3e541ef690ef6e7 | <ide><path>celery/worker/loops.py
<ide> import socket
<ide>
<ide> from celery import bootsteps
<del>from celery.exceptions import WorkerLostError, WorkerShutdown, WorkerTerminate
<add>from celery.exceptions import WorkerLostError
<ide> from celery.utils.log import get_logger
<ide>
<ide> from . import state
<ide> def asynloop(obj, connection, consumer, blueprint, hub, qos,
<ide>
<ide> try:
<ide> while blueprint.state == RUN and obj.connection:
<del> # shutdown if signal handlers told us to.
<del> should_stop, should_terminate = (
<del> state.should_stop, state.should_terminate,
<del> )
<del> # False == EX_OK, so must use is not False
<del> if should_stop is not None and should_stop is not False:
<del> raise WorkerShutdown(should_stop)
<del> elif should_terminate is not None and should_stop is not False:
<del> raise WorkerTerminate(should_terminate)
<add> state.maybe_shutdown()
<ide>
<ide> # We only update QoS when there's no more messages to read.
<ide> # This groups together qos calls, and makes sure that remote
<ide><path>celery/worker/state.py
<ide> def reset_state():
<ide>
<ide> def maybe_shutdown():
<ide> """Shutdown if flags have been set."""
<del> if should_stop is not None and should_stop is not False:
<del> raise WorkerShutdown(should_stop)
<del> elif should_terminate is not None and should_terminate is not False:
<add> if should_terminate is not None and should_terminate is not False:
<ide> raise WorkerTerminate(should_terminate)
<add> elif should_stop is not None and should_stop is not False:
<add> raise WorkerShutdown(should_stop)
<ide>
<ide>
<ide> def task_reserved(request,
<ide><path>t/unit/worker/test_loops.py
<ide> from celery.exceptions import (InvalidTaskError, WorkerLostError,
<ide> WorkerShutdown, WorkerTerminate)
<ide> from celery.five import Empty, python_2_unicode_compatible
<del>from celery.platforms import EX_FAILURE
<add>from celery.platforms import EX_FAILURE, EX_OK
<ide> from celery.worker import state
<ide> from celery.worker.consumer import Consumer
<ide> from celery.worker.loops import _quick_drain, asynloop, synloop
<ide> def test_on_task_DecodeError(self):
<ide> on_task(msg)
<ide> x.on_decode_error.assert_called_with(msg, exc)
<ide>
<del> def test_should_terminate(self):
<add> @pytest.mark.parametrize('should_stop', (None, False, True, EX_OK))
<add> def test_should_terminate(self, should_stop):
<ide> x = X(self.app)
<del> # XXX why aren't the errors propagated?!?
<add> state.should_stop = should_stop
<ide> state.should_terminate = True
<ide> try:
<ide> with pytest.raises(WorkerTerminate):
<ide> asynloop(*x.args)
<ide> finally:
<add> state.should_stop = None
<ide> state.should_terminate = None
<ide>
<ide> def test_should_terminate_hub_close_raises(self):
<ide><path>t/unit/worker/test_state.py
<ide> from case import Mock, patch
<ide> from celery import uuid
<ide> from celery.exceptions import WorkerShutdown, WorkerTerminate
<add>from celery.platforms import EX_OK
<ide> from celery.utils.collections import LimitedSet
<ide> from celery.worker import state
<ide>
<ide> def test_should_stop(self):
<ide> else:
<ide> raise RuntimeError('should have exited')
<ide>
<del> def test_should_terminate(self):
<add> @pytest.mark.parametrize('should_stop', (None, False, True, EX_OK))
<add> def test_should_terminate(self, should_stop):
<add> state.should_stop = should_stop
<ide> state.should_terminate = True
<ide> with pytest.raises(WorkerTerminate):
<ide> state.maybe_shutdown() | 4 |
PHP | PHP | fix malformed dataproviders | ad124a3260641e0c0f129544cc92df83d4a03105 | <ide><path>tests/TestCase/Controller/Component/CsrfComponentTest.php
<ide> public function testSettingCookie()
<ide> public static function safeHttpMethodProvider()
<ide> {
<ide> return [
<del> ['GET', 'HEAD']
<add> ['GET'],
<add> ['HEAD'],
<ide> ];
<ide> }
<ide>
<ide><path>tests/TestCase/Database/Schema/TableTest.php
<ide> public function testAddConstraintOverwriteUniqueIndex()
<ide> *
<ide> * @return array
<ide> */
<del> public static function addConstaintErrorProvider()
<add> public static function addConstraintErrorProvider()
<ide> {
<ide> return [
<ide> // No properties
<ide> public static function addConstaintErrorProvider()
<ide> * Test that an exception is raised when constraints
<ide> * are added for fields that do not exist.
<ide> *
<del> * @dataProvider addConstaintErrorProvider
<add> * @dataProvider addConstraintErrorProvider
<ide> * @expectedException \Cake\Database\Exception
<ide> * @return void
<ide> */
<ide><path>tests/TestCase/ORM/CompositeKeysTest.php
<ide> public function testBelongsToEager($strategy)
<ide> }
<ide>
<ide> /**
<del> * Tests loding hasOne with composite keys
<add> * Tests loading hasOne with composite keys
<ide> *
<ide> * @dataProvider strategiesProviderHasOne
<ide> * @return void
<ide><path>tests/TestCase/ORM/EntityTest.php
<ide> public function emptyNamesProvider()
<ide> return [[''], [null], [false]];
<ide> }
<ide> /**
<del> * Tests that trying to get an empty propery name throws exception
<add> * Tests that trying to get an empty propetry name throws exception
<ide> *
<ide> * @dataProvider emptyNamesProvider
<ide> * @expectedException \InvalidArgumentException
<ide> public function testEmptyProperties($property)
<ide> }
<ide>
<ide> /**
<del> * Tests that setitng an empty property name does nothing
<add> * Tests that setting an empty property name does nothing
<ide> *
<ide> * @expectedException \InvalidArgumentException
<ide> * @dataProvider emptyNamesProvider
<ide><path>tests/TestCase/ORM/QueryRegressionTest.php
<ide> public function testReciprocalBelongsToManyNoOverwrite()
<ide> */
<ide> public function strategyProvider()
<ide> {
<del> return [['append', 'replace']];
<add> return [
<add> ['append'],
<add> ['replace'],
<add> ];
<ide> }
<ide>
<ide> /** | 5 |
Ruby | Ruby | include missing modules | d92e8554921b7ab1906fd657325f395413cbdb30 | <ide><path>actionpack/lib/action_controller/metal/redirecting.rb
<ide> module Redirecting
<ide> extend ActiveSupport::Concern
<ide>
<ide> include AbstractController::Logger
<add> include ActionController::RackDelegation
<ide> include ActionController::UrlFor
<ide>
<ide> # Redirects the browser to the target specified in +options+. This parameter can take one of three forms:
<ide><path>actionpack/lib/action_controller/metal/rendering.rb
<ide> module ActionController
<ide> module Rendering
<ide> extend ActiveSupport::Concern
<ide>
<del> include RackDelegation
<add> include ActionController::RackDelegation
<ide> include AbstractController::Rendering
<ide> include AbstractController::LocalizedCache
<ide>
<ide><path>actionpack/lib/action_view/base.rb
<ide> class MissingTemplate < ActionViewError #:nodoc:
<ide>
<ide> def initialize(paths, path, details, partial)
<ide> @path = path
<del> display_paths = paths.compact.join(":")
<add> display_paths = paths.compact.map{ |p| p.to_s.inspect }.join(", ")
<ide> template_type = if partial
<ide> "partial"
<ide> elsif path =~ /layouts/i
<ide> def initialize(paths, path, details, partial)
<ide> 'template'
<ide> end
<ide>
<del> super("Missing #{template_type} #{path} with #{details.inspect} in view path #{display_paths}")
<add> super("Missing #{template_type} #{path} with #{details.inspect} in view paths #{display_paths}")
<ide> end
<ide> end
<ide> | 3 |
PHP | PHP | add afterloadingenvironment() test | daa6894a628f596f79edf861ef4f11ba69ef2be4 | <ide><path>tests/Foundation/FoundationApplicationTest.php
<ide> public function testEnvironment()
<ide> $this->assertFalse($app->environment('qux', 'bar'));
<ide> $this->assertFalse($app->environment(['qux', 'bar']));
<ide> }
<add>
<add> public function testMethodAfterLoadingEnvironmentAddsClosure()
<add> {
<add> $app = new Application;
<add> $closure = function(){};
<add> $app->afterLoadingEnvironment($closure);
<add> $eventName = 'bootstrapped: '
<add> .'Illuminate\Foundation\Bootstrap\DetectEnvironment';
<add> $this->assertTrue(isset($app['events']->getListeners($eventName)[0]));
<add> $this->assertSame($closure, $app['events']->getListeners($eventName)[0]);
<add> }
<ide> }
<ide>
<ide> class ApplicationDeferredSharedServiceProviderStub extends Illuminate\Support\ServiceProvider | 1 |
Ruby | Ruby | move softwarespec to a separate file | a31fcb554c1c1ca247bf10073a8c2425afe19a82 | <ide><path>Library/Homebrew/formula.rb
<ide> require 'build_environment'
<ide> require 'build_options'
<ide> require 'formulary'
<add>require 'software_spec'
<ide>
<ide>
<ide> class Formula
<ide><path>Library/Homebrew/formula_support.rb
<del>require 'download_strategy'
<del>require 'checksum'
<del>require 'version'
<del>
<ide> FormulaConflict = Struct.new(:name, :reason)
<ide>
<del>class SoftwareSpec
<del> attr_reader :checksum, :mirrors, :specs
<del> attr_reader :using # for auditing
<del>
<del> def initialize url=nil, version=nil
<del> @url = url
<del> @version = version
<del> @mirrors = []
<del> @specs = {}
<del> @checksum = nil
<del> @using = nil
<del> end
<del>
<del> def download_strategy
<del> @download_strategy ||= DownloadStrategyDetector.detect(url, using)
<del> end
<del>
<del> def verify_download_integrity fn
<del> fn.verify_checksum(checksum)
<del> rescue ChecksumMissingError
<del> opoo "Cannot verify package integrity"
<del> puts "The formula did not provide a download checksum"
<del> puts "For your reference the SHA1 is: #{fn.sha1}"
<del> rescue ChecksumMismatchError => e
<del> e.advice = <<-EOS.undent
<del> Archive: #{fn}
<del> (To retry an incomplete download, remove the file above.)
<del> EOS
<del> raise e
<del> end
<del>
<del> def detect_version(val)
<del> case val
<del> when nil then Version.detect(url, specs)
<del> when String then Version.new(val)
<del> when Hash then Version.new_with_scheme(*val.shift)
<del> else
<del> raise TypeError, "version '#{val.inspect}' should be a string"
<del> end
<del> end
<del>
<del> # The methods that follow are used in the block-form DSL spec methods
<del> Checksum::TYPES.each do |cksum|
<del> class_eval <<-EOS, __FILE__, __LINE__ + 1
<del> def #{cksum}(val)
<del> @checksum = Checksum.new(:#{cksum}, val)
<del> end
<del> EOS
<del> end
<del>
<del> def url val=nil, specs={}
<del> return @url if val.nil?
<del> @url = val
<del> @using = specs.delete(:using)
<del> @specs.merge!(specs)
<del> end
<del>
<del> def version val=nil
<del> @version ||= detect_version(val)
<del> end
<del>
<del> def mirror val
<del> mirrors << val
<del> end
<del>end
<del>
<del>class HeadSoftwareSpec < SoftwareSpec
<del> def initialize url=nil, version=Version.new(:HEAD)
<del> super
<del> end
<del>
<del> def verify_download_integrity fn
<del> return
<del> end
<del>end
<del>
<del>class Bottle < SoftwareSpec
<del> attr_writer :url
<del> attr_rw :root_url, :prefix, :cellar, :revision
<del>
<del> def initialize
<del> super
<del> @revision = 0
<del> @prefix = '/usr/local'
<del> @cellar = '/usr/local/Cellar'
<del> end
<del>
<del> # Checksum methods in the DSL's bottle block optionally take
<del> # a Hash, which indicates the platform the checksum applies on.
<del> Checksum::TYPES.each do |cksum|
<del> class_eval <<-EOS, __FILE__, __LINE__ + 1
<del> def #{cksum}(val=nil)
<del> return @#{cksum} if val.nil?
<del> @#{cksum} ||= Hash.new
<del> case val
<del> when Hash
<del> key, value = val.shift
<del> @#{cksum}[value] = Checksum.new(:#{cksum}, key)
<del> end
<del>
<del> if @#{cksum}.has_key? bottle_tag
<del> @checksum = @#{cksum}[bottle_tag]
<del> end
<del> end
<del> EOS
<del> end
<del>end
<del>
<del>
<ide> # Used to annotate formulae that duplicate OS X provided software
<ide> # or cause conflicts when linked in.
<ide> class KegOnlyReason
<ide><path>Library/Homebrew/software_spec.rb
<add>require 'download_strategy'
<add>require 'checksum'
<add>require 'version'
<add>
<add>class SoftwareSpec
<add> attr_reader :checksum, :mirrors, :specs
<add> attr_reader :using # for auditing
<add>
<add> def initialize url=nil, version=nil
<add> @url = url
<add> @version = version
<add> @mirrors = []
<add> @specs = {}
<add> @checksum = nil
<add> @using = nil
<add> end
<add>
<add> def download_strategy
<add> @download_strategy ||= DownloadStrategyDetector.detect(url, using)
<add> end
<add>
<add> def verify_download_integrity fn
<add> fn.verify_checksum(checksum)
<add> rescue ChecksumMissingError
<add> opoo "Cannot verify package integrity"
<add> puts "The formula did not provide a download checksum"
<add> puts "For your reference the SHA1 is: #{fn.sha1}"
<add> rescue ChecksumMismatchError => e
<add> e.advice = <<-EOS.undent
<add> Archive: #{fn}
<add> (To retry an incomplete download, remove the file above.)
<add> EOS
<add> raise e
<add> end
<add>
<add> def detect_version(val)
<add> case val
<add> when nil then Version.detect(url, specs)
<add> when String then Version.new(val)
<add> when Hash then Version.new_with_scheme(*val.shift)
<add> else
<add> raise TypeError, "version '#{val.inspect}' should be a string"
<add> end
<add> end
<add>
<add> # The methods that follow are used in the block-form DSL spec methods
<add> Checksum::TYPES.each do |cksum|
<add> class_eval <<-EOS, __FILE__, __LINE__ + 1
<add> def #{cksum}(val)
<add> @checksum = Checksum.new(:#{cksum}, val)
<add> end
<add> EOS
<add> end
<add>
<add> def url val=nil, specs={}
<add> return @url if val.nil?
<add> @url = val
<add> @using = specs.delete(:using)
<add> @specs.merge!(specs)
<add> end
<add>
<add> def version val=nil
<add> @version ||= detect_version(val)
<add> end
<add>
<add> def mirror val
<add> mirrors << val
<add> end
<add>end
<add>
<add>class HeadSoftwareSpec < SoftwareSpec
<add> def initialize url=nil, version=Version.new(:HEAD)
<add> super
<add> end
<add>
<add> def verify_download_integrity fn
<add> return
<add> end
<add>end
<add>
<add>class Bottle < SoftwareSpec
<add> attr_writer :url
<add> attr_rw :root_url, :prefix, :cellar, :revision
<add>
<add> def initialize
<add> super
<add> @revision = 0
<add> @prefix = '/usr/local'
<add> @cellar = '/usr/local/Cellar'
<add> end
<add>
<add> # Checksum methods in the DSL's bottle block optionally take
<add> # a Hash, which indicates the platform the checksum applies on.
<add> Checksum::TYPES.each do |cksum|
<add> class_eval <<-EOS, __FILE__, __LINE__ + 1
<add> def #{cksum}(val=nil)
<add> return @#{cksum} if val.nil?
<add> @#{cksum} ||= Hash.new
<add> case val
<add> when Hash
<add> key, value = val.shift
<add> @#{cksum}[value] = Checksum.new(:#{cksum}, key)
<add> end
<add>
<add> if @#{cksum}.has_key? bottle_tag
<add> @checksum = @#{cksum}[bottle_tag]
<add> end
<add> end
<add> EOS
<add> end
<add>end
<ide><path>Library/Homebrew/test/test_software_spec.rb
<ide> require 'testing_env'
<del>require 'formula_support'
<add>require 'software_spec'
<ide> require 'bottles'
<ide>
<ide> class SoftwareSpecTests < Test::Unit::TestCase | 4 |
Javascript | Javascript | compute flat normals when detail is zero | cd71783f755a3c2f79e496a0a874a0c2cc522d0b | <ide><path>src/geometries/PolyhedronGeometry.js
<ide> function PolyhedronBufferGeometry( vertices, indices, radius, detail ) {
<ide> this.addAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
<ide> this.addAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
<ide> this.addAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
<del> this.normalizeNormals();
<add>
<add> if ( detail === 0 ) {
<add>
<add> BufferGeometry.prototype.computeVertexNormals.call( this ); // flat normals
<add>
<add> } else {
<add>
<add> this.normalizeNormals(); // smooth normals
<add>
<add> }
<ide>
<ide> // helper functions
<ide> | 1 |
Python | Python | prepare new pypi release | 9cf7f816f28a6ac7d7a4264ae015addd72e57321 | <ide><path>keras/__init__.py
<ide> from . import optimizers
<ide> from . import regularizers
<ide>
<del>__version__ = '2.0.0'
<add>__version__ = '2.0.1'
<ide><path>setup.py
<ide>
<ide>
<ide> setup(name='Keras',
<del> version='2.0.0',
<add> version='2.0.1',
<ide> description='Deep Learning for Python',
<ide> author='Francois Chollet',
<ide> author_email='francois.chollet@gmail.com',
<ide> url='https://github.com/fchollet/keras',
<del> download_url='https://github.com/fchollet/keras/tarball/2.0.0',
<add> download_url='https://github.com/fchollet/keras/tarball/2.0.1',
<ide> license='MIT',
<ide> install_requires=['theano', 'pyyaml', 'six'],
<ide> extras_require={ | 2 |
Ruby | Ruby | use rails.root in railties tests | 01e04a446c801af88a1bb0315efffc775a00eedf | <ide><path>railties/test/generators/actions_test.rb
<ide> def test_gem_with_lib_option_set_to_false_should_put_gem_dependency_in_enviromen
<ide>
<ide> def test_environment_should_include_data_in_environment_initializer_block
<ide> run_generator
<del> load_paths = 'config.load_paths += %w["#{RAILS_ROOT}/app/extras"]'
<add> load_paths = 'config.load_paths += %w["#{Rails.root}/app/extras"]'
<ide> action :environment, load_paths
<ide> assert_file 'config/application.rb', /#{Regexp.escape(load_paths)}/
<ide> end
<ide><path>railties/test/generators/app_generator_test.rb
<ide> def test_rails_is_frozen
<ide> end
<ide>
<ide> def test_template_from_dir_pwd
<del> FileUtils.cd(RAILS_ROOT)
<add> FileUtils.cd(Rails.root)
<ide> assert_match /It works from file!/, run_generator(["-m", "lib/template.rb"])
<ide> end
<ide>
<ide><path>railties/test/generators_test.rb
<ide> def test_find_by_namespace_lookup_with_gem_specification
<ide> Rails::Generators.instance_variable_set(:@load_paths, nil)
<ide>
<ide> spec = Gem::Specification.new
<del> spec.expects(:full_gem_path).returns(File.join(RAILS_ROOT, 'vendor', 'another_gem_path', 'xspec'))
<add> spec.expects(:full_gem_path).returns(File.join(Rails.root, 'vendor', 'another_gem_path', 'xspec'))
<ide> Gem.expects(:respond_to?).with(:loaded_specs).returns(true)
<ide> Gem.expects(:loaded_specs).returns(:spec => spec)
<ide>
<ide> def test_no_color_sets_proper_shell
<ide> end
<ide>
<ide> def test_rails_root_templates
<del> template = File.join(RAILS_ROOT, "lib", "templates", "active_record", "model", "model.rb")
<add> template = File.join(Rails.root, "lib", "templates", "active_record", "model", "model.rb")
<ide>
<ide> # Create template
<ide> mkdir_p(File.dirname(template))
<ide> def self.name
<ide>
<ide> def test_source_paths_for_not_namespaced_generators
<ide> mspec = Rails::Generators.find_by_namespace :mspec
<del> assert mspec.source_paths.include?(File.join(RAILS_ROOT, "lib", "templates", "mspec"))
<add> assert mspec.source_paths.include?(File.join(Rails.root, "lib", "templates", "mspec"))
<ide> end
<ide> end | 3 |
Text | Text | add mildsunrise to collaborators | c399e2664b9939a8b803f11062a2499293300793 | <ide><path>README.md
<ide> For information about the governance of the Node.js project, see
<ide> **Matteo Collina** <matteo.collina@gmail.com> (he/him)
<ide> * [mhdawson](https://github.com/mhdawson) -
<ide> **Michael Dawson** <michael_dawson@ca.ibm.com> (he/him)
<add>* [mildsunrise](https://github.com/mildsunrise)
<add>**Alba Mendez** <me@alba.sh> (she/her)
<ide> * [misterdjules](https://github.com/misterdjules) -
<ide> **Julien Gilli** <jgilli@nodejs.org>
<ide> * [mmarchini](https://github.com/mmarchini) - | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.